diff options
Diffstat (limited to 'core')
231 files changed, 27465 insertions, 30482 deletions
diff --git a/core/allocators.h b/core/allocators.h index 14deeb8739..de92d02226 100644 --- a/core/allocators.h +++ b/core/allocators.h @@ -30,13 +30,13 @@ #define ALLOCATORS_H #include "os/memory.h" -template<int PREALLOC_COUNT=64, int MAX_HANDS=8> +template <int PREALLOC_COUNT = 64, int MAX_HANDS = 8> 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_HANDS); - ERR_FAIL_COND_V( p_size>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; + Hand &h = hands[hand]; - Hand &h=hands[hand]; + if (h.used == h.allocated) { - if (h.used==h.allocated) { + for (int i = 0; i < PREALLOC_COUNT; i++) { - for(int i=0;i<PREALLOC_COUNT;i++) { - - Balloon *b = (Balloon*)memalloc(sizeof(Balloon)+(1<<hand)); - b->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;i<PREALLOC_COUNT;i++) { - ERR_CONTINUE( h.last->hand& 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;i<MAX_HANDS;i++) { + for (int i = 0; i < MAX_HANDS; i++) { - 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; } - } void clear() { - for(int i=0;i<MAX_HANDS;i++) { + for (int i = 0; i < MAX_HANDS; i++) { - while(hands[i].first) { + while (hands[i].first) { - Balloon *b=hands[i].first; - hands[i].first=b->next; + 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 16598a044d..80aca6f850 100644 --- a/core/array.cpp +++ b/core/array.cpp @@ -28,10 +28,10 @@ /*************************************************************************/ #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 { Vector<Variant> array; }; -void Array::_ref(const Array& p_from) const { +void Array::_ref(const Array &p_from) const { ArrayPrivate *_fp = p_from._p; @@ -55,8 +55,6 @@ void Array::_ref(const Array& p_from) const { _unref(); _p = p_from._p; - - } void Array::_unref() const { @@ -67,19 +65,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 { @@ -95,27 +91,26 @@ void Array::clear() { _p->array.clear(); } +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); } @@ -125,12 +120,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); } @@ -145,12 +140,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; @@ -164,9 +159,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; }; }; @@ -174,20 +169,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++; }; }; @@ -195,7 +190,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; } @@ -204,25 +199,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; } }; @@ -230,7 +224,6 @@ struct _ArrayVariantSort { void Array::sort() { _p->array.sort_custom<_ArrayVariantSort>(); - } struct _ArrayVariantSortCustom { @@ -238,40 +231,37 @@ 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<Variant,_ArrayVariantSortCustom> avs; - avs.compare.obj=p_obj; - avs.compare.func=p_function; - avs.sort(_p->array.ptr(),_p->array.size()); - + SortArray<Variant, _ArrayVariantSortCustom> 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); } -Variant Array::pop_back(){ +Variant Array::pop_back() { if (!_p->array.empty()) { int n = _p->array.size() - 1; @@ -280,10 +270,9 @@ Variant Array::pop_back(){ return ret; } return Variant(); - } -Variant Array::pop_front(){ +Variant Array::pop_front() { if (!_p->array.empty()) { Variant ret = _p->array.get(0); @@ -291,21 +280,17 @@ Variant Array::pop_front(){ return ret; } return Variant(); - } +Array::Array(const Array &p_from) { -Array::Array(const Array& p_from) { - - _p=NULL; + _p = NULL; _ref(p_from); - } Array::Array() { - _p = memnew( ArrayPrivate ); + _p = memnew(ArrayPrivate); _p->refcount.init(); - } Array::~Array() { diff --git a/core/array.h b/core/array.h index 16ab16002c..f9ba9f7706 100644 --- a/core/array.h +++ b/core/array.h @@ -38,56 +38,54 @@ 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; void clear(); - 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); Variant pop_back(); Variant pop_front(); - Array(const Array& p_from); + Array(const Array &p_from); Array(); ~Array(); - }; #endif // ARRAY_H diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp index 08e1a311fa..ce3d65b448 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 "core/global_config.h" #include "geometry.h" -#include "io/marshalls.h" #include "io/base64.h" -#include "core/global_config.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<ResourceInteractiveLoader> _ResourceLoader::load_interactive(const String& p_path,const String& p_type_hint) { - return ResourceLoader::load_interactive(p_path,p_type_hint); +Ref<ResourceInteractiveLoader> _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; } -PoolVector<String> _ResourceLoader::get_recognized_extensions_for_type(const String& p_type) { +PoolVector<String> _ResourceLoader::get_recognized_extensions_for_type(const String &p_type) { List<String> exts; - ResourceLoader::get_recognized_extensions_for_type(p_type,&exts); + ResourceLoader::get_recognized_extensions_for_type(p_type, &exts); PoolVector<String> ret; - for(List<String>::Element *E=exts.front();E;E=E->next()) { + for (List<String>::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); } -PoolStringArray _ResourceLoader::get_dependencies(const String& p_path) { +PoolStringArray _ResourceLoader::get_dependencies(const String &p_path) { List<String> deps; ResourceLoader::get_dependencies(p_path, &deps); PoolStringArray ret; - for(List<String>::Element *E=deps.front();E;E=E->next()) { + for (List<String>::Element *E = deps.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -106,50 +106,46 @@ bool _ResourceLoader::has(const String &p_path) { return ResourceCache::has(local_path); }; - void _ResourceLoader::_bind_methods() { - - ClassDB::bind_method(D_METHOD("load_interactive:ResourceInteractiveLoader","path","type_hint"),&_ResourceLoader::load_interactive,DEFVAL("")); - ClassDB::bind_method(D_METHOD("load:Resource","path","type_hint", "p_no_cache"),&_ResourceLoader::load,DEFVAL(""), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_recognized_extensions_for_type","type"),&_ResourceLoader::get_recognized_extensions_for_type); - ClassDB::bind_method(D_METHOD("set_abort_on_missing_resources","abort"),&_ResourceLoader::set_abort_on_missing_resources); - ClassDB::bind_method(D_METHOD("get_dependencies","path"),&_ResourceLoader::get_dependencies); - ClassDB::bind_method(D_METHOD("has","path"),&_ResourceLoader::has); + ClassDB::bind_method(D_METHOD("load_interactive:ResourceInteractiveLoader", "path", "type_hint"), &_ResourceLoader::load_interactive, DEFVAL("")); + ClassDB::bind_method(D_METHOD("load:Resource", "path", "type_hint", "p_no_cache"), &_ResourceLoader::load, DEFVAL(""), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_recognized_extensions_for_type", "type"), &_ResourceLoader::get_recognized_extensions_for_type); + ClassDB::bind_method(D_METHOD("set_abort_on_missing_resources", "abort"), &_ResourceLoader::set_abort_on_missing_resources); + ClassDB::bind_method(D_METHOD("get_dependencies", "path"), &_ResourceLoader::get_dependencies); + ClassDB::bind_method(D_METHOD("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); } -PoolVector<String> _ResourceSaver::get_recognized_extensions(const RES& p_resource) { +PoolVector<String> _ResourceSaver::get_recognized_extensions(const RES &p_resource) { - ERR_FAIL_COND_V(p_resource.is_null(),PoolVector<String>()); + ERR_FAIL_COND_V(p_resource.is_null(), PoolVector<String>()); List<String> exts; - ResourceSaver::get_recognized_extensions(p_resource,&exts); + ResourceSaver::get_recognized_extensions(p_resource, &exts); PoolVector<String> ret; - for(List<String>::Element *E=exts.front();E;E=E->next()) { + for (List<String>::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() { - ClassDB::bind_method(D_METHOD("save","path","resource:Resource","flags"),&_ResourceSaver::save,DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_recognized_extensions","type"),&_ResourceSaver::get_recognized_extensions); + ClassDB::bind_method(D_METHOD("save", "path", "resource:Resource", "flags"), &_ResourceSaver::save, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_recognized_extensions", "type"), &_ResourceSaver::get_recognized_extensions); BIND_CONSTANT(FLAG_RELATIVE_PATHS); BIND_CONSTANT(FLAG_BUNDLE_RESOURCES); @@ -161,21 +157,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 { @@ -191,44 +184,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(); } @@ -251,14 +237,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); } @@ -266,7 +252,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); } @@ -325,11 +311,11 @@ bool _OS::is_video_mode_resizable(int p_screen) const { Array _OS::get_fullscreen_mode_list(int p_screen) const { List<OS::VideoMode> 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<OS::VideoMode>::Element *E=vmlist.front();E;E=E->next() ){ + for (List<OS::VideoMode>::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; @@ -354,22 +340,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<String> & p_arguments, bool p_blocking, Array p_output) { +int _OS::execute(const String &p_path, const Vector<String> &p_arguments, bool p_blocking, Array p_output) { OS::ProcessID pid; List<String> args; - for(int i=0;i<p_arguments.size();i++) + for (int i = 0; i < p_arguments.size(); i++) args.push_back(p_arguments[i]); String pipe; - Error err = OS::get_singleton()->execute(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) { @@ -381,12 +365,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); } @@ -399,7 +382,7 @@ Vector<String> _OS::get_cmdline_args() { List<String> cmdline = OS::get_singleton()->get_cmdline_args(); Vector<String> cmdlinev; - for(List<String>::Element *E=cmdline.front();E;E=E->next()) { + for (List<String>::Element *E = cmdline.front(); E; E = E->next()) { cmdlinev.push_back(E->get()); } @@ -413,13 +396,13 @@ 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"; } } @@ -429,14 +412,12 @@ String _OS::get_model_name() const { return OS::get_singleton()->get_model_name(); } - - 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); }; @@ -509,22 +490,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); } @@ -551,7 +529,7 @@ Dictionary _OS::get_datetime(bool utc) const { List<Variant> 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]]; } @@ -562,11 +540,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; } @@ -574,9 +552,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; } @@ -603,12 +581,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<unsigned int>(datetime[SECOND_KEY]): 0); - unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]): 0); - unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]): 0); - unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]): 0); - unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) -1: 0); - unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(datetime[YEAR_KEY]):0); + unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast<unsigned int>(datetime[SECOND_KEY]) : 0); + unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]) : 0); + unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]) : 0); + unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]) : 0); + unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) - 1 : 0); + unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(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] = { @@ -619,41 +597,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; - } /** @@ -667,12 +644,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; @@ -705,18 +682,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<OS::Month>(imonth+1); + date.month = static_cast<OS::Month>(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; } @@ -745,7 +722,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 { @@ -768,7 +745,6 @@ bool _OS::can_draw() const { return OS::get_singleton()->can_draw(); } - int _OS::get_processor_count() const { return OS::get_singleton()->get_processor_count(); @@ -777,10 +753,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()); } @@ -792,19 +767,18 @@ struct _OSCoreBindImg { int fmt; ObjectID id; int vram; - bool operator<(const _OSCoreBindImg& p_img) const { return vram==p_img.vram ? id<p_img.id : vram > 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<Ref<Resource> > rsrc; ResourceCache::get_cached_resources(&rsrc); - for (List<Ref<Resource> >::Element *E=rsrc.front();E;E=E->next()) { + for (List<Ref<Resource> >::Element *E = rsrc.front(); E; E = E->next()) { if (!E->get()->is_class("ImageTexture")) continue; @@ -813,27 +787,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<String>& p_types) { +void _OS::print_resources_by_type(const Vector<String> &p_types) { - Map<String,int> type_count; + Map<String, int> type_count; List<Ref<Resource> > resources; ResourceCache::get_cached_resources(&resources); @@ -841,13 +815,13 @@ void _OS::print_resources_by_type(const Vector<String>& p_types) { List<Ref<Resource> > rsrc; ResourceCache::get_cached_resources(&rsrc); - for (List<Ref<Resource> >::Element *E=rsrc.front();E;E=E->next()) { + for (List<Ref<Resource> >::Element *E = rsrc.front(); E; E = E->next()) { Ref<Resource> r = E->get(); bool found = false; - for (int i=0; i<p_types.size(); i++) { + for (int i = 0; i < p_types.size(); i++) { if (r->is_class(p_types[i])) found = true; } @@ -855,20 +829,18 @@ void _OS::print_resources_by_type(const Vector<String>& p_types) { continue; if (!type_count.has(r->get_class())) { - type_count[r->get_class()]=0; + type_count[r->get_class()] = 0; } - type_count[r->get_class()]++; } - }; 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()); } @@ -876,7 +848,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); } @@ -886,7 +858,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()); } @@ -932,7 +904,6 @@ bool _OS::is_debug_build() const { #else return false; #endif - } void _OS::set_screen_orientation(ScreenOrientation p_orientation) { @@ -960,8 +931,6 @@ String _OS::get_system_dir(SystemDir p_dir) const { return OS::get_singleton()->get_system_dir(OS::SystemDir(p_dir)); } - - String _OS::get_scancode_string(uint32_t p_code) const { return keycode_get_string(p_code); @@ -970,25 +939,25 @@ 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); } -_OS *_OS::singleton=NULL; +_OS *_OS::singleton = NULL; void _OS::_bind_methods() { //ClassDB::bind_method(D_METHOD("get_mouse_pos"),&_OS::get_mouse_pos); //ClassDB::bind_method(D_METHOD("is_mouse_grab_enabled"),&_OS::is_mouse_grab_enabled); - ClassDB::bind_method(D_METHOD("set_clipboard","clipboard"),&_OS::set_clipboard); - ClassDB::bind_method(D_METHOD("get_clipboard"),&_OS::get_clipboard); + ClassDB::bind_method(D_METHOD("set_clipboard", "clipboard"), &_OS::set_clipboard); + ClassDB::bind_method(D_METHOD("get_clipboard"), &_OS::get_clipboard); //will not delete for now, just unexpose //ClassDB::bind_method(D_METHOD("set_video_mode","size","fullscreen","resizable","screen"),&_OS::set_video_mode,DEFVAL(0)); @@ -997,219 +966,212 @@ void _OS::_bind_methods() { //ClassDB::bind_method(D_METHOD("is_video_mode_resizable","screen"),&_OS::is_video_mode_resizable,DEFVAL(0)); //ClassDB::bind_method(D_METHOD("get_fullscreen_mode_list","screen"),&_OS::get_fullscreen_mode_list,DEFVAL(0)); - - ClassDB::bind_method(D_METHOD("get_screen_count"),&_OS::get_screen_count); - ClassDB::bind_method(D_METHOD("get_current_screen"),&_OS::get_current_screen); - ClassDB::bind_method(D_METHOD("set_current_screen","screen"),&_OS::set_current_screen); - ClassDB::bind_method(D_METHOD("get_screen_position","screen"),&_OS::get_screen_position,DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_screen_size","screen"),&_OS::get_screen_size,DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_screen_dpi","screen"),&_OS::get_screen_dpi,DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_window_position"),&_OS::get_window_position); - ClassDB::bind_method(D_METHOD("set_window_position","position"),&_OS::set_window_position); - ClassDB::bind_method(D_METHOD("get_window_size"),&_OS::get_window_size); - ClassDB::bind_method(D_METHOD("set_window_size","size"),&_OS::set_window_size); - ClassDB::bind_method(D_METHOD("set_window_fullscreen","enabled"),&_OS::set_window_fullscreen); - ClassDB::bind_method(D_METHOD("is_window_fullscreen"),&_OS::is_window_fullscreen); - ClassDB::bind_method(D_METHOD("set_window_resizable","enabled"),&_OS::set_window_resizable); - ClassDB::bind_method(D_METHOD("is_window_resizable"),&_OS::is_window_resizable); - ClassDB::bind_method(D_METHOD("set_window_minimized", "enabled"),&_OS::set_window_minimized); - ClassDB::bind_method(D_METHOD("is_window_minimized"),&_OS::is_window_minimized); - ClassDB::bind_method(D_METHOD("set_window_maximized", "enabled"),&_OS::set_window_maximized); - ClassDB::bind_method(D_METHOD("is_window_maximized"),&_OS::is_window_maximized); + ClassDB::bind_method(D_METHOD("get_screen_count"), &_OS::get_screen_count); + ClassDB::bind_method(D_METHOD("get_current_screen"), &_OS::get_current_screen); + ClassDB::bind_method(D_METHOD("set_current_screen", "screen"), &_OS::set_current_screen); + ClassDB::bind_method(D_METHOD("get_screen_position", "screen"), &_OS::get_screen_position, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_screen_size", "screen"), &_OS::get_screen_size, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_screen_dpi", "screen"), &_OS::get_screen_dpi, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_window_position"), &_OS::get_window_position); + ClassDB::bind_method(D_METHOD("set_window_position", "position"), &_OS::set_window_position); + ClassDB::bind_method(D_METHOD("get_window_size"), &_OS::get_window_size); + ClassDB::bind_method(D_METHOD("set_window_size", "size"), &_OS::set_window_size); + ClassDB::bind_method(D_METHOD("set_window_fullscreen", "enabled"), &_OS::set_window_fullscreen); + ClassDB::bind_method(D_METHOD("is_window_fullscreen"), &_OS::is_window_fullscreen); + ClassDB::bind_method(D_METHOD("set_window_resizable", "enabled"), &_OS::set_window_resizable); + ClassDB::bind_method(D_METHOD("is_window_resizable"), &_OS::is_window_resizable); + ClassDB::bind_method(D_METHOD("set_window_minimized", "enabled"), &_OS::set_window_minimized); + ClassDB::bind_method(D_METHOD("is_window_minimized"), &_OS::is_window_minimized); + ClassDB::bind_method(D_METHOD("set_window_maximized", "enabled"), &_OS::set_window_maximized); + ClassDB::bind_method(D_METHOD("is_window_maximized"), &_OS::is_window_maximized); ClassDB::bind_method(D_METHOD("request_attention"), &_OS::request_attention); ClassDB::bind_method(D_METHOD("set_borderless_window", "borderless"), &_OS::set_borderless_window); ClassDB::bind_method(D_METHOD("get_borderless_window"), &_OS::get_borderless_window); - ClassDB::bind_method(D_METHOD("set_screen_orientation","orientation"),&_OS::set_screen_orientation); - ClassDB::bind_method(D_METHOD("get_screen_orientation"),&_OS::get_screen_orientation); + ClassDB::bind_method(D_METHOD("set_screen_orientation", "orientation"), &_OS::set_screen_orientation); + ClassDB::bind_method(D_METHOD("get_screen_orientation"), &_OS::get_screen_orientation); - ClassDB::bind_method(D_METHOD("set_keep_screen_on","enabled"),&_OS::set_keep_screen_on); - ClassDB::bind_method(D_METHOD("is_keep_screen_on"),&_OS::is_keep_screen_on); + ClassDB::bind_method(D_METHOD("set_keep_screen_on", "enabled"), &_OS::set_keep_screen_on); + ClassDB::bind_method(D_METHOD("is_keep_screen_on"), &_OS::is_keep_screen_on); + ClassDB::bind_method(D_METHOD("has_touchscreen_ui_hint"), &_OS::has_touchscreen_ui_hint); - ClassDB::bind_method(D_METHOD("has_touchscreen_ui_hint"),&_OS::has_touchscreen_ui_hint); + ClassDB::bind_method(D_METHOD("set_window_title", "title"), &_OS::set_window_title); - ClassDB::bind_method(D_METHOD("set_window_title","title"),&_OS::set_window_title); + ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode", "enable"), &_OS::set_low_processor_usage_mode); + ClassDB::bind_method(D_METHOD("is_in_low_processor_usage_mode"), &_OS::is_in_low_processor_usage_mode); - ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode","enable"),&_OS::set_low_processor_usage_mode); - ClassDB::bind_method(D_METHOD("is_in_low_processor_usage_mode"),&_OS::is_in_low_processor_usage_mode); + ClassDB::bind_method(D_METHOD("get_processor_count"), &_OS::get_processor_count); - ClassDB::bind_method(D_METHOD("get_processor_count"),&_OS::get_processor_count); + ClassDB::bind_method(D_METHOD("get_executable_path"), &_OS::get_executable_path); + ClassDB::bind_method(D_METHOD("execute", "path", "arguments", "blocking", "output"), &_OS::execute, DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("kill", "pid"), &_OS::kill); + ClassDB::bind_method(D_METHOD("shell_open", "uri"), &_OS::shell_open); + ClassDB::bind_method(D_METHOD("get_process_ID"), &_OS::get_process_ID); - ClassDB::bind_method(D_METHOD("get_executable_path"),&_OS::get_executable_path); - ClassDB::bind_method(D_METHOD("execute","path","arguments","blocking","output"),&_OS::execute,DEFVAL(Array())); - ClassDB::bind_method(D_METHOD("kill","pid"),&_OS::kill); - ClassDB::bind_method(D_METHOD("shell_open","uri"),&_OS::shell_open); - ClassDB::bind_method(D_METHOD("get_process_ID"),&_OS::get_process_ID); + ClassDB::bind_method(D_METHOD("get_environment", "environment"), &_OS::get_environment); + ClassDB::bind_method(D_METHOD("has_environment", "environment"), &_OS::has_environment); - ClassDB::bind_method(D_METHOD("get_environment","environment"),&_OS::get_environment); - ClassDB::bind_method(D_METHOD("has_environment","environment"),&_OS::has_environment); + ClassDB::bind_method(D_METHOD("get_name"), &_OS::get_name); + ClassDB::bind_method(D_METHOD("get_cmdline_args"), &_OS::get_cmdline_args); - ClassDB::bind_method(D_METHOD("get_name"),&_OS::get_name); - ClassDB::bind_method(D_METHOD("get_cmdline_args"),&_OS::get_cmdline_args); - - ClassDB::bind_method(D_METHOD("get_datetime","utc"),&_OS::get_datetime,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_date","utc"),&_OS::get_date,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_time","utc"),&_OS::get_time,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_time_zone_info"),&_OS::get_time_zone_info); - ClassDB::bind_method(D_METHOD("get_unix_time"),&_OS::get_unix_time); + ClassDB::bind_method(D_METHOD("get_datetime", "utc"), &_OS::get_datetime, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_date", "utc"), &_OS::get_date, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_time", "utc"), &_OS::get_time, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_time_zone_info"), &_OS::get_time_zone_info); + ClassDB::bind_method(D_METHOD("get_unix_time"), &_OS::get_unix_time); ClassDB::bind_method(D_METHOD("get_datetime_from_unix_time", "unix_time_val"), &_OS::get_datetime_from_unix_time); ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime", "datetime"), &_OS::get_unix_time_from_datetime); ClassDB::bind_method(D_METHOD("get_system_time_secs"), &_OS::get_system_time_secs); - ClassDB::bind_method(D_METHOD("set_icon","icon"),&_OS::set_icon); - - ClassDB::bind_method(D_METHOD("get_exit_code"),&_OS::get_exit_code); - ClassDB::bind_method(D_METHOD("set_exit_code","code"),&_OS::set_exit_code); + ClassDB::bind_method(D_METHOD("set_icon", "icon"), &_OS::set_icon); - ClassDB::bind_method(D_METHOD("delay_usec","usec"),&_OS::delay_usec); - ClassDB::bind_method(D_METHOD("delay_msec","msec"),&_OS::delay_msec); - ClassDB::bind_method(D_METHOD("get_ticks_msec"),&_OS::get_ticks_msec); - ClassDB::bind_method(D_METHOD("get_splash_tick_msec"),&_OS::get_splash_tick_msec); - ClassDB::bind_method(D_METHOD("get_locale"),&_OS::get_locale); - ClassDB::bind_method(D_METHOD("get_latin_keyboard_variant"),&_OS::get_latin_keyboard_variant); - ClassDB::bind_method(D_METHOD("get_model_name"),&_OS::get_model_name); + ClassDB::bind_method(D_METHOD("get_exit_code"), &_OS::get_exit_code); + ClassDB::bind_method(D_METHOD("set_exit_code", "code"), &_OS::set_exit_code); + ClassDB::bind_method(D_METHOD("delay_usec", "usec"), &_OS::delay_usec); + ClassDB::bind_method(D_METHOD("delay_msec", "msec"), &_OS::delay_msec); + ClassDB::bind_method(D_METHOD("get_ticks_msec"), &_OS::get_ticks_msec); + ClassDB::bind_method(D_METHOD("get_splash_tick_msec"), &_OS::get_splash_tick_msec); + ClassDB::bind_method(D_METHOD("get_locale"), &_OS::get_locale); + ClassDB::bind_method(D_METHOD("get_latin_keyboard_variant"), &_OS::get_latin_keyboard_variant); + ClassDB::bind_method(D_METHOD("get_model_name"), &_OS::get_model_name); - ClassDB::bind_method(D_METHOD("can_draw"),&_OS::can_draw); - ClassDB::bind_method(D_METHOD("is_stdout_verbose"),&_OS::is_stdout_verbose); + ClassDB::bind_method(D_METHOD("can_draw"), &_OS::can_draw); + ClassDB::bind_method(D_METHOD("is_stdout_verbose"), &_OS::is_stdout_verbose); - ClassDB::bind_method(D_METHOD("can_use_threads"),&_OS::can_use_threads); + ClassDB::bind_method(D_METHOD("can_use_threads"), &_OS::can_use_threads); - ClassDB::bind_method(D_METHOD("is_debug_build"),&_OS::is_debug_build); + ClassDB::bind_method(D_METHOD("is_debug_build"), &_OS::is_debug_build); //ClassDB::bind_method(D_METHOD("get_mouse_button_state"),&_OS::get_mouse_button_state); - ClassDB::bind_method(D_METHOD("dump_memory_to_file","file"),&_OS::dump_memory_to_file); - ClassDB::bind_method(D_METHOD("dump_resources_to_file","file"),&_OS::dump_resources_to_file); - ClassDB::bind_method(D_METHOD("has_virtual_keyboard"),&_OS::has_virtual_keyboard); - ClassDB::bind_method(D_METHOD("show_virtual_keyboard", "existing_text"),&_OS::show_virtual_keyboard,DEFVAL("")); - ClassDB::bind_method(D_METHOD("hide_virtual_keyboard"),&_OS::hide_virtual_keyboard); - ClassDB::bind_method(D_METHOD("print_resources_in_use","short"),&_OS::print_resources_in_use,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("print_all_resources","tofile"),&_OS::print_all_resources,DEFVAL("")); - - ClassDB::bind_method(D_METHOD("get_static_memory_usage"),&_OS::get_static_memory_usage); - ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"),&_OS::get_static_memory_peak_usage); - ClassDB::bind_method(D_METHOD("get_dynamic_memory_usage"),&_OS::get_dynamic_memory_usage); - - ClassDB::bind_method(D_METHOD("get_data_dir"),&_OS::get_data_dir); - ClassDB::bind_method(D_METHOD("get_system_dir","dir"),&_OS::get_system_dir); - ClassDB::bind_method(D_METHOD("get_unique_ID"),&_OS::get_unique_ID); - - ClassDB::bind_method(D_METHOD("is_ok_left_and_cancel_right"),&_OS::is_ok_left_and_cancel_right); - - - ClassDB::bind_method(D_METHOD("print_all_textures_by_size"),&_OS::print_all_textures_by_size); - ClassDB::bind_method(D_METHOD("print_resources_by_type","types"),&_OS::print_resources_by_type); - - ClassDB::bind_method(D_METHOD("native_video_play","path","volume","audio_track","subtitle_track"),&_OS::native_video_play); - ClassDB::bind_method(D_METHOD("native_video_is_playing"),&_OS::native_video_is_playing); - ClassDB::bind_method(D_METHOD("native_video_stop"),&_OS::native_video_stop); - ClassDB::bind_method(D_METHOD("native_video_pause"),&_OS::native_video_pause); - ClassDB::bind_method(D_METHOD("native_video_unpause"),&_OS::native_video_unpause); - - ClassDB::bind_method(D_METHOD("get_scancode_string","code"),&_OS::get_scancode_string); - ClassDB::bind_method(D_METHOD("is_scancode_unicode","code"),&_OS::is_scancode_unicode); - ClassDB::bind_method(D_METHOD("find_scancode_from_string","string"),&_OS::find_scancode_from_string); - - ClassDB::bind_method(D_METHOD("set_use_file_access_save_and_swap","enabled"),&_OS::set_use_file_access_save_and_swap); - - ClassDB::bind_method(D_METHOD("alert","text","title"),&_OS::alert,DEFVAL("Alert!")); - - ClassDB::bind_method(D_METHOD("set_thread_name","name"),&_OS::set_thread_name); - - ClassDB::bind_method(D_METHOD("set_use_vsync","enable"),&_OS::set_use_vsync); - ClassDB::bind_method(D_METHOD("is_vsync_enabled"),&_OS::is_vsync_enabled); - - ClassDB::bind_method(D_METHOD("get_power_state"),&_OS::get_power_state); - ClassDB::bind_method(D_METHOD("get_power_seconds_left"),&_OS::get_power_seconds_left); - ClassDB::bind_method(D_METHOD("get_power_percent_left"),&_OS::get_power_percent_left); - - 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( 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( POWERSTATE_UNKNOWN ); - BIND_CONSTANT( POWERSTATE_ON_BATTERY ); - BIND_CONSTANT( POWERSTATE_NO_BATTERY ); - BIND_CONSTANT( POWERSTATE_CHARGING ); - BIND_CONSTANT( POWERSTATE_CHARGED ); - + ClassDB::bind_method(D_METHOD("dump_memory_to_file", "file"), &_OS::dump_memory_to_file); + ClassDB::bind_method(D_METHOD("dump_resources_to_file", "file"), &_OS::dump_resources_to_file); + ClassDB::bind_method(D_METHOD("has_virtual_keyboard"), &_OS::has_virtual_keyboard); + ClassDB::bind_method(D_METHOD("show_virtual_keyboard", "existing_text"), &_OS::show_virtual_keyboard, DEFVAL("")); + ClassDB::bind_method(D_METHOD("hide_virtual_keyboard"), &_OS::hide_virtual_keyboard); + ClassDB::bind_method(D_METHOD("print_resources_in_use", "short"), &_OS::print_resources_in_use, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("print_all_resources", "tofile"), &_OS::print_all_resources, DEFVAL("")); + + ClassDB::bind_method(D_METHOD("get_static_memory_usage"), &_OS::get_static_memory_usage); + ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"), &_OS::get_static_memory_peak_usage); + ClassDB::bind_method(D_METHOD("get_dynamic_memory_usage"), &_OS::get_dynamic_memory_usage); + + ClassDB::bind_method(D_METHOD("get_data_dir"), &_OS::get_data_dir); + ClassDB::bind_method(D_METHOD("get_system_dir", "dir"), &_OS::get_system_dir); + ClassDB::bind_method(D_METHOD("get_unique_ID"), &_OS::get_unique_ID); + + ClassDB::bind_method(D_METHOD("is_ok_left_and_cancel_right"), &_OS::is_ok_left_and_cancel_right); + + ClassDB::bind_method(D_METHOD("print_all_textures_by_size"), &_OS::print_all_textures_by_size); + ClassDB::bind_method(D_METHOD("print_resources_by_type", "types"), &_OS::print_resources_by_type); + + ClassDB::bind_method(D_METHOD("native_video_play", "path", "volume", "audio_track", "subtitle_track"), &_OS::native_video_play); + ClassDB::bind_method(D_METHOD("native_video_is_playing"), &_OS::native_video_is_playing); + ClassDB::bind_method(D_METHOD("native_video_stop"), &_OS::native_video_stop); + ClassDB::bind_method(D_METHOD("native_video_pause"), &_OS::native_video_pause); + ClassDB::bind_method(D_METHOD("native_video_unpause"), &_OS::native_video_unpause); + + ClassDB::bind_method(D_METHOD("get_scancode_string", "code"), &_OS::get_scancode_string); + ClassDB::bind_method(D_METHOD("is_scancode_unicode", "code"), &_OS::is_scancode_unicode); + ClassDB::bind_method(D_METHOD("find_scancode_from_string", "string"), &_OS::find_scancode_from_string); + + ClassDB::bind_method(D_METHOD("set_use_file_access_save_and_swap", "enabled"), &_OS::set_use_file_access_save_and_swap); + + ClassDB::bind_method(D_METHOD("alert", "text", "title"), &_OS::alert, DEFVAL("Alert!")); + + ClassDB::bind_method(D_METHOD("set_thread_name", "name"), &_OS::set_thread_name); + + ClassDB::bind_method(D_METHOD("set_use_vsync", "enable"), &_OS::set_use_vsync); + ClassDB::bind_method(D_METHOD("is_vsync_enabled"), &_OS::is_vsync_enabled); + + ClassDB::bind_method(D_METHOD("get_power_state"), &_OS::get_power_state); + ClassDB::bind_method(D_METHOD("get_power_seconds_left"), &_OS::get_power_seconds_left); + ClassDB::bind_method(D_METHOD("get_power_percent_left"), &_OS::get_power_percent_left); + + 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(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(POWERSTATE_UNKNOWN); + BIND_CONSTANT(POWERSTATE_ON_BATTERY); + BIND_CONSTANT(POWERSTATE_NO_BATTERY); + BIND_CONSTANT(POWERSTATE_CHARGING); + BIND_CONSTANT(POWERSTATE_CHARGED); } _OS::_OS() { - singleton=this; + singleton = this; } - ///////////////////// GEOMETRY - -_Geometry *_Geometry::singleton=NULL; +_Geometry *_Geometry::singleton = NULL; _Geometry *_Geometry::get_singleton() { return singleton; } -PoolVector<Plane> _Geometry::build_box_planes(const Vector3& p_extents) { +PoolVector<Plane> _Geometry::build_box_planes(const Vector3 &p_extents) { return Geometry::build_box_planes(p_extents); } PoolVector<Plane> _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); } PoolVector<Plane> _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)) { @@ -1220,122 +1182,117 @@ Variant _Geometry::segment_intersects_segment_2d(const Vector2& p_from_a,const V }; }; -PoolVector<Vector2> _Geometry::get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2) { +PoolVector<Vector2> _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); PoolVector<Vector2> r; r.resize(2); - r.set(0,r1); - r.set(1,r2); + r.set(0, r1); + r.set(1, r2); return r; } -PoolVector<Vector3> _Geometry::get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2) { +PoolVector<Vector3> _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); PoolVector<Vector3> 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); } -PoolVector<Vector3> _Geometry::segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius) { +PoolVector<Vector3> _Geometry::segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius) { PoolVector<Vector3> 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; } -PoolVector<Vector3> _Geometry::segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius) { +PoolVector<Vector3> _Geometry::segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius) { PoolVector<Vector3> 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; - } -PoolVector<Vector3> _Geometry::segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector<Plane>& p_planes) { +PoolVector<Vector3> _Geometry::segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector<Plane> &p_planes) { PoolVector<Vector3> 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<int> _Geometry::triangulate_polygon(const Vector<Vector2>& p_polygon) { +Vector<int> _Geometry::triangulate_polygon(const Vector<Vector2> &p_polygon) { return Geometry::triangulate_polygon(p_polygon); } -Dictionary _Geometry::make_atlas(const Vector<Size2>& p_rects) { +Dictionary _Geometry::make_atlas(const Vector<Size2> &p_rects) { Dictionary ret; Vector<Size2i> rects; - for (int i=0; i<p_rects.size(); i++) { + for (int i = 0; i < p_rects.size(); i++) { rects.push_back(p_rects[i]); }; @@ -1347,215 +1304,193 @@ Dictionary _Geometry::make_atlas(const Vector<Size2>& p_rects) { Size2 r_size = size; Vector<Point2> r_result; - for (int i=0; i<result.size(); i++) { + for (int i = 0; i < result.size(); i++) { r_result.push_back(result[i]); }; - ret["points"] = r_result; ret["size"] = r_size; return ret; }; - -int _Geometry::get_uv84_normal_bit(const Vector3& p_vector) { +int _Geometry::get_uv84_normal_bit(const Vector3 &p_vector) { return Geometry::get_uv84_normal_bit(p_vector); } - void _Geometry::_bind_methods() { + ClassDB::bind_method(D_METHOD("build_box_planes", "extents"), &_Geometry::build_box_planes); + ClassDB::bind_method(D_METHOD("build_cylinder_planes", "radius", "height", "sides", "axis"), &_Geometry::build_cylinder_planes, DEFVAL(Vector3::AXIS_Z)); + ClassDB::bind_method(D_METHOD("build_capsule_planes", "radius", "height", "sides", "lats", "axis"), &_Geometry::build_capsule_planes, DEFVAL(Vector3::AXIS_Z)); + ClassDB::bind_method(D_METHOD("segment_intersects_circle", "segment_from", "segment_to", "circle_pos", "circle_radius"), &_Geometry::segment_intersects_circle); + ClassDB::bind_method(D_METHOD("segment_intersects_segment_2d", "from_a", "to_a", "from_b", "to_b"), &_Geometry::segment_intersects_segment_2d); - ClassDB::bind_method(D_METHOD("build_box_planes","extents"),&_Geometry::build_box_planes); - ClassDB::bind_method(D_METHOD("build_cylinder_planes","radius","height","sides","axis"),&_Geometry::build_cylinder_planes,DEFVAL(Vector3::AXIS_Z)); - ClassDB::bind_method(D_METHOD("build_capsule_planes","radius","height","sides","lats","axis"),&_Geometry::build_capsule_planes,DEFVAL(Vector3::AXIS_Z)); - ClassDB::bind_method(D_METHOD("segment_intersects_circle","segment_from","segment_to","circle_pos","circle_radius"),&_Geometry::segment_intersects_circle); - ClassDB::bind_method(D_METHOD("segment_intersects_segment_2d","from_a","to_a","from_b","to_b"),&_Geometry::segment_intersects_segment_2d); - - ClassDB::bind_method(D_METHOD("get_closest_points_between_segments_2d","p1","q1","p2","q2"),&_Geometry::get_closest_points_between_segments_2d); - ClassDB::bind_method(D_METHOD("get_closest_points_between_segments","p1","p2","q1","q2"),&_Geometry::get_closest_points_between_segments); + ClassDB::bind_method(D_METHOD("get_closest_points_between_segments_2d", "p1", "q1", "p2", "q2"), &_Geometry::get_closest_points_between_segments_2d); + ClassDB::bind_method(D_METHOD("get_closest_points_between_segments", "p1", "p2", "q1", "q2"), &_Geometry::get_closest_points_between_segments); - ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_2d","point","s1","s2"),&_Geometry::get_closest_point_to_segment_2d); - ClassDB::bind_method(D_METHOD("get_closest_point_to_segment","point","s1","s2"),&_Geometry::get_closest_point_to_segment); + ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_2d", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_2d); + ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment); - ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped_2d","point","s1","s2"),&_Geometry::get_closest_point_to_segment_uncapped_2d); - ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped","point","s1","s2"),&_Geometry::get_closest_point_to_segment_uncapped); + ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped_2d", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_uncapped_2d); + ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_uncapped); - ClassDB::bind_method(D_METHOD("get_uv84_normal_bit","normal"),&_Geometry::get_uv84_normal_bit); + ClassDB::bind_method(D_METHOD("get_uv84_normal_bit", "normal"), &_Geometry::get_uv84_normal_bit); - ClassDB::bind_method(D_METHOD("ray_intersects_triangle","from","dir","a","b","c"),&_Geometry::ray_intersects_triangle); - ClassDB::bind_method(D_METHOD("segment_intersects_triangle","from","to","a","b","c"),&_Geometry::segment_intersects_triangle); - ClassDB::bind_method(D_METHOD("segment_intersects_sphere","from","to","spos","sradius"),&_Geometry::segment_intersects_sphere); - ClassDB::bind_method(D_METHOD("segment_intersects_cylinder","from","to","height","radius"),&_Geometry::segment_intersects_cylinder); - ClassDB::bind_method(D_METHOD("segment_intersects_convex","from","to","planes"),&_Geometry::segment_intersects_convex); - ClassDB::bind_method(D_METHOD("point_is_inside_triangle","point","a","b","c"),&_Geometry::point_is_inside_triangle); + ClassDB::bind_method(D_METHOD("ray_intersects_triangle", "from", "dir", "a", "b", "c"), &_Geometry::ray_intersects_triangle); + ClassDB::bind_method(D_METHOD("segment_intersects_triangle", "from", "to", "a", "b", "c"), &_Geometry::segment_intersects_triangle); + ClassDB::bind_method(D_METHOD("segment_intersects_sphere", "from", "to", "spos", "sradius"), &_Geometry::segment_intersects_sphere); + ClassDB::bind_method(D_METHOD("segment_intersects_cylinder", "from", "to", "height", "radius"), &_Geometry::segment_intersects_cylinder); + ClassDB::bind_method(D_METHOD("segment_intersects_convex", "from", "to", "planes"), &_Geometry::segment_intersects_convex); + ClassDB::bind_method(D_METHOD("point_is_inside_triangle", "point", "a", "b", "c"), &_Geometry::point_is_inside_triangle); - ClassDB::bind_method(D_METHOD("triangulate_polygon","polygon"),&_Geometry::triangulate_polygon); + ClassDB::bind_method(D_METHOD("triangulate_polygon", "polygon"), &_Geometry::triangulate_polygon); - ClassDB::bind_method(D_METHOD("make_atlas","sizes"),&_Geometry::make_atlas); + ClassDB::bind_method(D_METHOD("make_atlas", "sizes"), &_Geometry::make_atlas); } - _Geometry::_Geometry() { - singleton=this; + singleton = this; } - ///////////////////////// FILE +Error _File::open_encrypted(const String &p_path, int p_mode_flags, const Vector<uint8_t> &p_key) { - -Error _File::open_encrypted(const String& p_path, int p_mode_flags,const Vector<uint8_t>& 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(); } -PoolVector<uint8_t> _File::get_buffer(int p_length) const{ +PoolVector<uint8_t> _File::get_buffer(int p_length) const { PoolVector<uint8_t> 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); PoolVector<uint8_t>::Write w = data.write(); - int len = f->get_buffer(&w[0],p_length); - ERR_FAIL_COND_V( len < 0 , PoolVector<uint8_t>()); + int len = f->get_buffer(&w[0], p_length); + ERR_FAIL_COND_V(len < 0, PoolVector<uint8_t>()); w = PoolVector<uint8_t>::Write(); @@ -1563,10 +1498,8 @@ PoolVector<uint8_t> _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()); @@ -1576,42 +1509,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<String> _File::get_csv_line(String delim) const { - ERR_FAIL_COND_V(!f,Vector<String>()); + ERR_FAIL_COND_V(!f, Vector<String>()); return f->get_csv_line(delim); } @@ -1620,79 +1546,76 @@ Vector<String> _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); @@ -1706,46 +1629,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 PoolVector<uint8_t>& p_buffer){ +void _File::store_buffer(const PoolVector<uint8_t> &p_buffer) { ERR_FAIL_COND(!f); int len = p_buffer.size(); - if (len==0) + if (len == 0) return; PoolVector<uint8_t>::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); PoolVector<uint8_t> buff; buff.resize(len); PoolVector<uint8_t>::Write w = buff.write(); - err = encode_variant(p_var,&w[0],len); - ERR_FAIL_COND( err != OK ); - w=PoolVector<uint8_t>::Write(); + err = encode_variant(p_var, &w[0], len); + ERR_FAIL_COND(err != OK); + w = PoolVector<uint8_t>::Write(); store_32(len); store_buffer(buff); @@ -1753,7 +1674,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(); PoolVector<uint8_t> buff = get_buffer(len); ERR_FAIL_COND_V(buff.size() != len, Variant()); @@ -1761,8 +1682,8 @@ Variant _File::get_var() const { PoolVector<uint8_t>::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; } @@ -1774,95 +1695,89 @@ uint64_t _File::get_modified_time(const String &p_file) const { void _File::_bind_methods() { - - ClassDB::bind_method(D_METHOD("open_encrypted","path","mode_flags","key"),&_File::open_encrypted); - ClassDB::bind_method(D_METHOD("open_encrypted_with_pass","path","mode_flags","pass"),&_File::open_encrypted_pass); - - ClassDB::bind_method(D_METHOD("open","path","flags"),&_File::open); - ClassDB::bind_method(D_METHOD("close"),&_File::close); - ClassDB::bind_method(D_METHOD("is_open"),&_File::is_open); - ClassDB::bind_method(D_METHOD("seek","pos"),&_File::seek); - ClassDB::bind_method(D_METHOD("seek_end","pos"),&_File::seek_end,DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_pos"),&_File::get_pos); - ClassDB::bind_method(D_METHOD("get_len"),&_File::get_len); - ClassDB::bind_method(D_METHOD("eof_reached"),&_File::eof_reached); - ClassDB::bind_method(D_METHOD("get_8"),&_File::get_8); - ClassDB::bind_method(D_METHOD("get_16"),&_File::get_16); - ClassDB::bind_method(D_METHOD("get_32"),&_File::get_32); - ClassDB::bind_method(D_METHOD("get_64"),&_File::get_64); - ClassDB::bind_method(D_METHOD("get_float"),&_File::get_float); - ClassDB::bind_method(D_METHOD("get_double"),&_File::get_double); - ClassDB::bind_method(D_METHOD("get_real"),&_File::get_real); - ClassDB::bind_method(D_METHOD("get_buffer","len"),&_File::get_buffer); - ClassDB::bind_method(D_METHOD("get_line"),&_File::get_line); - ClassDB::bind_method(D_METHOD("get_as_text"),&_File::get_as_text); - ClassDB::bind_method(D_METHOD("get_md5","path"),&_File::get_md5); - ClassDB::bind_method(D_METHOD("get_sha256","path"),&_File::get_sha256); - ClassDB::bind_method(D_METHOD("get_endian_swap"),&_File::get_endian_swap); - ClassDB::bind_method(D_METHOD("set_endian_swap","enable"),&_File::set_endian_swap); - ClassDB::bind_method(D_METHOD("get_error:Error"),&_File::get_error); - ClassDB::bind_method(D_METHOD("get_var"),&_File::get_var); - ClassDB::bind_method(D_METHOD("get_csv_line","delim"),&_File::get_csv_line,DEFVAL(",")); - - ClassDB::bind_method(D_METHOD("store_8","value"),&_File::store_8); - ClassDB::bind_method(D_METHOD("store_16","value"),&_File::store_16); - ClassDB::bind_method(D_METHOD("store_32","value"),&_File::store_32); - ClassDB::bind_method(D_METHOD("store_64","value"),&_File::store_64); - ClassDB::bind_method(D_METHOD("store_float","value"),&_File::store_float); - ClassDB::bind_method(D_METHOD("store_double","value"),&_File::store_double); - ClassDB::bind_method(D_METHOD("store_real","value"),&_File::store_real); - ClassDB::bind_method(D_METHOD("store_buffer","buffer"),&_File::store_buffer); - ClassDB::bind_method(D_METHOD("store_line","line"),&_File::store_line); - ClassDB::bind_method(D_METHOD("store_string","string"),&_File::store_string); - ClassDB::bind_method(D_METHOD("store_var","value"),&_File::store_var); - - ClassDB::bind_method(D_METHOD("store_pascal_string","string"),&_File::store_pascal_string); - ClassDB::bind_method(D_METHOD("get_pascal_string"),&_File::get_pascal_string); - - ClassDB::bind_method(D_METHOD("file_exists","path"),&_File::file_exists); - ClassDB::bind_method(D_METHOD("get_modified_time", "file"),&_File::get_modified_time); - - BIND_CONSTANT( READ ); - BIND_CONSTANT( WRITE ); - BIND_CONSTANT( READ_WRITE ); - BIND_CONSTANT( WRITE_READ ); -} - -_File::_File(){ + ClassDB::bind_method(D_METHOD("open_encrypted", "path", "mode_flags", "key"), &_File::open_encrypted); + ClassDB::bind_method(D_METHOD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &_File::open_encrypted_pass); + + ClassDB::bind_method(D_METHOD("open", "path", "flags"), &_File::open); + ClassDB::bind_method(D_METHOD("close"), &_File::close); + ClassDB::bind_method(D_METHOD("is_open"), &_File::is_open); + ClassDB::bind_method(D_METHOD("seek", "pos"), &_File::seek); + ClassDB::bind_method(D_METHOD("seek_end", "pos"), &_File::seek_end, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_pos"), &_File::get_pos); + ClassDB::bind_method(D_METHOD("get_len"), &_File::get_len); + ClassDB::bind_method(D_METHOD("eof_reached"), &_File::eof_reached); + ClassDB::bind_method(D_METHOD("get_8"), &_File::get_8); + ClassDB::bind_method(D_METHOD("get_16"), &_File::get_16); + ClassDB::bind_method(D_METHOD("get_32"), &_File::get_32); + ClassDB::bind_method(D_METHOD("get_64"), &_File::get_64); + ClassDB::bind_method(D_METHOD("get_float"), &_File::get_float); + ClassDB::bind_method(D_METHOD("get_double"), &_File::get_double); + ClassDB::bind_method(D_METHOD("get_real"), &_File::get_real); + ClassDB::bind_method(D_METHOD("get_buffer", "len"), &_File::get_buffer); + ClassDB::bind_method(D_METHOD("get_line"), &_File::get_line); + ClassDB::bind_method(D_METHOD("get_as_text"), &_File::get_as_text); + ClassDB::bind_method(D_METHOD("get_md5", "path"), &_File::get_md5); + ClassDB::bind_method(D_METHOD("get_sha256", "path"), &_File::get_sha256); + ClassDB::bind_method(D_METHOD("get_endian_swap"), &_File::get_endian_swap); + ClassDB::bind_method(D_METHOD("set_endian_swap", "enable"), &_File::set_endian_swap); + ClassDB::bind_method(D_METHOD("get_error:Error"), &_File::get_error); + ClassDB::bind_method(D_METHOD("get_var"), &_File::get_var); + ClassDB::bind_method(D_METHOD("get_csv_line", "delim"), &_File::get_csv_line, DEFVAL(",")); + + ClassDB::bind_method(D_METHOD("store_8", "value"), &_File::store_8); + ClassDB::bind_method(D_METHOD("store_16", "value"), &_File::store_16); + ClassDB::bind_method(D_METHOD("store_32", "value"), &_File::store_32); + ClassDB::bind_method(D_METHOD("store_64", "value"), &_File::store_64); + ClassDB::bind_method(D_METHOD("store_float", "value"), &_File::store_float); + ClassDB::bind_method(D_METHOD("store_double", "value"), &_File::store_double); + ClassDB::bind_method(D_METHOD("store_real", "value"), &_File::store_real); + ClassDB::bind_method(D_METHOD("store_buffer", "buffer"), &_File::store_buffer); + ClassDB::bind_method(D_METHOD("store_line", "line"), &_File::store_line); + ClassDB::bind_method(D_METHOD("store_string", "string"), &_File::store_string); + ClassDB::bind_method(D_METHOD("store_var", "value"), &_File::store_var); + + ClassDB::bind_method(D_METHOD("store_pascal_string", "string"), &_File::store_pascal_string); + ClassDB::bind_method(D_METHOD("get_pascal_string"), &_File::get_pascal_string); + + ClassDB::bind_method(D_METHOD("file_exists", "path"), &_File::file_exists); + ClassDB::bind_method(D_METHOD("get_modified_time", "file"), &_File::get_modified_time); + + BIND_CONSTANT(READ); + BIND_CONSTANT(WRITE); + BIND_CONSTANT(READ_WRITE); + BIND_CONSTANT(WRITE_READ); +} + +_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; } Error _Directory::list_dir_begin(bool p_skip_navigational, bool p_skip_hidden) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); _list_skip_navigational = p_skip_navigational; _list_skip_hidden = p_skip_hidden; @@ -1870,84 +1785,80 @@ Error _Directory::list_dir_begin(bool p_skip_navigational, bool p_skip_hidden) { return d->list_dir_begin(); } -String _Directory::get_next(){ +String _Directory::get_next() { - ERR_FAIL_COND_V(!d,""); + ERR_FAIL_COND_V(!d, ""); String next = d->get_next(); - while (next != "" - && ((_list_skip_navigational && (next == "." || next == "..")) - || (_list_skip_hidden && d->current_is_hidden()))) { + while (next != "" && ((_list_skip_navigational && (next == "." || next == "..")) || (_list_skip_hidden && d->current_is_hidden()))) { next = d->get_next(); } return 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); } int _Directory::get_current_drive() { - ERR_FAIL_COND_V(!d,0); + ERR_FAIL_COND_V(!d, 0); return d->get_current_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); @@ -1957,7 +1868,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); @@ -1970,33 +1881,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); @@ -2009,27 +1919,25 @@ Error _Directory::remove(String p_name){ void _Directory::_bind_methods() { - - ClassDB::bind_method(D_METHOD("open:Error","path"),&_Directory::open); + ClassDB::bind_method(D_METHOD("open:Error", "path"), &_Directory::open); ClassDB::bind_method(D_METHOD("list_dir_begin", "skip_navigational", "skip_hidden"), &_Directory::list_dir_begin, DEFVAL(false), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_next"),&_Directory::get_next); - ClassDB::bind_method(D_METHOD("current_is_dir"),&_Directory::current_is_dir); - ClassDB::bind_method(D_METHOD("list_dir_end"),&_Directory::list_dir_end); - ClassDB::bind_method(D_METHOD("get_drive_count"),&_Directory::get_drive_count); - ClassDB::bind_method(D_METHOD("get_drive","idx"),&_Directory::get_drive); - ClassDB::bind_method(D_METHOD("get_current_drive"),&_Directory::get_current_drive); - ClassDB::bind_method(D_METHOD("change_dir:Error","todir"),&_Directory::change_dir); - ClassDB::bind_method(D_METHOD("get_current_dir"),&_Directory::get_current_dir); - ClassDB::bind_method(D_METHOD("make_dir:Error","path"),&_Directory::make_dir); - ClassDB::bind_method(D_METHOD("make_dir_recursive:Error","path"),&_Directory::make_dir_recursive); - ClassDB::bind_method(D_METHOD("file_exists","path"),&_Directory::file_exists); - ClassDB::bind_method(D_METHOD("dir_exists","path"),&_Directory::dir_exists); + ClassDB::bind_method(D_METHOD("get_next"), &_Directory::get_next); + ClassDB::bind_method(D_METHOD("current_is_dir"), &_Directory::current_is_dir); + ClassDB::bind_method(D_METHOD("list_dir_end"), &_Directory::list_dir_end); + ClassDB::bind_method(D_METHOD("get_drive_count"), &_Directory::get_drive_count); + ClassDB::bind_method(D_METHOD("get_drive", "idx"), &_Directory::get_drive); + ClassDB::bind_method(D_METHOD("get_current_drive"), &_Directory::get_current_drive); + ClassDB::bind_method(D_METHOD("change_dir:Error", "todir"), &_Directory::change_dir); + ClassDB::bind_method(D_METHOD("get_current_dir"), &_Directory::get_current_dir); + ClassDB::bind_method(D_METHOD("make_dir:Error", "path"), &_Directory::make_dir); + ClassDB::bind_method(D_METHOD("make_dir_recursive:Error", "path"), &_Directory::make_dir_recursive); + ClassDB::bind_method(D_METHOD("file_exists", "path"), &_Directory::file_exists); + ClassDB::bind_method(D_METHOD("dir_exists", "path"), &_Directory::dir_exists); //ClassDB::bind_method(D_METHOD("get_modified_time","file"),&_Directory::get_modified_time); - ClassDB::bind_method(D_METHOD("get_space_left"),&_Directory::get_space_left); - ClassDB::bind_method(D_METHOD("copy:Error","from","to"),&_Directory::copy); - ClassDB::bind_method(D_METHOD("rename:Error","from","to"),&_Directory::rename); - ClassDB::bind_method(D_METHOD("remove:Error","path"),&_Directory::remove); - + ClassDB::bind_method(D_METHOD("get_space_left"), &_Directory::get_space_left); + ClassDB::bind_method(D_METHOD("copy:Error", "from", "to"), &_Directory::copy); + ClassDB::bind_method(D_METHOD("rename:Error", "from", "to"), &_Directory::rename); + ClassDB::bind_method(D_METHOD("remove:Error", "path"), &_Directory::remove); } _Directory::_Directory() { @@ -2043,40 +1951,39 @@ _Directory::~_Directory() { memdelete(d); } -_Marshalls* _Marshalls::singleton=NULL; +_Marshalls *_Marshalls::singleton = NULL; -_Marshalls *_Marshalls::get_singleton() -{ +_Marshalls *_Marshalls::get_singleton() { return singleton; } -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, ""); PoolVector<uint8_t> buff; buff.resize(len); PoolVector<uint8_t>::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; PoolVector<uint8_t> b64buff; b64buff.resize(b64len); PoolVector<uint8_t>::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(); @@ -2085,11 +1992,11 @@ Variant _Marshalls::base64_to_variant(const String& p_str) { buf.resize(strlen / 4 * 3 + 1); PoolVector<uint8_t>::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; }; @@ -2104,9 +2011,9 @@ String _Marshalls::raw_to_base64(const PoolVector<uint8_t> &p_arr) { b64buff.resize(b64len); PoolVector<uint8_t>::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; }; @@ -2122,7 +2029,7 @@ PoolVector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) { buf.resize(strlen / 4 * 3 + 1); PoolVector<uint8_t>::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); @@ -2130,7 +2037,7 @@ PoolVector<uint8_t> _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(); @@ -2140,15 +2047,15 @@ String _Marshalls::utf8_to_base64(const String& p_str) { b64buff.resize(b64len); PoolVector<uint8_t>::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(); @@ -2157,35 +2064,28 @@ String _Marshalls::base64_to_utf8(const String& p_str) { buf.resize(strlen / 4 * 3 + 1 + 1); PoolVector<uint8_t>::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() { - ClassDB::bind_method(D_METHOD("variant_to_base64:String","variant"),&_Marshalls::variant_to_base64); - ClassDB::bind_method(D_METHOD("base64_to_variant:Variant","base64_str"),&_Marshalls::base64_to_variant); - - ClassDB::bind_method(D_METHOD("raw_to_base64:String","array"),&_Marshalls::raw_to_base64); - ClassDB::bind_method(D_METHOD("base64_to_raw:RawArray","base64_str"),&_Marshalls::base64_to_raw); + ClassDB::bind_method(D_METHOD("variant_to_base64:String", "variant"), &_Marshalls::variant_to_base64); + ClassDB::bind_method(D_METHOD("base64_to_variant:Variant", "base64_str"), &_Marshalls::base64_to_variant); - ClassDB::bind_method(D_METHOD("utf8_to_base64:String","utf8_str"),&_Marshalls::utf8_to_base64); - ClassDB::bind_method(D_METHOD("base64_to_utf8:String","base64_str"),&_Marshalls::base64_to_utf8); + ClassDB::bind_method(D_METHOD("raw_to_base64:String", "array"), &_Marshalls::raw_to_base64); + ClassDB::bind_method(D_METHOD("base64_to_raw:RawArray", "base64_str"), &_Marshalls::base64_to_raw); + ClassDB::bind_method(D_METHOD("utf8_to_base64:String", "utf8_str"), &_Marshalls::utf8_to_base64); + ClassDB::bind_method(D_METHOD("base64_to_utf8:String", "base64_str"), &_Marshalls::base64_to_utf8); }; - - //////////////// - - - Error _Semaphore::wait() { return semaphore->wait(); @@ -2196,133 +2096,120 @@ Error _Semaphore::post() { return semaphore->post(); } - void _Semaphore::_bind_methods() { - ClassDB::bind_method(D_METHOD("wait:Error"),&_Semaphore::wait); - ClassDB::bind_method(D_METHOD("post:Error"),&_Semaphore::post); - + ClassDB::bind_method(D_METHOD("wait:Error"), &_Semaphore::wait); + ClassDB::bind_method(D_METHOD("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() { - ClassDB::bind_method(D_METHOD("lock"),&_Mutex::lock); - ClassDB::bind_method(D_METHOD("try_lock:Error"),&_Mutex::try_lock); - ClassDB::bind_method(D_METHOD("unlock"),&_Mutex::unlock); - + ClassDB::bind_method(D_METHOD("lock"), &_Mutex::lock); + ClassDB::bind_method(D_METHOD("try_lock:Error"), &_Mutex::try_lock); + ClassDB::bind_method(D_METHOD("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; } @@ -2343,36 +2230,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() { - ClassDB::bind_method(D_METHOD("start:Error","instance","method","userdata","priority"),&_Thread::start,DEFVAL(Variant()),DEFVAL(PRIORITY_NORMAL)); - ClassDB::bind_method(D_METHOD("get_id"),&_Thread::get_id); - ClassDB::bind_method(D_METHOD("is_active"),&_Thread::is_active); - ClassDB::bind_method(D_METHOD("wait_to_finish:Variant"),&_Thread::wait_to_finish); - - BIND_CONSTANT( PRIORITY_LOW ); - BIND_CONSTANT( PRIORITY_NORMAL ); - BIND_CONSTANT( PRIORITY_HIGH ); + ClassDB::bind_method(D_METHOD("start:Error", "instance", "method", "userdata", "priority"), &_Thread::start, DEFVAL(Variant()), DEFVAL(PRIORITY_NORMAL)); + ClassDB::bind_method(D_METHOD("get_id"), &_Thread::get_id); + ClassDB::bind_method(D_METHOD("is_active"), &_Thread::is_active); + ClassDB::bind_method(D_METHOD("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() { @@ -2380,11 +2266,10 @@ _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); } ///////////////////////////////////// - PoolStringArray _ClassDB::get_class_list() const { List<StringName> classes; @@ -2392,29 +2277,28 @@ PoolStringArray _ClassDB::get_class_list() const { PoolStringArray ret; ret.resize(classes.size()); - int idx=0; - for (List<StringName>::Element *E=classes.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List<StringName>::Element *E = classes.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; - } -PoolStringArray _ClassDB::get_inheriters_from_class( const StringName& p_class) const { +PoolStringArray _ClassDB::get_inheriters_from_class(const StringName &p_class) const { List<StringName> classes; - ClassDB::get_inheriters_from_class(p_class,&classes); + ClassDB::get_inheriters_from_class(p_class, &classes); PoolStringArray ret; ret.resize(classes.size()); - int idx=0; - for (List<StringName>::Element *E=classes.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List<StringName>::Element *E = classes.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; } -StringName _ClassDB::get_parent_class(const StringName& p_class) const { +StringName _ClassDB::get_parent_class(const StringName &p_class) const { return ClassDB::get_parent_class(p_class); } @@ -2422,9 +2306,9 @@ bool _ClassDB::class_exists(const StringName &p_class) const { return ClassDB::class_exists(p_class); } -bool _ClassDB::is_parent_class(const StringName &p_class,const StringName& p_inherits) const { +bool _ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) const { - return ClassDB::is_parent_class(p_class,p_inherits); + return ClassDB::is_parent_class(p_class, p_inherits); } bool _ClassDB::can_instance(const StringName &p_class) const { @@ -2444,27 +2328,26 @@ Variant _ClassDB::instance(const StringName &p_class) const { } } -bool _ClassDB::has_signal(StringName p_class,StringName p_signal) const { +bool _ClassDB::has_signal(StringName p_class, StringName p_signal) const { - return ClassDB::has_signal(p_class,p_signal); + return ClassDB::has_signal(p_class, p_signal); } -Dictionary _ClassDB::get_signal(StringName p_class,StringName p_signal) const { +Dictionary _ClassDB::get_signal(StringName p_class, StringName p_signal) const { MethodInfo signal; - if (ClassDB::get_signal(p_class,p_signal,&signal)) { + if (ClassDB::get_signal(p_class, p_signal, &signal)) { return signal.operator Dictionary(); } else { return Dictionary(); } - } -Array _ClassDB::get_signal_list(StringName p_class,bool p_no_inheritance) const { +Array _ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const { List<MethodInfo> signals; - ClassDB::get_signal_list(p_class,&signals,p_no_inheritance); + ClassDB::get_signal_list(p_class, &signals, p_no_inheritance); Array ret; - for (List<MethodInfo>::Element *E=signals.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { ret.push_back(E->get().operator Dictionary()); } @@ -2474,67 +2357,63 @@ Array _ClassDB::get_signal_list(StringName p_class,bool p_no_inheritance) const Array _ClassDB::get_property_list(StringName p_class, bool p_no_inheritance) const { List<PropertyInfo> plist; - ClassDB::get_property_list(p_class,&plist,p_no_inheritance); + ClassDB::get_property_list(p_class, &plist, p_no_inheritance); Array ret; - for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { ret.push_back(E->get().operator Dictionary()); } return ret; - - } -bool _ClassDB::has_method(StringName p_class,StringName p_method,bool p_no_inheritance) const { +bool _ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inheritance) const { - return ClassDB::has_method(p_class,p_method,p_no_inheritance); + return ClassDB::has_method(p_class, p_method, p_no_inheritance); } - -Array _ClassDB::get_method_list(StringName p_class,bool p_no_inheritance) const { +Array _ClassDB::get_method_list(StringName p_class, bool p_no_inheritance) const { List<MethodInfo> methods; - ClassDB::get_method_list(p_class,&methods,p_no_inheritance); + ClassDB::get_method_list(p_class, &methods, p_no_inheritance); Array ret; - for (List<MethodInfo>::Element *E=methods.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { ret.push_back(E->get().operator Dictionary()); } return ret; } -PoolStringArray _ClassDB::get_integer_constant_list(const StringName& p_class, bool p_no_inheritance) const { +PoolStringArray _ClassDB::get_integer_constant_list(const StringName &p_class, bool p_no_inheritance) const { List<String> constants; - ClassDB::get_integer_constant_list(p_class,&constants,p_no_inheritance); + ClassDB::get_integer_constant_list(p_class, &constants, p_no_inheritance); PoolStringArray ret; ret.resize(constants.size()); - int idx=0; - for (List<String>::Element *E=constants.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List<String>::Element *E = constants.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; } -bool _ClassDB::has_integer_constant(const StringName& p_class, const StringName &p_name) const { +bool _ClassDB::has_integer_constant(const StringName &p_class, const StringName &p_name) const { bool success; - ClassDB::get_integer_constant(p_class,p_name,&success); + ClassDB::get_integer_constant(p_class, p_name, &success); return success; } -int _ClassDB::get_integer_constant(const StringName& p_class, const StringName &p_name) const { +int _ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name) const { bool found; - int c = ClassDB::get_integer_constant(p_class,p_name,&found); - ERR_FAIL_COND_V(!found,0); + int c = ClassDB::get_integer_constant(p_class, p_name, &found); + ERR_FAIL_COND_V(!found, 0); return c; - } -StringName _ClassDB::get_category(const StringName& p_node) const { +StringName _ClassDB::get_category(const StringName &p_node) const { return ClassDB::get_category(p_node); } @@ -2546,46 +2425,39 @@ bool _ClassDB::is_class_enabled(StringName p_class) const { void _ClassDB::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_class_list"),&_ClassDB::get_class_list); - ClassDB::bind_method(D_METHOD("get_inheriters_from_class","class"),&_ClassDB::get_inheriters_from_class); - ClassDB::bind_method(D_METHOD("get_parent_class","class"),&_ClassDB::get_parent_class); - ClassDB::bind_method(D_METHOD("class_exists","class"),&_ClassDB::class_exists); - ClassDB::bind_method(D_METHOD("is_parent_class","class","inherits"),&_ClassDB::is_parent_class); - ClassDB::bind_method(D_METHOD("can_instance","class"),&_ClassDB::can_instance); - ClassDB::bind_method(D_METHOD("instance:Variant","class"),&_ClassDB::instance); + ClassDB::bind_method(D_METHOD("get_class_list"), &_ClassDB::get_class_list); + ClassDB::bind_method(D_METHOD("get_inheriters_from_class", "class"), &_ClassDB::get_inheriters_from_class); + ClassDB::bind_method(D_METHOD("get_parent_class", "class"), &_ClassDB::get_parent_class); + ClassDB::bind_method(D_METHOD("class_exists", "class"), &_ClassDB::class_exists); + ClassDB::bind_method(D_METHOD("is_parent_class", "class", "inherits"), &_ClassDB::is_parent_class); + ClassDB::bind_method(D_METHOD("can_instance", "class"), &_ClassDB::can_instance); + ClassDB::bind_method(D_METHOD("instance:Variant", "class"), &_ClassDB::instance); - ClassDB::bind_method(D_METHOD("class_has_signal","class","signal"),&_ClassDB::has_signal); - ClassDB::bind_method(D_METHOD("class_get_signal","class","signal"),&_ClassDB::get_signal); - ClassDB::bind_method(D_METHOD("class_get_signal_list","class","no_inheritance"),&_ClassDB::get_signal_list,DEFVAL(false)); + ClassDB::bind_method(D_METHOD("class_has_signal", "class", "signal"), &_ClassDB::has_signal); + ClassDB::bind_method(D_METHOD("class_get_signal", "class", "signal"), &_ClassDB::get_signal); + ClassDB::bind_method(D_METHOD("class_get_signal_list", "class", "no_inheritance"), &_ClassDB::get_signal_list, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("class_get_property_list","class","no_inheritance"),&_ClassDB::get_property_list,DEFVAL(false)); + ClassDB::bind_method(D_METHOD("class_get_property_list", "class", "no_inheritance"), &_ClassDB::get_property_list, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("class_has_method","class","method","no_inheritance"),&_ClassDB::has_method,DEFVAL(false)); + ClassDB::bind_method(D_METHOD("class_has_method", "class", "method", "no_inheritance"), &_ClassDB::has_method, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("class_get_method_list","class","no_inheritance"),&_ClassDB::get_method_list,DEFVAL(false)); + ClassDB::bind_method(D_METHOD("class_get_method_list", "class", "no_inheritance"), &_ClassDB::get_method_list, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("class_get_integer_constant_list","class","no_inheritance"),&_ClassDB::get_integer_constant_list,DEFVAL(false)); - - ClassDB::bind_method(D_METHOD("class_has_integer_constant","class","name"),&_ClassDB::has_integer_constant); - ClassDB::bind_method(D_METHOD("class_get_integer_constant","class","name"),&_ClassDB::get_integer_constant); - - ClassDB::bind_method(D_METHOD("class_get_category","class"),&_ClassDB::get_category); - ClassDB::bind_method(D_METHOD("is_class_enabled","class"),&_ClassDB::is_class_enabled); + ClassDB::bind_method(D_METHOD("class_get_integer_constant_list", "class", "no_inheritance"), &_ClassDB::get_integer_constant_list, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("class_has_integer_constant", "class", "name"), &_ClassDB::has_integer_constant); + ClassDB::bind_method(D_METHOD("class_get_integer_constant", "class", "name"), &_ClassDB::get_integer_constant); + ClassDB::bind_method(D_METHOD("class_get_category", "class"), &_ClassDB::get_category); + ClassDB::bind_method(D_METHOD("is_class_enabled", "class"), &_ClassDB::is_class_enabled); } -_ClassDB::_ClassDB(){ - - +_ClassDB::_ClassDB() { } -_ClassDB::~_ClassDB(){ - - +_ClassDB::~_ClassDB() { } /////////////////////////////// - void _Engine::set_iterations_per_second(int p_ips) { Engine::get_singleton()->set_iterations_per_second(p_ips); @@ -2593,7 +2465,6 @@ void _Engine::set_iterations_per_second(int p_ips) { int _Engine::get_iterations_per_second() const { return Engine::get_singleton()->get_iterations_per_second(); - } void _Engine::set_target_fps(int p_fps) { @@ -2604,8 +2475,6 @@ float _Engine::get_target_fps() const { return Engine::get_singleton()->get_target_fps(); } - - float _Engine::get_frames_per_second() const { return Engine::get_singleton()->get_frames_per_second(); @@ -2625,7 +2494,7 @@ float _Engine::get_time_scale() { return Engine::get_singleton()->get_time_scale(); } -int _Engine::get_frames_drawn() { +int _Engine::get_frames_drawn() { return Engine::get_singleton()->get_frames_drawn(); } @@ -2641,30 +2510,28 @@ Dictionary _Engine::get_version_info() const { return Engine::get_singleton()->get_version_info(); } - void _Engine::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_iterations_per_second","iterations_per_second"),&_Engine::set_iterations_per_second); - ClassDB::bind_method(D_METHOD("get_iterations_per_second"),&_Engine::get_iterations_per_second); - ClassDB::bind_method(D_METHOD("set_target_fps","target_fps"),&_Engine::set_target_fps); - ClassDB::bind_method(D_METHOD("get_target_fps"),&_Engine::get_target_fps); - - ClassDB::bind_method(D_METHOD("set_time_scale","time_scale"),&_Engine::set_time_scale); - ClassDB::bind_method(D_METHOD("get_time_scale"),&_Engine::get_time_scale); + ClassDB::bind_method(D_METHOD("set_iterations_per_second", "iterations_per_second"), &_Engine::set_iterations_per_second); + ClassDB::bind_method(D_METHOD("get_iterations_per_second"), &_Engine::get_iterations_per_second); + ClassDB::bind_method(D_METHOD("set_target_fps", "target_fps"), &_Engine::set_target_fps); + ClassDB::bind_method(D_METHOD("get_target_fps"), &_Engine::get_target_fps); - ClassDB::bind_method(D_METHOD("get_custom_level"),&_Engine::get_custom_level); + ClassDB::bind_method(D_METHOD("set_time_scale", "time_scale"), &_Engine::set_time_scale); + ClassDB::bind_method(D_METHOD("get_time_scale"), &_Engine::get_time_scale); - ClassDB::bind_method(D_METHOD("get_frames_drawn"),&_Engine::get_frames_drawn); - ClassDB::bind_method(D_METHOD("get_frames_per_second"),&_Engine::get_frames_per_second); + ClassDB::bind_method(D_METHOD("get_custom_level"), &_Engine::get_custom_level); - ClassDB::bind_method(D_METHOD("get_main_loop:MainLoop"),&_Engine::get_main_loop); + ClassDB::bind_method(D_METHOD("get_frames_drawn"), &_Engine::get_frames_drawn); + ClassDB::bind_method(D_METHOD("get_frames_per_second"), &_Engine::get_frames_per_second); - ClassDB::bind_method(D_METHOD("get_version_info"),&_Engine::get_version_info); + ClassDB::bind_method(D_METHOD("get_main_loop:MainLoop"), &_Engine::get_main_loop); + ClassDB::bind_method(D_METHOD("get_version_info"), &_Engine::get_version_info); } _Engine *_Engine::singleton = NULL; _Engine::_Engine() { - singleton=this; + singleton = this; } diff --git a/core/bind/core_bind.h b/core/bind/core_bind.h index 6b9ae198ef..1d231ff033 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/semaphore.h" +#include "os/file_access.h" #include "os/power.h" +#include "os/semaphore.h" +#include "os/thread.h" - -class _ResourceLoader : public Object { - GDCLASS(_ResourceLoader,Object); +class _ResourceLoader : public Object { + GDCLASS(_ResourceLoader, Object); protected: - static void _bind_methods(); static _ResourceLoader *singleton; -public: - +public: static _ResourceLoader *get_singleton() { return singleton; } - Ref<ResourceInteractiveLoader> 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); - PoolVector<String> get_recognized_extensions_for_type(const String& p_type); + Ref<ResourceInteractiveLoader> 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); + PoolVector<String> get_recognized_extensions_for_type(const String &p_type); void set_abort_on_missing_resources(bool p_abort); - PoolStringArray get_dependencies(const String& p_path); - bool has(const String& p_path); + PoolStringArray get_dependencies(const String &p_path); + bool has(const String &p_path); _ResourceLoader(); }; -class _ResourceSaver : public Object { - GDCLASS(_ResourceSaver,Object); +class _ResourceSaver : public Object { + GDCLASS(_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); - PoolVector<String> get_recognized_extensions(const RES& p_resource); - + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags); + PoolVector<String> get_recognized_extensions(const RES &p_resource); _ResourceSaver(); }; class MainLoop; -class _OS : public Object { - GDCLASS(_OS,Object); +class _OS : public Object { + GDCLASS(_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); @@ -173,15 +165,15 @@ public: bool is_in_low_processor_usage_mode() const; String get_executable_path() const; - int execute(const String& p_path, const Vector<String> & p_arguments,bool p_blocking,Array p_output=Array()); + int execute(const String &p_path, const Vector<String> &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<String> get_cmdline_args(); @@ -191,18 +183,17 @@ public: String get_model_name() 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<String>& p_types); + void print_resources_by_type(const Vector<String> &p_types); bool has_touchscreen_ui_hint() const; @@ -212,8 +203,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 { @@ -235,7 +225,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); @@ -289,11 +279,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; @@ -301,10 +289,9 @@ public: void set_keep_screen_on(bool p_enabled); bool is_keep_screen_on() const; - 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; @@ -321,76 +308,71 @@ public: VARIANT_ENUM_CAST(_OS::SystemDir); VARIANT_ENUM_CAST(_OS::ScreenOrientation); - class _Geometry : public Object { GDCLASS(_Geometry, Object); static _Geometry *singleton; -protected: +protected: static void _bind_methods(); -public: +public: static _Geometry *get_singleton(); - PoolVector<Plane> build_box_planes(const Vector3& p_extents); - PoolVector<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z); - PoolVector<Plane> 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); - PoolVector<Vector2> get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2); - PoolVector<Vector3> 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; - - PoolVector<Vector3> segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius); - PoolVector<Vector3> segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius); - PoolVector<Vector3> segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector<Plane>& 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<int> triangulate_polygon(const Vector<Vector2>& p_polygon); - - Dictionary make_atlas(const Vector<Size2>& p_rects); + PoolVector<Plane> build_box_planes(const Vector3 &p_extents); + PoolVector<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z); + PoolVector<Plane> 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); + PoolVector<Vector2> get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2); + PoolVector<Vector3> 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; + + PoolVector<Vector3> segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius); + PoolVector<Vector3> segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius); + PoolVector<Vector3> segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector<Plane> &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<int> triangulate_polygon(const Vector<Vector2> &p_polygon); + + Dictionary make_atlas(const Vector<Size2> &p_rects); _Geometry(); }; - - - class _File : public Reference { - GDCLASS(_File,Reference); + GDCLASS(_File, Reference); FileAccess *f; bool eswap; -protected: +protected: static void _bind_methods(); -public: - enum ModeFlags { +public: + 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<uint8_t>& 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<uint8_t> &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 @@ -410,8 +392,8 @@ public: PoolVector<uint8_t> 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. @@ -432,38 +414,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<String> get_csv_line(String delim=",") const; + Vector<String> get_csv_line(String delim = ",") const; + void store_buffer(const PoolVector<uint8_t> &p_buffer); ///< store an array of bytes - void store_buffer(const PoolVector<uint8_t>& 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 { - GDCLASS(_Directory,Reference); + GDCLASS(_Directory, Reference); DirAccess *d; -protected: +protected: static void _bind_methods(); -public: - Error open(const String& p_path); +public: + Error open(const String &p_path); Error list_dir_begin(bool p_skip_internal = false, bool p_skip_hidden = false); ///< This starts dir listing String get_next(); @@ -486,11 +466,10 @@ 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(); @@ -501,41 +480,37 @@ private: class _Marshalls : public Reference { - GDCLASS(_Marshalls,Reference); + GDCLASS(_Marshalls, Reference); - static _Marshalls* singleton; + static _Marshalls *singleton; protected: - static void _bind_methods(); - public: + static _Marshalls *get_singleton(); - static _Marshalls* get_singleton(); - - 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 PoolVector<uint8_t>& p_arr); - PoolVector<uint8_t> base64_to_raw(const String& p_str); + String raw_to_base64(const PoolVector<uint8_t> &p_arr); + PoolVector<uint8_t> 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() { singleton = this; } ~_Marshalls() { singleton = NULL; } }; - class _Mutex : public Reference { - GDCLASS(_Mutex,Reference); + GDCLASS(_Mutex, Reference); Mutex *mutex; static void _bind_methods(); -public: +public: void lock(); Error try_lock(); void unlock(); @@ -546,12 +521,12 @@ public: class _Semaphore : public Reference { - GDCLASS(_Semaphore,Reference); + GDCLASS(_Semaphore, Reference); Semaphore *semaphore; static void _bind_methods(); -public: +public: Error wait(); Error post(); @@ -561,10 +536,9 @@ public: class _Thread : public Reference { - GDCLASS(_Thread,Reference); + GDCLASS(_Thread, Reference); protected: - Variant ret; Variant userdata; volatile bool active; @@ -573,8 +547,8 @@ protected: Thread *thread; static void _bind_methods(); static void _start_func(void *ud); -public: +public: enum Priority { PRIORITY_LOW, @@ -582,7 +556,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(); @@ -593,35 +567,34 @@ public: class _ClassDB : public Object { - GDCLASS(_ClassDB,Object) + GDCLASS(_ClassDB, Object) protected: static void _bind_methods(); -public: +public: PoolStringArray get_class_list() const; - PoolStringArray get_inheriters_from_class( const StringName& p_class) const; - StringName get_parent_class(const StringName& p_class) const; + PoolStringArray get_inheriters_from_class(const StringName &p_class) const; + StringName get_parent_class(const StringName &p_class) const; bool class_exists(const StringName &p_class) const; - bool is_parent_class(const StringName &p_class,const StringName& p_inherits) const; + bool is_parent_class(const StringName &p_class, const StringName &p_inherits) const; bool can_instance(const StringName &p_class) const; Variant instance(const StringName &p_class) const; - bool has_signal(StringName p_class,StringName p_signal) const; - Dictionary get_signal(StringName p_class,StringName p_signal) const; - Array get_signal_list(StringName p_class,bool p_no_inheritance=false) const; + bool has_signal(StringName p_class, StringName p_signal) const; + Dictionary get_signal(StringName p_class, StringName p_signal) const; + Array get_signal_list(StringName p_class, bool p_no_inheritance = false) const; - Array get_property_list(StringName p_class, bool p_no_inheritance=false) const; + Array get_property_list(StringName p_class, bool p_no_inheritance = false) const; - bool has_method(StringName p_class,StringName p_method,bool p_no_inheritance=false) const; + bool has_method(StringName p_class, StringName p_method, bool p_no_inheritance = false) const; + Array get_method_list(StringName p_class, bool p_no_inheritance = false) const; - Array get_method_list(StringName p_class,bool p_no_inheritance=false) const; - - PoolStringArray get_integer_constant_list(const StringName& p_class, bool p_no_inheritance=false) const; - bool has_integer_constant(const StringName& p_class, const StringName &p_name) const; - int get_integer_constant(const StringName& p_class, const StringName &p_name) const; - StringName get_category(const StringName& p_node) const; + PoolStringArray get_integer_constant_list(const StringName &p_class, bool p_no_inheritance = false) const; + bool has_integer_constant(const StringName &p_class, const StringName &p_name) const; + int get_integer_constant(const StringName &p_class, const StringName &p_name) const; + StringName get_category(const StringName &p_node) const; bool is_class_enabled(StringName p_class) const; @@ -629,18 +602,15 @@ public: ~_ClassDB(); }; - -class _Engine : public Object { - GDCLASS(_Engine,Object); +class _Engine : public Object { + GDCLASS(_Engine, Object); protected: - static void _bind_methods(); static _Engine *singleton; public: - - static _Engine* get_singleton() { return singleton; } + static _Engine *get_singleton() { return singleton; } void set_iterations_per_second(int p_ips); int get_iterations_per_second() const; @@ -649,7 +619,7 @@ public: float get_frames_per_second() const; - int get_frames_drawn(); + int get_frames_drawn(); void set_time_scale(float p_scale); float get_time_scale(); @@ -663,5 +633,4 @@ public: _Engine(); }; - #endif // CORE_BIND_H diff --git a/core/class_db.cpp b/core/class_db.cpp index 4bdae45fb9..3c376f7451 100644 --- a/core/class_db.cpp +++ b/core/class_db.cpp @@ -44,200 +44,196 @@ #ifdef DEBUG_METHODS_ENABLED -ParamDef::ParamDef(const Variant& p_variant) { used=true; val=p_variant; } - +ParamDef::ParamDef(const Variant &p_variant) { + used = true; + val = p_variant; +} -MethodDefinition D_METHOD(const char* p_name) { +MethodDefinition D_METHOD(const char *p_name) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.push_back(StaticCString::create(p_arg1)); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(2); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(3); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(4); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(5); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); - md.args[4]=StaticCString::create(p_arg5); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); + md.args[4] = StaticCString::create(p_arg5); return md; } - -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(6); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); - md.args[4]=StaticCString::create(p_arg5); - md.args[5]=StaticCString::create(p_arg6); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); + md.args[4] = StaticCString::create(p_arg5); + md.args[5] = StaticCString::create(p_arg6); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(7); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); - md.args[4]=StaticCString::create(p_arg5); - md.args[5]=StaticCString::create(p_arg6); - md.args[6]=StaticCString::create(p_arg7); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); + md.args[4] = StaticCString::create(p_arg5); + md.args[5] = StaticCString::create(p_arg6); + md.args[6] = StaticCString::create(p_arg7); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(8); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); - md.args[4]=StaticCString::create(p_arg5); - md.args[5]=StaticCString::create(p_arg6); - md.args[6]=StaticCString::create(p_arg7); - md.args[7]=StaticCString::create(p_arg8); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); + md.args[4] = StaticCString::create(p_arg5); + md.args[5] = StaticCString::create(p_arg6); + md.args[6] = StaticCString::create(p_arg7); + md.args[7] = StaticCString::create(p_arg8); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(9); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); - md.args[4]=StaticCString::create(p_arg5); - md.args[5]=StaticCString::create(p_arg6); - md.args[6]=StaticCString::create(p_arg7); - md.args[7]=StaticCString::create(p_arg8); - md.args[8]=StaticCString::create(p_arg9); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); + md.args[4] = StaticCString::create(p_arg5); + md.args[5] = StaticCString::create(p_arg6); + md.args[6] = StaticCString::create(p_arg7); + md.args[7] = StaticCString::create(p_arg8); + md.args[8] = StaticCString::create(p_arg9); return md; } -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9,const char *p_arg10) { +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9, const char *p_arg10) { MethodDefinition md; - md.name=StaticCString::create(p_name); + md.name = StaticCString::create(p_name); md.args.resize(10); - md.args[0]=StaticCString::create(p_arg1); - md.args[1]=StaticCString::create(p_arg2); - md.args[2]=StaticCString::create(p_arg3); - md.args[3]=StaticCString::create(p_arg4); - md.args[4]=StaticCString::create(p_arg5); - md.args[5]=StaticCString::create(p_arg6); - md.args[6]=StaticCString::create(p_arg7); - md.args[7]=StaticCString::create(p_arg8); - md.args[8]=StaticCString::create(p_arg9); - md.args[9]=StaticCString::create(p_arg10); + md.args[0] = StaticCString::create(p_arg1); + md.args[1] = StaticCString::create(p_arg2); + md.args[2] = StaticCString::create(p_arg3); + md.args[3] = StaticCString::create(p_arg4); + md.args[4] = StaticCString::create(p_arg5); + md.args[5] = StaticCString::create(p_arg6); + md.args[6] = StaticCString::create(p_arg7); + md.args[7] = StaticCString::create(p_arg8); + md.args[8] = StaticCString::create(p_arg9); + md.args[9] = StaticCString::create(p_arg10); return md; } - #endif - -ClassDB::APIType ClassDB::current_api=API_CORE; +ClassDB::APIType ClassDB::current_api = API_CORE; void ClassDB::set_current_api(APIType p_api) { - current_api=p_api; + current_api = p_api; } -HashMap<StringName,ClassDB::ClassInfo,StringNameHasher> ClassDB::classes; -HashMap<StringName,StringName,StringNameHasher> ClassDB::resource_base_extensions; -HashMap<StringName,StringName,StringNameHasher> ClassDB::compat_classes; +HashMap<StringName, ClassDB::ClassInfo, StringNameHasher> ClassDB::classes; +HashMap<StringName, StringName, StringNameHasher> ClassDB::resource_base_extensions; +HashMap<StringName, StringName, StringNameHasher> ClassDB::compat_classes; ClassDB::ClassInfo::ClassInfo() { - creation_func=NULL; - inherits_ptr=NULL; - disabled=false; + creation_func = NULL; + inherits_ptr = NULL; + disabled = false; } ClassDB::ClassInfo::~ClassInfo() { - - } - -bool ClassDB::is_parent_class(const StringName &p_class,const StringName& p_inherits) { +bool ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) { OBJTYPE_RLOCK; - StringName inherits=p_class; + StringName inherits = p_class; while (inherits.operator String().length()) { - if (inherits==p_inherits) + if (inherits == p_inherits) return true; - inherits=get_parent_class(inherits); + inherits = get_parent_class(inherits); } return false; } -void ClassDB::get_class_list( List<StringName> *p_classes) { +void ClassDB::get_class_list(List<StringName> *p_classes) { OBJTYPE_RLOCK; - const StringName *k=NULL; + const StringName *k = NULL; - while((k=classes.next(k))) { + while ((k = classes.next(k))) { p_classes->push_back(*k); } @@ -245,22 +241,20 @@ void ClassDB::get_class_list( List<StringName> *p_classes) { p_classes->sort(); } - -void ClassDB::get_inheriters_from_class( const StringName& p_class,List<StringName> *p_classes) { +void ClassDB::get_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes) { OBJTYPE_RLOCK; - const StringName *k=NULL; + const StringName *k = NULL; - while((k=classes.next(k))) { + while ((k = classes.next(k))) { - if (*k!=p_class && is_parent_class(*k,p_class)) + if (*k != p_class && is_parent_class(*k, p_class)) p_classes->push_back(*k); } - } -StringName ClassDB::get_parent_class_nocheck(const StringName& p_class) { +StringName ClassDB::get_parent_class_nocheck(const StringName &p_class) { OBJTYPE_RLOCK; @@ -268,15 +262,14 @@ StringName ClassDB::get_parent_class_nocheck(const StringName& p_class) { if (!ti) return StringName(); return ti->inherits; - } -StringName ClassDB::get_parent_class(const StringName& p_class) { +StringName ClassDB::get_parent_class(const StringName &p_class) { OBJTYPE_RLOCK; ClassInfo *ti = classes.getptr(p_class); - ERR_FAIL_COND_V(!ti,StringName()); + ERR_FAIL_COND_V(!ti, StringName()); return ti->inherits; } @@ -286,7 +279,7 @@ ClassDB::APIType ClassDB::get_api_type(const StringName &p_class) { ClassInfo *ti = classes.getptr(p_class); - ERR_FAIL_COND_V(!ti,API_NONE); + ERR_FAIL_COND_V(!ti, API_NONE); return ti->api; } @@ -299,105 +292,102 @@ uint64_t ClassDB::get_api_hash(APIType p_api) { List<StringName> names; - const StringName *k=NULL; + const StringName *k = NULL; - while((k=classes.next(k))) { + while ((k = classes.next(k))) { names.push_back(*k); } //must be alphabetically sorted for hash to compute names.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *E=names.front();E;E=E->next()) { + for (List<StringName>::Element *E = names.front(); E; E = E->next()) { ClassInfo *t = classes.getptr(E->get()); - ERR_FAIL_COND_V(!t,0); - if (t->api!=p_api) + ERR_FAIL_COND_V(!t, 0); + if (t->api != p_api) continue; - hash = hash_djb2_one_64(t->name.hash(),hash); - hash = hash_djb2_one_64(t->inherits.hash(),hash); + hash = hash_djb2_one_64(t->name.hash(), hash); + hash = hash_djb2_one_64(t->inherits.hash(), hash); { //methods List<StringName> snames; - k=NULL; + k = NULL; - while((k=t->method_map.next(k))) { + while ((k = t->method_map.next(k))) { snames.push_back(*k); } snames.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *F=snames.front();F;F=F->next()) { + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { MethodBind *mb = t->method_map[F->get()]; - hash = hash_djb2_one_64( mb->get_name().hash(), hash); - hash = hash_djb2_one_64( mb->get_argument_count(), hash); - hash = hash_djb2_one_64( mb->get_argument_type(-1), hash); //return - - for(int i=0;i<mb->get_argument_count();i++) { - hash = hash_djb2_one_64( mb->get_argument_info(i).type, hash ); - hash = hash_djb2_one_64( mb->get_argument_info(i).name.hash(), hash ); - hash = hash_djb2_one_64( mb->get_argument_info(i).hint, hash ); - hash = hash_djb2_one_64( mb->get_argument_info(i).hint_string.hash(), hash ); + hash = hash_djb2_one_64(mb->get_name().hash(), hash); + hash = hash_djb2_one_64(mb->get_argument_count(), hash); + hash = hash_djb2_one_64(mb->get_argument_type(-1), hash); //return + + for (int i = 0; i < mb->get_argument_count(); i++) { + hash = hash_djb2_one_64(mb->get_argument_info(i).type, hash); + hash = hash_djb2_one_64(mb->get_argument_info(i).name.hash(), hash); + hash = hash_djb2_one_64(mb->get_argument_info(i).hint, hash); + hash = hash_djb2_one_64(mb->get_argument_info(i).hint_string.hash(), hash); } - hash = hash_djb2_one_64( mb->get_default_argument_count(), hash); + hash = hash_djb2_one_64(mb->get_default_argument_count(), hash); - for(int i=0;i<mb->get_default_argument_count();i++) { + for (int i = 0; i < mb->get_default_argument_count(); i++) { //hash should not change, i hope for tis Variant da = mb->get_default_argument(i); - hash = hash_djb2_one_64( da.hash(), hash ); + hash = hash_djb2_one_64(da.hash(), hash); } - hash = hash_djb2_one_64( mb->get_hint_flags(), hash); - + hash = hash_djb2_one_64(mb->get_hint_flags(), hash); } } - { //constants List<StringName> snames; - k=NULL; + k = NULL; - while((k=t->constant_map.next(k))) { + while ((k = t->constant_map.next(k))) { snames.push_back(*k); } snames.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *F=snames.front();F;F=F->next()) { + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { hash = hash_djb2_one_64(F->get().hash(), hash); - hash = hash_djb2_one_64( t->constant_map[F->get()], hash); + hash = hash_djb2_one_64(t->constant_map[F->get()], hash); } } - { //signals List<StringName> snames; - k=NULL; + k = NULL; - while((k=t->signal_map.next(k))) { + while ((k = t->signal_map.next(k))) { snames.push_back(*k); } snames.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *F=snames.front();F;F=F->next()) { + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { MethodInfo &mi = t->signal_map[F->get()]; - hash = hash_djb2_one_64( F->get().hash(), hash); - for(int i=0;i<mi.arguments.size();i++) { - hash = hash_djb2_one_64( mi.arguments[i].type, hash); + hash = hash_djb2_one_64(F->get().hash(), hash); + for (int i = 0; i < mi.arguments.size(); i++) { + hash = hash_djb2_one_64(mi.arguments[i].type, hash); } } } @@ -406,45 +396,40 @@ uint64_t ClassDB::get_api_hash(APIType p_api) { List<StringName> snames; - k=NULL; + k = NULL; - while((k=t->property_setget.next(k))) { + while ((k = t->property_setget.next(k))) { snames.push_back(*k); } snames.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *F=snames.front();F;F=F->next()) { + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { - PropertySetGet *psg=t->property_setget.getptr(F->get()); - - hash = hash_djb2_one_64( F->get().hash(), hash); - hash = hash_djb2_one_64( psg->setter.hash(), hash); - hash = hash_djb2_one_64( psg->getter.hash(), hash); + PropertySetGet *psg = t->property_setget.getptr(F->get()); + hash = hash_djb2_one_64(F->get().hash(), hash); + hash = hash_djb2_one_64(psg->setter.hash(), hash); + hash = hash_djb2_one_64(psg->getter.hash(), hash); } } //property list - for (List<PropertyInfo>::Element *F=t->property_list.front();F;F=F->next()) { + for (List<PropertyInfo>::Element *F = t->property_list.front(); F; F = F->next()) { - hash = hash_djb2_one_64( F->get().name.hash(), hash); - hash = hash_djb2_one_64( F->get().type, hash); - hash = hash_djb2_one_64( F->get().hint, hash); - hash = hash_djb2_one_64( F->get().hint_string.hash(), hash); - hash = hash_djb2_one_64( F->get().usage, hash); + hash = hash_djb2_one_64(F->get().name.hash(), hash); + hash = hash_djb2_one_64(F->get().type, hash); + hash = hash_djb2_one_64(F->get().hint, hash); + hash = hash_djb2_one_64(F->get().hint_string.hash(), hash); + hash = hash_djb2_one_64(F->get().usage, hash); } - - } - return hash; #else return 0; #endif - } bool ClassDB::class_exists(const StringName &p_class) { @@ -453,10 +438,10 @@ bool ClassDB::class_exists(const StringName &p_class) { return classes.has(p_class); } -void ClassDB::add_compatibility_class(const StringName& p_class,const StringName& p_fallback) { +void ClassDB::add_compatibility_class(const StringName &p_class, const StringName &p_fallback) { OBJTYPE_WLOCK; - compat_classes[p_class]=p_fallback; + compat_classes[p_class] = p_fallback; } Object *ClassDB::instance(const StringName &p_class) { @@ -464,15 +449,15 @@ Object *ClassDB::instance(const StringName &p_class) { ClassInfo *ti; { OBJTYPE_RLOCK; - ti=classes.getptr(p_class); + ti = classes.getptr(p_class); if (!ti || ti->disabled || !ti->creation_func) { if (compat_classes.has(p_class)) { - ti=classes.getptr(compat_classes[p_class]); + ti = classes.getptr(compat_classes[p_class]); } } - ERR_FAIL_COND_V(!ti,NULL); - ERR_FAIL_COND_V(ti->disabled,NULL); - ERR_FAIL_COND_V(!ti->creation_func,NULL); + ERR_FAIL_COND_V(!ti, NULL); + ERR_FAIL_COND_V(ti->disabled, NULL); + ERR_FAIL_COND_V(!ti->creation_func, NULL); } return ti->creation_func(); @@ -482,12 +467,11 @@ bool ClassDB::can_instance(const StringName &p_class) { OBJTYPE_RLOCK; ClassInfo *ti = classes.getptr(p_class); - ERR_FAIL_COND_V(!ti,false); - return (!ti->disabled && ti->creation_func!=NULL); + ERR_FAIL_COND_V(!ti, false); + return (!ti->disabled && ti->creation_func != NULL); } - -void ClassDB::_add_class2(const StringName& p_class, const StringName& p_inherits) { +void ClassDB::_add_class2(const StringName &p_class, const StringName &p_inherits) { OBJTYPE_WLOCK; @@ -495,120 +479,110 @@ void ClassDB::_add_class2(const StringName& p_class, const StringName& p_inherit ERR_FAIL_COND(classes.has(name)); - classes[name]=ClassInfo(); - ClassInfo &ti=classes[name]; - ti.name=name; - ti.inherits=p_inherits; - ti.api=current_api; + classes[name] = ClassInfo(); + ClassInfo &ti = classes[name]; + ti.name = name; + ti.inherits = p_inherits; + ti.api = current_api; if (ti.inherits) { - ERR_FAIL_COND( !classes.has(ti.inherits) ); //it MUST be registered. + ERR_FAIL_COND(!classes.has(ti.inherits)); //it MUST be registered. ti.inherits_ptr = &classes[ti.inherits]; } else { - ti.inherits_ptr=NULL; + ti.inherits_ptr = NULL; } - - } -void ClassDB::get_method_list(StringName p_class,List<MethodInfo> *p_methods,bool p_no_inheritance) { - +void ClassDB::get_method_list(StringName p_class, List<MethodInfo> *p_methods, bool p_no_inheritance) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); - while(type) { + while (type) { if (type->disabled) { if (p_no_inheritance) break; - type=type->inherits_ptr; + type = type->inherits_ptr; continue; } #ifdef DEBUG_METHODS_ENABLED - for( List<MethodInfo>::Element *E=type->virtual_methods.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = type->virtual_methods.front(); E; E = E->next()) { p_methods->push_back(E->get()); } - for( List<StringName>::Element *E=type->method_order.front();E;E=E->next()) { + for (List<StringName>::Element *E = type->method_order.front(); E; E = E->next()) { - MethodBind *method=type->method_map.get(E->get()); + MethodBind *method = type->method_map.get(E->get()); MethodInfo minfo; - minfo.name=E->get(); - minfo.id=method->get_method_id(); + minfo.name = E->get(); + minfo.id = method->get_method_id(); - for (int i=0;i<method->get_argument_count();i++) { + for (int i = 0; i < method->get_argument_count(); i++) { //Variant::Type t=method->get_argument_type(i); minfo.arguments.push_back(method->get_argument_info(i)); } - - if (method->get_argument_type(-1)!=Variant::NIL) { - minfo.return_val=method->get_argument_info(-1); + if (method->get_argument_type(-1) != Variant::NIL) { + minfo.return_val = method->get_argument_info(-1); } - minfo.flags=method->get_hint_flags(); + minfo.flags = method->get_hint_flags(); p_methods->push_back(minfo); } - - #else - const StringName *K=NULL; + const StringName *K = NULL; - while((K=type->method_map.next(K))) { + while ((K = type->method_map.next(K))) { - MethodBind*m = type->method_map[*K]; + MethodBind *m = type->method_map[*K]; MethodInfo mi; - mi.name=m->get_name(); + mi.name = m->get_name(); p_methods->push_back(mi); } - #endif if (p_no_inheritance) break; - type=type->inherits_ptr; + type = type->inherits_ptr; } - } - MethodBind *ClassDB::get_method(StringName p_class, StringName p_name) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); - while(type) { + while (type) { - MethodBind **method=type->method_map.getptr(p_name); + MethodBind **method = type->method_map.getptr(p_name); if (method && *method) return *method; - type=type->inherits_ptr; + type = type->inherits_ptr; } return NULL; } - -void ClassDB::bind_integer_constant(const StringName& p_class, const StringName &p_name, int p_constant) { +void ClassDB::bind_integer_constant(const StringName &p_class, const StringName &p_name, int p_constant) { OBJTYPE_WLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); if (!type) { ERR_FAIL_COND(!type); @@ -619,28 +593,27 @@ void ClassDB::bind_integer_constant(const StringName& p_class, const StringName ERR_FAIL(); } - type->constant_map[p_name]=p_constant; + type->constant_map[p_name] = p_constant; #ifdef DEBUG_METHODS_ENABLED type->constant_order.push_back(p_name); #endif - } -void ClassDB::get_integer_constant_list(const StringName& p_class, List<String> *p_constants, bool p_no_inheritance) { +void ClassDB::get_integer_constant_list(const StringName &p_class, List<String> *p_constants, bool p_no_inheritance) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); - while(type) { + while (type) { #ifdef DEBUG_METHODS_ENABLED - for(List<StringName>::Element *E=type->constant_order.front();E;E=E->next()) + for (List<StringName>::Element *E = type->constant_order.front(); E; E = E->next()) p_constants->push_back(E->get()); #else - const StringName *K=NULL; + const StringName *K = NULL; - while((K=type->constant_map.next(K))) { + while ((K = type->constant_map.next(K))) { p_constants->push_back(*K); } @@ -648,76 +621,71 @@ void ClassDB::get_integer_constant_list(const StringName& p_class, List<String> if (p_no_inheritance) break; - type=type->inherits_ptr; + type = type->inherits_ptr; } - } - -int ClassDB::get_integer_constant(const StringName& p_class, const StringName &p_name, bool *p_success) { +int ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name, bool *p_success) { OBJTYPE_RLOCK; + ClassInfo *type = classes.getptr(p_class); - ClassInfo *type=classes.getptr(p_class); - - while(type) { + while (type) { - - int *constant=type->constant_map.getptr(p_name); + int *constant = type->constant_map.getptr(p_name); if (constant) { if (p_success) - *p_success=true; + *p_success = true; return *constant; } - type=type->inherits_ptr; + type = type->inherits_ptr; } if (p_success) - *p_success=false; + *p_success = false; return 0; } -void ClassDB::add_signal(StringName p_class,const MethodInfo& p_signal) { +void ClassDB::add_signal(StringName p_class, const MethodInfo &p_signal) { OBJTYPE_WLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); ERR_FAIL_COND(!type); - ClassInfo *check=type; + ClassInfo *check = type; StringName sname = p_signal.name; #ifdef DEBUG_METHODS_ENABLED - while(check) { + while (check) { if (check->signal_map.has(sname)) { - ERR_EXPLAIN("Type "+String(p_class)+" already has signal: "+String(sname)); + ERR_EXPLAIN("Type " + String(p_class) + " already has signal: " + String(sname)); ERR_FAIL(); } - check=check->inherits_ptr; + check = check->inherits_ptr; } #endif - type->signal_map[sname]=p_signal; - + type->signal_map[sname] = p_signal; } -void ClassDB::get_signal_list(StringName p_class,List<MethodInfo> *p_signals,bool p_no_inheritance) { +void ClassDB::get_signal_list(StringName p_class, List<MethodInfo> *p_signals, bool p_no_inheritance) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); ERR_FAIL_COND(!type); - ClassInfo *check=type; + ClassInfo *check = type; - while(check) { + while (check) { - const StringName *S=NULL; - while((S=check->signal_map.next(S))) { + const StringName *S = NULL; + while ((S = check->signal_map.next(S))) { p_signals->push_back(check->signal_map[*S]); } @@ -725,63 +693,58 @@ void ClassDB::get_signal_list(StringName p_class,List<MethodInfo> *p_signals,boo if (p_no_inheritance) return; - check=check->inherits_ptr; + check = check->inherits_ptr; } - - } -bool ClassDB::has_signal(StringName p_class,StringName p_signal) { +bool ClassDB::has_signal(StringName p_class, StringName p_signal) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { if (check->signal_map.has(p_signal)) return true; - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; } -bool ClassDB::get_signal(StringName p_class,StringName p_signal,MethodInfo *r_signal) { +bool ClassDB::get_signal(StringName p_class, StringName p_signal, MethodInfo *r_signal) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { if (check->signal_map.has(p_signal)) { if (r_signal) { - *r_signal=check->signal_map[p_signal]; + *r_signal = check->signal_map[p_signal]; } return true; } - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; } - -void ClassDB::add_property_group(StringName p_class,const String& p_name,const String& p_prefix) { +void ClassDB::add_property_group(StringName p_class, const String &p_name, const String &p_prefix) { OBJTYPE_WLOCK; - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); ERR_FAIL_COND(!type); - type->property_list.push_back(PropertyInfo(Variant::NIL,p_name,PROPERTY_HINT_NONE,p_prefix,PROPERTY_USAGE_GROUP)); + type->property_list.push_back(PropertyInfo(Variant::NIL, p_name, PROPERTY_HINT_NONE, p_prefix, PROPERTY_USAGE_GROUP)); } -void ClassDB::add_property(StringName p_class,const PropertyInfo& p_pinfo, const StringName& p_setter, const StringName& p_getter, int p_index) { - - +void ClassDB::add_property(StringName p_class, const PropertyInfo &p_pinfo, const StringName &p_setter, const StringName &p_getter, int p_index) { #ifndef NO_THREADS lock->read_lock(); #endif - ClassInfo *type=classes.getptr(p_class); + ClassInfo *type = classes.getptr(p_class); #ifndef NO_THREADS lock->read_unlock(); @@ -789,52 +752,47 @@ void ClassDB::add_property(StringName p_class,const PropertyInfo& p_pinfo, const ERR_FAIL_COND(!type); - MethodBind *mb_set=NULL; + MethodBind *mb_set = NULL; if (p_setter) { - mb_set = get_method(p_class,p_setter); + mb_set = get_method(p_class, p_setter); #ifdef DEBUG_METHODS_ENABLED if (!mb_set) { - ERR_EXPLAIN("Invalid Setter: "+p_class+"::"+p_setter+" for property: "+p_pinfo.name); + ERR_EXPLAIN("Invalid Setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name); ERR_FAIL_COND(!mb_set); } else { - int exp_args=1+(p_index>=0?1:0); - if (mb_set->get_argument_count()!=exp_args) { - ERR_EXPLAIN("Invalid Function for Setter: "+p_class+"::"+p_setter+" for property: "+p_pinfo.name); + int exp_args = 1 + (p_index >= 0 ? 1 : 0); + if (mb_set->get_argument_count() != exp_args) { + ERR_EXPLAIN("Invalid Function for Setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name); ERR_FAIL(); - } } #endif } - MethodBind *mb_get=NULL; + MethodBind *mb_get = NULL; if (p_getter) { - MethodBind *mb_get = get_method(p_class,p_getter); + MethodBind *mb_get = get_method(p_class, p_getter); #ifdef DEBUG_METHODS_ENABLED if (!mb_get) { - ERR_EXPLAIN("Invalid Getter: "+p_class+"::"+p_getter+" for property: "+p_pinfo.name); + ERR_EXPLAIN("Invalid Getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name); ERR_FAIL_COND(!mb_get); } else { - int exp_args=0+(p_index>=0?1:0); - if (mb_get->get_argument_count()!=exp_args) { - ERR_EXPLAIN("Invalid Function for Getter: "+p_class+"::"+p_getter+" for property: "+p_pinfo.name); + int exp_args = 0 + (p_index >= 0 ? 1 : 0); + if (mb_get->get_argument_count() != exp_args) { + ERR_EXPLAIN("Invalid Function for Getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name); ERR_FAIL(); - } - } #endif } - - #ifdef DEBUG_METHODS_ENABLED if (type->property_setget.has(p_pinfo.name)) { - ERR_EXPLAIN("Object already has property: "+p_class); + ERR_EXPLAIN("Object already has property: " + p_class); ERR_FAIL(); } #endif @@ -844,28 +802,25 @@ void ClassDB::add_property(StringName p_class,const PropertyInfo& p_pinfo, const type->property_list.push_back(p_pinfo); PropertySetGet psg; - psg.setter=p_setter; - psg.getter=p_getter; - psg._setptr=mb_set; - psg._getptr=mb_get; - psg.index=p_index; - psg.type=p_pinfo.type; - - type->property_setget[p_pinfo.name]=psg; - + psg.setter = p_setter; + psg.getter = p_getter; + psg._setptr = mb_set; + psg._getptr = mb_get; + psg.index = p_index; + psg.type = p_pinfo.type; + + type->property_setget[p_pinfo.name] = psg; } - -void ClassDB::get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance,const Object *p_validator) { +void ClassDB::get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance, const Object *p_validator) { OBJTYPE_RLOCK; - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { - - for(List<PropertyInfo>::Element *E=check->property_list.front();E;E=E->next()) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { + for (List<PropertyInfo>::Element *E = check->property_list.front(); E; E = E->next()) { if (p_validator) { PropertyInfo pi = E->get(); @@ -877,266 +832,253 @@ void ClassDB::get_property_list(StringName p_class, List<PropertyInfo> *p_list, } if (p_no_inheritance) - return ; - check=check->inherits_ptr; + return; + check = check->inherits_ptr; } - } -bool ClassDB::set_property(Object* p_object,const StringName& p_property, const Variant& p_value,bool *r_valid) { - +bool ClassDB::set_property(Object *p_object, const StringName &p_property, const Variant &p_value, bool *r_valid) { - - ClassInfo *type=classes.getptr(p_object->get_class_name()); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_object->get_class_name()); + ClassInfo *check = type; + while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (!psg->setter) { if (r_valid) - *r_valid=false; + *r_valid = false; return true; //return true but do nothing } Variant::CallError ce; - if (psg->index>=0) { - Variant index=psg->index; - const Variant* arg[2]={&index,&p_value}; + if (psg->index >= 0) { + Variant index = psg->index; + const Variant *arg[2] = { &index, &p_value }; //p_object->call(psg->setter,arg,2,ce); if (psg->_setptr) { - psg->_setptr->call(p_object,arg,2,ce); + psg->_setptr->call(p_object, arg, 2, ce); } else { - p_object->call(psg->setter,arg,2,ce); + p_object->call(psg->setter, arg, 2, ce); } - } else { - const Variant* arg[1]={&p_value}; + const Variant *arg[1] = { &p_value }; if (psg->_setptr) { - psg->_setptr->call(p_object,arg,1,ce); + psg->_setptr->call(p_object, arg, 1, ce); } else { - p_object->call(psg->setter,arg,1,ce); + p_object->call(psg->setter, arg, 1, ce); } } if (r_valid) - *r_valid=ce.error==Variant::CallError::CALL_OK; + *r_valid = ce.error == Variant::CallError::CALL_OK; return true; } - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; } -bool ClassDB::get_property(Object* p_object,const StringName& p_property, Variant& r_value) { +bool ClassDB::get_property(Object *p_object, const StringName &p_property, Variant &r_value) { - ClassInfo *type=classes.getptr(p_object->get_class_name()); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_object->get_class_name()); + ClassInfo *check = type; + while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (!psg->getter) return true; //return true but do nothing - if (psg->index>=0) { - Variant index=psg->index; - const Variant* arg[1]={&index}; + if (psg->index >= 0) { + Variant index = psg->index; + const Variant *arg[1] = { &index }; Variant::CallError ce; - r_value = p_object->call(psg->getter,arg,1,ce); + r_value = p_object->call(psg->getter, arg, 1, ce); } else { Variant::CallError ce; if (psg->_getptr) { - r_value = psg->_getptr->call(p_object,NULL,0,ce); + r_value = psg->_getptr->call(p_object, NULL, 0, ce); } else { - r_value = p_object->call(psg->getter,NULL,0,ce); + r_value = p_object->call(psg->getter, NULL, 0, ce); } } return true; } - const int *c =check->constant_map.getptr(p_property); + const int *c = check->constant_map.getptr(p_property); if (c) { - r_value=*c; + r_value = *c; return true; } //if (check->constant_map.fin) - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; } -Variant::Type ClassDB::get_property_type(const StringName& p_class, const StringName& p_property,bool *r_is_valid) { +Variant::Type ClassDB::get_property_type(const StringName &p_class, const StringName &p_property, bool *r_is_valid) { - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (r_is_valid) - *r_is_valid=true; + *r_is_valid = true; return psg->type; } - check=check->inherits_ptr; + check = check->inherits_ptr; } if (r_is_valid) - *r_is_valid=false; + *r_is_valid = false; return Variant::NIL; - } -StringName ClassDB::get_property_setter(StringName p_class,const StringName p_property) { +StringName ClassDB::get_property_setter(StringName p_class, const StringName p_property) { - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { return psg->setter; } - check=check->inherits_ptr; + check = check->inherits_ptr; } return StringName(); } -StringName ClassDB::get_property_getter(StringName p_class,const StringName p_property) { +StringName ClassDB::get_property_getter(StringName p_class, const StringName p_property) { - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { return psg->getter; } - check=check->inherits_ptr; + check = check->inherits_ptr; } return StringName(); } -bool ClassDB::has_property(const StringName& p_class, const StringName& p_property, bool p_no_inheritance) { - +bool ClassDB::has_property(const StringName &p_class, const StringName &p_property, bool p_no_inheritance) { - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { if (check->property_setget.has(p_property)) return true; if (p_no_inheritance) break; - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; } -void ClassDB::set_method_flags(StringName p_class,StringName p_method,int p_flags) { +void ClassDB::set_method_flags(StringName p_class, StringName p_method, int p_flags) { OBJTYPE_WLOCK; - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; ERR_FAIL_COND(!check); ERR_FAIL_COND(!check->method_map.has(p_method)); check->method_map[p_method]->set_hint_flags(p_flags); - - } -bool ClassDB::has_method(StringName p_class,StringName p_method,bool p_no_inheritance) { +bool ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inheritance) { - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { if (check->method_map.has(p_method)) return true; if (p_no_inheritance) return false; - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; - } -bool ClassDB::get_setter_and_type_for_property(const StringName& p_class, const StringName& p_prop, StringName& r_class, StringName& r_setter) { +bool ClassDB::get_setter_and_type_for_property(const StringName &p_class, const StringName &p_prop, StringName &r_class, StringName &r_setter) { - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { if (check->property_setget.has(p_prop)) { - r_class=check->name; - r_setter=check->property_setget[p_prop].setter; + r_class = check->name; + r_setter = check->property_setget[p_prop].setter; return true; } - check=check->inherits_ptr; + check = check->inherits_ptr; } return false; - } #ifdef DEBUG_METHODS_ENABLED -MethodBind* ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) { - StringName mdname=method_name.name; +MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) { + StringName mdname = method_name.name; #else -MethodBind* ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const char *method_name, const Variant **p_defs, int p_defcount) { - StringName mdname=StaticCString::create(method_name); +MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount) { + StringName mdname = StaticCString::create(method_name); #endif - StringName rettype; - if (mdname.operator String().find(":")!=-1) { - rettype = mdname.operator String().get_slice(":",1); - mdname = mdname.operator String().get_slice(":",0); + if (mdname.operator String().find(":") != -1) { + rettype = mdname.operator String().get_slice(":", 1); + mdname = mdname.operator String().get_slice(":", 0); } - OBJTYPE_WLOCK; - ERR_FAIL_COND_V(!p_bind,NULL); + ERR_FAIL_COND_V(!p_bind, NULL); p_bind->set_name(mdname); - String instance_type=p_bind->get_instance_class(); + String instance_type = p_bind->get_instance_class(); #ifdef DEBUG_ENABLED - if (has_method(instance_type,mdname)) { - ERR_EXPLAIN("Class "+String(instance_type)+" already has a method "+String(mdname)); + if (has_method(instance_type, mdname)) { + ERR_EXPLAIN("Class " + String(instance_type) + " already has a method " + String(mdname)); ERR_FAIL_V(NULL); } #endif - - ClassInfo *type=classes.getptr(instance_type); + ClassInfo *type = classes.getptr(instance_type); if (!type) { - ERR_PRINTS("Couldn't bind method '"+mdname+"' for instance: "+instance_type); + ERR_PRINTS("Couldn't bind method '" + mdname + "' for instance: " + instance_type); memdelete(p_bind); - ERR_FAIL_COND_V(!type,NULL); + ERR_FAIL_COND_V(!type, NULL); } if (type->method_map.has(mdname)) { memdelete(p_bind); // overloading not supported - ERR_EXPLAIN("Method already bound: "+instance_type+"::"+mdname); + ERR_EXPLAIN("Method already bound: " + instance_type + "::" + mdname); ERR_FAIL_V(NULL); } #ifdef DEBUG_METHODS_ENABLED @@ -1144,87 +1086,83 @@ MethodBind* ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const p_bind->set_return_type(rettype); type->method_order.push_back(mdname); #endif - type->method_map[mdname]=p_bind; - + type->method_map[mdname] = p_bind; Vector<Variant> defvals; defvals.resize(p_defcount); - for(int i=0;i<p_defcount;i++) { + for (int i = 0; i < p_defcount; i++) { - defvals[i]=*p_defs[p_defcount-i-1]; + defvals[i] = *p_defs[p_defcount - i - 1]; } p_bind->set_default_arguments(defvals); p_bind->set_hint_flags(p_flags); return p_bind; - } -void ClassDB::add_virtual_method(const StringName& p_class, const MethodInfo& p_method , bool p_virtual) { +void ClassDB::add_virtual_method(const StringName &p_class, const MethodInfo &p_method, bool p_virtual) { ERR_FAIL_COND(!classes.has(p_class)); OBJTYPE_WLOCK; #ifdef DEBUG_METHODS_ENABLED - MethodInfo mi=p_method; + MethodInfo mi = p_method; if (p_virtual) - mi.flags|=METHOD_FLAG_VIRTUAL; + mi.flags |= METHOD_FLAG_VIRTUAL; classes[p_class].virtual_methods.push_back(mi); #endif - } -void ClassDB::get_virtual_methods(const StringName& p_class, List<MethodInfo> * p_methods , bool p_no_inheritance) { +void ClassDB::get_virtual_methods(const StringName &p_class, List<MethodInfo> *p_methods, bool p_no_inheritance) { ERR_FAIL_COND(!classes.has(p_class)); #ifdef DEBUG_METHODS_ENABLED - ClassInfo *type=classes.getptr(p_class); - ClassInfo *check=type; - while(check) { + ClassInfo *type = classes.getptr(p_class); + ClassInfo *check = type; + while (check) { - for(List<MethodInfo>::Element *E=check->virtual_methods.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = check->virtual_methods.front(); E; E = E->next()) { p_methods->push_back(E->get()); } if (p_no_inheritance) return; - check=check->inherits_ptr; + check = check->inherits_ptr; } #endif - } -void ClassDB::set_class_enabled(StringName p_class,bool p_enable) { +void ClassDB::set_class_enabled(StringName p_class, bool p_enable) { OBJTYPE_WLOCK; ERR_FAIL_COND(!classes.has(p_class)); - classes[p_class].disabled=!p_enable; + classes[p_class].disabled = !p_enable; } bool ClassDB::is_class_enabled(StringName p_class) { OBJTYPE_RLOCK; - ClassInfo *ti=classes.getptr(p_class); + ClassInfo *ti = classes.getptr(p_class); if (!ti || !ti->creation_func) { if (compat_classes.has(p_class)) { - ti=classes.getptr(compat_classes[p_class]); + ti = classes.getptr(compat_classes[p_class]); } } - ERR_FAIL_COND_V(!ti,false); + ERR_FAIL_COND_V(!ti, false); return !ti->disabled; } -StringName ClassDB::get_category(const StringName& p_node) { +StringName ClassDB::get_category(const StringName &p_node) { - ERR_FAIL_COND_V(!classes.has(p_node),StringName()); + ERR_FAIL_COND_V(!classes.has(p_node), StringName()); #ifdef DEBUG_ENABLED return classes[p_node].category; #else @@ -1232,37 +1170,36 @@ StringName ClassDB::get_category(const StringName& p_node) { #endif } -void ClassDB::add_resource_base_extension(const StringName& p_extension,const StringName& p_class) { +void ClassDB::add_resource_base_extension(const StringName &p_extension, const StringName &p_class) { if (resource_base_extensions.has(p_extension)) return; - resource_base_extensions[p_extension]=p_class; + resource_base_extensions[p_extension] = p_class; } void ClassDB::get_resource_base_extensions(List<String> *p_extensions) { - const StringName *K=NULL; + const StringName *K = NULL; - while((K=resource_base_extensions.next(K))) { + while ((K = resource_base_extensions.next(K))) { p_extensions->push_back(*K); } } -void ClassDB::get_extensions_for_type(const StringName& p_class,List<String> *p_extensions) { +void ClassDB::get_extensions_for_type(const StringName &p_class, List<String> *p_extensions) { - const StringName *K=NULL; + const StringName *K = NULL; - while((K=resource_base_extensions.next(K))) { + while ((K = resource_base_extensions.next(K))) { StringName cmp = resource_base_extensions[*K]; - if (is_parent_class(p_class,cmp)) + if (is_parent_class(p_class, cmp)) p_extensions->push_back(*K); } } - -RWLock *ClassDB::lock=NULL; +RWLock *ClassDB::lock = NULL; void ClassDB::init() { @@ -1274,20 +1211,18 @@ void ClassDB::init() { void ClassDB::cleanup() { - - //OBJTYPE_LOCK; hah not here - const StringName *k=NULL; + const StringName *k = NULL; - while((k=classes.next(k))) { + while ((k = classes.next(k))) { - ClassInfo &ti=classes[*k]; + ClassInfo &ti = classes[*k]; - const StringName *m=NULL; - while((m=ti.method_map.next(m))) { + const StringName *m = NULL; + while ((m = ti.method_map.next(m))) { - memdelete( ti.method_map[*m] ); + memdelete(ti.method_map[*m]); } } classes.clear(); @@ -1298,7 +1233,6 @@ void ClassDB::cleanup() { memdelete(lock); #endif - } // diff --git a/core/class_db.h b/core/class_db.h index 6e02d0bf46..6966183cfa 100644 --- a/core/class_db.h +++ b/core/class_db.h @@ -29,8 +29,8 @@ #ifndef CLASS_DB_H #define CLASS_DB_H -#include "object.h" #include "method_bind.h" +#include "object.h" #include "print_string.h" /** @@ -44,26 +44,24 @@ struct ParamHint { String hint_text; Variant default_val; - ParamHint(const String& p_name="", PropertyHint p_hint=PROPERTY_HINT_NONE, const String& p_hint_text="",Variant p_default_val=Variant()) { + ParamHint(const String &p_name = "", PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_text = "", Variant p_default_val = Variant()) { - name=p_name; - hint=p_hint; - hint_text=p_hint_text; - default_val=p_default_val; + name = p_name; + hint = p_hint; + hint_text = p_hint_text; + default_val = p_default_val; } - }; struct ParamDef { bool used; Variant val; - _FORCE_INLINE_ ParamDef() { used=false; } - ParamDef(const Variant& p_variant); + _FORCE_INLINE_ ParamDef() { used = false; } + ParamDef(const Variant &p_variant); }; //#define DEFVAL( m_defval ) ParamDef(m_defval) -#define DEFVAL( m_defval ) (m_defval) - +#define DEFVAL(m_defval) (m_defval) //#define SIMPLE_METHODDEF @@ -71,27 +69,24 @@ struct ParamDef { struct MethodDefinition { - StringName name; Vector<StringName> args; MethodDefinition() {} - MethodDefinition(const char *p_name) { name=p_name; } - MethodDefinition(const StringName& p_name) { name=p_name; } + MethodDefinition(const char *p_name) { name = p_name; } + MethodDefinition(const StringName &p_name) { name = p_name; } }; - - -MethodDefinition D_METHOD(const char* p_name); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9); -MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9,const char *p_arg10); +MethodDefinition D_METHOD(const char *p_name); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9); +MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9, const char *p_arg10); #else @@ -99,7 +94,9 @@ MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_ar #ifdef NO_VARIADIC_MACROS -static _FORCE_INLINE_ const char* D_METHOD(const char* m_name, ...) { return m_name; } +static _FORCE_INLINE_ const char *D_METHOD(const char *m_name, ...) { + return m_name; +} #else @@ -118,6 +115,7 @@ public: API_EDITOR, API_NONE }; + public: struct PropertySetGet { @@ -133,9 +131,9 @@ public: APIType api; ClassInfo *inherits_ptr; - HashMap<StringName,MethodBind*,StringNameHasher> method_map; - HashMap<StringName,int,StringNameHasher> constant_map; - HashMap<StringName,MethodInfo,StringNameHasher> signal_map; + HashMap<StringName, MethodBind *, StringNameHasher> method_map; + HashMap<StringName, int, StringNameHasher> constant_map; + HashMap<StringName, MethodInfo, StringNameHasher> signal_map; List<PropertyInfo> property_list; #ifdef DEBUG_METHODS_ENABLED List<StringName> constant_order; @@ -143,44 +141,42 @@ public: List<MethodInfo> virtual_methods; StringName category; #endif - HashMap<StringName,PropertySetGet,StringNameHasher> property_setget; - + HashMap<StringName, PropertySetGet, StringNameHasher> property_setget; StringName inherits; StringName name; bool disabled; - Object* (*creation_func)(); + Object *(*creation_func)(); ClassInfo(); ~ClassInfo(); }; - template<class T> + template <class T> static Object *creator() { - return memnew( T ); + return memnew(T); } static RWLock *lock; - static HashMap<StringName,ClassInfo,StringNameHasher> classes; - static HashMap<StringName,StringName,StringNameHasher> resource_base_extensions; - static HashMap<StringName,StringName,StringNameHasher> compat_classes; + static HashMap<StringName, ClassInfo, StringNameHasher> classes; + static HashMap<StringName, StringName, StringNameHasher> resource_base_extensions; + static HashMap<StringName, StringName, StringNameHasher> compat_classes; #ifdef DEBUG_METHODS_ENABLED - static MethodBind* bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const MethodDefinition &method_name, const Variant **p_defs, int p_defcount); + static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount); #else - static MethodBind* bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const char *method_name, const Variant **p_defs, int p_defcount); + static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount); #endif - static APIType current_api; - static void _add_class2(const StringName& p_class, const StringName& p_inherits); -public: + static void _add_class2(const StringName &p_class, const StringName &p_inherits); +public: // DO NOT USE THIS!!!!!! NEEDS TO BE PUBLIC BUT DO NOT USE NO MATTER WHAT!!! - template<class T> + template <class T> static void _add_class() { - _add_class2(T::get_class_static(),T::get_parent_class_static()); + _add_class2(T::get_class_static(), T::get_parent_class_static()); #if 0 GLOBAL_LOCK_FUNCTION; @@ -204,18 +200,18 @@ public: #endif } - template<class T> + template <class T> static void register_class() { GLOBAL_LOCK_FUNCTION; T::initialize_class(); - ClassInfo *t=classes.getptr(T::get_class_static()); + ClassInfo *t = classes.getptr(T::get_class_static()); ERR_FAIL_COND(!t); - t->creation_func=&creator<T>; + t->creation_func = &creator<T>; T::register_custom_data_to_otdb(); } - template<class T> + template <class T> static void register_virtual_class() { GLOBAL_LOCK_FUNCTION; @@ -223,29 +219,29 @@ public: //nothing } - template<class T> - static Object* _create_ptr_func() { + template <class T> + static Object *_create_ptr_func() { return T::create(); } - template<class T> + template <class T> static void register_custom_instance_class() { GLOBAL_LOCK_FUNCTION; T::initialize_class(); - ClassInfo *t=classes.getptr(T::get_class_static()); + ClassInfo *t = classes.getptr(T::get_class_static()); ERR_FAIL_COND(!t); - t->creation_func=&_create_ptr_func<T>; + t->creation_func = &_create_ptr_func<T>; T::register_custom_data_to_otdb(); } - static void get_class_list( List<StringName> *p_classes); - static void get_inheriters_from_class( const StringName& p_class,List<StringName> *p_classes); - static StringName get_parent_class_nocheck(const StringName& p_class); - static StringName get_parent_class(const StringName& p_class); + static void get_class_list(List<StringName> *p_classes); + static void get_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes); + static StringName get_parent_class_nocheck(const StringName &p_class); + static StringName get_parent_class(const StringName &p_class); static bool class_exists(const StringName &p_class); - static bool is_parent_class(const StringName &p_class,const StringName& p_inherits); + static bool is_parent_class(const StringName &p_class, const StringName &p_inherits); static bool can_instance(const StringName &p_class); static Object *instance(const StringName &p_class); static APIType get_api_type(const StringName &p_class); @@ -307,9 +303,11 @@ public: Vector<Variant> defvals; -#define PARSE_DEFVAL(m_defval)\ - if (d##m_defval.used) defvals.insert(0,d##m_defval.val);\ - else goto set_defvals; +#define PARSE_DEFVAL(m_defval) \ + if (d##m_defval.used) \ + defvals.insert(0, d##m_defval.val); \ + else \ + goto set_defvals; PARSE_DEFVAL(1); @@ -346,67 +344,66 @@ public: } #endif - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method) { MethodBind *bind = create_method_bind(p_method); - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,NULL,0); //use static function, much smaller binary usage + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, NULL, 0); //use static function, much smaller binary usage } - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1) { MethodBind *bind = create_method_bind(p_method); - const Variant* ptr[1]={&p_def1}; + const Variant *ptr[1] = { &p_def1 }; - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,1); + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 1); } - - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2) { MethodBind *bind = create_method_bind(p_method); - const Variant* ptr[2]={&p_def1,&p_def2}; + const Variant *ptr[2] = { &p_def1, &p_def2 }; - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,2); + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 2); } - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3) { MethodBind *bind = create_method_bind(p_method); - const Variant* ptr[3]={&p_def1,&p_def2,&p_def3}; + const Variant *ptr[3] = { &p_def1, &p_def2, &p_def3 }; - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,3); + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 3); } - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3,const Variant& p_def4) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3, const Variant &p_def4) { MethodBind *bind = create_method_bind(p_method); - const Variant* ptr[4]={&p_def1,&p_def2,&p_def3,&p_def4}; + const Variant *ptr[4] = { &p_def1, &p_def2, &p_def3, &p_def4 }; - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,4); + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 4); } - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3,const Variant& p_def4,const Variant& p_def5) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3, const Variant &p_def4, const Variant &p_def5) { MethodBind *bind = create_method_bind(p_method); - const Variant* ptr[5]={&p_def1,&p_def2,&p_def3,&p_def4,&p_def5}; + const Variant *ptr[5] = { &p_def1, &p_def2, &p_def3, &p_def4, &p_def5 }; - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,5); + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 5); } - template<class N, class M> - static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3,const Variant& p_def4,const Variant& p_def5,const Variant& p_def6) { + template <class N, class M> + static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3, const Variant &p_def4, const Variant &p_def5, const Variant &p_def6) { MethodBind *bind = create_method_bind(p_method); - const Variant* ptr[6]={&p_def1,&p_def2,&p_def3,&p_def4,&p_def5,&p_def6}; + const Variant *ptr[6] = { &p_def1, &p_def2, &p_def3, &p_def4, &p_def5, &p_def6 }; - return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,6); + return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 6); } #if 0 @@ -429,108 +426,99 @@ public: #endif #endif - template<class M> - static MethodBind* bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method,const MethodInfo& p_info=MethodInfo(),const Vector<Variant>& p_default_args=Vector<Variant>()) { + template <class M> + static MethodBind *bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method, const MethodInfo &p_info = MethodInfo(), const Vector<Variant> &p_default_args = Vector<Variant>()) { GLOBAL_LOCK_FUNCTION; - - - MethodBind *bind = create_vararg_method_bind(p_method,p_info); - ERR_FAIL_COND_V(!bind,NULL); + MethodBind *bind = create_vararg_method_bind(p_method, p_info); + ERR_FAIL_COND_V(!bind, NULL); String rettype; - if (p_name.operator String().find(":")!=-1) { - rettype = p_name.operator String().get_slice(":",1); - p_name = p_name.operator String().get_slice(":",0); + if (p_name.operator String().find(":") != -1) { + rettype = p_name.operator String().get_slice(":", 1); + p_name = p_name.operator String().get_slice(":", 0); } bind->set_name(p_name); bind->set_default_arguments(p_default_args); - String instance_type=bind->get_instance_class(); + String instance_type = bind->get_instance_class(); - ClassInfo *type=classes.getptr(instance_type); + ClassInfo *type = classes.getptr(instance_type); if (!type) { memdelete(bind); - ERR_FAIL_COND_V(!type,NULL); + ERR_FAIL_COND_V(!type, NULL); } if (type->method_map.has(p_name)) { memdelete(bind); // overloading not supported - ERR_EXPLAIN("Method already bound: "+instance_type+"::"+p_name); + ERR_EXPLAIN("Method already bound: " + instance_type + "::" + p_name); ERR_FAIL_V(NULL); } - type->method_map[p_name]=bind; + type->method_map[p_name] = bind; #ifdef DEBUG_METHODS_ENABLED if (!rettype.empty()) bind->set_return_type(rettype); type->method_order.push_back(p_name); #endif - return bind; - } - - static void add_signal(StringName p_class,const MethodInfo& p_signal); - static bool has_signal(StringName p_class,StringName p_signal); - static bool get_signal(StringName p_class,StringName p_signal,MethodInfo *r_signal); - static void get_signal_list(StringName p_class,List<MethodInfo> *p_signals,bool p_no_inheritance=false); - - static void add_property_group(StringName p_class,const String& p_name,const String& p_prefix=""); - static void add_property(StringName p_class,const PropertyInfo& p_pinfo, const StringName& p_setter, const StringName& p_getter, int p_index=-1); - static void get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance=false, const Object *p_validator=NULL); - static bool set_property(Object* p_object, const StringName& p_property, const Variant& p_value, bool *r_valid=NULL); - static bool get_property(Object* p_object,const StringName& p_property, Variant& r_value); - static bool has_property(const StringName& p_class,const StringName& p_property,bool p_no_inheritance=false); - static Variant::Type get_property_type(const StringName& p_class, const StringName& p_property,bool *r_is_valid=NULL); - static StringName get_property_setter(StringName p_class,const StringName p_property); - static StringName get_property_getter(StringName p_class,const StringName p_property); - - - - static bool has_method(StringName p_class,StringName p_method,bool p_no_inheritance=false); - static void set_method_flags(StringName p_class,StringName p_method,int p_flags); - - - static void get_method_list(StringName p_class,List<MethodInfo> *p_methods,bool p_no_inheritance=false); + static void add_signal(StringName p_class, const MethodInfo &p_signal); + static bool has_signal(StringName p_class, StringName p_signal); + static bool get_signal(StringName p_class, StringName p_signal, MethodInfo *r_signal); + static void get_signal_list(StringName p_class, List<MethodInfo> *p_signals, bool p_no_inheritance = false); + + static void add_property_group(StringName p_class, const String &p_name, const String &p_prefix = ""); + static void add_property(StringName p_class, const PropertyInfo &p_pinfo, const StringName &p_setter, const StringName &p_getter, int p_index = -1); + static void get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance = false, const Object *p_validator = NULL); + static bool set_property(Object *p_object, const StringName &p_property, const Variant &p_value, bool *r_valid = NULL); + static bool get_property(Object *p_object, const StringName &p_property, Variant &r_value); + static bool has_property(const StringName &p_class, const StringName &p_property, bool p_no_inheritance = false); + static Variant::Type get_property_type(const StringName &p_class, const StringName &p_property, bool *r_is_valid = NULL); + static StringName get_property_setter(StringName p_class, const StringName p_property); + static StringName get_property_getter(StringName p_class, const StringName p_property); + + static bool has_method(StringName p_class, StringName p_method, bool p_no_inheritance = false); + static void set_method_flags(StringName p_class, StringName p_method, int p_flags); + + static void get_method_list(StringName p_class, List<MethodInfo> *p_methods, bool p_no_inheritance = false); static MethodBind *get_method(StringName p_class, StringName p_name); - static void add_virtual_method(const StringName& p_class,const MethodInfo& p_method,bool p_virtual=true ); - static void get_virtual_methods(const StringName& p_class,List<MethodInfo> * p_methods,bool p_no_inheritance=false ); + static void add_virtual_method(const StringName &p_class, const MethodInfo &p_method, bool p_virtual = true); + static void get_virtual_methods(const StringName &p_class, List<MethodInfo> *p_methods, bool p_no_inheritance = false); - static void bind_integer_constant(const StringName& p_class, const StringName &p_name, int p_constant); - static void get_integer_constant_list(const StringName& p_class, List<String> *p_constants, bool p_no_inheritance=false); - static int get_integer_constant(const StringName& p_class, const StringName &p_name, bool *p_success=NULL); - static StringName get_category(const StringName& p_node); + static void bind_integer_constant(const StringName &p_class, const StringName &p_name, int p_constant); + static void get_integer_constant_list(const StringName &p_class, List<String> *p_constants, bool p_no_inheritance = false); + static int get_integer_constant(const StringName &p_class, const StringName &p_name, bool *p_success = NULL); + static StringName get_category(const StringName &p_node); - static bool get_setter_and_type_for_property(const StringName& p_class, const StringName& p_prop, StringName& r_class, StringName& r_setter); + static bool get_setter_and_type_for_property(const StringName &p_class, const StringName &p_prop, StringName &r_class, StringName &r_setter); - static void set_class_enabled(StringName p_class,bool p_enable); + static void set_class_enabled(StringName p_class, bool p_enable); static bool is_class_enabled(StringName p_class); - static void add_resource_base_extension(const StringName& p_extension,const StringName& p_class); + static void add_resource_base_extension(const StringName &p_extension, const StringName &p_class); static void get_resource_base_extensions(List<String> *p_extensions); - static void get_extensions_for_type(const StringName& p_class,List<String> *p_extensions); + static void get_extensions_for_type(const StringName &p_class, List<String> *p_extensions); - static void add_compatibility_class(const StringName& p_class,const StringName& p_fallback); + static void add_compatibility_class(const StringName &p_class, const StringName &p_fallback); static void init(); static void set_current_api(APIType p_api); static void cleanup(); }; - -#define BIND_CONSTANT(m_constant)\ - ClassDB::bind_integer_constant( get_class_static() , #m_constant, m_constant); +#define BIND_CONSTANT(m_constant) \ + ClassDB::bind_integer_constant(get_class_static(), #m_constant, m_constant); #ifdef TOOLS_ENABLED -#define BIND_VMETHOD(m_method)\ - ClassDB::add_virtual_method( get_class_static() , m_method ); +#define BIND_VMETHOD(m_method) \ + ClassDB::add_virtual_method(get_class_static(), m_method); #else @@ -538,6 +526,4 @@ public: #endif - - #endif // CLASS_DB_H diff --git a/core/color.cpp b/core/color.cpp index 80a98da252..f052ddea8a 100644 --- a/core/color.cpp +++ b/core/color.cpp @@ -28,82 +28,80 @@ /*************************************************************************/ #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; } @@ -111,24 +109,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; @@ -164,170 +162,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) { @@ -340,12 +334,12 @@ Color Color::named(const String &p_name) { name = name.replace("'", ""); name = name.replace(".", ""); name = name.to_lower(); - - const Map<String, Color>::Element* color = _named_colors.find(name); - if(color) { + + const Map<String, Color>::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()); } } @@ -353,48 +347,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 50a6761340..2339cd6cd7 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 <reduzio@gmail.com> */ @@ -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 (a<p_color.a); + if (r == p_color.r) { + if (g == p_color.g) { + if (b == p_color.b) { + return (a < p_color.a); } else - return (b<p_color.b); + return (b < p_color.b); } else - return g<p_color.g; + return g < p_color.g; } else - return r<p_color.r; - + return r < p_color.r; } #endif diff --git a/core/command_queue_mt.cpp b/core/command_queue_mt.cpp index 6d50ed8d9a..c66177261b 100644 --- a/core/command_queue_mt.cpp +++ b/core/command_queue_mt.cpp @@ -48,22 +48,22 @@ void CommandQueueMT::wait_for_flush() { OS::get_singleton()->delay_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<SYNC_SEMAPHORES;i++) { + for (int i = 0; i < SYNC_SEMAPHORES; i++) { if (!sync_sems[i].in_use) { - sync_sems[i].in_use=true; - idx=i; + sync_sems[i].in_use = true; + idx = i; break; } } - if (idx==-1) { + if (idx == -1) { wait_for_flush(); } else { break; @@ -73,36 +73,30 @@ CommandQueueMT::SyncSemaphore* CommandQueueMT::_alloc_sync_sem() { return &sync_sems[idx]; } +CommandQueueMT::CommandQueueMT(bool p_sync) { -CommandQueueMT::CommandQueueMT(bool p_sync){ - - read_ptr=0; - write_ptr=0; + read_ptr = 0; + write_ptr = 0; mutex = Mutex::create(); - for(int i=0;i<SYNC_SEMAPHORES;i++) { - - sync_sems[i].sem=Semaphore::create(); - sync_sems[i].in_use=false; - + for (int i = 0; i < SYNC_SEMAPHORES; i++) { + sync_sems[i].sem = Semaphore::create(); + sync_sems[i].in_use = false; } if (p_sync) sync = Semaphore::create(); else - sync=NULL; + sync = NULL; } - CommandQueueMT::~CommandQueueMT() { if (sync) memdelete(sync); memdelete(mutex); - for(int i=0;i<SYNC_SEMAPHORES;i++) { + for (int i = 0; i < SYNC_SEMAPHORES; i++) { memdelete(sync_sems[i].sem); } } - - diff --git a/core/command_queue_mt.h b/core/command_queue_mt.h index 3975df7658..3a859c809c 100644 --- a/core/command_queue_mt.h +++ b/core/command_queue_mt.h @@ -29,11 +29,11 @@ #ifndef COMMAND_QUEUE_MT_H #define COMMAND_QUEUE_MT_H -#include "typedefs.h" -#include "os/semaphore.h" -#include "os/mutex.h" #include "os/memory.h" +#include "os/mutex.h" +#include "os/semaphore.h" #include "simple_type.h" +#include "typedefs.h" /** @author Juan Linietsky <reduzio@gmail.com> */ @@ -48,69 +48,69 @@ class CommandQueueMT { struct CommandBase { - virtual void call()=0; - virtual ~CommandBase() {}; + virtual void call() = 0; + virtual ~CommandBase(){}; }; - template<class T,class M> + template <class T, class M> struct Command0 : public CommandBase { - T*instance; + T *instance; M method; virtual void call() { (instance->*method)(); } }; - template<class T,class M,class P1> + template <class T, class M, class P1> struct Command1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; virtual void call() { (instance->*method)(p1); } }; - template<class T,class M,class P1,class P2> + template <class T, class M, class P1, class P2> struct Command2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; - virtual void call() { (instance->*method)(p1,p2); } + virtual void call() { (instance->*method)(p1, p2); } }; - template<class T,class M,class P1,class P2,class P3> + template <class T, class M, class P1, class P2, class P3> struct Command3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; typename GetSimpleTypeT<P3>::type_t p3; - virtual void call() { (instance->*method)(p1,p2,p3); } + virtual void call() { (instance->*method)(p1, p2, p3); } }; - template<class T,class M,class P1,class P2,class P3,class P4> + template <class T, class M, class P1, class P2, class P3, class P4> struct Command4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; typename GetSimpleTypeT<P3>::type_t p3; typename GetSimpleTypeT<P4>::type_t p4; - virtual void call() { (instance->*method)(p1,p2,p3,p4); } + virtual void call() { (instance->*method)(p1, p2, p3, p4); } }; - template<class T,class M,class P1,class P2,class P3,class P4,class P5> + template <class T, class M, class P1, class P2, class P3, class P4, class P5> struct Command5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -118,13 +118,13 @@ class CommandQueueMT { typename GetSimpleTypeT<P4>::type_t p4; typename GetSimpleTypeT<P5>::type_t p5; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5); } + virtual void call() { (instance->*method)(p1, p2, p3, p4, p5); } }; - template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6> struct Command6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -133,13 +133,13 @@ class CommandQueueMT { typename GetSimpleTypeT<P5>::type_t p5; typename GetSimpleTypeT<P6>::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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7> struct Command7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -149,13 +149,13 @@ class CommandQueueMT { typename GetSimpleTypeT<P6>::type_t p6; typename GetSimpleTypeT<P7>::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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class P8> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> struct Command8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -166,96 +166,120 @@ class CommandQueueMT { typename GetSimpleTypeT<P7>::type_t p7; typename GetSimpleTypeT<P8>::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<class T,class M,class R> + template <class T, class M, class R> 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<class T,class M,class P1,class R> + template <class T, class M, class P1, class R> struct CommandRet1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::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<class T,class M,class P1,class P2,class R> + template <class T, class M, class P1, class P2, class R> struct CommandRet2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::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<class T,class M,class P1,class P2,class P3,class R> + template <class T, class M, class P1, class P2, class P3, class R> struct CommandRet3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; typename GetSimpleTypeT<P3>::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<class T,class M,class P1,class P2,class P3,class P4,class R> + template <class T, class M, class P1, class P2, class P3, class P4, class R> struct CommandRet4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; typename GetSimpleTypeT<P3>::type_t p3; typename GetSimpleTypeT<P4>::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<class T,class M,class P1,class P2,class P3,class P4,class P5,class R> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class R> struct CommandRet5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; typename GetSimpleTypeT<P3>::type_t p3; typename GetSimpleTypeT<P4>::type_t p4; typename GetSimpleTypeT<P5>::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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class R> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class R> struct CommandRet6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -263,16 +287,20 @@ class CommandQueueMT { typename GetSimpleTypeT<P4>::type_t p4; typename GetSimpleTypeT<P5>::type_t p5; typename GetSimpleTypeT<P6>::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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class R> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class R> struct CommandRet7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -281,16 +309,20 @@ class CommandQueueMT { typename GetSimpleTypeT<P5>::type_t p5; typename GetSimpleTypeT<P6>::type_t p6; typename GetSimpleTypeT<P7>::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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class P8,class R> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class R> struct CommandRet8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -300,56 +332,72 @@ class CommandQueueMT { typename GetSimpleTypeT<P6>::type_t p6; typename GetSimpleTypeT<P7>::type_t p7; typename GetSimpleTypeT<P8>::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<class T,class M> + template <class T, class M> 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<class T,class M,class P1> + template <class T, class M, class P1> struct CommandSync1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::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<class T,class M,class P1,class P2> + template <class T, class M, class P1, class P2> struct CommandSync2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::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<class T,class M,class P1,class P2,class P3> + template <class T, class M, class P1, class P2, class P3> struct CommandSync3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -357,13 +405,17 @@ 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<class T,class M,class P1,class P2,class P3,class P4> + template <class T, class M, class P1, class P2, class P3, class P4> struct CommandSync4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -372,13 +424,17 @@ 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<class T,class M,class P1,class P2,class P3,class P4,class P5> + template <class T, class M, class P1, class P2, class P3, class P4, class P5> struct CommandSync5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -388,13 +444,17 @@ 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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6> struct CommandSync6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -405,13 +465,17 @@ 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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7> struct CommandSync7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -423,13 +487,17 @@ 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<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class P8> + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> struct CommandSync8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT<P1>::type_t p1; typename GetSimpleTypeT<P2>::type_t p2; @@ -442,18 +510,21 @@ 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 +532,247 @@ class CommandQueueMT { Mutex *mutex; Semaphore *sync; - - template<class T> - T* allocate() { + template <class T> + 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<class T> - T* allocate_and_lock() { + template <class T> + T *allocate_and_lock() { lock(); - T* ret; + T *ret; - while ( (ret=allocate<T>())==NULL ) { + while ((ret = allocate<T>()) == 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<CommandBase*>( &command_mem[read_ptr] ); + CommandBase *cmd = reinterpret_cast<CommandBase *>(&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<class T, class M> - void push( T * p_instance, M p_method ) { + template <class T, class M> + void push(T *p_instance, M p_method) { - Command0<T,M> * cmd = allocate_and_lock< Command0<T,M> >(); + Command0<T, M> *cmd = allocate_and_lock<Command0<T, M> >(); - cmd->instance=p_instance; - cmd->method=p_method; + cmd->instance = p_instance; + cmd->method = p_method; unlock(); if (sync) sync->post(); } - template<class T, class M, class P1> - void push( T * p_instance, M p_method, P1 p1 ) { + template <class T, class M, class P1> + void push(T *p_instance, M p_method, P1 p1) { - Command1<T,M,P1> * cmd = allocate_and_lock< Command1<T,M,P1> >(); + Command1<T, M, P1> *cmd = allocate_and_lock<Command1<T, M, P1> >(); - 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<class T, class M, class P1, class P2> - void push( T * p_instance, M p_method, P1 p1, P2 p2 ) { + template <class T, class M, class P1, class P2> + void push(T *p_instance, M p_method, P1 p1, P2 p2) { - Command2<T,M,P1,P2> * cmd = allocate_and_lock< Command2<T,M,P1,P2> >(); + Command2<T, M, P1, P2> *cmd = allocate_and_lock<Command2<T, M, P1, P2> >(); - 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<class T, class M, class P1, class P2, class P3> - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) { + template <class T, class M, class P1, class P2, class P3> + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) { - Command3<T,M,P1,P2,P3> * cmd = allocate_and_lock< Command3<T,M,P1,P2,P3> >(); + Command3<T, M, P1, P2, P3> *cmd = allocate_and_lock<Command3<T, M, P1, P2, P3> >(); - 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<class T, class M, class P1, class P2, class P3, class P4> - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) { + template <class T, class M, class P1, class P2, class P3, class P4> + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) { - Command4<T,M,P1,P2,P3,P4> * cmd = allocate_and_lock< Command4<T,M,P1,P2,P3,P4> >(); + Command4<T, M, P1, P2, P3, P4> *cmd = allocate_and_lock<Command4<T, M, P1, P2, P3, P4> >(); - 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<class T, class M, class P1, class P2, class P3, class P4, class P5> - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) { + template <class T, class M, class P1, class P2, class P3, class P4, class P5> + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - Command5<T,M,P1,P2,P3,P4,P5> * cmd = allocate_and_lock< Command5<T,M,P1,P2,P3,P4,P5> >(); + Command5<T, M, P1, P2, P3, P4, P5> *cmd = allocate_and_lock<Command5<T, M, P1, P2, P3, P4, P5> >(); - 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<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6> - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) { + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6> + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - Command6<T,M,P1,P2,P3,P4,P5,P6> * cmd = allocate_and_lock< Command6<T,M,P1,P2,P3,P4,P5,P6> >(); + Command6<T, M, P1, P2, P3, P4, P5, P6> *cmd = allocate_and_lock<Command6<T, M, P1, P2, P3, P4, P5, 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; + 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<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7> - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7 ) { + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7> + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { - Command7<T,M,P1,P2,P3,P4,P5,P6,P7> * cmd = allocate_and_lock< Command7<T,M,P1,P2,P3,P4,P5,P6,P7> >(); + Command7<T, M, P1, P2, P3, P4, P5, P6, P7> *cmd = allocate_and_lock<Command7<T, M, P1, P2, P3, P4, P5, P6, 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; + 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<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7,class P8> - 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 <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> + 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<T,M,P1,P2,P3,P4,P5,P6,P7,P8> * cmd = allocate_and_lock< Command8<T,M,P1,P2,P3,P4,P5,P6,P7,P8> >(); + Command8<T, M, P1, P2, P3, P4, P5, P6, P7, P8> *cmd = allocate_and_lock<Command8<T, M, P1, P2, P3, P4, P5, P6, P7, 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; + 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 +780,16 @@ public: } /*** PUSH AND RET COMMANDS ***/ + template <class T, class M, class R> + void push_and_ret(T *p_instance, M p_method, R *r_ret) { - template<class T, class M,class R> - void push_and_ret( T * p_instance, M p_method, R* r_ret) { - - CommandRet0<T,M,R> * cmd = allocate_and_lock< CommandRet0<T,M,R> >(); + CommandRet0<T, M, R> *cmd = allocate_and_lock<CommandRet0<T, M, R> >(); - 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 +797,17 @@ public: ss->sem->wait(); } - template<class T, class M, class P1,class R> - void push_and_ret( T * p_instance, M p_method, P1 p1, R* r_ret) { + template <class T, class M, class P1, class R> + void push_and_ret(T *p_instance, M p_method, P1 p1, R *r_ret) { - CommandRet1<T,M,P1,R> * cmd = allocate_and_lock< CommandRet1<T,M,P1,R> >(); + CommandRet1<T, M, P1, R> *cmd = allocate_and_lock<CommandRet1<T, M, P1, R> >(); - 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 +815,18 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2,class R> - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, R* r_ret) { + template <class T, class M, class P1, class P2, class R> + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, R *r_ret) { - CommandRet2<T,M,P1,P2,R> * cmd = allocate_and_lock< CommandRet2<T,M,P1,P2,R> >(); + CommandRet2<T, M, P1, P2, R> *cmd = allocate_and_lock<CommandRet2<T, M, P1, P2, R> >(); - 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 +834,19 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3,class R> - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, R* r_ret ) { + template <class T, class M, class P1, class P2, class P3, class R> + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, R *r_ret) { - CommandRet3<T,M,P1,P2,P3,R> * cmd = allocate_and_lock< CommandRet3<T,M,P1,P2,P3,R> >(); + CommandRet3<T, M, P1, P2, P3, R> *cmd = allocate_and_lock<CommandRet3<T, M, P1, P2, P3, R> >(); - 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 +854,20 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4,class R> - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R* r_ret ) { + template <class T, class M, class P1, class P2, class P3, class P4, class R> + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R *r_ret) { - CommandRet4<T,M,P1,P2,P3,P4,R> * cmd = allocate_and_lock< CommandRet4<T,M,P1,P2,P3,P4,R> >(); + CommandRet4<T, M, P1, P2, P3, P4, R> *cmd = allocate_and_lock<CommandRet4<T, M, P1, P2, P3, P4, R> >(); - 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 +875,21 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5,class R> - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R* r_ret ) { + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class R> + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R *r_ret) { - CommandRet5<T,M,P1,P2,P3,P4,P5,R> * cmd = allocate_and_lock< CommandRet5<T,M,P1,P2,P3,P4,P5,R> >(); + CommandRet5<T, M, P1, P2, P3, P4, P5, R> *cmd = allocate_and_lock<CommandRet5<T, M, P1, P2, P3, P4, P5, R> >(); - 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 +897,22 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class R> - 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 <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class R> + 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<T,M,P1,P2,P3,P4,P5,P6,R> * cmd = allocate_and_lock< CommandRet6<T,M,P1,P2,P3,P4,P5,P6,R> >(); + CommandRet6<T, M, P1, P2, P3, P4, P5, P6, R> *cmd = allocate_and_lock<CommandRet6<T, M, P1, P2, P3, P4, P5, P6, R> >(); - 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 +920,23 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7,class R> - 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 <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class R> + 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<T,M,P1,P2,P3,P4,P5,P6,P7,R> * cmd = allocate_and_lock< CommandRet7<T,M,P1,P2,P3,P4,P5,P6,P7,R> >(); + CommandRet7<T, M, P1, P2, P3, P4, P5, P6, P7, R> *cmd = allocate_and_lock<CommandRet7<T, M, P1, P2, P3, P4, P5, P6, P7, R> >(); - 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 +944,24 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7,class P8,class R> - 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<T,M,P1,P2,P3,P4,P5,P6,P7,P8,R> * cmd = allocate_and_lock< CommandRet8<T,M,P1,P2,P3,P4,P5,P6,P7,P8,R> >(); - - 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; + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class R> + 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<T, M, P1, P2, P3, P4, P5, P6, P7, P8, R> *cmd = allocate_and_lock<CommandRet8<T, M, P1, P2, P3, P4, P5, P6, P7, P8, R> >(); + + 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 +969,16 @@ public: ss->sem->wait(); } + template <class T, class M> + void push_and_sync(T *p_instance, M p_method) { - template<class T, class M> - void push_and_sync( T * p_instance, M p_method) { + CommandSync0<T, M> *cmd = allocate_and_lock<CommandSync0<T, M> >(); - CommandSync0<T,M> * cmd = allocate_and_lock< CommandSync0<T,M> >(); + 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 +986,17 @@ public: ss->sem->wait(); } - template<class T, class M, class P1> - void push_and_sync( T * p_instance, M p_method, P1 p1) { + template <class T, class M, class P1> + void push_and_sync(T *p_instance, M p_method, P1 p1) { - CommandSync1<T,M,P1> * cmd = allocate_and_lock< CommandSync1<T,M,P1> >(); + CommandSync1<T, M, P1> *cmd = allocate_and_lock<CommandSync1<T, M, P1> >(); - 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 +1004,18 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2> - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2) { + template <class T, class M, class P1, class P2> + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2) { - CommandSync2<T,M,P1,P2> * cmd = allocate_and_lock< CommandSync2<T,M,P1,P2> >(); + CommandSync2<T, M, P1, P2> *cmd = allocate_and_lock<CommandSync2<T, M, P1, P2> >(); - 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 +1023,19 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3> - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) { + template <class T, class M, class P1, class P2, class P3> + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) { - CommandSync3<T,M,P1,P2,P3> * cmd = allocate_and_lock< CommandSync3<T,M,P1,P2,P3> >(); + CommandSync3<T, M, P1, P2, P3> *cmd = allocate_and_lock<CommandSync3<T, M, P1, P2, P3> >(); - 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 +1043,20 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4> - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) { + template <class T, class M, class P1, class P2, class P3, class P4> + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) { - CommandSync4<T,M,P1,P2,P3,P4> * cmd = allocate_and_lock< CommandSync4<T,M,P1,P2,P3,P4> >(); + CommandSync4<T, M, P1, P2, P3, P4> *cmd = allocate_and_lock<CommandSync4<T, M, P1, P2, P3, P4> >(); - 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 +1064,21 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5> - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) { + template <class T, class M, class P1, class P2, class P3, class P4, class P5> + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - CommandSync5<T,M,P1,P2,P3,P4,P5> * cmd = allocate_and_lock< CommandSync5<T,M,P1,P2,P3,P4,P5> >(); + CommandSync5<T, M, P1, P2, P3, P4, P5> *cmd = allocate_and_lock<CommandSync5<T, M, P1, P2, P3, P4, P5> >(); - 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 +1086,22 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6> - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) { + template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6> + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - CommandSync6<T,M,P1,P2,P3,P4,P5,P6> * cmd = allocate_and_lock< CommandSync6<T,M,P1,P2,P3,P4,P5,P6> >(); + CommandSync6<T, M, P1, P2, P3, P4, P5, P6> *cmd = allocate_and_lock<CommandSync6<T, M, P1, P2, P3, P4, P5, 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; + 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 +1109,23 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7> - 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 <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7> + 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<T,M,P1,P2,P3,P4,P5,P6,P7> * cmd = allocate_and_lock< CommandSync7<T,M,P1,P2,P3,P4,P5,P6,P7> >(); + CommandSync7<T, M, P1, P2, P3, P4, P5, P6, P7> *cmd = allocate_and_lock<CommandSync7<T, M, P1, P2, P3, P4, P5, P6, 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; + 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 +1133,24 @@ public: ss->sem->wait(); } - template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7,class P8> - 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 <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8> + 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<T,M,P1,P2,P3,P4,P5,P6,P7,P8> * cmd = allocate_and_lock< CommandSync8<T,M,P1,P2,P3,P4,P5,P6,P7,P8> >(); + CommandSync8<T, M, P1, P2, P3, P4, P5, P6, P7, P8> *cmd = allocate_and_lock<CommandSync8<T, M, P1, P2, P3, P4, P5, P6, P7, 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; + 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 +1180,6 @@ public: CommandQueueMT(bool p_sync); ~CommandQueueMT(); - }; #endif diff --git a/core/compressed_translation.cpp b/core/compressed_translation.cpp index 570cf114f7..75c24a5aba 100644 --- a/core/compressed_translation.cpp +++ b/core/compressed_translation.cpp @@ -46,201 +46,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</\361", "\003 wh\237", "\002 4", -"\003nd ?", "\002re!", "", "\003ng c", "", -"\003ly \307\003ass\323\001a\004\002rir", "", "", "", "\002se_", "\003of \"", -"\003div\364\002ros\003ere\240", "", "\002ta\310\001bZ\002si\324", "", -"\003and\a\002rs\335", "\002rt\362", "\002teE", "\003ati\316", "\002so\263", -"\002th\021", "\002tiJ\001c\034\003allp", "\003ate\345", "\002ss\246", -"\002stM", "", "\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</\361", "\003 wh\237", "\002 4", + "\003nd ?", "\002re!", "", "\003ng c", "", + "\003ly \307\003ass\323\001a\004\002rir", "", "", "", "\002se_", "\003of \"", + "\003div\364\002ros\003ere\240", "", "\002ta\310\001bZ\002si\324", "", + "\003and\a\002rs\335", "\002rt\362", "\002teE", "\003ati\316", "\002so\263", + "\002th\021", "\002tiJ\001c\034\003allp", "\003ate\345", "\002ss\246", + "\002stM", "", "\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", "</", "rt", " wi", "div", -"e, ", " it", "whi", " ma", "ge", "x", "e c", "men", ".com" + " ", "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", "</", "rt", " wi", "div", + "e, ", " it", "whi", " ma", "ge", "x", "e c", "men", ".com" }; static int smaz_compress(const char *in, int inlen, char *out, int outlen) { - unsigned int h1,h2,h3=0; - int verblen = 0, _outlen = outlen; - char verb[256], *_out = out; + unsigned int h1, h2, h3 = 0; + int verblen = 0, _outlen = outlen; + char verb[256], *_out = out; - while(inlen) { - int j = 7, needed; - char *flush = NULL; - const char *slot; + while (inlen) { + int j = 7, needed; + char *flush = NULL; + const char *slot; - h1 = h2 = in[0]<<3; - if (inlen > 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; - - 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--; + 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); + + 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 { @@ -255,104 +253,100 @@ void PHashTranslation::generate(const Ref<Translation> &p_from) { List<StringName> 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<int,CharString> > > buckets; - Vector< Map< uint32_t, int > > table; - Vector< uint32_t > hfunc_table; - Vector< _PHashTranslationCmp > compressed; + print_line("compressing keys: " + itos(keys.size())); + Vector<Vector<Pair<int, CharString> > > buckets; + Vector<Map<uint32_t, int> > table; + Vector<uint32_t> 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<StringName>::Element *E=keys.front();E;E=E->next()) { + for (List<StringName>::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<int,CharString> p; - p.first=idx; - p.second=cs; + uint32_t h = hash(0, cs.get_data()); + Pair<int, CharString> 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<size;i++) { + for (int i = 0; i < size; i++) { - Vector< Pair<int,CharString> > &b = buckets[i]; - Map< uint32_t, int > &t=table[i]; + Vector<Pair<int, CharString> > &b = buckets[i]; + Map<uint32_t, int> &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); @@ -360,136 +354,130 @@ void PHashTranslation::generate(const Ref<Translation> &p_from) { PoolVector<int>::Write htwb = hash_table.write(); PoolVector<int>::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<size;i++) { + for (int i = 0; i < size; i++) { - Map< uint32_t, int > &t=table[i]; - if (t.size()==0) { - htw[i]=0xFFFFFFFF; //nothing + Map<uint32_t, int> &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<uint32_t, int>::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); PoolVector<uint8_t>::Write cw = strings.write(); - for(int i=0;i<compressed.size();i++) { - memcpy(&cw[compressed[i].offset],compressed[i].compressed.get_data(),compressed[i].compressed.size()); + for (int i = 0; i < compressed.size(); i++) { + memcpy(&cw[compressed[i].offset], compressed[i].compressed.get_data(), compressed[i].compressed.size()); } - - ERR_FAIL_COND(btindex!=bucket_table_size); + ERR_FAIL_COND(btindex != bucket_table_size); set_locale(p_from->get_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()); - - PoolVector<int>::Read htr = hash_table.read(); - const uint32_t *htptr = (const uint32_t*)&htr[0]; - PoolVector<int>::Read btr = bucket_table.read(); - const uint32_t *btptr = (const uint32_t*)&btr[0]; + PoolVector<int>::Read htr = hash_table.read(); + const uint32_t *htptr = (const uint32_t *)&htr[0]; + PoolVector<int>::Read btr = bucket_table.read(); + const uint32_t *btptr = (const uint32_t *)&btr[0]; PoolVector<uint8_t>::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) { + 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<bucket.size;i++) { + for (int i = 0; i < bucket.size; i++) { - if (bucket.elem[i].key==h) { + if (bucket.elem[i].key == h) { - idx=i; + idx = i; break; } - } //print_line("bucket pos: "+itos(idx)); - if (idx==-1) { + if (idx == -1) { //print_line("GETMSG: Not in Bucket!"); return StringName(); } @@ -497,7 +485,7 @@ StringName PHashTranslation::get_message(const StringName& p_src_text) const { if (bucket.elem[idx].comp_size == bucket.elem[idx].uncomp_size) { String rstr; - rstr.parse_utf8(&sptr[ bucket.elem[idx].str_offset ], bucket.elem[idx].uncomp_size ); + rstr.parse_utf8(&sptr[bucket.elem[idx].str_offset], bucket.elem[idx].uncomp_size); //print_line("Uncompressed, size: "+itos(bucket.elem[idx].comp_size)); //print_line("Return: "+rstr); @@ -505,31 +493,27 @@ StringName PHashTranslation::get_message(const StringName& p_src_text) const { } else { CharString uncomp; - uncomp.resize( bucket.elem[idx].uncomp_size+1 ); - smaz_decompress(&sptr[ bucket.elem[idx].str_offset ], bucket.elem[idx].comp_size,uncomp.ptr(),bucket.elem[idx].uncomp_size ); + uncomp.resize(bucket.elem[idx].uncomp_size + 1); + smaz_decompress(&sptr[bucket.elem[idx].str_offset], bucket.elem[idx].comp_size, uncomp.ptr(), bucket.elem[idx].uncomp_size); String rstr; rstr.parse_utf8(uncomp.get_data()); //print_line("Compressed, size: "+itos(bucket.elem[idx].comp_size)); //print_line("Return: "+rstr); return rstr; } - } +void PHashTranslation::_get_property_list(List<PropertyInfo> *p_list) const { -void PHashTranslation::_get_property_list( List<PropertyInfo> *p_list) const{ - - p_list->push_back( PropertyInfo(Variant::POOL_INT_ARRAY, "hash_table")); - p_list->push_back( PropertyInfo(Variant::POOL_INT_ARRAY, "bucket_table")); - p_list->push_back( PropertyInfo(Variant::POOL_BYTE_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::POOL_INT_ARRAY, "hash_table")); + p_list->push_back(PropertyInfo(Variant::POOL_INT_ARRAY, "bucket_table")); + p_list->push_back(PropertyInfo(Variant::POOL_BYTE_ARRAY, "strings")); + p_list->push_back(PropertyInfo(Variant::OBJECT, "load_from", PROPERTY_HINT_RESOURCE_TYPE, "Translation", PROPERTY_USAGE_EDITOR)); } void PHashTranslation::_bind_methods() { - ClassDB::bind_method(D_METHOD("generate","from:Translation"),&PHashTranslation::generate); + ClassDB::bind_method(D_METHOD("generate", "from:Translation"), &PHashTranslation::generate); } -PHashTranslation::PHashTranslation() -{ +PHashTranslation::PHashTranslation() { } diff --git a/core/compressed_translation.h b/core/compressed_translation.h index cb1e084051..abaa4ebe2c 100644 --- a/core/compressed_translation.h +++ b/core/compressed_translation.h @@ -33,8 +33,7 @@ class PHashTranslation : public Translation { - GDCLASS(PHashTranslation,Translation); - + GDCLASS(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 { PoolVector<int> bucket_table; PoolVector<uint8_t> 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<PropertyInfo> *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<PropertyInfo> *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<Translation> &p_from); PHashTranslation(); diff --git a/core/core_string_names.cpp b/core/core_string_names.cpp index f8c6f47797..cbb3060f13 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_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_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 7d3754786c..f6542be290 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 1176b9be3b..3663bb1a4f 100644 --- a/core/dictionary.cpp +++ b/core/dictionary.cpp @@ -33,13 +33,9 @@ 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 { struct Data { @@ -48,171 +44,156 @@ struct DictionaryPrivate { }; SafeRefCount refcount; - HashMap<Variant,Data,_DictionaryVariantHash> variant_map; + HashMap<Variant, Data, _DictionaryVariantHash> variant_map; int counter; - }; struct DictionaryPrivateSort { - bool operator()(const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *A,const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *B) const { + bool operator()(const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *A, const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *B) const { return A->data.order < B->data.order; } }; -void Dictionary::get_key_list( List<Variant> *p_keys) const { +void Dictionary::get_key_list(List<Variant> *p_keys) const { if (_p->variant_map.empty()) return; int count = _p->variant_map.size(); - const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair**)alloca( count * sizeof(HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *) ); + const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **)alloca(count * sizeof(HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *)); _p->variant_map.get_key_value_ptr_array(pairs); - SortArray<const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair*,DictionaryPrivateSort> sort; - sort.sort(pairs,count); + SortArray<const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *, DictionaryPrivateSort> sort; + sort.sort(pairs, count); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { p_keys->push_back(pairs[i]->key); } - } -Variant& Dictionary::operator[](const Variant& p_key) { - +Variant &Dictionary::operator[](const Variant &p_key) { - DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key); + DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key); if (!v) { DictionaryPrivate::Data d; - d.order=_p->counter++; - _p->variant_map[p_key]=d; - v =_p->variant_map.getptr(p_key); - + d.order = _p->counter++; + _p->variant_map[p_key] = d; + v = _p->variant_map.getptr(p_key); } return v->variant; } -const Variant& Dictionary::operator[](const Variant& p_key) const { +const Variant &Dictionary::operator[](const Variant &p_key) const { return _p->variant_map[p_key].variant; - } -const Variant* Dictionary::getptr(const Variant& p_key) const { +const Variant *Dictionary::getptr(const Variant &p_key) const { - const DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key); + const DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key); if (!v) return NULL; else return &v->variant; } -Variant* Dictionary::getptr(const Variant& p_key) { +Variant *Dictionary::getptr(const Variant &p_key) { - DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key); + DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key); if (!v) return NULL; else return &v->variant; - - } -Variant Dictionary::get_valid(const Variant& p_key) const { +Variant Dictionary::get_valid(const Variant &p_key) const { - DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key); + DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key); if (!v) return Variant(); else return v->variant; } - 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;i<p_keys.size();i++) { - if( !has(p_keys[i]) ) { +bool Dictionary::has_all(const Array &p_keys) const { + for (int i = 0; i < p_keys.size(); i++) { + if (!has(p_keys[i])) { return false; } } return true; } -void Dictionary::erase(const Variant& p_key) { - +void Dictionary::erase(const Variant &p_key) { _p->variant_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() { _p->variant_map.clear(); - _p->counter=0; + _p->counter = 0; } - 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<Variant> keys; get_key_list(&keys); - for (List<Variant>::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<Variant>::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; } @@ -220,13 +201,12 @@ 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 { @@ -237,20 +217,20 @@ Array Dictionary::values() const { return varr; int count = _p->variant_map.size(); - const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair**)alloca( count * sizeof(HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *) ); + const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **)alloca(count * sizeof(HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *)); _p->variant_map.get_key_value_ptr_array(pairs); - SortArray<const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair*,DictionaryPrivateSort> sort; - sort.sort(pairs,count); + SortArray<const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *, DictionaryPrivateSort> sort; + sort.sort(pairs, count); - for(int i=0;i<count;i++) { - varr[i]=pairs[i]->data.variant; + for (int i = 0; i < count; i++) { + varr[i] = pairs[i]->data.variant; } 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); } @@ -262,34 +242,28 @@ Dictionary Dictionary::copy() const { List<Variant> keys; get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { - n[E->get()]=operator[](E->get()); + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { + n[E->get()] = operator[](E->get()); } return n; } - -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() { - _p=memnew( DictionaryPrivate ); + _p = memnew(DictionaryPrivate); _p->refcount.init(); - _p->counter=0; - - + _p->counter = 0; } Dictionary::~Dictionary() { diff --git a/core/dictionary.h b/core/dictionary.h index a1bf291d6b..588e33a95f 100644 --- a/core/dictionary.h +++ b/core/dictionary.h @@ -29,57 +29,53 @@ #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 _ref(const Dictionary& p_from) const; + void _ref(const Dictionary &p_from) const; void _unref() const; -public: - void get_key_list( List<Variant> *p_keys) const; +public: + void get_key_list(List<Variant> *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(); - 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 copy() const; - Dictionary(const Dictionary& p_from); + Dictionary(const Dictionary &p_from); Dictionary(); ~Dictionary(); }; diff --git a/core/dvector.cpp b/core/dvector.cpp index f6b5a5fcbf..5930a1220b 100644 --- a/core/dvector.cpp +++ b/core/dvector.cpp @@ -28,38 +28,35 @@ /*************************************************************************/ #include "dvector.h" -Mutex* dvector_lock=NULL; +Mutex *dvector_lock = NULL; -PoolAllocator *MemoryPool::memory_pool=NULL; -uint8_t *MemoryPool::pool_memory=NULL; -size_t *MemoryPool::pool_size=NULL; +PoolAllocator *MemoryPool::memory_pool = NULL; +uint8_t *MemoryPool::pool_memory = NULL; +size_t *MemoryPool::pool_size = NULL; +MemoryPool::Alloc *MemoryPool::allocs = NULL; +MemoryPool::Alloc *MemoryPool::free_list = NULL; +uint32_t MemoryPool::alloc_count = 0; +uint32_t MemoryPool::allocs_used = 0; +Mutex *MemoryPool::alloc_mutex = NULL; -MemoryPool::Alloc *MemoryPool::allocs=NULL; -MemoryPool::Alloc *MemoryPool::free_list=NULL; -uint32_t MemoryPool::alloc_count=0; -uint32_t MemoryPool::allocs_used=0; -Mutex *MemoryPool::alloc_mutex=NULL; - -size_t MemoryPool::total_memory=0; -size_t MemoryPool::max_memory=0; - +size_t MemoryPool::total_memory = 0; +size_t MemoryPool::max_memory = 0; void MemoryPool::setup(uint32_t p_max_allocs) { - allocs = memnew_arr( Alloc, p_max_allocs); + allocs = memnew_arr(Alloc, p_max_allocs); alloc_count = p_max_allocs; - allocs_used=0; + allocs_used = 0; - for(uint32_t i=0;i<alloc_count-1;i++) { + for (uint32_t i = 0; i < alloc_count - 1; i++) { - allocs[i].free_list=&allocs[i+1]; + allocs[i].free_list = &allocs[i + 1]; } - free_list=&allocs[0]; + free_list = &allocs[0]; alloc_mutex = Mutex::create(); - } void MemoryPool::cleanup() { @@ -68,6 +65,5 @@ void MemoryPool::cleanup() { memdelete(alloc_mutex); ERR_EXPLAINC("There are still MemoryPool allocs in use at exit!"); - ERR_FAIL_COND(allocs_used>0); - + ERR_FAIL_COND(allocs_used > 0); } diff --git a/core/dvector.h b/core/dvector.h index 456be41289..3f4318216d 100644 --- a/core/dvector.h +++ b/core/dvector.h @@ -29,11 +29,11 @@ #ifndef DVECTOR_H #define DVECTOR_H -#include "os/memory.h" #include "os/copymem.h" +#include "os/memory.h" +#include "os/rw_lock.h" #include "pool_allocator.h" #include "safe_refcount.h" -#include "os/rw_lock.h" #include "ustring.h" struct MemoryPool { @@ -44,7 +44,6 @@ struct MemoryPool { static uint8_t *pool_memory; static size_t *pool_size; - struct Alloc { SafeRefCount refcount; @@ -55,10 +54,15 @@ struct MemoryPool { Alloc *free_list; - Alloc() { mem=NULL; lock=0; pool_id=POOL_ALLOCATOR_INVALID_ID; size=0; free_list=NULL; } + Alloc() { + mem = NULL; + lock = 0; + pool_id = POOL_ALLOCATOR_INVALID_ID; + size = 0; + free_list = NULL; + } }; - static Alloc *allocs; static Alloc *free_list; static uint32_t alloc_count; @@ -67,39 +71,33 @@ struct MemoryPool { static size_t total_memory; static size_t max_memory; - - static void setup(uint32_t p_max_allocs=(1<<16)); + static void setup(uint32_t p_max_allocs = (1 << 16)); static void cleanup(); }; - /** @author Juan Linietsky <reduzio@gmail.com> */ - -template<class T> +template <class T> class PoolVector { MemoryPool::Alloc *alloc; - void _copy_on_write() { - if (!alloc) return; -// ERR_FAIL_COND(alloc->lock>0); should not be illegal to lock this for copy on write, as it's a copy on write after all + // ERR_FAIL_COND(alloc->lock>0); should not be illegal to lock this for copy on write, as it's a copy on write after all - if (alloc->refcount.get()==1) + if (alloc->refcount.get() == 1) return; //nothing to do - //must allocate something MemoryPool::alloc_mutex->lock(); - if (MemoryPool::allocs_used==MemoryPool::alloc_count) { + if (MemoryPool::allocs_used == MemoryPool::alloc_count) { MemoryPool::alloc_mutex->unlock(); ERR_EXPLAINC("All memory pool allocations are in use, can't COW."); ERR_FAIL(); @@ -114,26 +112,24 @@ class PoolVector { MemoryPool::allocs_used++; //copy the alloc data - alloc->size=old_alloc->size; + alloc->size = old_alloc->size; alloc->refcount.init(); - alloc->pool_id=POOL_ALLOCATOR_INVALID_ID; - alloc->lock=0; + alloc->pool_id = POOL_ALLOCATOR_INVALID_ID; + alloc->lock = 0; #ifdef DEBUG_ENABLED - MemoryPool::total_memory+=alloc->size; - if (MemoryPool::total_memory>MemoryPool::max_memory) { - MemoryPool::max_memory=MemoryPool::total_memory; + MemoryPool::total_memory += alloc->size; + if (MemoryPool::total_memory > MemoryPool::max_memory) { + MemoryPool::max_memory = MemoryPool::total_memory; } #endif MemoryPool::alloc_mutex->unlock(); - if (MemoryPool::memory_pool) { - } else { - alloc->mem = memalloc( alloc->size ); + alloc->mem = memalloc(alloc->size); } { @@ -142,21 +138,20 @@ class PoolVector { Read r; r._ref(old_alloc); - int cur_elements = alloc->size/sizeof(T); - T*dst = (T*)w.ptr(); - const T*src = (const T*)r.ptr(); - for(int i=0;i<cur_elements;i++) { - memnew_placement(&dst[i],T(src[i])); + int cur_elements = alloc->size / sizeof(T); + T *dst = (T *)w.ptr(); + const T *src = (const T *)r.ptr(); + for (int i = 0; i < cur_elements; i++) { + memnew_placement(&dst[i], T(src[i])); } } - - if (old_alloc->refcount.unref()==true) { - //this should never happen but.. + if (old_alloc->refcount.unref() == true) { +//this should never happen but.. #ifdef DEBUG_ENABLED MemoryPool::alloc_mutex->lock(); - MemoryPool::total_memory-=old_alloc->size; + MemoryPool::total_memory -= old_alloc->size; MemoryPool::alloc_mutex->unlock(); #endif @@ -164,12 +159,11 @@ class PoolVector { Write w; w._ref(old_alloc); - int cur_elements = old_alloc->size/sizeof(T); - T*elems = (T*)w.ptr(); - for(int i=0;i<cur_elements;i++) { + int cur_elements = old_alloc->size / sizeof(T); + T *elems = (T *)w.ptr(); + for (int i = 0; i < cur_elements; i++) { elems[i].~T(); } - } if (MemoryPool::memory_pool) { @@ -178,26 +172,22 @@ class PoolVector { //if some resize } else { - - memfree( old_alloc->mem ); - old_alloc->mem=NULL; - old_alloc->size=0; - + memfree(old_alloc->mem); + old_alloc->mem = NULL; + old_alloc->size = 0; MemoryPool::alloc_mutex->lock(); - old_alloc->free_list=MemoryPool::free_list; - MemoryPool::free_list=old_alloc; + old_alloc->free_list = MemoryPool::free_list; + MemoryPool::free_list = old_alloc; MemoryPool::allocs_used--; MemoryPool::alloc_mutex->unlock(); } - } - } - void _reference( const PoolVector& p_dvector ) { + void _reference(const PoolVector &p_dvector) { - if (alloc==p_dvector.alloc) + if (alloc == p_dvector.alloc) return; _unreference(); @@ -207,108 +197,98 @@ class PoolVector { } if (p_dvector.alloc->refcount.ref()) { - alloc=p_dvector.alloc; + alloc = p_dvector.alloc; } - } - void _unreference() { if (!alloc) return; - if (alloc->refcount.unref()==false) { - alloc=NULL; + if (alloc->refcount.unref() == false) { + alloc = NULL; return; } //must be disposed! { - int cur_elements = alloc->size/sizeof(T); + int cur_elements = alloc->size / sizeof(T); Write w = write(); - for (int i=0;i<cur_elements;i++) { + for (int i = 0; i < cur_elements; i++) { w[i].~T(); } - } #ifdef DEBUG_ENABLED MemoryPool::alloc_mutex->lock(); - MemoryPool::total_memory-=alloc->size; + MemoryPool::total_memory -= alloc->size; MemoryPool::alloc_mutex->unlock(); #endif - if (MemoryPool::memory_pool) { //resize memory pool //if none, create //if some resize } else { - memfree( alloc->mem ); - alloc->mem=NULL; - alloc->size=0; - + memfree(alloc->mem); + alloc->mem = NULL; + alloc->size = 0; MemoryPool::alloc_mutex->lock(); - alloc->free_list=MemoryPool::free_list; - MemoryPool::free_list=alloc; + alloc->free_list = MemoryPool::free_list; + MemoryPool::free_list = alloc; MemoryPool::allocs_used--; MemoryPool::alloc_mutex->unlock(); - } - alloc=NULL; + alloc = NULL; } public: - class Access { - friend class PoolVector; + friend class PoolVector; + protected: MemoryPool::Alloc *alloc; - T * mem; + T *mem; _FORCE_INLINE_ void _ref(MemoryPool::Alloc *p_alloc) { - alloc=p_alloc; + alloc = p_alloc; if (alloc) { - if (atomic_increment(&alloc->lock)==1) { + if (atomic_increment(&alloc->lock) == 1) { if (MemoryPool::memory_pool) { //lock it and get mem } } - mem = (T*)alloc->mem; + mem = (T *)alloc->mem; } } _FORCE_INLINE_ void _unref() { - if (alloc) { - if (atomic_decrement(&alloc->lock)==0) { + if (atomic_decrement(&alloc->lock) == 0) { if (MemoryPool::memory_pool) { //put mem back } } mem = NULL; - alloc=NULL; + alloc = NULL; } - - } Access() { - alloc=NULL; - mem=NULL; + alloc = NULL; + mem = NULL; } - public: virtual ~Access() { _unref(); @@ -317,48 +297,42 @@ public: class Read : public Access { public: - - _FORCE_INLINE_ const T& operator[](int p_index) const { return this->mem[p_index]; } + _FORCE_INLINE_ const T &operator[](int p_index) const { return this->mem[p_index]; } _FORCE_INLINE_ const T *ptr() const { return this->mem; } - void operator=(const Read& p_read) { - if (this->alloc==p_read.alloc) + void operator=(const Read &p_read) { + if (this->alloc == p_read.alloc) return; this->_unref(); this->_ref(p_read.alloc); } - Read(const Read& p_read) { + Read(const Read &p_read) { this->_ref(p_read.alloc); } Read() {} - - }; class Write : public Access { public: - - _FORCE_INLINE_ T& operator[](int p_index) const { return this->mem[p_index]; } + _FORCE_INLINE_ T &operator[](int p_index) const { return this->mem[p_index]; } _FORCE_INLINE_ T *ptr() const { return this->mem; } - void operator=(const Write& p_read) { - if (this->alloc==p_read.alloc) + void operator=(const Write &p_read) { + if (this->alloc == p_read.alloc) return; this->_unref(); this->_ref(p_read.alloc); } - Write(const Write& p_read) { + Write(const Write &p_read) { this->_ref(p_read.alloc); } Write() {} - }; - Read read() const { Read r; @@ -366,7 +340,6 @@ public: r._ref(alloc); } return r; - } Write write() { @@ -378,90 +351,88 @@ public: return w; } - template<class MC> - void fill_with(const MC& p_mc) { - + template <class MC> + 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<s-1; i++) { + for (int i = p_index; i < s - 1; i++) { - w[i]=w[i+1]; + w[i] = w[i + 1]; }; w = Write(); - resize(s-1); + resize(s - 1); } inline int size() const; T get(int p_index) const; - 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 PoolVector<T>& 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 PoolVector<T> &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;i<ds;i++) - w[bs+i]=r[i]; + for (int i = 0; i < ds; i++) + w[bs + i] = r[i]; } PoolVector<T> subarray(int p_from, int p_to) { - if (p_from<0) { - p_from=size()+p_from; + if (p_from < 0) { + p_from = size() + p_from; } - if (p_to<0) { - p_to=size()+p_to; + if (p_to < 0) { + p_to = size() + p_to; } - if (p_from<0 || p_from>=size()) { - PoolVector<T>& aux=*((PoolVector<T>*)0); // nullreturn - ERR_FAIL_COND_V(p_from<0 || p_from>=size(),aux) + if (p_from < 0 || p_from >= size()) { + PoolVector<T> &aux = *((PoolVector<T> *)0); // nullreturn + ERR_FAIL_COND_V(p_from < 0 || p_from >= size(), aux) } - if (p_to<0 || p_to>=size()) { - PoolVector<T>& aux=*((PoolVector<T>*)0); // nullreturn - ERR_FAIL_COND_V(p_to<0 || p_to>=size(),aux) + if (p_to < 0 || p_to >= size()) { + PoolVector<T> &aux = *((PoolVector<T> *)0); // nullreturn + ERR_FAIL_COND_V(p_to < 0 || p_to >= size(), aux) } PoolVector<T> slice; - int span=1 + p_to - p_from; + int span = 1 + p_to - p_from; slice.resize(span); Read r = read(); Write w = slice.write(); - for (int i=0; i<span; ++i) { - w[i] = r[p_from+i]; + for (int i = 0; i < span; ++i) { + w[i] = r[p_from + i]; } return slice; } - Error insert(int p_pos,const T& p_val) { + Error insert(int p_pos, const T &p_val) { - int s=size(); - ERR_FAIL_INDEX_V(p_pos,s+1,ERR_INVALID_PARAMETER); - resize(s+1); + int s = size(); + ERR_FAIL_INDEX_V(p_pos, s + 1, ERR_INVALID_PARAMETER); + resize(s + 1); { Write w = write(); - for (int i=s;i>p_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; @@ -471,14 +442,14 @@ public: String rs = ""; int s = size(); Read r = read(); - for(int i=0;i<s;i++) { + for (int i = 0; i < s; i++) { rs += r[i] + delimiter; } - rs.erase( rs.length()-delimiter.length(), delimiter.length()); + rs.erase(rs.length() - delimiter.length(), delimiter.length()); return rs; } - bool is_locked() const { return alloc && alloc->lock>0; } + bool is_locked() const { return alloc && alloc->lock > 0; } inline const T operator[](int p_index) const; @@ -486,49 +457,51 @@ public: void invert(); - void operator=(const PoolVector& p_dvector) { _reference(p_dvector); } - PoolVector() { alloc=NULL; } - PoolVector(const PoolVector& p_dvector) { alloc=NULL; _reference(p_dvector); } + void operator=(const PoolVector &p_dvector) { _reference(p_dvector); } + PoolVector() { alloc = NULL; } + PoolVector(const PoolVector &p_dvector) { + alloc = NULL; + _reference(p_dvector); + } ~PoolVector() { _unreference(); } - }; -template<class T> +template <class T> int PoolVector<T>::size() const { - return alloc ? alloc->size/sizeof(T) : 0; + return alloc ? alloc->size / sizeof(T) : 0; } -template<class T> +template <class T> T PoolVector<T>::get(int p_index) const { return operator[](p_index); } -template<class T> -void PoolVector<T>::set(int p_index, const T& p_val) { +template <class T> +void PoolVector<T>::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<class T> -void PoolVector<T>::push_back(const T& p_val) { +template <class T> +void PoolVector<T>::push_back(const T &p_val) { - resize( size() + 1 ); - set( size() -1, p_val ); + resize(size() + 1); + set(size() - 1, p_val); } -template<class T> +template <class T> const T PoolVector<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); } Read r = read(); @@ -536,19 +509,17 @@ const T PoolVector<T>::operator[](int p_index) const { return r[p_index]; } - -template<class T> +template <class T> Error PoolVector<T>::resize(int p_size) { + if (alloc == NULL) { - if (alloc==NULL) { - - if (p_size==0) + if (p_size == 0) return OK; //nothing to do here //must allocate something MemoryPool::alloc_mutex->lock(); - if (MemoryPool::allocs_used==MemoryPool::alloc_count) { + if (MemoryPool::allocs_used == MemoryPool::alloc_count) { MemoryPool::alloc_mutex->unlock(); ERR_EXPLAINC("All memory pool allocations are in use."); ERR_FAIL_V(ERR_OUT_OF_MEMORY); @@ -561,22 +532,22 @@ Error PoolVector<T>::resize(int p_size) { MemoryPool::allocs_used++; //cleanup the alloc - alloc->size=0; + alloc->size = 0; alloc->refcount.init(); - alloc->pool_id=POOL_ALLOCATOR_INVALID_ID; + alloc->pool_id = POOL_ALLOCATOR_INVALID_ID; MemoryPool::alloc_mutex->unlock(); } else { - ERR_FAIL_COND_V( alloc->lock>0, ERR_LOCKED ); //can't resize if locked! + ERR_FAIL_COND_V(alloc->lock > 0, ERR_LOCKED); //can't resize if locked! } - size_t new_size = sizeof(T)*p_size; + size_t new_size = sizeof(T) * p_size; - if (alloc->size==new_size) + if (alloc->size == new_size) return OK; //nothing to do - if (p_size == 0 ) { + if (p_size == 0) { _unreference(); return OK; } @@ -585,18 +556,17 @@ Error PoolVector<T>::resize(int p_size) { #ifdef DEBUG_ENABLED MemoryPool::alloc_mutex->lock(); - MemoryPool::total_memory-=alloc->size; - MemoryPool::total_memory+=new_size; - if (MemoryPool::total_memory>MemoryPool::max_memory) { - MemoryPool::max_memory=MemoryPool::total_memory; + MemoryPool::total_memory -= alloc->size; + MemoryPool::total_memory += new_size; + if (MemoryPool::total_memory > MemoryPool::max_memory) { + MemoryPool::max_memory = MemoryPool::total_memory; } MemoryPool::alloc_mutex->unlock(); #endif - int cur_elements = alloc->size / sizeof(T); - if (p_size > cur_elements ) { + if (p_size > cur_elements) { if (MemoryPool::memory_pool) { //resize memory pool @@ -604,32 +574,30 @@ Error PoolVector<T>::resize(int p_size) { //if some resize } else { - if (alloc->size==0) { - alloc->mem = memalloc( new_size ); + if (alloc->size == 0) { + alloc->mem = memalloc(new_size); } else { - alloc->mem = memrealloc( alloc->mem, new_size ); + alloc->mem = memrealloc(alloc->mem, new_size); } } - alloc->size=new_size; + alloc->size = new_size; Write w = write(); - for (int i=cur_elements;i<p_size;i++) { + for (int i = cur_elements; i < p_size; i++) { - memnew_placement(&w[i], T ); + memnew_placement(&w[i], T); } - } else { { Write w = write(); - for (int i=p_size;i<cur_elements;i++) { + for (int i = p_size; i < cur_elements; i++) { w[i].~T(); } - } if (MemoryPool::memory_pool) { @@ -638,39 +606,38 @@ Error PoolVector<T>::resize(int p_size) { //if some resize } else { - if (new_size==0) { - memfree( alloc->mem ); - alloc->mem=NULL; - alloc->size=0; + if (new_size == 0) { + memfree(alloc->mem); + alloc->mem = NULL; + alloc->size = 0; MemoryPool::alloc_mutex->lock(); - alloc->free_list=MemoryPool::free_list; - MemoryPool::free_list=alloc; + alloc->free_list = MemoryPool::free_list; + MemoryPool::free_list = alloc; MemoryPool::allocs_used--; MemoryPool::alloc_mutex->unlock(); } else { - alloc->mem = memrealloc( alloc->mem, new_size ); - alloc->size=new_size; + alloc->mem = memrealloc(alloc->mem, new_size); + alloc->size = new_size; } } - } return OK; } -template<class T> +template <class T> void PoolVector<T>::invert() { T temp; Write w = write(); int s = size(); - int half_s = s/2; + int half_s = s / 2; - for(int i=0;i<half_s;i++) { + for (int i = 0; i < half_s; i++) { temp = w[i]; - w[i] = w[s-i-1]; - w[s-i-1] = temp; + w[i] = w[s - i - 1]; + w[s - i - 1] = temp; } } diff --git a/core/engine.cpp b/core/engine.cpp index b017e77275..1e46117bd6 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -32,7 +32,7 @@ void Engine::set_iterations_per_second(int p_ips) { - ips=p_ips; + ips = p_ips; } int Engine::get_iterations_per_second() const { @@ -40,7 +40,7 @@ int Engine::get_iterations_per_second() const { } void Engine::set_target_fps(int p_fps) { - _target_fps=p_fps>0? p_fps : 0; + _target_fps = p_fps > 0 ? p_fps : 0; } float Engine::get_target_fps() const { @@ -54,7 +54,7 @@ uint64_t Engine::get_frames_drawn() { void Engine::set_frame_delay(uint32_t p_msec) { - _frame_delay=p_msec; + _frame_delay = p_msec; } uint32_t Engine::get_frame_delay() const { @@ -64,7 +64,7 @@ uint32_t Engine::get_frame_delay() const { void Engine::set_time_scale(float p_scale) { - _time_scale=p_scale; + _time_scale = p_scale; } float Engine::get_time_scale() const { @@ -77,11 +77,11 @@ Dictionary Engine::get_version_info() const { Dictionary dict; dict["major"] = VERSION_MAJOR; dict["minor"] = VERSION_MINOR; - #ifdef VERSION_PATCH +#ifdef VERSION_PATCH dict["patch"] = VERSION_PATCH; - #else +#else dict["patch"] = 0; - #endif +#endif dict["status"] = _MKSTR(VERSION_STATUS); dict["revision"] = _MKSTR(VERSION_REVISION); dict["year"] = VERSION_YEAR; @@ -95,25 +95,23 @@ Dictionary Engine::get_version_info() const { return dict; } - -Engine *Engine::singleton=NULL; +Engine *Engine::singleton = NULL; Engine *Engine::get_singleton() { return singleton; } -Engine::Engine() -{ - - singleton=this; - frames_drawn=0; - ips=60; - _frame_delay=0; - _fps=1; - _target_fps=0; - _time_scale=1.0; - _pixel_snap=false; - _fixed_frames=0; - _idle_frames=0; - _in_fixed=false; +Engine::Engine() { + + singleton = this; + frames_drawn = 0; + ips = 60; + _frame_delay = 0; + _fps = 1; + _target_fps = 0; + _time_scale = 1.0; + _pixel_snap = false; + _fixed_frames = 0; + _idle_frames = 0; + _in_fixed = false; } diff --git a/core/engine.h b/core/engine.h index 9af4219a68..346e9538d6 100644 --- a/core/engine.h +++ b/core/engine.h @@ -29,14 +29,14 @@ #ifndef ENGINE_H #define ENGINE_H -#include "ustring.h" #include "list.h" -#include "vector.h" #include "os/main_loop.h" +#include "ustring.h" +#include "vector.h" class Engine { -friend class Main; + friend class Main; String _custom_level; uint64_t frames_drawn; @@ -52,8 +52,8 @@ friend class Main; bool _in_fixed; static Engine *singleton; -public: +public: static Engine *get_singleton(); virtual void set_iterations_per_second(int p_ips); diff --git a/core/error_list.h b/core/error_list.h index f4063a9285..72b8425444 100644 --- a/core/error_list.h +++ b/core/error_list.h @@ -47,7 +47,7 @@ enum Error { ERR_FILE_NOT_FOUND, ERR_FILE_BAD_DRIVE, ERR_FILE_BAD_PATH, - ERR_FILE_NO_PERMISSION, // (10) + ERR_FILE_NO_PERMISSION, // (10) ERR_FILE_ALREADY_IN_USE, ERR_FILE_CANT_OPEN, ERR_FILE_CANT_WRITE, @@ -57,15 +57,15 @@ enum Error { ERR_FILE_MISSING_DEPENDENCIES, ERR_FILE_EOF, ERR_CANT_OPEN, ///< Can't open a resource/socket/file - ERR_CANT_CREATE, // (20) + ERR_CANT_CREATE, // (20) ERR_QUERY_FAILED, ERR_ALREADY_IN_USE, - ERR_LOCKED, ///< resource is locked - ERR_TIMEOUT, - ERR_CANT_CONNECT, // (25) + ERR_LOCKED, ///< resource is locked + ERR_TIMEOUT, + ERR_CANT_CONNECT, // (25) ERR_CANT_RESOLVE, ERR_CONNECTION_ERROR, - ERR_CANT_AQUIRE_RESOURCE, + ERR_CANT_AQUIRE_RESOURCE, ERR_CANT_FORK, ERR_INVALID_DATA, ///< Data passed is invalid (30) ERR_INVALID_PARAMETER, ///< Parameter passed is invalid @@ -74,15 +74,15 @@ enum Error { ERR_DATABASE_CANT_READ, ///< database is full ERR_DATABASE_CANT_WRITE, ///< database is full (35) ERR_COMPILATION_FAILED, - ERR_METHOD_NOT_FOUND, - ERR_LINK_FAILED, + ERR_METHOD_NOT_FOUND, + ERR_LINK_FAILED, ERR_SCRIPT_FAILED, - ERR_CYCLIC_LINK, // (40) + ERR_CYCLIC_LINK, // (40) ERR_INVALID_DECLARATION, ERR_DUPLICATE_SYMBOL, ERR_PARSE_ERROR, ERR_BUSY, - ERR_SKIP, // (45) + ERR_SKIP, // (45) ERR_HELP, ///< user requested help!! ERR_BUG, ///< a bug in the software certainly happened, due to a double check failing or unexpected behavior. ERR_PRINTER_ON_FIRE, /// the parallel port printer is engulfed in flames @@ -90,7 +90,4 @@ enum Error { ERR_WTF = ERR_OMFG_THIS_IS_VERY_VERY_BAD ///< short version of the above }; - - #endif - diff --git a/core/error_macros.cpp b/core/error_macros.cpp index e963f6122b..530e209dd8 100644 --- a/core/error_macros.cpp +++ b/core/error_macros.cpp @@ -30,12 +30,11 @@ #include "os/os.h" +bool _err_error_exists = false; -bool _err_error_exists=false; +static ErrorHandlerList *error_handler_list = NULL; -static ErrorHandlerList *error_handler_list=NULL; - -void _err_set_last_error(const char* p_err) { +void _err_set_last_error(const char *p_err) { OS::get_singleton()->set_last_error(p_err); } @@ -48,8 +47,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(); } @@ -60,44 +59,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 ac86ef432b..02a15de067 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 @@ -53,8 +52,8 @@ enum ErrorHandlerType { ERR_HANDLER_SHADER, }; -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 { @@ -62,22 +61,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 */ @@ -86,13 +89,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 @@ -103,49 +114,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_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(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; \ + } /** 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. @@ -153,81 +178,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_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_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; \ + } #endif diff --git a/core/event_queue.cpp b/core/event_queue.cpp index 587283cc79..f9ebc82e40 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) { - - 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; +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; 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;i<event->args;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 d15ff81bc7..8e35445b68 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); +public: + 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 2233615e25..1589be996e 100644 --- a/core/func_ref.cpp +++ b/core/func_ref.cpp @@ -28,51 +28,46 @@ /*************************************************************************/ #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<Variant> defargs; - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call_func:Variant",&FuncRef::call_func,mi,defargs); - + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_func:Variant", &FuncRef::call_func, mi, defargs); } - ClassDB::bind_method(D_METHOD("set_instance","instance"),&FuncRef::set_instance); - ClassDB::bind_method(D_METHOD("set_function","name"),&FuncRef::set_function); - + ClassDB::bind_method(D_METHOD("set_instance", "instance"), &FuncRef::set_instance); + ClassDB::bind_method(D_METHOD("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 0c9bca4680..1179c98e29 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 { - GDCLASS(FuncRef,Reference); + GDCLASS(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_config.cpp b/core/global_config.cpp index b76991c04e..6aded6fbb7 100644 --- a/core/global_config.cpp +++ b/core/global_config.cpp @@ -28,19 +28,19 @@ /*************************************************************************/ #include "global_config.h" +#include "bind/core_bind.h" +#include "io/file_access_network.h" +#include "io/file_access_pack.h" +#include "io/marshalls.h" #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 "variant_parser.h" #define FORMAT_VERSION 3 -GlobalConfig *GlobalConfig::singleton=NULL; +GlobalConfig *GlobalConfig::singleton = NULL; GlobalConfig *GlobalConfig::get_singleton() { @@ -52,24 +52,23 @@ String GlobalConfig::get_resource_path() const { return resource_path; }; -String GlobalConfig::localize_path(const String& p_path) const { +String GlobalConfig::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); @@ -84,10 +83,9 @@ String GlobalConfig::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); @@ -96,23 +94,21 @@ String GlobalConfig::localize_path(const String& p_path) const { }; return plocal + path.substr(sep, path.size() - sep); }; - } -void GlobalConfig::set_initial_value(const String& p_name, const Variant & p_value) { +void GlobalConfig::set_initial_value(const String &p_name, const Variant &p_value) { ERR_FAIL_COND(!props.has(p_name)); - props[p_name].initial=p_value; + props[p_name].initial = p_value; } - -String GlobalConfig::globalize_path(const String& p_path) const { +String GlobalConfig::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://", ""); }; @@ -120,63 +116,59 @@ String GlobalConfig::globalize_path(const String& p_path) const { return p_path; } - -bool GlobalConfig::_set(const StringName& p_name, const Variant& p_value) { +bool GlobalConfig::_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<String> ps = s.substr(0,sl).split("."); - String prop=s.substr(sl,s.length()-sl); - for(int i=1;i<ps.size();i++) { + Vector<String> 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 GlobalConfig::_get(const StringName& p_name,Variant &r_ret) const { +bool GlobalConfig::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (!props.has(p_name)) { - print_line("WARNING: not found: "+String(p_name)); + print_line("WARNING: not found: " + String(p_name)); return false; } - r_ret=props[p_name].variant; + r_ret = props[p_name].variant; return true; - } struct _VCSort { @@ -186,7 +178,7 @@ struct _VCSort { int order; int flags; - bool operator<(const _VCSort& p_vcs) const{ return order==p_vcs.order?name<p_vcs.name:order< p_vcs.order; } + bool operator<(const _VCSort &p_vcs) const { return order == p_vcs.order ? name < p_vcs.name : order < p_vcs.order; } }; void GlobalConfig::_get_property_list(List<PropertyInfo> *p_list) const { @@ -195,66 +187,63 @@ void GlobalConfig::_get_property_list(List<PropertyInfo> *p_list) const { Set<_VCSort> vclist; - for(Map<StringName,VariantContainer>::Element *E=props.front();E;E=E->next()) { + for (Map<StringName, VariantContainer>::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_STORAGE; + vc.flags = PROPERTY_USAGE_STORAGE; else - vc.flags=PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE; + vc.flags = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE; 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 GlobalConfig::_load_resource_pack(const String& p_pack) { +bool GlobalConfig::_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<DirAccessPack>(DirAccess::ACCESS_RESOURCES); - using_datapack=true; + using_datapack = true; return true; } -Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) { +Error GlobalConfig::setup(const String &p_path, const String &p_main_pack) { //If looking for files in network, just use network! if (FileAccessNetworkClient::get_singleton()) { - if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) { + if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) { _load_settings("res://override.cfg"); - } return OK; @@ -264,56 +253,47 @@ Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) { //Attempt with a passed main pack first - 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://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) { + if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) { //load override from location of the main pack _load_settings(p_main_pack.get_base_dir().plus_file("override.cfg")); - } return OK; - } //Attempt with execname.pck - if (exec_path!="") { - + if (exec_path != "") { - if (_load_resource_pack(exec_path.get_basename()+".pck")) { + if (_load_resource_pack(exec_path.get_basename() + ".pck")) { - if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) { + if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) { //load override from location of executable _load_settings(exec_path.get_base_dir().plus_file("override.cfg")); - } - - return OK; } - } - //Try to use the filesystem for files, according to OS. (only Android -when reading from pck- and iOS use this) - if (OS::get_singleton()->get_resource_dir()!="") { + 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 // data.pck and data.zip are deprecated and no longer supported, apologies. // make sure this is loaded from the resource path - if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) { + if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) { _load_settings("res://override.cfg"); - } return OK; @@ -322,7 +302,7 @@ Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) { //Nothing was found, try to find a godot.cfg somewhere! DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!d,ERR_CANT_CREATE); + ERR_FAIL_COND_V(!d, ERR_CANT_CREATE); d->change_dir(p_path); @@ -330,33 +310,32 @@ Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) { String current_dir = d->get_current_dir(); bool found = false; - while(true) { + while (true) { //try to load settings in ascending through dirs shape! - if (_load_settings(current_dir+"/godot.cfg")==OK || _load_settings_binary(current_dir+"/godot.cfb")==OK) { + if (_load_settings(current_dir + "/godot.cfg") == OK || _load_settings_binary(current_dir + "/godot.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(); + current_dir = d->get_current_dir(); } - - 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; } @@ -368,24 +347,22 @@ bool GlobalConfig::has(String p_var) const { return props.has(p_var); } - void GlobalConfig::set_registering_order(bool p_enable) { - registering_order=p_enable; + registering_order = p_enable; } Error GlobalConfig::_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 godot.cfb (not ECFG)"); @@ -394,111 +371,101 @@ Error GlobalConfig::_load_settings_binary(const String p_path) { set_registering_order(false); - uint32_t count=f->get_32(); + uint32_t count = f->get_32(); - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - uint32_t slen=f->get_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<uint8_t> 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); - + Error err = decode_variant(value, d.ptr(), d.size()); + ERR_EXPLAIN("Error decoding property: " + key); + ERR_CONTINUE(err != OK); + set(key, value); } set_registering_order(true); - return OK; } Error GlobalConfig::_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 (!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("GlobalConfig::load - "+p_path+":"+itos(lines)+" error: "+error_text); + } else if (err != OK) { + ERR_PRINTS("GlobalConfig::load - " + p_path + ":" + itos(lines) + " error: " + error_text); memdelete(f); return err; } - if (assign!=String()) { - if (section==String() && assign=="config_version") { + if (assign != String()) { + if (section == String() && assign == "config_version") { int config_version = value; if (config_version > FORMAT_VERSION) { memdelete(f); - ERR_FAIL_COND_V(config_version > FORMAT_VERSION,ERR_FILE_CANT_OPEN); + ERR_FAIL_COND_V(config_version > FORMAT_VERSION, ERR_FILE_CANT_OPEN); } - } - set(section+"/"+assign,value); - } else if (next_tag.name!=String()) { - section=next_tag.name; + set(section + "/" + assign, value); + } else if (next_tag.name != String()) { + section = next_tag.name; } } memdelete(f); return OK; - } +int GlobalConfig::get_order(const String &p_name) const { - -int GlobalConfig::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 GlobalConfig::set_order(const String& p_name, int p_order){ +void GlobalConfig::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 GlobalConfig::clear(const String& p_name) { +void GlobalConfig::clear(const String &p_name) { ERR_FAIL_COND(!props.has(p_name)); props.erase(p_name); @@ -506,28 +473,27 @@ void GlobalConfig::clear(const String& p_name) { Error GlobalConfig::save() { - return save_custom(get_resource_path()+"/godot.cfg"); + return save_custom(get_resource_path() + "/godot.cfg"); } -Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom) { - +Error GlobalConfig::_save_settings_binary(const String &p_file, const Map<String, List<String> > &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 godot.cfb at "+p_file); - ERR_FAIL_COND_V(err,err) + ERR_EXPLAIN("Coudln't save godot.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<String,List<String> >::Element *E=props.front();E;E=E->next()) { + for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) { - for(List<String>::Element *F=E->get().front();F;F=F->next()) { + for (List<String>::Element *F = E->get().front(); F; F = F->next()) { count++; } @@ -535,17 +501,16 @@ Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String, file->store_32(count); //store how many properties are saved + for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) { - for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) { - - for(List<String>::Element *F=E->get().front();F;F=F->next()) { + for (List<String>::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); @@ -553,67 +518,62 @@ Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String, file->store_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<uint8_t> 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 GlobalConfig::_save_settings_text(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom) { +Error GlobalConfig::_save_settings_text(const String &p_file, const Map<String, List<String> > &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 godot.cfg - "+p_file); - ERR_FAIL_COND_V(err,err) + ERR_EXPLAIN("Coudln't save godot.cfg - " + p_file); + ERR_FAIL_COND_V(err, err) } - file->store_string("config_version="+itos(FORMAT_VERSION)+"\n"); + file->store_string("config_version=" + itos(FORMAT_VERSION) + "\n"); + for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) { - for(Map<String,List<String> >::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<String>::Element *F=E->get().front();F;F=F->next()) { + if (E->key() != "") + file->store_string("[" + E->key() + "]\n\n"); + for (List<String>::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); - String vstr; - VariantWriter::write_to_string(value,vstr); - file->store_string(F->get()+"="+vstr+"\n"); - + VariantWriter::write_to_string(value, vstr); + file->store_string(F->get() + "=" + vstr + "\n"); } } @@ -628,15 +588,15 @@ Error GlobalConfig::_save_custom_bnd(const String &p_file) { // add other params return save_custom(p_file); }; -Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,const Set<String>& p_ignore_masks) { +Error GlobalConfig::save_custom(const String &p_path, const CustomMap &p_custom, const Set<String> &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<StringName,VariantContainer>::Element *G=props.front();G;G=G->next()) { + for (Map<StringName, VariantContainer>::Element *G = props.front(); G; G = G->next()) { - const VariantContainer *v=&G->get(); + const VariantContainer *v = &G->get(); if (v->hide_from_editor) continue; @@ -644,12 +604,12 @@ Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,c if (p_custom.has(G->key())) continue; - bool discard=false; + bool discard = false; - for(const Set<String>::Element *E=p_ignore_masks.front();E;E=E->next()) { + for (const Set<String>::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; } } @@ -658,57 +618,53 @@ Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,c continue; _VCSort vc; - vc.name=G->key();//*k; - vc.order=v->order; - vc.type=v->variant.get_type(); - vc.flags=PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE; - if (v->variant==v->initial) + vc.name = G->key(); //*k; + vc.order = v->order; + vc.type = v->variant.get_type(); + vc.flags = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE; + if (v->variant == v->initial) continue; - vclist.insert(vc); } - for(const Map<String,Variant>::Element *E=p_custom.front();E;E=E->next()) { - + for (const Map<String, Variant>::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<String,List<String> > props; + Map<String, List<String> > 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; @@ -754,43 +710,40 @@ Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,c #endif } -Variant _GLOBAL_DEF( const String& p_var, const Variant& p_default) { +Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default) { if (GlobalConfig::get_singleton()->has(p_var)) { - GlobalConfig::get_singleton()->set_initial_value(p_var,p_default); + GlobalConfig::get_singleton()->set_initial_value(p_var, p_default); return GlobalConfig::get_singleton()->get(p_var); } - GlobalConfig::get_singleton()->set(p_var,p_default); - GlobalConfig::get_singleton()->set_initial_value(p_var,p_default); + GlobalConfig::get_singleton()->set(p_var, p_default); + GlobalConfig::get_singleton()->set_initial_value(p_var, p_default); return p_default; - } void GlobalConfig::add_singleton(const Singleton &p_singleton) { singletons.push_back(p_singleton); - singleton_ptrs[p_singleton.name]=p_singleton.ptr; + singleton_ptrs[p_singleton.name] = p_singleton.ptr; } -Object* GlobalConfig::get_singleton_object(const String& p_name) const { +Object *GlobalConfig::get_singleton_object(const String &p_name) const { - - const Map<StringName,Object*>::Element *E=singleton_ptrs.find(p_name); + const Map<StringName, Object *>::Element *E = singleton_ptrs.find(p_name); if (!E) return NULL; else return E->get(); - }; -bool GlobalConfig::has_singleton(const String& p_name) const { +bool GlobalConfig::has_singleton(const String &p_name) const { return get_singleton_object(p_name) != NULL; }; void GlobalConfig::get_singletons(List<Singleton> *p_singletons) { - for(List<Singleton>::Element *E=singletons.front();E;E=E->next()) + for (List<Singleton>::Element *E = singletons.front(); E; E = E->next()) p_singletons->push_back(E->get()); } @@ -800,20 +753,19 @@ Vector<String> GlobalConfig::get_optimizer_presets() const { GlobalConfig::get_singleton()->get_property_list(&pi); Vector<String> names; - for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) { + for (List<PropertyInfo>::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 GlobalConfig::_add_property_info_bind(const Dictionary& p_info) { +void GlobalConfig::_add_property_info_bind(const Dictionary &p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); @@ -832,17 +784,16 @@ void GlobalConfig::_add_property_info_bind(const Dictionary& p_info) { set_custom_property_info(pinfo.name, pinfo); } -void GlobalConfig::set_custom_property_info(const String& p_prop,const PropertyInfo& p_info) { +void GlobalConfig::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].name=p_prop; - + custom_prop_info[p_prop] = p_info; + custom_prop_info[p_prop].name = p_prop; } void GlobalConfig::set_disable_platform_override(bool p_disable) { - disable_platform_override=p_disable; + disable_platform_override = p_disable; } bool GlobalConfig::is_using_datapack() const { @@ -850,16 +801,15 @@ bool GlobalConfig::is_using_datapack() const { return using_datapack; } -bool GlobalConfig::property_can_revert(const String& p_name) { +bool GlobalConfig::property_can_revert(const String &p_name) { if (!props.has(p_name)) return false; - return props[p_name].initial!=props[p_name].variant; - + return props[p_name].initial != props[p_name].variant; } -Variant GlobalConfig::property_get_revert(const String& p_name) { +Variant GlobalConfig::property_get_revert(const String &p_name) { if (!props.has(p_name)) return Variant(); @@ -869,150 +819,140 @@ Variant GlobalConfig::property_get_revert(const String& p_name) { void GlobalConfig::_bind_methods() { - ClassDB::bind_method(D_METHOD("has","name"),&GlobalConfig::has); - ClassDB::bind_method(D_METHOD("set_order","name","pos"),&GlobalConfig::set_order); - ClassDB::bind_method(D_METHOD("get_order","name"),&GlobalConfig::get_order); - ClassDB::bind_method(D_METHOD("set_initial_value","name","value"),&GlobalConfig::set_initial_value); - ClassDB::bind_method(D_METHOD("add_property_info", "hint"),&GlobalConfig::_add_property_info_bind); - ClassDB::bind_method(D_METHOD("clear","name"),&GlobalConfig::clear); - ClassDB::bind_method(D_METHOD("localize_path","path"),&GlobalConfig::localize_path); - ClassDB::bind_method(D_METHOD("globalize_path","path"),&GlobalConfig::globalize_path); - ClassDB::bind_method(D_METHOD("save"),&GlobalConfig::save); - ClassDB::bind_method(D_METHOD("has_singleton","name"),&GlobalConfig::has_singleton); - ClassDB::bind_method(D_METHOD("get_singleton","name"),&GlobalConfig::get_singleton_object); - ClassDB::bind_method(D_METHOD("load_resource_pack","pack"),&GlobalConfig::_load_resource_pack); - ClassDB::bind_method(D_METHOD("property_can_revert","name"),&GlobalConfig::property_can_revert); - ClassDB::bind_method(D_METHOD("property_get_revert","name"),&GlobalConfig::property_get_revert); - - ClassDB::bind_method(D_METHOD("save_custom","file"),&GlobalConfig::_save_custom_bnd); + ClassDB::bind_method(D_METHOD("has", "name"), &GlobalConfig::has); + ClassDB::bind_method(D_METHOD("set_order", "name", "pos"), &GlobalConfig::set_order); + ClassDB::bind_method(D_METHOD("get_order", "name"), &GlobalConfig::get_order); + ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value"), &GlobalConfig::set_initial_value); + ClassDB::bind_method(D_METHOD("add_property_info", "hint"), &GlobalConfig::_add_property_info_bind); + ClassDB::bind_method(D_METHOD("clear", "name"), &GlobalConfig::clear); + ClassDB::bind_method(D_METHOD("localize_path", "path"), &GlobalConfig::localize_path); + ClassDB::bind_method(D_METHOD("globalize_path", "path"), &GlobalConfig::globalize_path); + ClassDB::bind_method(D_METHOD("save"), &GlobalConfig::save); + ClassDB::bind_method(D_METHOD("has_singleton", "name"), &GlobalConfig::has_singleton); + ClassDB::bind_method(D_METHOD("get_singleton", "name"), &GlobalConfig::get_singleton_object); + ClassDB::bind_method(D_METHOD("load_resource_pack", "pack"), &GlobalConfig::_load_resource_pack); + ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &GlobalConfig::property_can_revert); + ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &GlobalConfig::property_get_revert); + ClassDB::bind_method(D_METHOD("save_custom", "file"), &GlobalConfig::_save_custom_bnd); } GlobalConfig::GlobalConfig() { - - 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::JOYPAD_BUTTON; - - - GLOBAL_DEF("application/name","" ); - GLOBAL_DEF("application/main_scene",""); - custom_prop_info["application/main_scene"]=PropertyInfo(Variant::STRING,"application/main_scene",PROPERTY_HINT_FILE,"tscn,scn,xscn,xml,res"); - GLOBAL_DEF("application/disable_stdout",false); - GLOBAL_DEF("application/disable_stderr",false); - GLOBAL_DEF("application/use_shared_user_dir",true); + joyb.type = InputEvent::JOYPAD_BUTTON; + GLOBAL_DEF("application/name", ""); + GLOBAL_DEF("application/main_scene", ""); + custom_prop_info["application/main_scene"] = PropertyInfo(Variant::STRING, "application/main_scene", PROPERTY_HINT_FILE, "tscn,scn,xscn,xml,res"); + GLOBAL_DEF("application/disable_stdout", false); + GLOBAL_DEF("application/disable_stderr", false); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_accept",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_select",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_cancel",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_focus_next",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_focus_prev",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_left",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_right",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_up",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_down",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_page_up",va); + GLOBAL_DEF("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); - GLOBAL_DEF("input/ui_page_down",va); + GLOBAL_DEF("input/ui_page_down", va); input_presets.push_back("input/ui_page_down"); //GLOBAL_DEF("display/handheld/orientation", "landscape"); + custom_prop_info["display/handheld/orientation"] = PropertyInfo(Variant::STRING, "display/handheld/orientation", PROPERTY_HINT_ENUM, "landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor"); + custom_prop_info["rendering/threads/thread_model"] = PropertyInfo(Variant::INT, "rendering/threads/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/handheld/orientation"]=PropertyInfo(Variant::STRING,"display/handheld/orientation",PROPERTY_HINT_ENUM,"landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor"); - custom_prop_info["rendering/threads/thread_model"]=PropertyInfo(Variant::INT,"rendering/threads/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"); - - GLOBAL_DEF("debug/profiler/max_functions",16384); - using_datapack=false; + GLOBAL_DEF("debug/profiler/max_functions", 16384); + using_datapack = false; } - GlobalConfig::~GlobalConfig() { - singleton=NULL; + singleton = NULL; } - - diff --git a/core/global_config.h b/core/global_config.h index 471f1ff885..7bdf356129 100644 --- a/core/global_config.h +++ b/core/global_config.h @@ -30,32 +30,32 @@ #define GLOBAL_CONFIG_H #include "object.h" -#include "set.h" #include "os/thread_safe.h" +#include "set.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - class GlobalConfig : public Object { - GDCLASS( GlobalConfig, Object ); + GDCLASS(GlobalConfig, Object); _THREAD_SAFE_CLASS_ public: - - typedef Map<String,Variant> CustomMap; + typedef Map<String, Variant> 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 { @@ -65,22 +65,32 @@ protected: Variant initial; 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<StringName,VariantContainer> props; + Map<StringName, VariantContainer> props; String resource_path; - Map<StringName,PropertyInfo> custom_prop_info; + Map<StringName, PropertyInfo> custom_prop_info; bool disable_platform_override; bool using_datapack; List<String> 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<PropertyInfo> *p_list) const; static GlobalConfig *singleton; @@ -88,58 +98,55 @@ 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<String,List<String> > &props,const CustomMap& p_custom=CustomMap()); - Error _save_settings_binary(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom=CustomMap()); + Error _save_settings_text(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom = CustomMap()); + Error _save_settings_binary(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom = CustomMap()); List<Singleton> singletons; - Map<StringName,Object*> singleton_ptrs; + Map<StringName, Object *> singleton_ptrs; - 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: - +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_initial_value(const String& p_name, const Variant & p_value); - bool property_can_revert(const String& p_name); - Variant property_get_revert(const String& p_name); + void set_initial_value(const String &p_name, const Variant &p_value); + bool property_can_revert(const String &p_name); + Variant property_get_revert(const String &p_name); String get_resource_path() const; static GlobalConfig *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<String>& p_ignore_masks=Set<String>()); + Error save_custom(const String &p_path = "", const CustomMap &p_custom = CustomMap(), const Set<String> &p_ignore_masks = Set<String>()); 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<Singleton> *p_singletons); - bool has_singleton(const String& p_name) const; + bool has_singleton(const String &p_name) const; Vector<String> get_optimizer_presets() const; List<String> 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(); @@ -149,12 +156,11 @@ public: GlobalConfig(); ~GlobalConfig(); - }; //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) #define GLOBAL_GET(m_var) GlobalConfig::get_singleton()->get(m_var) #endif diff --git a/core/global_constants.cpp b/core/global_constants.cpp index be811ccbd2..c7f353ac44 100644 --- a/core/global_constants.cpp +++ b/core/global_constants.cpp @@ -28,9 +28,9 @@ /*************************************************************************/ #include "global_constants.h" -#include "variant.h" -#include "os/keyboard.h" #include "object.h" +#include "os/keyboard.h" +#include "variant.h" struct _GlobalConstant { @@ -38,519 +38,515 @@ 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( 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_DIVISION ), - BIND_GLOBAL_CONSTANT( KEY_YDIAERESIS ), - - 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(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_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_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), // 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), //joypads - 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_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_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_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_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_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_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_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_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_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_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_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( ERR_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_LAYERS_2D_RENDER ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_2D_PHYSICS ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_3D_RENDER ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_3D_PHYSICS), - - 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_GROUP ), - 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_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_TRANSFORM2D",Variant::TRANSFORM2D}, - {"TYPE_PLANE",Variant::PLANE}, - {"TYPE_QUAT",Variant::QUAT}, // 10 - {"TYPE_RECT3",Variant::RECT3}, //sorry naming convention fail :( not like it's used often - {"TYPE_BASIS",Variant::BASIS}, - {"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::POOL_BYTE_ARRAY}, - {"TYPE_INT_ARRAY",Variant::POOL_INT_ARRAY}, - {"TYPE_REAL_ARRAY",Variant::POOL_REAL_ARRAY}, - {"TYPE_STRING_ARRAY",Variant::POOL_STRING_ARRAY}, // 25 - {"TYPE_VECTOR2_ARRAY",Variant::POOL_VECTOR2_ARRAY}, - {"TYPE_VECTOR3_ARRAY",Variant::POOL_VECTOR3_ARRAY}, - {"TYPE_COLOR_ARRAY",Variant::POOL_COLOR_ARRAY}, - {"TYPE_MAX",Variant::VARIANT_MAX}, - {NULL,0} + 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(ERR_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_LAYERS_2D_RENDER), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_2D_PHYSICS), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_3D_RENDER), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_3D_PHYSICS), + + 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_GROUP), + 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_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_TRANSFORM2D", Variant::TRANSFORM2D }, + { "TYPE_PLANE", Variant::PLANE }, + { "TYPE_QUAT", Variant::QUAT }, // 10 + { "TYPE_RECT3", Variant::RECT3 }, //sorry naming convention fail :( not like it's used often + { "TYPE_BASIS", Variant::BASIS }, + { "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::POOL_BYTE_ARRAY }, + { "TYPE_INT_ARRAY", Variant::POOL_INT_ARRAY }, + { "TYPE_REAL_ARRAY", Variant::POOL_REAL_ARRAY }, + { "TYPE_STRING_ARRAY", Variant::POOL_STRING_ARRAY }, // 25 + { "TYPE_VECTOR2_ARRAY", Variant::POOL_VECTOR2_ARRAY }, + { "TYPE_VECTOR3_ARRAY", Variant::POOL_VECTOR3_ARRAY }, + { "TYPE_COLOR_ARRAY", Variant::POOL_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) { @@ -562,5 +558,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 3270dcd151..8823ebf3b0 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/hash_map.h b/core/hash_map.h index 515fc6c4fe..645e34e923 100644 --- a/core/hash_map.h +++ b/core/hash_map.h @@ -29,42 +29,42 @@ #ifndef HASH_MAP_H #define HASH_MAP_H +#include "error_macros.h" #include "hashfuncs.h" +#include "list.h" #include "math_funcs.h" -#include "error_macros.h" -#include "ustring.h" #include "os/memory.h" -#include "list.h" +#include "ustring.h" struct HashMapHasherDefault { - 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) { return hash_one_uint64(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) { return hash_one_uint64(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 float p_float) { return hash_djb2_one_float(p_float); } - static _FORCE_INLINE_ uint32_t hash(const double p_double){ return hash_djb2_one_float(p_double); } + static _FORCE_INLINE_ uint32_t hash(const int64_t p_int) { return hash(uint64_t(p_int)); } + static _FORCE_INLINE_ uint32_t hash(const float p_float) { return hash_djb2_one_float(p_float); } + static _FORCE_INLINE_ uint32_t hash(const double p_double) { return hash_djb2_one_float(p_double); } 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 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 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); } }; template <typename T> struct HashMapComparatorDefault { - static bool compare(const T& p_lhs, const T& p_rhs) { + static bool compare(const T &p_lhs, const T &p_rhs) { return p_lhs == p_rhs; } - bool compare(const float& p_lhs, const float& p_rhs) { + bool compare(const float &p_lhs, const float &p_rhs) { return (p_lhs == p_rhs) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs)); } - bool compare(const double& p_lhs, const double& p_rhs) { + bool compare(const double &p_lhs, const double &p_rhs) { return (p_lhs == p_rhs) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs)); } }; @@ -86,20 +86,21 @@ struct HashMapComparatorDefault { * */ -template<class TKey, class TData, class Hasher=HashMapHasherDefault, class Comparator=HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER=3,uint8_t RELATIONSHIP=8> +template <class TKey, class TData, class Hasher = HashMapHasherDefault, class Comparator = HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER = 3, uint8_t RELATIONSHIP = 8> 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 { @@ -107,7 +108,7 @@ private: Entry *next; Pair pair; - Entry() { next=0; } + Entry() { next = 0; } }; Entry **hash_table; @@ -116,204 +117,191 @@ private: void make_hash_table() { - ERR_FAIL_COND( hash_table ); - + ERR_FAIL_COND(hash_table); - hash_table = memnew_arr( Entry*, (1<<MIN_HASH_TABLE_POWER) ); + hash_table = memnew_arr(Entry *, (1 << MIN_HASH_TABLE_POWER)); hash_table_power = MIN_HASH_TABLE_POWER; - elements=0; - for (int i=0;i<(1<<MIN_HASH_TABLE_POWER);i++) - hash_table[i]=0; + elements = 0; + for (int i = 0; i < (1 << MIN_HASH_TABLE_POWER); i++) + hash_table[i] = 0; } void erase_hash_table() { ERR_FAIL_COND(elements); - memdelete_arr( hash_table ); - hash_table=0; - hash_table_power=0; - elements=0; + memdelete_arr(hash_table); + hash_table = 0; + hash_table_power = 0; + elements = 0; } void check_hash_table() { - int new_hash_table_power=-1; + int new_hash_table_power = -1; - if ((int)elements > ( (1<<hash_table_power) * RELATIONSHIP ) ) { + if ((int)elements > ((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<<new_hash_table_power) * RELATIONSHIP ) ) { + while ((int)elements > ((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<<new_hash_table_power) ); + Entry **new_hash_table = memnew_arr(Entry *, (1 << new_hash_table_power)); if (!new_hash_table) { ERR_PRINT("Out of Memory"); return; } - for (int i=0;i<(1<<new_hash_table_power);i++) { + for (int i = 0; i < (1 << new_hash_table_power); i++) { - new_hash_table[i]=0; + new_hash_table[i] = 0; } - for (int i=0;i<(1<<hash_table_power);i++) { + for (int i = 0; i < (1 << hash_table_power); i++) { - while( hash_table[i] ) { + while (hash_table[i]) { - 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; + 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_table_power)-1); + uint32_t hash = Hasher::hash(p_key); + uint32_t index = hash & ((1 << hash_table_power) - 1); Entry *e = hash_table[index]; while (e) { /* checking hash first avoids comparing key, which may take longer */ - if (e->hash == hash && Comparator::compare(e->pair.key,p_key) ) { + if (e->hash == hash && Comparator::compare(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<<hash_table_power)-1); + 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 << hash_table_power) - 1); e->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<<p_t.hash_table_power); - hash_table_power=p_t.hash_table_power; - elements=p_t.elements; + hash_table = memnew_arr(Entry *, 1 << p_t.hash_table_power); + hash_table_power = p_t.hash_table_power; + elements = p_t.elements; - for (int i=0;i<( 1<<p_t.hash_table_power );i++) { + for (int i = 0; i < (1 << p_t.hash_table_power); i++) { - hash_table[i]=NULL; + hash_table[i] = NULL; const Entry *e = p_t.hash_table[i]; - while(e) { + while (e) { - Entry *le = memnew( Entry ); /* local entry */ + Entry *le = memnew(Entry); /* local entry */ - *le=*e; /* copy data */ + *le = *e; /* copy data */ /* add to list and reassign pointers */ - le->next=hash_table[i]; - hash_table[i]=le; + le->next = hash_table[i]; + hash_table[i] = le; - e=e->next; + e = e->next; } - - } - - } -public: +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<Entry*>( get_entry(p_pair.key) ); + e = const_cast<Entry *>(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; } /** @@ -322,17 +310,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; } @@ -341,33 +329,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<Entry*>(get_entry(p_key )); + Entry *e = const_cast<Entry *>(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<Entry*>(get_entry(p_key )); + const Entry *e = const_cast<Entry *>(get_entry(p_key)); if (e) return &e->pair.data; return NULL; - } /** @@ -375,129 +360,124 @@ public: * This version is custom, will take a hash and a custom key (that should support operator==() */ - template<class C> - _FORCE_INLINE_ TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) { + template <class C> + _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_table_power)-1); + uint32_t index = hash & ((1 << hash_table_power) - 1); Entry *e = hash_table[index]; while (e) { /* checking hash first avoids comparing key, which may take longer */ - if (e->hash == hash && Comparator::compare(e->pair.key,p_custom_key) ) { + if (e->hash == hash && Comparator::compare(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<class C> - _FORCE_INLINE_ const TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) const { + template <class C> + _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_table_power)-1); + uint32_t index = hash & ((1 << hash_table_power) - 1); const Entry *e = hash_table[index]; while (e) { /* checking hash first avoids comparing key, which may take longer */ - if (e->hash == hash && Comparator::compare(e->pair.key,p_custom_key) ) { + if (e->hash == hash && Comparator::compare(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_table_power)-1); - + uint32_t hash = Hasher::hash(p_key); + uint32_t index = hash & ((1 << hash_table_power) - 1); Entry *e = hash_table[index]; - Entry *p=NULL; + Entry *p = NULL; while (e) { /* checking hash first avoids comparing key, which may take longer */ - if (e->hash == hash && Comparator::compare(e->pair.key,p_key) ) { + if (e->hash == hash && Comparator::compare(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<Entry*>( get_entry(p_key) ); + e = const_cast<Entry *>(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; - } /** @@ -515,13 +495,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<<hash_table_power);i++) { + for (int i = 0; i < (1 << hash_table_power); i++) { if (hash_table[i]) { return &hash_table[i]->pair.key; @@ -530,17 +510,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_table_power)-1); + uint32_t index = e->hash & ((1 << hash_table_power) - 1); index++; - for (int i=index;i<(1<<hash_table_power);i++) { + for (int i = index; i < (1 << hash_table_power); i++) { if (hash_table[i]) { return &hash_table[i]->pair.key; @@ -549,10 +529,8 @@ public: } /* nothing found, was at end */ - } - return NULL; /* nothing found */ } @@ -563,53 +541,52 @@ public: inline bool empty() const { - return elements==0; + return elements == 0; } void clear() { /* clean up */ if (hash_table) { - for (int i=0;i<(1<<hash_table_power);i++) { + for (int i = 0; i < (1 << hash_table_power); i++) { while (hash_table[i]) { - Entry *e=hash_table[i]; - hash_table[i]=e->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_value_ptr_array(const Pair **p_pairs) const { if (!hash_table) return; - for(int i=0;i<(1<<hash_table_power);i++) { + for (int i = 0; i < (1 << hash_table_power); i++) { - Entry *e=hash_table[i]; - while(e) { - *p_pairs=&e->pair; + Entry *e = hash_table[i]; + while (e) { + *p_pairs = &e->pair; p_pairs++; - e=e->next; + e = e->next; } } } @@ -617,24 +594,23 @@ public: void get_key_list(List<TKey> *p_keys) const { if (!hash_table) return; - for(int i=0;i<(1<<hash_table_power);i++) { + for (int i = 0; i < (1 << hash_table_power); i++) { - Entry *e=hash_table[i]; - while(e) { + Entry *e = hash_table[i]; + while (e) { p_keys->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() { @@ -643,6 +619,4 @@ public: } }; - - #endif diff --git a/core/hashfuncs.h b/core/hashfuncs.h index 121d7e8c59..aff6772d68 100644 --- a/core/hashfuncs.h +++ b/core/hashfuncs.h @@ -29,15 +29,14 @@ #ifndef HASHFUNCS_H #define HASHFUNCS_H -#include "math_funcs.h" #include "math_defs.h" +#include "math_funcs.h" #include "typedefs.h" /** * Hashing functions */ - /** * DJB2 Hash function * @param C String @@ -45,7 +44,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; @@ -55,99 +54,95 @@ 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<p_len;i++) + for (int i = 0; i < p_len; i++) hash = ((hash << 5) + hash) + p_buff[i]; /* hash * 33 + c */ return hash; } -static inline uint32_t hash_djb2_one_32(uint32_t p_in,uint32_t p_prev=5381) { +static inline uint32_t hash_djb2_one_32(uint32_t p_in, uint32_t p_prev = 5381) { - return ((p_prev<<5)+p_prev)+p_in; + return ((p_prev << 5) + p_prev) + p_in; } static inline uint32_t hash_one_uint64(const uint64_t p_int) { - uint64_t v=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 inline uint32_t hash_djb2_one_float(float p_in,uint32_t p_prev=5381) { +static inline uint32_t hash_djb2_one_float(float p_in, uint32_t p_prev = 5381) { union { float f; uint32_t i; } u; // Normalize +/- 0.0 and NaN values so they hash the same. - if (p_in==0.0f) - u.f=0.0; + if (p_in == 0.0f) + u.f = 0.0; else if (Math::is_nan(p_in)) - u.f=Math_NAN; + u.f = Math_NAN; else - u.f=p_in; + u.f = p_in; - return ((p_prev<<5)+p_prev)+u.i; + return ((p_prev << 5) + p_prev) + u.i; } // Overload for real_t size changes -static inline uint32_t hash_djb2_one_float(double p_in,uint32_t p_prev=5381) { +static inline uint32_t hash_djb2_one_float(double p_in, uint32_t p_prev = 5381) { union { double d; uint64_t i; } u; // Normalize +/- 0.0 and NaN values so they hash the same. - if (p_in==0.0f) - u.d=0.0; + if (p_in == 0.0f) + u.d = 0.0; else if (Math::is_nan(p_in)) - u.d=Math_NAN; + u.d = Math_NAN; else - u.d=p_in; + u.d = p_in; - return ((p_prev<<5)+p_prev) + hash_one_uint64(u.i); + return ((p_prev << 5) + p_prev) + hash_one_uint64(u.i); } -template<class T> +template <class T> 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<class T> +template <class T> 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 1ea754b70f..377a3f8234 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()) { @@ -169,7 +174,7 @@ Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const ERR_FAIL_V(p_target); } - /* clang-format on */ + /* clang-format on */ } } diff --git a/core/helper/math_fieldwise.h b/core/helper/math_fieldwise.h index 31f9af8d0b..e73227f148 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 9ea03db4c6..e001e1646a 100644 --- a/core/helper/value_evaluator.h +++ b/core/helper/value_evaluator.h @@ -34,8 +34,9 @@ class ValueEvaluator : public Object { GDCLASS(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 037ff82452..649a51c174 100644 --- a/core/image.cpp +++ b/core/image.cpp @@ -28,16 +28,15 @@ /*************************************************************************/ #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 <stdio.h> - -const char* Image::format_names[Image::FORMAT_MAX]={ +const char *Image::format_names[Image::FORMAT_MAX] = { "Lum8", //luminance "LumAlpha8", //luminance-alpha "Red8", @@ -80,113 +79,124 @@ const char* Image::format_names[Image::FORMAT_MAX]={ SavePNGFunc Image::save_png_func = NULL; +void Image::_put_pixelb(int p_x, int p_y, uint32_t p_pixelsize, uint8_t *p_dst, const uint8_t *p_src) { -void Image::_put_pixelb(int p_x,int p_y, uint32_t p_pixelsize,uint8_t *p_dst,const uint8_t *p_src) { + uint32_t ofs = (p_y * width + p_x) * p_pixelsize; - - uint32_t ofs=(p_y*width+p_x)*p_pixelsize; - - for(uint32_t i=0;i<p_pixelsize;i++) { - p_dst[ofs+i]=p_src[i]; + for (uint32_t i = 0; i < p_pixelsize; i++) { + p_dst[ofs + i] = p_src[i]; } } -void Image::_get_pixelb(int p_x,int p_y, uint32_t p_pixelsize,const uint8_t *p_src,uint8_t *p_dst) { +void Image::_get_pixelb(int p_x, int p_y, uint32_t p_pixelsize, const uint8_t *p_src, uint8_t *p_dst) { - uint32_t ofs=(p_y*width+p_x)*p_pixelsize; + uint32_t ofs = (p_y * width + p_x) * p_pixelsize; - for(uint32_t i=0;i<p_pixelsize;i++) { - p_dst[ofs]=p_src[ofs+i]; + for (uint32_t i = 0; i < p_pixelsize; i++) { + p_dst[ofs] = p_src[ofs + i]; } - } - int Image::get_format_pixel_size(Format p_format) { - switch(p_format) { - case FORMAT_L8: return 1; //luminance - case FORMAT_LA8: return 2; //luminance-alpha + switch (p_format) { + case FORMAT_L8: + return 1; //luminance + case FORMAT_LA8: + return 2; //luminance-alpha case FORMAT_R8: return 1; case FORMAT_RG8: return 2; case FORMAT_RGB8: return 3; case FORMAT_RGBA8: return 4; - case FORMAT_RGB565: return 2; //16 bit + case FORMAT_RGB565: + return 2; //16 bit case FORMAT_RGBA4444: return 2; case FORMAT_RGBA5551: return 2; - case FORMAT_RF: return 4; //float + case FORMAT_RF: + return 4; //float case FORMAT_RGF: return 8; case FORMAT_RGBF: return 12; case FORMAT_RGBAF: return 16; - case FORMAT_RH: return 2; //half float + case FORMAT_RH: + return 2; //half float case FORMAT_RGH: return 4; case FORMAT_RGBH: return 8; case FORMAT_RGBAH: return 12; - case FORMAT_DXT1: return 1; //s3tc bc1 - case FORMAT_DXT3: return 1; //bc2 - case FORMAT_DXT5: return 1; //bc3 - case FORMAT_ATI1: return 1; //bc4 - case FORMAT_ATI2: return 1; //bc5 - case FORMAT_BPTC_RGBA: return 1; //btpc bc6h - case FORMAT_BPTC_RGBF: return 1; //float / - case FORMAT_BPTC_RGBFU: return 1; //unsigned float - case FORMAT_PVRTC2: return 1; //pvrtc + case FORMAT_DXT1: + return 1; //s3tc bc1 + case FORMAT_DXT3: + return 1; //bc2 + case FORMAT_DXT5: + return 1; //bc3 + case FORMAT_ATI1: + return 1; //bc4 + case FORMAT_ATI2: + return 1; //bc5 + case FORMAT_BPTC_RGBA: + return 1; //btpc bc6h + case FORMAT_BPTC_RGBF: + return 1; //float / + case FORMAT_BPTC_RGBFU: + return 1; //unsigned float + case FORMAT_PVRTC2: + return 1; //pvrtc case FORMAT_PVRTC2A: return 1; case FORMAT_PVRTC4: return 1; case FORMAT_PVRTC4A: return 1; - case FORMAT_ETC: return 1; //etc1 - case FORMAT_ETC2_R11: return 1; //etc2 - case FORMAT_ETC2_R11S: return 1; //signed: return 1; NOT srgb. + case FORMAT_ETC: + return 1; //etc1 + case FORMAT_ETC2_R11: + return 1; //etc2 + case FORMAT_ETC2_R11S: + return 1; //signed: return 1; NOT srgb. case FORMAT_ETC2_RG11: return 1; case FORMAT_ETC2_RG11S: return 1; case FORMAT_ETC2_RGB8: return 1; case FORMAT_ETC2_RGBA8: return 1; case FORMAT_ETC2_RGB8A1: return 1; - case FORMAT_MAX: {} - - + case FORMAT_MAX: { + } } return 0; } -void Image::get_format_min_pixel_size(Format p_format,int &r_w, int &r_h) { - +void Image::get_format_min_pixel_size(Format p_format, int &r_w, int &r_h) { - switch(p_format) { + switch (p_format) { case FORMAT_DXT1: //s3tc bc1 case FORMAT_DXT3: //bc2 case FORMAT_DXT5: //bc3 case FORMAT_ATI1: //bc4 case FORMAT_ATI2: { //bc5 case case FORMAT_DXT1: - r_w=4; - r_h=4; + r_w = 4; + r_h = 4; } break; case FORMAT_PVRTC2: case FORMAT_PVRTC2A: { - r_w=16; - r_h=8; + r_w = 16; + r_h = 8; } break; case FORMAT_PVRTC4A: case FORMAT_PVRTC4: { - 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; case FORMAT_BPTC_RGBA: case FORMAT_BPTC_RGBF: case FORMAT_BPTC_RGBFU: { - r_w=4; - r_h=4; + r_w = 4; + r_h = 4; } break; - case FORMAT_ETC2_R11: //etc2 + case FORMAT_ETC2_R11: //etc2 case FORMAT_ETC2_R11S: //signed: NOT srgb. case FORMAT_ETC2_RG11: case FORMAT_ETC2_RG11S: @@ -194,85 +204,79 @@ void Image::get_format_min_pixel_size(Format p_format,int &r_w, int &r_h) { case FORMAT_ETC2_RGBA8: case FORMAT_ETC2_RGB8A1: { - 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_DXT1 || p_format==FORMAT_ATI1 || p_format==FORMAT_PVRTC4 || p_format==FORMAT_PVRTC4A || p_format==FORMAT_ETC || p_format==FORMAT_ETC2_R11 || p_format==FORMAT_ETC2_R11S || p_format==FORMAT_ETC2_RGB8 || p_format==FORMAT_ETC2_RGB8A1) + if (p_format == FORMAT_DXT1 || p_format == FORMAT_ATI1 || p_format == FORMAT_PVRTC4 || p_format == FORMAT_PVRTC4A || p_format == FORMAT_ETC || p_format == FORMAT_ETC2_R11 || p_format == FORMAT_ETC2_R11S || p_format == FORMAT_ETC2_RGB8 || p_format == FORMAT_ETC2_RGB8A1) return 1; - else if (p_format==FORMAT_PVRTC2 || p_format==FORMAT_PVRTC2A) + else if (p_format == FORMAT_PVRTC2 || p_format == FORMAT_PVRTC2A) return 2; else return 0; } +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_pixel_size(format,minw,minh); - - 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); + int minw, minh; + get_format_min_pixel_size(format, minw, minh); + + 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,get_mipmap_count()+1,-1); + ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 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; } int Image::get_width() const { @@ -280,7 +284,7 @@ int Image::get_width() const { return width; } -int Image::get_height() const{ +int Image::get_height() const { return height; } @@ -293,77 +297,70 @@ bool Image::has_mipmaps() const { int Image::get_mipmap_count() const { if (mipmaps) - return get_image_required_mipmaps(width,height,format); + return get_image_required_mipmaps(width, height, format); else return 0; } - //using template generates perfectly optimized code due to constant expression reduction and unused variable removal present in all compilers -template<uint32_t read_bytes,bool read_alpha,uint32_t write_bytes,bool write_alpha,bool read_gray,bool write_gray> -static void _convert( int p_width,int p_height,const uint8_t* p_src,uint8_t* p_dst ){ - - +template <uint32_t read_bytes, bool read_alpha, uint32_t write_bytes, bool write_alpha, bool read_gray, bool write_gray> +static void _convert(int p_width, int p_height, const uint8_t *p_src, uint8_t *p_dst) { - for(int y=0;y<p_height;y++) { - for(int x=0;x<p_width;x++) { + for (int y = 0; y < p_height; y++) { + for (int x = 0; x < p_width; x++) { - const uint8_t *rofs = &p_src[((y*p_width)+x)*(read_bytes+(read_alpha?1:0))]; - uint8_t *wofs = &p_dst[((y*p_width)+x)*(write_bytes+(write_alpha?1:0))]; + const uint8_t *rofs = &p_src[((y * p_width) + x) * (read_bytes + (read_alpha ? 1 : 0))]; + uint8_t *wofs = &p_dst[((y * p_width) + x) * (write_bytes + (write_alpha ? 1 : 0))]; uint8_t rgba[4]; if (read_gray) { - rgba[0]=rofs[0]; - rgba[1]=rofs[0]; - rgba[2]=rofs[0]; + rgba[0] = rofs[0]; + rgba[1] = rofs[0]; + rgba[2] = rofs[0]; } else { - for(uint32_t i=0;i<MAX(read_bytes,write_bytes);i++) { + for (uint32_t i = 0; i < MAX(read_bytes, write_bytes); i++) { - rgba[i]=(i<read_bytes)?rofs[i]:0; + rgba[i] = (i < read_bytes) ? rofs[i] : 0; } } if (read_alpha || write_alpha) { - rgba[3]=read_alpha?rofs[read_bytes]:255; + rgba[3] = read_alpha ? rofs[read_bytes] : 255; } if (write_gray) { //TODO: not correct grayscale, should use fixed point version of actual weights - wofs[0]=uint8_t((uint16_t(rofs[0])+uint16_t(rofs[1])+uint16_t(rofs[2]))/3); + wofs[0] = uint8_t((uint16_t(rofs[0]) + uint16_t(rofs[1]) + uint16_t(rofs[2])) / 3); } else { - for(uint32_t i=0;i<write_bytes;i++) { + for (uint32_t i = 0; i < write_bytes; i++) { - wofs[i]=rgba[i]; + wofs[i] = rgba[i]; } } if (write_alpha) { - wofs[write_bytes]=rgba[3]; + wofs[write_bytes] = rgba[3]; } - } } - } -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_RGB565 || p_new_format>=FORMAT_RGB565) { + if (format >= FORMAT_RGB565 || p_new_format >= FORMAT_RGB565) { ERR_EXPLAIN("Cannot convert to <-> from non byte formats."); ERR_FAIL(); } - - Image new_img(width,height,0,p_new_format); + Image new_img(width, height, 0, p_new_format); //int len=data.size(); @@ -373,179 +370,168 @@ void Image::convert( Format p_new_format ){ const uint8_t *rptr = r.ptr(); uint8_t *wptr = w.ptr(); - int conversion_type = format | p_new_format<<8; - - switch(conversion_type) { - - case FORMAT_L8|(FORMAT_LA8<<8): _convert<1,false,1,true,true,true>( width, height,rptr, wptr ); break; - case FORMAT_L8|(FORMAT_R8<<8): _convert<1,false,1,false,true,false>( width, height,rptr, wptr ); break; - case FORMAT_L8|(FORMAT_RG8<<8): _convert<1,false,2,false,true,false>( width, height,rptr, wptr ); break; - case FORMAT_L8|(FORMAT_RGB8<<8): _convert<1,false,3,false,true,false>( width, height,rptr, wptr ); break; - case FORMAT_L8|(FORMAT_RGBA8<<8): _convert<1,false,3,true,true,false>( width, height,rptr, wptr ); break; - case FORMAT_LA8|(FORMAT_L8<<8): _convert<1,true,1,false,true,true>( width, height,rptr, wptr ); break; - case FORMAT_LA8|(FORMAT_R8<<8): _convert<1,true,1,false,true,false>( width, height,rptr, wptr ); break; - case FORMAT_LA8|(FORMAT_RG8<<8): _convert<1,true,2,false,true,false>( width, height,rptr, wptr ); break; - case FORMAT_LA8|(FORMAT_RGB8<<8): _convert<1,true,3,false,true,false>( width, height,rptr, wptr ); break; - case FORMAT_LA8|(FORMAT_RGBA8<<8): _convert<1,true,3,true,true,false>( width, height,rptr, wptr ); break; - case FORMAT_R8|(FORMAT_L8<<8): _convert<1,false,1,false,false,true>( width, height,rptr, wptr ); break; - case FORMAT_R8|(FORMAT_LA8<<8): _convert<1,false,1,true,false,true>( width, height,rptr, wptr ); break; - case FORMAT_R8|(FORMAT_RG8<<8): _convert<1,false,2,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_R8|(FORMAT_RGB8<<8): _convert<1,false,3,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_R8|(FORMAT_RGBA8<<8): _convert<1,false,3,true,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RG8|(FORMAT_L8<<8): _convert<2,false,1,false,false,true>( width, height,rptr, wptr ); break; - case FORMAT_RG8|(FORMAT_LA8<<8): _convert<2,false,1,true,false,true>( width, height,rptr, wptr ); break; - case FORMAT_RG8|(FORMAT_R8<<8): _convert<2,false,1,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RG8|(FORMAT_RGB8<<8): _convert<2,false,3,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RG8|(FORMAT_RGBA8<<8): _convert<2,false,3,true,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RGB8|(FORMAT_L8<<8): _convert<3,false,1,false,false,true>( width, height,rptr, wptr ); break; - case FORMAT_RGB8|(FORMAT_LA8<<8): _convert<3,false,1,true,false,true>( width, height,rptr, wptr ); break; - case FORMAT_RGB8|(FORMAT_R8<<8): _convert<3,false,1,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RGB8|(FORMAT_RG8<<8): _convert<3,false,2,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RGB8|(FORMAT_RGBA8<<8): _convert<3,false,3,true,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RGBA8|(FORMAT_L8<<8): _convert<3,true,1,false,false,true>( width, height,rptr, wptr ); break; - case FORMAT_RGBA8|(FORMAT_LA8<<8): _convert<3,true,1,true,false,true>( width, height,rptr, wptr ); break; - case FORMAT_RGBA8|(FORMAT_R8<<8): _convert<3,true,1,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RGBA8|(FORMAT_RG8<<8): _convert<3,true,2,false,false,false>( width, height,rptr, wptr ); break; - case FORMAT_RGBA8|(FORMAT_RGB8<<8): _convert<3,true,3,false,false,false>( width, height,rptr, wptr ); break; - + int conversion_type = format | p_new_format << 8; + + switch (conversion_type) { + + case FORMAT_L8 | (FORMAT_LA8 << 8): _convert<1, false, 1, true, true, true>(width, height, rptr, wptr); break; + case FORMAT_L8 | (FORMAT_R8 << 8): _convert<1, false, 1, false, true, false>(width, height, rptr, wptr); break; + case FORMAT_L8 | (FORMAT_RG8 << 8): _convert<1, false, 2, false, true, false>(width, height, rptr, wptr); break; + case FORMAT_L8 | (FORMAT_RGB8 << 8): _convert<1, false, 3, false, true, false>(width, height, rptr, wptr); break; + case FORMAT_L8 | (FORMAT_RGBA8 << 8): _convert<1, false, 3, true, true, false>(width, height, rptr, wptr); break; + case FORMAT_LA8 | (FORMAT_L8 << 8): _convert<1, true, 1, false, true, true>(width, height, rptr, wptr); break; + case FORMAT_LA8 | (FORMAT_R8 << 8): _convert<1, true, 1, false, true, false>(width, height, rptr, wptr); break; + case FORMAT_LA8 | (FORMAT_RG8 << 8): _convert<1, true, 2, false, true, false>(width, height, rptr, wptr); break; + case FORMAT_LA8 | (FORMAT_RGB8 << 8): _convert<1, true, 3, false, true, false>(width, height, rptr, wptr); break; + case FORMAT_LA8 | (FORMAT_RGBA8 << 8): _convert<1, true, 3, true, true, false>(width, height, rptr, wptr); break; + case FORMAT_R8 | (FORMAT_L8 << 8): _convert<1, false, 1, false, false, true>(width, height, rptr, wptr); break; + case FORMAT_R8 | (FORMAT_LA8 << 8): _convert<1, false, 1, true, false, true>(width, height, rptr, wptr); break; + case FORMAT_R8 | (FORMAT_RG8 << 8): _convert<1, false, 2, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_R8 | (FORMAT_RGB8 << 8): _convert<1, false, 3, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_R8 | (FORMAT_RGBA8 << 8): _convert<1, false, 3, true, false, false>(width, height, rptr, wptr); break; + case FORMAT_RG8 | (FORMAT_L8 << 8): _convert<2, false, 1, false, false, true>(width, height, rptr, wptr); break; + case FORMAT_RG8 | (FORMAT_LA8 << 8): _convert<2, false, 1, true, false, true>(width, height, rptr, wptr); break; + case FORMAT_RG8 | (FORMAT_R8 << 8): _convert<2, false, 1, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_RG8 | (FORMAT_RGB8 << 8): _convert<2, false, 3, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_RG8 | (FORMAT_RGBA8 << 8): _convert<2, false, 3, true, false, false>(width, height, rptr, wptr); break; + case FORMAT_RGB8 | (FORMAT_L8 << 8): _convert<3, false, 1, false, false, true>(width, height, rptr, wptr); break; + case FORMAT_RGB8 | (FORMAT_LA8 << 8): _convert<3, false, 1, true, false, true>(width, height, rptr, wptr); break; + case FORMAT_RGB8 | (FORMAT_R8 << 8): _convert<3, false, 1, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_RGB8 | (FORMAT_RG8 << 8): _convert<3, false, 2, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_RGB8 | (FORMAT_RGBA8 << 8): _convert<3, false, 3, true, false, false>(width, height, rptr, wptr); break; + case FORMAT_RGBA8 | (FORMAT_L8 << 8): _convert<3, true, 1, false, false, true>(width, height, rptr, wptr); break; + case FORMAT_RGBA8 | (FORMAT_LA8 << 8): _convert<3, true, 1, true, false, true>(width, height, rptr, wptr); break; + case FORMAT_RGBA8 | (FORMAT_R8 << 8): _convert<3, true, 1, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_RGBA8 | (FORMAT_RG8 << 8): _convert<3, true, 2, false, false, false>(width, height, rptr, wptr); break; + case FORMAT_RGBA8 | (FORMAT_RGB8 << 8): _convert<3, true, 3, false, false, false>(width, height, rptr, wptr); break; } - r = PoolVector<uint8_t>::Read(); w = PoolVector<uint8_t>::Write(); - bool gen_mipmaps=mipmaps; + bool gen_mipmaps = mipmaps; //mipmaps=false; - *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<int CC> -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 <int CC> +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 ( uint32_t y = 0; y < p_dst_height; y++ ) { + for (uint32_t 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 ( uint32_t x = 0; x < p_dst_width; x++ ) { + for (uint32_t 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<CC;i++) { - color[i]=0; + for (int i = 0; i < CC; i++) { + color[i] = 0; } - - - for ( int n = -1; n < 3; n++ ) { + for (int n = -1; n < 3; n++) { // get Y cooefficient - k1 = _bicubic_interp_kernel( dy - (double) n ); + k1 = _bicubic_interp_kernel(dy - (double)n); oy2 = oy1 + n; - if ( oy2 < 0 ) + if (oy2 < 0) oy2 = 0; - if ( oy2 > 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<CC;i++) { + for (int i = 0; i < CC; i++) { - color[i]+=p[i]*k2; + color[i] += p[i] * k2; } } } - for(int i=0;i<CC;i++) { - dst[i]=CLAMP(Math::fast_ftoi(color[i]),0,255); + for (int i = 0; i < CC; i++) { + dst[i] = CLAMP(Math::fast_ftoi(color[i]), 0, 255); } } } } - - - -template<int CC> -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 <int CC> +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), - FRAC_MASK=FRAC_LEN-1 + FRAC_BITS = 8, + FRAC_LEN = (1 << FRAC_BITS), + FRAC_MASK = FRAC_LEN - 1 }; - for(uint32_t i=0;i<p_dst_height;i++) { + for (uint32_t i = 0; i < p_dst_height; i++) { - uint32_t src_yofs_up_fp = (i*p_src_height*FRAC_LEN/p_dst_height); + uint32_t src_yofs_up_fp = (i * p_src_height * FRAC_LEN / p_dst_height); uint32_t src_yofs_frac = src_yofs_up_fp & FRAC_MASK; uint32_t src_yofs_up = src_yofs_up_fp >> 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; @@ -553,60 +539,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<p_dst_width;j++) { + for (uint32_t j = 0; j < p_dst_width; j++) { - uint32_t src_xofs_left_fp = (j*p_src_width*FRAC_LEN/p_dst_width); + uint32_t src_xofs_left_fp = (j * p_src_width * FRAC_LEN / p_dst_width); uint32_t src_xofs_frac = src_xofs_left_fp & FRAC_MASK; uint32_t src_xofs_left = src_xofs_left_fp >> 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<CC;l++) { + for (uint32_t l = 0; l < CC; l++) { - uint32_t p00=p_src[y_ofs_up+src_xofs_left+l]<<FRAC_BITS; - uint32_t p10=p_src[y_ofs_up+src_xofs_right+l]<<FRAC_BITS; - uint32_t p01=p_src[y_ofs_down+src_xofs_left+l]<<FRAC_BITS; - uint32_t p11=p_src[y_ofs_down+src_xofs_right+l]<<FRAC_BITS; + uint32_t p00 = p_src[y_ofs_up + src_xofs_left + l] << FRAC_BITS; + uint32_t p10 = p_src[y_ofs_up + src_xofs_right + l] << FRAC_BITS; + uint32_t p01 = p_src[y_ofs_down + src_xofs_left + l] << FRAC_BITS; + uint32_t p11 = p_src[y_ofs_down + src_xofs_right + l] << FRAC_BITS; - 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; + 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 <int CC> +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<int CC> -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;i<p_dst_height;i++) { - - uint32_t src_yofs = i*p_src_height/p_dst_height; + uint32_t src_yofs = i * p_src_height / p_dst_height; uint32_t y_ofs = src_yofs * p_src_width * CC; - for(uint32_t j=0;j<p_dst_width;j++) { + for (uint32_t j = 0; j < p_dst_width; j++) { - uint32_t src_xofs = j*p_src_width/p_dst_width; - src_xofs*=CC; + uint32_t src_xofs = j * p_src_width / p_dst_width; + src_xofs *= CC; - for(uint32_t l=0;l<CC;l++) { + for (uint32_t l = 0; l < CC; l++) { - uint32_t p=p_src[y_ofs+src_xofs+l]; - p_dst[i*p_dst_width*CC+j*CC+l]=p; + uint32_t p = p_src[y_ofs + src_xofs + l]; + p_dst[i * p_dst_width * CC + j * CC + l] = p; } } } } - void Image::resize_to_po2(bool p_square) { if (!_can_modify(format)) { @@ -617,16 +600,16 @@ void Image::resize_to_po2(bool p_square) { int w = nearest_power_of_2(width); int h = nearest_power_of_2(height); - if (w==width && h==height) { + if (w == width && h == height) { - if (!p_square || w==h) + if (!p_square || w == h) return; //nothing to do } - resize(w,h); + resize(w, h); } -Image Image::resized( int p_width, int p_height, int p_interpolation ) { +Image Image::resized(int p_width, int p_height, int p_interpolation) { Image ret = *this; ret.resize(p_width, p_height, (Interpolation)p_interpolation); @@ -634,124 +617,116 @@ Image Image::resized( int p_width, int p_height, int p_interpolation ) { return ret; }; - -void Image::resize( int p_width, int p_height, Interpolation p_interpolation ) { +void Image::resize(int p_width, int p_height, Interpolation p_interpolation) { if (!_can_modify(format)) { ERR_EXPLAIN("Cannot resize 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); - 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); PoolVector<uint8_t>::Read r = data.read(); - const unsigned char*r_ptr=r.ptr(); + const unsigned char *r_ptr = r.ptr(); PoolVector<uint8_t>::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 = PoolVector<uint8_t>::Read(); w = PoolVector<uint8_t>::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; uint8_t pdata[16]; //largest is 16 uint32_t pixel_size = get_format_pixel_size(format); - Image dst( p_width, p_height,0, format ); + Image dst(p_width, p_height, 0, format); { PoolVector<uint8_t>::Read r = data.read(); PoolVector<uint8_t>::Write w = dst.data.write(); - for (int y=0;y<p_height;y++) { + for (int y = 0; y < p_height; y++) { - for (int x=0;x<p_width;x++) { + for (int x = 0; x < p_width; x++) { - if ((x>=width || y>=height)) { - for(uint32_t i=0;i<pixel_size;i++) - pdata[i]=0; + if ((x >= width || y >= height)) { + for (uint32_t i = 0; i < pixel_size; i++) + pdata[i] = 0; } else { - _get_pixelb(x,y,pixel_size,r.ptr(),pdata); + _get_pixelb(x, y, pixel_size, r.ptr(), pdata); } - - dst._put_pixelb(x,y,pixel_size,w.ptr(),pdata); + dst._put_pixelb(x, y, pixel_size, w.ptr(), pdata); } } } - - if (mipmaps>0) + if (mipmaps > 0) dst.generate_mipmaps(); - *this=dst; - + *this = dst; } void Image::flip_y() { @@ -761,38 +736,32 @@ void Image::flip_y() { ERR_FAIL(); } - bool gm=mipmaps; + bool gm = mipmaps; if (gm) clear_mipmaps(); - - { PoolVector<uint8_t>::Write w = data.write(); uint8_t up[16]; uint8_t down[16]; uint32_t pixel_size = get_format_pixel_size(format); - for (int y=0;y<height;y++) { - - for (int x=0;x<width;x++) { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { - _get_pixelb(x,y,pixel_size,w.ptr(),up); - _get_pixelb(x,height-y-1,pixel_size,w.ptr(),down); - - _put_pixelb(x,height-y-1,pixel_size,w.ptr(),up); - _put_pixelb(x,y,pixel_size,w.ptr(),down); + _get_pixelb(x, y, pixel_size, w.ptr(), up); + _get_pixelb(x, height - y - 1, pixel_size, w.ptr(), down); + _put_pixelb(x, height - y - 1, pixel_size, w.ptr(), up); + _put_pixelb(x, y, pixel_size, w.ptr(), down); } } } - if (gm) generate_mipmaps(); - } void Image::flip_x() { @@ -802,161 +771,149 @@ void Image::flip_x() { ERR_FAIL(); } - bool gm=mipmaps; + bool gm = mipmaps; if (gm) clear_mipmaps(); - { PoolVector<uint8_t>::Write w = data.write(); uint8_t up[16]; uint8_t down[16]; uint32_t pixel_size = get_format_pixel_size(format); - for (int y=0;y<height;y++) { - - for (int x=0;x<width;x++) { - + for (int y = 0; y < height; y++) { - _get_pixelb(x,y,pixel_size,w.ptr(),up); - _get_pixelb(width-x-1,y,pixel_size,w.ptr(),down); + for (int x = 0; x < width; x++) { - _put_pixelb(width-x-1,y,pixel_size,w.ptr(),up); - _put_pixelb(x,y,pixel_size,w.ptr(),down); + _get_pixelb(x, y, pixel_size, w.ptr(), up); + _get_pixelb(width - x - 1, y, pixel_size, w.ptr(), down); + _put_pixelb(width - x - 1, y, pixel_size, w.ptr(), up); + _put_pixelb(x, y, pixel_size, w.ptr(), down); } } } if (gm) generate_mipmaps(); - } -int Image::_get_dst_image_size(int p_width, int p_height, Format p_format,int &r_mipmaps,int p_mipmaps) { +int Image::_get_dst_image_size(int p_width, int p_height, Format p_format, int &r_mipmaps, int p_mipmaps) { - int size=0; - int w=p_width; - int h=p_height; - int mm=0; + int size = 0; + int w = p_width; + int h = p_height; + int mm = 0; - int pixsize=get_format_pixel_size(p_format); - int pixshift=get_format_pixel_rshift(p_format); - int minw,minh; - get_format_min_pixel_size(p_format,minw,minh); + int pixsize = get_format_pixel_size(p_format); + int pixshift = get_format_pixel_rshift(p_format); + int minw, minh; + get_format_min_pixel_size(p_format, minw, minh); - while(true) { + while (true) { - int s = w*h; - s*=pixsize; - s>>=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 { - return p_format<FORMAT_RGB565; + return p_format < FORMAT_RGB565; } -template<int CC> -static void _generate_po2_mipmap(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_width, uint32_t p_height) { +template <int CC> +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<dst_h;i++) { + for (uint32_t i = 0; i < dst_h; i++) { - const uint8_t *rup_ptr = &p_src[i*2*p_width*CC]; + const uint8_t *rup_ptr = &p_src[i * 2 * p_width * CC]; const uint8_t *rdown_ptr = rup_ptr + p_width * CC; - uint8_t *dst_ptr = &p_dst[i*dst_w*CC]; - uint32_t count=dst_w; - - - while(count--) { + uint8_t *dst_ptr = &p_dst[i * dst_w * CC]; + uint32_t count = dst_w; - for(int j=0;j<CC;j++) { + while (count--) { - 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; + 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(!_can_modify(format)); Format current = format; - bool mm=has_mipmaps(); + bool mm = has_mipmaps(); if (mm) { clear_mipmaps(); } - if (current!=FORMAT_RGBA8) + if (current != FORMAT_RGBA8) convert(FORMAT_RGBA8); PoolVector<uint8_t> dest; - dest.resize(width*2*height*2*4); + dest.resize(width * 2 * height * 2 * 4); { PoolVector<uint8_t>::Read r = data.read(); PoolVector<uint8_t>::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_RGBA8) + if (current != FORMAT_RGBA8) convert(current); if (mipmaps) { generate_mipmaps(); } - } void Image::shrink_x2() { - ERR_FAIL_COND( data.size()==0 ); - - + ERR_FAIL_COND(data.size() == 0); if (mipmaps) { @@ -965,136 +922,126 @@ 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); - { - PoolVector<uint8_t>::Write w=new_img.write(); - PoolVector<uint8_t>::Read r=data.read(); + PoolVector<uint8_t>::Write w = new_img.write(); + PoolVector<uint8_t>::Read r = data.read(); - copymem(w.ptr(),&r[ofs],new_size); + copymem(w.ptr(), &r[ofs], new_size); } - width/=2; - height/=2; - data=new_img; + width /= 2; + height /= 2; + data = new_img; } else { PoolVector<uint8_t> new_img; - ERR_FAIL_COND( !_can_modify(format) ); + ERR_FAIL_COND(!_can_modify(format)); int ps = get_format_pixel_size(format); - new_img.resize((width/2)*(height/2)*ps); + new_img.resize((width / 2) * (height / 2) * ps); { - PoolVector<uint8_t>::Write w=new_img.write(); - PoolVector<uint8_t>::Read r=data.read(); + PoolVector<uint8_t>::Write w = new_img.write(); + PoolVector<uint8_t>::Read r = data.read(); - switch(format) { + switch (format) { case FORMAT_L8: - case FORMAT_R8: _generate_po2_mipmap<1>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_LA8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_RG8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_RGB8: _generate_po2_mipmap<3>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_RGBA8: _generate_po2_mipmap<4>(r.ptr(), w.ptr(), width,height); break; + case FORMAT_R8: _generate_po2_mipmap<1>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_LA8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_RG8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_RGB8: _generate_po2_mipmap<3>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_RGBA8: _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() { +Error Image::generate_mipmaps() { if (!_can_modify(format)) { ERR_EXPLAIN("Cannot generate mipmaps in indexed, compressed or custom image formats."); ERR_FAIL_V(ERR_UNAVAILABLE); - } - ERR_FAIL_COND_V(width==0 || height==0,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(width == 0 || height == 0, ERR_UNCONFIGURED); int mmcount; - int size = _get_dst_image_size(width,height,format,mmcount); + int size = _get_dst_image_size(width, height, format, mmcount); data.resize(size); - print_line("to gen mipmaps w "+itos(width)+" h "+itos(height) +" format "+get_format_name(format)+" mipmaps " +itos(mmcount)+" new size is: "+itos(size)); + print_line("to gen mipmaps w " + itos(width) + " h " + itos(height) + " format " + get_format_name(format) + " mipmaps " + itos(mmcount) + " new size is: " + itos(size)); - PoolVector<uint8_t>::Write wp=data.write(); + PoolVector<uint8_t>::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; - - for(int i=1;i<mmcount;i++) { + int prev_ofs = 0; + int prev_h = height; + int prev_w = width; + for (int i = 1; i < mmcount; i++) { - int ofs,w,h; - _get_mipmap_offset_and_size(i,ofs, w,h); + int ofs, w, h; + _get_mipmap_offset_and_size(i, ofs, w, h); - - switch(format) { + switch (format) { case FORMAT_L8: - case FORMAT_R8: _generate_po2_mipmap<1>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; + case FORMAT_R8: _generate_po2_mipmap<1>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; case FORMAT_LA8: - case FORMAT_RG8: _generate_po2_mipmap<2>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; - case FORMAT_RGB8: _generate_po2_mipmap<3>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; - case FORMAT_RGBA8: _generate_po2_mipmap<4>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; + case FORMAT_RG8: _generate_po2_mipmap<2>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; + case FORMAT_RGB8: _generate_po2_mipmap<3>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; + case FORMAT_RGBA8: _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; - - for(int i=1;i<mmcount;i++) { + int prev_ofs = 0; + int prev_h = height; + int prev_w = width; + for (int i = 1; i < mmcount; i++) { - int ofs,w,h; - _get_mipmap_offset_and_size(i,ofs, w,h); + int ofs, w, h; + _get_mipmap_offset_and_size(i, ofs, w, h); - switch(format) { + switch (format) { case FORMAT_L8: - case FORMAT_R8: _scale_bilinear<1>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; + case FORMAT_R8: _scale_bilinear<1>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; case FORMAT_LA8: - case FORMAT_RG8: _scale_bilinear<2>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; - case FORMAT_RGB8:_scale_bilinear<3>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; - case FORMAT_RGBA8: _scale_bilinear<4>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; + case FORMAT_RG8: _scale_bilinear<2>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; + case FORMAT_RGB8: _scale_bilinear<3>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; + case FORMAT_RGBA8: _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; } - - - } - mipmaps=true; + mipmaps = true; return OK; } @@ -1107,18 +1054,16 @@ void Image::clear_mipmaps() { 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); data.resize(ofs); - mipmaps=false; - + mipmaps = false; } - bool Image::empty() const { - return (data.size()==0); + return (data.size() == 0); } PoolVector<uint8_t> Image::get_data() const { @@ -1126,53 +1071,48 @@ PoolVector<uint8_t> 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); { - PoolVector<uint8_t>::Write w= data.write(); - zeromem(w.ptr(),size); + PoolVector<uint8_t>::Write w = data.write(); + zeromem(w.ptr(), size); } - width=p_width; - height=p_height; - mipmaps=p_use_mipmaps; - format=p_format; - - + width = p_width; + height = p_height; + mipmaps = p_use_mipmaps; + format = p_format; } -void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data) { +void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t> &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); int mm; - int size = _get_dst_image_size(p_width,p_height,p_format,mm,p_use_mipmaps?-1:0); + int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0); - 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_use_mipmaps; + height = p_height; + width = p_width; + format = p_format; + data = p_data; + mipmaps = p_use_mipmaps; } +void Image::create(const char **p_xpm) { -void Image::create( const char ** p_xpm ) { - - - int size_width,size_height; - int pixelchars=0; - mipmaps=false; - bool has_alpha=false; + int size_width, size_height; + int pixelchars = 0; + mipmaps = false; + bool has_alpha = false; enum Status { READING_HEADER, @@ -1182,132 +1122,128 @@ void Image::create( const char ** p_xpm ) { }; Status status = READING_HEADER; - int line=0; + int line = 0; - HashMap<String,Color> colormap; + HashMap<String, Color> colormap; int colormap_size; uint32_t pixel_size; PoolVector<uint8_t>::Write w; - 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<pixelchars;i++) { + String colorstring; + for (int i = 0; i < pixelchars; i++) { - colorstring+=*line_ptr; - line_ptr++; - } + colorstring += *line_ptr; + line_ptr++; + } //skip spaces - while (*line_ptr==' ' || *line_ptr=='\t' || *line_ptr==0) { - if (*line_ptr==0) - break; - line_ptr++; - } - if (*line_ptr=='c') { - - line_ptr++; - while (*line_ptr==' ' || *line_ptr=='\t' || *line_ptr==0) { - if (*line_ptr==0) + while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) { + if (*line_ptr == 0) break; line_ptr++; } + if (*line_ptr == 'c') { - if (*line_ptr=='#') { line_ptr++; - uint8_t col_r; - uint8_t col_g; - uint8_t col_b; - //uint8_t col_a=255; - - for (int i=0;i<6;i++) { - - 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 + 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) { - - 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_ptr == '#') { + line_ptr++; + uint8_t col_r; + uint8_t col_g; + uint8_t col_b; + //uint8_t col_a=255; + + for (int i = 0; i < 6; i++) { + + 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_RGBA8:FORMAT_RGB8); - w=data.write(); - pixel_size=has_alpha?4:3; - } - } break; - case READING_PIXELS: { + status = READING_PIXELS; + create(size_width, size_height, 0, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8); + w = data.write(); + pixel_size = has_alpha ? 4 : 3; + } + } break; + case READING_PIXELS: { - int y=line-colormap_size-1; - for (int x=0;x<size_width;x++) { + int y = line - colormap_size - 1; + for (int x = 0; x < size_width; x++) { - char pixelstr[6]={0,0,0,0,0,0}; - for (int i=0;i<pixelchars;i++) - pixelstr[i]=line_ptr[x*pixelchars+i]; + char pixelstr[6] = { 0, 0, 0, 0, 0, 0 }; + for (int i = 0; i < pixelchars; i++) + pixelstr[i] = line_ptr[x * pixelchars + i]; - Color *colorptr = colormap.getptr(pixelstr); - ERR_FAIL_COND(!colorptr); - uint8_t pixel[4]; - for(uint32_t i=0;i<pixel_size;i++) { - pixel[i]=CLAMP((*colorptr)[i]*255,0,255); + Color *colorptr = colormap.getptr(pixelstr); + ERR_FAIL_COND(!colorptr); + uint8_t pixel[4]; + for (uint32_t i = 0; i < pixel_size; i++) { + pixel[i] = CLAMP((*colorptr)[i] * 255, 0, 255); + } + _put_pixelb(x, y, pixel_size, w.ptr(), pixel); } - _put_pixelb(x,y,pixel_size,w.ptr(),pixel); - } - - if (y==(size_height-1)) - status=DONE; - } break; - default:{} + if (y == (size_height - 1)) + status = DONE; + } break; + default: {} } line++; @@ -1316,63 +1252,60 @@ void Image::create( const char ** p_xpm ) { #define DETECT_ALPHA_MAX_TRESHOLD 254 #define DETECT_ALPHA_MIN_TRESHOLD 2 -#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;\ - }\ -} +#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_L8 || - format==FORMAT_RGB8 || format==FORMAT_RG8) + if (format == FORMAT_L8 || + format == FORMAT_RGB8 || format == FORMAT_RG8) return false; int len = data.size(); - if (len==0) + if (len == 0) return true; - - int w,h; - _get_mipmap_offset_and_size(1,len,w,h); + int w, h; + _get_mipmap_offset_and_size(1, len, w, h); PoolVector<uint8_t>::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_LA8: { - - for(int i=0;i<(len>>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_RGBA8: { - 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; @@ -1381,7 +1314,7 @@ bool Image::is_invisible() const { case FORMAT_PVRTC4A: case FORMAT_DXT3: case FORMAT_DXT5: { - detected=true; + detected = true; } break; default: {} } @@ -1391,43 +1324,41 @@ bool Image::is_invisible() const { Image::AlphaMode Image::detect_alpha() const { - int len = data.size(); - if (len==0) + if (len == 0) 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); PoolVector<uint8_t>::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_LA8: { - - for(int i=0;i<(len>>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_RGBA8: { - 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; + } break; case FORMAT_PVRTC2A: case FORMAT_PVRTC4A: case FORMAT_DXT3: case FORMAT_DXT5: { - detected=true; + detected = true; } break; default: {} } @@ -1438,15 +1369,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; @@ -1454,7 +1384,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; @@ -1464,42 +1394,31 @@ bool Image::operator==(const Image& p_image) const { return r.ptr() == pr.ptr(); } - - - -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; - } - - - - Error Image::_decompress_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_RGBA8,mm); + int size = _get_dst_image_size(wd, ht, FORMAT_RGBA8, mm); PoolVector<uint8_t> newdata; newdata.resize(size); @@ -1507,358 +1426,339 @@ Error Image::_decompress_bc() { PoolVector<uint8_t>::Write w = newdata.write(); PoolVector<uint8_t>::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_DXT1: { - 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*8]; - uint16_t col_a=src[1]; - col_a<<=8; - col_a|=src[0]; - uint16_t col_b=src[3]; - col_b<<=8; - col_b|=src[2]; - - uint8_t table[4][4]={ - { uint8_t((col_a>>11)<<3), uint8_t(((col_a>>5)&0x3f)<<2),uint8_t(((col_a)&0x1f)<<3), 255 }, - { uint8_t((col_b>>11)<<3), uint8_t(((col_b>>5)&0x3f)<<2),uint8_t(((col_b)&0x1f)<<3), 255 }, - {0,0,0,255}, - {0,0,0,255} + for (int j = 0; j < len; j++) { + + const uint8_t *src = &r[rofs + j * 8]; + uint16_t col_a = src[1]; + col_a <<= 8; + col_a |= src[0]; + uint16_t col_b = src[3]; + col_b <<= 8; + col_b |= src[2]; + + uint8_t table[4][4] = { + { uint8_t((col_a >> 11) << 3), uint8_t(((col_a >> 5) & 0x3f) << 2), uint8_t(((col_a)&0x1f) << 3), 255 }, + { uint8_t((col_b >> 11) << 3), uint8_t(((col_b >> 5) & 0x3f) << 2), uint8_t(((col_b)&0x1f) << 3), 255 }, + { 0, 0, 0, 255 }, + { 0, 0, 0, 255 } }; - if (col_a<col_b) { + if (col_a < col_b) { //punchrough - 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 + 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]; - - 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; + 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; + + 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_DXT3: { - 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]; - - uint64_t ablock=src[1]; - ablock<<=8; - ablock|=src[0]; - ablock<<=8; - ablock|=src[3]; - ablock<<=8; - ablock|=src[2]; - ablock<<=8; - ablock|=src[5]; - ablock<<=8; - ablock|=src[4]; - ablock<<=8; - ablock|=src[7]; - ablock<<=8; - ablock|=src[6]; - - - 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]={ - { uint8_t((col_a>>11)<<3), uint8_t(((col_a>>5)&0x3f)<<2),uint8_t(((col_a)&0x1f)<<3), 255 }, - { uint8_t((col_b>>11)<<3), uint8_t(((col_b>>5)&0x3f)<<2),uint8_t(((col_b)&0x1f)<<3), 255 }, - - {0,0,0,255}, - {0,0,0,255} + for (int j = 0; j < len; j++) { + + const uint8_t *src = &r[rofs + j * 16]; + + uint64_t ablock = src[1]; + ablock <<= 8; + ablock |= src[0]; + ablock <<= 8; + ablock |= src[3]; + ablock <<= 8; + ablock |= src[2]; + ablock <<= 8; + ablock |= src[5]; + ablock <<= 8; + ablock |= src[4]; + ablock <<= 8; + ablock |= src[7]; + ablock <<= 8; + ablock |= src[6]; + + 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] = { + { uint8_t((col_a >> 11) << 3), uint8_t(((col_a >> 5) & 0x3f) << 2), uint8_t(((col_a)&0x1f) << 3), 255 }, + { uint8_t((col_b >> 11) << 3), uint8_t(((col_b >> 5) & 0x3f) << 2), uint8_t(((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; - - 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; - - 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; + 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]; + + 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; } - } - 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_DXT5: { - 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;j<len;j++) { - - const uint8_t* src=&r[rofs+j*16]; - - uint8_t a_start=src[1]; - uint8_t a_end=src[0]; + uint8_t a_start = src[1]; + uint8_t a_end = src[0]; - uint64_t ablock=src[3]; - ablock<<=8; - ablock|=src[2]; - ablock<<=8; - ablock|=src[5]; - ablock<<=8; - ablock|=src[4]; - ablock<<=8; - ablock|=src[7]; - ablock<<=8; - ablock|=src[6]; + uint64_t ablock = src[3]; + ablock <<= 8; + ablock |= src[2]; + ablock <<= 8; + ablock |= src[5]; + ablock <<= 8; + ablock |= src[4]; + ablock <<= 8; + ablock |= src[7]; + ablock <<= 8; + ablock |= src[6]; uint8_t atable[8]; - if (a_start>a_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]={ - { uint8_t((col_a>>11)<<3), uint8_t(((col_a>>5)&0x3f)<<2),uint8_t(((col_a)&0x1f)<<3), 255 }, - { uint8_t((col_b>>11)<<3), uint8_t(((col_b>>5)&0x3f)<<2),uint8_t(((col_b)&0x1f)<<3), 255 }, + uint8_t table[4][4] = { + { uint8_t((col_a >> 11) << 3), uint8_t(((col_a >> 5) & 0x3f) << 2), uint8_t(((col_a)&0x1f) << 3), 255 }, + { uint8_t((col_b >> 11) << 3), uint8_t(((col_b >> 5) & 0x3f) << 2), uint8_t(((col_b)&0x1f) << 3), 255 }, - {0,0,0,255}, - {0,0,0,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; - - - 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; - - - - 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; + 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]; + + 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; } - } - rofs+=len*16; - wofs+=wd*ht*4; + rofs += len * 16; + wofs += wd * ht * 4; - - wd/=2; - ht/=2; + wd /= 2; + ht /= 2; } break; default: {} } - } - w=PoolVector<uint8_t>::Write(); - r=PoolVector<uint8_t>::Read(); + w = PoolVector<uint8_t>::Write(); + r = PoolVector<uint8_t>::Read(); - data=newdata; - format=FORMAT_RGBA8; - if (wd!=width || ht!=height) { + data = newdata; + format = FORMAT_RGBA8; + if (wd != width || ht != height) { - SWAP(width,wd); - SWAP(height,ht); - crop(wd,ht); + SWAP(width, wd); + SWAP(height, ht); + crop(wd, ht); } return OK; } bool Image::is_compressed() const { - return format>=FORMAT_RGB565; + return format >= FORMAT_RGB565; } - Image Image::decompressed() const { - Image img=*this; + Image img = *this; img.decompress(); return img; } Error Image::decompress() { - if (format>=FORMAT_DXT1 && format<=FORMAT_ATI2 ) - _decompress_bc();//_image_decompress_bc(this); - else if (format>=FORMAT_PVRTC2 && format<=FORMAT_PVRTC4A&& _image_decompress_pvrtc) + if (format >= FORMAT_DXT1 && format <= FORMAT_ATI2) + _decompress_bc(); //_image_decompress_bc(this); + else if (format >= FORMAT_PVRTC2 && format <= FORMAT_PVRTC4A && _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 if (format>=FORMAT_ETC2_R11 && format<=FORMAT_ETC2_RGB8A1 && _image_decompress_etc) + else if (format >= FORMAT_ETC2_R11 && format <= FORMAT_ETC2_RGB8A1 && _image_decompress_etc) _image_decompress_etc2(this); else return ERR_UNAVAILABLE; return OK; } - Error Image::compress(CompressMode p_mode) { - switch(p_mode) { + switch (p_mode) { case COMPRESS_16BIT: { @@ -1892,7 +1792,6 @@ Error Image::compress(CompressMode p_mode) { } break; } - return OK; } @@ -1906,82 +1805,75 @@ Image Image::compressed(int p_mode) { Image::Image(const char **p_xpm) { - width=0; - height=0; - mipmaps=false; - format=FORMAT_L8; + width = 0; + height = 0; + mipmaps = false; + format = FORMAT_L8; 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=p_use_mipmaps; - format=FORMAT_L8; - - create(p_width,p_height,p_use_mipmaps,p_format); + width = 0; + height = 0; + mipmaps = p_use_mipmaps; + format = FORMAT_L8; + create(p_width, p_height, p_use_mipmaps, p_format); } -Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data) { - - width=0; - height=0; - mipmaps=p_mipmaps; - format=FORMAT_L8; +Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t> &p_data) { - create(p_width,p_height,p_mipmaps,p_format,p_data); + width = 0; + height = 0; + mipmaps = p_mipmaps; + format = FORMAT_L8; + create(p_width, p_height, p_mipmaps, p_format, p_data); } - Rect2 Image::get_used_rect() const { - if (format!=FORMAT_LA8 && format!=FORMAT_RGBA8) - return Rect2(Point2(),Size2(width,height)); + if (format != FORMAT_LA8 && format != FORMAT_RGBA8) + return Rect2(Point2(), Size2(width, height)); int len = data.size(); - if (len==0) + if (len == 0) return Rect2(); //int data_size = len; PoolVector<uint8_t>::Read r = data.read(); - const unsigned char *rptr=r.ptr(); + const unsigned char *rptr = r.ptr(); - int ps = format==FORMAT_LA8?2:4; - int minx=0xFFFFFF,miny=0xFFFFFFF; - int maxx=-1,maxy=-1; - for(int j=0;j<height;j++) { - for(int i=0;i<width;i++) { + int ps = format == FORMAT_LA8 ? 2 : 4; + int minx = 0xFFFFFF, miny = 0xFFFFFFF; + int maxx = -1, maxy = -1; + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { - - bool opaque = rptr[(j*width+i)*ps+(ps-1)]>2; + bool opaque = rptr[(j * width + i) * ps + (ps - 1)] > 2; if (!opaque) continue; - if (i>maxx) - maxx=i; - if (j>maxy) - maxy=j; - if (i<minx) - minx=i; - if (j<miny) - miny=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)); @@ -1989,91 +1881,85 @@ Image Image::get_rect(const Rect2& p_area) const { return img; } -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 ); - ERR_FAIL_COND( format!=p_src.format ); + int dsize = data.size(); + int srcdsize = p_src.data.size(); + ERR_FAIL_COND(dsize == 0); + ERR_FAIL_COND(srcdsize == 0); + ERR_FAIL_COND(format != p_src.format); + Rect2i local_src_rect = Rect2i(0, 0, width, height).clip(Rect2i(p_dest + p_src_rect.pos, p_src_rect.size)); - Rect2i local_src_rect = Rect2i(0,0,width,height).clip( Rect2i(p_dest+p_src_rect.pos,p_src_rect.size) ); - - if (local_src_rect.size.x<=0 || local_src_rect.size.y<=0) + if (local_src_rect.size.x <= 0 || local_src_rect.size.y <= 0) return; - Rect2i src_rect( p_src_rect.pos + ( local_src_rect.pos - p_dest), local_src_rect.size ); + Rect2i src_rect(p_src_rect.pos + (local_src_rect.pos - p_dest), local_src_rect.size); PoolVector<uint8_t>::Write wp = data.write(); - uint8_t *dst_data_ptr=wp.ptr(); + uint8_t *dst_data_ptr = wp.ptr(); PoolVector<uint8_t>::Read rp = p_src.data.read(); - const uint8_t *src_data_ptr=rp.ptr(); - - int pixel_size=get_format_pixel_size(format); + const uint8_t *src_data_ptr = rp.ptr(); - for(int i=0;i<src_rect.size.y;i++) { + int pixel_size = get_format_pixel_size(format); + for (int i = 0; i < src_rect.size.y; i++) { - for(int j=0;j<src_rect.size.x;j++) { + for (int j = 0; j < src_rect.size.x; j++) { - int src_x = src_rect.pos.x+j; - int src_y = src_rect.pos.y+i; + int src_x = src_rect.pos.x + j; + int src_y = src_rect.pos.y + i; - int dst_x = local_src_rect.pos.x+j; - int dst_y = local_src_rect.pos.y+i; + int dst_x = local_src_rect.pos.x + j; + int dst_y = local_src_rect.pos.y + i; - const uint8_t *src = &src_data_ptr[ (src_y*p_src.width+src_x)*pixel_size]; - uint8_t *dst = &dst_data_ptr[ (dst_y*width+dst_x)*pixel_size]; + const uint8_t *src = &src_data_ptr[(src_y * p_src.width + src_x) * pixel_size]; + uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size]; - for(int k=0;k<pixel_size;k++) { - dst[k]=src[k]; + for (int k = 0; k < pixel_size; k++) { + dst[k] = src[k]; } } } - } +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_compress_etc2_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_decompress_etc2)(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_compress_etc2_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_decompress_etc2)(Image *) = NULL; -PoolVector<uint8_t> (*Image::lossy_packer)(const Image& ,float )=NULL; -Image (*Image::lossy_unpacker)(const PoolVector<uint8_t>& )=NULL; -PoolVector<uint8_t> (*Image::lossless_packer)(const Image& )=NULL; -Image (*Image::lossless_unpacker)(const PoolVector<uint8_t>& )=NULL; +PoolVector<uint8_t> (*Image::lossy_packer)(const Image &, float) = NULL; +Image (*Image::lossy_unpacker)(const PoolVector<uint8_t> &) = NULL; +PoolVector<uint8_t> (*Image::lossless_packer)(const Image &) = NULL; +Image (*Image::lossless_unpacker)(const PoolVector<uint8_t> &) = 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_RGBA8); { - int len = data.size()/4; + int len = data.size() / 4; PoolVector<uint8_t>::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - data_ptr[(i<<2)+3]=data_ptr[(i<<2)+0]; //x to w - data_ptr[(i<<2)+0]=data_ptr[(i<<2)+1]; //y to xz - data_ptr[(i<<2)+2]=data_ptr[(i<<2)+1]; + data_ptr[(i << 2) + 3] = data_ptr[(i << 2) + 0]; //x to w + data_ptr[(i << 2) + 0] = data_ptr[(i << 2) + 1]; //y to xz + data_ptr[(i << 2) + 2] = data_ptr[(i << 2) + 1]; } } @@ -2082,171 +1968,159 @@ void Image::normalmap_to_xy() { void Image::srgb_to_linear() { - if (data.size()==0) + if (data.size() == 0) return; - static const uint8_t srgb2lin[256]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252}; - + static const uint8_t srgb2lin[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252 }; - ERR_FAIL_COND( format!=FORMAT_RGB8 && format!=FORMAT_RGBA8 ); + ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8); - if (format==FORMAT_RGBA8) { + if (format == FORMAT_RGBA8) { - int len = data.size()/4; + int len = data.size() / 4; PoolVector<uint8_t>::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - data_ptr[(i<<2)+0]=srgb2lin[ data_ptr[(i<<2)+0] ]; - data_ptr[(i<<2)+1]=srgb2lin[ data_ptr[(i<<2)+1] ]; - data_ptr[(i<<2)+2]=srgb2lin[ data_ptr[(i<<2)+2] ]; + data_ptr[(i << 2) + 0] = srgb2lin[data_ptr[(i << 2) + 0]]; + data_ptr[(i << 2) + 1] = srgb2lin[data_ptr[(i << 2) + 1]]; + data_ptr[(i << 2) + 2] = srgb2lin[data_ptr[(i << 2) + 2]]; } - } else if (format==FORMAT_RGB8) { + } else if (format == FORMAT_RGB8) { - int len = data.size()/3; + int len = data.size() / 3; PoolVector<uint8_t>::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - data_ptr[(i*3)+0]=srgb2lin[ data_ptr[(i*3)+0] ]; - data_ptr[(i*3)+1]=srgb2lin[ data_ptr[(i*3)+1] ]; - data_ptr[(i*3)+2]=srgb2lin[ data_ptr[(i*3)+2] ]; + data_ptr[(i * 3) + 0] = srgb2lin[data_ptr[(i * 3) + 0]]; + data_ptr[(i * 3) + 1] = srgb2lin[data_ptr[(i * 3) + 1]]; + data_ptr[(i * 3) + 2] = srgb2lin[data_ptr[(i * 3) + 2]]; } } - } void Image::premultiply_alpha() { - if (data.size()==0) + if (data.size() == 0) return; - if (format!=FORMAT_RGBA8) + if (format != FORMAT_RGBA8) return; //not needed PoolVector<uint8_t>::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<height;i++) { - for(int j=0;j<width;j++) { + uint8_t *ptr = &data_ptr[(i * width + j) * 4]; - uint8_t *ptr = &data_ptr[(i*width+j)*4]; - - ptr[0]=(uint16_t(ptr[0])*uint16_t(ptr[3]))>>8; - ptr[1]=(uint16_t(ptr[1])*uint16_t(ptr[3]))>>8; - ptr[2]=(uint16_t(ptr[2])*uint16_t(ptr[3]))>>8; + ptr[0] = (uint16_t(ptr[0]) * uint16_t(ptr[3])) >> 8; + ptr[1] = (uint16_t(ptr[1]) * uint16_t(ptr[3])) >> 8; + ptr[2] = (uint16_t(ptr[2]) * uint16_t(ptr[3])) >> 8; } } } void Image::fix_alpha_edges() { - if (data.size()==0) + if (data.size() == 0) return; - if (format!=FORMAT_RGBA8) + if (format != FORMAT_RGBA8) return; //not needed PoolVector<uint8_t> dcopy = data; PoolVector<uint8_t>::Read rp = dcopy.read(); - const uint8_t *srcptr=rp.ptr(); + const uint8_t *srcptr = rp.ptr(); PoolVector<uint8_t>::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<height;i++) { - for(int j=0;j<width;j++) { + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { - const uint8_t *rptr = &srcptr[(i*width+j)*4]; - uint8_t *wptr = &data_ptr[(i*width+j)*4]; + const uint8_t *rptr = &srcptr[(i * width + j) * 4]; + uint8_t *wptr = &data_ptr[(i * width + j) * 4]; - if (rptr[3]>=alpha_treshold) + if (rptr[3] >= alpha_treshold) continue; - int closest_dist=max_dist; + int closest_dist = max_dist; uint8_t closest_color[3]; + 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); - 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 = &srcptr[(k*width+l)<<2]; + const uint8_t *rp = &srcptr[(k * width + l) << 2]; - if (rp[3]<alpha_treshold) + if (rp[3] < alpha_treshold) continue; - closest_color[0]=rp[0]; - closest_color[1]=rp[1]; - closest_color[2]=rp[2]; - + closest_color[0] = rp[0]; + closest_color[1] = rp[1]; + closest_color[2] = rp[2]; } } + if (closest_dist != max_dist) { - if (closest_dist!=max_dist) { - - wptr[0]=closest_color[0]; - wptr[1]=closest_color[1]; - wptr[2]=closest_color[2]; + wptr[0] = closest_color[0]; + wptr[1] = closest_color[1]; + wptr[2] = closest_color[2]; } - } } - } String Image::get_format_name(Format p_format) { - ERR_FAIL_INDEX_V(p_format,FORMAT_MAX,String()); + ERR_FAIL_INDEX_V(p_format, FORMAT_MAX, String()); return format_names[p_format]; } -Image::Image(const uint8_t* p_mem_png_jpg, int p_len) { +Image::Image(const uint8_t *p_mem_png_jpg, int p_len) { - width=0; - height=0; - mipmaps=false; - format=FORMAT_L8; + width = 0; + height = 0; + mipmaps = false; + format = FORMAT_L8; if (_png_mem_loader_func) { - *this = _png_mem_loader_func(p_mem_png_jpg,p_len); + *this = _png_mem_loader_func(p_mem_png_jpg, p_len); } if (empty() && _jpg_mem_loader_func) { - *this = _jpg_mem_loader_func(p_mem_png_jpg,p_len); + *this = _jpg_mem_loader_func(p_mem_png_jpg, p_len); } - } Image::Image() { - width=0; - height=0; - mipmaps=false; + width = 0; + height = 0; + mipmaps = false; format = FORMAT_L8; } Image::~Image() { - } - - diff --git a/core/image.h b/core/image.h index 1a257f28a0..310351e547 100644 --- a/core/image.h +++ b/core/image.h @@ -29,8 +29,8 @@ #ifndef IMAGE_H #define IMAGE_H -#include "dvector.h" #include "color.h" +#include "dvector.h" #include "math_2d.h" /** * @author Juan Linietsky <reduzio@gmail.com> @@ -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 { @@ -96,7 +96,7 @@ public: FORMAT_MAX }; - static const char* format_names[FORMAT_MAX]; + static const char *format_names[FORMAT_MAX]; enum Interpolation { INTERPOLATE_NEAREST, @@ -107,8 +107,8 @@ public: //some functions provided by something else - 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 *); @@ -123,30 +123,26 @@ public: Error _decompress_bc(); - static PoolVector<uint8_t> (*lossy_packer)(const Image& p_image,float p_quality); - static Image (*lossy_unpacker)(const PoolVector<uint8_t>& p_buffer); - static PoolVector<uint8_t> (*lossless_packer)(const Image& p_image); - static Image (*lossless_unpacker)(const PoolVector<uint8_t>& p_buffer); -private: + static PoolVector<uint8_t> (*lossy_packer)(const Image &p_image, float p_quality); + static Image (*lossy_unpacker)(const PoolVector<uint8_t> &p_buffer); + static PoolVector<uint8_t> (*lossless_packer)(const Image &p_image); + static Image (*lossless_unpacker)(const PoolVector<uint8_t> &p_buffer); +private: Format format; PoolVector<uint8_t> data; - int width,height; + int width, height; bool mipmaps; - _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_ 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 - 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; - - _FORCE_INLINE_ void _put_pixelb(int p_x,int p_y, uint32_t p_pixelsize,uint8_t *p_dst,const uint8_t *p_src); - _FORCE_INLINE_ void _get_pixelb(int p_x,int p_y, uint32_t p_pixelsize,const uint8_t *p_src,uint8_t *p_dst); + _FORCE_INLINE_ void _put_pixelb(int p_x, int p_y, uint32_t p_pixelsize, uint8_t *p_dst, const uint8_t *p_src); + _FORCE_INLINE_ void _get_pixelb(int p_x, int p_y, uint32_t p_pixelsize, const uint8_t *p_src, uint8_t *p_dst); public: - - - int get_width() const; ///< Get image width int get_height() const; ///< Get image height bool has_mipmaps() const; @@ -155,7 +151,7 @@ public: /** * Convert the image to another format, conversion only to raw byte format */ - 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()); @@ -171,24 +167,23 @@ 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(); @@ -200,15 +195,13 @@ public: void clear_mipmaps(); - - /** * 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, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data); + void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t> &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 */ @@ -216,8 +209,8 @@ public: PoolVector<uint8_t> 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 @@ -230,7 +223,7 @@ public: /** * import an image of a specific size and format from a pointer */ - Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data); + Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t> &p_data); enum AlphaMode { ALPHA_NONE, @@ -241,16 +234,14 @@ public: AlphaMode detect_alpha() const; bool is_invisible() const; - static int get_format_pixel_size(Format p_format); static int get_format_pixel_rshift(Format p_format); - static void get_format_min_pixel_size(Format p_format,int &r_w, int &r_h); + static void get_format_min_pixel_size(Format p_format, int &r_w, int &r_h); - 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; enum CompressMode { COMPRESS_16BIT, @@ -261,7 +252,7 @@ public: COMPRESS_ETC2 }; - Error compress(CompressMode p_mode=COMPRESS_S3TC); + Error compress(CompressMode p_mode = COMPRESS_S3TC); Image compressed(int p_mode); /* from the Image::CompressMode enum */ Error decompress(); Image decompressed() const; @@ -272,19 +263,17 @@ 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 blit_rect(const Image &p_src, const Rect2 &p_src_rect, const Point2 &p_dest); 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/input_map.cpp b/core/input_map.cpp index 444c55cac6..b2b4246d6a 100644 --- a/core/input_map.cpp +++ b/core/input_map.cpp @@ -31,50 +31,45 @@ #include "global_config.h" #include "os/keyboard.h" -InputMap *InputMap::singleton=NULL; +InputMap *InputMap::singleton = NULL; void InputMap::_bind_methods() { - ClassDB::bind_method(D_METHOD("has_action","action"),&InputMap::has_action); - ClassDB::bind_method(D_METHOD("get_action_id","action"),&InputMap::get_action_id); - ClassDB::bind_method(D_METHOD("get_action_from_id","id"),&InputMap::get_action_from_id); - ClassDB::bind_method(D_METHOD("get_actions"),&InputMap::_get_actions); - ClassDB::bind_method(D_METHOD("add_action","action"),&InputMap::add_action); - ClassDB::bind_method(D_METHOD("erase_action","action"),&InputMap::erase_action); - - ClassDB::bind_method(D_METHOD("action_add_event","action","event"),&InputMap::action_add_event); - ClassDB::bind_method(D_METHOD("action_has_event","action","event"),&InputMap::action_has_event); - ClassDB::bind_method(D_METHOD("action_erase_event","action","event"),&InputMap::action_erase_event); - ClassDB::bind_method(D_METHOD("get_action_list","action"),&InputMap::_get_action_list); - ClassDB::bind_method(D_METHOD("event_is_action","event","action"),&InputMap::event_is_action); - ClassDB::bind_method(D_METHOD("load_from_globals"),&InputMap::load_from_globals); - + ClassDB::bind_method(D_METHOD("has_action", "action"), &InputMap::has_action); + ClassDB::bind_method(D_METHOD("get_action_id", "action"), &InputMap::get_action_id); + ClassDB::bind_method(D_METHOD("get_action_from_id", "id"), &InputMap::get_action_from_id); + ClassDB::bind_method(D_METHOD("get_actions"), &InputMap::_get_actions); + ClassDB::bind_method(D_METHOD("add_action", "action"), &InputMap::add_action); + ClassDB::bind_method(D_METHOD("erase_action", "action"), &InputMap::erase_action); + + ClassDB::bind_method(D_METHOD("action_add_event", "action", "event"), &InputMap::action_add_event); + ClassDB::bind_method(D_METHOD("action_has_event", "action", "event"), &InputMap::action_has_event); + ClassDB::bind_method(D_METHOD("action_erase_event", "action", "event"), &InputMap::action_erase_event); + ClassDB::bind_method(D_METHOD("get_action_list", "action"), &InputMap::_get_action_list); + ClassDB::bind_method(D_METHOD("event_is_action", "event", "action"), &InputMap::event_is_action); + ClassDB::bind_method(D_METHOD("load_from_globals"), &InputMap::load_from_globals); } +void InputMap::add_action(const StringName &p_action) { -void InputMap::add_action(const StringName& p_action) { - - ERR_FAIL_COND( input_map.has(p_action) ); - input_map[p_action]=Action(); - static int last_id=1; - input_map[p_action].id=last_id; - input_id_map[last_id]=p_action; + ERR_FAIL_COND(input_map.has(p_action)); + input_map[p_action] = Action(); + static int last_id = 1; + input_map[p_action].id = last_id; + input_id_map[last_id] = p_action; last_id++; - - } -void InputMap::erase_action(const StringName& p_action) { +void InputMap::erase_action(const StringName &p_action) { - ERR_FAIL_COND( !input_map.has(p_action) ); + ERR_FAIL_COND(!input_map.has(p_action)); input_id_map.erase(input_map[p_action].id); input_map.erase(p_action); - } StringName InputMap::get_action_from_id(int p_id) const { - ERR_FAIL_COND_V(!input_id_map.has(p_id),StringName()); + ERR_FAIL_COND_V(!input_id_map.has(p_id), StringName()); return input_id_map[p_id]; } @@ -82,10 +77,10 @@ Array InputMap::_get_actions() { Array ret; List<StringName> actions = get_actions(); - if(actions.empty()) + if (actions.empty()) return ret; - for(const List<StringName>::Element *E=actions.front();E;E=E->next()) { + for (const List<StringName>::Element *E = actions.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -96,55 +91,55 @@ Array InputMap::_get_actions() { List<StringName> InputMap::get_actions() const { List<StringName> actions = List<StringName>(); - if(input_map.empty()){ + if (input_map.empty()) { return actions; } - for (Map<StringName, Action>::Element *E=input_map.front();E;E=E->next()) { + for (Map<StringName, Action>::Element *E = input_map.front(); E; E = E->next()) { actions.push_back(E->key()); } return actions; } -List<InputEvent>::Element *InputMap::_find_event(List<InputEvent> &p_list,const InputEvent& p_event, bool p_action_test) const { +List<InputEvent>::Element *InputMap::_find_event(List<InputEvent> &p_list, const InputEvent &p_event, bool p_action_test) const { - for (List<InputEvent>::Element *E=p_list.front();E;E=E->next()) { + for (List<InputEvent>::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: { - if(p_action_test) { + if (p_action_test) { uint32_t code = e.key.get_scancode_with_modifiers(); uint32_t event_code = p_event.key.get_scancode_with_modifiers(); - same=(e.key.scancode==p_event.key.scancode && (!p_event.key.pressed || ((code & event_code) == code))); + same = (e.key.scancode == p_event.key.scancode && (!p_event.key.pressed || ((code & event_code) == code))); } else { - 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::JOYPAD_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::JOYPAD_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; } @@ -153,93 +148,85 @@ List<InputEvent>::Element *InputMap::_find_event(List<InputEvent> &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<InputEvent>::Element *E=_find_event(input_map[p_action].inputs,p_event); + List<InputEvent>::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<InputEvent> *al = get_action_list(p_action); if (al) { - for(const List<InputEvent>::Element *E=al->front();E;E=E->next()) { + for (const List<InputEvent>::Element *E = al->front(); E; E = E->next()) { ret.push_back(E->get()); } } return ret; - } -const List<InputEvent> *InputMap::get_action_list(const StringName& p_action) { +const List<InputEvent> *InputMap::get_action_list(const StringName &p_action) { - const Map<StringName, Action>::Element *E=input_map.find(p_action); + const Map<StringName, Action>::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<StringName,Action >::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<StringName, Action>::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,true)!=NULL; + return _find_event(E->get().inputs, p_event, true) != NULL; } -const Map<StringName, InputMap::Action>& InputMap::get_action_map() const { +const Map<StringName, InputMap::Action> &InputMap::get_action_map() const { return input_map; } @@ -250,94 +237,88 @@ void InputMap::load_from_globals() { List<PropertyInfo> pinfo; GlobalConfig::get_singleton()->get_property_list(&pinfo); - for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { - const PropertyInfo &pi=E->get(); + for (List<PropertyInfo>::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 = GlobalConfig::get_singleton()->get(pi.name); - for(int i=0;i<va.size();i++) { + for (int i = 0; i < va.size(); i++) { - InputEvent ie=va[i]; - if (ie.type==InputEvent::NONE) + InputEvent ie = va[i]; + if (ie.type == InputEvent::NONE) continue; - action_add_event(name,ie); - + action_add_event(name, ie); } - } - } void InputMap::load_default() { InputEvent key; - key.type=InputEvent::KEY; + key.type = InputEvent::KEY; add_action("ui_accept"); - key.key.scancode=KEY_RETURN; - action_add_event("ui_accept",key); - key.key.scancode=KEY_ENTER; - action_add_event("ui_accept",key); - key.key.scancode=KEY_SPACE; - action_add_event("ui_accept",key); + key.key.scancode = KEY_RETURN; + action_add_event("ui_accept", key); + key.key.scancode = KEY_ENTER; + action_add_event("ui_accept", key); + key.key.scancode = KEY_SPACE; + action_add_event("ui_accept", key); add_action("ui_select"); - key.key.scancode=KEY_SPACE; - action_add_event("ui_select",key); + key.key.scancode = KEY_SPACE; + action_add_event("ui_select", key); add_action("ui_cancel"); - key.key.scancode=KEY_ESCAPE; - action_add_event("ui_cancel",key); + key.key.scancode = KEY_ESCAPE; + action_add_event("ui_cancel", key); add_action("ui_focus_next"); - key.key.scancode=KEY_TAB; - action_add_event("ui_focus_next",key); + key.key.scancode = KEY_TAB; + action_add_event("ui_focus_next", key); add_action("ui_focus_prev"); - key.key.scancode=KEY_TAB; - key.key.mod.shift=true; - action_add_event("ui_focus_prev",key); - key.key.mod.shift=false; + key.key.scancode = KEY_TAB; + key.key.mod.shift = true; + action_add_event("ui_focus_prev", key); + key.key.mod.shift = false; add_action("ui_left"); - key.key.scancode=KEY_LEFT; - action_add_event("ui_left",key); + key.key.scancode = KEY_LEFT; + action_add_event("ui_left", key); add_action("ui_right"); - key.key.scancode=KEY_RIGHT; - action_add_event("ui_right",key); + key.key.scancode = KEY_RIGHT; + action_add_event("ui_right", key); add_action("ui_up"); - key.key.scancode=KEY_UP; - action_add_event("ui_up",key); + key.key.scancode = KEY_UP; + action_add_event("ui_up", key); add_action("ui_down"); - key.key.scancode=KEY_DOWN; - action_add_event("ui_down",key); - + key.key.scancode = KEY_DOWN; + action_add_event("ui_down", key); add_action("ui_page_up"); - key.key.scancode=KEY_PAGEUP; - action_add_event("ui_page_up",key); + key.key.scancode = KEY_PAGEUP; + action_add_event("ui_page_up", key); add_action("ui_page_down"); - key.key.scancode=KEY_PAGEDOWN; - action_add_event("ui_page_down",key); + key.key.scancode = KEY_PAGEDOWN; + action_add_event("ui_page_down", key); //set("display/handheld/orientation", "landscape"); - - } InputMap::InputMap() { ERR_FAIL_COND(singleton); - singleton=this; + singleton = this; } diff --git a/core/input_map.h b/core/input_map.h index 6ccd24f29c..25d0c3e1b9 100644 --- a/core/input_map.h +++ b/core/input_map.h @@ -29,51 +29,50 @@ #ifndef INPUT_MAP_H #define INPUT_MAP_H - #include "object.h" class InputMap : public Object { - GDCLASS( InputMap, Object ); + GDCLASS(InputMap, Object); + public: struct Action { int id; List<InputEvent> inputs; }; + private: static InputMap *singleton; mutable Map<StringName, Action> input_map; - mutable Map<int,StringName> input_id_map; + mutable Map<int, StringName> input_id_map; - List<InputEvent>::Element *_find_event(List<InputEvent> &p_list,const InputEvent& p_event, bool p_action_test=false) const; + List<InputEvent>::Element *_find_event(List<InputEvent> &p_list, const InputEvent &p_event, bool p_action_test = false) 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<StringName> 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); + 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<InputEvent> *get_action_list(const StringName& p_action); - bool event_is_action(const InputEvent& p_event, const StringName& p_action) const; + const List<InputEvent> *get_action_list(const StringName &p_action); + bool event_is_action(const InputEvent &p_event, const StringName &p_action) const; - const Map<StringName, Action>& get_action_map() const; + const Map<StringName, Action> &get_action_map() const; void load_from_globals(); void load_default(); diff --git a/core/int_types.h b/core/int_types.h index a7f04c680e..50ce38a3ba 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 <stdint.h> diff --git a/core/io/compression.cpp b/core/io/compression.cpp index 6fda7d52f3..25fd2ad2ee 100644 --- a/core/io/compression.cpp +++ b/core/io/compression.cpp @@ -26,25 +26,25 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "zlib.h" -#include "os/copymem.h" #include "compression.h" +#include "os/copymem.h" +#include "zlib.h" #include "fastlz.h" #include "zip_io.h" -int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode) { +int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) { - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - if (p_src_size<16) { + if (p_src_size < 16) { uint8_t src[16]; - zeromem(&src[p_src_size],16-p_src_size); - copymem(src,p_src,p_src_size); - return fastlz_compress(src,16,p_dst); + zeromem(&src[p_src_size], 16 - p_src_size); + copymem(src, p_src, p_src_size); + return fastlz_compress(src, 16, p_dst); } else { - return fastlz_compress(p_src,p_src_size,p_dst); + return fastlz_compress(p_src, p_src_size, p_dst); } } break; @@ -54,20 +54,20 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION); - if (err!=Z_OK) - return -1; + int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION); + if (err != Z_OK) + return -1; - strm.avail_in=p_src_size; - int aout = deflateBound(&strm,p_src_size); + strm.avail_in = p_src_size; + int aout = deflateBound(&strm, p_src_size); /*if (aout>p_src_size) { deflateEnd(&strm); return -1; }*/ - strm.avail_out=aout; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; - deflate(&strm,Z_FINISH); + strm.avail_out = aout; + strm.next_in = (Bytef *)p_src; + strm.next_out = p_dst; + deflate(&strm, Z_FINISH); aout = aout - strm.avail_out; deflateEnd(&strm); return aout; @@ -78,15 +78,14 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M ERR_FAIL_V(-1); } -int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){ +int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) { - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - - int ss = p_src_size+p_src_size*6/100; - if (ss<66) - ss=66; + int ss = p_src_size + p_src_size * 6 / 100; + if (ss < 66) + ss = 66; return ss; } break; @@ -96,34 +95,31 @@ int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){ strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION); - if (err!=Z_OK) - return -1; - int aout = deflateBound(&strm,p_src_size); + int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION); + if (err != Z_OK) + return -1; + int aout = deflateBound(&strm, p_src_size); deflateEnd(&strm); return aout; } break; } ERR_FAIL_V(-1); - } +int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { - -int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode){ - - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - int ret_size=0; + int ret_size = 0; - if (p_dst_max_size<16) { + if (p_dst_max_size < 16) { uint8_t dst[16]; - ret_size = fastlz_decompress(p_src,p_src_size,dst,16); - copymem(p_dst,dst,p_dst_max_size); + ret_size = fastlz_decompress(p_src, p_src_size, dst, 16); + copymem(p_dst, dst, p_dst_max_size); } else { - ret_size = fastlz_decompress(p_src,p_src_size,p_dst,p_dst_max_size); + ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size); } return ret_size; } break; @@ -133,20 +129,20 @@ int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - strm.avail_in= 0; - strm.next_in=Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; int err = inflateInit(&strm); - ERR_FAIL_COND_V(err!=Z_OK,-1); + ERR_FAIL_COND_V(err != Z_OK, -1); - strm.avail_in=p_src_size; - strm.avail_out=p_dst_max_size; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; + strm.avail_in = p_src_size; + strm.avail_out = p_dst_max_size; + strm.next_in = (Bytef *)p_src; + strm.next_out = p_dst; - err = inflate(&strm,Z_FINISH); + err = inflate(&strm, Z_FINISH); int total = strm.total_out; inflateEnd(&strm); - ERR_FAIL_COND_V(err!=Z_STREAM_END,-1); + ERR_FAIL_COND_V(err != Z_STREAM_END, -1); return total; } break; } diff --git a/core/io/compression.h b/core/io/compression.h index fc00d02dda..5156919867 100644 --- a/core/io/compression.h +++ b/core/io/compression.h @@ -31,23 +31,18 @@ #include "typedefs.h" -class Compression -{ +class Compression { public: - enum Mode { MODE_FASTLZ, MODE_DEFLATE }; - - static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ); - static int get_max_compressed_buffer_size(int p_src_size,Mode p_mode=MODE_FASTLZ); - static int decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ); + static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ); + static int get_max_compressed_buffer_size(int p_src_size, Mode p_mode = MODE_FASTLZ); + static int decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ); Compression(); }; - - #endif // COMPRESSION_H diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp index fdfcc3ae3a..052a83168d 100644 --- a/core/io/config_file.cpp +++ b/core/io/config_file.cpp @@ -27,8 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "config_file.h" -#include "os/keyboard.h" #include "os/file_access.h" +#include "os/keyboard.h" #include "variant_parser.h" PoolStringArray ConfigFile::_get_sections() const { @@ -37,35 +37,33 @@ PoolStringArray ConfigFile::_get_sections() const { get_sections(&s); PoolStringArray arr; arr.resize(s.size()); - int idx=0; - for(const List<String>::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; } -PoolStringArray ConfigFile::_get_section_keys(const String& p_section) const{ +PoolStringArray ConfigFile::_get_section_keys(const String &p_section) const { List<String> s; - get_section_keys(p_section,&s); + get_section_keys(p_section, &s); PoolStringArray arr; arr.resize(s.size()); - int idx=0; - for(const List<String>::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; - } +void ConfigFile::set_value(const String &p_section, const String &p_key, const Variant &p_value) { -void ConfigFile::set_value(const String& p_section, const String& p_key, const Variant& p_value){ - - if (p_value.get_type()==Variant::NIL) { + if (p_value.get_type() == Variant::NIL) { //erase if (!values.has(p_section)) return; // ? @@ -76,58 +74,54 @@ void ConfigFile::set_value(const String& p_section, const String& p_key, const V } else { if (!values.has(p_section)) { - values[p_section]=Map<String, Variant>(); + values[p_section] = Map<String, Variant>(); } - values[p_section][p_key]=p_value; - + values[p_section][p_key] = p_value; } - } -Variant ConfigFile::get_value(const String& p_section, const String& p_key, Variant p_default) const { +Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const { - ERR_FAIL_COND_V(!values.has(p_section),p_default); - ERR_FAIL_COND_V(!values[p_section].has(p_key),p_default); + ERR_FAIL_COND_V(!values.has(p_section), p_default); + ERR_FAIL_COND_V(!values[p_section].has(p_key), p_default); return values[p_section][p_key]; - } -bool ConfigFile::has_section(const String& p_section) const { +bool ConfigFile::has_section(const String &p_section) const { return values.has(p_section); } -bool ConfigFile::has_section_key(const String& p_section,const String& p_key) const { +bool ConfigFile::has_section_key(const String &p_section, const String &p_key) const { if (!values.has(p_section)) return false; return values[p_section].has(p_key); } -void ConfigFile::get_sections(List<String> *r_sections) const{ +void ConfigFile::get_sections(List<String> *r_sections) const { - for(const Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) { + for (const Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) { r_sections->push_back(E->key()); } } -void ConfigFile::get_section_keys(const String& p_section,List<String> *r_keys) const{ +void ConfigFile::get_section_keys(const String &p_section, List<String> *r_keys) const { ERR_FAIL_COND(!values.has(p_section)); - for(const Map<String, Variant> ::Element *E=values[p_section].front();E;E=E->next()) { + for (const Map<String, Variant>::Element *E = values[p_section].front(); E; E = E->next()) { r_keys->push_back(E->key()); } - } -void ConfigFile::erase_section(const String& p_section) { +void ConfigFile::erase_section(const String &p_section) { values.erase(p_section); } -Error ConfigFile::save(const String& p_path){ +Error ConfigFile::save(const String &p_path) { Error err; - FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err); + FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { if (file) @@ -135,18 +129,17 @@ Error ConfigFile::save(const String& p_path){ return err; } + for (Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) { - for(Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) { - - if (E!=values.front()) + if (E != values.front()) file->store_string("\n"); - file->store_string("["+E->key()+"]\n\n"); + file->store_string("[" + E->key() + "]\n\n"); - for(Map<String, Variant>::Element *F=E->get().front();F;F=F->next()) { + for (Map<String, Variant>::Element *F = E->get().front(); F; F = F->next()) { String vstr; - VariantWriter::write_to_string(F->get(),vstr); - file->store_string(F->key()+"="+vstr+"\n"); + VariantWriter::write_to_string(F->get(), vstr); + file->store_string(F->key() + "=" + vstr + "\n"); } } @@ -155,48 +148,46 @@ Error ConfigFile::save(const String& p_path){ return OK; } - -Error ConfigFile::load(const String& p_path) { +Error ConfigFile::load(const String &p_path) { Error err; - FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return ERR_CANT_OPEN; VariantParser::StreamFile stream; - stream.f=f; + stream.f = f; String assign; Variant value; VariantParser::Tag next_tag; - int lines=0; + int lines = 0; String error_text; String section; - while(true) { + while (true) { - assign=Variant(); + assign = Variant(); next_tag.fields.clear(); - next_tag.name=String(); + next_tag.name = String(); - err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true); - if (err==ERR_FILE_EOF) { + err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true); + if (err == ERR_FILE_EOF) { memdelete(f); return OK; - } - else if (err!=OK) { - ERR_PRINTS("ConfgFile::load - "+p_path+":"+itos(lines)+" error: "+error_text); + } else if (err != OK) { + ERR_PRINTS("ConfgFile::load - " + p_path + ":" + itos(lines) + " error: " + error_text); memdelete(f); return err; } - if (assign!=String()) { - set_value(section,assign,value); - } else if (next_tag.name!=String()) { - section=next_tag.name; + if (assign != String()) { + set_value(section, assign, value); + } else if (next_tag.name != String()) { + section = next_tag.name; } } @@ -205,27 +196,22 @@ Error ConfigFile::load(const String& p_path) { return OK; } +void ConfigFile::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_value", "section", "key", "value"), &ConfigFile::set_value); + ClassDB::bind_method(D_METHOD("get_value:Variant", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant())); -void ConfigFile::_bind_methods(){ - - ClassDB::bind_method(D_METHOD("set_value","section","key","value"),&ConfigFile::set_value); - ClassDB::bind_method(D_METHOD("get_value:Variant","section","key","default"),&ConfigFile::get_value,DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("has_section", "section"), &ConfigFile::has_section); + ClassDB::bind_method(D_METHOD("has_section_key", "section", "key"), &ConfigFile::has_section_key); - ClassDB::bind_method(D_METHOD("has_section","section"),&ConfigFile::has_section); - ClassDB::bind_method(D_METHOD("has_section_key","section","key"),&ConfigFile::has_section_key); + ClassDB::bind_method(D_METHOD("get_sections"), &ConfigFile::_get_sections); + ClassDB::bind_method(D_METHOD("get_section_keys", "section"), &ConfigFile::_get_section_keys); - ClassDB::bind_method(D_METHOD("get_sections"),&ConfigFile::_get_sections); - ClassDB::bind_method(D_METHOD("get_section_keys","section"),&ConfigFile::_get_section_keys); - - ClassDB::bind_method(D_METHOD("erase_section","section"),&ConfigFile::erase_section); - - ClassDB::bind_method(D_METHOD("load:Error","path"),&ConfigFile::load); - ClassDB::bind_method(D_METHOD("save:Error","path"),&ConfigFile::save); + ClassDB::bind_method(D_METHOD("erase_section", "section"), &ConfigFile::erase_section); + ClassDB::bind_method(D_METHOD("load:Error", "path"), &ConfigFile::load); + ClassDB::bind_method(D_METHOD("save:Error", "path"), &ConfigFile::save); } - -ConfigFile::ConfigFile() -{ +ConfigFile::ConfigFile() { } diff --git a/core/io/config_file.h b/core/io/config_file.h index c9c4a9fbc0..4d179bd137 100644 --- a/core/io/config_file.h +++ b/core/io/config_file.h @@ -31,33 +31,32 @@ #include "reference.h" - class ConfigFile : public Reference { - GDCLASS(ConfigFile,Reference); + GDCLASS(ConfigFile, Reference); - Map< String, Map<String, Variant> > values; + Map<String, Map<String, Variant> > values; PoolStringArray _get_sections() const; - PoolStringArray _get_section_keys(const String& p_section) const; -protected: + PoolStringArray _get_section_keys(const String &p_section) const; +protected: static void _bind_methods(); -public: - void set_value(const String& p_section, const String& p_key, const Variant& p_value); - Variant get_value(const String& p_section, const String& p_key, Variant p_default=Variant()) const; +public: + void set_value(const String &p_section, const String &p_key, const Variant &p_value); + Variant get_value(const String &p_section, const String &p_key, Variant p_default = Variant()) const; - bool has_section(const String& p_section) const; - bool has_section_key(const String& p_section,const String& p_key) const; + bool has_section(const String &p_section) const; + bool has_section_key(const String &p_section, const String &p_key) const; void get_sections(List<String> *r_sections) const; - void get_section_keys(const String& p_section,List<String> *r_keys) const; + void get_section_keys(const String &p_section, List<String> *r_keys) const; - void erase_section(const String& p_section); + void erase_section(const String &p_section); - Error save(const String& p_path); - Error load(const String& p_path); + Error save(const String &p_path); + Error load(const String &p_path); ConfigFile(); }; diff --git a/core/io/file_access_buffered.cpp b/core/io/file_access_buffered.cpp index 71518de38b..dd4d3e6e8f 100644 --- a/core/io/file_access_buffered.cpp +++ b/core/io/file_access_buffered.cpp @@ -92,7 +92,7 @@ bool FileAccessBuffered::eof_reached() const { uint8_t FileAccessBuffered::get_8() const { - ERR_FAIL_COND_V(!file.open,0); + ERR_FAIL_COND_V(!file.open, 0); uint8_t byte = 0; if (cache_data_left() >= 1) { @@ -105,7 +105,7 @@ uint8_t FileAccessBuffered::get_8() const { return byte; }; -int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { +int FileAccessBuffered::get_buffer(uint8_t *p_dest, int p_elements) const { ERR_FAIL_COND_V(!file.open, -1); @@ -135,7 +135,6 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { return total_read; }; - int to_read = p_elements; int total_read = 0; while (to_read > 0) { @@ -154,7 +153,7 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { int r = MIN(left, to_read); //PoolVector<uint8_t>::Read read = cache.buffer.read(); //memcpy(p_dest+total_read, &read.ptr()[file.offset - cache.offset], r); - memcpy(p_dest+total_read, cache.buffer.ptr() + (file.offset - cache.offset), r); + memcpy(p_dest + total_read, cache.buffer.ptr() + (file.offset - cache.offset), r); file.offset += r; total_read += r; @@ -179,6 +178,5 @@ FileAccessBuffered::FileAccessBuffered() { cache_size = DEFAULT_CACHE_SIZE; }; -FileAccessBuffered::~FileAccessBuffered(){ - +FileAccessBuffered::~FileAccessBuffered() { } diff --git a/core/io/file_access_buffered.h b/core/io/file_access_buffered.h index be8ea714b1..964152af5e 100644 --- a/core/io/file_access_buffered.h +++ b/core/io/file_access_buffered.h @@ -42,14 +42,12 @@ public: }; private: - int cache_size; int cache_data_left() const; mutable Error last_error; protected: - Error set_error(Error p_error) const; mutable struct File { @@ -67,23 +65,22 @@ protected: int offset; } cache; - virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const =0; + virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const = 0; void set_cache_size(int p_size); int get_cache_size(); public: - virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual bool eof_reached() const; virtual uint8_t get_8() const; - virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes + virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes virtual bool is_open() const; @@ -94,4 +91,3 @@ public: }; #endif - diff --git a/core/io/file_access_buffered_fa.h b/core/io/file_access_buffered_fa.h index 000c2b45f3..dd1e99f8f6 100644 --- a/core/io/file_access_buffered_fa.h +++ b/core/io/file_access_buffered_fa.h @@ -31,16 +31,16 @@ #include "core/io/file_access_buffered.h" -template<class T> +template <class T> class FileAccessBufferedFA : public FileAccessBuffered { T f; int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const { - ERR_FAIL_COND_V( !f.is_open(), -1 ); + ERR_FAIL_COND_V(!f.is_open(), -1); - ((T*)&f)->seek(p_offset); + ((T *)&f)->seek(p_offset); if (p_dest) { @@ -63,9 +63,9 @@ class FileAccessBufferedFA : public FileAccessBuffered { }; }; - static FileAccess* create() { + static FileAccess *create() { - return memnew( FileAccessBufferedFA<T>() ); + return memnew(FileAccessBufferedFA<T>()); }; protected: @@ -75,29 +75,27 @@ protected: }; public: - - void store_8(uint8_t p_dest) { f.store_8(p_dest); }; - void store_buffer(const uint8_t *p_src,int p_length) { + void store_buffer(const uint8_t *p_src, int p_length) { f.store_buffer(p_src, p_length); }; - bool file_exists(const String& p_name) { + bool file_exists(const String &p_name) { return f.file_exists(p_name); }; - Error _open(const String& p_path, int p_mode_flags) { + Error _open(const String &p_path, int p_mode_flags) { close(); Error ret = f._open(p_path, p_mode_flags); - if (ret !=OK) + if (ret != OK) return ret; //ERR_FAIL_COND_V( ret != OK, ret ); @@ -133,16 +131,14 @@ public: }; */ - virtual uint64_t _get_modified_time(const String& p_file) { + virtual uint64_t _get_modified_time(const String &p_file) { return f._get_modified_time(p_file); } - FileAccessBufferedFA() { - + FileAccessBufferedFA(){ }; }; - #endif // FILE_ACCESS_BUFFERED_FA_H diff --git a/core/io/file_access_compressed.cpp b/core/io/file_access_compressed.cpp index 3bcfade526..d8ae3e6ff1 100644 --- a/core/io/file_access_compressed.cpp +++ b/core/io/file_access_compressed.cpp @@ -28,244 +28,223 @@ /*************************************************************************/ #include "file_access_compressed.h" #include "print_string.h" -void FileAccessCompressed::configure(const String& p_magic, Compression::Mode p_mode, int p_block_size) { +void FileAccessCompressed::configure(const String &p_magic, Compression::Mode p_mode, int p_block_size) { - magic=p_magic.ascii().get_data(); - if (magic.length()>4) - magic=magic.substr(0,4); + magic = p_magic.ascii().get_data(); + if (magic.length() > 4) + magic = magic.substr(0, 4); else { - while(magic.length()<4) - magic+=" "; + while (magic.length() < 4) + magic += " "; } - cmode=p_mode; - block_size=p_block_size; - -} - - -#define WRITE_FIT(m_bytes) \ -{\ -if (write_pos+(m_bytes) > write_max) {\ - write_max=write_pos+(m_bytes);\ -}\ -if (write_max > write_buffer_size) {\ - write_buffer_size = nearest_power_of_2( write_max );\ - buffer.resize(write_buffer_size);\ - write_ptr=buffer.ptr();\ -}\ + cmode = p_mode; + block_size = p_block_size; } +#define WRITE_FIT(m_bytes) \ + { \ + if (write_pos + (m_bytes) > write_max) { \ + write_max = write_pos + (m_bytes); \ + } \ + if (write_max > write_buffer_size) { \ + write_buffer_size = nearest_power_of_2(write_max); \ + buffer.resize(write_buffer_size); \ + write_ptr = buffer.ptr(); \ + } \ + } Error FileAccessCompressed::open_after_magic(FileAccess *p_base) { - - f=p_base; - cmode=(Compression::Mode)f->get_32(); - block_size=f->get_32(); - read_total=f->get_32(); - int bc = (read_total/block_size)+1; - int acc_ofs=f->get_pos()+bc*4; - int max_bs=0; - for(int i=0;i<bc;i++) { + f = p_base; + cmode = (Compression::Mode)f->get_32(); + block_size = f->get_32(); + read_total = f->get_32(); + int bc = (read_total / block_size) + 1; + int acc_ofs = f->get_pos() + bc * 4; + int max_bs = 0; + for (int i = 0; i < bc; i++) { ReadBlock rb; - rb.offset=acc_ofs; - rb.csize=f->get_32(); - acc_ofs+=rb.csize; - max_bs=MAX(max_bs,rb.csize); + rb.offset = acc_ofs; + rb.csize = f->get_32(); + acc_ofs += rb.csize; + max_bs = MAX(max_bs, rb.csize); read_blocks.push_back(rb); - - } comp_buffer.resize(max_bs); buffer.resize(block_size); - read_ptr=buffer.ptr(); - f->get_buffer(comp_buffer.ptr(),read_blocks[0].csize); - at_end=false; - read_eof=false; - read_block_count=bc; - read_block_size=read_blocks.size()==1?read_total:block_size; + read_ptr = buffer.ptr(); + f->get_buffer(comp_buffer.ptr(), read_blocks[0].csize); + at_end = false; + read_eof = false; + read_block_count = bc; + read_block_size = read_blocks.size() == 1 ? read_total : block_size; - Compression::decompress(buffer.ptr(),read_block_size,comp_buffer.ptr(),read_blocks[0].csize,cmode); - read_block=0; - read_pos=0; + Compression::decompress(buffer.ptr(), read_block_size, comp_buffer.ptr(), read_blocks[0].csize, cmode); + read_block = 0; + read_pos = 0; return OK; - } -Error FileAccessCompressed::_open(const String& p_path, int p_mode_flags){ +Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags==READ_WRITE,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(p_mode_flags == READ_WRITE, ERR_UNAVAILABLE); if (f) close(); - Error err; - f = FileAccess::open(p_path,p_mode_flags,&err); - if (err!=OK) { + f = FileAccess::open(p_path, p_mode_flags, &err); + if (err != OK) { //not openable - f=NULL; + f = NULL; return err; } - if (p_mode_flags&WRITE) { + if (p_mode_flags & WRITE) { buffer.clear(); - writing=true; - write_pos=0; - write_buffer_size=256; + writing = true; + write_pos = 0; + write_buffer_size = 256; buffer.resize(256); - write_max=0; - write_ptr=buffer.ptr(); - - + write_max = 0; + write_ptr = buffer.ptr(); //don't store anything else unless it's done saving! } else { char rmagic[5]; - f->get_buffer((uint8_t*)rmagic,4); - rmagic[4]=0; - if (magic!=rmagic) { + f->get_buffer((uint8_t *)rmagic, 4); + rmagic[4] = 0; + if (magic != rmagic) { memdelete(f); - f=NULL; + f = NULL; return ERR_FILE_UNRECOGNIZED; } open_after_magic(f); - } return OK; - } -void FileAccessCompressed::close(){ +void FileAccessCompressed::close() { if (!f) return; - if (writing) { //save block table and all compressed blocks CharString mgc = magic.utf8(); - f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //write header 4 + f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //write header 4 f->store_32(cmode); //write compression mode 4 f->store_32(block_size); //write block size 4 f->store_32(write_max); //max amount of data written 4 - int bc=(write_max/block_size)+1; + int bc = (write_max / block_size) + 1; - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { f->store_32(0); //compressed sizes, will update later } - Vector<int> block_sizes; - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { - int bl = i==(bc-1) ? write_max % block_size : block_size; - uint8_t *bp = &write_ptr[i*block_size]; + int bl = i == (bc - 1) ? write_max % block_size : block_size; + uint8_t *bp = &write_ptr[i * block_size]; Vector<uint8_t> cblock; - cblock.resize(Compression::get_max_compressed_buffer_size(bl,cmode)); - int s = Compression::compress(cblock.ptr(),bp,bl,cmode); + cblock.resize(Compression::get_max_compressed_buffer_size(bl, cmode)); + int s = Compression::compress(cblock.ptr(), bp, bl, cmode); - f->store_buffer(cblock.ptr(),s); + f->store_buffer(cblock.ptr(), s); block_sizes.push_back(s); } f->seek(16); //ok write block sizes - for(int i=0;i<bc;i++) + for (int i = 0; i < bc; i++) f->store_32(block_sizes[i]); f->seek_end(); - f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //magic at the end too + f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //magic at the end too buffer.clear(); } else { - comp_buffer.clear(); buffer.clear(); read_blocks.clear(); } memdelete(f); - f=NULL; - + f = NULL; } -bool FileAccessCompressed::is_open() const{ +bool FileAccessCompressed::is_open() const { - return f!=NULL; + return f != NULL; } -void FileAccessCompressed::seek(size_t p_position){ +void FileAccessCompressed::seek(size_t p_position) { ERR_FAIL_COND(!f); if (writing) { - ERR_FAIL_COND(p_position>write_max); + ERR_FAIL_COND(p_position > write_max); - write_pos=p_position; + write_pos = p_position; } else { - ERR_FAIL_COND(p_position>read_total); - if (p_position==read_total) { - at_end=true; + ERR_FAIL_COND(p_position > read_total); + if (p_position == read_total) { + at_end = true; } else { - int block_idx = p_position/block_size; - if (block_idx!=read_block) { + int block_idx = p_position / block_size; + if (block_idx != read_block) { - read_block=block_idx; + read_block = block_idx; f->seek(read_blocks[read_block].offset); - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; } - read_pos=p_position%block_size; + read_pos = p_position % block_size; } } } - -void FileAccessCompressed::seek_end(int64_t p_position){ +void FileAccessCompressed::seek_end(int64_t p_position) { ERR_FAIL_COND(!f); if (writing) { - seek(write_max+p_position); + seek(write_max + p_position); } else { - seek(read_total+p_position); - + seek(read_total + p_position); } - - } -size_t FileAccessCompressed::get_pos() const{ +size_t FileAccessCompressed::get_pos() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); if (writing) { return write_pos; } else { - return read_block*block_size+read_pos; + return read_block * block_size + read_pos; } - } -size_t FileAccessCompressed::get_len() const{ +size_t FileAccessCompressed::get_len() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); if (writing) { return write_max; @@ -274,9 +253,9 @@ size_t FileAccessCompressed::get_len() const{ } } -bool FileAccessCompressed::eof_reached() const{ +bool FileAccessCompressed::eof_reached() const { - ERR_FAIL_COND_V(!f,false); + ERR_FAIL_COND_V(!f, false); if (writing) { return false; } else { @@ -284,106 +263,99 @@ bool FileAccessCompressed::eof_reached() const{ } } -uint8_t FileAccessCompressed::get_8() const{ +uint8_t FileAccessCompressed::get_8() const { - ERR_FAIL_COND_V(writing,0); - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(writing, 0); + ERR_FAIL_COND_V(!f, 0); if (at_end) { - read_eof=true; + read_eof = true; return 0; } uint8_t ret = read_ptr[read_pos]; read_pos++; - if (read_pos>=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_block<read_block_count) { + if (read_block < read_block_count) { //read another block of compressed data - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; - read_pos=0; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; + read_pos = 0; } else { read_block--; - at_end=true; - ret =0; + at_end = true; + ret = 0; } } return ret; - } -int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const { - ERR_FAIL_COND_V(writing,0); - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(writing, 0); + ERR_FAIL_COND_V(!f, 0); if (at_end) { - read_eof=true; + read_eof = true; return 0; } + for (int i = 0; i < p_length; i++) { - for(int i=0;i<p_length;i++) { - - - p_dst[i]=read_ptr[read_pos]; + p_dst[i] = read_ptr[read_pos]; read_pos++; - if (read_pos>=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_block<read_block_count) { + if (read_block < read_block_count) { //read another block of compressed data - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; - read_pos=0; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; + read_pos = 0; } else { read_block--; - at_end=true; - if (i<p_length-1) - read_eof=true; + at_end = true; + if (i < p_length - 1) + read_eof = true; return i; - } } - } return p_length; - } -Error FileAccessCompressed::get_error() const{ +Error FileAccessCompressed::get_error() const { - return read_eof?ERR_FILE_EOF:OK; + return read_eof ? ERR_FILE_EOF : OK; } -void FileAccessCompressed::store_8(uint8_t p_dest){ +void FileAccessCompressed::store_8(uint8_t p_dest) { ERR_FAIL_COND(!f); ERR_FAIL_COND(!writing); WRITE_FIT(1); - write_ptr[write_pos++]=p_dest; - + write_ptr[write_pos++] = p_dest; } -bool FileAccessCompressed::file_exists(const String& p_name){ +bool FileAccessCompressed::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name,FileAccess::READ); + FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); if (!fa) return false; memdelete(fa); return true; } -uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) { +uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) { if (f) return f->get_modified_time(p_file); @@ -393,29 +365,27 @@ uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) { FileAccessCompressed::FileAccessCompressed() { - f=NULL; - magic="GCMP"; - block_size=16384; - cmode=Compression::MODE_DEFLATE; - writing=false; - write_ptr=0; - write_buffer_size=0; - write_max=0; - block_size=0; - read_eof=false; - at_end=false; - read_total=0; - read_ptr=NULL; - read_block=0; - read_block_count=0; - read_block_size=0; - read_pos=0; - + f = NULL; + magic = "GCMP"; + block_size = 16384; + cmode = Compression::MODE_DEFLATE; + writing = false; + write_ptr = 0; + write_buffer_size = 0; + write_max = 0; + block_size = 0; + read_eof = false; + at_end = false; + read_total = 0; + read_ptr = NULL; + read_block = 0; + read_block_count = 0; + read_block_size = 0; + read_pos = 0; } -FileAccessCompressed::~FileAccessCompressed(){ +FileAccessCompressed::~FileAccessCompressed() { if (f) close(); - } diff --git a/core/io/file_access_compressed.h b/core/io/file_access_compressed.h index 70034120f9..ea45c110d2 100644 --- a/core/io/file_access_compressed.h +++ b/core/io/file_access_compressed.h @@ -37,7 +37,7 @@ class FileAccessCompressed : public FileAccess { Compression::Mode cmode; bool writing; int write_pos; - uint8_t*write_ptr; + uint8_t *write_ptr; int write_buffer_size; int write_max; int block_size; @@ -58,24 +58,21 @@ class FileAccessCompressed : public FileAccess { Vector<ReadBlock> read_blocks; int read_total; - - - String magic; mutable Vector<uint8_t> buffer; FileAccess *f; -public: - void configure(const String& p_magic, Compression::Mode p_mode=Compression::MODE_FASTLZ, int p_block_size=4096); +public: + void configure(const String &p_magic, Compression::Mode p_mode = Compression::MODE_FASTLZ, int p_block_size = 4096); Error open_after_magic(FileAccess *p_base); - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -88,14 +85,12 @@ public: virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_name); ///< return true if a file exists - - virtual uint64_t _get_modified_time(const String& p_file); + virtual bool file_exists(const String &p_name); ///< return true if a file exists + virtual uint64_t _get_modified_time(const String &p_file); FileAccessCompressed(); virtual ~FileAccessCompressed(); - }; #endif // FILE_ACCESS_COMPRESSED_H diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp index 039458237d..03700cad48 100644 --- a/core/io/file_access_encrypted.cpp +++ b/core/io/file_access_encrypted.cpp @@ -36,55 +36,55 @@ #include "core/variant.h" #include <stdio.h> -Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode) { +Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode) { //print_line("open and parse!"); - ERR_FAIL_COND_V(file!=NULL,ERR_ALREADY_IN_USE); - ERR_FAIL_COND_V(p_key.size()!=32,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(file != NULL, ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(p_key.size() != 32, ERR_INVALID_PARAMETER); - pos=0; - eofed=false; + pos = 0; + eofed = false; - if (p_mode==MODE_WRITE_AES256) { + if (p_mode == MODE_WRITE_AES256) { data.clear(); - writing=true; - file=p_base; - mode=p_mode; - key=p_key; + writing = true; + file = p_base; + mode = p_mode; + key = p_key; - } else if (p_mode==MODE_READ) { + } else if (p_mode == MODE_READ) { - writing=false; - key=p_key; + writing = false; + key = p_key; uint32_t magic = p_base->get_32(); - print_line("MAGIC: "+itos(magic)); - ERR_FAIL_COND_V(magic!=COMP_MAGIC,ERR_FILE_UNRECOGNIZED); - mode=Mode(p_base->get_32()); - ERR_FAIL_INDEX_V(mode,MODE_MAX,ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(mode==0,ERR_FILE_CORRUPT); - print_line("MODE: "+itos(mode)); + print_line("MAGIC: " + itos(magic)); + ERR_FAIL_COND_V(magic != COMP_MAGIC, ERR_FILE_UNRECOGNIZED); + mode = Mode(p_base->get_32()); + ERR_FAIL_INDEX_V(mode, MODE_MAX, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(mode == 0, ERR_FILE_CORRUPT); + print_line("MODE: " + itos(mode)); unsigned char md5d[16]; - p_base->get_buffer(md5d,16); - length=p_base->get_64(); - base=p_base->get_pos(); - ERR_FAIL_COND_V(p_base->get_len() < base+length, ERR_FILE_CORRUPT ); + p_base->get_buffer(md5d, 16); + length = p_base->get_64(); + base = p_base->get_pos(); + ERR_FAIL_COND_V(p_base->get_len() < base + length, ERR_FILE_CORRUPT); int ds = length; if (ds % 16) { - ds+=16-(ds % 16); + ds += 16 - (ds % 16); } data.resize(ds); - int blen = p_base->get_buffer(data.ptr(),ds); - ERR_FAIL_COND_V(blen!=ds,ERR_FILE_CORRUPT); + int blen = p_base->get_buffer(data.ptr(), ds); + ERR_FAIL_COND_V(blen != ds, ERR_FILE_CORRUPT); aes256_context ctx; - aes256_init(&ctx,key.ptr()); + aes256_init(&ctx, key.ptr()); - for(size_t i=0;i<ds;i+=16) { + for (size_t i = 0; i < ds; i += 16) { - aes256_decrypt_ecb(&ctx,&data[i]); + aes256_decrypt_ecb(&ctx, &data[i]); } aes256_done(&ctx); @@ -93,37 +93,32 @@ Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_ MD5_CTX md5; MD5Init(&md5); - MD5Update(&md5,data.ptr(),data.size()); + MD5Update(&md5, data.ptr(), data.size()); MD5Final(&md5); + ERR_FAIL_COND_V(String::md5(md5.digest) != String::md5(md5d), ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(String::md5(md5.digest)!=String::md5(md5d),ERR_FILE_CORRUPT) ; - - - file=p_base; + file = p_base; } return OK; } -Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode){ - +Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode) { String cs = p_key.md5_text(); - ERR_FAIL_COND_V(cs.length()!=32,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(cs.length() != 32, ERR_INVALID_PARAMETER); Vector<uint8_t> key; key.resize(32); - for(int i=0;i<32;i++) { + for (int i = 0; i < 32; i++) { - key[i]=cs[i]; + key[i] = cs[i]; } - return open_and_parse(p_base,key,p_mode); + return open_and_parse(p_base, key, p_mode); } - - -Error FileAccessEncrypted::_open(const String& p_path, int p_mode_flags) { +Error FileAccessEncrypted::_open(const String &p_path, int p_mode_flags) { return OK; } @@ -137,26 +132,26 @@ void FileAccessEncrypted::close() { Vector<uint8_t> compressed; size_t len = data.size(); if (len % 16) { - len+=16-(len % 16); + len += 16 - (len % 16); } MD5_CTX md5; MD5Init(&md5); - MD5Update(&md5,data.ptr(),data.size()); + MD5Update(&md5, data.ptr(), data.size()); MD5Final(&md5); compressed.resize(len); - zeromem( compressed.ptr(), len ); - for(int i=0;i<data.size();i++) { - compressed[i]=data[i]; + zeromem(compressed.ptr(), len); + for (int i = 0; i < data.size(); i++) { + compressed[i] = data[i]; } aes256_context ctx; - aes256_init(&ctx,key.ptr()); + aes256_init(&ctx, key.ptr()); - for(size_t i=0;i<len;i+=16) { + for (size_t i = 0; i < len; i += 16) { - aes256_encrypt_ecb(&ctx,&compressed[i]); + aes256_encrypt_ecb(&ctx, &compressed[i]); } aes256_done(&ctx); @@ -164,14 +159,13 @@ void FileAccessEncrypted::close() { file->store_32(COMP_MAGIC); file->store_32(mode); - - file->store_buffer(md5.digest,16); + file->store_buffer(md5.digest, 16); file->store_64(data.size()); - file->store_buffer(compressed.ptr(),compressed.size()); + file->store_buffer(compressed.ptr(), compressed.size()); file->close(); memdelete(file); - file=NULL; + file = NULL; data.clear(); } else { @@ -179,143 +173,133 @@ void FileAccessEncrypted::close() { file->close(); memdelete(file); data.clear(); - file=NULL; + file = NULL; } - - - } -bool FileAccessEncrypted::is_open() const{ +bool FileAccessEncrypted::is_open() const { - return file!=NULL; + return file != NULL; } -void FileAccessEncrypted::seek(size_t p_position){ +void FileAccessEncrypted::seek(size_t p_position) { if (p_position > (size_t)data.size()) - p_position=data.size(); - - pos=p_position; - eofed=false; + p_position = data.size(); + pos = p_position; + eofed = false; } +void FileAccessEncrypted::seek_end(int64_t p_position) { -void FileAccessEncrypted::seek_end(int64_t p_position){ - - seek( data.size() + p_position ); + seek(data.size() + p_position); } -size_t FileAccessEncrypted::get_pos() const{ +size_t FileAccessEncrypted::get_pos() const { return pos; } -size_t FileAccessEncrypted::get_len() const{ +size_t FileAccessEncrypted::get_len() const { return data.size(); } -bool FileAccessEncrypted::eof_reached() const{ +bool FileAccessEncrypted::eof_reached() const { return eofed; } -uint8_t FileAccessEncrypted::get_8() const{ +uint8_t FileAccessEncrypted::get_8() const { - ERR_FAIL_COND_V(writing,0); - if (pos>=data.size()) { - eofed=true; + ERR_FAIL_COND_V(writing, 0); + if (pos >= data.size()) { + eofed = true; return 0; } uint8_t b = data[pos]; pos++; return b; - } -int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const { - ERR_FAIL_COND_V(writing,0); + ERR_FAIL_COND_V(writing, 0); - int to_copy=MIN(p_length,data.size()-pos); - for(int i=0;i<to_copy;i++) { + int to_copy = MIN(p_length, data.size() - pos); + for (int i = 0; i < to_copy; i++) { - p_dst[i]=data[pos++]; + p_dst[i] = data[pos++]; } - if (to_copy<p_length) { - eofed=true; + if (to_copy < p_length) { + eofed = true; } - return to_copy; } -Error FileAccessEncrypted::get_error() const{ +Error FileAccessEncrypted::get_error() const { - return eofed?ERR_FILE_EOF:OK; + return eofed ? ERR_FILE_EOF : OK; } -void FileAccessEncrypted::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessEncrypted::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL_COND(!writing); - if (pos<data.size()) { + if (pos < data.size()) { - for(int i=0;i<p_length;i++) { + for (int i = 0; i < p_length; i++) { store_8(p_src[i]); } - } else if (pos==data.size()) { + } else if (pos == data.size()) { - data.resize(pos+p_length); - for(int i=0;i<p_length;i++) { + data.resize(pos + p_length); + for (int i = 0; i < p_length; i++) { - data[pos+i]=p_src[i]; + data[pos + i] = p_src[i]; } - pos+=p_length; + pos += p_length; } } - -void FileAccessEncrypted::store_8(uint8_t p_dest){ +void FileAccessEncrypted::store_8(uint8_t p_dest) { ERR_FAIL_COND(!writing); - if (pos<data.size()) { - data[pos]=p_dest; + if (pos < data.size()) { + data[pos] = p_dest; pos++; - } else if (pos==data.size()){ + } else if (pos == data.size()) { data.push_back(p_dest); pos++; } } -bool FileAccessEncrypted::file_exists(const String& p_name){ +bool FileAccessEncrypted::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name,FileAccess::READ); + FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); if (!fa) return false; memdelete(fa); return true; } -uint64_t FileAccessEncrypted::_get_modified_time(const String& p_file){ - +uint64_t FileAccessEncrypted::_get_modified_time(const String &p_file) { return 0; } FileAccessEncrypted::FileAccessEncrypted() { - file=NULL; - pos=0; - eofed=false; - mode=MODE_MAX; - writing=false; + file = NULL; + pos = 0; + eofed = false; + mode = MODE_MAX; + writing = false; } - FileAccessEncrypted::~FileAccessEncrypted() { if (file) diff --git a/core/io/file_access_encrypted.h b/core/io/file_access_encrypted.h index 51ed9a8677..ac4d2bd1c7 100644 --- a/core/io/file_access_encrypted.h +++ b/core/io/file_access_encrypted.h @@ -29,12 +29,10 @@ #ifndef FILE_ACCESS_ENCRYPTED_H #define FILE_ACCESS_ENCRYPTED_H - #include "os/file_access.h" class FileAccessEncrypted : public FileAccess { public: - enum Mode { MODE_READ, MODE_WRITE_AES256, @@ -42,8 +40,6 @@ public: }; private: - - Mode mode; Vector<uint8_t> key; bool writing; @@ -54,21 +50,16 @@ private: mutable size_t pos; mutable bool eofed; - public: + Error open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode); + Error open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode); - - - - Error open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode); - Error open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode); - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -80,11 +71,11 @@ public: virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes + virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes - virtual bool file_exists(const String& p_name); ///< return true if a file exists + virtual bool file_exists(const String &p_name); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file); + virtual uint64_t _get_modified_time(const String &p_file); FileAccessEncrypted(); ~FileAccessEncrypted(); diff --git a/core/io/file_access_memory.cpp b/core/io/file_access_memory.cpp index b4ba14ddc9..966109bfe1 100644 --- a/core/io/file_access_memory.cpp +++ b/core/io/file_access_memory.cpp @@ -28,12 +28,12 @@ /*************************************************************************/ #include "file_access_memory.h" -#include "os/dir_access.h" -#include "os/copymem.h" #include "global_config.h" #include "map.h" +#include "os/copymem.h" +#include "os/dir_access.h" -static Map<String, Vector<uint8_t> >* files = NULL; +static Map<String, Vector<uint8_t> > *files = NULL; void FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) { @@ -59,13 +59,12 @@ void FileAccessMemory::cleanup() { memdelete(files); } - -FileAccess* FileAccessMemory::create() { +FileAccess *FileAccessMemory::create() { return memnew(FileAccessMemory); } -bool FileAccessMemory::file_exists(const String& p_name) { +bool FileAccessMemory::file_exists(const String &p_name) { String name = fix_path(p_name); //name = DirAccess::normalize_path(name); @@ -73,23 +72,22 @@ bool FileAccessMemory::file_exists(const String& p_name) { return files && (files->find(name) != NULL); } +Error FileAccessMemory::open_custom(const uint8_t *p_data, int p_len) { -Error FileAccessMemory::open_custom(const uint8_t* p_data, int p_len) { - - data=(uint8_t*)p_data; - length=p_len; - pos=0; + data = (uint8_t *)p_data; + length = p_len; + pos = 0; return OK; } -Error FileAccessMemory::_open(const String& p_path, int p_mode_flags) { +Error FileAccessMemory::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND); String name = fix_path(p_path); //name = DirAccess::normalize_path(name); - Map<String, Vector<uint8_t> >::Element* E = files->find(name); + Map<String, Vector<uint8_t> >::Element *E = files->find(name); ERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND); data = &(E->get()[0]); @@ -149,7 +147,7 @@ uint8_t FileAccessMemory::get_8() const { return ret; } -int FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessMemory::get_buffer(uint8_t *p_dst, int p_length) const { ERR_FAIL_COND_V(!data, -1); @@ -178,7 +176,7 @@ void FileAccessMemory::store_8(uint8_t p_byte) { data[pos++] = p_byte; } -void FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessMemory::store_buffer(const uint8_t *p_src, int p_length) { int left = length - pos; int write = MIN(p_length, left); diff --git a/core/io/file_access_memory.h b/core/io/file_access_memory.h index c6dda07971..687e3e9bee 100644 --- a/core/io/file_access_memory.h +++ b/core/io/file_access_memory.h @@ -33,19 +33,18 @@ class FileAccessMemory : public FileAccess { - uint8_t* data; + uint8_t *data; int length; mutable int pos; - static FileAccess* create(); + static FileAccess *create(); public: - static void register_file(String p_name, Vector<uint8_t> p_data); static void cleanup(); - virtual Error open_custom(const uint8_t* p_data, int p_len); ///< open a file - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error open_custom(const uint8_t *p_data, int p_len); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open @@ -58,18 +57,16 @@ public: virtual uint8_t get_8() const; ///< get a byte - virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes + virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes - - virtual bool file_exists(const String& p_name); ///< return true if a file exists - - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } + virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes + virtual bool file_exists(const String &p_name); ///< return true if a file exists + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } FileAccessMemory(); }; diff --git a/core/io/file_access_network.cpp b/core/io/file_access_network.cpp index d9fdc9cedc..9120b55565 100644 --- a/core/io/file_access_network.cpp +++ b/core/io/file_access_network.cpp @@ -27,19 +27,16 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "file_access_network.h" -#include "marshalls.h" #include "global_config.h" -#include "os/os.h" #include "io/ip.h" - - +#include "marshalls.h" +#include "os/os.h" //#define DEBUG_PRINT(m_p) print_line(m_p) //#define DEBUG_TIME(m_what) printf("MS: %s - %lli\n",m_what,OS::get_singleton()->get_ticks_usec()); #define DEBUG_PRINT(m_p) #define DEBUG_TIME(m_what) - void FileAccessNetworkClient::lock_mutex() { mutex->lock(); @@ -50,59 +47,55 @@ void FileAccessNetworkClient::unlock_mutex() { lockcount--; mutex->unlock(); - } void FileAccessNetworkClient::put_32(int p_32) { uint8_t buf[4]; - encode_uint32(p_32,buf); - client->put_data(buf,4); - DEBUG_PRINT("put32: "+itos(p_32)); + encode_uint32(p_32, buf); + client->put_data(buf, 4); + DEBUG_PRINT("put32: " + itos(p_32)); } void FileAccessNetworkClient::put_64(int64_t p_64) { uint8_t buf[8]; - encode_uint64(p_64,buf); - client->put_data(buf,8); - DEBUG_PRINT("put64: "+itos(p_64)); - + encode_uint64(p_64, buf); + client->put_data(buf, 8); + DEBUG_PRINT("put64: " + itos(p_64)); } int FileAccessNetworkClient::get_32() { uint8_t buf[4]; - client->get_data(buf,4); + client->get_data(buf, 4); return decode_uint32(buf); - } int64_t FileAccessNetworkClient::get_64() { uint8_t buf[8]; - client->get_data(buf,8); + client->get_data(buf, 8); return decode_uint64(buf); - } void FileAccessNetworkClient::_thread_func() { client->set_nodelay(true); - while(!quit) { + while (!quit) { - DEBUG_PRINT("SEM WAIT - "+itos(sem->get())); + DEBUG_PRINT("SEM WAIT - " + itos(sem->get())); Error err = sem->wait(); DEBUG_TIME("sem_unlock"); //DEBUG_PRINT("semwait returned "+itos(werr)); - DEBUG_PRINT("MUTEX LOCK "+itos(lockcount)); + DEBUG_PRINT("MUTEX LOCK " + itos(lockcount)); DEBUG_PRINT("POPO"); DEBUG_PRINT("PEPE"); lock_mutex(); DEBUG_PRINT("MUTEX PASS"); blockrequest_mutex->lock(); - while(block_requests.size()) { + while (block_requests.size()) { put_32(block_requests.front()->get().id); put_32(FileAccessNetwork::COMMAND_READ_BLOCK); put_64(block_requests.front()->get().offset); @@ -117,35 +110,32 @@ void FileAccessNetworkClient::_thread_func() { int id = get_32(); int response = get_32(); - DEBUG_PRINT("GET RESPONSE: "+itos(response)); + DEBUG_PRINT("GET RESPONSE: " + itos(response)); - FileAccessNetwork *fa=NULL; + FileAccessNetwork *fa = NULL; - if (response!=FileAccessNetwork::RESPONSE_DATA) { + if (response != FileAccessNetwork::RESPONSE_DATA) { ERR_FAIL_COND(!accesses.has(id)); } if (accesses.has(id)) - fa=accesses[id]; + fa = accesses[id]; - - switch(response) { + switch (response) { case FileAccessNetwork::RESPONSE_OPEN: { - DEBUG_TIME("sem_open"); int status = get_32(); - if (status!=OK) { - fa->_respond(0,Error(status)); + if (status != OK) { + fa->_respond(0, Error(status)); } else { uint64_t len = get_64(); - fa->_respond(len,Error(status)); + fa->_respond(len, Error(status)); } fa->sem->post(); - } break; case FileAccessNetwork::RESPONSE_DATA: { @@ -154,104 +144,95 @@ void FileAccessNetworkClient::_thread_func() { Vector<uint8_t> block; block.resize(len); - client->get_data(block.ptr(),len); + client->get_data(block.ptr(), len); if (fa) //may have been queued - fa->_set_block(offset,block); + fa->_set_block(offset, block); } break; case FileAccessNetwork::RESPONSE_FILE_EXISTS: { - int status = get_32(); - fa->exists_modtime=status!=0; + fa->exists_modtime = status != 0; fa->sem->post(); - - } break; case FileAccessNetwork::RESPONSE_GET_MODTIME: { - uint64_t status = get_64(); - fa->exists_modtime=status; + fa->exists_modtime = status; fa->sem->post(); } break; - } - unlock_mutex(); } - } void FileAccessNetworkClient::_thread_func(void *s) { - FileAccessNetworkClient *self =(FileAccessNetworkClient*)s; + FileAccessNetworkClient *self = (FileAccessNetworkClient *)s; self->_thread_func(); - } -Error FileAccessNetworkClient::connect(const String& p_host,int p_port,const String& p_password) { +Error FileAccessNetworkClient::connect(const String &p_host, int p_port, const String &p_password) { IP_Address ip; if (p_host.is_valid_ip_address()) { - ip=p_host; + ip = p_host; } else { - ip=IP::get_singleton()->resolve_hostname(p_host); + ip = IP::get_singleton()->resolve_hostname(p_host); } - DEBUG_PRINT("IP: "+String(ip)+" port "+itos(p_port)); - Error err = client->connect_to_host(ip,p_port); - ERR_FAIL_COND_V(err,err); - while(client->get_status()==StreamPeerTCP::STATUS_CONNECTING) { -//DEBUG_PRINT("trying to connect...."); + DEBUG_PRINT("IP: " + String(ip) + " port " + itos(p_port)); + Error err = client->connect_to_host(ip, p_port); + ERR_FAIL_COND_V(err, err); + while (client->get_status() == StreamPeerTCP::STATUS_CONNECTING) { + //DEBUG_PRINT("trying to connect...."); OS::get_singleton()->delay_usec(1000); } - if (client->get_status()!=StreamPeerTCP::STATUS_CONNECTED) { + if (client->get_status() != StreamPeerTCP::STATUS_CONNECTED) { return ERR_CANT_CONNECT; } CharString cs = p_password.utf8(); put_32(cs.length()); - client->put_data((const uint8_t*)cs.ptr(),cs.length()); + client->put_data((const uint8_t *)cs.ptr(), cs.length()); int e = get_32(); - if (e!=OK) { + if (e != OK) { return ERR_INVALID_PARAMETER; } - thread = Thread::create(_thread_func,this); + thread = Thread::create(_thread_func, this); return OK; } -FileAccessNetworkClient *FileAccessNetworkClient::singleton=NULL; - +FileAccessNetworkClient *FileAccessNetworkClient::singleton = NULL; FileAccessNetworkClient::FileAccessNetworkClient() { - thread=NULL; + thread = NULL; mutex = Mutex::create(); blockrequest_mutex = Mutex::create(); - quit=false; - singleton=this; - last_id=0; - client = Ref<StreamPeerTCP>( StreamPeerTCP::create_ref() ); - sem=Semaphore::create(); - lockcount=0; + quit = false; + singleton = this; + last_id = 0; + client = Ref<StreamPeerTCP>(StreamPeerTCP::create_ref()); + sem = Semaphore::create(); + lockcount = 0; } FileAccessNetworkClient::~FileAccessNetworkClient() { if (thread) { - quit=true; + quit = true; sem->post(); Thread::wait_to_finish(thread); memdelete(thread); @@ -260,70 +241,62 @@ FileAccessNetworkClient::~FileAccessNetworkClient() { memdelete(blockrequest_mutex); memdelete(mutex); memdelete(sem); - - } -void FileAccessNetwork::_set_block(size_t p_offset,const Vector<uint8_t>& p_block) { +void FileAccessNetwork::_set_block(size_t p_offset, const Vector<uint8_t> &p_block) { - - int page = p_offset/page_size; - ERR_FAIL_INDEX(page,pages.size()); - if (page<pages.size()-1) { - ERR_FAIL_COND(p_block.size()!=page_size); + int page = p_offset / page_size; + ERR_FAIL_INDEX(page, pages.size()); + if (page < pages.size() - 1) { + ERR_FAIL_COND(p_block.size() != page_size); } else { - ERR_FAIL_COND( (p_block.size() != (total_size%page_size))); + ERR_FAIL_COND((p_block.size() != (total_size % page_size))); } buffer_mutex->lock(); - pages[page].buffer=p_block; - pages[page].queued=false; + pages[page].buffer = p_block; + pages[page].queued = false; buffer_mutex->unlock(); - if (waiting_on_page==page) { - waiting_on_page=-1; + if (waiting_on_page == page) { + waiting_on_page = -1; page_sem->post(); } } +void FileAccessNetwork::_respond(size_t p_len, Error p_status) { -void FileAccessNetwork::_respond(size_t p_len,Error p_status) { - - DEBUG_PRINT("GOT RESPONSE - len: "+itos(p_len)+" status: "+itos(p_status)); - response=p_status; - if (response!=OK) + DEBUG_PRINT("GOT RESPONSE - len: " + itos(p_len) + " status: " + itos(p_status)); + response = p_status; + if (response != OK) return; - opened=true; - total_size=p_len; - int pc = ((total_size-1)/page_size)+1; + opened = true; + total_size = p_len; + int pc = ((total_size - 1) / page_size) + 1; pages.resize(pc); - - - - } -Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) { +Error FileAccessNetwork::_open(const String &p_path, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags!=READ,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(p_mode_flags != READ, ERR_UNAVAILABLE); if (opened) close(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - DEBUG_PRINT("open: "+p_path); + DEBUG_PRINT("open: " + p_path); DEBUG_TIME("open_begin"); nc->lock_mutex(); nc->put_32(id); - nc->accesses[id]=this; + nc->accesses[id] = this; nc->put_32(COMMAND_OPEN_FILE); - CharString cs =p_path.utf8(); + CharString cs = p_path.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); - pos=0; - eof_flag=false; - last_page=-1; - last_page_buff=NULL; + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); + pos = 0; + eof_flag = false; + last_page = -1; + last_page_buff = NULL; //buffers.clear(); nc->unlock_mutex(); @@ -338,7 +311,7 @@ Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) { return response; } -void FileAccessNetwork::close(){ +void FileAccessNetwork::close() { if (!opened) return; @@ -350,110 +323,103 @@ void FileAccessNetwork::close(){ nc->put_32(id); nc->put_32(COMMAND_CLOSE); pages.clear(); - opened=false; + opened = false; nc->unlock_mutex(); - - } -bool FileAccessNetwork::is_open() const{ +bool FileAccessNetwork::is_open() const { return opened; } -void FileAccessNetwork::seek(size_t p_position){ +void FileAccessNetwork::seek(size_t p_position) { ERR_FAIL_COND(!opened); - eof_flag=p_position>total_size; + eof_flag = p_position > total_size; - if (p_position>=total_size) { - p_position=total_size; + if (p_position >= total_size) { + p_position = total_size; } - pos=p_position; + pos = p_position; } -void FileAccessNetwork::seek_end(int64_t p_position){ - - seek(total_size+p_position); +void FileAccessNetwork::seek_end(int64_t p_position) { + seek(total_size + p_position); } -size_t FileAccessNetwork::get_pos() const{ +size_t FileAccessNetwork::get_pos() const { - ERR_FAIL_COND_V(!opened,0); + ERR_FAIL_COND_V(!opened, 0); return pos; } -size_t FileAccessNetwork::get_len() const{ +size_t FileAccessNetwork::get_len() const { - ERR_FAIL_COND_V(!opened,0); + ERR_FAIL_COND_V(!opened, 0); return total_size; } -bool FileAccessNetwork::eof_reached() const{ +bool FileAccessNetwork::eof_reached() const { - ERR_FAIL_COND_V(!opened,false); + ERR_FAIL_COND_V(!opened, false); return eof_flag; } -uint8_t FileAccessNetwork::get_8() const{ +uint8_t FileAccessNetwork::get_8() const { uint8_t v; - get_buffer(&v,1); + get_buffer(&v, 1); return v; - } - void FileAccessNetwork::_queue_page(int p_page) const { - if (p_page>=pages.size()) + if (p_page >= pages.size()) return; if (pages[p_page].buffer.empty() && !pages[p_page].queued) { - FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->blockrequest_mutex->lock(); FileAccessNetworkClient::BlockRequest br; - br.id=id; - br.offset=size_t(p_page)*page_size; - br.size=page_size; + br.id = id; + br.offset = size_t(p_page) * page_size; + br.size = page_size; nc->block_requests.push_back(br); - pages[p_page].queued=true; + pages[p_page].queued = true; nc->blockrequest_mutex->unlock(); DEBUG_PRINT("QUEUE PAGE POST"); nc->sem->post(); - DEBUG_PRINT("queued "+itos(p_page)); + DEBUG_PRINT("queued " + itos(p_page)); } - } -int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const { //bool eof=false; - if (pos+p_length>total_size) { - eof_flag=true; + if (pos + p_length > total_size) { + eof_flag = true; } - if (pos+p_length>=total_size) { - p_length=total_size-pos; + if (pos + p_length >= total_size) { + p_length = total_size - pos; } //FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - uint8_t *buff=last_page_buff; + uint8_t *buff = last_page_buff; - for(int i=0;i<p_length;i++) { + for (int i = 0; i < p_length; i++) { - int page=pos/page_size; + int page = pos / page_size; - if (page!=last_page) { + if (page != last_page) { buffer_mutex->lock(); if (pages[page].buffer.empty()) { //fuck - waiting_on_page=page; - for(int j=0;j<read_ahead;j++) { + waiting_on_page = page; + for (int j = 0; j < read_ahead; j++) { - _queue_page(page+j); + _queue_page(page + j); } buffer_mutex->unlock(); DEBUG_PRINT("wait"); @@ -461,30 +427,30 @@ int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{ DEBUG_PRINT("done"); } else { - for(int j=0;j<read_ahead;j++) { + for (int j = 0; j < read_ahead; j++) { - _queue_page(page+j); + _queue_page(page + j); } - buff=pages[page].buffer.ptr(); + buff = pages[page].buffer.ptr(); //queue pages buffer_mutex->unlock(); } - buff=pages[page].buffer.ptr(); - last_page_buff=buff; - last_page=page; + buff = pages[page].buffer.ptr(); + last_page_buff = buff; + last_page = page; } - p_dst[i]=buff[pos-uint64_t(page)*page_size]; + p_dst[i] = buff[pos - uint64_t(page) * page_size]; pos++; } return p_length; } -Error FileAccessNetwork::get_error() const{ +Error FileAccessNetwork::get_error() const { - return pos==total_size?ERR_FILE_EOF:OK; + return pos == total_size ? ERR_FILE_EOF : OK; } void FileAccessNetwork::store_8(uint8_t p_dest) { @@ -492,71 +458,66 @@ void FileAccessNetwork::store_8(uint8_t p_dest) { ERR_FAIL(); } -bool FileAccessNetwork::file_exists(const String& p_path){ +bool FileAccessNetwork::file_exists(const String &p_path) { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); nc->put_32(id); nc->put_32(COMMAND_FILE_EXISTS); - CharString cs=p_path.utf8(); + CharString cs = p_path.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); nc->unlock_mutex(); DEBUG_PRINT("FILE EXISTS POST"); nc->sem->post(); sem->wait(); - return exists_modtime!=0; - + return exists_modtime != 0; } -uint64_t FileAccessNetwork::_get_modified_time(const String& p_file){ +uint64_t FileAccessNetwork::_get_modified_time(const String &p_file) { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); nc->put_32(id); nc->put_32(COMMAND_GET_MODTIME); - CharString cs=p_file.utf8(); + CharString cs = p_file.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); nc->unlock_mutex(); DEBUG_PRINT("MODTIME POST"); nc->sem->post(); sem->wait(); return exists_modtime; - } void FileAccessNetwork::configure() { - GLOBAL_DEF("network/remote_fs/page_size",65536); - GLOBAL_DEF("network/remote_fs/page_read_ahead",4); - GLOBAL_DEF("network/remote_fs/max_pages",20); - + GLOBAL_DEF("network/remote_fs/page_size", 65536); + GLOBAL_DEF("network/remote_fs/page_read_ahead", 4); + GLOBAL_DEF("network/remote_fs/max_pages", 20); } FileAccessNetwork::FileAccessNetwork() { - eof_flag=false; - opened=false; - pos=0; - sem=Semaphore::create(); - page_sem=Semaphore::create(); - buffer_mutex=Mutex::create(); + eof_flag = false; + opened = false; + pos = 0; + sem = Semaphore::create(); + page_sem = Semaphore::create(); + buffer_mutex = Mutex::create(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); - id=nc->last_id++; - nc->accesses[id]=this; + id = nc->last_id++; + nc->accesses[id] = this; nc->unlock_mutex(); page_size = GLOBAL_GET("network/remote_fs/page_size"); read_ahead = GLOBAL_GET("network/remote_fs/page_read_ahead"); max_pages = GLOBAL_GET("network/remote_fs/max_pages"); - last_activity_val=0; - waiting_on_page=-1; - last_page=-1; - - + last_activity_val = 0; + waiting_on_page = -1; + last_page = -1; } FileAccessNetwork::~FileAccessNetwork() { @@ -568,8 +529,7 @@ FileAccessNetwork::~FileAccessNetwork() { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); - id=nc->last_id++; + id = nc->last_id++; nc->accesses.erase(id); nc->unlock_mutex(); - } diff --git a/core/io/file_access_network.h b/core/io/file_access_network.h index 4dbfb04b10..bb3d22c1e9 100644 --- a/core/io/file_access_network.h +++ b/core/io/file_access_network.h @@ -29,16 +29,15 @@ #ifndef FILE_ACCESS_NETWORK_H #define FILE_ACCESS_NETWORK_H +#include "io/stream_peer_tcp.h" #include "os/file_access.h" #include "os/semaphore.h" #include "os/thread.h" -#include "io/stream_peer_tcp.h" class FileAccessNetwork; class FileAccessNetworkClient { - struct BlockRequest { int id; @@ -55,7 +54,7 @@ class FileAccessNetworkClient { bool quit; Mutex *mutex; Mutex *blockrequest_mutex; - Map<int,FileAccessNetwork*> accesses; + Map<int, FileAccessNetwork *> accesses; Ref<StreamPeerTCP> client; int last_id; @@ -72,18 +71,16 @@ class FileAccessNetworkClient { void lock_mutex(); void unlock_mutex(); -friend class FileAccessNetwork; + friend class FileAccessNetwork; static FileAccessNetworkClient *singleton; public: - static FileAccessNetworkClient *get_singleton() { return singleton; } - Error connect(const String& p_host,int p_port,const String& p_password=""); + Error connect(const String &p_host, int p_port, const String &p_password = ""); FileAccessNetworkClient(); ~FileAccessNetworkClient(); - }; class FileAccessNetwork : public FileAccess { @@ -109,21 +106,23 @@ class FileAccessNetwork : public FileAccess { int activity; bool queued; Vector<uint8_t> buffer; - Page() { activity=0; queued=false; } + Page() { + activity = 0; + queued = false; + } }; - mutable Vector< Page > pages; + mutable Vector<Page> pages; mutable Error response; uint64_t exists_modtime; -friend class FileAccessNetworkClient; + friend class FileAccessNetworkClient; void _queue_page(int p_page) const; - void _respond(size_t p_len,Error p_status); - void _set_block(size_t p_offset,const Vector<uint8_t>& p_block); + void _respond(size_t p_len, Error p_status); + void _set_block(size_t p_offset, const Vector<uint8_t> &p_block); public: - enum Command { COMMAND_OPEN_FILE, COMMAND_READ_BLOCK, @@ -139,13 +138,12 @@ public: RESPONSE_GET_MODTIME, }; - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -158,9 +156,9 @@ public: virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_path); ///< return true if a file exists + virtual bool file_exists(const String &p_path); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file); + virtual uint64_t _get_modified_time(const String &p_file); static void configure(); diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp index fa1bebde16..91d256ee2b 100644 --- a/core/io/file_access_pack.cpp +++ b/core/io/file_access_pack.cpp @@ -33,9 +33,9 @@ #define PACK_VERSION 1 -Error PackedData::add_pack(const String& p_path) { +Error PackedData::add_pack(const String &p_path) { - for (int i=0; i<sources.size(); i++) { + for (int i = 0; i < sources.size(); i++) { if (sources[i]->try_open_pack(p_path)) { @@ -46,7 +46,7 @@ Error PackedData::add_pack(const String& p_path) { return ERR_FILE_UNRECOGNIZED; }; -void PackedData::add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src) { +void PackedData::add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src) { PathMD5 pmd5(path.md5_buffer()); //printf("adding path %ls, %lli, %lli\n", path.c_str(), pmd5.a, pmd5.b); @@ -54,35 +54,35 @@ void PackedData::add_path(const String& pkg_path, const String& path, uint64_t o bool exists = files.has(pmd5); PackedFile pf; - pf.pack=pkg_path; - pf.offset=ofs; - pf.size=size; - for(int i=0;i<16;i++) - pf.md5[i]=p_md5[i]; + pf.pack = pkg_path; + pf.offset = ofs; + pf.size = size; + for (int i = 0; i < 16; i++) + pf.md5[i] = p_md5[i]; pf.src = p_src; - files[pmd5]=pf; + files[pmd5] = pf; if (!exists) { //search for dir - String p = path.replace_first("res://",""); - PackedDir *cd=root; + String p = path.replace_first("res://", ""); + PackedDir *cd = root; - if (p.find("/")!=-1) { //in a subdir + if (p.find("/") != -1) { //in a subdir - Vector<String> ds=p.get_base_dir().split("/"); + Vector<String> ds = p.get_base_dir().split("/"); - for(int j=0;j<ds.size();j++) { + for (int j = 0; j < ds.size(); j++) { if (!cd->subdirs.has(ds[j])) { - PackedDir *pd = memnew( PackedDir ); - pd->name=ds[j]; - pd->parent=cd; - cd->subdirs[pd->name]=pd; - cd=pd; + PackedDir *pd = memnew(PackedDir); + pd->name = ds[j]; + pd->parent = cd; + cd->subdirs[pd->name] = pd; + cd = pd; } else { - cd=cd->subdirs[ds[j]]; + cd = cd->subdirs[ds[j]]; } } } @@ -97,61 +97,59 @@ void PackedData::add_pack_source(PackSource *p_source) { } }; -PackedData *PackedData::singleton=NULL; +PackedData *PackedData::singleton = NULL; PackedData::PackedData() { - singleton=this; - root=memnew(PackedDir); - root->parent=NULL; - disabled=false; + singleton = this; + root = memnew(PackedDir); + root->parent = NULL; + disabled = false; add_pack_source(memnew(PackedSourcePCK)); } void PackedData::_free_packed_dirs(PackedDir *p_dir) { - for (Map<String,PackedDir*>::Element *E=p_dir->subdirs.front();E;E=E->next()) + for (Map<String, PackedDir *>::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { - for(int i=0;i<sources.size();i++) { + for (int i = 0; i < sources.size(); i++) { memdelete(sources[i]); } _free_packed_dirs(root); } - ////////////////////////////////////////////////////////////////// -bool PackedSourcePCK::try_open_pack(const String& p_path) { +bool PackedSourcePCK::try_open_pack(const String &p_path) { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) return false; //printf("try open %ls!\n", p_path.c_str()); - uint32_t magic= f->get_32(); + uint32_t magic = f->get_32(); if (magic != 0x43504447) { //maybe at he end.... self contained exe f->seek_end(); - f->seek( f->get_pos() -4 ); + f->seek(f->get_pos() - 4); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } - f->seek( f->get_pos() -12 ); - + f->seek(f->get_pos() - 12); uint64_t ds = f->get_64(); - f->seek( f->get_pos() -ds-8 ); + f->seek(f->get_pos() - ds - 8); magic = f->get_32(); if (magic != 0x43504447) { @@ -159,7 +157,6 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { memdelete(f); return false; } - } uint32_t version = f->get_32(); @@ -167,25 +164,25 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { uint32_t ver_minor = f->get_32(); uint32_t ver_rev = f->get_32(); - ERR_EXPLAIN("Pack version unsupported: "+itos(version)); - ERR_FAIL_COND_V( version != PACK_VERSION, ERR_INVALID_DATA); - ERR_EXPLAIN("Pack created with a newer version of the engine: "+itos(ver_major)+"."+itos(ver_minor)+"."+itos(ver_rev)); - ERR_FAIL_COND_V( ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA); + ERR_EXPLAIN("Pack version unsupported: " + itos(version)); + ERR_FAIL_COND_V(version != PACK_VERSION, ERR_INVALID_DATA); + ERR_EXPLAIN("Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "." + itos(ver_rev)); + ERR_FAIL_COND_V(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA); - for(int i=0;i<16;i++) { + for (int i = 0; i < 16; i++) { //reserved f->get_32(); } int file_count = f->get_32(); - for(int i=0;i<file_count;i++) { + for (int i = 0; i < file_count; i++) { uint32_t sl = f->get_32(); CharString cs; - cs.resize(sl+1); - f->get_buffer((uint8_t*)cs.ptr(),sl); - cs[sl]=0; + cs.resize(sl + 1); + f->get_buffer((uint8_t *)cs.ptr(), sl); + cs[sl] = 0; String path; path.parse_utf8(cs.ptr()); @@ -193,22 +190,21 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { uint64_t ofs = f->get_64(); uint64_t size = f->get_64(); uint8_t md5[16]; - f->get_buffer(md5,16); - PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5,this); + f->get_buffer(md5, 16); + PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this); }; return true; }; -FileAccess* PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile* p_file) { +FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { - return memnew( FileAccessPack(p_path, *p_file)); + return memnew(FileAccessPack(p_path, *p_file)); }; ////////////////////////////////////////////////////////////////// - -Error FileAccessPack::_open(const String& p_path, int p_mode_flags) { +Error FileAccessPack::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_V(ERR_UNAVAILABLE); return ERR_UNAVAILABLE; @@ -219,45 +215,44 @@ void FileAccessPack::close() { f->close(); } -bool FileAccessPack::is_open() const{ +bool FileAccessPack::is_open() const { return f->is_open(); } -void FileAccessPack::seek(size_t p_position){ +void FileAccessPack::seek(size_t p_position) { - if (p_position>pf.size) { - eof=true; + if (p_position > pf.size) { + eof = true; } else { - eof=false; + eof = false; } - f->seek(pf.offset+p_position); - pos=p_position; + f->seek(pf.offset + p_position); + pos = p_position; } -void FileAccessPack::seek_end(int64_t p_position){ - - seek(pf.size+p_position); +void FileAccessPack::seek_end(int64_t p_position) { + seek(pf.size + p_position); } size_t FileAccessPack::get_pos() const { return pos; } -size_t FileAccessPack::get_len() const{ +size_t FileAccessPack::get_len() const { return pf.size; } -bool FileAccessPack::eof_reached() const{ +bool FileAccessPack::eof_reached() const { return eof; } uint8_t FileAccessPack::get_8() const { - if (pos>=pf.size) { - eof=true; + if (pos >= pf.size) { + eof = true; return 0; } @@ -265,23 +260,22 @@ uint8_t FileAccessPack::get_8() const { return f->get_8(); } - -int FileAccessPack::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessPack::get_buffer(uint8_t *p_dst, int p_length) const { if (eof) return 0; - int64_t to_read=p_length; - if (to_read+pos > pf.size) { - eof=true; - to_read=int64_t(pf.size)-int64_t(pos); + int64_t to_read = p_length; + if (to_read + pos > pf.size) { + eof = true; + to_read = int64_t(pf.size) - int64_t(pos); } - pos+=p_length; + pos += p_length; - if (to_read<=0) + if (to_read <= 0) return 0; - f->get_buffer(p_dst,to_read); + f->get_buffer(p_dst, to_read); return to_read; } @@ -301,32 +295,29 @@ Error FileAccessPack::get_error() const { void FileAccessPack::store_8(uint8_t p_dest) { ERR_FAIL(); - } -void FileAccessPack::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessPack::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL(); - } -bool FileAccessPack::file_exists(const String& p_name) { +bool FileAccessPack::file_exists(const String &p_name) { return false; } +FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) { -FileAccessPack::FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file) { - - pf=p_file; - f=FileAccess::open(pf.pack,FileAccess::READ); + pf = p_file; + f = FileAccess::open(pf.pack, FileAccess::READ); if (!f) { - ERR_EXPLAIN("Can't open pack-referenced file: "+String(pf.pack)); + ERR_EXPLAIN("Can't open pack-referenced file: " + String(pf.pack)); ERR_FAIL_COND(!f); } f->seek(pf.offset); - pos=0; - eof=false; + pos = 0; + eof = false; } FileAccessPack::~FileAccessPack() { @@ -334,24 +325,21 @@ FileAccessPack::~FileAccessPack() { memdelete(f); } - ////////////////////////////////////////////////////////////////////////////////// // DIR ACCESS ////////////////////////////////////////////////////////////////////////////////// - Error DirAccessPack::list_dir_begin() { - list_dirs.clear(); list_files.clear(); - for (Map<String,PackedData::PackedDir*>::Element *E=current->subdirs.front();E;E=E->next()) { + for (Map<String, PackedData::PackedDir *>::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } - for (Set<String>::Element *E=current->files.front();E;E=E->next()) { + for (Set<String>::Element *E = current->files.front(); E; E = E->next()) { list_files.push_back(E->get()); } @@ -359,15 +347,15 @@ Error DirAccessPack::list_dir_begin() { return OK; } -String DirAccessPack::get_next(){ +String DirAccessPack::get_next() { if (list_dirs.size()) { - cdir=true; + cdir = true; String d = list_dirs.front()->get(); list_dirs.pop_front(); return d; } else if (list_files.size()) { - cdir=false; + cdir = false; String f = list_files.front()->get(); list_files.pop_front(); return f; @@ -375,11 +363,11 @@ String DirAccessPack::get_next(){ return String(); } } -bool DirAccessPack::current_is_dir() const{ +bool DirAccessPack::current_is_dir() const { return cdir; } -bool DirAccessPack::current_is_hidden() const{ +bool DirAccessPack::current_is_hidden() const { return false; } @@ -400,20 +388,20 @@ String DirAccessPack::get_drive(int p_drive) { Error DirAccessPack::change_dir(String p_dir) { - String nd = p_dir.replace("\\","/"); - bool absolute=false; + String nd = p_dir.replace("\\", "/"); + bool absolute = false; if (nd.begins_with("res://")) { - nd=nd.replace_first("res://",""); - absolute=true; + nd = nd.replace_first("res://", ""); + absolute = true; } - nd=nd.simplify_path(); + nd = nd.simplify_path(); if (nd == "") nd = "."; if (nd.begins_with("/")) { - nd=nd.replace_first("/","") ; - absolute=true; + nd = nd.replace_first("/", ""); + absolute = true; } Vector<String> paths = nd.split("/"); @@ -425,18 +413,18 @@ Error DirAccessPack::change_dir(String p_dir) { else pd = current; - for(int i=0;i<paths.size();i++) { + for (int i = 0; i < paths.size(); i++) { String p = paths[i]; - if (p==".") { + if (p == ".") { continue; - } else if (p=="..") { + } else if (p == "..") { if (pd->parent) { - pd=pd->parent; + pd = pd->parent; } } else if (pd->subdirs.has(p)) { - pd=pd->subdirs[p]; + pd = pd->subdirs[p]; } else { @@ -444,29 +432,26 @@ Error DirAccessPack::change_dir(String p_dir) { } } - current=pd; + current = pd; return OK; - - } String DirAccessPack::get_current_dir() { String p; PackedData::PackedDir *pd = current; - while(pd->parent) { + while (pd->parent) { - if (pd!=current) - p="/"+p; - p=p+pd->name; + if (pd != current) + p = "/" + p; + p = p + pd->name; } - return "res://"+p; - + return "res://" + p; } -bool DirAccessPack::file_exists(String p_file){ +bool DirAccessPack::file_exists(String p_file) { return current->files.has(p_file); } @@ -476,36 +461,30 @@ bool DirAccessPack::dir_exists(String p_dir) { return current->subdirs.has(p_dir); } -Error DirAccessPack::make_dir(String p_dir){ +Error DirAccessPack::make_dir(String p_dir) { return ERR_UNAVAILABLE; } -Error DirAccessPack::rename(String p_from, String p_to){ +Error DirAccessPack::rename(String p_from, String p_to) { return ERR_UNAVAILABLE; - } -Error DirAccessPack::remove(String p_name){ +Error DirAccessPack::remove(String p_name) { return ERR_UNAVAILABLE; - } -size_t DirAccessPack::get_space_left(){ +size_t DirAccessPack::get_space_left() { return 0; } DirAccessPack::DirAccessPack() { - current=PackedData::get_singleton()->root; - cdir=false; + current = PackedData::get_singleton()->root; + cdir = false; } DirAccessPack::~DirAccessPack() { - - } - - diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h index 0a1320e57b..d16f5c461e 100644 --- a/core/io/file_access_pack.h +++ b/core/io/file_access_pack.h @@ -29,18 +29,18 @@ #ifndef FILE_ACCESS_PACK_H #define FILE_ACCESS_PACK_H -#include "os/file_access.h" -#include "os/dir_access.h" -#include "map.h" #include "list.h" +#include "map.h" +#include "os/dir_access.h" +#include "os/file_access.h" #include "print_string.h" class PackSource; class PackedData { -friend class FileAccessPack; -friend class DirAccessPack; -friend class PackSource; + friend class FileAccessPack; + friend class DirAccessPack; + friend class PackSource; public: struct PackedFile { @@ -49,21 +49,21 @@ public: uint64_t offset; //if offset is ZERO, the file was ERASED uint64_t size; uint8_t md5[16]; - PackSource* src; + PackSource *src; }; private: struct PackedDir { PackedDir *parent; String name; - Map<String,PackedDir*> subdirs; + Map<String, PackedDir *> subdirs; Set<String> files; }; struct PathMD5 { uint64_t a; uint64_t b; - bool operator < (const PathMD5& p_md5) const { + bool operator<(const PathMD5 &p_md5) const { if (p_md5.a == a) { return b < p_md5.b; @@ -72,7 +72,7 @@ private: } } - bool operator == (const PathMD5& p_md5) const { + bool operator==(const PathMD5 &p_md5) const { return a == p_md5.a && b == p_md5.b; }; @@ -81,14 +81,14 @@ private: }; PathMD5(const Vector<uint8_t> p_buf) { - a = *((uint64_t*)&p_buf[0]); - b = *((uint64_t*)&p_buf[8]); + a = *((uint64_t *)&p_buf[0]); + b = *((uint64_t *)&p_buf[8]); }; }; - Map<PathMD5,PackedFile> files; + Map<PathMD5, PackedFile> files; - Vector<PackSource*> sources; + Vector<PackSource *> sources; PackedDir *root; //Map<String,PackedDir*> dirs; @@ -99,18 +99,17 @@ private: void _free_packed_dirs(PackedDir *p_dir); public: + void add_pack_source(PackSource *p_source); + void add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src); // for PackSource - void add_pack_source(PackSource* p_source); - void add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src); // for PackSource - - void set_disabled(bool p_disabled) { disabled=p_disabled; } + void set_disabled(bool p_disabled) { disabled = p_disabled; } _FORCE_INLINE_ bool is_disabled() const { return disabled; } static PackedData *get_singleton() { return singleton; } - Error add_pack(const String& p_path); + Error add_pack(const String &p_path); - _FORCE_INLINE_ FileAccess *try_open_path(const String& p_path); - _FORCE_INLINE_ bool has_path(const String& p_path); + _FORCE_INLINE_ FileAccess *try_open_path(const String &p_path); + _FORCE_INLINE_ bool has_path(const String &p_path); PackedData(); ~PackedData(); @@ -119,21 +118,18 @@ public: class PackSource { public: - - virtual bool try_open_pack(const String& p_path)=0; - virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file)=0; + virtual bool try_open_pack(const String &p_path) = 0; + virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file) = 0; virtual ~PackSource() {} }; class PackedSourcePCK : public PackSource { public: - virtual bool try_open_pack(const String &p_path); - virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file); + virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); }; - class FileAccessPack : public FileAccess { PackedData::PackedFile pf; @@ -142,17 +138,15 @@ class FileAccessPack : public FileAccess { mutable bool eof; FileAccess *f; - virtual Error _open(const String& p_path, int p_mode_flags); - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } + virtual Error _open(const String &p_path, int p_mode_flags); + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } public: - - virtual void close(); virtual bool is_open() const; virtual void seek(size_t p_position); - virtual void seek_end(int64_t p_position=0); + virtual void seek_end(int64_t p_position = 0); virtual size_t get_pos() const; virtual size_t get_len() const; @@ -160,8 +154,7 @@ public: virtual uint8_t get_8() const; - - virtual int get_buffer(uint8_t *p_dst,int p_length) const; + virtual int get_buffer(uint8_t *p_dst, int p_length) const; virtual void set_endian_swap(bool p_swap); @@ -169,38 +162,34 @@ public: virtual void store_8(uint8_t p_dest); - virtual void store_buffer(const uint8_t *p_src,int p_length); - - virtual bool file_exists(const String& p_name); + virtual void store_buffer(const uint8_t *p_src, int p_length); + virtual bool file_exists(const String &p_name); - FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file); + FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file); ~FileAccessPack(); }; - -FileAccess *PackedData::try_open_path(const String& p_path) { +FileAccess *PackedData::try_open_path(const String &p_path) { //print_line("try open path " + p_path); PathMD5 pmd5(p_path.md5_buffer()); - Map<PathMD5,PackedFile>::Element *E=files.find(pmd5); + Map<PathMD5, PackedFile>::Element *E = files.find(pmd5); if (!E) return NULL; //not found - if (E->get().offset==0) + if (E->get().offset == 0) return NULL; //was erased return E->get().src->get_file(p_path, &E->get()); } -bool PackedData::has_path(const String& p_path) { +bool PackedData::has_path(const String &p_path) { return files.has(PathMD5(p_path.md5_buffer())); } - class DirAccessPack : public DirAccess { - PackedData::PackedDir *current; List<String> list_dirs; @@ -208,7 +197,6 @@ class DirAccessPack : public DirAccess { bool cdir; public: - virtual Error list_dir_begin(); virtual String get_next(); virtual bool current_is_dir() const; @@ -221,7 +209,6 @@ public: virtual Error change_dir(String p_dir); virtual String get_current_dir(); - virtual bool file_exists(String p_file); virtual bool dir_exists(String p_dir); @@ -234,8 +221,6 @@ public: DirAccessPack(); ~DirAccessPack(); - }; - #endif // FILE_ACCESS_PACK_H diff --git a/core/io/file_access_zip.cpp b/core/io/file_access_zip.cpp index 87f07cb7b1..4cc2edd1c3 100644 --- a/core/io/file_access_zip.cpp +++ b/core/io/file_access_zip.cpp @@ -30,78 +30,75 @@ #include "file_access_zip.h" -#include "core/os/file_access.h" #include "core/os/copymem.h" +#include "core/os/file_access.h" -ZipArchive* ZipArchive::instance = NULL; +ZipArchive *ZipArchive::instance = NULL; extern "C" { -static void* godot_open(void* data, const char* p_fname, int mode) { +static void *godot_open(void *data, const char *p_fname, int mode) { if (mode & ZLIB_FILEFUNC_MODE_WRITE) { return NULL; }; - FileAccess* f = (FileAccess*)data; + FileAccess *f = (FileAccess *)data; f->open(p_fname, FileAccess::READ); - return f->is_open()?data:NULL; - + return f->is_open() ? data : NULL; }; -static uLong godot_read(void* data, void* fdata, void* buf, uLong size) { +static uLong godot_read(void *data, void *fdata, void *buf, uLong size) { - FileAccess* f = (FileAccess*)data; - f->get_buffer((uint8_t*)buf, size); + FileAccess *f = (FileAccess *)data; + f->get_buffer((uint8_t *)buf, size); return size; }; -static uLong godot_write(voidpf opaque, voidpf stream, const void* buf, uLong size) { +static uLong godot_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { return 0; }; +static long godot_tell(voidpf opaque, voidpf stream) { -static long godot_tell (voidpf opaque, voidpf stream) { - - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; return f->get_pos(); }; static long godot_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; int pos = offset; switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_pos() + offset; - break; - case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_len() + offset; - break; - default: - break; + case ZLIB_FILEFUNC_SEEK_CUR: + pos = f->get_pos() + offset; + break; + case ZLIB_FILEFUNC_SEEK_END: + pos = f->get_len() + offset; + break; + default: + break; }; f->seek(pos); return 0; }; - static int godot_close(voidpf opaque, voidpf stream) { - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; f->close(); return 0; }; static int godot_testerror(voidpf opaque, voidpf stream) { - FileAccess* f = (FileAccess*)opaque; - return f->get_error()!=OK?1:0; + FileAccess *f = (FileAccess *)opaque; + return f->get_error() != OK ? 1 : 0; }; static voidpf godot_alloc(voidpf opaque, uInt items, uInt size) { @@ -119,7 +116,7 @@ static void godot_free(voidpf opaque, voidpf address) { void ZipArchive::close_handle(unzFile p_file) const { ERR_FAIL_COND(!p_file); - FileAccess* f = (FileAccess*)unzGetOpaque(p_file); + FileAccess *f = (FileAccess *)unzGetOpaque(p_file); unzCloseCurrentFile(p_file); unzClose(p_file); memdelete(f); @@ -130,7 +127,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const { ERR_FAIL_COND_V(!file_exists(p_file), NULL); File file = files[p_file]; - FileAccess* f = FileAccess::open(packages[file.package].filename, FileAccess::READ); + FileAccess *f = FileAccess::open(packages[file.package].filename, FileAccess::READ); ERR_FAIL_COND_V(!f, NULL); zlib_filefunc_def io; @@ -162,7 +159,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const { return pkg; }; -bool ZipArchive::try_open_pack(const String& p_name) { +bool ZipArchive::try_open_pack(const String &p_name) { //printf("opening zip pack %ls, %i, %i\n", p_name.c_str(), p_name.extension().nocasecmp_to("zip"), p_name.extension().nocasecmp_to("pcz")); if (p_name.get_extension().nocasecmp_to("zip") != 0 && p_name.get_extension().nocasecmp_to("pcz") != 0) @@ -170,7 +167,7 @@ bool ZipArchive::try_open_pack(const String& p_name) { zlib_filefunc_def io; - FileAccess* f = FileAccess::open(p_name, FileAccess::READ); + FileAccess *f = FileAccess::open(p_name, FileAccess::READ); if (!f) return false; io.opaque = f; @@ -188,20 +185,20 @@ bool ZipArchive::try_open_pack(const String& p_name) { unz_global_info64 gi; int err = unzGetGlobalInfo64(zfile, &gi); - ERR_FAIL_COND_V(err!=UNZ_OK, false); + ERR_FAIL_COND_V(err != UNZ_OK, false); Package pkg; pkg.filename = p_name; pkg.zfile = zfile; packages.push_back(pkg); - int pkg_num = packages.size()-1; + int pkg_num = packages.size() - 1; - for (unsigned int i=0;i<gi.number_entry;i++) { + for (unsigned int i = 0; i < gi.number_entry; i++) { char filename_inzip[256]; unz_file_info64 file_info; - err = unzGetCurrentFileInfo64(zfile,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); + err = unzGetCurrentFileInfo64(zfile, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); ERR_CONTINUE(err != UNZ_OK); File f; @@ -211,11 +208,11 @@ bool ZipArchive::try_open_pack(const String& p_name) { String fname = String("res://") + filename_inzip; files[fname] = f; - uint8_t md5[16]={0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0}; + uint8_t md5[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; PackedData::get_singleton()->add_path(p_name, fname, 1, 0, md5, this); //printf("packed data add path %ls, %ls\n", p_name.c_str(), fname.c_str()); - if ((i+1)<gi.number_entry) { + if ((i + 1) < gi.number_entry) { unzGoToNextFile(zfile); }; }; @@ -228,13 +225,12 @@ bool ZipArchive::file_exists(String p_name) const { return files.has(p_name); }; -FileAccess* ZipArchive::get_file(const String& p_path, PackedData::PackedFile* p_file) { +FileAccess *ZipArchive::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessZip(p_path, *p_file)); }; - -ZipArchive* ZipArchive::get_singleton() { +ZipArchive *ZipArchive::get_singleton() { if (instance == NULL) { instance = memnew(ZipArchive); @@ -251,9 +247,9 @@ ZipArchive::ZipArchive() { ZipArchive::~ZipArchive() { - for (int i=0; i<packages.size(); i++) { + for (int i = 0; i < packages.size(); i++) { - FileAccess* f = (FileAccess*)unzGetOpaque(packages[i].zfile); + FileAccess *f = (FileAccess *)unzGetOpaque(packages[i].zfile); unzClose(packages[i].zfile); memdelete(f); }; @@ -261,18 +257,17 @@ ZipArchive::~ZipArchive() { packages.clear(); }; - -Error FileAccessZip::_open(const String& p_path, int p_mode_flags) { +Error FileAccessZip::_open(const String &p_path, int p_mode_flags) { close(); ERR_FAIL_COND_V(p_mode_flags & FileAccess::WRITE, FAILED); - ZipArchive* arch = ZipArchive::get_singleton(); + ZipArchive *arch = ZipArchive::get_singleton(); ERR_FAIL_COND_V(!arch, FAILED); zfile = arch->get_file_handle(p_path); ERR_FAIL_COND_V(!zfile, FAILED); - int err = unzGetCurrentFileInfo64(zfile,&file_info,NULL,0,NULL,0,NULL,0); + int err = unzGetCurrentFileInfo64(zfile, &file_info, NULL, 0, NULL, 0, NULL, 0); ERR_FAIL_COND_V(err != UNZ_OK, FAILED); return OK; @@ -283,7 +278,7 @@ void FileAccessZip::close() { if (!zfile) return; - ZipArchive* arch = ZipArchive::get_singleton(); + ZipArchive *arch = ZipArchive::get_singleton(); ERR_FAIL_COND(!arch); arch->close_handle(zfile); zfile = NULL; @@ -332,7 +327,7 @@ uint8_t FileAccessZip::get_8() const { return ret; }; -int FileAccessZip::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessZip::get_buffer(uint8_t *p_dst, int p_length) const { ERR_FAIL_COND_V(!zfile, -1); at_eof = unzeof(zfile); @@ -363,13 +358,12 @@ void FileAccessZip::store_8(uint8_t p_dest) { ERR_FAIL(); }; -bool FileAccessZip::file_exists(const String& p_name) { +bool FileAccessZip::file_exists(const String &p_name) { return false; }; - -FileAccessZip::FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file) { +FileAccessZip::FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file) { zfile = NULL; _open(p_path, FileAccess::READ); diff --git a/core/io/file_access_zip.h b/core/io/file_access_zip.h index e34bc1283a..7d5be8678d 100644 --- a/core/io/file_access_zip.h +++ b/core/io/file_access_zip.h @@ -31,15 +31,14 @@ #ifndef FILE_ACCESS_Zip_H #define FILE_ACCESS_Zip_H -#include <stdlib.h> #include "core/io/file_access_pack.h" -#include "unzip.h" #include "map.h" +#include "unzip.h" +#include <stdlib.h> class ZipArchive : public PackSource { public: - struct File { int package; @@ -50,23 +49,20 @@ public: }; }; - private: - struct Package { String filename; unzFile zfile; }; Vector<Package> packages; - Map<String,File> files; + Map<String, File> files; - static ZipArchive* instance; + static ZipArchive *instance; FileAccess::CreateFunc fa_create_func; public: - void close_handle(unzFile p_file) const; unzFile get_file_handle(String p_file) const; @@ -74,49 +70,47 @@ public: bool file_exists(String p_name) const; - virtual bool try_open_pack(const String& p_path); - FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file); + virtual bool try_open_pack(const String &p_path); + FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); - static ZipArchive* get_singleton(); + static ZipArchive *get_singleton(); ZipArchive(); ~ZipArchive(); }; - class FileAccessZip : public FileAccess { unzFile zfile; - unz_file_info64 file_info; + unz_file_info64 file_info; mutable bool at_eof; - ZipArchive* archive; + ZipArchive *archive; public: - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file virtual bool eof_reached() const; ///< reading passed EOF virtual uint8_t get_8() const; ///< get a byte - virtual int get_buffer(uint8_t *p_dst,int p_length) const; + virtual int get_buffer(uint8_t *p_dst, int p_length) const; virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_name); ///< return true if a file exists + virtual bool file_exists(const String &p_name); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } // todo + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } // todo - FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file); + FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file); ~FileAccessZip(); }; diff --git a/core/io/http_client.cpp b/core/io/http_client.cpp index ae14f8fa38..be5309ddfa 100644 --- a/core/io/http_client.cpp +++ b/core/io/http_client.cpp @@ -29,52 +29,47 @@ #include "http_client.h" #include "io/stream_peer_ssl.h" -Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl,bool p_verify_host){ +Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) { close(); - conn_port=p_port; - conn_host=p_host; + conn_port = p_port; + conn_host = p_host; if (conn_host.begins_with("http://")) { - conn_host=conn_host.replace_first("http://",""); + conn_host = conn_host.replace_first("http://", ""); } else if (conn_host.begins_with("https://")) { //use https - conn_host=conn_host.replace_first("https://",""); + conn_host = conn_host.replace_first("https://", ""); } - - ssl=p_ssl; - ssl_verify_host=p_verify_host; - connection=tcp_connection; - - + ssl = p_ssl; + ssl_verify_host = p_verify_host; + connection = tcp_connection; if (conn_host.is_valid_ip_address()) { //is ip - Error err = tcp_connection->connect_to_host(IP_Address(conn_host),p_port); + Error err = tcp_connection->connect_to_host(IP_Address(conn_host), p_port); if (err) { - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return err; } - status=STATUS_CONNECTING; + status = STATUS_CONNECTING; } else { //is hostname - resolving=IP::get_singleton()->resolve_hostname_queue_item(conn_host); - status=STATUS_RESOLVING; - + resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host); + status = STATUS_RESOLVING; } return OK; } -void HTTPClient::set_connection(const Ref<StreamPeer>& p_connection){ +void HTTPClient::set_connection(const Ref<StreamPeer> &p_connection) { close(); - connection=p_connection; - status=STATUS_CONNECTED; - + connection = p_connection; + status = STATUS_CONNECTED; } Ref<StreamPeer> HTTPClient::get_connection() const { @@ -82,14 +77,13 @@ Ref<StreamPeer> HTTPClient::get_connection() const { return connection; } -Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const PoolVector<uint8_t>& p_body) { - - ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA); +Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body) { + ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA); - static const char* _methods[METHOD_MAX]={ + static const char *_methods[METHOD_MAX] = { "GET", "HEAD", "POST", @@ -97,54 +91,54 @@ Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vecto "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; - - String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n"; - request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n"; - bool add_clen=p_body.size()>0; - for(int i=0;i<p_headers.size();i++) { - request+=p_headers[i]+"\r\n"; - if (add_clen && p_headers[i].find("Content-Length:")==0) { - add_clen=false; + "CONNECT" + }; + + String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n"; + request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n"; + bool add_clen = p_body.size() > 0; + for (int i = 0; i < p_headers.size(); i++) { + request += p_headers[i] + "\r\n"; + if (add_clen && p_headers[i].find("Content-Length:") == 0) { + add_clen = false; } } if (add_clen) { - request+="Content-Length: "+itos(p_body.size())+"\r\n"; + request += "Content-Length: " + itos(p_body.size()) + "\r\n"; //should it add utf8 encoding? not sure } - request+="\r\n"; - CharString cs=request.utf8(); + request += "\r\n"; + CharString cs = request.utf8(); PoolVector<uint8_t> data; //Maybe this goes faster somehow? - for(int i=0;i<cs.length();i++) { - data.append( cs[i] ); + for (int i = 0; i < cs.length(); i++) { + data.append(cs[i]); } - data.append_array( p_body ); + data.append_array(p_body); PoolVector<uint8_t>::Read r = data.read(); Error err = connection->put_data(&r[0], data.size()); if (err) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return err; } - status=STATUS_REQUESTING; + status = STATUS_REQUESTING; return OK; } -Error HTTPClient::request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body) { +Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) { - ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA); + ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA); - - static const char* _methods[METHOD_MAX]={ + static const char *_methods[METHOD_MAX] = { "GET", "HEAD", "POST", @@ -152,50 +146,51 @@ Error HTTPClient::request( Method p_method, const String& p_url, const Vector<St "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; - - String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n"; - request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n"; - bool add_clen=p_body.length()>0; - for(int i=0;i<p_headers.size();i++) { - request+=p_headers[i]+"\r\n"; - if (add_clen && p_headers[i].find("Content-Length:")==0) { - add_clen=false; + "CONNECT" + }; + + String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n"; + request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n"; + bool add_clen = p_body.length() > 0; + for (int i = 0; i < p_headers.size(); i++) { + request += p_headers[i] + "\r\n"; + if (add_clen && p_headers[i].find("Content-Length:") == 0) { + add_clen = false; } } if (add_clen) { - request+="Content-Length: "+itos(p_body.utf8().length())+"\r\n"; + request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n"; //should it add utf8 encoding? not sure } - request+="\r\n"; - request+=p_body; + request += "\r\n"; + request += p_body; - CharString cs=request.utf8(); - Error err = connection->put_data((const uint8_t*)cs.ptr(),cs.length()); + CharString cs = request.utf8(); + Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length()); if (err) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return err; } - status=STATUS_REQUESTING; + status = STATUS_REQUESTING; return OK; } -Error HTTPClient::send_body_text(const String& p_body){ +Error HTTPClient::send_body_text(const String &p_body) { return OK; } -Error HTTPClient::send_body_data(const PoolByteArray& p_body){ +Error HTTPClient::send_body_data(const PoolByteArray &p_body) { return OK; } bool HTTPClient::has_response() const { - return response_headers.size()!=0; + return response_headers.size() != 0; } bool HTTPClient::is_response_chunked() const { @@ -213,7 +208,7 @@ Error HTTPClient::get_response_headers(List<String> *r_response) { if (!response_headers.size()) return ERR_INVALID_PARAMETER; - for(int i=0;i<response_headers.size();i++) { + for (int i = 0; i < response_headers.size(); i++) { r_response->push_back(response_headers[i]); } @@ -223,71 +218,67 @@ Error HTTPClient::get_response_headers(List<String> *r_response) { return OK; } +void HTTPClient::close() { -void HTTPClient::close(){ - - if (tcp_connection->get_status()!=StreamPeerTCP::STATUS_NONE) + if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE) tcp_connection->disconnect_from_host(); connection.unref(); - status=STATUS_DISCONNECTED; - if (resolving!=IP::RESOLVER_INVALID_ID) { + status = STATUS_DISCONNECTED; + if (resolving != IP::RESOLVER_INVALID_ID) { IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; - + resolving = IP::RESOLVER_INVALID_ID; } response_headers.clear(); response_str.clear(); - body_size=0; - body_left=0; - chunk_left=0; - response_num=0; + body_size = 0; + body_left = 0; + chunk_left = 0; + response_num = 0; } +Error HTTPClient::poll() { -Error HTTPClient::poll(){ - - switch(status) { - + switch (status) { case STATUS_RESOLVING: { - ERR_FAIL_COND_V(resolving==IP::RESOLVER_INVALID_ID,ERR_BUG); + ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG); IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving); - switch(rstatus) { - case IP::RESOLVER_STATUS_WAITING: return OK; //still resolving + switch (rstatus) { + case IP::RESOLVER_STATUS_WAITING: + return OK; //still resolving case IP::RESOLVER_STATUS_DONE: { IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving); - Error err = tcp_connection->connect_to_host(host,conn_port); + Error err = tcp_connection->connect_to_host(host, conn_port); IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; + resolving = IP::RESOLVER_INVALID_ID; if (err) { - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return err; } - status=STATUS_CONNECTING; + status = STATUS_CONNECTING; } break; case IP::RESOLVER_STATUS_NONE: case IP::RESOLVER_STATUS_ERROR: { IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; + resolving = IP::RESOLVER_INVALID_ID; close(); - status=STATUS_CANT_RESOLVE; + status = STATUS_CANT_RESOLVE; return ERR_CANT_RESOLVE; } break; - } } break; case STATUS_CONNECTING: { StreamPeerTCP::Status s = tcp_connection->get_status(); - switch(s) { + switch (s) { case StreamPeerTCP::STATUS_CONNECTING: { return OK; //do none @@ -295,23 +286,23 @@ Error HTTPClient::poll(){ case StreamPeerTCP::STATUS_CONNECTED: { if (ssl) { Ref<StreamPeerSSL> ssl = StreamPeerSSL::create(); - Error err = ssl->connect_to_stream(tcp_connection,true,ssl_verify_host?conn_host:String()); - if (err!=OK) { + Error err = ssl->connect_to_stream(tcp_connection, true, ssl_verify_host ? conn_host : String()); + if (err != OK) { close(); - status=STATUS_SSL_HANDSHAKE_ERROR; + status = STATUS_SSL_HANDSHAKE_ERROR; return ERR_CANT_CONNECT; } //print_line("SSL! TURNED ON!"); - connection=ssl; + connection = ssl; } - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; return OK; } break; case StreamPeerTCP::STATUS_ERROR: case StreamPeerTCP::STATUS_NONE: { close(); - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return ERR_CANT_CONNECT; } break; } @@ -322,78 +313,73 @@ Error HTTPClient::poll(){ } break; case STATUS_REQUESTING: { - - while(true) { + while (true) { uint8_t byte; - int rec=0; - Error err = _get_http_data(&byte,1,rec); - if (err!=OK) { + int rec = 0; + Error err = _get_http_data(&byte, 1, rec); + if (err != OK) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ERR_CONNECTION_ERROR; } - if (rec==0) + if (rec == 0) return OK; //keep trying! response_str.push_back(byte); int rs = response_str.size(); if ( - (rs>=2 && response_str[rs-2]=='\n' && response_str[rs-1]=='\n') || - (rs>=4 && response_str[rs-4]=='\r' && response_str[rs-3]=='\n' && response_str[rs-2]=='\r' && response_str[rs-1]=='\n') - ) { - + (rs >= 2 && response_str[rs - 2] == '\n' && response_str[rs - 1] == '\n') || + (rs >= 4 && response_str[rs - 4] == '\r' && response_str[rs - 3] == '\n' && response_str[rs - 2] == '\r' && response_str[rs - 1] == '\n')) { //end of response, parse. response_str.push_back(0); String response; - response.parse_utf8((const char*)response_str.ptr()); + response.parse_utf8((const char *)response_str.ptr()); //print_line("END OF RESPONSE? :\n"+response+"\n------"); Vector<String> responses = response.split("\n"); - body_size=0; - chunked=false; - body_left=0; - chunk_left=0; + body_size = 0; + chunked = false; + body_left = 0; + chunk_left = 0; response_str.clear(); response_headers.clear(); response_num = RESPONSE_OK; - for(int i=0;i<responses.size();i++) { + for (int i = 0; i < responses.size(); i++) { String header = responses[i].strip_edges(); String s = header.to_lower(); - if (s.length()==0) + if (s.length() == 0) continue; if (s.begins_with("content-length:")) { - body_size = s.substr(s.find(":")+1,s.length()).strip_edges().to_int(); - body_left=body_size; + body_size = s.substr(s.find(":") + 1, s.length()).strip_edges().to_int(); + body_left = body_size; } if (s.begins_with("transfer-encoding:")) { - String encoding = header.substr(header.find(":")+1,header.length()).strip_edges(); + String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges(); //print_line("TRANSFER ENCODING: "+encoding); - if (encoding=="chunked") { - chunked=true; + if (encoding == "chunked") { + chunked = true; } - } - if (i==0 && responses[i].begins_with("HTTP")) { + if (i == 0 && responses[i].begins_with("HTTP")) { - String num = responses[i].get_slicec(' ',1); - response_num=num.to_int(); + String num = responses[i].get_slicec(' ', 1); + response_num = num.to_int(); } else { response_headers.push_back(header); } - } - if (body_size==0 && !chunked) { + if (body_size == 0 && !chunked) { - status=STATUS_CONNECTED; //ask for something again? + status = STATUS_CONNECTED; //ask for something again? } else { - status=STATUS_BODY; + status = STATUS_BODY; } return OK; } @@ -415,25 +401,22 @@ Error HTTPClient::poll(){ } break; } - return OK; } - Dictionary HTTPClient::_get_response_headers_as_dictionary() { List<String> rh; get_response_headers(&rh); Dictionary ret; - for(const List<String>::Element *E=rh.front();E;E=E->next()) { + for (const List<String>::Element *E = rh.front(); E; E = E->next()) { String s = E->get(); int sp = s.find(":"); - if (sp==-1) + if (sp == -1) continue; - String key = s.substr(0,sp).strip_edges(); - String value = s.substr(sp+1,s.length()).strip_edges(); - ret[key]=value; - + String key = s.substr(0, sp).strip_edges(); + String value = s.substr(sp + 1, s.length()).strip_edges(); + ret[key] = value; } return ret; @@ -445,9 +428,9 @@ PoolStringArray HTTPClient::_get_response_headers() { get_response_headers(&rh); PoolStringArray ret; ret.resize(rh.size()); - int idx=0; - for(const List<String>::Element *E=rh.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (const List<String>::Element *E = rh.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; @@ -460,96 +443,93 @@ int HTTPClient::get_response_body_length() const { PoolByteArray HTTPClient::read_response_body_chunk() { - ERR_FAIL_COND_V( status !=STATUS_BODY, PoolByteArray() ); + ERR_FAIL_COND_V(status != STATUS_BODY, PoolByteArray()); - Error err=OK; + Error err = OK; if (chunked) { - while(true) { + while (true) { - if (chunk_left==0) { + if (chunk_left == 0) { //reading len uint8_t b; - int rec=0; - err = _get_http_data(&b,1,rec); + int rec = 0; + err = _get_http_data(&b, 1, rec); - if (rec==0) + if (rec == 0) break; chunk.push_back(b); - if (chunk.size()>32) { + if (chunk.size() > 32) { ERR_PRINT("HTTP Invalid chunk hex len"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } - if (chunk.size()>2 && chunk[chunk.size()-2]=='\r' && chunk[chunk.size()-1]=='\n') { + if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') { - int len=0; - for(int i=0;i<chunk.size()-2;i++) { + int len = 0; + for (int i = 0; i < chunk.size() - 2; i++) { char c = chunk[i]; - int v=0; - if (c>='0' && c<='9') - v=c-'0'; - else if (c>='a' && c<='f') - v=c-'a'+10; - else if (c>='A' && c<='F') - v=c-'A'+10; + int v = 0; + if (c >= '0' && c <= '9') + v = c - '0'; + else if (c >= 'a' && c <= 'f') + v = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + v = c - 'A' + 10; else { ERR_PRINT("HTTP Chunk len not in hex!!"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } - len<<=4; - len|=v; - if (len>(1<<24)) { + len <<= 4; + len |= v; + if (len > (1 << 24)) { ERR_PRINT("HTTP Chunk too big!! >16mb"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } - } - if (len==0) { + if (len == 0) { //end! - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; chunk.clear(); return PoolByteArray(); } - chunk_left=len+2; + chunk_left = len + 2; chunk.resize(chunk_left); - } } else { - int rec=0; - err = _get_http_data(&chunk[chunk.size()-chunk_left],chunk_left,rec); - if (rec==0) { + int rec = 0; + err = _get_http_data(&chunk[chunk.size() - chunk_left], chunk_left, rec); + if (rec == 0) { break; } - chunk_left-=rec; + chunk_left -= rec; - if (chunk_left==0) { + if (chunk_left == 0) { - if (chunk[chunk.size()-2]!='\r' || chunk[chunk.size()-1]!='\n') { + if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') { ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } PoolByteArray ret; - ret.resize(chunk.size()-2); + ret.resize(chunk.size() - 2); { PoolByteArray::Write w = ret.write(); - copymem(w.ptr(),chunk.ptr(),chunk.size()-2); + copymem(w.ptr(), chunk.ptr(), chunk.size() - 2); } chunk.clear(); return ret; - } break; @@ -558,46 +538,44 @@ PoolByteArray HTTPClient::read_response_body_chunk() { } else { - int to_read = MIN(body_left,read_chunk_size); + int to_read = MIN(body_left, read_chunk_size); PoolByteArray ret; ret.resize(to_read); int _offset = 0; while (to_read > 0) { - int rec=0; + int rec = 0; { PoolByteArray::Write w = ret.write(); - err = _get_http_data(w.ptr()+_offset,to_read,rec); + err = _get_http_data(w.ptr() + _offset, to_read, rec); } - if (rec>0) { - body_left-=rec; - to_read-=rec; + if (rec > 0) { + body_left -= rec; + to_read -= rec; _offset += rec; } else { - if (to_read>0) //ended up reading less + if (to_read > 0) //ended up reading less ret.resize(_offset); break; } } - if (body_left==0) { - status=STATUS_CONNECTED; + if (body_left == 0) { + status = STATUS_CONNECTED; } return ret; - } - - if (err!=OK) { + if (err != OK) { close(); - if (err==ERR_FILE_EOF) { + if (err == ERR_FILE_EOF) { - status=STATUS_DISCONNECTED; //server disconnected + status = STATUS_DISCONNECTED; //server disconnected } else { - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; } - } else if (body_left==0 && !chunked) { + } else if (body_left == 0 && !chunked) { - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; } return PoolByteArray(); @@ -605,179 +583,172 @@ PoolByteArray HTTPClient::read_response_body_chunk() { HTTPClient::Status HTTPClient::get_status() const { - return status; } void HTTPClient::set_blocking_mode(bool p_enable) { - blocking=p_enable; + blocking = p_enable; } -bool HTTPClient::is_blocking_mode_enabled() const{ +bool HTTPClient::is_blocking_mode_enabled() const { return blocking; } -Error HTTPClient::_get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received) { +Error HTTPClient::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) { if (blocking) { - Error err = connection->get_data(p_buffer,p_bytes); - if (err==OK) - r_received=p_bytes; + Error err = connection->get_data(p_buffer, p_bytes); + if (err == OK) + r_received = p_bytes; else - r_received=0; + r_received = 0; return err; } else { - return connection->get_partial_data(p_buffer,p_bytes,r_received); + return connection->get_partial_data(p_buffer, p_bytes, r_received); } } void HTTPClient::_bind_methods() { - ClassDB::bind_method(D_METHOD("connect_to_host:Error","host","port","use_ssl","verify_host"),&HTTPClient::connect_to_host,DEFVAL(false),DEFVAL(true)); - ClassDB::bind_method(D_METHOD("set_connection","connection:StreamPeer"),&HTTPClient::set_connection); - ClassDB::bind_method(D_METHOD("get_connection:StreamPeer"),&HTTPClient::get_connection); - ClassDB::bind_method(D_METHOD("request_raw","method","url","headers","body"),&HTTPClient::request_raw); - ClassDB::bind_method(D_METHOD("request","method","url","headers","body"),&HTTPClient::request,DEFVAL(String())); - ClassDB::bind_method(D_METHOD("send_body_text","body"),&HTTPClient::send_body_text); - ClassDB::bind_method(D_METHOD("send_body_data","body"),&HTTPClient::send_body_data); - ClassDB::bind_method(D_METHOD("close"),&HTTPClient::close); - - ClassDB::bind_method(D_METHOD("has_response"),&HTTPClient::has_response); - ClassDB::bind_method(D_METHOD("is_response_chunked"),&HTTPClient::is_response_chunked); - ClassDB::bind_method(D_METHOD("get_response_code"),&HTTPClient::get_response_code); - ClassDB::bind_method(D_METHOD("get_response_headers"),&HTTPClient::_get_response_headers); - ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"),&HTTPClient::_get_response_headers_as_dictionary); - ClassDB::bind_method(D_METHOD("get_response_body_length"),&HTTPClient::get_response_body_length); - ClassDB::bind_method(D_METHOD("read_response_body_chunk"),&HTTPClient::read_response_body_chunk); - ClassDB::bind_method(D_METHOD("set_read_chunk_size","bytes"),&HTTPClient::set_read_chunk_size); - - ClassDB::bind_method(D_METHOD("set_blocking_mode","enabled"),&HTTPClient::set_blocking_mode); - ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"),&HTTPClient::is_blocking_mode_enabled); - - ClassDB::bind_method(D_METHOD("get_status"),&HTTPClient::get_status); - ClassDB::bind_method(D_METHOD("poll:Error"),&HTTPClient::poll); - - ClassDB::bind_method(D_METHOD("query_string_from_dict:String","fields"),&HTTPClient::query_string_from_dict); - - - BIND_CONSTANT( METHOD_GET ); - BIND_CONSTANT( METHOD_HEAD ); - BIND_CONSTANT( METHOD_POST ); - BIND_CONSTANT( METHOD_PUT ); - BIND_CONSTANT( METHOD_DELETE ); - BIND_CONSTANT( METHOD_OPTIONS ); - BIND_CONSTANT( METHOD_TRACE ); - BIND_CONSTANT( METHOD_CONNECT ); - BIND_CONSTANT( METHOD_MAX ); - - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_RESOLVING ); //resolving hostname (if passed a hostname) - BIND_CONSTANT( STATUS_CANT_RESOLVE ); - BIND_CONSTANT( STATUS_CONNECTING ); //connecting to ip - BIND_CONSTANT( STATUS_CANT_CONNECT ); - BIND_CONSTANT( STATUS_CONNECTED ); //connected ); requests only accepted here - BIND_CONSTANT( STATUS_REQUESTING ); // request in progress - BIND_CONSTANT( STATUS_BODY ); // request resulted in body ); which must be read - BIND_CONSTANT( STATUS_CONNECTION_ERROR ); - BIND_CONSTANT( STATUS_SSL_HANDSHAKE_ERROR ); - - - BIND_CONSTANT( RESPONSE_CONTINUE ); - BIND_CONSTANT( RESPONSE_SWITCHING_PROTOCOLS ); - BIND_CONSTANT( RESPONSE_PROCESSING ); + ClassDB::bind_method(D_METHOD("connect_to_host:Error", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect_to_host, DEFVAL(false), DEFVAL(true)); + ClassDB::bind_method(D_METHOD("set_connection", "connection:StreamPeer"), &HTTPClient::set_connection); + ClassDB::bind_method(D_METHOD("get_connection:StreamPeer"), &HTTPClient::get_connection); + ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw); + ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String())); + ClassDB::bind_method(D_METHOD("send_body_text", "body"), &HTTPClient::send_body_text); + ClassDB::bind_method(D_METHOD("send_body_data", "body"), &HTTPClient::send_body_data); + ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close); + + ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response); + ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked); + ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code); + ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers); + ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary); + ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length); + ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk); + ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size); + + ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode); + ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled); + + ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status); + ClassDB::bind_method(D_METHOD("poll:Error"), &HTTPClient::poll); + + ClassDB::bind_method(D_METHOD("query_string_from_dict:String", "fields"), &HTTPClient::query_string_from_dict); + + BIND_CONSTANT(METHOD_GET); + BIND_CONSTANT(METHOD_HEAD); + BIND_CONSTANT(METHOD_POST); + BIND_CONSTANT(METHOD_PUT); + BIND_CONSTANT(METHOD_DELETE); + BIND_CONSTANT(METHOD_OPTIONS); + BIND_CONSTANT(METHOD_TRACE); + BIND_CONSTANT(METHOD_CONNECT); + BIND_CONSTANT(METHOD_MAX); + + BIND_CONSTANT(STATUS_DISCONNECTED); + BIND_CONSTANT(STATUS_RESOLVING); //resolving hostname (if passed a hostname) + BIND_CONSTANT(STATUS_CANT_RESOLVE); + BIND_CONSTANT(STATUS_CONNECTING); //connecting to ip + BIND_CONSTANT(STATUS_CANT_CONNECT); + BIND_CONSTANT(STATUS_CONNECTED); //connected ); requests only accepted here + BIND_CONSTANT(STATUS_REQUESTING); // request in progress + BIND_CONSTANT(STATUS_BODY); // request resulted in body ); which must be read + BIND_CONSTANT(STATUS_CONNECTION_ERROR); + BIND_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR); + + BIND_CONSTANT(RESPONSE_CONTINUE); + BIND_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS); + BIND_CONSTANT(RESPONSE_PROCESSING); // 2xx successful - BIND_CONSTANT( RESPONSE_OK ); - BIND_CONSTANT( RESPONSE_CREATED ); - BIND_CONSTANT( RESPONSE_ACCEPTED ); - BIND_CONSTANT( RESPONSE_NON_AUTHORITATIVE_INFORMATION ); - BIND_CONSTANT( RESPONSE_NO_CONTENT ); - BIND_CONSTANT( RESPONSE_RESET_CONTENT ); - BIND_CONSTANT( RESPONSE_PARTIAL_CONTENT ); - BIND_CONSTANT( RESPONSE_MULTI_STATUS ); - BIND_CONSTANT( RESPONSE_IM_USED ); + BIND_CONSTANT(RESPONSE_OK); + BIND_CONSTANT(RESPONSE_CREATED); + BIND_CONSTANT(RESPONSE_ACCEPTED); + BIND_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION); + BIND_CONSTANT(RESPONSE_NO_CONTENT); + BIND_CONSTANT(RESPONSE_RESET_CONTENT); + BIND_CONSTANT(RESPONSE_PARTIAL_CONTENT); + BIND_CONSTANT(RESPONSE_MULTI_STATUS); + BIND_CONSTANT(RESPONSE_IM_USED); // 3xx redirection - BIND_CONSTANT( RESPONSE_MULTIPLE_CHOICES ); - BIND_CONSTANT( RESPONSE_MOVED_PERMANENTLY ); - BIND_CONSTANT( RESPONSE_FOUND ); - BIND_CONSTANT( RESPONSE_SEE_OTHER ); - BIND_CONSTANT( RESPONSE_NOT_MODIFIED ); - BIND_CONSTANT( RESPONSE_USE_PROXY ); - BIND_CONSTANT( RESPONSE_TEMPORARY_REDIRECT ); + BIND_CONSTANT(RESPONSE_MULTIPLE_CHOICES); + BIND_CONSTANT(RESPONSE_MOVED_PERMANENTLY); + BIND_CONSTANT(RESPONSE_FOUND); + BIND_CONSTANT(RESPONSE_SEE_OTHER); + BIND_CONSTANT(RESPONSE_NOT_MODIFIED); + BIND_CONSTANT(RESPONSE_USE_PROXY); + BIND_CONSTANT(RESPONSE_TEMPORARY_REDIRECT); // 4xx client error - BIND_CONSTANT( RESPONSE_BAD_REQUEST ); - BIND_CONSTANT( RESPONSE_UNAUTHORIZED ); - BIND_CONSTANT( RESPONSE_PAYMENT_REQUIRED ); - BIND_CONSTANT( RESPONSE_FORBIDDEN ); - BIND_CONSTANT( RESPONSE_NOT_FOUND ); - BIND_CONSTANT( RESPONSE_METHOD_NOT_ALLOWED ); - BIND_CONSTANT( RESPONSE_NOT_ACCEPTABLE ); - BIND_CONSTANT( RESPONSE_PROXY_AUTHENTICATION_REQUIRED ); - BIND_CONSTANT( RESPONSE_REQUEST_TIMEOUT ); - BIND_CONSTANT( RESPONSE_CONFLICT ); - BIND_CONSTANT( RESPONSE_GONE ); - BIND_CONSTANT( RESPONSE_LENGTH_REQUIRED ); - BIND_CONSTANT( RESPONSE_PRECONDITION_FAILED ); - BIND_CONSTANT( RESPONSE_REQUEST_ENTITY_TOO_LARGE ); - BIND_CONSTANT( RESPONSE_REQUEST_URI_TOO_LONG ); - BIND_CONSTANT( RESPONSE_UNSUPPORTED_MEDIA_TYPE ); - BIND_CONSTANT( RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE ); - BIND_CONSTANT( RESPONSE_EXPECTATION_FAILED ); - BIND_CONSTANT( RESPONSE_UNPROCESSABLE_ENTITY ); - BIND_CONSTANT( RESPONSE_LOCKED ); - BIND_CONSTANT( RESPONSE_FAILED_DEPENDENCY ); - BIND_CONSTANT( RESPONSE_UPGRADE_REQUIRED ); + BIND_CONSTANT(RESPONSE_BAD_REQUEST); + BIND_CONSTANT(RESPONSE_UNAUTHORIZED); + BIND_CONSTANT(RESPONSE_PAYMENT_REQUIRED); + BIND_CONSTANT(RESPONSE_FORBIDDEN); + BIND_CONSTANT(RESPONSE_NOT_FOUND); + BIND_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED); + BIND_CONSTANT(RESPONSE_NOT_ACCEPTABLE); + BIND_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED); + BIND_CONSTANT(RESPONSE_REQUEST_TIMEOUT); + BIND_CONSTANT(RESPONSE_CONFLICT); + BIND_CONSTANT(RESPONSE_GONE); + BIND_CONSTANT(RESPONSE_LENGTH_REQUIRED); + BIND_CONSTANT(RESPONSE_PRECONDITION_FAILED); + BIND_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE); + BIND_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG); + BIND_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE); + BIND_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE); + BIND_CONSTANT(RESPONSE_EXPECTATION_FAILED); + BIND_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY); + BIND_CONSTANT(RESPONSE_LOCKED); + BIND_CONSTANT(RESPONSE_FAILED_DEPENDENCY); + BIND_CONSTANT(RESPONSE_UPGRADE_REQUIRED); // 5xx server error - BIND_CONSTANT( RESPONSE_INTERNAL_SERVER_ERROR ); - BIND_CONSTANT( RESPONSE_NOT_IMPLEMENTED ); - BIND_CONSTANT( RESPONSE_BAD_GATEWAY ); - BIND_CONSTANT( RESPONSE_SERVICE_UNAVAILABLE ); - BIND_CONSTANT( RESPONSE_GATEWAY_TIMEOUT ); - BIND_CONSTANT( RESPONSE_HTTP_VERSION_NOT_SUPPORTED ); - BIND_CONSTANT( RESPONSE_INSUFFICIENT_STORAGE ); - BIND_CONSTANT( RESPONSE_NOT_EXTENDED ); - + BIND_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR); + BIND_CONSTANT(RESPONSE_NOT_IMPLEMENTED); + BIND_CONSTANT(RESPONSE_BAD_GATEWAY); + BIND_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE); + BIND_CONSTANT(RESPONSE_GATEWAY_TIMEOUT); + BIND_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED); + BIND_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE); + BIND_CONSTANT(RESPONSE_NOT_EXTENDED); } void HTTPClient::set_read_chunk_size(int p_size) { - ERR_FAIL_COND(p_size<256 || p_size>(1<<24)); - read_chunk_size=p_size; + ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24)); + read_chunk_size = p_size; } -String HTTPClient::query_string_from_dict(const Dictionary& p_dict) { - String query = ""; - Array keys = p_dict.keys(); - for (int i = 0; i < keys.size(); ++i) { - query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape(); - } - query.erase(0, 1); - return query; +String HTTPClient::query_string_from_dict(const Dictionary &p_dict) { + String query = ""; + Array keys = p_dict.keys(); + for (int i = 0; i < keys.size(); ++i) { + query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape(); + } + query.erase(0, 1); + return query; } -HTTPClient::HTTPClient(){ +HTTPClient::HTTPClient() { tcp_connection = StreamPeerTCP::create_ref(); resolving = IP::RESOLVER_INVALID_ID; - status=STATUS_DISCONNECTED; - conn_port=80; - body_size=0; - chunked=false; - body_left=0; - chunk_left=0; - response_num=0; - ssl=false; - blocking=false; - read_chunk_size=4096; + status = STATUS_DISCONNECTED; + conn_port = 80; + body_size = 0; + chunked = false; + body_left = 0; + chunk_left = 0; + response_num = 0; + ssl = false; + blocking = false; + read_chunk_size = 4096; } -HTTPClient::~HTTPClient(){ - - +HTTPClient::~HTTPClient() { } - diff --git a/core/io/http_client.h b/core/io/http_client.h index 4b0c1b730f..e2b0e9ccea 100644 --- a/core/io/http_client.h +++ b/core/io/http_client.h @@ -29,17 +29,16 @@ #ifndef HTTP_CLIENT_H #define HTTP_CLIENT_H +#include "io/ip.h" #include "io/stream_peer.h" #include "io/stream_peer_tcp.h" -#include "io/ip.h" #include "reference.h" - class HTTPClient : public Reference { - GDCLASS(HTTPClient,Reference); -public: + GDCLASS(HTTPClient, Reference); +public: enum ResponseCode { // 1xx informational @@ -131,7 +130,6 @@ public: }; private: - Status status; IP::ResolverID resolving; int conn_port; @@ -159,21 +157,19 @@ private: Dictionary _get_response_headers_as_dictionary(); int read_chunk_size; - Error _get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received); + Error _get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received); public: - - //Error connect_and_get(const String& p_url,bool p_verify_host=true); //connects to a full url and perform request - Error connect_to_host(const String &p_host,int p_port,bool p_ssl=false,bool p_verify_host=true); + Error connect_to_host(const String &p_host, int p_port, bool p_ssl = false, bool p_verify_host = true); - void set_connection(const Ref<StreamPeer>& p_connection); + void set_connection(const Ref<StreamPeer> &p_connection); Ref<StreamPeer> get_connection() const; - Error request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const PoolVector<uint8_t>& p_body); - Error request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body=String()); - Error send_body_text(const String& p_body); - Error send_body_data(const PoolByteArray& p_body); + Error request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body); + Error request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body = String()); + Error send_body_text(const String &p_body); + Error send_body_data(const PoolByteArray &p_body); void close(); @@ -194,7 +190,7 @@ public: Error poll(); - String query_string_from_dict(const Dictionary& p_dict); + String query_string_from_dict(const Dictionary &p_dict); HTTPClient(); ~HTTPClient(); diff --git a/core/io/image_loader.cpp b/core/io/image_loader.cpp index 2b01e865f4..5f88ca65e3 100644 --- a/core/io/image_loader.cpp +++ b/core/io/image_loader.cpp @@ -29,90 +29,78 @@ #include "image_loader.h" #include "print_string.h" -bool ImageFormatLoader::recognize(const String& p_extension) const { - +bool ImageFormatLoader::recognize(const String &p_extension) const { List<String> extensions; get_recognized_extensions(&extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(p_extension.get_extension())==0) + if (E->get().nocasecmp_to(p_extension.get_extension()) == 0) return true; } return false; } -Error ImageLoader::load_image(String p_file,Image *p_image, FileAccess *p_custom) { - +Error ImageLoader::load_image(String p_file, Image *p_image, FileAccess *p_custom) { - FileAccess *f=p_custom; + FileAccess *f = p_custom; if (!f) { Error err; - f=FileAccess::open(p_file,FileAccess::READ,&err); + f = FileAccess::open(p_file, FileAccess::READ, &err); if (!f) { - ERR_PRINTS("Error opening file: "+p_file); + ERR_PRINTS("Error opening file: " + p_file); return err; } } String extension = p_file.get_extension(); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; - Error err = loader[i]->load_image(p_image,f); - - if (err!=ERR_FILE_UNRECOGNIZED) { + Error err = loader[i]->load_image(p_image, f); + if (err != ERR_FILE_UNRECOGNIZED) { if (!p_custom) memdelete(f); return err; } - - } if (!p_custom) memdelete(f); return ERR_FILE_UNRECOGNIZED; - } void ImageLoader::get_recognized_extensions(List<String> *p_extensions) { - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { loader[i]->get_recognized_extensions(p_extensions); - } } -bool ImageLoader::recognize(const String& p_extension) { +bool ImageLoader::recognize(const String &p_extension) { - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (loader[i]->recognize(p_extension)) return true; - } return false; } ImageFormatLoader *ImageLoader::loader[MAX_LOADERS]; -int ImageLoader::loader_count=0; +int ImageLoader::loader_count = 0; void ImageLoader::add_image_format_loader(ImageFormatLoader *p_loader) { - ERR_FAIL_COND(loader_count >=MAX_LOADERS ); - loader[loader_count++]=p_loader; + ERR_FAIL_COND(loader_count >= MAX_LOADERS); + loader[loader_count++] = p_loader; } - - - diff --git a/core/io/image_loader.h b/core/io/image_loader.h index 4de7706ab0..b70170303d 100644 --- a/core/io/image_loader.h +++ b/core/io/image_loader.h @@ -30,14 +30,13 @@ #define IMAGE_LOADER_H #include "image.h" -#include "ustring.h" -#include "os/file_access.h" #include "list.h" +#include "os/file_access.h" +#include "ustring.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - /** * @class ImageScanLineLoader * @author Juan Linietsky <reduzio@gmail.com> @@ -46,21 +45,19 @@ */ class ImageLoader; - /** * @class ImageLoader * Base Class and singleton for loading images from disk * Can load images in one go, or by scanline */ - class ImageFormatLoader { -friend class ImageLoader; -protected: - virtual Error load_image(Image *p_image,FileAccess *p_fileaccess)=0; - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - bool recognize(const String& p_extension) const; + friend class ImageLoader; +protected: + virtual Error load_image(Image *p_image, FileAccess *p_fileaccess) = 0; + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + bool recognize(const String &p_extension) const; public: virtual ~ImageFormatLoader() {} @@ -69,23 +66,19 @@ public: class ImageLoader { enum { - MAX_LOADERS=8 + MAX_LOADERS = 8 }; static ImageFormatLoader *loader[MAX_LOADERS]; static int loader_count; protected: - - public: - - static Error load_image(String p_file,Image *p_image, FileAccess *p_custom=NULL); - static void get_recognized_extensions(List<String> *p_extensions) ; - static bool recognize(const String& p_extension) ; + static Error load_image(String p_file, Image *p_image, FileAccess *p_custom = NULL); + static void get_recognized_extensions(List<String> *p_extensions); + static bool recognize(const String &p_extension); static void add_image_format_loader(ImageFormatLoader *p_loader); - }; #endif diff --git a/core/io/ip.cpp b/core/io/ip.cpp index d820273a14..6713963495 100644 --- a/core/io/ip.cpp +++ b/core/io/ip.cpp @@ -27,15 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "ip.h" -#include "os/thread.h" -#include "os/semaphore.h" #include "hash_map.h" +#include "os/semaphore.h" +#include "os/thread.h" VARIANT_ENUM_CAST(IP::ResolverStatus); /************* RESOLVER ******************/ - struct _IP_ResolverPrivate { struct QueueItem { @@ -49,7 +48,7 @@ struct _IP_ResolverPrivate { status = IP::RESOLVER_STATUS_NONE; response = IP_Address(); type = IP::TYPE_NONE; - hostname=""; + hostname = ""; }; QueueItem() { @@ -61,8 +60,8 @@ struct _IP_ResolverPrivate { IP::ResolverID find_empty_id() const { - for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) { - if (queue[i].status==IP::RESOLVER_STATUS_NONE) + for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) { + if (queue[i].status == IP::RESOLVER_STATUS_NONE) return i; } return IP::RESOLVER_INVALID_ID; @@ -70,39 +69,35 @@ struct _IP_ResolverPrivate { Semaphore *sem; - Thread* thread; + Thread *thread; //Semaphore* semaphore; bool thread_abort; void resolve_queues() { - for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) { + for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) { - if (queue[i].status!=IP::RESOLVER_STATUS_WAITING) + if (queue[i].status != IP::RESOLVER_STATUS_WAITING) continue; - queue[i].response=IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type); + queue[i].response = IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type); if (!queue[i].response.is_valid()) - queue[i].status=IP::RESOLVER_STATUS_ERROR; + queue[i].status = IP::RESOLVER_STATUS_ERROR; else - queue[i].status=IP::RESOLVER_STATUS_DONE; - + queue[i].status = IP::RESOLVER_STATUS_DONE; } } - static void _thread_function(void *self) { - _IP_ResolverPrivate *ipr=(_IP_ResolverPrivate*)self; + _IP_ResolverPrivate *ipr = (_IP_ResolverPrivate *)self; - while(!ipr->thread_abort) { + while (!ipr->thread_abort) { ipr->sem->wait(); GLOBAL_LOCK_FUNCTION; ipr->resolve_queues(); - } - } HashMap<String, IP_Address> cache; @@ -110,12 +105,9 @@ struct _IP_ResolverPrivate { static String get_cache_key(String p_hostname, IP::Type p_type) { return itos(p_type) + p_hostname; } - }; - - -IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) { +IP_Address IP::resolve_hostname(const String &p_hostname, IP::Type p_type) { GLOBAL_LOCK_FUNCTION; @@ -124,30 +116,29 @@ IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) { return resolver->cache[key]; IP_Address res = _resolve_hostname(p_hostname, p_type); - resolver->cache[key]=res; + resolver->cache[key] = res; return res; - } -IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Type p_type) { +IP::ResolverID IP::resolve_hostname_queue_item(const String &p_hostname, IP::Type p_type) { GLOBAL_LOCK_FUNCTION; ResolverID id = resolver->find_empty_id(); - if (id==RESOLVER_INVALID_ID) { + if (id == RESOLVER_INVALID_ID) { WARN_PRINT("Out of resolver queries"); return id; } String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type); - resolver->queue[id].hostname=p_hostname; + resolver->queue[id].hostname = p_hostname; resolver->queue[id].type = p_type; if (resolver->cache.has(key)) { - resolver->queue[id].response=resolver->cache[key]; - resolver->queue[id].status=IP::RESOLVER_STATUS_DONE; + resolver->queue[id].response = resolver->cache[key]; + resolver->queue[id].status = IP::RESOLVER_STATUS_DONE; } else { - resolver->queue[id].response=IP_Address(); - resolver->queue[id].status=IP::RESOLVER_STATUS_WAITING; + resolver->queue[id].response = IP_Address(); + resolver->queue[id].status = IP::RESOLVER_STATUS_WAITING; if (resolver->thread) resolver->sem->post(); else @@ -159,37 +150,33 @@ IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Typ IP::ResolverStatus IP::get_resolve_item_status(ResolverID p_id) const { - ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP::RESOLVER_STATUS_NONE); + ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP::RESOLVER_STATUS_NONE); GLOBAL_LOCK_FUNCTION; - ERR_FAIL_COND_V(resolver->queue[p_id].status==IP::RESOLVER_STATUS_NONE,IP::RESOLVER_STATUS_NONE); + ERR_FAIL_COND_V(resolver->queue[p_id].status == IP::RESOLVER_STATUS_NONE, IP::RESOLVER_STATUS_NONE); return resolver->queue[p_id].status; - } IP_Address IP::get_resolve_item_address(ResolverID p_id) const { - ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP_Address()); + ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP_Address()); GLOBAL_LOCK_FUNCTION; - if (resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE) { - ERR_EXPLAIN("Resolve of '"+resolver->queue[p_id].hostname+"'' didn't complete yet."); - ERR_FAIL_COND_V(resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE,IP_Address()); + if (resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE) { + ERR_EXPLAIN("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet."); + ERR_FAIL_COND_V(resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE, IP_Address()); } - return resolver->queue[p_id].response; - } void IP::erase_resolve_item(ResolverID p_id) { - ERR_FAIL_INDEX(p_id,IP::RESOLVER_MAX_QUERIES); + ERR_FAIL_INDEX(p_id, IP::RESOLVER_MAX_QUERIES); GLOBAL_LOCK_FUNCTION; - resolver->queue[p_id].status=IP::RESOLVER_STATUS_NONE; - + resolver->queue[p_id].status = IP::RESOLVER_STATUS_NONE; } void IP::clear_cache(const String &p_hostname) { @@ -209,7 +196,7 @@ Array IP::_get_local_addresses() const { Array addresses; List<IP_Address> ip_addresses; get_local_addresses(&ip_addresses); - for(List<IP_Address>::Element *E=ip_addresses.front();E;E=E->next()) { + for (List<IP_Address>::Element *E = ip_addresses.front(); E; E = E->next()) { addresses.push_back(E->get()); } @@ -218,87 +205,82 @@ Array IP::_get_local_addresses() const { void IP::_bind_methods() { - ClassDB::bind_method(D_METHOD("resolve_hostname","host","ip_type"),&IP::resolve_hostname,DEFVAL(IP::TYPE_ANY)); - ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item","host","ip_type"),&IP::resolve_hostname_queue_item,DEFVAL(IP::TYPE_ANY)); - ClassDB::bind_method(D_METHOD("get_resolve_item_status","id"),&IP::get_resolve_item_status); - ClassDB::bind_method(D_METHOD("get_resolve_item_address","id"),&IP::get_resolve_item_address); - ClassDB::bind_method(D_METHOD("erase_resolve_item","id"),&IP::erase_resolve_item); - ClassDB::bind_method(D_METHOD("get_local_addresses"),&IP::_get_local_addresses); - ClassDB::bind_method(D_METHOD("clear_cache"),&IP::clear_cache, DEFVAL("")); - - BIND_CONSTANT( RESOLVER_STATUS_NONE ); - BIND_CONSTANT( RESOLVER_STATUS_WAITING ); - BIND_CONSTANT( RESOLVER_STATUS_DONE ); - BIND_CONSTANT( RESOLVER_STATUS_ERROR ); - - BIND_CONSTANT( RESOLVER_MAX_QUERIES ); - BIND_CONSTANT( RESOLVER_INVALID_ID ); - - BIND_CONSTANT( TYPE_NONE ); - BIND_CONSTANT( TYPE_IPV4 ); - BIND_CONSTANT( TYPE_IPV6 ); - BIND_CONSTANT( TYPE_ANY ); + ClassDB::bind_method(D_METHOD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY)); + ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY)); + ClassDB::bind_method(D_METHOD("get_resolve_item_status", "id"), &IP::get_resolve_item_status); + ClassDB::bind_method(D_METHOD("get_resolve_item_address", "id"), &IP::get_resolve_item_address); + ClassDB::bind_method(D_METHOD("erase_resolve_item", "id"), &IP::erase_resolve_item); + ClassDB::bind_method(D_METHOD("get_local_addresses"), &IP::_get_local_addresses); + ClassDB::bind_method(D_METHOD("clear_cache"), &IP::clear_cache, DEFVAL("")); + + BIND_CONSTANT(RESOLVER_STATUS_NONE); + BIND_CONSTANT(RESOLVER_STATUS_WAITING); + BIND_CONSTANT(RESOLVER_STATUS_DONE); + BIND_CONSTANT(RESOLVER_STATUS_ERROR); + + BIND_CONSTANT(RESOLVER_MAX_QUERIES); + BIND_CONSTANT(RESOLVER_INVALID_ID); + + BIND_CONSTANT(TYPE_NONE); + BIND_CONSTANT(TYPE_IPV4); + BIND_CONSTANT(TYPE_IPV6); + BIND_CONSTANT(TYPE_ANY); } +IP *IP::singleton = NULL; -IP*IP::singleton=NULL; - -IP* IP::get_singleton() { +IP *IP::get_singleton() { return singleton; } +IP *(*IP::_create)() = NULL; -IP* (*IP::_create)()=NULL; +IP *IP::create() { -IP* IP::create() { - - ERR_FAIL_COND_V(singleton,NULL); - ERR_FAIL_COND_V(!_create,NULL); + ERR_FAIL_COND_V(singleton, NULL); + ERR_FAIL_COND_V(!_create, NULL); return _create(); } IP::IP() { - singleton=this; - resolver = memnew( _IP_ResolverPrivate ); - resolver->sem=NULL; + singleton = this; + resolver = memnew(_IP_ResolverPrivate); + resolver->sem = NULL; #ifndef NO_THREADS //resolver->sem = Semaphore::create(); - resolver->sem=NULL; + resolver->sem = NULL; if (resolver->sem) { - resolver->thread_abort=false; + resolver->thread_abort = false; - resolver->thread = Thread::create( _IP_ResolverPrivate::_thread_function,resolver ); + resolver->thread = Thread::create(_IP_ResolverPrivate::_thread_function, resolver); if (!resolver->thread) memdelete(resolver->sem); //wtf } else { - resolver->thread=NULL; + resolver->thread = NULL; } #else resolver->sem = NULL; - resolver->thread=NULL; + resolver->thread = NULL; #endif - - } IP::~IP() { #ifndef NO_THREADS if (resolver->thread) { - resolver->thread_abort=true; + resolver->thread_abort = true; resolver->sem->post(); Thread::wait_to_finish(resolver->thread); - memdelete( resolver->thread ); - memdelete( resolver->sem); + memdelete(resolver->thread); + memdelete(resolver->sem); } memdelete(resolver); #endif - } diff --git a/core/io/ip.h b/core/io/ip.h index 3e028f2613..052a0e08cc 100644 --- a/core/io/ip.h +++ b/core/io/ip.h @@ -29,17 +29,16 @@ #ifndef IP_H #define IP_H - -#include "os/os.h" #include "io/ip_address.h" +#include "os/os.h" struct _IP_ResolverPrivate; class IP : public Object { - GDCLASS( IP, Object ); + GDCLASS(IP, Object); OBJ_CATEGORY("Networking"); -public: +public: enum ResolverStatus { RESOLVER_STATUS_NONE, @@ -58,47 +57,40 @@ public: enum { RESOLVER_MAX_QUERIES = 32, - RESOLVER_INVALID_ID=-1 + RESOLVER_INVALID_ID = -1 }; - typedef int ResolverID; - private: - _IP_ResolverPrivate *resolver; -protected: - static IP*singleton; +protected: + static IP *singleton; static void _bind_methods(); - virtual IP_Address _resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY)=0; + virtual IP_Address _resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY) = 0; Array _get_local_addresses() const; - static IP* (*_create)(); -public: - + static IP *(*_create)(); - - IP_Address resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY); +public: + IP_Address resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY); // async resolver hostname - ResolverID resolve_hostname_queue_item(const String& p_hostname, Type p_type = TYPE_ANY); + ResolverID resolve_hostname_queue_item(const String &p_hostname, Type p_type = TYPE_ANY); ResolverStatus get_resolve_item_status(ResolverID p_id) const; IP_Address get_resolve_item_address(ResolverID p_id) const; - virtual void get_local_addresses(List<IP_Address> *r_addresses) const=0; + virtual void get_local_addresses(List<IP_Address> *r_addresses) const = 0; void erase_resolve_item(ResolverID p_id); - void clear_cache(const String& p_hostname = ""); + void clear_cache(const String &p_hostname = ""); - static IP* get_singleton(); + static IP *get_singleton(); - static IP* create(); + static IP *create(); IP(); ~IP(); - - }; VARIANT_ENUM_CAST(IP::Type); diff --git a/core/io/ip_address.cpp b/core/io/ip_address.cpp index 69c7df619d..fa0eab4f0d 100644 --- a/core/io/ip_address.cpp +++ b/core/io/ip_address.cpp @@ -33,32 +33,32 @@ IP_Address::operator Variant() const { return operator String(); }*/ -#include <string.h> #include <stdio.h> +#include <string.h> IP_Address::operator String() const { - if(!valid) + if (!valid) return ""; - if(is_ipv4()) + if (is_ipv4()) // IPv4 address mapped to IPv6 - return itos(field8[12])+"."+itos(field8[13])+"."+itos(field8[14])+"."+itos(field8[15]); + return itos(field8[12]) + "." + itos(field8[13]) + "." + itos(field8[14]) + "." + itos(field8[15]); String ret; - for (int i=0; i<8; i++) { + for (int i = 0; i < 8; i++) { if (i > 0) ret = ret + ":"; - uint16_t num = (field8[i*2] << 8) + field8[i*2+1]; + uint16_t num = (field8[i * 2] << 8) + field8[i * 2 + 1]; ret = ret + String::num_int64(num, 16); }; return ret; } -static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) { +static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) { uint16_t ret = 0; - for (int i=p_start; i<p_start + 4; i++) { + for (int i = p_start; i < p_start + 4; i++) { if (i >= p_string.length()) { break; @@ -87,17 +87,17 @@ static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) { p_dst[1] = ret & 0xff; }; -void IP_Address::_parse_ipv6(const String& p_string) { +void IP_Address::_parse_ipv6(const String &p_string) { static const int parts_total = 8; - int parts[parts_total] = {0}; + int parts[parts_total] = { 0 }; int parts_count = 0; bool part_found = false; bool part_skip = false; bool part_ipv4 = false; int parts_idx = 0; - for (int i=0; i<p_string.length(); i++) { + for (int i = 0; i < p_string.length(); i++) { CharType c = p_string[i]; if (c == ':') { @@ -133,26 +133,25 @@ void IP_Address::_parse_ipv6(const String& p_string) { }; int idx = 0; - for (int i=0; i<parts_idx; i++) { + for (int i = 0; i < parts_idx; i++) { if (parts[i] == -1) { - for (int j=0; j<parts_extra; j++) { + for (int j = 0; j < parts_extra; j++) { field16[idx++] = 0; }; continue; }; if (part_ipv4 && i == parts_idx - 1) { - _parse_ipv4(p_string, parts[i], (uint8_t*)&field16[idx]); // should be the last one + _parse_ipv4(p_string, parts[i], (uint8_t *)&field16[idx]); // should be the last one } else { - _parse_hex(p_string, parts[i], (uint8_t*)&(field16[idx++])); + _parse_hex(p_string, parts[i], (uint8_t *)&(field16[idx++])); }; }; - }; -void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret) { +void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret) { String ip; if (p_start != 0) { @@ -162,12 +161,12 @@ void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret }; int slices = ip.get_slice_count("."); - if (slices!=4) { - ERR_EXPLAIN("Invalid IP Address String: "+ip); + if (slices != 4) { + ERR_EXPLAIN("Invalid IP Address String: " + ip); ERR_FAIL(); } - for(int i=0;i<4;i++) { - p_ret[i]=ip.get_slicec('.',i).to_int(); + for (int i = 0; i < 4; i++) { + p_ret[i] = ip.get_slicec('.', i).to_int(); } }; @@ -178,34 +177,34 @@ void IP_Address::clear() { wildcard = false; }; -bool IP_Address::is_ipv4() const{ - return (field32[0]==0 && field32[1]==0 && field16[4]==0 && field16[5]==0xffff); +bool IP_Address::is_ipv4() const { + return (field32[0] == 0 && field32[1] == 0 && field16[4] == 0 && field16[5] == 0xffff); } -const uint8_t *IP_Address::get_ipv4() const{ - ERR_FAIL_COND_V(!is_ipv4(),0); +const uint8_t *IP_Address::get_ipv4() const { + ERR_FAIL_COND_V(!is_ipv4(), 0); return &(field8[12]); } void IP_Address::set_ipv4(const uint8_t *p_ip) { clear(); valid = true; - field16[5]=0xffff; - field32[3]=*((const uint32_t *)p_ip); + field16[5] = 0xffff; + field32[3] = *((const uint32_t *)p_ip); } -const uint8_t *IP_Address::get_ipv6() const{ +const uint8_t *IP_Address::get_ipv6() const { return field8; } void IP_Address::set_ipv6(const uint8_t *p_buf) { clear(); valid = true; - for (int i=0; i<16; i++) + for (int i = 0; i < 16; i++) field8[i] = p_buf[i]; } -IP_Address::IP_Address(const String& p_string) { +IP_Address::IP_Address(const String &p_string) { clear(); @@ -229,7 +228,7 @@ IP_Address::IP_Address(const String& p_string) { } } -_FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) { +_FORCE_INLINE_ static void _32_to_buf(uint8_t *p_dst, uint32_t p_n) { p_dst[0] = (p_n >> 24) & 0xff; p_dst[1] = (p_n >> 16) & 0xff; @@ -237,17 +236,17 @@ _FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) { p_dst[3] = (p_n >> 0) & 0xff; }; -IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6) { +IP_Address::IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6) { clear(); valid = true; if (!is_v6) { // Mapped to IPv6 - field16[5]=0xffff; - field8[12]=p_a; - field8[13]=p_b; - field8[14]=p_c; - field8[15]=p_d; + field16[5] = 0xffff; + field8[12] = p_a; + field8[13] = p_b; + field8[14] = p_c; + field8[15] = p_d; } else { _32_to_buf(&field8[0], p_a); @@ -255,5 +254,4 @@ IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool _32_to_buf(&field8[8], p_c); _32_to_buf(&field8[12], p_d); } - } diff --git a/core/io/ip_address.h b/core/io/ip_address.h index 257836601a..52d6974d5e 100644 --- a/core/io/ip_address.h +++ b/core/io/ip_address.h @@ -34,7 +34,6 @@ struct IP_Address { private: - union { uint8_t field8[16]; uint16_t field16[8]; @@ -45,31 +44,31 @@ private: bool wildcard; protected: - void _parse_ipv6(const String& p_string); - void _parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret); + void _parse_ipv6(const String &p_string); + void _parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret); public: //operator Variant() const; - bool operator==(const IP_Address& p_ip) const { + bool operator==(const IP_Address &p_ip) const { if (p_ip.valid != valid) return false; if (!valid) return false; - for (int i=0; i<4; i++) + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return false; return true; } - bool operator!=(const IP_Address& p_ip) const { + bool operator!=(const IP_Address &p_ip) const { if (p_ip.valid != valid) return true; if (!valid) return true; - for (int i=0; i<4; i++) + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return true; return false; } void clear(); - bool is_wildcard() const {return wildcard;} - bool is_valid() const {return valid;} + bool is_wildcard() const { return wildcard; } + bool is_valid() const { return valid; } bool is_ipv4() const; const uint8_t *get_ipv4() const; void set_ipv4(const uint8_t *p_ip); @@ -78,11 +77,9 @@ public: void set_ipv6(const uint8_t *buf); operator String() const; - IP_Address(const String& p_string); - IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6=false); + IP_Address(const String &p_string); + IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6 = false); IP_Address() { clear(); } }; - - #endif // IP_ADDRESS_H diff --git a/core/io/json.cpp b/core/io/json.cpp index 5ade25aab4..98d48ce4ae 100644 --- a/core/io/json.cpp +++ b/core/io/json.cpp @@ -29,7 +29,7 @@ #include "json.h" #include "print_string.h" -const char * JSON::tk_name[TK_MAX] = { +const char *JSON::tk_name[TK_MAX] = { "'{'", "'}'", "'['", @@ -42,14 +42,12 @@ const char * JSON::tk_name[TK_MAX] = { "EOF", }; +String JSON::_print_var(const Variant &p_var) { - -String JSON::_print_var(const Variant& p_var) { - - switch(p_var.get_type()) { + switch (p_var.get_type()) { case Variant::NIL: return "null"; - case Variant::BOOL: return p_var.operator bool() ? "true": "false"; + case Variant::BOOL: return p_var.operator bool() ? "true" : "false"; case Variant::INT: return itos(p_var); case Variant::REAL: return rtos(p_var); case Variant::POOL_INT_ARRAY: @@ -59,12 +57,12 @@ String JSON::_print_var(const Variant& p_var) { String s = "["; Array a = p_var; - for(int i=0;i<a.size();i++) { - if (i>0) - s+=", "; - s+=_print_var(a[i]); + for (int i = 0; i < a.size(); i++) { + if (i > 0) + s += ", "; + s += _print_var(a[i]); } - s+="]"; + s += "]"; return s; }; case Variant::DICTIONARY: { @@ -74,34 +72,31 @@ String JSON::_print_var(const Variant& p_var) { List<Variant> keys; d.get_key_list(&keys); - for (List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { - if (E!=keys.front()) - s+=", "; - s+=_print_var(String(E->get())); - s+=":"; - s+=_print_var(d[E->get()]); + if (E != keys.front()) + s += ", "; + s += _print_var(String(E->get())); + s += ":"; + s += _print_var(d[E->get()]); } - s+="}"; + s += "}"; return s; }; - default: return "\""+String(p_var).json_escape()+"\""; - + default: return "\"" + String(p_var).json_escape() + "\""; } - } -String JSON::print(const Variant& p_var) { +String JSON::print(const Variant &p_var) { return _print_var(p_var); } - -Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_token,int &line,String &r_err_str) { +Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token &r_token, int &line, String &r_err_str) { while (p_len > 0) { - switch(p_str[idx]) { + switch (p_str[idx]) { case '\n': { @@ -110,42 +105,42 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke break; }; case 0: { - r_token.type=TK_EOF; + r_token.type = TK_EOF; return OK; } break; case '{': { - r_token.type=TK_CURLY_BRACKET_OPEN; + r_token.type = TK_CURLY_BRACKET_OPEN; idx++; return OK; }; case '}': { - r_token.type=TK_CURLY_BRACKET_CLOSE; + r_token.type = TK_CURLY_BRACKET_CLOSE; idx++; return OK; }; case '[': { - r_token.type=TK_BRACKET_OPEN; + r_token.type = TK_BRACKET_OPEN; idx++; return OK; }; case ']': { - r_token.type=TK_BRACKET_CLOSE; + r_token.type = TK_BRACKET_CLOSE; idx++; return OK; }; case ':': { - r_token.type=TK_COLON; + r_token.type = TK_COLON; idx++; return OK; }; case ',': { - r_token.type=TK_COMMA; + r_token.type = TK_COMMA; idx++; return OK; }; @@ -153,66 +148,62 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke idx++; String str; - while(true) { - if (p_str[idx]==0) { - r_err_str="Unterminated String"; + while (true) { + if (p_str[idx] == 0) { + r_err_str = "Unterminated String"; return ERR_PARSE_ERROR; - } else if (p_str[idx]=='"') { + } else if (p_str[idx] == '"') { idx++; break; - } else if (p_str[idx]=='\\') { + } else if (p_str[idx] == '\\') { //escaped characters... idx++; CharType next = p_str[idx]; - if (next==0) { - r_err_str="Unterminated String"; - return ERR_PARSE_ERROR; + if (next == 0) { + r_err_str = "Unterminated String"; + return ERR_PARSE_ERROR; } - CharType res=0; + CharType res = 0; - switch(next) { + switch (next) { - case 'b': res=8; break; - case 't': res=9; break; - case 'n': res=10; break; - case 'f': res=12; break; - case 'r': res=13; break; + case 'b': res = 8; break; + case 't': res = 9; break; + case 'n': res = 10; break; + case 'f': res = 12; break; + case 'r': res = 13; break; case 'u': { //hexnumbarh - oct is deprecated - - for(int j=0;j<4;j++) { - CharType c = p_str[idx+j+1]; - if (c==0) { - r_err_str="Unterminated String"; + for (int j = 0; j < 4; j++) { + CharType c = p_str[idx + j + 1]; + if (c == 0) { + r_err_str = "Unterminated String"; return ERR_PARSE_ERROR; } - if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { - r_err_str="Malformed hex constant in string"; + r_err_str = "Malformed hex constant in string"; return ERR_PARSE_ERROR; } CharType v; - if (c>='0' && c<='9') { - v=c-'0'; - } else if (c>='a' && c<='f') { - v=c-'a'; - v+=10; - } else if (c>='A' && c<='F') { - v=c-'A'; - v+=10; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a'; + v += 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A'; + v += 10; } else { ERR_PRINT("BUG"); - v=0; + v = 0; } - res<<=4; - res|=v; - - + res <<= 4; + res |= v; } - idx+=4; //will add at the end anyway - + idx += 4; //will add at the end anyway } break; //case '\"': res='\"'; break; @@ -225,250 +216,232 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke } break; } - str+=res; + str += res; } else { - if (p_str[idx]=='\n') + if (p_str[idx] == '\n') line++; - str+=p_str[idx]; + str += p_str[idx]; } idx++; } - r_token.type=TK_STRING; - r_token.value=str; + r_token.type = TK_STRING; + r_token.value = str; return OK; } break; default: { - if (p_str[idx]<=32) { + if (p_str[idx] <= 32) { idx++; break; } - if (p_str[idx]=='-' || (p_str[idx]>='0' && p_str[idx]<='9')) { + if (p_str[idx] == '-' || (p_str[idx] >= '0' && p_str[idx] <= '9')) { //a number const CharType *rptr; - double number = String::to_double(&p_str[idx],&rptr); - idx+=(rptr - &p_str[idx]); - r_token.type=TK_NUMBER; - r_token.value=number; + double number = String::to_double(&p_str[idx], &rptr); + idx += (rptr - &p_str[idx]); + r_token.type = TK_NUMBER; + r_token.value = number; return OK; - } else if ((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) { + } else if ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) { String id; - while((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) { + while ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) { - id+=p_str[idx]; + id += p_str[idx]; idx++; } - r_token.type=TK_IDENTIFIER; - r_token.value=id; + r_token.type = TK_IDENTIFIER; + r_token.value = id; return OK; } else { - r_err_str="Unexpected character."; + r_err_str = "Unexpected character."; return ERR_PARSE_ERROR; } } - } } return ERR_PARSE_ERROR; } +Error JSON::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { - -Error JSON::_parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { - - - if (token.type==TK_CURLY_BRACKET_OPEN) { + if (token.type == TK_CURLY_BRACKET_OPEN) { Dictionary d; - Error err = _parse_object(d,p_str,index,p_len,line,r_err_str); + Error err = _parse_object(d, p_str, index, p_len, line, r_err_str); if (err) return err; - value=d; + value = d; return OK; - } else if (token.type==TK_BRACKET_OPEN) { + } else if (token.type == TK_BRACKET_OPEN) { Array a; - Error err = _parse_array(a,p_str,index,p_len,line,r_err_str); + Error err = _parse_array(a, p_str, index, p_len, line, r_err_str); if (err) return err; - value=a; + value = a; return OK; - } else if (token.type==TK_IDENTIFIER) { + } else if (token.type == TK_IDENTIFIER) { String id = token.value; - if (id=="true") - value=true; - else if (id=="false") - value=false; - else if (id=="null") - value=Variant(); + if (id == "true") + value = true; + else if (id == "false") + value = false; + else if (id == "null") + value = Variant(); else { - r_err_str="Expected 'true','false' or 'null', got '"+id+"'."; + r_err_str = "Expected 'true','false' or 'null', got '" + id + "'."; return ERR_PARSE_ERROR; } return OK; - } else if (token.type==TK_NUMBER) { + } else if (token.type == TK_NUMBER) { - value=token.value; + value = token.value; return OK; - } else if (token.type==TK_STRING) { + } else if (token.type == TK_STRING) { - value=token.value; + value = token.value; return OK; } else { - r_err_str="Expected value, got "+String(tk_name[token.type])+"."; + r_err_str = "Expected value, got " + String(tk_name[token.type]) + "."; return ERR_PARSE_ERROR; } return ERR_PARSE_ERROR; } - -Error JSON::_parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { +Error JSON::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { Token token; - bool need_comma=false; - + bool need_comma = false; - while(index<p_len) { + while (index < p_len) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_BRACKET_CLOSE) { + if (token.type == TK_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected ','"; + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str); if (err) return err; array.push_back(v); - need_comma=true; - + need_comma = true; } return ERR_PARSE_ERROR; - } -Error JSON::_parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { +Error JSON::_parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { - bool at_key=true; + bool at_key = true; String key; Token token; - bool need_comma=false; - - - while(index<p_len) { + bool need_comma = false; + while (index < p_len) { if (at_key) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_CURLY_BRACKET_CLOSE) { + if (token.type == TK_CURLY_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected '}' or ','"; + r_err_str = "Expected '}' or ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } - if (token.type!=TK_STRING) { - + if (token.type != TK_STRING) { - r_err_str="Expected key"; + r_err_str = "Expected key"; return ERR_PARSE_ERROR; } - key=token.value; - err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + key = token.value; + err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type!=TK_COLON) { + if (token.type != TK_COLON) { - r_err_str="Expected ':'"; + r_err_str = "Expected ':'"; return ERR_PARSE_ERROR; } - at_key=false; + at_key = false; } else { - - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str); if (err) return err; - object[key]=v; - need_comma=true; - at_key=true; + object[key] = v; + need_comma = true; + at_key = true; } } return ERR_PARSE_ERROR; } - -Error JSON::parse(const String& p_json, Variant &r_ret, String &r_err_str, int &r_err_line) { - +Error JSON::parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line) { const CharType *str = p_json.ptr(); int idx = 0; int len = p_json.length(); Token token; - r_err_line=0; + r_err_line = 0; String aux_key; - Error err = _get_token(str,idx,len,token,r_err_line,r_err_str); + Error err = _get_token(str, idx, len, token, r_err_line, r_err_str); if (err) return err; - err = _parse_value(r_ret,token,str,idx,len,r_err_line,r_err_str); + err = _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str); return err; - - } - - diff --git a/core/io/json.h b/core/io/json.h index 97457d223e..afd97c85b5 100644 --- a/core/io/json.h +++ b/core/io/json.h @@ -29,11 +29,8 @@ #ifndef JSON_H #define JSON_H - - #include "variant.h" - class JSON { enum TokenType { @@ -64,18 +61,18 @@ class JSON { Variant value; }; - static const char * tk_name[TK_MAX]; + static const char *tk_name[TK_MAX]; - static String _print_var(const Variant& p_var); + static String _print_var(const Variant &p_var); - static Error _get_token(const CharType *p_str,int &index, int p_len,Token& r_token,int &line,String &r_err_str); - static Error _parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); - static Error _parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); - static Error _parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); + static Error _get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str); + static Error _parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); + static Error _parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); + static Error _parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); public: static String print(const Variant &p_var); - static Error parse(const String& p_json,Variant& r_ret,String &r_err_str,int &r_err_line); + static Error parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line); }; #endif // JSON_H diff --git a/core/io/marshalls.cpp b/core/io/marshalls.cpp index a8c1cd0a10..927ce31744 100644 --- a/core/io/marshalls.cpp +++ b/core/io/marshalls.cpp @@ -27,99 +27,96 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "marshalls.h" -#include "print_string.h" #include "os/keyboard.h" +#include "print_string.h" #include <stdio.h> +#define ENCODE_MASK 0xFF +#define ENCODE_FLAG_64 1 << 16 -#define ENCODE_MASK 0xFF -#define ENCODE_FLAG_64 1<<16 +Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) { -Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len) { + const uint8_t *buf = p_buffer; + int len = p_len; - const uint8_t * buf=p_buffer; - int len=p_len; + if (len < 4) { - if (len<4) { - - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); } + uint32_t type = decode_uint32(buf); - uint32_t type=decode_uint32(buf); - - ERR_FAIL_COND_V((type&ENCODE_MASK)>=Variant::VARIANT_MAX,ERR_INVALID_DATA); + ERR_FAIL_COND_V((type & ENCODE_MASK) >= Variant::VARIANT_MAX, ERR_INVALID_DATA); - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) - *r_len=4; + *r_len = 4; - switch(type&ENCODE_MASK) { + switch (type & ENCODE_MASK) { case Variant::NIL: { - r_variant=Variant(); + r_variant = Variant(); } break; case Variant::BOOL: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); bool val = decode_uint32(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case Variant::INT: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); - if (type&ENCODE_FLAG_64) { + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); + if (type & ENCODE_FLAG_64) { int64_t val = decode_uint64(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=8; + (*r_len) += 8; } else { int32_t val = decode_uint32(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } } break; case Variant::REAL: { - ERR_FAIL_COND_V(len<(int)4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4, ERR_INVALID_DATA); - if (type&ENCODE_FLAG_64) { + if (type & ENCODE_FLAG_64) { double val = decode_double(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=8; + (*r_len) += 8; } else { float val = decode_float(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } } break; case Variant::STRING: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); - r_variant=str; + str.parse_utf8((const char *)buf, strlen); + r_variant = str; if (r_len) { - if (strlen%4) - (*r_len)+=4-strlen%4; - (*r_len)+=4+strlen; - + if (strlen % 4) + (*r_len) += 4 - strlen % 4; + (*r_len) += 4 + strlen; } } break; @@ -127,268 +124,262 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * case Variant::VECTOR2: { - ERR_FAIL_COND_V(len<(int)4*2,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 2, ERR_INVALID_DATA); Vector2 val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + r_variant = val; if (r_len) - (*r_len)+=4*2; + (*r_len) += 4 * 2; - } break; // 5 + } break; // 5 case Variant::RECT2: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Rect2 val; - val.pos.x=decode_float(&buf[0]); - val.pos.y=decode_float(&buf[4]); - val.size.x=decode_float(&buf[8]); - val.size.y=decode_float(&buf[12]); - r_variant=val; + val.pos.x = decode_float(&buf[0]); + val.pos.y = decode_float(&buf[4]); + val.size.x = decode_float(&buf[8]); + val.size.y = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::VECTOR3: { - ERR_FAIL_COND_V(len<(int)4*3,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 3, ERR_INVALID_DATA); Vector3 val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - val.z=decode_float(&buf[8]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + val.z = decode_float(&buf[8]); + r_variant = val; if (r_len) - (*r_len)+=4*3; + (*r_len) += 4 * 3; } break; case Variant::TRANSFORM2D: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); Transform2D val; - for(int i=0;i<3;i++) { - for(int j=0;j<2;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - val.elements[i][j]=decode_float(&buf[(i*2+j)*4]); + val.elements[i][j] = decode_float(&buf[(i * 2 + j) * 4]); } } - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*6; + (*r_len) += 4 * 6; } break; case Variant::PLANE: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Plane val; - val.normal.x=decode_float(&buf[0]); - val.normal.y=decode_float(&buf[4]); - val.normal.z=decode_float(&buf[8]); - val.d=decode_float(&buf[12]); - r_variant=val; + val.normal.x = decode_float(&buf[0]); + val.normal.y = decode_float(&buf[4]); + val.normal.z = decode_float(&buf[8]); + val.d = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::QUAT: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Quat val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - val.z=decode_float(&buf[8]); - val.w=decode_float(&buf[12]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + val.z = decode_float(&buf[8]); + val.w = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::RECT3: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); Rect3 val; - val.pos.x=decode_float(&buf[0]); - val.pos.y=decode_float(&buf[4]); - val.pos.z=decode_float(&buf[8]); - val.size.x=decode_float(&buf[12]); - val.size.y=decode_float(&buf[16]); - val.size.z=decode_float(&buf[20]); - r_variant=val; + val.pos.x = decode_float(&buf[0]); + val.pos.y = decode_float(&buf[4]); + val.pos.z = decode_float(&buf[8]); + val.size.x = decode_float(&buf[12]); + val.size.y = decode_float(&buf[16]); + val.size.z = decode_float(&buf[20]); + r_variant = val; if (r_len) - (*r_len)+=4*6; + (*r_len) += 4 * 6; } break; case Variant::BASIS: { - ERR_FAIL_COND_V(len<(int)4*9,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 9, ERR_INVALID_DATA); Basis val; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - val.elements[i][j]=decode_float(&buf[(i*3+j)*4]); + val.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*9; + (*r_len) += 4 * 9; } break; case Variant::TRANSFORM: { - ERR_FAIL_COND_V(len<(int)4*12,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 12, ERR_INVALID_DATA); Transform val; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - val.basis.elements[i][j]=decode_float(&buf[(i*3+j)*4]); + val.basis.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } - val.origin[0]=decode_float(&buf[36]); - val.origin[1]=decode_float(&buf[40]); - val.origin[2]=decode_float(&buf[44]); + val.origin[0] = decode_float(&buf[36]); + val.origin[1] = decode_float(&buf[40]); + val.origin[2] = decode_float(&buf[44]); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*12; + (*r_len) += 4 * 12; } break; // misc types case Variant::COLOR: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Color val; - val.r=decode_float(&buf[0]); - val.g=decode_float(&buf[4]); - val.b=decode_float(&buf[8]); - val.a=decode_float(&buf[12]); - r_variant=val; + val.r = decode_float(&buf[0]); + val.g = decode_float(&buf[4]); + val.b = decode_float(&buf[8]); + val.a = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::IMAGE: { - ERR_FAIL_COND_V(len<(int)5*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)5 * 4, ERR_INVALID_DATA); Image::Format fmt = (Image::Format)decode_uint32(&buf[0]); - ERR_FAIL_INDEX_V( fmt, Image::FORMAT_MAX, ERR_INVALID_DATA); + ERR_FAIL_INDEX_V(fmt, Image::FORMAT_MAX, ERR_INVALID_DATA); uint32_t mipmaps = decode_uint32(&buf[4]); uint32_t w = decode_uint32(&buf[8]); uint32_t h = decode_uint32(&buf[12]); uint32_t datalen = decode_uint32(&buf[16]); Image img; - if (datalen>0) { - len-=5*4; - ERR_FAIL_COND_V( len < datalen, ERR_INVALID_DATA ); + if (datalen > 0) { + len -= 5 * 4; + ERR_FAIL_COND_V(len < datalen, ERR_INVALID_DATA); PoolVector<uint8_t> data; data.resize(datalen); PoolVector<uint8_t>::Write wr = data.write(); - copymem(&wr[0],&buf[20],datalen); + copymem(&wr[0], &buf[20], datalen); wr = PoolVector<uint8_t>::Write(); - - - img=Image(w,h,mipmaps,fmt,data); + img = Image(w, h, mipmaps, fmt, data); } - r_variant=img; + r_variant = img; if (r_len) { - if (datalen%4) - (*r_len)+=4-datalen%4; + if (datalen % 4) + (*r_len) += 4 - datalen % 4; - (*r_len)+=4*5+datalen; + (*r_len) += 4 * 5 + datalen; } } break; case Variant::NODE_PATH: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - if (strlen&0x80000000) { + if (strlen & 0x80000000) { //new format - ERR_FAIL_COND_V(len<12,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 12, ERR_INVALID_DATA); Vector<StringName> names; Vector<StringName> subnames; StringName prop; - uint32_t namecount=strlen&=0x7FFFFFFF; - uint32_t subnamecount = decode_uint32(buf+4); - uint32_t flags = decode_uint32(buf+8); + uint32_t namecount = strlen &= 0x7FFFFFFF; + uint32_t subnamecount = decode_uint32(buf + 4); + uint32_t flags = decode_uint32(buf + 8); - len-=12; - buf+=12; + len -= 12; + buf += 12; - int total=namecount+subnamecount; - if (flags&2) + int total = namecount + subnamecount; + if (flags & 2) total++; if (r_len) - (*r_len)+=12; - + (*r_len) += 12; - for(int i=0;i<total;i++) { + for (int i = 0; i < total; i++) { - ERR_FAIL_COND_V((int)len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)len < 4, ERR_INVALID_DATA); strlen = decode_uint32(buf); - int pad=0; + int pad = 0; - if (strlen%4) - pad+=4-strlen%4; + if (strlen % 4) + pad += 4 - strlen % 4; - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen+pad>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen + pad > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); - + str.parse_utf8((const char *)buf, strlen); - if (i<namecount) + if (i < namecount) names.push_back(str); - else if (i<namecount+subnamecount) + else if (i < namecount + subnamecount) subnames.push_back(str); else - prop=str; + prop = str; - buf+=strlen+pad; - len-=strlen+pad; + buf += strlen + pad; + len -= strlen + pad; if (r_len) - (*r_len)+=4+strlen+pad; - + (*r_len) += 4 + strlen + pad; } - r_variant=NodePath(names,subnames,flags&1,prop); + r_variant = NodePath(names, subnames, flags & 1, prop); } else { //old format, just a string - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); - r_variant=NodePath(str); + r_variant = NodePath(str); if (r_len) - (*r_len)+=4+strlen; + (*r_len) += 4 + strlen; } } break; @@ -403,64 +394,62 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * } break; case Variant::OBJECT: { - - r_variant = (Object*)NULL; + r_variant = (Object *)NULL; } break; case Variant::INPUT_EVENT: { InputEvent ie; - ie.type=decode_uint32(&buf[0]); - ie.device=decode_uint32(&buf[4]); + ie.type = decode_uint32(&buf[0]); + ie.device = decode_uint32(&buf[4]); if (r_len) - (*r_len)+=12; + (*r_len) += 12; - switch(ie.type) { + switch (ie.type) { case InputEvent::KEY: { - uint32_t mods=decode_uint32(&buf[12]); - if (mods&KEY_MASK_SHIFT) - ie.key.mod.shift=true; - if (mods&KEY_MASK_CTRL) - ie.key.mod.control=true; - if (mods&KEY_MASK_ALT) - ie.key.mod.alt=true; - if (mods&KEY_MASK_META) - ie.key.mod.meta=true; - ie.key.scancode=decode_uint32(&buf[16]); + uint32_t mods = decode_uint32(&buf[12]); + if (mods & KEY_MASK_SHIFT) + ie.key.mod.shift = true; + if (mods & KEY_MASK_CTRL) + ie.key.mod.control = true; + if (mods & KEY_MASK_ALT) + ie.key.mod.alt = true; + if (mods & KEY_MASK_META) + ie.key.mod.meta = true; + ie.key.scancode = decode_uint32(&buf[16]); if (r_len) - (*r_len)+=8; - + (*r_len) += 8; } break; case InputEvent::MOUSE_BUTTON: { - ie.mouse_button.button_index=decode_uint32(&buf[12]); + ie.mouse_button.button_index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::JOYPAD_BUTTON: { - ie.joy_button.button_index=decode_uint32(&buf[12]); + ie.joy_button.button_index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::SCREEN_TOUCH: { - ie.screen_touch.index=decode_uint32(&buf[12]); + ie.screen_touch.index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::JOYPAD_MOTION: { - ie.joy_motion.axis=decode_uint32(&buf[12]); - ie.joy_motion.axis_value=decode_float(&buf[16]); + ie.joy_motion.axis = decode_uint32(&buf[12]); + ie.joy_motion.axis_value = decode_float(&buf[16]); if (r_len) - (*r_len)+=8; + (*r_len) += 8; } break; } @@ -469,125 +458,121 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * } break; case Variant::DICTIONARY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); - uint32_t count = decode_uint32(buf); - // bool shared = count&0x80000000; - count&=0x7FFFFFFF; + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); + uint32_t count = decode_uint32(buf); + // bool shared = count&0x80000000; + count &= 0x7FFFFFFF; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } - Dictionary d; + Dictionary d; - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - Variant key,value; + Variant key, value; int used; - Error err = decode_variant(key,buf,len,&used); - ERR_FAIL_COND_V(err,err); + Error err = decode_variant(key, buf, len, &used); + ERR_FAIL_COND_V(err, err); - buf+=used; - len-=used; + buf += used; + len -= used; if (r_len) { - (*r_len)+=used; + (*r_len) += used; } - err = decode_variant(value,buf,len,&used); - ERR_FAIL_COND_V(err,err); + err = decode_variant(value, buf, len, &used); + ERR_FAIL_COND_V(err, err); - buf+=used; - len-=used; + buf += used; + len -= used; if (r_len) { - (*r_len)+=used; + (*r_len) += used; } - d[key]=value; + d[key] = value; } - r_variant=d; + r_variant = d; } break; case Variant::ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - // bool shared = count&0x80000000; - count&=0x7FFFFFFF; + // bool shared = count&0x80000000; + count &= 0x7FFFFFFF; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } - Array varr; + Array varr; - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - int used=0; + int used = 0; Variant v; - Error err = decode_variant(v,buf,len,&used); - ERR_FAIL_COND_V(err,err); - buf+=used; - len-=used; + Error err = decode_variant(v, buf, len, &used); + ERR_FAIL_COND_V(err, err); + buf += used; + len -= used; varr.push_back(v); if (r_len) { - (*r_len)+=used; + (*r_len) += used; } } - r_variant=varr; - + r_variant = varr; } break; // arrays case Variant::POOL_BYTE_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count>len,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count > len, ERR_INVALID_DATA); PoolVector<uint8_t> data; if (count) { data.resize(count); PoolVector<uint8_t>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=buf[i]; + w[i] = buf[i]; } w = PoolVector<uint8_t>::Write(); } - r_variant=data; + r_variant = data; if (r_len) { - if (count%4) - (*r_len)+=4-count%4; - (*r_len)+=4+count; + if (count % 4) + (*r_len) += 4 - count % 4; + (*r_len) += 4 + count; } - - } break; case Variant::POOL_INT_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA); PoolVector<int> data; @@ -595,26 +580,26 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const int*rbuf=(const int*)buf; data.resize(count); PoolVector<int>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=decode_uint32(&buf[i*4]); + w[i] = decode_uint32(&buf[i * 4]); } w = PoolVector<int>::Write(); } - r_variant=Variant(data); + r_variant = Variant(data); if (r_len) { - (*r_len)+=4+count*sizeof(int); + (*r_len) += 4 + count * sizeof(int); } } break; case Variant::POOL_REAL_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA); PoolVector<float> data; @@ -622,182 +607,173 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const float*rbuf=(const float*)buf; data.resize(count); PoolVector<float>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=decode_float(&buf[i*4]); + w[i] = decode_float(&buf[i * 4]); } w = PoolVector<float>::Write(); } - r_variant=data; + r_variant = data; if (r_len) { - (*r_len)+=4+count*sizeof(float); + (*r_len) += 4 + count * sizeof(float); } - } break; case Variant::POOL_STRING_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); PoolVector<String> strings; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) - (*r_len)+=4; + (*r_len) += 4; //printf("string count: %i\n",count); - for(int i=0;i<(int)count;i++) { + for (int i = 0; i < (int)count; i++) { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); //printf("loaded string: %s\n",(const char*)buf); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); strings.push_back(str); - buf+=strlen; - len-=strlen; + buf += strlen; + len -= strlen; if (r_len) - (*r_len)+=4+strlen; + (*r_len) += 4 + strlen; - if (strlen%4) { - int pad = 4-(strlen%4); - buf+=pad; - len-=pad; + if (strlen % 4) { + int pad = 4 - (strlen % 4); + buf += pad; + len -= pad; if (r_len) { - (*r_len)+=pad; + (*r_len) += pad; } } - } - r_variant=strings; - + r_variant = strings; } break; case Variant::POOL_VECTOR2_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*2>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 2 > len, ERR_INVALID_DATA); PoolVector<Vector2> varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); PoolVector<Vector2>::Write w = varray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].x=decode_float(buf+i*4*2+4*0); - w[i].y=decode_float(buf+i*4*2+4*1); + for (int i = 0; i < (int)count; i++) { + w[i].x = decode_float(buf + i * 4 * 2 + 4 * 0); + w[i].y = decode_float(buf + i * 4 * 2 + 4 * 1); } - int adv = 4*2*count; + int adv = 4 * 2 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=varray; + r_variant = varray; } break; case Variant::POOL_VECTOR3_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*3>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 3 > len, ERR_INVALID_DATA); PoolVector<Vector3> varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); PoolVector<Vector3>::Write w = varray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].x=decode_float(buf+i*4*3+4*0); - w[i].y=decode_float(buf+i*4*3+4*1); - w[i].z=decode_float(buf+i*4*3+4*2); + for (int i = 0; i < (int)count; i++) { + w[i].x = decode_float(buf + i * 4 * 3 + 4 * 0); + w[i].y = decode_float(buf + i * 4 * 3 + 4 * 1); + w[i].z = decode_float(buf + i * 4 * 3 + 4 * 2); } - int adv = 4*3*count; + int adv = 4 * 3 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=varray; + r_variant = varray; } break; case Variant::POOL_COLOR_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*4>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 4 > len, ERR_INVALID_DATA); PoolVector<Color> carray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { carray.resize(count); PoolVector<Color>::Write w = carray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].r=decode_float(buf+i*4*4+4*0); - w[i].g=decode_float(buf+i*4*4+4*1); - w[i].b=decode_float(buf+i*4*4+4*2); - w[i].a=decode_float(buf+i*4*4+4*3); + for (int i = 0; i < (int)count; i++) { + w[i].r = decode_float(buf + i * 4 * 4 + 4 * 0); + w[i].g = decode_float(buf + i * 4 * 4 + 4 * 1); + w[i].b = decode_float(buf + i * 4 * 4 + 4 * 2); + w[i].a = decode_float(buf + i * 4 * 4 + 4 * 3); } - int adv = 4*4*count; + int adv = 4 * 4 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=carray; + r_variant = carray; } break; default: { ERR_FAIL_V(ERR_BUG); } @@ -806,39 +782,39 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * return OK; } -Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { +Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) { - uint8_t * buf=r_buffer; + uint8_t *buf = r_buffer; - r_len=0; + r_len = 0; - uint32_t flags=0; + uint32_t flags = 0; - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::INT: { int64_t val = p_variant; - if (val>0x7FFFFFFF || val < -0x80000000) { - flags|=ENCODE_FLAG_64; + if (val > 0x7FFFFFFF || val < -0x80000000) { + flags |= ENCODE_FLAG_64; } } break; case Variant::REAL: { double d = p_variant; float f = d; - if (double(f)!=d) { - flags|=ENCODE_FLAG_64; //always encode real as double + if (double(f) != d) { + flags |= ENCODE_FLAG_64; //always encode real as double } } break; } if (buf) { - encode_uint32(p_variant.get_type()|flags,buf); - buf+=4; + encode_uint32(p_variant.get_type() | flags, buf); + buf += 4; } - r_len+=4; + r_len += 4; - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::NIL: { @@ -847,118 +823,115 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::BOOL: { if (buf) { - encode_uint32(p_variant.operator bool(),buf); + encode_uint32(p_variant.operator bool(), buf); } - r_len+=4; + r_len += 4; } break; case Variant::INT: { int64_t val = p_variant; - if (val>0x7FFFFFFF || val < -0x80000000) { + if (val > 0x7FFFFFFF || val < -0x80000000) { //64 bits if (buf) { - encode_uint64(val,buf); + encode_uint64(val, buf); } - r_len+=8; + r_len += 8; } else { if (buf) { - encode_uint32(int32_t(val),buf); + encode_uint32(int32_t(val), buf); } - r_len+=4; + r_len += 4; } } break; case Variant::REAL: { double d = p_variant; float f = d; - if (double(f)!=d) { + if (double(f) != d) { if (buf) { - encode_double(p_variant.operator double(),buf); + encode_double(p_variant.operator double(), buf); } - r_len+=8; + r_len += 8; } else { if (buf) { - encode_double(p_variant.operator float(),buf); + encode_double(p_variant.operator float(), buf); } - r_len+=4; + r_len += 4; } - } break; case Variant::NODE_PATH: { - NodePath np=p_variant; + NodePath np = p_variant; if (buf) { - encode_uint32(uint32_t(np.get_name_count())|0x80000000,buf); //for compatibility with the old format - encode_uint32(np.get_subname_count(),buf+4); - uint32_t flags=0; + encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format + encode_uint32(np.get_subname_count(), buf + 4); + uint32_t flags = 0; if (np.is_absolute()) - flags|=1; - if (np.get_property()!=StringName()) - flags|=2; + flags |= 1; + if (np.get_property() != StringName()) + flags |= 2; - encode_uint32(flags,buf+8); + encode_uint32(flags, buf + 8); - buf+=12; + buf += 12; } - r_len+=12; + r_len += 12; - int total = np.get_name_count()+np.get_subname_count(); - if (np.get_property()!=StringName()) + int total = np.get_name_count() + np.get_subname_count(); + if (np.get_property() != StringName()) total++; - for(int i=0;i<total;i++) { + for (int i = 0; i < total; i++) { String str; - if (i<np.get_name_count()) - str=np.get_name(i); - else if (i<np.get_name_count()+np.get_subname_count()) - str=np.get_subname(i-np.get_subname_count()); + if (i < np.get_name_count()) + str = np.get_name(i); + else if (i < np.get_name_count() + np.get_subname_count()) + str = np.get_subname(i - np.get_subname_count()); else - str=np.get_property(); + str = np.get_property(); CharString utf8 = str.utf8(); int pad = 0; - if (utf8.length()%4) - pad=4-utf8.length()%4; + if (utf8.length() % 4) + pad = 4 - utf8.length() % 4; if (buf) { - encode_uint32(utf8.length(),buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()); - buf+=pad+utf8.length(); + encode_uint32(utf8.length(), buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length()); + buf += pad + utf8.length(); } - - r_len+=4+utf8.length()+pad; + r_len += 4 + utf8.length() + pad; } } break; case Variant::STRING: { - CharString utf8 = p_variant.operator String().utf8(); if (buf) { - encode_uint32(utf8.length(),buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()); + encode_uint32(utf8.length(), buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length()); } - r_len+=4+utf8.length(); - while (r_len%4) + r_len += 4 + utf8.length(); + while (r_len % 4) r_len++; //pad } break; @@ -967,132 +940,126 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::VECTOR2: { if (buf) { - Vector2 v2=p_variant; - encode_float(v2.x,&buf[0]); - encode_float(v2.y,&buf[4]); - + Vector2 v2 = p_variant; + encode_float(v2.x, &buf[0]); + encode_float(v2.y, &buf[4]); } - r_len+=2*4; + r_len += 2 * 4; - } break; // 5 + } break; // 5 case Variant::RECT2: { if (buf) { - Rect2 r2=p_variant; - encode_float(r2.pos.x,&buf[0]); - encode_float(r2.pos.y,&buf[4]); - encode_float(r2.size.x,&buf[8]); - encode_float(r2.size.y,&buf[12]); + Rect2 r2 = p_variant; + encode_float(r2.pos.x, &buf[0]); + encode_float(r2.pos.y, &buf[4]); + encode_float(r2.size.x, &buf[8]); + encode_float(r2.size.y, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::VECTOR3: { if (buf) { - Vector3 v3=p_variant; - encode_float(v3.x,&buf[0]); - encode_float(v3.y,&buf[4]); - encode_float(v3.z,&buf[8]); + Vector3 v3 = p_variant; + encode_float(v3.x, &buf[0]); + encode_float(v3.y, &buf[4]); + encode_float(v3.z, &buf[8]); } - r_len+=3*4; + r_len += 3 * 4; } break; case Variant::TRANSFORM2D: { if (buf) { - Transform2D val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<2;j++) { + Transform2D val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - copymem(&buf[(i*2+j)*4],&val.elements[i][j],sizeof(float)); + copymem(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float)); } } } - - r_len+=6*4; + r_len += 6 * 4; } break; case Variant::PLANE: { if (buf) { - Plane p=p_variant; - encode_float(p.normal.x,&buf[0]); - encode_float(p.normal.y,&buf[4]); - encode_float(p.normal.z,&buf[8]); - encode_float(p.d,&buf[12]); + Plane p = p_variant; + encode_float(p.normal.x, &buf[0]); + encode_float(p.normal.y, &buf[4]); + encode_float(p.normal.z, &buf[8]); + encode_float(p.d, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::QUAT: { if (buf) { - Quat q=p_variant; - encode_float(q.x,&buf[0]); - encode_float(q.y,&buf[4]); - encode_float(q.z,&buf[8]); - encode_float(q.w,&buf[12]); + Quat q = p_variant; + encode_float(q.x, &buf[0]); + encode_float(q.y, &buf[4]); + encode_float(q.z, &buf[8]); + encode_float(q.w, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::RECT3: { if (buf) { - Rect3 aabb=p_variant; - encode_float(aabb.pos.x,&buf[0]); - encode_float(aabb.pos.y,&buf[4]); - encode_float(aabb.pos.z,&buf[8]); - encode_float(aabb.size.x,&buf[12]); - encode_float(aabb.size.y,&buf[16]); - encode_float(aabb.size.z,&buf[20]); + Rect3 aabb = p_variant; + encode_float(aabb.pos.x, &buf[0]); + encode_float(aabb.pos.y, &buf[4]); + encode_float(aabb.pos.z, &buf[8]); + encode_float(aabb.size.x, &buf[12]); + encode_float(aabb.size.y, &buf[16]); + encode_float(aabb.size.z, &buf[20]); } - r_len+=6*4; - + r_len += 6 * 4; } break; case Variant::BASIS: { if (buf) { - Basis val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Basis val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - copymem(&buf[(i*3+j)*4],&val.elements[i][j],sizeof(float)); + copymem(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float)); } } } - - r_len+=9*4; + r_len += 9 * 4; } break; case Variant::TRANSFORM: { if (buf) { - Transform val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Transform val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - copymem(&buf[(i*3+j)*4],&val.basis.elements[i][j],sizeof(float)); + copymem(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float)); } } - encode_float(val.origin.x,&buf[36]); - encode_float(val.origin.y,&buf[40]); - encode_float(val.origin.z,&buf[44]); - - + encode_float(val.origin.x, &buf[36]); + encode_float(val.origin.y, &buf[40]); + encode_float(val.origin.z, &buf[44]); } - r_len+=12*4; + r_len += 12 * 4; } break; @@ -1100,38 +1067,38 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::COLOR: { if (buf) { - Color c=p_variant; - encode_float(c.r,&buf[0]); - encode_float(c.g,&buf[4]); - encode_float(c.b,&buf[8]); - encode_float(c.a,&buf[12]); + Color c = p_variant; + encode_float(c.r, &buf[0]); + encode_float(c.g, &buf[4]); + encode_float(c.b, &buf[8]); + encode_float(c.a, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::IMAGE: { Image image = p_variant; - PoolVector<uint8_t> data=image.get_data(); + PoolVector<uint8_t> data = image.get_data(); if (buf) { - encode_uint32(image.get_format(),&buf[0]); - encode_uint32(image.has_mipmaps(),&buf[4]); - encode_uint32(image.get_width(),&buf[8]); - encode_uint32(image.get_height(),&buf[12]); - int ds=data.size(); - encode_uint32(ds,&buf[16]); + encode_uint32(image.get_format(), &buf[0]); + encode_uint32(image.has_mipmaps(), &buf[4]); + encode_uint32(image.get_width(), &buf[8]); + encode_uint32(image.get_height(), &buf[12]); + int ds = data.size(); + encode_uint32(ds, &buf[16]); PoolVector<uint8_t>::Read r = data.read(); - copymem(&buf[20],&r[0],ds); + copymem(&buf[20], &r[0], ds); } - int pad=0; - if (data.size()%4) - pad=4-data.size()%4; + int pad = 0; + if (data.size() % 4) + pad = 4 - data.size() % 4; - r_len+=data.size()+5*4+pad; + r_len += data.size() + 5 * 4 + pad; } break; /*case Variant::RESOURCE: { @@ -1142,84 +1109,81 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::_RID: case Variant::OBJECT: { - } break; case Variant::INPUT_EVENT: { - - InputEvent ie=p_variant; + InputEvent ie = p_variant; if (buf) { - encode_uint32(ie.type,&buf[0]); - encode_uint32(ie.device,&buf[4]); - encode_uint32(0,&buf[8]); + encode_uint32(ie.type, &buf[0]); + encode_uint32(ie.device, &buf[4]); + encode_uint32(0, &buf[8]); } - int llen=12; + int llen = 12; - switch(ie.type) { + switch (ie.type) { case InputEvent::KEY: { if (buf) { - uint32_t mods=0; + uint32_t mods = 0; if (ie.key.mod.shift) - mods|=KEY_MASK_SHIFT; + mods |= KEY_MASK_SHIFT; if (ie.key.mod.control) - mods|=KEY_MASK_CTRL; + mods |= KEY_MASK_CTRL; if (ie.key.mod.alt) - mods|=KEY_MASK_ALT; + mods |= KEY_MASK_ALT; if (ie.key.mod.meta) - mods|=KEY_MASK_META; + mods |= KEY_MASK_META; - encode_uint32(mods,&buf[llen]); - encode_uint32(ie.key.scancode,&buf[llen+4]); + encode_uint32(mods, &buf[llen]); + encode_uint32(ie.key.scancode, &buf[llen + 4]); } - llen+=8; + llen += 8; } break; case InputEvent::MOUSE_BUTTON: { if (buf) { - encode_uint32(ie.mouse_button.button_index,&buf[llen]); + encode_uint32(ie.mouse_button.button_index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::JOYPAD_BUTTON: { if (buf) { - encode_uint32(ie.joy_button.button_index,&buf[llen]); + encode_uint32(ie.joy_button.button_index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::SCREEN_TOUCH: { if (buf) { - encode_uint32(ie.screen_touch.index,&buf[llen]); + encode_uint32(ie.screen_touch.index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::JOYPAD_MOTION: { if (buf) { int axis = ie.joy_motion.axis; - encode_uint32(axis,&buf[llen]); - encode_float(ie.joy_motion.axis_value, &buf[llen+4]); + encode_uint32(axis, &buf[llen]); + encode_float(ie.joy_motion.axis_value, &buf[llen + 4]); } - llen+=8; + llen += 8; } break; } if (buf) - encode_uint32(llen,&buf[8]); - r_len+=llen; - + encode_uint32(llen, &buf[8]); + r_len += llen; // not supported } break; @@ -1228,16 +1192,15 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { Dictionary d = p_variant; if (buf) { - encode_uint32(uint32_t(d.size()),buf); - buf+=4; + encode_uint32(uint32_t(d.size()), buf); + buf += 4; } - r_len+=4; + r_len += 4; List<Variant> keys; d.get_key_list(&keys); - - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* CharString utf8 = E->->utf8(); @@ -1253,14 +1216,14 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { r_len++; //pad */ int len; - encode_variant(E->get(),buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(E->get(), buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) buf += len; - encode_variant(d[E->get()],buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(d[E->get()], buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) buf += len; } @@ -1271,107 +1234,101 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { Array v = p_variant; if (buf) { - encode_uint32(uint32_t(v.size()),buf); - buf+=4; + encode_uint32(uint32_t(v.size()), buf); + buf += 4; } - r_len+=4; + r_len += 4; - for(int i=0;i<v.size();i++) { + for (int i = 0; i < v.size(); i++) { int len; - encode_variant(v.get(i),buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(v.get(i), buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) - buf+=len; + buf += len; } - } break; // arrays case Variant::POOL_BYTE_ARRAY: { PoolVector<uint8_t> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(uint8_t); + int datalen = data.size(); + int datasize = sizeof(uint8_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; PoolVector<uint8_t>::Read r = data.read(); - copymem(buf,&r[0],datalen*datasize); - + copymem(buf, &r[0], datalen * datasize); } - r_len+=4+datalen*datasize; - while(r_len%4) + r_len += 4 + datalen * datasize; + while (r_len % 4) r_len++; } break; case Variant::POOL_INT_ARRAY: { PoolVector<int> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(int32_t); + int datalen = data.size(); + int datasize = sizeof(int32_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; PoolVector<int>::Read r = data.read(); - for(int i=0;i<datalen;i++) - encode_uint32(r[i],&buf[i*datasize]); - + for (int i = 0; i < datalen; i++) + encode_uint32(r[i], &buf[i * datasize]); } - r_len+=4+datalen*datasize; + r_len += 4 + datalen * datasize; } break; case Variant::POOL_REAL_ARRAY: { PoolVector<real_t> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(real_t); + int datalen = data.size(); + int datasize = sizeof(real_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; PoolVector<real_t>::Read r = data.read(); - for(int i=0;i<datalen;i++) - encode_float(r[i],&buf[i*datasize]); - + for (int i = 0; i < datalen; i++) + encode_float(r[i], &buf[i * datasize]); } - r_len+=4+datalen*datasize; + r_len += 4 + datalen * datasize; } break; case Variant::POOL_STRING_ARRAY: { - PoolVector<String> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; - - for(int i=0;i<len;i++) { + r_len += 4; + for (int i = 0; i < len; i++) { CharString utf8 = data.get(i).utf8(); if (buf) { - encode_uint32(utf8.length()+1,buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()+1); - buf+=utf8.length()+1; + encode_uint32(utf8.length() + 1, buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length() + 1); + buf += utf8.length() + 1; } - r_len+=4+utf8.length()+1; - while (r_len%4) { + r_len += 4 + utf8.length() + 1; + while (r_len % 4) { r_len++; //pad if (buf) buf++; @@ -1382,95 +1339,89 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::POOL_VECTOR2_ARRAY: { PoolVector<Vector2> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Vector2 v = data.get(i); - encode_float(v.x,&buf[0]); - encode_float(v.y,&buf[4]); - buf+=4*2; - + encode_float(v.x, &buf[0]); + encode_float(v.y, &buf[4]); + buf += 4 * 2; } } - r_len+=4*2*len; + r_len += 4 * 2 * len; } break; case Variant::POOL_VECTOR3_ARRAY: { PoolVector<Vector3> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Vector3 v = data.get(i); - encode_float(v.x,&buf[0]); - encode_float(v.y,&buf[4]); - encode_float(v.z,&buf[8]); - buf+=4*3; - + encode_float(v.x, &buf[0]); + encode_float(v.y, &buf[4]); + encode_float(v.z, &buf[8]); + buf += 4 * 3; } } - r_len+=4*3*len; + r_len += 4 * 3 * len; } break; case Variant::POOL_COLOR_ARRAY: { PoolVector<Color> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Color c = data.get(i); - - encode_float(c.r,&buf[0]); - encode_float(c.g,&buf[4]); - encode_float(c.b,&buf[8]); - encode_float(c.a,&buf[12]); - buf+=4*4; + encode_float(c.r, &buf[0]); + encode_float(c.g, &buf[4]); + encode_float(c.b, &buf[8]); + encode_float(c.a, &buf[12]); + buf += 4 * 4; } } - r_len+=4*4*len; + r_len += 4 * 4 * len; } break; default: { ERR_FAIL_V(ERR_BUG); } } return OK; - } - - diff --git a/core/io/marshalls.h b/core/io/marshalls.h index f04ec9a256..939ed9cea9 100644 --- a/core/io/marshalls.h +++ b/core/io/marshalls.h @@ -38,7 +38,6 @@ * in an endian independent way */ - union MarshallFloat { uint32_t i; ///< int @@ -53,41 +52,44 @@ union MarshallDouble { static inline unsigned int encode_uint16(uint16_t p_uint, uint8_t *p_arr) { - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } - return sizeof( uint16_t ); + return sizeof(uint16_t); } static inline unsigned int encode_uint32(uint32_t p_uint, uint8_t *p_arr) { - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } - return sizeof( uint32_t ); + return sizeof(uint32_t); } static inline unsigned int encode_float(float p_float, uint8_t *p_arr) { MarshallFloat mf; - mf.f=p_float; - encode_uint32( mf.i, p_arr ); + mf.f = p_float; + encode_uint32(mf.i, p_arr); - return sizeof( uint32_t ); + return sizeof(uint32_t); } static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) { - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } return sizeof(uint64_t); @@ -96,23 +98,21 @@ static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) { static inline unsigned int encode_double(double p_double, uint8_t *p_arr) { MarshallDouble md; - md.d=p_double; - encode_uint64( md.l, p_arr ); + md.d = p_double; + encode_uint64(md.l, p_arr); return sizeof(uint64_t); - } +static inline int encode_cstring(const char *p_string, uint8_t *p_data) { -static inline int encode_cstring(const char *p_string, uint8_t * p_data) { - - int len=0; + int len = 0; while (*p_string) { if (p_data) { - *p_data=(uint8_t)*p_string; + *p_data = (uint8_t)*p_string; p_data++; } p_string++; @@ -120,18 +120,18 @@ static inline int encode_cstring(const char *p_string, uint8_t * p_data) { }; if (p_data) *p_data = 0; - return len+1; + return len + 1; } static inline uint16_t decode_uint16(const uint8_t *p_arr) { - uint16_t u=0; + uint16_t u = 0; - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { uint16_t b = *p_arr; - b<<=(i*8); - u|=b; + b <<= (i * 8); + u |= b; p_arr++; } @@ -140,13 +140,13 @@ static inline uint16_t decode_uint16(const uint8_t *p_arr) { static inline uint32_t decode_uint32(const uint8_t *p_arr) { - uint32_t u=0; + uint32_t u = 0; - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { uint32_t b = *p_arr; - b<<=(i*8); - u|=b; + b <<= (i * 8); + u |= b; p_arr++; } @@ -162,13 +162,13 @@ static inline float decode_float(const uint8_t *p_arr) { static inline uint64_t decode_uint64(const uint8_t *p_arr) { - uint64_t u=0; + uint64_t u = 0; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - uint64_t b = (*p_arr)&0xFF; - b<<=(i*8); - u|=b; + uint64_t b = (*p_arr) & 0xFF; + b <<= (i * 8); + u |= b; p_arr++; } @@ -178,13 +178,11 @@ static inline uint64_t decode_uint64(const uint8_t *p_arr) { static inline double decode_double(const uint8_t *p_arr) { MarshallDouble md; - md.l = decode_uint64( p_arr ); + md.l = decode_uint64(p_arr); return md.d; - } - -Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len=NULL); -Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len); +Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len = NULL); +Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len); #endif diff --git a/core/io/networked_multiplayer_peer.cpp b/core/io/networked_multiplayer_peer.cpp index fb81a806e2..da661d0981 100644 --- a/core/io/networked_multiplayer_peer.cpp +++ b/core/io/networked_multiplayer_peer.cpp @@ -28,42 +28,38 @@ /*************************************************************************/ #include "networked_multiplayer_peer.h" - void NetworkedMultiplayerPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_transfer_mode","mode"), &NetworkedMultiplayerPeer::set_transfer_mode ); - ClassDB::bind_method(D_METHOD("set_target_peer","id"), &NetworkedMultiplayerPeer::set_target_peer ); - - ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer ); + ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &NetworkedMultiplayerPeer::set_transfer_mode); + ClassDB::bind_method(D_METHOD("set_target_peer", "id"), &NetworkedMultiplayerPeer::set_target_peer); - ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll ); + ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer); - ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status ); - ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id ); + ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll); - ClassDB::bind_method(D_METHOD("set_refuse_new_connections","enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections ); - ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections ); + ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status); + ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id); - BIND_CONSTANT( TRANSFER_MODE_UNRELIABLE ); - BIND_CONSTANT( TRANSFER_MODE_UNRELIABLE_ORDERED ); - BIND_CONSTANT( TRANSFER_MODE_RELIABLE ); + ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections); + ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections); - BIND_CONSTANT( CONNECTION_DISCONNECTED ); - BIND_CONSTANT( CONNECTION_CONNECTING ); - BIND_CONSTANT( CONNECTION_CONNECTED ); + BIND_CONSTANT(TRANSFER_MODE_UNRELIABLE); + BIND_CONSTANT(TRANSFER_MODE_UNRELIABLE_ORDERED); + BIND_CONSTANT(TRANSFER_MODE_RELIABLE); - BIND_CONSTANT( TARGET_PEER_BROADCAST ); - BIND_CONSTANT( TARGET_PEER_SERVER ); + BIND_CONSTANT(CONNECTION_DISCONNECTED); + BIND_CONSTANT(CONNECTION_CONNECTING); + BIND_CONSTANT(CONNECTION_CONNECTED); + BIND_CONSTANT(TARGET_PEER_BROADCAST); + BIND_CONSTANT(TARGET_PEER_SERVER); - ADD_SIGNAL( MethodInfo("peer_connected",PropertyInfo(Variant::INT,"id"))); - ADD_SIGNAL( MethodInfo("peer_disconnected",PropertyInfo(Variant::INT,"id"))); - ADD_SIGNAL( MethodInfo("server_disconnected")); - ADD_SIGNAL( MethodInfo("connection_succeeded") ); - ADD_SIGNAL( MethodInfo("connection_failed") ); + ADD_SIGNAL(MethodInfo("peer_connected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("peer_disconnected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("server_disconnected")); + ADD_SIGNAL(MethodInfo("connection_succeeded")); + ADD_SIGNAL(MethodInfo("connection_failed")); } NetworkedMultiplayerPeer::NetworkedMultiplayerPeer() { - - } diff --git a/core/io/networked_multiplayer_peer.h b/core/io/networked_multiplayer_peer.h index 5d859a2f25..1324a61c72 100644 --- a/core/io/networked_multiplayer_peer.h +++ b/core/io/networked_multiplayer_peer.h @@ -33,15 +33,15 @@ class NetworkedMultiplayerPeer : public PacketPeer { - GDCLASS(NetworkedMultiplayerPeer,PacketPeer); + GDCLASS(NetworkedMultiplayerPeer, PacketPeer); protected: static void _bind_methods(); -public: +public: enum { - TARGET_PEER_BROADCAST=0, - TARGET_PEER_SERVER=1 + TARGET_PEER_BROADCAST = 0, + TARGET_PEER_SERVER = 1 }; enum TransferMode { TRANSFER_MODE_UNRELIABLE, @@ -55,28 +55,26 @@ public: CONNECTION_CONNECTED, }; + virtual void set_transfer_mode(TransferMode p_mode) = 0; + virtual void set_target_peer(int p_peer_id) = 0; - virtual void set_transfer_mode(TransferMode p_mode)=0; - virtual void set_target_peer(int p_peer_id)=0; - - virtual int get_packet_peer() const=0; - - virtual bool is_server() const=0; + virtual int get_packet_peer() const = 0; - virtual void poll()=0; + virtual bool is_server() const = 0; - virtual int get_unique_id() const=0; + virtual void poll() = 0; - virtual void set_refuse_new_connections(bool p_enable)=0; - virtual bool is_refusing_new_connections() const=0; + virtual int get_unique_id() const = 0; + virtual void set_refuse_new_connections(bool p_enable) = 0; + virtual bool is_refusing_new_connections() const = 0; - virtual ConnectionStatus get_connection_status() const=0; + virtual ConnectionStatus get_connection_status() const = 0; NetworkedMultiplayerPeer(); }; -VARIANT_ENUM_CAST( NetworkedMultiplayerPeer::TransferMode ) -VARIANT_ENUM_CAST( NetworkedMultiplayerPeer::ConnectionStatus ) +VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::TransferMode) +VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::ConnectionStatus) #endif // NetworkedMultiplayerPeer_H diff --git a/core/io/packet_peer.cpp b/core/io/packet_peer.cpp index cf5883121f..8115673d46 100644 --- a/core/io/packet_peer.cpp +++ b/core/io/packet_peer.cpp @@ -28,77 +28,71 @@ /*************************************************************************/ #include "packet_peer.h" -#include "io/marshalls.h" #include "global_config.h" +#include "io/marshalls.h" /* helpers / binders */ - - PacketPeer::PacketPeer() { - last_get_error=OK; + last_get_error = OK; } Error PacketPeer::get_packet_buffer(PoolVector<uint8_t> &r_buffer) const { const uint8_t *buffer; int buffer_size; - Error err = get_packet(&buffer,buffer_size); + Error err = get_packet(&buffer, buffer_size); if (err) return err; r_buffer.resize(buffer_size); - if (buffer_size==0) + if (buffer_size == 0) return OK; PoolVector<uint8_t>::Write w = r_buffer.write(); - for(int i=0;i<buffer_size;i++) - w[i]=buffer[i]; + for (int i = 0; i < buffer_size; i++) + w[i] = buffer[i]; return OK; - } Error PacketPeer::put_packet_buffer(const PoolVector<uint8_t> &p_buffer) { int len = p_buffer.size(); - if (len==0) + if (len == 0) return OK; PoolVector<uint8_t>::Read r = p_buffer.read(); - return put_packet(&r[0],len); - + return put_packet(&r[0], len); } Error PacketPeer::get_var(Variant &r_variant) const { const uint8_t *buffer; int buffer_size; - Error err = get_packet(&buffer,buffer_size); + Error err = get_packet(&buffer, buffer_size); if (err) return err; - return decode_variant(r_variant,buffer,buffer_size); - + return decode_variant(r_variant, buffer, buffer_size); } -Error PacketPeer::put_var(const Variant& p_packet) { +Error PacketPeer::put_var(const Variant &p_packet) { int len; - Error err = encode_variant(p_packet,NULL,len); // compute len first + Error err = encode_variant(p_packet, NULL, len); // compute len first if (err) return err; - if (len==0) + if (len == 0) return OK; - uint8_t *buf = (uint8_t*)alloca(len); - ERR_FAIL_COND_V(!buf,ERR_OUT_OF_MEMORY); - err = encode_variant(p_packet,buf,len); + uint8_t *buf = (uint8_t *)alloca(len); + ERR_FAIL_COND_V(!buf, ERR_OUT_OF_MEMORY); + err = encode_variant(p_packet, buf, len); ERR_FAIL_COND_V(err, err); return put_packet(buf, len); - } Variant PacketPeer::_bnd_get_var() const { @@ -108,13 +102,13 @@ Variant PacketPeer::_bnd_get_var() const { return var; }; -Error PacketPeer::_put_packet(const PoolVector<uint8_t> &p_buffer) { +Error PacketPeer::_put_packet(const PoolVector<uint8_t> &p_buffer) { return put_packet_buffer(p_buffer); } PoolVector<uint8_t> PacketPeer::_get_packet() const { PoolVector<uint8_t> raw; - last_get_error=get_packet_buffer(raw); + last_get_error = get_packet_buffer(raw); return raw; } @@ -123,20 +117,18 @@ Error PacketPeer::_get_packet_error() const { return last_get_error; } - void PacketPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_var:Variant"),&PacketPeer::_bnd_get_var); - ClassDB::bind_method(D_METHOD("put_var", "var:Variant"),&PacketPeer::put_var); - ClassDB::bind_method(D_METHOD("get_packet"),&PacketPeer::_get_packet); - ClassDB::bind_method(D_METHOD("put_packet:Error", "buffer"),&PacketPeer::_put_packet); - ClassDB::bind_method(D_METHOD("get_packet_error:Error"),&PacketPeer::_get_packet_error); - ClassDB::bind_method(D_METHOD("get_available_packet_count"),&PacketPeer::get_available_packet_count); + ClassDB::bind_method(D_METHOD("get_var:Variant"), &PacketPeer::_bnd_get_var); + ClassDB::bind_method(D_METHOD("put_var", "var:Variant"), &PacketPeer::put_var); + ClassDB::bind_method(D_METHOD("get_packet"), &PacketPeer::_get_packet); + ClassDB::bind_method(D_METHOD("put_packet:Error", "buffer"), &PacketPeer::_put_packet); + ClassDB::bind_method(D_METHOD("get_packet_error:Error"), &PacketPeer::_get_packet_error); + ClassDB::bind_method(D_METHOD("get_available_packet_count"), &PacketPeer::get_available_packet_count); }; /***************/ - void PacketPeerStream::_set_stream_peer(REF p_peer) { ERR_FAIL_COND(p_peer.is_null()); @@ -145,22 +137,22 @@ void PacketPeerStream::_set_stream_peer(REF p_peer) { void PacketPeerStream::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_stream_peer","peer:StreamPeer"),&PacketPeerStream::_set_stream_peer); + ClassDB::bind_method(D_METHOD("set_stream_peer", "peer:StreamPeer"), &PacketPeerStream::_set_stream_peer); } Error PacketPeerStream::_poll_buffer() const { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); int read = 0; Error err = peer->get_partial_data(&temp_buffer[0], ring_buffer.space_left(), read); if (err) return err; - if (read==0) + if (read == 0) return OK; - int w = ring_buffer.write(&temp_buffer[0],read); - ERR_FAIL_COND_V(w!=read,ERR_BUG); + int w = ring_buffer.write(&temp_buffer[0], read); + ERR_FAIL_COND_V(w != read, ERR_BUG); return OK; } @@ -171,73 +163,71 @@ int PacketPeerStream::get_available_packet_count() const { uint32_t remaining = ring_buffer.data_left(); - int ofs=0; - int count=0; + int ofs = 0; + int count = 0; - while(remaining>=4) { + while (remaining >= 4) { uint8_t lbuf[4]; - ring_buffer.copy(lbuf,ofs,4); + ring_buffer.copy(lbuf, ofs, 4); uint32_t len = decode_uint32(lbuf); - remaining-=4; - ofs+=4; - if (len>remaining) + remaining -= 4; + ofs += 4; + if (len > remaining) break; - remaining-=len; - ofs+=len; + remaining -= len; + ofs += len; count++; } return count; } -Error PacketPeerStream::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const { +Error PacketPeerStream::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); _poll_buffer(); int remaining = ring_buffer.data_left(); - ERR_FAIL_COND_V(remaining<4,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(remaining < 4, ERR_UNAVAILABLE); uint8_t lbuf[4]; - ring_buffer.copy(lbuf,0,4); - remaining-=4; + ring_buffer.copy(lbuf, 0, 4); + remaining -= 4; uint32_t len = decode_uint32(lbuf); - ERR_FAIL_COND_V(remaining<(int)len,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(remaining < (int)len, ERR_UNAVAILABLE); - ring_buffer.read(lbuf,4); //get rid of first 4 bytes - ring_buffer.read(&temp_buffer[0],len); // read packet + ring_buffer.read(lbuf, 4); //get rid of first 4 bytes + ring_buffer.read(&temp_buffer[0], len); // read packet - *r_buffer=&temp_buffer[0]; - r_buffer_size=len; + *r_buffer = &temp_buffer[0]; + r_buffer_size = len; return OK; - } -Error PacketPeerStream::put_packet(const uint8_t *p_buffer,int p_buffer_size) { +Error PacketPeerStream::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); Error err = _poll_buffer(); //won't hurt to poll here too if (err) return err; - if (p_buffer_size==0) + if (p_buffer_size == 0) return OK; - ERR_FAIL_COND_V( p_buffer_size<0, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V( p_buffer_size+4 > temp_buffer.size(), ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_buffer_size < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_buffer_size + 4 > temp_buffer.size(), ERR_INVALID_PARAMETER); - encode_uint32(p_buffer_size,&temp_buffer[0]); - uint8_t *dst=&temp_buffer[4]; - for(int i=0;i<p_buffer_size;i++) - dst[i]=p_buffer[i]; + encode_uint32(p_buffer_size, &temp_buffer[0]); + uint8_t *dst = &temp_buffer[4]; + for (int i = 0; i < p_buffer_size; i++) + dst[i] = p_buffer[i]; - return peer->put_data(&temp_buffer[0],p_buffer_size+4); + return peer->put_data(&temp_buffer[0], p_buffer_size + 4); } int PacketPeerStream::get_max_packet_size() const { - return temp_buffer.size(); } @@ -249,7 +239,7 @@ void PacketPeerStream::set_stream_peer(const Ref<StreamPeer> &p_peer) { ring_buffer.advance_read(ring_buffer.data_left()); // reset the ring buffer }; - peer=p_peer; + peer = p_peer; } void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { @@ -257,19 +247,14 @@ void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { //warning may lose packets ERR_EXPLAIN("Buffer in use, resizing would cause loss of data"); ERR_FAIL_COND(ring_buffer.data_left()); - ring_buffer.resize(nearest_shift(p_max_size+4)); - temp_buffer.resize(nearest_power_of_2(p_max_size+4)); - + ring_buffer.resize(nearest_shift(p_max_size + 4)); + temp_buffer.resize(nearest_power_of_2(p_max_size + 4)); } PacketPeerStream::PacketPeerStream() { - - int rbsize=GLOBAL_GET( "network/packets/packet_stream_peer_max_buffer_po2"); - + int rbsize = GLOBAL_GET("network/packets/packet_stream_peer_max_buffer_po2"); ring_buffer.resize(rbsize); - temp_buffer.resize(1<<rbsize); - - + temp_buffer.resize(1 << rbsize); } diff --git a/core/io/packet_peer.h b/core/io/packet_peer.h index bacd5214f1..5f8d63f8c8 100644 --- a/core/io/packet_peer.h +++ b/core/io/packet_peer.h @@ -29,33 +29,30 @@ #ifndef PACKET_PEER_H #define PACKET_PEER_H -#include "object.h" #include "io/stream_peer.h" +#include "object.h" #include "ring_buffer.h" class PacketPeer : public Reference { - GDCLASS( PacketPeer, Reference ); + GDCLASS(PacketPeer, Reference); Variant _bnd_get_var() const; - void _bnd_put_var(const Variant& p_var); + void _bnd_put_var(const Variant &p_var); static void _bind_methods(); - Error _put_packet(const PoolVector<uint8_t> &p_buffer); PoolVector<uint8_t> _get_packet() const; Error _get_packet_error() const; - mutable Error last_get_error; public: + virtual int get_available_packet_count() const = 0; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const = 0; ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0; - virtual int get_available_packet_count() const=0; - virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const=0; ///< buffer is GONE after next get_packet - virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size)=0; - - virtual int get_max_packet_size() const=0; + virtual int get_max_packet_size() const = 0; /* helpers / binders */ @@ -63,15 +60,15 @@ public: virtual Error put_packet_buffer(const PoolVector<uint8_t> &p_buffer); virtual Error get_var(Variant &r_variant) const; - virtual Error put_var(const Variant& p_packet); + virtual Error put_var(const Variant &p_packet); PacketPeer(); - ~PacketPeer(){} + ~PacketPeer() {} }; class PacketPeerStream : public PacketPeer { - GDCLASS(PacketPeerStream,PacketPeer); + GDCLASS(PacketPeerStream, PacketPeer); //the way the buffers work sucks, will change later @@ -80,25 +77,21 @@ class PacketPeerStream : public PacketPeer { mutable Vector<uint8_t> temp_buffer; Error _poll_buffer() const; -protected: +protected: void _set_stream_peer(REF p_peer); static void _bind_methods(); -public: +public: virtual int get_available_packet_count() const; - virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const; - virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size); + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const; + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); virtual int get_max_packet_size() const; - - - void set_stream_peer(const Ref<StreamPeer>& p_peer); + void set_stream_peer(const Ref<StreamPeer> &p_peer); void set_input_buffer_max_size(int p_max_size); PacketPeerStream(); - }; - #endif // PACKET_STREAM_H diff --git a/core/io/packet_peer_udp.cpp b/core/io/packet_peer_udp.cpp index c4a6fd79a8..46accf420a 100644 --- a/core/io/packet_peer_udp.cpp +++ b/core/io/packet_peer_udp.cpp @@ -29,40 +29,38 @@ #include "packet_peer_udp.h" #include "io/ip.h" -PacketPeerUDP* (*PacketPeerUDP::_create)()=NULL; +PacketPeerUDP *(*PacketPeerUDP::_create)() = NULL; String PacketPeerUDP::_get_packet_ip() const { return get_packet_address(); } -Error PacketPeerUDP::_set_dest_address(const String& p_address, int p_port) { +Error PacketPeerUDP::_set_dest_address(const String &p_address, int p_port) { IP_Address ip; if (p_address.is_valid_ip_address()) { - ip=p_address; + ip = p_address; } else { - ip=IP::get_singleton()->resolve_hostname(p_address); + ip = IP::get_singleton()->resolve_hostname(p_address); if (!ip.is_valid()) return ERR_CANT_RESOLVE; } - set_dest_address(ip,p_port); + set_dest_address(ip, p_port); return OK; } void PacketPeerUDP::_bind_methods() { - ClassDB::bind_method(D_METHOD("listen:Error","port", "bind_address", "recv_buf_size"),&PacketPeerUDP::listen,DEFVAL("*"),DEFVAL(65536)); - ClassDB::bind_method(D_METHOD("close"),&PacketPeerUDP::close); - ClassDB::bind_method(D_METHOD("wait:Error"),&PacketPeerUDP::wait); - ClassDB::bind_method(D_METHOD("is_listening"),&PacketPeerUDP::is_listening); - ClassDB::bind_method(D_METHOD("get_packet_ip"),&PacketPeerUDP::_get_packet_ip); + ClassDB::bind_method(D_METHOD("listen:Error", "port", "bind_address", "recv_buf_size"), &PacketPeerUDP::listen, DEFVAL("*"), DEFVAL(65536)); + ClassDB::bind_method(D_METHOD("close"), &PacketPeerUDP::close); + ClassDB::bind_method(D_METHOD("wait:Error"), &PacketPeerUDP::wait); + ClassDB::bind_method(D_METHOD("is_listening"), &PacketPeerUDP::is_listening); + ClassDB::bind_method(D_METHOD("get_packet_ip"), &PacketPeerUDP::_get_packet_ip); //ClassDB::bind_method(D_METHOD("get_packet_address"),&PacketPeerUDP::_get_packet_address); - ClassDB::bind_method(D_METHOD("get_packet_port"),&PacketPeerUDP::get_packet_port); - ClassDB::bind_method(D_METHOD("set_dest_address","host","port"),&PacketPeerUDP::_set_dest_address); - - + ClassDB::bind_method(D_METHOD("get_packet_port"), &PacketPeerUDP::get_packet_port); + ClassDB::bind_method(D_METHOD("set_dest_address", "host", "port"), &PacketPeerUDP::_set_dest_address); } Ref<PacketPeerUDP> PacketPeerUDP::create_ref() { @@ -72,14 +70,12 @@ Ref<PacketPeerUDP> PacketPeerUDP::create_ref() { return Ref<PacketPeerUDP>(_create()); } -PacketPeerUDP* PacketPeerUDP::create() { +PacketPeerUDP *PacketPeerUDP::create() { if (!_create) return NULL; return _create(); } -PacketPeerUDP::PacketPeerUDP() -{ - +PacketPeerUDP::PacketPeerUDP() { } diff --git a/core/io/packet_peer_udp.h b/core/io/packet_peer_udp.h index 726406887c..c316faad4b 100644 --- a/core/io/packet_peer_udp.h +++ b/core/io/packet_peer_udp.h @@ -29,35 +29,31 @@ #ifndef PACKET_PEER_UDP_H #define PACKET_PEER_UDP_H - #include "io/ip.h" #include "io/packet_peer.h" class PacketPeerUDP : public PacketPeer { - GDCLASS(PacketPeerUDP,PacketPeer); + GDCLASS(PacketPeerUDP, PacketPeer); protected: - - static PacketPeerUDP* (*_create)(); + static PacketPeerUDP *(*_create)(); static void _bind_methods(); String _get_packet_ip() const; - Error _set_dest_address(const String& p_address,int p_port); + Error _set_dest_address(const String &p_address, int p_port); public: - - virtual Error listen(int p_port, IP_Address p_bind_address=IP_Address("*"), int p_recv_buffer_size=65536)=0; - virtual void close()=0; - virtual Error wait()=0; - virtual bool is_listening() const=0; - virtual IP_Address get_packet_address() const=0; - virtual int get_packet_port() const=0; - virtual void set_dest_address(const IP_Address& p_address,int p_port)=0; - + virtual Error listen(int p_port, IP_Address p_bind_address = IP_Address("*"), int p_recv_buffer_size = 65536) = 0; + virtual void close() = 0; + virtual Error wait() = 0; + virtual bool is_listening() const = 0; + virtual IP_Address get_packet_address() const = 0; + virtual int get_packet_port() const = 0; + virtual void set_dest_address(const IP_Address &p_address, int p_port) = 0; static Ref<PacketPeerUDP> create_ref(); - static PacketPeerUDP* create(); + static PacketPeerUDP *create(); PacketPeerUDP(); }; diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp index 2cd46843e8..9dd9b044a2 100644 --- a/core/io/pck_packer.cpp +++ b/core/io/pck_packer.cpp @@ -42,9 +42,9 @@ static uint64_t _align(uint64_t p_n, int p_alignment) { return p_n + (p_alignment - rest); }; -static void _pad(FileAccess* p_file, int p_bytes) { +static void _pad(FileAccess *p_file, int p_bytes) { - for (int i=0; i<p_bytes; i++) { + for (int i = 0; i < p_bytes; i++) { p_file->store_8(0); }; @@ -52,13 +52,12 @@ static void _pad(FileAccess* p_file, int p_bytes) { void PCKPacker::_bind_methods() { - ClassDB::bind_method(D_METHOD("pck_start","pck_name","alignment"),&PCKPacker::pck_start); - ClassDB::bind_method(D_METHOD("add_file","pck_path","source_path"),&PCKPacker::add_file); - ClassDB::bind_method(D_METHOD("flush","verbose"),&PCKPacker::flush); + ClassDB::bind_method(D_METHOD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start); + ClassDB::bind_method(D_METHOD("add_file", "pck_path", "source_path"), &PCKPacker::add_file); + ClassDB::bind_method(D_METHOD("flush", "verbose"), &PCKPacker::flush); }; - -Error PCKPacker::pck_start(const String& p_file, int p_alignment) { +Error PCKPacker::pck_start(const String &p_file, int p_alignment) { file = FileAccess::open(p_file, FileAccess::WRITE); if (file == NULL) { @@ -74,7 +73,7 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) { file->store_32(0); // # minor file->store_32(0); // # revision - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { file->store_32(0); // reserved }; @@ -84,9 +83,9 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) { return OK; }; -Error PCKPacker::add_file(const String& p_file, const String& p_src) { +Error PCKPacker::add_file(const String &p_file, const String &p_src) { - FileAccess* f = FileAccess::open(p_src, FileAccess::READ); + FileAccess *f = FileAccess::open(p_src, FileAccess::READ); if (!f) { return ERR_FILE_CANT_OPEN; }; @@ -116,7 +115,7 @@ Error PCKPacker::flush(bool p_verbose) { file->store_32(files.size()); - for (int i=0; i<files.size(); i++) { + for (int i = 0; i < files.size(); i++) { file->store_pascal_string(files[i].path); files[i].offset_offset = file->get_pos(); @@ -130,7 +129,6 @@ Error PCKPacker::flush(bool p_verbose) { file->store_32(0); }; - uint64_t ofs = file->get_pos(); ofs = _align(ofs, alignment); @@ -140,9 +138,9 @@ Error PCKPacker::flush(bool p_verbose) { uint8_t *buf = memnew_arr(uint8_t, buf_max); int count = 0; - for (int i=0; i<files.size(); i++) { + for (int i = 0; i < files.size(); i++) { - FileAccess* src = FileAccess::open(files[i].src_path, FileAccess::READ); + FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ); uint64_t to_write = files[i].size; while (to_write > 0) { diff --git a/core/io/pck_packer.h b/core/io/pck_packer.h index a4eba04f2d..1edb14ab27 100644 --- a/core/io/pck_packer.h +++ b/core/io/pck_packer.h @@ -34,7 +34,7 @@ class PCKPacker : public Reference { GDCLASS(PCKPacker, Reference); - FileAccess* file; + FileAccess *file; int alignment; static void _bind_methods(); @@ -49,11 +49,10 @@ class PCKPacker : public Reference { Vector<File> files; public: - Error pck_start(const String& p_file, int p_alignment); - Error add_file(const String& p_file, const String& p_src); + Error pck_start(const String &p_file, int p_alignment); + Error add_file(const String &p_file, const String &p_src); Error flush(bool p_verbose = false); - PCKPacker(); ~PCKPacker(); }; diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp index 2d733842fa..60dccebebf 100644 --- a/core/io/resource_format_binary.cpp +++ b/core/io/resource_format_binary.cpp @@ -26,315 +26,303 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "version.h" #include "resource_format_binary.h" #include "global_config.h" #include "io/file_access_compressed.h" #include "io/marshalls.h" #include "os/dir_access.h" +#include "version.h" //#define print_bl(m_what) print_line(m_what) #define print_bl(m_what) - enum { //numbering must be different from variant, in case new variant types are added (variant must be always contiguous for jumptable optimization) - VARIANT_NIL=1, - VARIANT_BOOL=2, - VARIANT_INT=3, - VARIANT_REAL=4, - VARIANT_STRING=5, - VARIANT_VECTOR2=10, - VARIANT_RECT2=11, - VARIANT_VECTOR3=12, - VARIANT_PLANE=13, - VARIANT_QUAT=14, - VARIANT_AABB=15, - VARIANT_MATRIX3=16, - VARIANT_TRANSFORM=17, - VARIANT_MATRIX32=18, - VARIANT_COLOR=20, - VARIANT_IMAGE=21, - VARIANT_NODE_PATH=22, - VARIANT_RID=23, - VARIANT_OBJECT=24, - VARIANT_INPUT_EVENT=25, - VARIANT_DICTIONARY=26, - VARIANT_ARRAY=30, - VARIANT_RAW_ARRAY=31, - VARIANT_INT_ARRAY=32, - VARIANT_REAL_ARRAY=33, - VARIANT_STRING_ARRAY=34, - VARIANT_VECTOR3_ARRAY=35, - VARIANT_COLOR_ARRAY=36, - VARIANT_VECTOR2_ARRAY=37, - VARIANT_INT64=40, - VARIANT_DOUBLE=41, - - IMAGE_ENCODING_EMPTY=0, - IMAGE_ENCODING_RAW=1, - IMAGE_ENCODING_LOSSLESS=2, - IMAGE_ENCODING_LOSSY=3, - - OBJECT_EMPTY=0, - OBJECT_EXTERNAL_RESOURCE=1, - OBJECT_INTERNAL_RESOURCE=2, - OBJECT_EXTERNAL_RESOURCE_INDEX=3, + VARIANT_NIL = 1, + VARIANT_BOOL = 2, + VARIANT_INT = 3, + VARIANT_REAL = 4, + VARIANT_STRING = 5, + VARIANT_VECTOR2 = 10, + VARIANT_RECT2 = 11, + VARIANT_VECTOR3 = 12, + VARIANT_PLANE = 13, + VARIANT_QUAT = 14, + VARIANT_AABB = 15, + VARIANT_MATRIX3 = 16, + VARIANT_TRANSFORM = 17, + VARIANT_MATRIX32 = 18, + VARIANT_COLOR = 20, + VARIANT_IMAGE = 21, + VARIANT_NODE_PATH = 22, + VARIANT_RID = 23, + VARIANT_OBJECT = 24, + VARIANT_INPUT_EVENT = 25, + VARIANT_DICTIONARY = 26, + VARIANT_ARRAY = 30, + VARIANT_RAW_ARRAY = 31, + VARIANT_INT_ARRAY = 32, + VARIANT_REAL_ARRAY = 33, + VARIANT_STRING_ARRAY = 34, + VARIANT_VECTOR3_ARRAY = 35, + VARIANT_COLOR_ARRAY = 36, + VARIANT_VECTOR2_ARRAY = 37, + VARIANT_INT64 = 40, + VARIANT_DOUBLE = 41, + + IMAGE_ENCODING_EMPTY = 0, + IMAGE_ENCODING_RAW = 1, + IMAGE_ENCODING_LOSSLESS = 2, + IMAGE_ENCODING_LOSSY = 3, + + OBJECT_EMPTY = 0, + OBJECT_EXTERNAL_RESOURCE = 1, + OBJECT_INTERNAL_RESOURCE = 2, + OBJECT_EXTERNAL_RESOURCE_INDEX = 3, //version 2: added 64 bits support for float and int - FORMAT_VERSION=2, - FORMAT_VERSION_CAN_RENAME_DEPS=1 - + FORMAT_VERSION = 2, + FORMAT_VERSION_CAN_RENAME_DEPS = 1 }; - void ResourceInteractiveLoaderBinary::_advance_padding(uint32_t p_len) { - uint32_t extra = 4-(p_len%4); - if (extra<4) { - for(uint32_t i=0;i<extra;i++) + uint32_t extra = 4 - (p_len % 4); + if (extra < 4) { + for (uint32_t i = 0; i < extra; i++) f->get_8(); //pad to 32 } - } - StringName ResourceInteractiveLoaderBinary::_get_string() { uint32_t id = f->get_32(); - if (id&0x80000000) { - uint32_t len = id&0x7FFFFFFF; - if (len>str_buf.size()) { + if (id & 0x80000000) { + uint32_t len = id & 0x7FFFFFFF; + if (len > str_buf.size()) { str_buf.resize(len); } - if (len==0) + if (len == 0) return StringName(); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; } return string_map[id]; - } -Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { - +Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) { uint32_t type = f->get_32(); - print_bl("find property of type: "+itos(type)); - + print_bl("find property of type: " + itos(type)); - switch(type) { + switch (type) { case VARIANT_NIL: { - r_v=Variant(); + r_v = Variant(); } break; case VARIANT_BOOL: { - r_v=bool(f->get_32()); + r_v = bool(f->get_32()); } break; case VARIANT_INT: { - r_v=int(f->get_32()); + r_v = int(f->get_32()); } break; case VARIANT_INT64: { - r_v=int64_t(f->get_64()); + r_v = int64_t(f->get_64()); } break; case VARIANT_REAL: { - r_v=f->get_real(); + r_v = f->get_real(); } break; case VARIANT_DOUBLE: { - r_v=f->get_double(); + r_v = f->get_double(); } break; case VARIANT_STRING: { - r_v=get_unicode_string(); + r_v = get_unicode_string(); } break; case VARIANT_VECTOR2: { Vector2 v; - v.x=f->get_real(); - v.y=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + r_v = v; } break; case VARIANT_RECT2: { Rect2 v; - v.pos.x=f->get_real(); - v.pos.y=f->get_real(); - v.size.x=f->get_real(); - v.size.y=f->get_real(); - r_v=v; + v.pos.x = f->get_real(); + v.pos.y = f->get_real(); + v.size.x = f->get_real(); + v.size.y = f->get_real(); + r_v = v; } break; case VARIANT_VECTOR3: { Vector3 v; - v.x=f->get_real(); - v.y=f->get_real(); - v.z=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + v.z = f->get_real(); + r_v = v; } break; case VARIANT_PLANE: { Plane v; - v.normal.x=f->get_real(); - v.normal.y=f->get_real(); - v.normal.z=f->get_real(); - v.d=f->get_real(); - r_v=v; + v.normal.x = f->get_real(); + v.normal.y = f->get_real(); + v.normal.z = f->get_real(); + v.d = f->get_real(); + r_v = v; } break; case VARIANT_QUAT: { Quat v; - v.x=f->get_real(); - v.y=f->get_real(); - v.z=f->get_real(); - v.w=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + v.z = f->get_real(); + v.w = f->get_real(); + r_v = v; } break; case VARIANT_AABB: { Rect3 v; - v.pos.x=f->get_real(); - v.pos.y=f->get_real(); - v.pos.z=f->get_real(); - v.size.x=f->get_real(); - v.size.y=f->get_real(); - v.size.z=f->get_real(); - r_v=v; + v.pos.x = f->get_real(); + v.pos.y = f->get_real(); + v.pos.z = f->get_real(); + v.size.x = f->get_real(); + v.size.y = f->get_real(); + v.size.z = f->get_real(); + r_v = v; } break; case VARIANT_MATRIX32: { Transform2D v; - v.elements[0].x=f->get_real(); - v.elements[0].y=f->get_real(); - v.elements[1].x=f->get_real(); - v.elements[1].y=f->get_real(); - v.elements[2].x=f->get_real(); - v.elements[2].y=f->get_real(); - r_v=v; + v.elements[0].x = f->get_real(); + v.elements[0].y = f->get_real(); + v.elements[1].x = f->get_real(); + v.elements[1].y = f->get_real(); + v.elements[2].x = f->get_real(); + v.elements[2].y = f->get_real(); + r_v = v; } break; case VARIANT_MATRIX3: { Basis v; - v.elements[0].x=f->get_real(); - v.elements[0].y=f->get_real(); - v.elements[0].z=f->get_real(); - v.elements[1].x=f->get_real(); - v.elements[1].y=f->get_real(); - v.elements[1].z=f->get_real(); - v.elements[2].x=f->get_real(); - v.elements[2].y=f->get_real(); - v.elements[2].z=f->get_real(); - r_v=v; + v.elements[0].x = f->get_real(); + v.elements[0].y = f->get_real(); + v.elements[0].z = f->get_real(); + v.elements[1].x = f->get_real(); + v.elements[1].y = f->get_real(); + v.elements[1].z = f->get_real(); + v.elements[2].x = f->get_real(); + v.elements[2].y = f->get_real(); + v.elements[2].z = f->get_real(); + r_v = v; } break; case VARIANT_TRANSFORM: { Transform v; - v.basis.elements[0].x=f->get_real(); - v.basis.elements[0].y=f->get_real(); - v.basis.elements[0].z=f->get_real(); - v.basis.elements[1].x=f->get_real(); - v.basis.elements[1].y=f->get_real(); - v.basis.elements[1].z=f->get_real(); - v.basis.elements[2].x=f->get_real(); - v.basis.elements[2].y=f->get_real(); - v.basis.elements[2].z=f->get_real(); - v.origin.x=f->get_real(); - v.origin.y=f->get_real(); - v.origin.z=f->get_real(); - r_v=v; + v.basis.elements[0].x = f->get_real(); + v.basis.elements[0].y = f->get_real(); + v.basis.elements[0].z = f->get_real(); + v.basis.elements[1].x = f->get_real(); + v.basis.elements[1].y = f->get_real(); + v.basis.elements[1].z = f->get_real(); + v.basis.elements[2].x = f->get_real(); + v.basis.elements[2].y = f->get_real(); + v.basis.elements[2].z = f->get_real(); + v.origin.x = f->get_real(); + v.origin.y = f->get_real(); + v.origin.z = f->get_real(); + r_v = v; } break; case VARIANT_COLOR: { Color v; - v.r=f->get_real(); - v.g=f->get_real(); - v.b=f->get_real(); - v.a=f->get_real(); - r_v=v; + v.r = f->get_real(); + v.g = f->get_real(); + v.b = f->get_real(); + v.a = f->get_real(); + r_v = v; } break; case VARIANT_IMAGE: { - uint32_t encoding = f->get_32(); - if (encoding==IMAGE_ENCODING_EMPTY) { - r_v=Variant(); + if (encoding == IMAGE_ENCODING_EMPTY) { + r_v = Variant(); break; - } else if (encoding==IMAGE_ENCODING_RAW) { + } else if (encoding == IMAGE_ENCODING_RAW) { uint32_t width = f->get_32(); uint32_t height = f->get_32(); uint32_t mipmaps = f->get_32(); uint32_t format = f->get_32(); - const uint32_t format_version_shift=24; - const uint32_t format_version_mask=format_version_shift-1; + const uint32_t format_version_shift = 24; + const uint32_t format_version_mask = format_version_shift - 1; - uint32_t format_version = format>>format_version_shift; + uint32_t format_version = format >> format_version_shift; const uint32_t current_version = 0; - if (format_version>current_version) { + if (format_version > current_version) { ERR_PRINT("Format version for encoded binary image is too new"); return ERR_PARSE_ERROR; } - - Image::Format fmt=Image::Format(format&format_version_mask); //if format changes, we can add a compatibility bit on top + Image::Format fmt = Image::Format(format & format_version_mask); //if format changes, we can add a compatibility bit on top uint32_t datalen = f->get_32(); - print_line("image format: "+String(Image::get_format_name(fmt))+" datalen "+itos(datalen)); + print_line("image format: " + String(Image::get_format_name(fmt)) + " datalen " + itos(datalen)); PoolVector<uint8_t> imgdata; imgdata.resize(datalen); PoolVector<uint8_t>::Write w = imgdata.write(); - f->get_buffer(w.ptr(),datalen); + f->get_buffer(w.ptr(), datalen); _advance_padding(datalen); - w=PoolVector<uint8_t>::Write(); + w = PoolVector<uint8_t>::Write(); #ifdef TOOLS_ENABLED -//compatibility - int correct_size = Image::get_image_data_size(width,height,fmt,mipmaps?-1:0); + //compatibility + int correct_size = Image::get_image_data_size(width, height, fmt, mipmaps ? -1 : 0); if (correct_size < datalen) { WARN_PRINT("Image data was too large, shrinking for compatibility") imgdata.resize(correct_size); } #endif - r_v=Image(width,height,mipmaps,fmt,imgdata); + r_v = Image(width, height, mipmaps, fmt, imgdata); } else { //compressed PoolVector<uint8_t> data; data.resize(f->get_32()); PoolVector<uint8_t>::Write w = data.write(); - f->get_buffer(w.ptr(),data.size()); + f->get_buffer(w.ptr(), data.size()); w = PoolVector<uint8_t>::Write(); Image img; - if (encoding==IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { + if (encoding == IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { img = Image::lossy_unpacker(data); - } else if (encoding==IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { + } else if (encoding == IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { img = Image::lossless_unpacker(data); } _advance_padding(data.size()); - - r_v=img; - + r_v = img; } } break; @@ -347,44 +335,43 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { int name_count = f->get_16(); uint32_t subname_count = f->get_16(); - absolute=subname_count&0x8000; - subname_count&=0x7FFF; - + absolute = subname_count & 0x8000; + subname_count &= 0x7FFF; - for(int i=0;i<name_count;i++) + for (int i = 0; i < name_count; i++) names.push_back(_get_string()); - for(uint32_t i=0;i<subname_count;i++) + for (uint32_t i = 0; i < subname_count; i++) subnames.push_back(_get_string()); - property=_get_string(); + property = _get_string(); - NodePath np = NodePath(names,subnames,absolute,property); + NodePath np = NodePath(names, subnames, absolute, property); //print_line("got path: "+String(np)); - r_v=np; + r_v = np; } break; case VARIANT_RID: { - r_v=f->get_32(); + r_v = f->get_32(); } break; case VARIANT_OBJECT: { - uint32_t type=f->get_32(); + uint32_t type = f->get_32(); - switch(type) { + switch (type) { case OBJECT_EMPTY: { //do none } break; case OBJECT_INTERNAL_RESOURCE: { - uint32_t index=f->get_32(); - String path = res_path+"::"+itos(index); + uint32_t index = f->get_32(); + String path = res_path + "::" + itos(index); RES res = ResourceLoader::load(path); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } break; case OBJECT_EXTERNAL_RESOURCE: { @@ -393,51 +380,48 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { String type = get_unicode_string(); String path = get_unicode_string(); - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } if (remaps.find(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } break; case OBJECT_EXTERNAL_RESOURCE_INDEX: { //new file format, just refers to an index in the external list uint32_t erindex = f->get_32(); - if (erindex>=external_resources.size()) { + if (erindex >= external_resources.size()) { WARN_PRINT("Broken external resource! (index out of size"); - r_v=Variant(); + r_v = Variant(); } else { String type = external_resources[erindex].type; String path = external_resources[erindex].path; - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } - } break; default: { @@ -449,39 +433,39 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { case VARIANT_INPUT_EVENT: { InputEvent ev; - ev.type=f->get_32(); //will only work for null though. - r_v=ev; + ev.type = f->get_32(); //will only work for null though. + r_v = ev; } break; case VARIANT_DICTIONARY: { - uint32_t len=f->get_32(); + uint32_t len = f->get_32(); Dictionary d; //last bit means shared - len&=0x7FFFFFFF; - for(uint32_t i=0;i<len;i++) { + len &= 0x7FFFFFFF; + for (uint32_t i = 0; i < len; i++) { Variant key; Error err = parse_variant(key); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); Variant value; err = parse_variant(value); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - d[key]=value; + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); + d[key] = value; } - r_v=d; + r_v = d; } break; case VARIANT_ARRAY: { - uint32_t len=f->get_32(); + uint32_t len = f->get_32(); Array a; //last bit means shared - len&=0x7FFFFFFF; + len &= 0x7FFFFFFF; a.resize(len); - for(uint32_t i=0;i<len;i++) { + for (uint32_t i = 0; i < len; i++) { Variant val; Error err = parse_variant(val); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - a[i]=val; + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); + a[i] = val; } - r_v=a; + r_v = a; } break; case VARIANT_RAW_ARRAY: { @@ -491,10 +475,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<uint8_t> array; array.resize(len); PoolVector<uint8_t>::Write w = array.write(); - f->get_buffer(w.ptr(),len); + f->get_buffer(w.ptr(), len); _advance_padding(len); - w=PoolVector<uint8_t>::Write(); - r_v=array; + w = PoolVector<uint8_t>::Write(); + r_v = array; } break; case VARIANT_INT_ARRAY: { @@ -504,19 +488,19 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<int> array; array.resize(len); PoolVector<int>::Write w = array.write(); - f->get_buffer((uint8_t*)w.ptr(),len*4); + f->get_buffer((uint8_t *)w.ptr(), len * 4); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } #endif - w=PoolVector<int>::Write(); - r_v=array; + w = PoolVector<int>::Write(); + r_v = array; } break; case VARIANT_REAL_ARRAY: { @@ -525,20 +509,20 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<real_t> array; array.resize(len); PoolVector<real_t>::Write w = array.write(); - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)); + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t)); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } #endif - w=PoolVector<real_t>::Write(); - r_v=array; + w = PoolVector<real_t>::Write(); + r_v = array; } break; case VARIANT_STRING_ARRAY: { @@ -546,11 +530,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<String> array; array.resize(len); PoolVector<String>::Write w = array.write(); - for(uint32_t i=0;i<len;i++) - w[i]=get_unicode_string(); - w=PoolVector<String>::Write(); - r_v=array; - + for (uint32_t i = 0; i < len; i++) + w[i] = get_unicode_string(); + w = PoolVector<String>::Write(); + r_v = array; } break; case VARIANT_VECTOR2_ARRAY: { @@ -560,16 +543,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<Vector2> array; array.resize(len); PoolVector<Vector2>::Write w = array.write(); - if (sizeof(Vector2)==8) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*2); + if (sizeof(Vector2) == 8) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 2); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*2;i++) { + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 2; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); + } } - } #endif @@ -577,8 +560,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { ERR_EXPLAIN("Vector2 size is NOT 8!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=PoolVector<Vector2>::Write(); - r_v=array; + w = PoolVector<Vector2>::Write(); + r_v = array; } break; case VARIANT_VECTOR3_ARRAY: { @@ -588,14 +571,14 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<Vector3> array; array.resize(len); PoolVector<Vector3>::Write w = array.write(); - if (sizeof(Vector3)==12) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*3); + if (sizeof(Vector3) == 12) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 3); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*3;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 3; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } @@ -605,8 +588,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { ERR_EXPLAIN("Vector3 size is NOT 12!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=PoolVector<Vector3>::Write(); - r_v=array; + w = PoolVector<Vector3>::Write(); + r_v = array; } break; case VARIANT_COLOR_ARRAY: { @@ -616,16 +599,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<Color> array; array.resize(len); PoolVector<Color>::Write w = array.write(); - if (sizeof(Color)==16) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*4); + if (sizeof(Color) == 16) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 4); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*4;i++) { + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 4; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); + } } - } #endif @@ -633,8 +616,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { ERR_EXPLAIN("Color size is NOT 16!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=PoolVector<Color>::Write(); - r_v=array; + w = PoolVector<Color>::Write(); + r_v = array; } break; default: { @@ -642,49 +625,43 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { } break; } - - return OK; //never reach anyway - } +void ResourceInteractiveLoaderBinary::set_local_path(const String &p_local_path) { -void ResourceInteractiveLoaderBinary::set_local_path(const String& p_local_path) { - - res_path=p_local_path; + res_path = p_local_path; } -Ref<Resource> ResourceInteractiveLoaderBinary::get_resource(){ - +Ref<Resource> ResourceInteractiveLoaderBinary::get_resource() { return resource; } -Error ResourceInteractiveLoaderBinary::poll(){ +Error ResourceInteractiveLoaderBinary::poll() { - if (error!=OK) + if (error != OK) return error; - int s = stage; - if (s<external_resources.size()) { + if (s < external_resources.size()) { String path = external_resources[s].path; - print_line("load external res: "+path); + print_line("load external res: " + path); if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res = ResourceLoader::load(path,external_resources[s].type); + RES res = ResourceLoader::load(path, external_resources[s].type); if (res.is_null()) { if (!ResourceLoader::get_abort_on_missing_resources()) { - ResourceLoader::notify_dependency_error(local_path,path,external_resources[s].type); + ResourceLoader::notify_dependency_error(local_path, path, external_resources[s].type); } else { - error=ERR_FILE_MISSING_DEPENDENCIES; - ERR_EXPLAIN("Can't load dependency: "+path); + error = ERR_FILE_MISSING_DEPENDENCIES; + ERR_EXPLAIN("Can't load dependency: " + path); ERR_FAIL_V(error); } @@ -696,44 +673,39 @@ Error ResourceInteractiveLoaderBinary::poll(){ return error; } - s-=external_resources.size(); - + s -= external_resources.size(); - if (s>=internal_resources.size()) { + if (s >= internal_resources.size()) { - error=ERR_BUG; - ERR_FAIL_COND_V(s>=internal_resources.size(),error); + error = ERR_BUG; + ERR_FAIL_COND_V(s >= internal_resources.size(), error); } - bool main = s==(internal_resources.size()-1); + bool main = s == (internal_resources.size() - 1); //maybe it is loaded already String path; - int subindex=0; - - + int subindex = 0; if (!main) { - path=internal_resources[s].path; + path = internal_resources[s].path; if (path.begins_with("local://")) { - path=path.replace_first("local://",""); + path = path.replace_first("local://", ""); subindex = path.to_int(); - path=res_path+"::"+path; + path = res_path + "::" + path; } - - if (ResourceCache::has(path)) { //already loaded, don't do anything stage++; - error=OK; + error = OK; return error; } } else { if (!ResourceCache::has(res_path)) - path=res_path; + path = res_path; } uint64_t offset = internal_resources[s].offset; @@ -742,24 +714,24 @@ Error ResourceInteractiveLoaderBinary::poll(){ String t = get_unicode_string(); -// print_line("loading resource of type "+t+" path is "+path); + // print_line("loading resource of type "+t+" path is "+path); Object *obj = ClassDB::instance(t); if (!obj) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":Resource of unrecognized type in file: "+t); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":Resource of unrecognized type in file: " + t); } - ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!obj, ERR_FILE_CORRUPT); Resource *r = obj->cast_to<Resource>(); if (!r) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; memdelete(obj); //bye - ERR_EXPLAIN(local_path+":Resoucre type in resource field not a resource, type is: "+obj->get_class()); - ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":Resoucre type in resource field not a resource, type is: " + obj->get_class()); + ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT); } - RES res = RES( r ); + RES res = RES(r); r->set_path(path); r->set_subindex(subindex); @@ -768,11 +740,11 @@ Error ResourceInteractiveLoaderBinary::poll(){ //set properties - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { StringName name = _get_string(); - if (name==StringName()) { - error=ERR_FILE_CORRUPT; + if (name == StringName()) { + error = ERR_FILE_CORRUPT; ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -782,7 +754,7 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (error) return error; - res->set(name,value); + res->set(name, value); } #ifdef TOOLS_ENABLED res->set_edited(false); @@ -794,41 +766,37 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (main) { f->close(); - resource=res; - error=ERR_FILE_EOF; + resource = res; + error = ERR_FILE_EOF; } else { - error=OK; + error = OK; } return OK; - } -int ResourceInteractiveLoaderBinary::get_stage() const{ +int ResourceInteractiveLoaderBinary::get_stage() const { return stage; } int ResourceInteractiveLoaderBinary::get_stage_count() const { - return external_resources.size()+internal_resources.size(); + return external_resources.size() + internal_resources.size(); } - -static void save_ustring(FileAccess* f,const String& p_string) { - +static void save_ustring(FileAccess *f, const String &p_string) { CharString utf8 = p_string.utf8(); - f->store_32(utf8.length()+1); - f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1); + f->store_32(utf8.length() + 1); + f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } - static String get_ustring(FileAccess *f) { int len = f->get_32(); Vector<char> str_buf; str_buf.resize(len); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; @@ -837,60 +805,53 @@ static String get_ustring(FileAccess *f) { String ResourceInteractiveLoaderBinary::get_unicode_string() { int len = f->get_32(); - if (len>str_buf.size()) { + if (len > str_buf.size()) { str_buf.resize(len); } - if (len==0) + if (len == 0) return String(); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; } - - -void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f,List<String> *p_dependencies,bool p_add_types) { +void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) { open(p_f); if (error) return; - for(int i=0;i<external_resources.size();i++) { + for (int i = 0; i < external_resources.size(); i++) { - String dep=external_resources[i].path; + String dep = external_resources[i].path; - if (p_add_types && external_resources[i].type!=String()) { - dep+="::"+external_resources[i].type; + if (p_add_types && external_resources[i].type != String()) { + dep += "::" + external_resources[i].type; } p_dependencies->push_back(dep); } - } - - - void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { + error = OK; - error=OK; - - f=p_f; + f = p_f; uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal - error=ERR_FILE_UNRECOGNIZED; - ERR_EXPLAIN("Unrecognized binary resource file: "+local_path); + error = ERR_FILE_UNRECOGNIZED; + ERR_EXPLAIN("Unrecognized binary resource file: " + local_path); ERR_FAIL(); } @@ -903,53 +864,51 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - print_bl("big endian: "+itos(big_endian)); - print_bl("endian swap: "+itos(endian_swap)); - print_bl("real64: "+itos(use_real64)); - print_bl("major: "+itos(ver_major)); - print_bl("minor: "+itos(ver_minor)); - print_bl("format: "+itos(ver_format)); + print_bl("big endian: " + itos(big_endian)); + print_bl("endian swap: " + itos(endian_swap)); + print_bl("real64: " + itos(use_real64)); + print_bl("major: " + itos(ver_major)); + print_bl("minor: " + itos(ver_minor)); + print_bl("format: " + itos(ver_format)); - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { f->close(); - ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path); + ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL(); - } - type=get_unicode_string(); + type = get_unicode_string(); - print_bl("type: "+type); + print_bl("type: " + type); importmd_ofs = f->get_64(); - for(int i=0;i<14;i++) + for (int i = 0; i < 14; i++) f->get_32(); //skip a few reserved fields - uint32_t string_table_size=f->get_32(); + uint32_t string_table_size = f->get_32(); string_map.resize(string_table_size); - for(uint32_t i=0;i<string_table_size;i++) { + for (uint32_t i = 0; i < string_table_size; i++) { StringName s = get_unicode_string(); - string_map[i]=s; + string_map[i] = s; } - print_bl("strings: "+itos(string_table_size)); + print_bl("strings: " + itos(string_table_size)); - uint32_t ext_resources_size=f->get_32(); - for(uint32_t i=0;i<ext_resources_size;i++) { + uint32_t ext_resources_size = f->get_32(); + for (uint32_t i = 0; i < ext_resources_size; i++) { ExtResoucre er; - er.type=get_unicode_string(); - er.path=get_unicode_string(); + er.type = get_unicode_string(); + er.path = get_unicode_string(); external_resources.push_back(er); - } //see if the exporter has different set of external resources for more efficient loading @@ -966,46 +925,43 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { print_line(res_path+" - EXTERNAL RESOURCES: "+itos(external_resources.size())); }*/ - print_bl("ext resources: "+itos(ext_resources_size)); - uint32_t int_resources_size=f->get_32(); + print_bl("ext resources: " + itos(ext_resources_size)); + uint32_t int_resources_size = f->get_32(); - for(uint32_t i=0;i<int_resources_size;i++) { + for (uint32_t i = 0; i < int_resources_size; i++) { IntResoucre ir; - ir.path=get_unicode_string(); - ir.offset=f->get_64(); + ir.path = get_unicode_string(); + ir.offset = f->get_64(); internal_resources.push_back(ir); } - print_bl("int resources: "+itos(int_resources_size)); - + print_bl("int resources: " + itos(int_resources_size)); if (f->eof_reached()) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN("Premature End Of File: "+local_path); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN("Premature End Of File: " + local_path); ERR_FAIL(); } - } String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) { - error=OK; + error = OK; - - f=p_f; + f = p_f; uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal - error=ERR_FILE_UNRECOGNIZED; + error = ERR_FILE_UNRECOGNIZED; return ""; } @@ -1018,30 +974,30 @@ String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) { bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { f->close(); return ""; } - String type=get_unicode_string(); + String type = get_unicode_string(); return type; } ResourceInteractiveLoaderBinary::ResourceInteractiveLoaderBinary() { - f=NULL; - stage=0; - endian_swap=false; - use_real64=false; - error=OK; + f = NULL; + stage = 0; + endian_swap = false; + use_real64 = false; + error = OK; } ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { @@ -1050,126 +1006,117 @@ ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { memdelete(f); } - Ref<ResourceInteractiveLoader> ResourceFormatLoaderBinary::load_interactive(const String &p_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err!=OK) { + if (err != OK) { - ERR_FAIL_COND_V(err!=OK,Ref<ResourceInteractiveLoader>()); + ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>()); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); - return ria; } -void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { +void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List<String> extensions; - ClassDB::get_extensions_for_type(p_type,&extensions); + ClassDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); p_extensions->push_back(ext); } - } -void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const { List<String> extensions; ClassDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); p_extensions->push_back(ext); } - } -bool ResourceFormatLoaderBinary::handles_type(const String& p_type) const{ - +bool ResourceFormatLoaderBinary::handles_type(const String &p_type) const { return true; //handles all } +void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { -void ResourceFormatLoaderBinary::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types) { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND(!f); - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); - ria->get_dependencies(f,p_dependencies,p_add_types); + ria->get_dependencies(f, p_dependencies, p_add_types); } -Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { - +Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { //Error error=OK; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); - - FileAccess* fw=NULL;//=FileAccess::open(p_path+".depren"); + FileAccess *fw = NULL; //=FileAccess::open(p_path+".depren"); - String local_path=p_path.get_base_dir(); + String local_path = p_path.get_base_dir(); uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - FileAccessCompressed *facw = memnew( FileAccessCompressed ); + FileAccessCompressed *facw = memnew(FileAccessCompressed); facw->configure("RSCC"); - Error err = facw->_open(p_path+".depren",FileAccess::WRITE); + Error err = facw->_open(p_path + ".depren", FileAccess::WRITE); if (err) { memdelete(fac); memdelete(facw); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); } - fw=facw; + fw = facw; - - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal //error=ERR_FILE_UNRECOGNIZED; memdelete(f); - ERR_EXPLAIN("Unrecognized binary resource file: "+local_path); + ERR_EXPLAIN("Unrecognized binary resource file: " + local_path); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } else { - fw = FileAccess::open(p_path+".depren",FileAccess::WRITE); + fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); if (!fw) { memdelete(f); } - ERR_FAIL_COND_V(!fw,ERR_CANT_CREATE); + ERR_FAIL_COND_V(!fw, ERR_CANT_CREATE); } bool big_endian = f->get_32(); @@ -1181,144 +1128,139 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian fw->store_32(endian_swap); - fw->set_endian_swap(big_endian!=0); + fw->set_endian_swap(big_endian != 0); fw->store_32(use_real64); //use real64 - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - if (ver_format<FORMAT_VERSION_CAN_RENAME_DEPS) { + if (ver_format < FORMAT_VERSION_CAN_RENAME_DEPS) { memdelete(f); memdelete(fw); DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - da->remove(p_path+".depren"); + da->remove(p_path + ".depren"); memdelete(da); //fuck it, use the old approach; - WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: "+p_path).utf8().get_data()); + WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path).utf8().get_data()); Error err; - f = FileAccess::open(p_path,FileAccess::READ,&err); - if (err!=OK) { - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CANT_OPEN); + f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { + ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - ria->remaps=p_map; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + ria->remaps = p_map; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); err = ria->poll(); - while(err==OK) { - err=ria->poll(); + while (err == OK) { + err = ria->poll(); } - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, ERR_FILE_CORRUPT); RES res = ria->get_resource(); - ERR_FAIL_COND_V(!res.is_valid(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!res.is_valid(), ERR_FILE_CORRUPT); - return ResourceFormatSaverBinary::singleton->save(p_path,res); + return ResourceFormatSaverBinary::singleton->save(p_path, res); } - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { memdelete(f); memdelete(fw); - ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path); + ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } - fw->store_32( VERSION_MAJOR ); //current version - fw->store_32( VERSION_MINOR ); - fw->store_32( FORMAT_VERSION ); - - save_ustring(fw,get_ustring(f)); //type + fw->store_32(VERSION_MAJOR); //current version + fw->store_32(VERSION_MINOR); + fw->store_32(FORMAT_VERSION); + save_ustring(fw, get_ustring(f)); //type size_t md_ofs = f->get_pos(); size_t importmd_ofs = f->get_64(); fw->store_64(0); //metadata offset - for(int i=0;i<14;i++) { + for (int i = 0; i < 14; i++) { fw->store_32(0); f->get_32(); } //string table - uint32_t string_table_size=f->get_32(); + uint32_t string_table_size = f->get_32(); fw->store_32(string_table_size); - for(uint32_t i=0;i<string_table_size;i++) { + for (uint32_t i = 0; i < string_table_size; i++) { String s = get_ustring(f); - save_ustring(fw,s); + save_ustring(fw, s); } //external resources - uint32_t ext_resources_size=f->get_32(); + uint32_t ext_resources_size = f->get_32(); fw->store_32(ext_resources_size); - for(uint32_t i=0;i<ext_resources_size;i++) { + for (uint32_t i = 0; i < ext_resources_size; i++) { String type = get_ustring(f); String path = get_ustring(f); - bool relative=false; + bool relative = false; if (!path.begins_with("res://")) { - path=local_path.plus_file(path).simplify_path(); - relative=true; + path = local_path.plus_file(path).simplify_path(); + relative = true; } - if (p_map.has(path)) { - String np=p_map[path]; - path=np; + String np = p_map[path]; + path = np; } if (relative) { //restore relative - path=local_path.path_to_file(path); + path = local_path.path_to_file(path); } - save_ustring(fw,type); - save_ustring(fw,path); + save_ustring(fw, type); + save_ustring(fw, path); } int64_t size_diff = (int64_t)fw->get_pos() - (int64_t)f->get_pos(); //internal resources - uint32_t int_resources_size=f->get_32(); + uint32_t int_resources_size = f->get_32(); fw->store_32(int_resources_size); - for(uint32_t i=0;i<int_resources_size;i++) { + for (uint32_t i = 0; i < int_resources_size; i++) { - - String path=get_ustring(f); - uint64_t offset=f->get_64(); - save_ustring(fw,path); - fw->store_64(offset+size_diff); + String path = get_ustring(f); + uint64_t offset = f->get_64(); + save_ustring(fw, path); + fw->store_64(offset + size_diff); } //rest of file uint8_t b = f->get_8(); - while(!f->eof_reached()) { + while (!f->eof_reached()) { fw->store_8(b); b = f->get_8(); } - bool all_ok = fw->get_error()==OK; + bool all_ok = fw->get_error() == OK; fw->seek(md_ofs); - fw->store_64(importmd_ofs+size_diff); - + fw->store_64(importmd_ofs + size_diff); memdelete(f); memdelete(fw); @@ -1329,50 +1271,42 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); - da->rename(p_path+".depren",p_path); + da->rename(p_path + ".depren", p_path); memdelete(da); return OK; } - String ResourceFormatLoaderBinary::get_resource_type(const String &p_path) const { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ""; //could not rwead } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); String r = ria->recognize(f); return r; - - } - - /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// - void ResourceFormatSaverBinaryInstance::_pad_buffer(int p_bytes) { - int extra = 4-(p_bytes%4); - if (extra<4) { - for(int i=0;i<extra;i++) + int extra = 4 - (p_bytes % 4); + if (extra < 4) { + for (int i = 0; i < extra; i++) f->store_8(0); //pad to 32 } - } +void ResourceFormatSaverBinaryInstance::write_variant(const Variant &p_property, const PropertyInfo &p_hint) { -void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,const PropertyInfo& p_hint) { - - switch(p_property.get_type()) { + switch (p_property.get_type()) { case Variant::NIL: { @@ -1382,51 +1316,48 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::BOOL: { f->store_32(VARIANT_BOOL); - bool val=p_property; + bool val = p_property; f->store_32(val); } break; case Variant::INT: { int64_t val = p_property; - if (val>0x7FFFFFFF || val < -0x80000000) { + if (val > 0x7FFFFFFF || val < -0x80000000) { f->store_32(VARIANT_INT64); f->store_64(val); } else { f->store_32(VARIANT_INT); - int val=p_property; + int val = p_property; f->store_32(int32_t(val)); - } } break; case Variant::REAL: { - double d = p_property; float fl = d; - if (double(fl)!=d) { + if (double(fl) != d) { f->store_32(VARIANT_DOUBLE); f->store_double(d); } else { f->store_32(VARIANT_REAL); f->store_real(fl); - } } break; case Variant::STRING: { f->store_32(VARIANT_STRING); - String val=p_property; + String val = p_property; save_unicode_string(val); } break; case Variant::VECTOR2: { f->store_32(VARIANT_VECTOR2); - Vector2 val=p_property; + Vector2 val = p_property; f->store_real(val.x); f->store_real(val.y); @@ -1434,7 +1365,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::RECT2: { f->store_32(VARIANT_RECT2); - Rect2 val=p_property; + Rect2 val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.size.x); @@ -1444,7 +1375,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::VECTOR3: { f->store_32(VARIANT_VECTOR3); - Vector3 val=p_property; + Vector3 val = p_property; f->store_real(val.x); f->store_real(val.y); f->store_real(val.z); @@ -1453,7 +1384,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::PLANE: { f->store_32(VARIANT_PLANE); - Plane val=p_property; + Plane val = p_property; f->store_real(val.normal.x); f->store_real(val.normal.y); f->store_real(val.normal.z); @@ -1463,7 +1394,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::QUAT: { f->store_32(VARIANT_QUAT); - Quat val=p_property; + Quat val = p_property; f->store_real(val.x); f->store_real(val.y); f->store_real(val.z); @@ -1473,7 +1404,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::RECT3: { f->store_32(VARIANT_AABB); - Rect3 val=p_property; + Rect3 val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.pos.z); @@ -1485,7 +1416,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::TRANSFORM2D: { f->store_32(VARIANT_MATRIX32); - Transform2D val=p_property; + Transform2D val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[1].x); @@ -1497,7 +1428,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::BASIS: { f->store_32(VARIANT_MATRIX3); - Basis val=p_property; + Basis val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[0].z); @@ -1512,7 +1443,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::TRANSFORM: { f->store_32(VARIANT_TRANSFORM); - Transform val=p_property; + Transform val = p_property; f->store_real(val.basis.elements[0].x); f->store_real(val.basis.elements[0].y); f->store_real(val.basis.elements[0].z); @@ -1530,7 +1461,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::COLOR: { f->store_32(VARIANT_COLOR); - Color val=p_property; + Color val = p_property; f->store_real(val.r); f->store_real(val.g); f->store_real(val.b); @@ -1540,34 +1471,32 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::IMAGE: { f->store_32(VARIANT_IMAGE); - Image val =p_property; + Image val = p_property; if (val.empty()) { f->store_32(IMAGE_ENCODING_EMPTY); break; } - int encoding=IMAGE_ENCODING_RAW; - float quality=0.7; + int encoding = IMAGE_ENCODING_RAW; + float quality = 0.7; if (!val.is_compressed()) { //can only compress uncompressed stuff - if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) { - encoding=IMAGE_ENCODING_LOSSY; - float qs=p_hint.hint_string.to_double(); - if (qs!=0.0) - quality=qs; - - } else if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) { - encoding=IMAGE_ENCODING_LOSSLESS; + if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) { + encoding = IMAGE_ENCODING_LOSSY; + float qs = p_hint.hint_string.to_double(); + if (qs != 0.0) + quality = qs; + } else if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) { + encoding = IMAGE_ENCODING_LOSSLESS; } } f->store_32(encoding); //raw encoding - if (encoding==IMAGE_ENCODING_RAW) { - + if (encoding == IMAGE_ENCODING_RAW) { f->store_32(val.get_width()); f->store_32(val.get_height()); @@ -1577,42 +1506,40 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, int dlen = val.get_data().size(); f->store_32(dlen); PoolVector<uint8_t>::Read r = val.get_data().read(); - f->store_buffer(r.ptr(),dlen); + f->store_buffer(r.ptr(), dlen); _pad_buffer(dlen); } else { PoolVector<uint8_t> data; - if (encoding==IMAGE_ENCODING_LOSSY) { - data=Image::lossy_packer(val,quality); - - } else if (encoding==IMAGE_ENCODING_LOSSLESS) { - data=Image::lossless_packer(val); + if (encoding == IMAGE_ENCODING_LOSSY) { + data = Image::lossy_packer(val, quality); + } else if (encoding == IMAGE_ENCODING_LOSSLESS) { + data = Image::lossless_packer(val); } - int ds=data.size(); + int ds = data.size(); f->store_32(ds); - if (ds>0) { + if (ds > 0) { PoolVector<uint8_t>::Read r = data.read(); - f->store_buffer(r.ptr(),ds); + f->store_buffer(r.ptr(), ds); _pad_buffer(ds); - } } } break; case Variant::NODE_PATH: { f->store_32(VARIANT_NODE_PATH); - NodePath np=p_property; + NodePath np = p_property; f->store_16(np.get_name_count()); uint16_t snc = np.get_subname_count(); if (np.is_absolute()) - snc|=0x8000; + snc |= 0x8000; f->store_16(snc); - for(int i=0;i<np.get_name_count();i++) + for (int i = 0; i < np.get_name_count(); i++) f->store_32(get_string_index(np.get_name(i))); - for(int i=0;i<np.get_subname_count();i++) + for (int i = 0; i < np.get_subname_count(); i++) f->store_32(get_string_index(np.get_subname(i))); f->store_32(get_string_index(np.get_property())); @@ -1633,7 +1560,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, return; // don't save it } - if (res->get_path().length() && res->get_path().find("::")==-1) { + if (res->get_path().length() && res->get_path().find("::") == -1) { f->store_32(OBJECT_EXTERNAL_RESOURCE_INDEX); f->store_32(external_resources[res]); } else { @@ -1649,12 +1576,11 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, //internal resource } - } break; case Variant::INPUT_EVENT: { f->store_32(VARIANT_INPUT_EVENT); - InputEvent event=p_property; + InputEvent event = p_property; f->store_32(0); //event type none, nothing else suported for now. } break; @@ -1667,7 +1593,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* if (!_check_type(dict[E->get()])) @@ -1678,14 +1604,13 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, write_variant(d[E->get()]); } - } break; case Variant::ARRAY: { f->store_32(VARIANT_ARRAY); - Array a=p_property; + Array a = p_property; f->store_32(uint32_t(a.size())); - for(int i=0;i<a.size();i++) { + for (int i = 0; i < a.size(); i++) { write_variant(a[i]); } @@ -1695,10 +1620,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_RAW_ARRAY); PoolVector<uint8_t> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<uint8_t>::Read r = arr.read(); - f->store_buffer(r.ptr(),len); + f->store_buffer(r.ptr(), len); _pad_buffer(len); } break; @@ -1706,10 +1631,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_INT_ARRAY); PoolVector<int> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<int>::Read r = arr.read(); - for(int i=0;i<len;i++) + for (int i = 0; i < len; i++) f->store_32(r[i]); } break; @@ -1717,10 +1642,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_REAL_ARRAY); PoolVector<real_t> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<real_t>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i]); } @@ -1729,10 +1654,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_STRING_ARRAY); PoolVector<String> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<String>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { save_unicode_string(r[i]); } @@ -1741,10 +1666,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR3_ARRAY); PoolVector<Vector3> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<Vector3>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].x); f->store_real(r[i].y); f->store_real(r[i].z); @@ -1755,10 +1680,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR2_ARRAY); PoolVector<Vector2> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<Vector2>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].x); f->store_real(r[i].y); } @@ -1768,10 +1693,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_COLOR_ARRAY); PoolVector<Color> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<Color>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].r); f->store_real(r[i].g); f->store_real(r[i].b); @@ -1787,26 +1712,22 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, } } +void ResourceFormatSaverBinaryInstance::_find_resources(const Variant &p_variant, bool p_main) { -void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant,bool p_main) { - - - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::OBJECT: { - RES res = p_variant.operator RefPtr(); if (res.is_null() || external_resources.has(res)) return; - if (!p_main && (!bundle_resources ) && res->get_path().length() && res->get_path().find("::") == -1 ) { + if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) { int idx = external_resources.size(); - external_resources[res]=idx; + external_resources[res] = idx; return; } - if (resource_set.has(res)) return; @@ -1814,9 +1735,9 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant res->get_property_list(&property_list); - for(List<PropertyInfo>::Element *E=property_list.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { - if (E->get().usage&PROPERTY_USAGE_STORAGE) { + if (E->get().usage & PROPERTY_USAGE_STORAGE) { _find_resources(res->get(E->get().name)); } @@ -1829,11 +1750,11 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::ARRAY: { - Array varray=p_variant; - int len=varray.size(); - for(int i=0;i<len;i++) { + Array varray = p_variant; + int len = varray.size(); + for (int i = 0; i < len; i++) { - Variant v=varray.get(i); + Variant v = varray.get(i); _find_resources(v); } @@ -1841,10 +1762,10 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::DICTIONARY: { - Dictionary d=p_variant; + Dictionary d = p_variant; List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _find_resources(E->get()); Variant v = d[E->get()]; @@ -1854,18 +1775,16 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::NODE_PATH: { //take the chance and save node path strings NodePath np = p_variant; - for(int i=0;i<np.get_name_count();i++) + for (int i = 0; i < np.get_name_count(); i++) get_string_index(np.get_name(i)); - for(int i=0;i<np.get_subname_count();i++) + for (int i = 0; i < np.get_subname_count(); i++) get_string_index(np.get_subname(i)); get_string_index(np.get_property()); - } break; default: {} } - } #if 0 Error ResourceFormatSaverBinary::_save_obj(const Object *p_object,SavedObject *so) { @@ -1916,64 +1835,60 @@ Error ResourceFormatSaverBinary::save(const Object *p_object,const Variant &p_me } #endif -void ResourceFormatSaverBinaryInstance::save_unicode_string(const String& p_string) { - +void ResourceFormatSaverBinaryInstance::save_unicode_string(const String &p_string) { CharString utf8 = p_string.utf8(); - f->store_32(utf8.length()+1); - f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1); + f->store_32(utf8.length() + 1); + f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } -int ResourceFormatSaverBinaryInstance::get_string_index(const String& p_string) { +int ResourceFormatSaverBinaryInstance::get_string_index(const String &p_string) { - StringName s=p_string; + StringName s = p_string; if (string_map.has(s)) return string_map[s]; - string_map[s]=strings.size(); + string_map[s] = strings.size(); strings.push_back(s); - return strings.size()-1; + return strings.size() - 1; } - -Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverBinaryInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Error err; - if (p_flags&ResourceSaver::FLAG_COMPRESS) { - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + if (p_flags & ResourceSaver::FLAG_COMPRESS) { + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->configure("RSCC"); - f=fac; - err = fac->_open(p_path,FileAccess::WRITE); + f = fac; + err = fac->_open(p_path, FileAccess::WRITE); if (err) memdelete(f); } else { - f=FileAccess::open(p_path,FileAccess::WRITE,&err); + f = FileAccess::open(p_path, FileAccess::WRITE, &err); } - - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); FileAccessRef _fref(f); - - relative_paths=p_flags&ResourceSaver::FLAG_RELATIVE_PATHS; - skip_editor=p_flags&ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES; - bundle_resources=p_flags&ResourceSaver::FLAG_BUNDLE_RESOURCES; - big_endian=p_flags&ResourceSaver::FLAG_SAVE_BIG_ENDIAN; - takeover_paths=p_flags&ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; + relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS; + skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES; + bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES; + big_endian = p_flags & ResourceSaver::FLAG_SAVE_BIG_ENDIAN; + takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; if (!p_path.begins_with("res://")) - takeover_paths=false; + takeover_paths = false; - local_path=p_path.get_base_dir(); + local_path = p_path.get_base_dir(); //bin_meta_idx = get_string_index("__bin_meta__"); //is often used, so create - _find_resources(p_resource,true); + _find_resources(p_resource, true); - if (!(p_flags&ResourceSaver::FLAG_COMPRESS)) { + if (!(p_flags & ResourceSaver::FLAG_COMPRESS)) { //save header compressed - static const uint8_t header[4]={'R','S','R','C'}; - f->store_buffer(header,4); + static const uint8_t header[4] = { 'R', 'S', 'R', 'C' }; + f->store_buffer(header, 4); } if (big_endian) { @@ -1987,7 +1902,7 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ f->store_32(VERSION_MINOR); f->store_32(FORMAT_VERSION); - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } @@ -1996,50 +1911,41 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ save_unicode_string(p_resource->get_class()); uint64_t md_at = f->get_pos(); f->store_64(0); //offset to impoty metadata - for(int i=0;i<14;i++) + for (int i = 0; i < 14; i++) f->store_32(0); // reserved - List<ResourceData> resources; - { - - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { - + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { ResourceData &rd = resources.push_back(ResourceData())->get(); - rd.type=E->get()->get_class(); + rd.type = E->get()->get_class(); List<PropertyInfo> property_list; - E->get()->get_property_list( &property_list ); + E->get()->get_property_list(&property_list); - for(List<PropertyInfo>::Element *F=property_list.front();F;F=F->next()) { + for (List<PropertyInfo>::Element *F = property_list.front(); F; F = F->next()) { if (skip_editor && F->get().name.begins_with("__editor")) continue; - if (F->get().usage&PROPERTY_USAGE_STORAGE ) { + if (F->get().usage & PROPERTY_USAGE_STORAGE) { Property p; - p.name_idx=get_string_index(F->get().name); - p.value=E->get()->get(F->get().name); - if ((F->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero())||(F->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one()) ) + p.name_idx = get_string_index(F->get().name); + p.value = E->get()->get(F->get().name); + if ((F->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero()) || (F->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one())) continue; - p.pi=F->get(); + p.pi = F->get(); rd.properties.push_back(p); - } } - - - } } - f->store_32(strings.size()); //string table size - for(int i=0;i<strings.size();i++) { + for (int i = 0; i < strings.size(); i++) { //print_bl("saving string: "+strings[i]); save_unicode_string(strings[i]); } @@ -2049,15 +1955,15 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector<RES> save_order; save_order.resize(external_resources.size()); - for(Map<RES,int>::Element *E=external_resources.front();E;E=E->next()) { - save_order[E->get()]=E->key(); + for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) { + save_order[E->get()] = E->key(); } - for(int i=0;i<save_order.size();i++) { + for (int i = 0; i < save_order.size(); i++) { save_unicode_string(save_order[i]->get_save_class()); String path = save_order[i]->get_path(); - path=relative_paths?local_path.path_to_file(path):path; + path = relative_paths ? local_path.path_to_file(path) : path; save_unicode_string(path); } // save internal resource table @@ -2065,12 +1971,12 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector<uint64_t> ofs_pos; Set<int> used_indices; - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { RES r = E->get(); - if (r->get_path()=="" || r->get_path().find("::")!=-1) { + if (r->get_path() == "" || r->get_path().find("::") != -1) { - if (r->get_subindex()!=0) { + if (r->get_subindex() != 0) { if (used_indices.has(r->get_subindex())) { r->set_subindex(0); //repeated } else { @@ -2078,29 +1984,25 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ } } } - } - - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { - + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { RES r = E->get(); - if (r->get_path()=="" || r->get_path().find("::")!=-1) { - if (r->get_subindex()==0) { - int new_subindex=1; + if (r->get_path() == "" || r->get_path().find("::") != -1) { + if (r->get_subindex() == 0) { + int new_subindex = 1; if (used_indices.size()) { - new_subindex=used_indices.back()->get()+1; + new_subindex = used_indices.back()->get() + 1; } r->set_subindex(new_subindex); used_indices.insert(new_subindex); - } - save_unicode_string("local://"+itos(r->get_subindex())); + save_unicode_string("local://" + itos(r->get_subindex())); if (takeover_paths) { - r->set_path(p_path+"::"+itos(r->get_subindex()),true); + r->set_path(p_path + "::" + itos(r->get_subindex()), true); } #ifdef TOOLS_ENABLED r->set_edited(false); @@ -2116,74 +2018,64 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ //int saved_idx=0; //now actually save the resources - for(List<ResourceData>::Element *E=resources.front();E;E=E->next()) { + for (List<ResourceData>::Element *E = resources.front(); E; E = E->next()) { - ResourceData & rd = E->get(); + ResourceData &rd = E->get(); ofs_table.push_back(f->get_pos()); save_unicode_string(rd.type); f->store_32(rd.properties.size()); - for (List<Property>::Element *F=rd.properties.front();F;F=F->next()) { + for (List<Property>::Element *F = rd.properties.front(); F; F = F->next()) { - Property &p=F->get(); + Property &p = F->get(); f->store_32(p.name_idx); - write_variant(p.value,F->get().pi); + write_variant(p.value, F->get().pi); } - } - for(int i=0;i<ofs_table.size();i++) { + for (int i = 0; i < ofs_table.size(); i++) { f->seek(ofs_pos[i]); f->store_64(ofs_table[i]); } f->seek_end(); + f->store_buffer((const uint8_t *)"RSRC", 4); //magic at end - f->store_buffer((const uint8_t*)"RSRC",4); //magic at end - - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } f->close(); - return OK; } - - -Error ResourceFormatSaverBinary::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { - +Error ResourceFormatSaverBinary::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { String local_path = GlobalConfig::get_singleton()->localize_path(p_path); ResourceFormatSaverBinaryInstance saver; - return saver.save(local_path,p_resource,p_flags); - + return saver.save(local_path, p_resource, p_flags); } - -bool ResourceFormatSaverBinary::recognize(const RES& p_resource) const { +bool ResourceFormatSaverBinary::recognize(const RES &p_resource) const { return true; //all recognized - } -void ResourceFormatSaverBinary::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { +void ResourceFormatSaverBinary::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { String base = p_resource->get_base_extension().to_lower(); p_extensions->push_back(base); - if (base!="res") + if (base != "res") p_extensions->push_back("res"); - } -ResourceFormatSaverBinary* ResourceFormatSaverBinary::singleton=NULL; +ResourceFormatSaverBinary *ResourceFormatSaverBinary::singleton = NULL; ResourceFormatSaverBinary::ResourceFormatSaverBinary() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_format_binary.h b/core/io/resource_format_binary.h index 1fab6144d5..f378d0eae9 100644 --- a/core/io/resource_format_binary.h +++ b/core/io/resource_format_binary.h @@ -33,7 +33,6 @@ #include "io/resource_saver.h" #include "os/file_access.h" - class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String local_path; @@ -43,7 +42,6 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { FileAccess *f; - bool endian_swap; bool use_real64; uint64_t importmd_ofs; @@ -73,58 +71,46 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String get_unicode_string(); void _advance_padding(uint32_t p_len); - Map<String,String> remaps; + Map<String, String> remaps; Error error; int stage; -friend class ResourceFormatLoaderBinary; + friend class ResourceFormatLoaderBinary; - - Error parse_variant(Variant& r_v); + Error parse_variant(Variant &r_v); public: - - virtual void set_local_path(const String& p_local_path); + virtual void set_local_path(const String &p_local_path); virtual Ref<Resource> get_resource(); virtual Error poll(); virtual int get_stage() const; virtual int get_stage_count() const; - void set_remaps(const Map<String,String>& p_remaps) { remaps=p_remaps; } + void set_remaps(const Map<String, String> &p_remaps) { remaps = p_remaps; } void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); - ResourceInteractiveLoaderBinary(); ~ResourceInteractiveLoaderBinary(); - }; class ResourceFormatLoaderBinary : public ResourceFormatLoader { public: - - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - virtual void get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - - - + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); }; - - - -class ResourceFormatSaverBinaryInstance { +class ResourceFormatSaverBinaryInstance { String local_path; - bool relative_paths; bool bundle_resources; bool skip_editor; @@ -134,19 +120,16 @@ class ResourceFormatSaverBinaryInstance { FileAccess *f; String magic; Set<RES> resource_set; - Map<StringName,int> string_map; + Map<StringName, int> string_map; Vector<StringName> strings; - - Map<RES,int> external_resources; + Map<RES, int> external_resources; List<RES> saved_resources; - struct Property { int name_idx; Variant value; PropertyInfo pi; - }; struct ResourceData { @@ -155,36 +138,25 @@ class ResourceFormatSaverBinaryInstance { List<Property> properties; }; - - - void _pad_buffer(int p_bytes); - void write_variant(const Variant& p_property,const PropertyInfo& p_hint=PropertyInfo()); - void _find_resources(const Variant& p_variant,bool p_main=false); - void save_unicode_string(const String& p_string); - int get_string_index(const String& p_string); -public: + void write_variant(const Variant &p_property, const PropertyInfo &p_hint = PropertyInfo()); + void _find_resources(const Variant &p_variant, bool p_main = false); + void save_unicode_string(const String &p_string); + int get_string_index(const String &p_string); - - Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); +public: + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); }; - - -class ResourceFormatSaverBinary : public ResourceFormatSaver { - - - +class ResourceFormatSaverBinary : public ResourceFormatSaver { public: - - static ResourceFormatSaverBinary* singleton; - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - virtual bool recognize(const RES& p_resource) const; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const; + static ResourceFormatSaverBinary *singleton; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual bool recognize(const RES &p_resource) const; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; ResourceFormatSaverBinary(); }; - #endif // RESOURCE_FORMAT_BINARY_H diff --git a/core/io/resource_import.cpp b/core/io/resource_import.cpp index 41245db173..27173a721d 100644 --- a/core/io/resource_import.cpp +++ b/core/io/resource_import.cpp @@ -28,106 +28,101 @@ /*************************************************************************/ #include "resource_import.h" -#include "variant_parser.h" #include "os/os.h" +#include "variant_parser.h" -Error ResourceFormatImporter::_get_path_and_type(const String& p_path, PathAndType &r_path_and_type) const { +Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type) const { Error err; - FileAccess *f= FileAccess::open(p_path+".import",FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); if (!f) return err; VariantParser::StreamFile stream; - stream.f=f; + stream.f = f; String assign; Variant value; VariantParser::Tag next_tag; - int lines=0; + int lines = 0; String error_text; - while(true) { + while (true) { - assign=Variant(); + assign = Variant(); next_tag.fields.clear(); - next_tag.name=String(); + next_tag.name = String(); - err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true); - if (err==ERR_FILE_EOF) { + err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true); + if (err == ERR_FILE_EOF) { memdelete(f); return OK; - } - else if (err!=OK) { - ERR_PRINTS("ResourceFormatImporter::load - "+p_path+".import:"+itos(lines)+" error: "+error_text); + } else if (err != OK) { + ERR_PRINTS("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text); memdelete(f); return err; } - if (assign!=String()) { - if (assign.begins_with("path.") && r_path_and_type.path==String()) { - String feature = assign.get_slicec('.',1); + if (assign != String()) { + if (assign.begins_with("path.") && r_path_and_type.path == String()) { + String feature = assign.get_slicec('.', 1); if (OS::get_singleton()->check_feature_support(feature)) { - r_path_and_type.path=value; + r_path_and_type.path = value; } - } else if (assign=="path") { - r_path_and_type.path=value; - } else if (assign=="type") { - r_path_and_type.type=value; + } else if (assign == "path") { + r_path_and_type.path = value; + } else if (assign == "type") { + r_path_and_type.type = value; } - } else if (next_tag.name!="remap") { + } else if (next_tag.name != "remap") { break; } } memdelete(f); - if (r_path_and_type.path==String() || r_path_and_type.type==String()) { + if (r_path_and_type.path == String() || r_path_and_type.type == String()) { return ERR_FILE_CORRUPT; } return OK; - } - -RES ResourceFormatImporter::load(const String &p_path,const String& p_original_path,Error *r_error) { +RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error) { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { if (r_error) - *r_error=err; + *r_error = err; return RES(); } - - RES res = ResourceLoader::load(pat.path,pat.type,false,r_error); + RES res = ResourceLoader::load(pat.path, pat.type, false, r_error); #ifdef TOOLS_ENABLED if (res.is_valid()) { - res->set_import_last_modified_time( res->get_last_modified_time() ); //pass this, if used + res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used res->set_import_path(pat.path); } #endif return res; - } -void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const { Set<String> found; - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { if (!found.has(F->get())) { p_extensions->push_back(F->get()); found.insert(F->get()); @@ -136,25 +131,25 @@ void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extension } } -void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const{ +void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="") { + if (p_type == "") { return get_recognized_extensions(p_extensions); } Set<String> found; - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { String res_type = E->get()->get_resource_type(); - if (res_type==String()) + if (res_type == String()) continue; - if (!ClassDB::is_parent_class(res_type,p_type)) + if (!ClassDB::is_parent_class(res_type, p_type)) continue; List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { if (!found.has(F->get())) { p_extensions->push_back(F->get()); found.insert(F->get()); @@ -163,40 +158,36 @@ void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_ } } -bool ResourceFormatImporter::recognize_path(const String& p_path,const String& p_for_type) const{ - - return FileAccess::exists(p_path+".import"); +bool ResourceFormatImporter::recognize_path(const String &p_path, const String &p_for_type) const { + return FileAccess::exists(p_path + ".import"); } -bool ResourceFormatImporter::can_be_imported(const String& p_path) const { +bool ResourceFormatImporter::can_be_imported(const String &p_path) const { return ResourceFormatLoader::recognize_path(p_path); } +bool ResourceFormatImporter::handles_type(const String &p_type) const { -bool ResourceFormatImporter::handles_type(const String& p_type) const { - - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { String res_type = E->get()->get_resource_type(); - if (res_type==String()) + if (res_type == String()) continue; - if (ClassDB::is_parent_class(res_type,p_type)) + if (ClassDB::is_parent_class(res_type, p_type)) return true; - } return true; } - -String ResourceFormatImporter::get_internal_resource_path(const String& p_path) const { +String ResourceFormatImporter::get_internal_resource_path(const String &p_path) const { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { return String(); } @@ -207,9 +198,9 @@ String ResourceFormatImporter::get_internal_resource_path(const String& p_path) String ResourceFormatImporter::get_resource_type(const String &p_path) const { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { return ""; } @@ -217,23 +208,23 @@ String ResourceFormatImporter::get_resource_type(const String &p_path) const { return pat.type; } -void ResourceFormatImporter::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types){ +void ResourceFormatImporter::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { return; } - return ResourceLoader::get_dependencies(pat.path,p_dependencies,p_add_types); + return ResourceLoader::get_dependencies(pat.path, p_dependencies, p_add_types); } -Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String& p_name) { +Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String &p_name) { - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { - if (E->get()->get_importer_name()==p_name) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { + if (E->get()->get_importer_name() == p_name) { return E->get(); } } @@ -241,34 +232,32 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String& return Ref<ResourceImporter>(); } +void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter> > *r_importers) { -void ResourceFormatImporter::get_importers_for_extension(const String& p_extension,List<Ref<ResourceImporter> > *r_importers) { - - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { - if (p_extension.to_lower()==F->get()) { + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { + if (p_extension.to_lower() == F->get()) { r_importers->push_back(E->get()); } } } } -Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String& p_extension) { - +Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String &p_extension) { Ref<ResourceImporter> importer; - float priority=0; + float priority = 0; - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { - if (p_extension.to_lower()==F->get() && E->get()->get_priority() > priority) { - importer=E->get(); - priority=E->get()->get_priority(); + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { + if (p_extension.to_lower() == F->get() && E->get()->get_priority() > priority) { + importer = E->get(); + priority = E->get()->get_priority(); } } } @@ -276,13 +265,13 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const St return importer; } -String ResourceFormatImporter::get_import_base_path(const String& p_for_file) const { +String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const { - return "res://.import/"+p_for_file.get_file()+"-"+p_for_file.md5_text(); + return "res://.import/" + p_for_file.get_file() + "-" + p_for_file.md5_text(); } -ResourceFormatImporter *ResourceFormatImporter::singleton=NULL; +ResourceFormatImporter *ResourceFormatImporter::singleton = NULL; ResourceFormatImporter::ResourceFormatImporter() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_import.h b/core/io/resource_import.h index dd7a82fe75..f4349a9c61 100644 --- a/core/io/resource_import.h +++ b/core/io/resource_import.h @@ -29,7 +29,6 @@ #ifndef RESOURCE_IMPORT_H #define RESOURCE_IMPORT_H - #include "io/resource_loader.h" class ResourceImporter; @@ -40,66 +39,64 @@ class ResourceFormatImporter : public ResourceFormatLoader { String type; }; - - Error _get_path_and_type(const String& p_path,PathAndType & r_path_and_type) const; + Error _get_path_and_type(const String &p_path, PathAndType &r_path_and_type) const; static ResourceFormatImporter *singleton; - Set< Ref<ResourceImporter> > importers; -public: + Set<Ref<ResourceImporter> > importers; +public: static ResourceFormatImporter *get_singleton() { return singleton; } - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; - virtual bool recognize_path(const String& p_path,const String& p_for_type=String()) const; - virtual bool handles_type(const String& p_type) const; + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; + virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); - virtual bool can_be_imported(const String& p_path) const; + virtual bool can_be_imported(const String &p_path) const; - String get_internal_resource_path(const String& p_path) const; + String get_internal_resource_path(const String &p_path) const; - void add_importer(const Ref<ResourceImporter>& p_importer) { importers.insert(p_importer); } - Ref<ResourceImporter> get_importer_by_name(const String& p_name); - Ref<ResourceImporter> get_importer_by_extension(const String& p_extension); - void get_importers_for_extension(const String& p_extension,List<Ref<ResourceImporter> > *r_importers); + void add_importer(const Ref<ResourceImporter> &p_importer) { importers.insert(p_importer); } + Ref<ResourceImporter> get_importer_by_name(const String &p_name); + Ref<ResourceImporter> get_importer_by_extension(const String &p_extension); + void get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter> > *r_importers); - String get_import_base_path(const String& p_for_file) const; + String get_import_base_path(const String &p_for_file) const; ResourceFormatImporter(); }; - class ResourceImporter : public Reference { - GDCLASS(ResourceImporter,Reference) + GDCLASS(ResourceImporter, Reference) public: - virtual String get_importer_name() const=0; - virtual String get_visible_name() const=0; - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - virtual String get_save_extension() const=0; - virtual String get_resource_type() const=0; + virtual String get_importer_name() const = 0; + virtual String get_visible_name() const = 0; + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + virtual String get_save_extension() const = 0; + virtual String get_resource_type() const = 0; virtual float get_priority() const { return 1.0; } struct ImportOption { PropertyInfo option; Variant default_value; - ImportOption(const PropertyInfo& p_info,const Variant& p_default) { option=p_info; default_value=p_default; } + ImportOption(const PropertyInfo &p_info, const Variant &p_default) { + option = p_info; + default_value = p_default; + } ImportOption() {} }; - virtual int get_preset_count() const { return 0; } virtual String get_preset_name(int p_idx) const { return String(); } - virtual void get_import_options(List<ImportOption> *r_options,int p_preset=0) const=0; - virtual bool get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const=0; - - - virtual Error import(const String& p_source_file,const String& p_save_path,const Map<StringName,Variant>& p_options,List<String>* r_platform_variants,List<String>* r_gen_files=NULL)=0; + virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const = 0; + virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const = 0; + virtual Error import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files = NULL) = 0; }; #endif // RESOURCE_IMPORT_H diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp index c14389eefa..5d8ec57ee0 100644 --- a/core/io/resource_loader.cpp +++ b/core/io/resource_loader.cpp @@ -27,81 +27,76 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "resource_loader.h" -#include "print_string.h" #include "global_config.h" -#include "path_remap.h" #include "os/file_access.h" #include "os/os.h" +#include "path_remap.h" +#include "print_string.h" ResourceFormatLoader *ResourceLoader::loader[MAX_LOADERS]; -int ResourceLoader::loader_count=0; - +int ResourceLoader::loader_count = 0; Error ResourceInteractiveLoader::wait() { Error err = poll(); - while (err==OK) { - err=poll(); + while (err == OK) { + err = poll(); } return err; } -bool ResourceFormatLoader::recognize_path(const String& p_path,const String& p_for_type) const { - +bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const { String extension = p_path.get_extension(); List<String> extensions; - if (p_for_type==String()) { + if (p_for_type == String()) { get_recognized_extensions(&extensions); } else { - get_recognized_extensions_for_type(p_for_type,&extensions); + get_recognized_extensions_for_type(p_for_type, &extensions); } - for (List<String>::Element *E=extensions.front();E;E=E->next()) { - + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(extension)==0) + if (E->get().nocasecmp_to(extension) == 0) return true; } return false; - } +void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { -void ResourceFormatLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { - - if (p_type=="" || handles_type(p_type)) + if (p_type == "" || handles_type(p_type)) get_recognized_extensions(p_extensions); } -void ResourceLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) { +void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) { - for (int i=0;i<loader_count;i++) { - loader[i]->get_recognized_extensions_for_type(p_type,p_extensions); + for (int i = 0; i < loader_count; i++) { + loader[i]->get_recognized_extensions_for_type(p_type, p_extensions); } - } void ResourceInteractiveLoader::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_resource"),&ResourceInteractiveLoader::get_resource); - ClassDB::bind_method(D_METHOD("poll"),&ResourceInteractiveLoader::poll); - ClassDB::bind_method(D_METHOD("wait"),&ResourceInteractiveLoader::wait); - ClassDB::bind_method(D_METHOD("get_stage"),&ResourceInteractiveLoader::get_stage); - ClassDB::bind_method(D_METHOD("get_stage_count"),&ResourceInteractiveLoader::get_stage_count); + ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource); + ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll); + ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait); + ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage); + ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count); } class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader { - GDCLASS( ResourceInteractiveLoaderDefault, ResourceInteractiveLoader ); -public: + GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader); +public: Ref<Resource> resource; - virtual void set_local_path(const String& p_local_path) { /*scene->set_filename(p_local_path);*/ } + virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/ + } virtual Ref<Resource> get_resource() { return resource; } virtual Error poll() { return ERR_FILE_EOF; } virtual int get_stage() const { return 1; } @@ -110,94 +105,87 @@ public: ResourceInteractiveLoaderDefault() {} }; - - Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, Error *r_error) { //either this - Ref<Resource> res = load(p_path,p_path,r_error); + Ref<Resource> res = load(p_path, p_path, r_error); if (res.is_null()) return Ref<ResourceInteractiveLoader>(); - Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>( memnew( ResourceInteractiveLoaderDefault )); - ril->resource=res; + Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault)); + ril->resource = res; return ril; } -RES ResourceFormatLoader::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) { - - String path=p_path; + String path = p_path; //or this must be implemented - Ref<ResourceInteractiveLoader> ril = load_interactive(p_path,r_error); + Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, r_error); if (!ril.is_valid()) return RES(); ril->set_local_path(p_original_path); - while(true) { + while (true) { Error err = ril->poll(); - if (err==ERR_FILE_EOF) { + if (err == ERR_FILE_EOF) { if (r_error) - *r_error=OK; + *r_error = OK; return ril->get_resource(); } if (r_error) - *r_error=err; + *r_error = err; - ERR_FAIL_COND_V(err!=OK,RES()); + ERR_FAIL_COND_V(err != OK, RES()); } return RES(); - } -void ResourceFormatLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) { +void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { //do nothing by default } - /////////////////////////////////// - -RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p_no_cache, Error *r_error) { +RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - ERR_FAIL_COND_V(local_path=="",RES()); + ERR_FAIL_COND_V(local_path == "", RES()); if (!p_no_cache && ResourceCache::has(local_path)) { if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path+" (cached)"); + print_line("load resource: " + local_path + " (cached)"); - return RES( ResourceCache::get(local_path ) ); + return RES(ResourceCache::get(local_path)); } if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path); - bool found=false; + print_line("load resource: " + local_path); + bool found = false; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { - if (!loader[i]->recognize_path(local_path,p_type_hint)) { + if (!loader[i]->recognize_path(local_path, p_type_hint)) { print_line("path not recognized"); continue; } - found=true; - RES res = loader[i]->load(local_path,local_path,r_error); + found = true; + RES res = loader[i]->load(local_path, local_path, r_error); if (res.is_null()) { continue; } @@ -217,37 +205,31 @@ RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p } if (found) { - ERR_EXPLAIN("Failed loading resource: "+p_path); + ERR_EXPLAIN("Failed loading resource: " + p_path); } else { - ERR_EXPLAIN("No loader found for resource: "+p_path); + ERR_EXPLAIN("No loader found for resource: " + p_path); } ERR_FAIL_V(RES()); return RES(); } - - -Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) { - +Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - ERR_FAIL_COND_V(local_path=="",Ref<ResourceInteractiveLoader>()); - - + ERR_FAIL_COND_V(local_path == "", Ref<ResourceInteractiveLoader>()); if (!p_no_cache && ResourceCache::has(local_path)) { if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path+" (cached)"); + print_line("load resource: " + local_path + " (cached)"); Ref<Resource> res_cached = ResourceCache::get(local_path); Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault)); @@ -259,14 +241,14 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_ if (OS::get_singleton()->is_stdout_verbose()) print_line("load resource: "); - bool found=false; + bool found = false; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { - if (!loader[i]->recognize_path(local_path,p_type_hint)) + if (!loader[i]->recognize_path(local_path, p_type_hint)) continue; - found=true; - Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(local_path,r_error); + found = true; + Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(local_path, r_error); if (ril.is_null()) continue; if (!p_no_cache) @@ -276,39 +258,37 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_ } if (found) { - ERR_EXPLAIN("Failed loading resource: "+p_path); + ERR_EXPLAIN("Failed loading resource: " + p_path); } else { - ERR_EXPLAIN("No loader found for resource: "+p_path); + ERR_EXPLAIN("No loader found for resource: " + p_path); } ERR_FAIL_V(Ref<ResourceInteractiveLoader>()); return Ref<ResourceInteractiveLoader>(); - } void ResourceLoader::add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front) { - ERR_FAIL_COND( loader_count >= MAX_LOADERS ); + ERR_FAIL_COND(loader_count >= MAX_LOADERS); if (p_at_front) { - for(int i=loader_count;i>0;i--) { - loader[i]=loader[i-1]; + for (int i = loader_count; i > 0; i--) { + loader[i] = loader[i - 1]; } - loader[0]=p_format_loader; + loader[0] = p_format_loader; loader_count++; } else { - loader[loader_count++]=p_format_loader; + loader[loader_count++] = p_format_loader; } } -void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) { - +void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize_path(local_path)) continue; @@ -317,22 +297,19 @@ void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_depe continue; */ - loader[i]->get_dependencies(local_path,p_dependencies,p_add_types); - + loader[i]->get_dependencies(local_path, p_dependencies, p_add_types); } } -Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { - +Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize_path(local_path)) continue; @@ -341,41 +318,34 @@ Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String, continue; */ - return loader[i]->rename_dependencies(local_path,p_map); - + return loader[i]->rename_dependencies(local_path, p_map); } return OK; // ?? - } - - String ResourceLoader::get_resource_type(const String &p_path) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { String result = loader[i]->get_resource_type(local_path); - if (result!="") + if (result != "") return result; } return ""; - } -ResourceLoadErrorNotify ResourceLoader::err_notify=NULL; -void *ResourceLoader::err_notify_ud=NULL; - -DependencyErrorNotify ResourceLoader::dep_err_notify=NULL; -void *ResourceLoader::dep_err_notify_ud=NULL; +ResourceLoadErrorNotify ResourceLoader::err_notify = NULL; +void *ResourceLoader::err_notify_ud = NULL; -bool ResourceLoader::abort_on_missing_resource=true; -bool ResourceLoader::timestamp_on_load=false; +DependencyErrorNotify ResourceLoader::dep_err_notify = NULL; +void *ResourceLoader::dep_err_notify_ud = NULL; +bool ResourceLoader::abort_on_missing_resource = true; +bool ResourceLoader::timestamp_on_load = false; diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h index f464415e12..0d51b07414 100644 --- a/core/io/resource_loader.h +++ b/core/io/resource_loader.h @@ -37,86 +37,86 @@ class ResourceInteractiveLoader : public Reference { - GDCLASS(ResourceInteractiveLoader,Reference); -protected: + GDCLASS(ResourceInteractiveLoader, Reference); +protected: static void _bind_methods(); -public: - virtual void set_local_path(const String& p_local_path)=0; - virtual Ref<Resource> get_resource()=0; - virtual Error poll()=0; - virtual int get_stage() const=0; - virtual int get_stage_count() const=0; +public: + virtual void set_local_path(const String &p_local_path) = 0; + virtual Ref<Resource> get_resource() = 0; + virtual Error poll() = 0; + virtual int get_stage() const = 0; + virtual int get_stage_count() const = 0; virtual Error wait(); ResourceInteractiveLoader() {} }; - class ResourceFormatLoader { public: - - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; - virtual bool recognize_path(const String& p_path,const String& p_for_type=String()) const; - virtual bool handles_type(const String& p_type) const=0; - virtual String get_resource_type(const String &p_path) const=0; - virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map) { return OK; } + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; + virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const; + virtual bool handles_type(const String &p_type) const = 0; + virtual String get_resource_type(const String &p_path) const = 0; + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map) { return OK; } virtual ~ResourceFormatLoader() {} }; - -typedef void (*ResourceLoadErrorNotify)(void *p_ud,const String& p_text); -typedef void (*DependencyErrorNotify)(void *p_ud,const String& p_loading,const String& p_which,const String& p_type); - +typedef void (*ResourceLoadErrorNotify)(void *p_ud, const String &p_text); +typedef void (*DependencyErrorNotify)(void *p_ud, const String &p_loading, const String &p_which, const String &p_type); class ResourceLoader { enum { - MAX_LOADERS=64 + MAX_LOADERS = 64 }; static ResourceFormatLoader *loader[MAX_LOADERS]; static int loader_count; static bool timestamp_on_load; - static void* err_notify_ud; + static void *err_notify_ud; static ResourceLoadErrorNotify err_notify; - static void* dep_err_notify_ud; + static void *dep_err_notify_ud; static DependencyErrorNotify dep_err_notify; static bool abort_on_missing_resource; public: + static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); + static RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); - - - static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL); - static RES load(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL); - - static void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions); - static void add_resource_format_loader(ResourceFormatLoader *p_format_loader,bool p_at_front=false); + static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions); + static void add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front = false); static String get_resource_type(const String &p_path); - static void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); - static Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - - static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load=p_timestamp; } - - static void notify_load_error(const String& p_err) { if (err_notify) err_notify(err_notify_ud,p_err); } - static void set_error_notify_func(void* p_ud,ResourceLoadErrorNotify p_err_notify) { err_notify=p_err_notify; err_notify_ud=p_ud;} - - static void notify_dependency_error(const String& p_path,const String& p_dependency,const String& p_type) { if (dep_err_notify) dep_err_notify(dep_err_notify_ud,p_path,p_dependency,p_type); } - static void set_dependency_error_notify_func(void* p_ud,DependencyErrorNotify p_err_notify) { dep_err_notify=p_err_notify; dep_err_notify_ud=p_ud;} - - - static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource=p_abort; } + static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + static Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); + + static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; } + + static void notify_load_error(const String &p_err) { + if (err_notify) err_notify(err_notify_ud, p_err); + } + static void set_error_notify_func(void *p_ud, ResourceLoadErrorNotify p_err_notify) { + err_notify = p_err_notify; + err_notify_ud = p_ud; + } + + static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) { + if (dep_err_notify) dep_err_notify(dep_err_notify_ud, p_path, p_dependency, p_type); + } + static void set_dependency_error_notify_func(void *p_ud, DependencyErrorNotify p_err_notify) { + dep_err_notify = p_err_notify; + dep_err_notify_ud = p_ud; + } + + static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; } static bool get_abort_on_missing_resources() { return abort_on_missing_resource; } }; - - #endif diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp index f0bea30051..e4548b16ff 100644 --- a/core/io/resource_saver.cpp +++ b/core/io/resource_saver.cpp @@ -29,62 +29,61 @@ #include "resource_saver.h" #include "global_config.h" #include "os/file_access.h" -#include "script_language.h" #include "resource_loader.h" +#include "script_language.h" ResourceFormatSaver *ResourceSaver::saver[MAX_SAVERS]; -int ResourceSaver::saver_count=0; -bool ResourceSaver::timestamp_on_save=false; -ResourceSavedCallback ResourceSaver::save_callback=0; +int ResourceSaver::saver_count = 0; +bool ResourceSaver::timestamp_on_save = false; +ResourceSavedCallback ResourceSaver::save_callback = 0; -Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - String extension=p_path.get_extension(); - Error err=ERR_FILE_UNRECOGNIZED; + String extension = p_path.get_extension(); + Error err = ERR_FILE_UNRECOGNIZED; - for (int i=0;i<saver_count;i++) { + for (int i = 0; i < saver_count; i++) { if (!saver[i]->recognize(p_resource)) continue; List<String> extensions; - bool recognized=false; - saver[i]->get_recognized_extensions(p_resource,&extensions); + bool recognized = false; + saver[i]->get_recognized_extensions(p_resource, &extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(extension.get_extension())==0) - recognized=true; + if (E->get().nocasecmp_to(extension.get_extension()) == 0) + recognized = true; } if (!recognized) continue; - String old_path=p_resource->get_path(); + String old_path = p_resource->get_path(); - - String local_path=GlobalConfig::get_singleton()->localize_path(p_path); + String local_path = GlobalConfig::get_singleton()->localize_path(p_path); RES rwcopy = p_resource; - if (p_flags&FLAG_CHANGE_PATH) + if (p_flags & FLAG_CHANGE_PATH) rwcopy->set_path(local_path); - err = saver[i]->save(p_path,p_resource,p_flags); + err = saver[i]->save(p_path, p_resource, p_flags); - if (err == OK ) { + if (err == OK) { #ifdef TOOLS_ENABLED - ((Resource*)p_resource.ptr())->set_edited(false); + ((Resource *)p_resource.ptr())->set_edited(false); if (timestamp_on_save) { uint64_t mt = FileAccess::get_modified_time(p_path); - ((Resource*)p_resource.ptr())->set_last_modified_time(mt); + ((Resource *)p_resource.ptr())->set_last_modified_time(mt); } #endif - if (p_flags&FLAG_CHANGE_PATH) + if (p_flags & FLAG_CHANGE_PATH) rwcopy->set_path(old_path); if (save_callback && p_path.begins_with("res://")) @@ -92,46 +91,36 @@ Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_ return OK; } else { - } } return err; } - void ResourceSaver::set_save_callback(ResourceSavedCallback p_callback) { - save_callback=p_callback; + save_callback = p_callback; } +void ResourceSaver::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) { -void ResourceSaver::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) { - - - for (int i=0;i<saver_count;i++) { + for (int i = 0; i < saver_count; i++) { - saver[i]->get_recognized_extensions(p_resource,p_extensions); + saver[i]->get_recognized_extensions(p_resource, p_extensions); } - } void ResourceSaver::add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front) { - ERR_FAIL_COND( saver_count >= MAX_SAVERS ); + ERR_FAIL_COND(saver_count >= MAX_SAVERS); if (p_at_front) { - for(int i=saver_count;i>0;i--) { - saver[i]=saver[i-1]; + for (int i = saver_count; i > 0; i--) { + saver[i] = saver[i - 1]; } - saver[0]=p_format_saver; + saver[0] = p_format_saver; saver_count++; } else { - saver[saver_count++]=p_format_saver; + saver[saver_count++] = p_format_saver; } - } - - - - diff --git a/core/io/resource_saver.h b/core/io/resource_saver.h index f00f074090..b9bb2aafae 100644 --- a/core/io/resource_saver.h +++ b/core/io/resource_saver.h @@ -35,27 +35,21 @@ @author Juan Linietsky <reduzio@gmail.com> */ - - - - - class ResourceFormatSaver { public: - - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0)=0; - virtual bool recognize(const RES& p_resource) const=0; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const=0; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0) = 0; + virtual bool recognize(const RES &p_resource) const = 0; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const = 0; virtual ~ResourceFormatSaver() {} }; -typedef void (*ResourceSavedCallback)(const String& p_path); +typedef void (*ResourceSavedCallback)(const String &p_path); class ResourceSaver { enum { - MAX_SAVERS=64 + MAX_SAVERS = 64 }; static ResourceFormatSaver *saver[MAX_SAVERS]; @@ -63,31 +57,24 @@ class ResourceSaver { static bool timestamp_on_save; static ResourceSavedCallback save_callback; - public: - enum SaverFlags { - FLAG_RELATIVE_PATHS=1, - FLAG_BUNDLE_RESOURCES=2, - FLAG_CHANGE_PATH=4, - FLAG_OMIT_EDITOR_PROPERTIES=8, - FLAG_SAVE_BIG_ENDIAN=16, - FLAG_COMPRESS=32, - FLAG_REPLACE_SUBRESOURCE_PATHS=64, + FLAG_RELATIVE_PATHS = 1, + FLAG_BUNDLE_RESOURCES = 2, + FLAG_CHANGE_PATH = 4, + FLAG_OMIT_EDITOR_PROPERTIES = 8, + FLAG_SAVE_BIG_ENDIAN = 16, + FLAG_COMPRESS = 32, + FLAG_REPLACE_SUBRESOURCE_PATHS = 64, }; + static Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + static void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions); + static void add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front = false); - static Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - static void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions); - static void add_resource_format_saver(ResourceFormatSaver *p_format_saver,bool p_at_front=false); - - static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save=p_timestamp; } + static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save = p_timestamp; } static void set_save_callback(ResourceSavedCallback p_callback); - - - }; - #endif diff --git a/core/io/stream_peer.cpp b/core/io/stream_peer.cpp index 3c4719269f..07df47f8c0 100644 --- a/core/io/stream_peer.cpp +++ b/core/io/stream_peer.cpp @@ -29,21 +29,21 @@ #include "stream_peer.h" #include "io/marshalls.h" -Error StreamPeer::_put_data(const PoolVector<uint8_t>& p_data) { +Error StreamPeer::_put_data(const PoolVector<uint8_t> &p_data) { int len = p_data.size(); - if (len==0) + if (len == 0) return OK; PoolVector<uint8_t>::Read r = p_data.read(); - return put_data(&r[0],len); + return put_data(&r[0], len); } -Array StreamPeer::_put_partial_data(const PoolVector<uint8_t>& p_data) { +Array StreamPeer::_put_partial_data(const PoolVector<uint8_t> &p_data) { Array ret; int len = p_data.size(); - if (len==0) { + if (len == 0) { ret.push_back(OK); ret.push_back(0); return ret; @@ -51,24 +51,23 @@ Array StreamPeer::_put_partial_data(const PoolVector<uint8_t>& p_data) { PoolVector<uint8_t>::Read r = p_data.read(); int sent; - Error err = put_partial_data(&r[0],len,sent); + Error err = put_partial_data(&r[0], len, sent); - if (err!=OK) { - sent=0; + if (err != OK) { + sent = 0; } ret.push_back(err); ret.push_back(sent); return ret; } - Array StreamPeer::_get_data(int p_bytes) { Array ret; PoolVector<uint8_t> data; data.resize(p_bytes); - if (data.size()!=p_bytes) { + if (data.size() != p_bytes) { ret.push_back(ERR_OUT_OF_MEMORY); ret.push_back(PoolVector<uint8_t>()); @@ -76,12 +75,11 @@ Array StreamPeer::_get_data(int p_bytes) { } PoolVector<uint8_t>::Write w = data.write(); - Error err = get_data(&w[0],p_bytes); + Error err = get_data(&w[0], p_bytes); w = PoolVector<uint8_t>::Write(); ret.push_back(err); ret.push_back(data); return ret; - } Array StreamPeer::_get_partial_data(int p_bytes) { @@ -90,7 +88,7 @@ Array StreamPeer::_get_partial_data(int p_bytes) { PoolVector<uint8_t> data; data.resize(p_bytes); - if (data.size()!=p_bytes) { + if (data.size() != p_bytes) { ret.push_back(ERR_OUT_OF_MEMORY); ret.push_back(PoolVector<uint8_t>()); @@ -99,12 +97,12 @@ Array StreamPeer::_get_partial_data(int p_bytes) { PoolVector<uint8_t>::Write w = data.write(); int received; - Error err = get_partial_data(&w[0],p_bytes,received); + Error err = get_partial_data(&w[0], p_bytes, received); w = PoolVector<uint8_t>::Write(); - if (err!=OK) { + if (err != OK) { data.resize(0); - } else if (received!=data.size()) { + } else if (received != data.size()) { data.resize(received); } @@ -112,12 +110,11 @@ Array StreamPeer::_get_partial_data(int p_bytes) { ret.push_back(err); ret.push_back(data); return ret; - } void StreamPeer::set_big_endian(bool p_enable) { - big_endian=p_enable; + big_endian = p_enable; } bool StreamPeer::is_big_endian_enabled() const { @@ -125,389 +122,359 @@ bool StreamPeer::is_big_endian_enabled() const { return big_endian; } - void StreamPeer::put_u8(uint8_t p_val) { - put_data((const uint8_t*)&p_val,1); - + put_data((const uint8_t *)&p_val, 1); } -void StreamPeer::put_8(int8_t p_val){ +void StreamPeer::put_8(int8_t p_val) { - put_data((const uint8_t*)&p_val,1); + put_data((const uint8_t *)&p_val, 1); } -void StreamPeer::put_u16(uint16_t p_val){ +void StreamPeer::put_u16(uint16_t p_val) { if (big_endian) { - p_val=BSWAP16(p_val); + p_val = BSWAP16(p_val); } uint8_t buf[2]; - encode_uint16(p_val,buf); - put_data(buf,2); - + encode_uint16(p_val, buf); + put_data(buf, 2); } -void StreamPeer::put_16(int16_t p_val){ +void StreamPeer::put_16(int16_t p_val) { if (big_endian) { - p_val=BSWAP16(p_val); + p_val = BSWAP16(p_val); } uint8_t buf[2]; - encode_uint16(p_val,buf); - put_data(buf,2); - + encode_uint16(p_val, buf); + put_data(buf, 2); } -void StreamPeer::put_u32(uint32_t p_val){ +void StreamPeer::put_u32(uint32_t p_val) { if (big_endian) { - p_val=BSWAP32(p_val); + p_val = BSWAP32(p_val); } uint8_t buf[4]; - encode_uint32(p_val,buf); - put_data(buf,4); - + encode_uint32(p_val, buf); + put_data(buf, 4); } -void StreamPeer::put_32(int32_t p_val){ +void StreamPeer::put_32(int32_t p_val) { if (big_endian) { - p_val=BSWAP32(p_val); + p_val = BSWAP32(p_val); } uint8_t buf[4]; - encode_uint32(p_val,buf); - put_data(buf,4); - + encode_uint32(p_val, buf); + put_data(buf, 4); } -void StreamPeer::put_u64(uint64_t p_val){ +void StreamPeer::put_u64(uint64_t p_val) { if (big_endian) { - p_val=BSWAP64(p_val); + p_val = BSWAP64(p_val); } uint8_t buf[8]; - encode_uint64(p_val,buf); - put_data(buf,8); - + encode_uint64(p_val, buf); + put_data(buf, 8); } -void StreamPeer::put_64(int64_t p_val){ +void StreamPeer::put_64(int64_t p_val) { if (big_endian) { - p_val=BSWAP64(p_val); + p_val = BSWAP64(p_val); } uint8_t buf[8]; - encode_uint64(p_val,buf); - put_data(buf,8); - + encode_uint64(p_val, buf); + put_data(buf, 8); } -void StreamPeer::put_float(float p_val){ +void StreamPeer::put_float(float p_val) { uint8_t buf[4]; - encode_float(p_val,buf); + encode_float(p_val, buf); if (big_endian) { - uint32_t *p32=(uint32_t *)buf; - *p32=BSWAP32(*p32); + uint32_t *p32 = (uint32_t *)buf; + *p32 = BSWAP32(*p32); } - put_data(buf,4); - + put_data(buf, 4); } -void StreamPeer::put_double(double p_val){ +void StreamPeer::put_double(double p_val) { uint8_t buf[8]; - encode_double(p_val,buf); + encode_double(p_val, buf); if (big_endian) { - uint64_t *p64=(uint64_t *)buf; - *p64=BSWAP64(*p64); + uint64_t *p64 = (uint64_t *)buf; + *p64 = BSWAP64(*p64); } - put_data(buf,8); - + put_data(buf, 8); } -void StreamPeer::put_utf8_string(const String& p_string) { +void StreamPeer::put_utf8_string(const String &p_string) { - CharString cs=p_string.utf8(); + CharString cs = p_string.utf8(); put_u32(p_string.length()); - put_data((const uint8_t*)cs.get_data(),cs.length()); - + put_data((const uint8_t *)cs.get_data(), cs.length()); } -void StreamPeer::put_var(const Variant& p_variant){ +void StreamPeer::put_var(const Variant &p_variant) { - int len=0; + int len = 0; Vector<uint8_t> buf; - encode_variant(p_variant,NULL,len); + encode_variant(p_variant, NULL, len); buf.resize(len); put_32(len); - encode_variant(p_variant,buf.ptr(),len); - put_data(buf.ptr(),buf.size()); - - + encode_variant(p_variant, buf.ptr(), len); + put_data(buf.ptr(), buf.size()); } -uint8_t StreamPeer::get_u8(){ +uint8_t StreamPeer::get_u8() { uint8_t buf[1]; - get_data(buf,1); + get_data(buf, 1); return buf[0]; } -int8_t StreamPeer::get_8(){ +int8_t StreamPeer::get_8() { uint8_t buf[1]; - get_data(buf,1); + get_data(buf, 1); return buf[0]; - } -uint16_t StreamPeer::get_u16(){ +uint16_t StreamPeer::get_u16() { uint8_t buf[2]; - get_data(buf,2); + get_data(buf, 2); uint16_t r = decode_uint16(buf); if (big_endian) { - r=BSWAP16(r); + r = BSWAP16(r); } return r; - } -int16_t StreamPeer::get_16(){ +int16_t StreamPeer::get_16() { uint8_t buf[2]; - get_data(buf,2); + get_data(buf, 2); uint16_t r = decode_uint16(buf); if (big_endian) { - r=BSWAP16(r); + r = BSWAP16(r); } return r; - } -uint32_t StreamPeer::get_u32(){ +uint32_t StreamPeer::get_u32() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); uint32_t r = decode_uint32(buf); if (big_endian) { - r=BSWAP32(r); + r = BSWAP32(r); } return r; - } -int32_t StreamPeer::get_32(){ +int32_t StreamPeer::get_32() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); uint32_t r = decode_uint32(buf); if (big_endian) { - r=BSWAP32(r); + r = BSWAP32(r); } return r; - } -uint64_t StreamPeer::get_u64(){ +uint64_t StreamPeer::get_u64() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); uint64_t r = decode_uint64(buf); if (big_endian) { - r=BSWAP64(r); + r = BSWAP64(r); } return r; - } -int64_t StreamPeer::get_64(){ +int64_t StreamPeer::get_64() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); uint64_t r = decode_uint64(buf); if (big_endian) { - r=BSWAP64(r); + r = BSWAP64(r); } return r; - } -float StreamPeer::get_float(){ +float StreamPeer::get_float() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); if (big_endian) { - uint32_t *p32=(uint32_t *)buf; - *p32=BSWAP32(*p32); + uint32_t *p32 = (uint32_t *)buf; + *p32 = BSWAP32(*p32); } return decode_float(buf); } -float StreamPeer::get_double(){ +float StreamPeer::get_double() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); if (big_endian) { - uint64_t *p64=(uint64_t *)buf; - *p64=BSWAP64(*p64); + uint64_t *p64 = (uint64_t *)buf; + *p64 = BSWAP64(*p64); } return decode_double(buf); - } -String StreamPeer::get_string(int p_bytes){ +String StreamPeer::get_string(int p_bytes) { - ERR_FAIL_COND_V(p_bytes<0,String()); + ERR_FAIL_COND_V(p_bytes < 0, String()); Vector<char> buf; - Error err = buf.resize(p_bytes+1); - ERR_FAIL_COND_V(err!=OK,String()); - err = get_data((uint8_t*)&buf[0],p_bytes); - ERR_FAIL_COND_V(err!=OK,String()); - buf[p_bytes]=0; + Error err = buf.resize(p_bytes + 1); + ERR_FAIL_COND_V(err != OK, String()); + err = get_data((uint8_t *)&buf[0], p_bytes); + ERR_FAIL_COND_V(err != OK, String()); + buf[p_bytes] = 0; return buf.ptr(); - } -String StreamPeer::get_utf8_string(int p_bytes){ +String StreamPeer::get_utf8_string(int p_bytes) { - ERR_FAIL_COND_V(p_bytes<0,String()); + ERR_FAIL_COND_V(p_bytes < 0, String()); Vector<uint8_t> buf; Error err = buf.resize(p_bytes); - ERR_FAIL_COND_V(err!=OK,String()); - err = get_data(buf.ptr(),p_bytes); - ERR_FAIL_COND_V(err!=OK,String()); + ERR_FAIL_COND_V(err != OK, String()); + err = get_data(buf.ptr(), p_bytes); + ERR_FAIL_COND_V(err != OK, String()); String ret; - ret.parse_utf8((const char*)buf.ptr(),buf.size()); + ret.parse_utf8((const char *)buf.ptr(), buf.size()); return ret; - } -Variant StreamPeer::get_var(){ +Variant StreamPeer::get_var() { int len = get_32(); Vector<uint8_t> var; Error err = var.resize(len); - ERR_FAIL_COND_V(err!=OK,Variant()); - err = get_data(var.ptr(),len); - ERR_FAIL_COND_V(err!=OK,Variant()); + ERR_FAIL_COND_V(err != OK, Variant()); + err = get_data(var.ptr(), len); + ERR_FAIL_COND_V(err != OK, Variant()); Variant ret; - decode_variant(ret,var.ptr(),len); + decode_variant(ret, var.ptr(), len); return ret; } - void StreamPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("put_data","data"),&StreamPeer::_put_data); - ClassDB::bind_method(D_METHOD("put_partial_data","data"),&StreamPeer::_put_partial_data); - - ClassDB::bind_method(D_METHOD("get_data","bytes"),&StreamPeer::_get_data); - ClassDB::bind_method(D_METHOD("get_partial_data","bytes"),&StreamPeer::_get_partial_data); - - ClassDB::bind_method(D_METHOD("get_available_bytes"),&StreamPeer::get_available_bytes); - - ClassDB::bind_method(D_METHOD("set_big_endian","enable"),&StreamPeer::set_big_endian); - ClassDB::bind_method(D_METHOD("is_big_endian_enabled"),&StreamPeer::is_big_endian_enabled); - - ClassDB::bind_method(D_METHOD("put_8","val"),&StreamPeer::put_8); - ClassDB::bind_method(D_METHOD("put_u8","val"),&StreamPeer::put_u8); - ClassDB::bind_method(D_METHOD("put_16","val"),&StreamPeer::put_16); - ClassDB::bind_method(D_METHOD("put_u16","val"),&StreamPeer::put_u16); - ClassDB::bind_method(D_METHOD("put_32","val"),&StreamPeer::put_32); - ClassDB::bind_method(D_METHOD("put_u32","val"),&StreamPeer::put_u32); - ClassDB::bind_method(D_METHOD("put_64","val"),&StreamPeer::put_64); - ClassDB::bind_method(D_METHOD("put_u64","val"),&StreamPeer::put_u64); - ClassDB::bind_method(D_METHOD("put_float","val"),&StreamPeer::put_float); - ClassDB::bind_method(D_METHOD("put_double","val"),&StreamPeer::put_double); - ClassDB::bind_method(D_METHOD("put_utf8_string","val"),&StreamPeer::put_utf8_string); - ClassDB::bind_method(D_METHOD("put_var","val:Variant"),&StreamPeer::put_var); - - ClassDB::bind_method(D_METHOD("get_8"),&StreamPeer::get_8); - ClassDB::bind_method(D_METHOD("get_u8"),&StreamPeer::get_u8); - ClassDB::bind_method(D_METHOD("get_16"),&StreamPeer::get_16); - ClassDB::bind_method(D_METHOD("get_u16"),&StreamPeer::get_u16); - ClassDB::bind_method(D_METHOD("get_32"),&StreamPeer::get_32); - ClassDB::bind_method(D_METHOD("get_u32"),&StreamPeer::get_u32); - ClassDB::bind_method(D_METHOD("get_64"),&StreamPeer::get_64); - ClassDB::bind_method(D_METHOD("get_u64"),&StreamPeer::get_u64); - ClassDB::bind_method(D_METHOD("get_float"),&StreamPeer::get_float); - ClassDB::bind_method(D_METHOD("get_double"),&StreamPeer::get_double); - ClassDB::bind_method(D_METHOD("get_string","bytes"),&StreamPeer::get_string); - ClassDB::bind_method(D_METHOD("get_utf8_string","bytes"),&StreamPeer::get_utf8_string); - ClassDB::bind_method(D_METHOD("get_var:Variant"),&StreamPeer::get_var); + ClassDB::bind_method(D_METHOD("put_data", "data"), &StreamPeer::_put_data); + ClassDB::bind_method(D_METHOD("put_partial_data", "data"), &StreamPeer::_put_partial_data); + + ClassDB::bind_method(D_METHOD("get_data", "bytes"), &StreamPeer::_get_data); + ClassDB::bind_method(D_METHOD("get_partial_data", "bytes"), &StreamPeer::_get_partial_data); + + ClassDB::bind_method(D_METHOD("get_available_bytes"), &StreamPeer::get_available_bytes); + + ClassDB::bind_method(D_METHOD("set_big_endian", "enable"), &StreamPeer::set_big_endian); + ClassDB::bind_method(D_METHOD("is_big_endian_enabled"), &StreamPeer::is_big_endian_enabled); + + ClassDB::bind_method(D_METHOD("put_8", "val"), &StreamPeer::put_8); + ClassDB::bind_method(D_METHOD("put_u8", "val"), &StreamPeer::put_u8); + ClassDB::bind_method(D_METHOD("put_16", "val"), &StreamPeer::put_16); + ClassDB::bind_method(D_METHOD("put_u16", "val"), &StreamPeer::put_u16); + ClassDB::bind_method(D_METHOD("put_32", "val"), &StreamPeer::put_32); + ClassDB::bind_method(D_METHOD("put_u32", "val"), &StreamPeer::put_u32); + ClassDB::bind_method(D_METHOD("put_64", "val"), &StreamPeer::put_64); + ClassDB::bind_method(D_METHOD("put_u64", "val"), &StreamPeer::put_u64); + ClassDB::bind_method(D_METHOD("put_float", "val"), &StreamPeer::put_float); + ClassDB::bind_method(D_METHOD("put_double", "val"), &StreamPeer::put_double); + ClassDB::bind_method(D_METHOD("put_utf8_string", "val"), &StreamPeer::put_utf8_string); + ClassDB::bind_method(D_METHOD("put_var", "val:Variant"), &StreamPeer::put_var); + + ClassDB::bind_method(D_METHOD("get_8"), &StreamPeer::get_8); + ClassDB::bind_method(D_METHOD("get_u8"), &StreamPeer::get_u8); + ClassDB::bind_method(D_METHOD("get_16"), &StreamPeer::get_16); + ClassDB::bind_method(D_METHOD("get_u16"), &StreamPeer::get_u16); + ClassDB::bind_method(D_METHOD("get_32"), &StreamPeer::get_32); + ClassDB::bind_method(D_METHOD("get_u32"), &StreamPeer::get_u32); + ClassDB::bind_method(D_METHOD("get_64"), &StreamPeer::get_64); + ClassDB::bind_method(D_METHOD("get_u64"), &StreamPeer::get_u64); + ClassDB::bind_method(D_METHOD("get_float"), &StreamPeer::get_float); + ClassDB::bind_method(D_METHOD("get_double"), &StreamPeer::get_double); + ClassDB::bind_method(D_METHOD("get_string", "bytes"), &StreamPeer::get_string); + ClassDB::bind_method(D_METHOD("get_utf8_string", "bytes"), &StreamPeer::get_utf8_string); + ClassDB::bind_method(D_METHOD("get_var:Variant"), &StreamPeer::get_var); } //////////////////////////////// - void StreamPeerBuffer::_bind_methods() { - ClassDB::bind_method(D_METHOD("seek","pos"),&StreamPeerBuffer::seek); - ClassDB::bind_method(D_METHOD("get_size"),&StreamPeerBuffer::get_size); - ClassDB::bind_method(D_METHOD("get_pos"),&StreamPeerBuffer::get_pos); - ClassDB::bind_method(D_METHOD("resize","size"),&StreamPeerBuffer::resize); - ClassDB::bind_method(D_METHOD("set_data_array","data"),&StreamPeerBuffer::set_data_array); - ClassDB::bind_method(D_METHOD("get_data_array"),&StreamPeerBuffer::get_data_array); - ClassDB::bind_method(D_METHOD("clear"),&StreamPeerBuffer::clear); - ClassDB::bind_method(D_METHOD("duplicate:StreamPeerBuffer"),&StreamPeerBuffer::duplicate); - + ClassDB::bind_method(D_METHOD("seek", "pos"), &StreamPeerBuffer::seek); + ClassDB::bind_method(D_METHOD("get_size"), &StreamPeerBuffer::get_size); + ClassDB::bind_method(D_METHOD("get_pos"), &StreamPeerBuffer::get_pos); + ClassDB::bind_method(D_METHOD("resize", "size"), &StreamPeerBuffer::resize); + ClassDB::bind_method(D_METHOD("set_data_array", "data"), &StreamPeerBuffer::set_data_array); + ClassDB::bind_method(D_METHOD("get_data_array"), &StreamPeerBuffer::get_data_array); + ClassDB::bind_method(D_METHOD("clear"), &StreamPeerBuffer::clear); + ClassDB::bind_method(D_METHOD("duplicate:StreamPeerBuffer"), &StreamPeerBuffer::duplicate); } +Error StreamPeerBuffer::put_data(const uint8_t *p_data, int p_bytes) { -Error StreamPeerBuffer::put_data(const uint8_t* p_data,int p_bytes) { - - if (p_bytes<=0) + if (p_bytes <= 0) return OK; - if (pointer+p_bytes > data.size()) { - data.resize(pointer+p_bytes); - + if (pointer + p_bytes > data.size()) { + data.resize(pointer + p_bytes); } PoolVector<uint8_t>::Write w = data.write(); - copymem(&w[pointer],p_data,p_bytes); + copymem(&w[pointer], p_data, p_bytes); - pointer+=p_bytes; + pointer += p_bytes; return OK; } -Error StreamPeerBuffer::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent){ +Error StreamPeerBuffer::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) { - r_sent=p_bytes; - return put_data(p_data,p_bytes); + r_sent = p_bytes; + return put_data(p_data, p_bytes); } -Error StreamPeerBuffer::get_data(uint8_t* p_buffer, int p_bytes){ +Error StreamPeerBuffer::get_data(uint8_t *p_buffer, int p_bytes) { int recv; - get_partial_data(p_buffer,p_bytes,recv); - if (recv!=p_bytes) + get_partial_data(p_buffer, p_bytes, recv); + if (recv != p_bytes) return ERR_INVALID_PARAMETER; return OK; - } -Error StreamPeerBuffer::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received){ - +Error StreamPeerBuffer::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) { - if (pointer+p_bytes > data.size()) { - r_received=data.size()-pointer; - if (r_received<=0) { - r_received=0; + if (pointer + p_bytes > data.size()) { + r_received = data.size() - pointer; + if (r_received <= 0) { + r_received = 0; return OK; //you got 0 } } else { - r_received=p_bytes; + r_received = p_bytes; } PoolVector<uint8_t>::Read r = data.read(); - copymem(p_buffer,r.ptr(),r_received); - + copymem(p_buffer, r.ptr(), r_received); + // FIXME: return what? OK or ERR_* } int StreamPeerBuffer::get_available_bytes() const { - return data.size()-pointer; + return data.size() - pointer; } -void StreamPeerBuffer::seek(int p_pos){ +void StreamPeerBuffer::seek(int p_pos) { ERR_FAIL_COND(p_pos < 0); ERR_FAIL_COND(p_pos > data.size()); - pointer=p_pos; + pointer = p_pos; } -int StreamPeerBuffer::get_size() const{ +int StreamPeerBuffer::get_size() const { return data.size(); } @@ -517,40 +484,37 @@ int StreamPeerBuffer::get_pos() const { return pointer; } -void StreamPeerBuffer::resize(int p_size){ +void StreamPeerBuffer::resize(int p_size) { data.resize(p_size); } -void StreamPeerBuffer::set_data_array(const PoolVector<uint8_t> & p_data){ +void StreamPeerBuffer::set_data_array(const PoolVector<uint8_t> &p_data) { - data=p_data; - pointer=0; + data = p_data; + pointer = 0; } -PoolVector<uint8_t> StreamPeerBuffer::get_data_array() const{ +PoolVector<uint8_t> StreamPeerBuffer::get_data_array() const { return data; } - void StreamPeerBuffer::clear() { data.resize(0); - pointer=0; + pointer = 0; } - Ref<StreamPeerBuffer> StreamPeerBuffer::duplicate() const { Ref<StreamPeerBuffer> spb; spb.instance(); - spb->data=data; + spb->data = data; return spb; } - StreamPeerBuffer::StreamPeerBuffer() { - pointer=0; + pointer = 0; } diff --git a/core/io/stream_peer.h b/core/io/stream_peer.h index eb0f90ba50..7c20d10b10 100644 --- a/core/io/stream_peer.h +++ b/core/io/stream_peer.h @@ -32,14 +32,15 @@ #include "reference.h" class StreamPeer : public Reference { - GDCLASS( StreamPeer, Reference ); + GDCLASS(StreamPeer, Reference); OBJ_CATEGORY("Networking"); + protected: static void _bind_methods(); //bind helpers - Error _put_data(const PoolVector<uint8_t>& p_data); - Array _put_partial_data(const PoolVector<uint8_t>& p_data); + Error _put_data(const PoolVector<uint8_t> &p_data); + Array _put_partial_data(const PoolVector<uint8_t> &p_data); Array _get_data(int p_bytes); Array _get_partial_data(int p_bytes); @@ -47,14 +48,13 @@ protected: bool big_endian; public: + virtual Error put_data(const uint8_t *p_data, int p_bytes) = 0; ///< put a whole chunk of data, blocking until it sent + virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) = 0; ///< put as much data as possible, without blocking. - virtual Error put_data(const uint8_t* p_data,int p_bytes)=0; ///< put a whole chunk of data, blocking until it sent - virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent)=0; ///< put as much data as possible, without blocking. - - virtual Error get_data(uint8_t* p_buffer, int p_bytes)=0; ///< read p_bytes of data, if p_bytes > available, it will block - virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received)=0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received + virtual Error get_data(uint8_t *p_buffer, int p_bytes) = 0; ///< read p_bytes of data, if p_bytes > available, it will block + virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) = 0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received - virtual int get_available_bytes() const=0; + virtual int get_available_bytes() const = 0; void set_big_endian(bool p_enable); bool is_big_endian_enabled() const; @@ -69,8 +69,8 @@ public: void put_u64(uint64_t p_val); void put_float(float p_val); void put_double(double p_val); - void put_utf8_string(const String& p_string); - void put_var(const Variant& p_variant); + void put_utf8_string(const String &p_string); + void put_var(const Variant &p_variant); uint8_t get_u8(); int8_t get_8(); @@ -86,27 +86,25 @@ public: String get_utf8_string(int p_bytes); Variant get_var(); - - - StreamPeer() { big_endian=false; } + StreamPeer() { big_endian = false; } }; - class StreamPeerBuffer : public StreamPeer { - GDCLASS(StreamPeerBuffer,StreamPeer); + GDCLASS(StreamPeerBuffer, StreamPeer); PoolVector<uint8_t> data; int pointer; -protected: +protected: static void _bind_methods(); + public: - Error put_data(const uint8_t* p_data,int p_bytes); - Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent); + Error put_data(const uint8_t *p_data, int p_bytes); + Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent); - Error get_data(uint8_t* p_buffer, int p_bytes); - Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received); + Error get_data(uint8_t *p_buffer, int p_bytes); + Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received); virtual int get_available_bytes() const; @@ -115,8 +113,7 @@ public: int get_pos() const; void resize(int p_size); - - void set_data_array(const PoolVector<uint8_t> & p_data); + void set_data_array(const PoolVector<uint8_t> &p_data); PoolVector<uint8_t> get_data_array() const; void clear(); @@ -126,5 +123,4 @@ public: StreamPeerBuffer(); }; - #endif // STREAM_PEER_H diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp index 5f7247bd7a..6db6eb30ed 100644 --- a/core/io/stream_peer_ssl.cpp +++ b/core/io/stream_peer_ssl.cpp @@ -28,24 +28,18 @@ /*************************************************************************/ #include "stream_peer_ssl.h" - -StreamPeerSSL* (*StreamPeerSSL::_create)()=NULL; - - - +StreamPeerSSL *(*StreamPeerSSL::_create)() = NULL; StreamPeerSSL *StreamPeerSSL::create() { return _create(); } +StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func = NULL; +bool StreamPeerSSL::available = false; +bool StreamPeerSSL::initialize_certs = true; - -StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func=NULL; -bool StreamPeerSSL::available=false; -bool StreamPeerSSL::initialize_certs=true; - -void StreamPeerSSL::load_certs_from_memory(const PoolByteArray& p_memory) { +void StreamPeerSSL::load_certs_from_memory(const PoolByteArray &p_memory) { if (load_certs_func) load_certs_func(p_memory); } @@ -56,18 +50,15 @@ bool StreamPeerSSL::is_available() { void StreamPeerSSL::_bind_methods() { - - ClassDB::bind_method(D_METHOD("accept_stream:Error","stream:StreamPeer"),&StreamPeerSSL::accept_stream); - ClassDB::bind_method(D_METHOD("connect_to_stream:Error","stream:StreamPeer","validate_certs","for_hostname"),&StreamPeerSSL::connect_to_stream,DEFVAL(false),DEFVAL(String())); - ClassDB::bind_method(D_METHOD("get_status"),&StreamPeerSSL::get_status); - ClassDB::bind_method(D_METHOD("disconnect_from_stream"),&StreamPeerSSL::disconnect_from_stream); - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR_NO_CERTIFICATE ); - BIND_CONSTANT( STATUS_ERROR_HOSTNAME_MISMATCH ); - + ClassDB::bind_method(D_METHOD("accept_stream:Error", "stream:StreamPeer"), &StreamPeerSSL::accept_stream); + ClassDB::bind_method(D_METHOD("connect_to_stream:Error", "stream:StreamPeer", "validate_certs", "for_hostname"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String())); + ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerSSL::get_status); + ClassDB::bind_method(D_METHOD("disconnect_from_stream"), &StreamPeerSSL::disconnect_from_stream); + BIND_CONSTANT(STATUS_DISCONNECTED); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR_NO_CERTIFICATE); + BIND_CONSTANT(STATUS_ERROR_HOSTNAME_MISMATCH); } -StreamPeerSSL::StreamPeerSSL() -{ +StreamPeerSSL::StreamPeerSSL() { } diff --git a/core/io/stream_peer_ssl.h b/core/io/stream_peer_ssl.h index 9aafac874d..468cef66a2 100644 --- a/core/io/stream_peer_ssl.h +++ b/core/io/stream_peer_ssl.h @@ -32,24 +32,22 @@ #include "io/stream_peer.h" class StreamPeerSSL : public StreamPeer { - GDCLASS(StreamPeerSSL,StreamPeer); + GDCLASS(StreamPeerSSL, StreamPeer); + public: + typedef void (*LoadCertsFromMemory)(const PoolByteArray &p_certs); - typedef void (*LoadCertsFromMemory)(const PoolByteArray& p_certs); protected: - static StreamPeerSSL* (*_create)(); + static StreamPeerSSL *(*_create)(); static void _bind_methods(); static LoadCertsFromMemory load_certs_func; static bool available; - -friend class Main; + friend class Main; static bool initialize_certs; public: - - enum Status { STATUS_DISCONNECTED, STATUS_CONNECTED, @@ -57,20 +55,20 @@ public: STATUS_ERROR_HOSTNAME_MISMATCH }; - virtual Error accept_stream(Ref<StreamPeer> p_base)=0; - virtual Error connect_to_stream(Ref<StreamPeer> p_base,bool p_validate_certs=false,const String& p_for_hostname=String())=0; - virtual Status get_status() const=0; + virtual Error accept_stream(Ref<StreamPeer> p_base) = 0; + virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0; + virtual Status get_status() const = 0; - virtual void disconnect_from_stream()=0; + virtual void disconnect_from_stream() = 0; - static StreamPeerSSL* create(); + static StreamPeerSSL *create(); - static void load_certs_from_memory(const PoolByteArray& p_memory); + static void load_certs_from_memory(const PoolByteArray &p_memory); static bool is_available(); StreamPeerSSL(); }; -VARIANT_ENUM_CAST( StreamPeerSSL::Status ); +VARIANT_ENUM_CAST(StreamPeerSSL::Status); #endif // STREAM_PEER_SSL_H diff --git a/core/io/stream_peer_tcp.cpp b/core/io/stream_peer_tcp.cpp index cedc33079e..db5952e16f 100644 --- a/core/io/stream_peer_tcp.cpp +++ b/core/io/stream_peer_tcp.cpp @@ -28,37 +28,36 @@ /*************************************************************************/ #include "stream_peer_tcp.h" -StreamPeerTCP* (*StreamPeerTCP::_create)()=NULL; +StreamPeerTCP *(*StreamPeerTCP::_create)() = NULL; -Error StreamPeerTCP::_connect(const String& p_address,int p_port) { +Error StreamPeerTCP::_connect(const String &p_address, int p_port) { IP_Address ip; if (p_address.is_valid_ip_address()) { - ip=p_address; + ip = p_address; } else { - ip=IP::get_singleton()->resolve_hostname(p_address); + ip = IP::get_singleton()->resolve_hostname(p_address); if (!ip.is_valid()) return ERR_CANT_RESOLVE; } - connect_to_host(ip,p_port); + connect_to_host(ip, p_port); return OK; } void StreamPeerTCP::_bind_methods() { - ClassDB::bind_method(D_METHOD("connect_to_host","host","port"),&StreamPeerTCP::_connect); - ClassDB::bind_method(D_METHOD("is_connected_to_host"),&StreamPeerTCP::is_connected_to_host); - ClassDB::bind_method(D_METHOD("get_status"),&StreamPeerTCP::get_status); - ClassDB::bind_method(D_METHOD("get_connected_host"),&StreamPeerTCP::get_connected_host); - ClassDB::bind_method(D_METHOD("get_connected_port"),&StreamPeerTCP::get_connected_port); - ClassDB::bind_method(D_METHOD("disconnect_from_host"),&StreamPeerTCP::disconnect_from_host); - - BIND_CONSTANT( STATUS_NONE ); - BIND_CONSTANT( STATUS_CONNECTING ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR ); - + ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port"), &StreamPeerTCP::_connect); + ClassDB::bind_method(D_METHOD("is_connected_to_host"), &StreamPeerTCP::is_connected_to_host); + ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerTCP::get_status); + ClassDB::bind_method(D_METHOD("get_connected_host"), &StreamPeerTCP::get_connected_host); + ClassDB::bind_method(D_METHOD("get_connected_port"), &StreamPeerTCP::get_connected_port); + ClassDB::bind_method(D_METHOD("disconnect_from_host"), &StreamPeerTCP::disconnect_from_host); + + BIND_CONSTANT(STATUS_NONE); + BIND_CONSTANT(STATUS_CONNECTING); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR); } Ref<StreamPeerTCP> StreamPeerTCP::create_ref() { @@ -68,7 +67,7 @@ Ref<StreamPeerTCP> StreamPeerTCP::create_ref() { return Ref<StreamPeerTCP>(_create()); } -StreamPeerTCP* StreamPeerTCP::create() { +StreamPeerTCP *StreamPeerTCP::create() { if (!_create) return NULL; @@ -76,10 +75,8 @@ StreamPeerTCP* StreamPeerTCP::create() { } StreamPeerTCP::StreamPeerTCP() { - } -StreamPeerTCP::~StreamPeerTCP() { +StreamPeerTCP::~StreamPeerTCP(){ }; - diff --git a/core/io/stream_peer_tcp.h b/core/io/stream_peer_tcp.h index 4401378743..1733619a1c 100644 --- a/core/io/stream_peer_tcp.h +++ b/core/io/stream_peer_tcp.h @@ -31,16 +31,15 @@ #include "stream_peer.h" -#include "ip_address.h" #include "io/ip.h" +#include "ip_address.h" class StreamPeerTCP : public StreamPeer { - GDCLASS( StreamPeerTCP, StreamPeer ); + GDCLASS(StreamPeerTCP, StreamPeer); OBJ_CATEGORY("Networking"); public: - enum Status { STATUS_NONE, @@ -50,31 +49,29 @@ public: }; protected: - - virtual Error _connect(const String& p_address, int p_port); - static StreamPeerTCP* (*_create)(); + virtual Error _connect(const String &p_address, int p_port); + static StreamPeerTCP *(*_create)(); static void _bind_methods(); public: - - virtual Error connect_to_host(const IP_Address& p_host, uint16_t p_port)=0; + virtual Error connect_to_host(const IP_Address &p_host, uint16_t p_port) = 0; //read/write from streampeer - virtual bool is_connected_to_host() const=0; - virtual Status get_status() const=0; - virtual void disconnect_from_host()=0; - virtual IP_Address get_connected_host() const=0; - virtual uint16_t get_connected_port() const=0; - virtual void set_nodelay(bool p_enabled)=0; + virtual bool is_connected_to_host() const = 0; + virtual Status get_status() const = 0; + virtual void disconnect_from_host() = 0; + virtual IP_Address get_connected_host() const = 0; + virtual uint16_t get_connected_port() const = 0; + virtual void set_nodelay(bool p_enabled) = 0; static Ref<StreamPeerTCP> create_ref(); - static StreamPeerTCP* create(); + static StreamPeerTCP *create(); StreamPeerTCP(); ~StreamPeerTCP(); }; -VARIANT_ENUM_CAST( StreamPeerTCP::Status ); +VARIANT_ENUM_CAST(StreamPeerTCP::Status); #endif diff --git a/core/io/tcp_server.cpp b/core/io/tcp_server.cpp index 5127bd6e3b..f602b569ad 100644 --- a/core/io/tcp_server.cpp +++ b/core/io/tcp_server.cpp @@ -28,7 +28,7 @@ /*************************************************************************/ #include "tcp_server.h" -TCP_Server* (*TCP_Server::_create)()=NULL; +TCP_Server *(*TCP_Server::_create)() = NULL; Ref<TCP_Server> TCP_Server::create_ref() { @@ -37,7 +37,7 @@ Ref<TCP_Server> TCP_Server::create_ref() { return Ref<TCP_Server>(_create()); } -TCP_Server* TCP_Server::create() { +TCP_Server *TCP_Server::create() { if (!_create) return NULL; @@ -46,15 +46,11 @@ TCP_Server* TCP_Server::create() { void TCP_Server::_bind_methods() { - ClassDB::bind_method(D_METHOD("listen","port","bind_address"),&TCP_Server::listen,DEFVAL("*")); - ClassDB::bind_method(D_METHOD("is_connection_available"),&TCP_Server::is_connection_available); - ClassDB::bind_method(D_METHOD("take_connection"),&TCP_Server::take_connection); - ClassDB::bind_method(D_METHOD("stop"),&TCP_Server::stop); - + ClassDB::bind_method(D_METHOD("listen", "port", "bind_address"), &TCP_Server::listen, DEFVAL("*")); + ClassDB::bind_method(D_METHOD("is_connection_available"), &TCP_Server::is_connection_available); + ClassDB::bind_method(D_METHOD("take_connection"), &TCP_Server::take_connection); + ClassDB::bind_method(D_METHOD("stop"), &TCP_Server::stop); } - -TCP_Server::TCP_Server() -{ - +TCP_Server::TCP_Server() { } diff --git a/core/io/tcp_server.h b/core/io/tcp_server.h index 3cbd8c58cf..736aa16f99 100644 --- a/core/io/tcp_server.h +++ b/core/io/tcp_server.h @@ -29,29 +29,29 @@ #ifndef TCP_SERVER_H #define TCP_SERVER_H -#include "io/stream_peer.h" #include "io/ip.h" +#include "io/stream_peer.h" #include "stream_peer_tcp.h" class TCP_Server : public Reference { - GDCLASS( TCP_Server, Reference ); -protected: + GDCLASS(TCP_Server, Reference); - static TCP_Server* (*_create)(); +protected: + static TCP_Server *(*_create)(); //bind helper static void _bind_methods(); -public: - virtual Error listen(uint16_t p_port, const IP_Address p_bind_address=IP_Address("*"))=0; - virtual bool is_connection_available() const=0; - virtual Ref<StreamPeerTCP> take_connection()=0; +public: + virtual Error listen(uint16_t p_port, const IP_Address p_bind_address = IP_Address("*")) = 0; + virtual bool is_connection_available() const = 0; + virtual Ref<StreamPeerTCP> take_connection() = 0; - virtual void stop()=0; //stop listening + virtual void stop() = 0; //stop listening static Ref<TCP_Server> create_ref(); - static TCP_Server* create(); + static TCP_Server *create(); TCP_Server(); }; diff --git a/core/io/translation_loader_po.cpp b/core/io/translation_loader_po.cpp index bee38e037f..4da661e675 100644 --- a/core/io/translation_loader_po.cpp +++ b/core/io/translation_loader_po.cpp @@ -30,7 +30,6 @@ #include "os/file_access.h" #include "translation.h" - RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) { enum Status { @@ -40,175 +39,169 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S STATUS_READING_STRING, }; - Status status=STATUS_NONE; + Status status = STATUS_NONE; String msg_id; String msg_str; String config; if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; - Ref<Translation> translation = Ref<Translation>( memnew( Translation )); + Ref<Translation> translation = Ref<Translation>(memnew(Translation)); int line = 1; - while(true) { + while (true) { String l = f->get_line(); if (f->eof_reached()) { - if ( status == STATUS_READING_STRING) { + if (status == STATUS_READING_STRING) { - if (msg_id!="") - translation->add_message(msg_id,msg_str); - else if (config=="") - config=msg_str; + if (msg_id != "") + translation->add_message(msg_id, msg_str); + else if (config == "") + config = msg_str; break; - } else if ( status==STATUS_NONE) + } else if (status == STATUS_NONE) break; memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected EOF while reading 'msgid' at file: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: "); ERR_FAIL_V(RES()); } - l=l.strip_edges(); + l = l.strip_edges(); if (l.begins_with("msgid")) { - if (status==STATUS_READING_ID) { + if (status == STATUS_READING_ID) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgid', was expecting 'msgstr' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: "); ERR_FAIL_V(RES()); } - if (msg_id!="") - translation->add_message(msg_id,msg_str); - else if (config=="") - config=msg_str; + if (msg_id != "") + translation->add_message(msg_id, msg_str); + else if (config == "") + config = msg_str; - l=l.substr(5,l.length()).strip_edges(); - status=STATUS_READING_ID; - msg_id=""; - msg_str=""; + l = l.substr(5, l.length()).strip_edges(); + status = STATUS_READING_ID; + msg_id = ""; + msg_str = ""; } if (l.begins_with("msgstr")) { - if (status!=STATUS_READING_ID) { + if (status != STATUS_READING_ID) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgstr', was expecting 'msgid' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: "); ERR_FAIL_V(RES()); } - l=l.substr(6,l.length()).strip_edges(); - status=STATUS_READING_STRING; + l = l.substr(6, l.length()).strip_edges(); + status = STATUS_READING_STRING; } - if (l=="" || l.begins_with("#")) { + if (l == "" || l.begins_with("#")) { line++; continue; //nothing to read or comment } - if (!l.begins_with("\"") || status==STATUS_NONE) { + if (!l.begins_with("\"") || status == STATUS_NONE) { //not a string? failure! - ERR_EXPLAIN(p_path+":"+itos(line)+" Invalid line '"+l+"' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: "); ERR_FAIL_V(RES()); - } - l=l.substr(1,l.length()); + l = l.substr(1, l.length()); //find final quote - int end_pos=-1; - for(int i=0;i<l.length();i++) { + int end_pos = -1; + for (int i = 0; i < l.length(); i++) { - if (l[i]=='"' && (i==0 || l[i-1]!='\\')) { - end_pos=i; + if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) { + end_pos = i; break; } } - if (end_pos==-1) { - ERR_EXPLAIN(p_path+":"+itos(line)+" Expected '\"' at end of message while parsing file: "); + if (end_pos == -1) { + ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: "); ERR_FAIL_V(RES()); } - l=l.substr(0,end_pos); - l=l.c_unescape(); - + l = l.substr(0, end_pos); + l = l.c_unescape(); - if (status==STATUS_READING_ID) - msg_id+=l; + if (status == STATUS_READING_ID) + msg_id += l; else - msg_str+=l; + msg_str += l; line++; } - f->close(); memdelete(f); - if (config=="") { - ERR_EXPLAIN("No config found in file: "+p_path); + if (config == "") { + ERR_EXPLAIN("No config found in file: " + p_path); ERR_FAIL_V(RES()); } Vector<String> configs = config.split("\n"); - for(int i=0;i<configs.size();i++) { + for (int i = 0; i < configs.size(); i++) { String c = configs[i].strip_edges(); int p = c.find(":"); - if (p==-1) + if (p == -1) continue; - String prop = c.substr(0,p).strip_edges(); - String value = c.substr(p+1,c.length()).strip_edges(); + String prop = c.substr(0, p).strip_edges(); + String value = c.substr(p + 1, c.length()).strip_edges(); - if (prop=="X-Language") { + if (prop == "X-Language") { translation->set_locale(value); } } if (r_error) - *r_error=OK; + *r_error = OK; return translation; } -RES TranslationLoaderPO::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; - - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,RES()); - + *r_error = ERR_CANT_OPEN; - return load_translation(f,r_error); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, RES()); + return load_translation(f, r_error); } -void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const{ +void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("po"); //p_extensions->push_back("mo"); //mo in the future... } -bool TranslationLoaderPO::handles_type(const String& p_type) const{ +bool TranslationLoaderPO::handles_type(const String &p_type) const { - return (p_type=="Translation"); + return (p_type == "Translation"); } String TranslationLoaderPO::get_resource_type(const String &p_path) const { - if (p_path.get_extension().to_lower()=="po") + if (p_path.get_extension().to_lower() == "po") return "Translation"; return ""; } -TranslationLoaderPO::TranslationLoaderPO() -{ +TranslationLoaderPO::TranslationLoaderPO() { } diff --git a/core/io/translation_loader_po.h b/core/io/translation_loader_po.h index 127c8dafab..fe0440cb2a 100644 --- a/core/io/translation_loader_po.h +++ b/core/io/translation_loader_po.h @@ -30,18 +30,16 @@ #define TRANSLATION_LOADER_PO_H #include "io/resource_loader.h" -#include "translation.h" #include "os/file_access.h" +#include "translation.h" class TranslationLoaderPO : public ResourceFormatLoader { public: - - static RES load_translation(FileAccess *f, Error *r_error,const String& p_path=String()); - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + static RES load_translation(FileAccess *f, Error *r_error, const String &p_path = String()); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - TranslationLoaderPO(); }; diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp index 1a4ff1a8d4..e3b669409a 100644 --- a/core/io/xml_parser.cpp +++ b/core/io/xml_parser.cpp @@ -32,19 +32,18 @@ VARIANT_ENUM_CAST(XMLParser::NodeType); -static bool _equalsn(const CharType* str1, const CharType* str2, int len) { +static bool _equalsn(const CharType *str1, const CharType *str2, int len) { int i; - for(i=0; i < len && str1[i] && str2[i] ; ++i) - if (str1[i] != str2[i]) - return false; + for (i = 0; i < len && str1[i] && str2[i]; ++i) + if (str1[i] != str2[i]) + return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same lenght return (i == len) || (str1[i] == 0 && str2[i] == 0); } - -String XMLParser::_replace_special_characters(const String& origstr) { +String XMLParser::_replace_special_characters(const String &origstr) { int pos = origstr.find("&"); int oldPos = 0; @@ -54,30 +53,25 @@ String XMLParser::_replace_special_characters(const String& origstr) { String newstr; - while(pos != -1 && pos < origstr.length()-2) { + while (pos != -1 && pos < origstr.length() - 2) { // check if it is one of the special characters int specialChar = -1; - for (int i=0; i<(int)special_characters.size(); ++i) - { - const CharType* p = &origstr[pos]+1; + for (int i = 0; i < (int)special_characters.size(); ++i) { + const CharType *p = &origstr[pos] + 1; - if (_equalsn(&special_characters[i][1], p, special_characters[i].length()-1)) - { + if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) { specialChar = i; break; } } - if (specialChar != -1) - { - newstr+=(origstr.substr(oldPos, pos - oldPos)); - newstr+=(special_characters[specialChar][0]); + if (specialChar != -1) { + newstr += (origstr.substr(oldPos, pos - oldPos)); + newstr += (special_characters[specialChar][0]); pos += special_characters[specialChar].length(); - } - else - { - newstr+=(origstr.substr(oldPos, pos - oldPos + 1)); + } else { + newstr += (origstr.substr(oldPos, pos - oldPos + 1)); pos += 1; } @@ -86,27 +80,23 @@ String XMLParser::_replace_special_characters(const String& origstr) { pos = origstr.find("&", pos); } - if (oldPos < origstr.length()-1) - newstr+=(origstr.substr(oldPos, origstr.length()-oldPos)); + if (oldPos < origstr.length() - 1) + newstr += (origstr.substr(oldPos, origstr.length() - oldPos)); return newstr; } - -static inline bool _is_white_space(char c) -{ - return (c==' ' || c=='\t' || c=='\n' || c=='\r'); +static inline bool _is_white_space(char c) { + return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } - //! sets the state that text was found. Returns true if set should be set -bool XMLParser::_set_text(char* start, char* end) { +bool XMLParser::_set_text(char *start, char *end) { // check if text is more than 2 characters, and if not, check if there is // only white space, so that this text won't be reported - if (end - start < 3) - { - char* p = start; - for(; p != end; ++p) + if (end - start < 3) { + char *p = start; + for (; p != end; ++p) if (!_is_white_space(*p)) break; @@ -130,14 +120,14 @@ void XMLParser::_parse_closing_xml_element() { attributes.clear(); ++P; - const char* pBeginClose = P; + const char *pBeginClose = P; - while(*P != '>') + while (*P != '>') ++P; node_name = String::utf8(pBeginClose, (int)(P - pBeginClose)); #ifdef DEBUG_XML - print_line("XML CLOSE: "+node_name); + print_line("XML CLOSE: " + node_name); #endif ++P; } @@ -145,25 +135,24 @@ void XMLParser::_parse_closing_xml_element() { void XMLParser::_ignore_definition() { node_type = NODE_UNKNOWN; - char *F=P; + char *F = P; // move until end marked with '>' reached - while(*P != '>') + while (*P != '>') ++P; - node_name.parse_utf8(F,P-F); + node_name.parse_utf8(F, P - F); ++P; } bool XMLParser::_parse_cdata() { - if (*(P+1) != '[') + if (*(P + 1) != '[') return false; node_type = NODE_CDATA; // skip '<![CDATA[' - int count=0; - while( *P && count<8 ) - { + int count = 0; + while (*P && count < 8) { ++P; ++count; } @@ -175,23 +164,22 @@ bool XMLParser::_parse_cdata() { char *cDataEnd = 0; // find end of CDATA - while(*P && !cDataEnd) { + while (*P && !cDataEnd) { if (*P == '>' && - (*(P-1) == ']') && - (*(P-2) == ']')) - { + (*(P - 1) == ']') && + (*(P - 2) == ']')) { cDataEnd = P - 2; } ++P; } - if ( cDataEnd ) + if (cDataEnd) node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin)); else node_name = ""; #ifdef DEBUG_XML - print_line("XML CDATA: "+node_name); + print_line("XML CDATA: " + node_name); #endif return true; @@ -207,24 +195,21 @@ void XMLParser::_parse_comment() { int count = 1; // move until end of comment reached - while(count) - { + while (count) { if (*P == '>') --count; - else - if (*P == '<') + else if (*P == '<') ++count; ++P; } P -= 3; - node_name = String::utf8(pCommentBegin+2, (int)(P - pCommentBegin-2)); + node_name = String::utf8(pCommentBegin + 2, (int)(P - pCommentBegin - 2)); P += 3; #ifdef DEBUG_XML - print_line("XML COMMENT: "+node_name); + print_line("XML COMMENT: " + node_name); #endif - } void XMLParser::_parse_opening_xml_element() { @@ -234,37 +219,34 @@ void XMLParser::_parse_opening_xml_element() { attributes.clear(); // find name - const char* startName = P; + const char *startName = P; // find end of element - while(*P != '>' && !_is_white_space(*P)) + while (*P != '>' && !_is_white_space(*P)) ++P; - const char* endName = P; + const char *endName = P; // find attributes - while(*P != '>') - { + while (*P != '>') { if (_is_white_space(*P)) ++P; - else - { - if (*P != '/') - { + else { + if (*P != '/') { // we've got an attribute // read the attribute names - const char* attributeNameBegin = P; + const char *attributeNameBegin = P; - while(!_is_white_space(*P) && *P != '=') + while (!_is_white_space(*P) && *P != '=') ++P; - const char* attributeNameEnd = P; + const char *attributeNameEnd = P; ++P; // read the attribute value // check for quotes and single quotes, thx to murphy - while( (*P != '\"') && (*P != '\'') && *P) + while ((*P != '\"') && (*P != '\'') && *P) ++P; if (!*P) // malformatted xml file @@ -273,29 +255,27 @@ void XMLParser::_parse_opening_xml_element() { const char attributeQuoteChar = *P; ++P; - const char* attributeValueBegin = P; + const char *attributeValueBegin = P; - while(*P != attributeQuoteChar && *P) + while (*P != attributeQuoteChar && *P) ++P; if (!*P) // malformatted xml file return; - const char* attributeValueEnd = P; + const char *attributeValueEnd = P; ++P; Attribute attr; attr.name = String::utf8(attributeNameBegin, - (int)(attributeNameEnd - attributeNameBegin)); + (int)(attributeNameEnd - attributeNameBegin)); - String s =String::utf8(attributeValueBegin, - (int)(attributeValueEnd - attributeValueBegin)); + String s = String::utf8(attributeValueBegin, + (int)(attributeValueEnd - attributeValueBegin)); attr.value = _replace_special_characters(s); attributes.push_back(attr); - } - else - { + } else { // tag is closed directly ++P; node_empty = true; @@ -305,8 +285,7 @@ void XMLParser::_parse_opening_xml_element() { } // check if this tag is closing directly - if (endName > startName && *(endName-1) == '/') - { + if (endName > startName && *(endName - 1) == '/') { // directly closing tag node_empty = true; endName--; @@ -314,27 +293,25 @@ void XMLParser::_parse_opening_xml_element() { node_name = String::utf8(startName, (int)(endName - startName)); #ifdef DEBUG_XML - print_line("XML OPEN: "+node_name); + print_line("XML OPEN: " + node_name); #endif ++P; } - void XMLParser::_parse_current_node() { - char* start = P; + char *start = P; node_offset = P - data; // more forward until '<' found - while(*P != '<' && *P) + while (*P != '<' && *P) ++P; if (!*P) return; - if (P - start > 0) - { + if (P - start > 0) { // we found some text, store it if (_set_text(start, P)) return; @@ -343,25 +320,23 @@ void XMLParser::_parse_current_node() { ++P; // based on current token, parse and report next element - switch(*P) - { - case '/': - _parse_closing_xml_element(); - break; - case '?': - _ignore_definition(); - break; - case '!': - if (!_parse_cdata()) - _parse_comment(); - break; - default: - _parse_opening_xml_element(); - break; + switch (*P) { + case '/': + _parse_closing_xml_element(); + break; + case '?': + _ignore_definition(); + break; + case '!': + if (!_parse_cdata()) + _parse_comment(); + break; + default: + _parse_opening_xml_element(); + break; } } - uint64_t XMLParser::get_node_offset() const { return node_offset; @@ -379,41 +354,37 @@ Error XMLParser::seek(uint64_t p_pos) { void XMLParser::_bind_methods() { - ClassDB::bind_method(D_METHOD("read"),&XMLParser::read); - ClassDB::bind_method(D_METHOD("get_node_type"),&XMLParser::get_node_type); - ClassDB::bind_method(D_METHOD("get_node_name"),&XMLParser::get_node_name); - ClassDB::bind_method(D_METHOD("get_node_data"),&XMLParser::get_node_data); - ClassDB::bind_method(D_METHOD("get_node_offset"),&XMLParser::get_node_offset); - ClassDB::bind_method(D_METHOD("get_attribute_count"),&XMLParser::get_attribute_count); - ClassDB::bind_method(D_METHOD("get_attribute_name","idx"),&XMLParser::get_attribute_name); - ClassDB::bind_method(D_METHOD("get_attribute_value","idx"),(String (XMLParser::*)(int) const) &XMLParser::get_attribute_value); - ClassDB::bind_method(D_METHOD("has_attribute","name"),&XMLParser::has_attribute); - ClassDB::bind_method(D_METHOD("get_named_attribute_value","name"), (String (XMLParser::*)(const String&) const) &XMLParser::get_attribute_value); - ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe","name"), &XMLParser::get_attribute_value_safe); - ClassDB::bind_method(D_METHOD("is_empty"),&XMLParser::is_empty); - ClassDB::bind_method(D_METHOD("get_current_line"),&XMLParser::get_current_line); - ClassDB::bind_method(D_METHOD("skip_section"),&XMLParser::skip_section); - ClassDB::bind_method(D_METHOD("seek","pos"),&XMLParser::seek); - ClassDB::bind_method(D_METHOD("open","file"),&XMLParser::open); - ClassDB::bind_method(D_METHOD("open_buffer","buffer"),&XMLParser::open_buffer); - - BIND_CONSTANT( NODE_NONE ); - BIND_CONSTANT( NODE_ELEMENT ); - BIND_CONSTANT( NODE_ELEMENT_END ); - BIND_CONSTANT( NODE_TEXT ); - BIND_CONSTANT( NODE_COMMENT ); - BIND_CONSTANT( NODE_CDATA ); - BIND_CONSTANT( NODE_UNKNOWN ); - + ClassDB::bind_method(D_METHOD("read"), &XMLParser::read); + ClassDB::bind_method(D_METHOD("get_node_type"), &XMLParser::get_node_type); + ClassDB::bind_method(D_METHOD("get_node_name"), &XMLParser::get_node_name); + ClassDB::bind_method(D_METHOD("get_node_data"), &XMLParser::get_node_data); + ClassDB::bind_method(D_METHOD("get_node_offset"), &XMLParser::get_node_offset); + ClassDB::bind_method(D_METHOD("get_attribute_count"), &XMLParser::get_attribute_count); + ClassDB::bind_method(D_METHOD("get_attribute_name", "idx"), &XMLParser::get_attribute_name); + ClassDB::bind_method(D_METHOD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value); + ClassDB::bind_method(D_METHOD("has_attribute", "name"), &XMLParser::has_attribute); + ClassDB::bind_method(D_METHOD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value); + ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe); + ClassDB::bind_method(D_METHOD("is_empty"), &XMLParser::is_empty); + ClassDB::bind_method(D_METHOD("get_current_line"), &XMLParser::get_current_line); + ClassDB::bind_method(D_METHOD("skip_section"), &XMLParser::skip_section); + ClassDB::bind_method(D_METHOD("seek", "pos"), &XMLParser::seek); + ClassDB::bind_method(D_METHOD("open", "file"), &XMLParser::open); + ClassDB::bind_method(D_METHOD("open_buffer", "buffer"), &XMLParser::open_buffer); + + BIND_CONSTANT(NODE_NONE); + BIND_CONSTANT(NODE_ELEMENT); + BIND_CONSTANT(NODE_ELEMENT_END); + BIND_CONSTANT(NODE_TEXT); + BIND_CONSTANT(NODE_COMMENT); + BIND_CONSTANT(NODE_CDATA); + BIND_CONSTANT(NODE_UNKNOWN); }; - - Error XMLParser::read() { // if not end reached, parse the node - if (P && (P - data) < length - 1 && *P != 0) - { + if (P && (P - data) < length - 1 && *P != 0) { _parse_current_node(); return OK; } @@ -427,12 +398,12 @@ XMLParser::NodeType XMLParser::get_node_type() { } String XMLParser::get_node_data() const { - ERR_FAIL_COND_V( node_type != NODE_TEXT, ""); + ERR_FAIL_COND_V(node_type != NODE_TEXT, ""); return node_name; } String XMLParser::get_node_name() const { - ERR_FAIL_COND_V( node_type == NODE_TEXT, ""); + ERR_FAIL_COND_V(node_type == NODE_TEXT, ""); return node_name; } int XMLParser::get_attribute_count() const { @@ -441,95 +412,91 @@ int XMLParser::get_attribute_count() const { } String XMLParser::get_attribute_name(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,attributes.size(),""); + ERR_FAIL_INDEX_V(p_idx, attributes.size(), ""); return attributes[p_idx].name; } String XMLParser::get_attribute_value(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,attributes.size(),""); + ERR_FAIL_INDEX_V(p_idx, attributes.size(), ""); return attributes[p_idx].value; } -bool XMLParser::has_attribute(const String& p_name) const { +bool XMLParser::has_attribute(const String &p_name) const { - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) return true; } return false; } -String XMLParser::get_attribute_value(const String& p_name) const { +String XMLParser::get_attribute_value(const String &p_name) const { - int idx=-1; - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) { + idx = i; break; } } - if (idx<0) { - ERR_EXPLAIN("Attribute not found: "+p_name); + if (idx < 0) { + ERR_EXPLAIN("Attribute not found: " + p_name); } - ERR_FAIL_COND_V(idx<0,""); + ERR_FAIL_COND_V(idx < 0, ""); return attributes[idx].value; - } -String XMLParser::get_attribute_value_safe(const String& p_name) const { +String XMLParser::get_attribute_value_safe(const String &p_name) const { - int idx=-1; - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) { + idx = i; break; } } - if (idx<0) + if (idx < 0) return ""; return attributes[idx].value; - } bool XMLParser::is_empty() const { return node_empty; } -Error XMLParser::open_buffer(const Vector<uint8_t>& p_buffer) { +Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) { - ERR_FAIL_COND_V(p_buffer.size()==0,ERR_INVALID_DATA); + ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA); length = p_buffer.size(); - data = memnew_arr( char, length+1); - copymem(data,p_buffer.ptr(),length); - data[length]=0; - P=data; + data = memnew_arr(char, length + 1); + copymem(data, p_buffer.ptr(), length); + data[length] = 0; + P = data; return OK; - } -Error XMLParser::open(const String& p_path) { +Error XMLParser::open(const String &p_path) { Error err; - FileAccess * file = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); } length = file->get_len(); - ERR_FAIL_COND_V(length<1, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT); - data = memnew_arr( char, length+1); - file->get_buffer((uint8_t*)data,length); - data[length]=0; - P=data; + data = memnew_arr(char, length + 1); + file->get_buffer((uint8_t *)data, length); + data[length] = 0; + P = data; memdelete(file); return OK; - } void XMLParser::skip_section() { @@ -541,29 +508,24 @@ void XMLParser::skip_section() { // read until we've reached the last element in this section int tagcount = 1; - while(tagcount && read()==OK) - { + while (tagcount && read() == OK) { if (get_node_type() == XMLParser::NODE_ELEMENT && - !is_empty()) - { + !is_empty()) { ++tagcount; - } - else - if (get_node_type() == XMLParser::NODE_ELEMENT_END) + } else if (get_node_type() == XMLParser::NODE_ELEMENT_END) --tagcount; } - } void XMLParser::close() { if (data) memdelete_arr(data); - data=NULL; - length=0; - P=NULL; - node_empty=false; - node_type=NODE_NONE; + data = NULL; + length = 0; + P = NULL; + node_empty = false; + node_type = NODE_NONE; node_offset = 0; } @@ -574,19 +536,16 @@ int XMLParser::get_current_line() const { XMLParser::XMLParser() { - data=NULL; + data = NULL; close(); special_characters.push_back("&"); special_characters.push_back("<lt;"); special_characters.push_back(">gt;"); special_characters.push_back("\"quot;"); special_characters.push_back("'apos;"); - - } XMLParser::~XMLParser() { - if (data) memdelete_arr(data); } diff --git a/core/io/xml_parser.h b/core/io/xml_parser.h index 7f80751156..631d77a41e 100644 --- a/core/io/xml_parser.h +++ b/core/io/xml_parser.h @@ -29,10 +29,10 @@ #ifndef XML_PARSER_H #define XML_PARSER_H -#include "ustring.h" -#include "vector.h" #include "os/file_access.h" #include "reference.h" +#include "ustring.h" +#include "vector.h" /* Based on irrXML (see their zlib license). Added mainly for compatibility with their Collada loader. @@ -40,7 +40,8 @@ class XMLParser : public Reference { - GDCLASS( XMLParser, Reference ); + GDCLASS(XMLParser, Reference); + public: //! Enumeration of all supported source text file formats enum SourceFormat { @@ -63,11 +64,10 @@ public: }; private: - char *data; char *P; int length; - void unescape(String& p_str); + void unescape(String &p_str); Vector<String> special_characters; String node_name; bool node_empty; @@ -81,8 +81,8 @@ private: Vector<Attribute> attributes; - String _replace_special_characters(const String& origstr); - bool _set_text(char* start, char* end); + String _replace_special_characters(const String &origstr); + bool _set_text(char *start, char *end); void _parse_closing_xml_element(); void _ignore_definition(); bool _parse_cdata(); @@ -93,8 +93,6 @@ private: static void _bind_methods(); public: - - Error read(); NodeType get_node_type(); String get_node_name() const; @@ -103,17 +101,17 @@ public: int get_attribute_count() const; String get_attribute_name(int p_idx) const; String get_attribute_value(int p_idx) const; - bool has_attribute(const String& p_name) const; - String get_attribute_value(const String& p_name) const; - String get_attribute_value_safe(const String& p_name) const; // do not print error if doesn't exist + bool has_attribute(const String &p_name) const; + String get_attribute_value(const String &p_name) const; + String get_attribute_value_safe(const String &p_name) const; // do not print error if doesn't exist bool is_empty() const; int get_current_line() const; void skip_section(); Error seek(uint64_t p_pos); - Error open(const String& p_path); - Error open_buffer(const Vector<uint8_t>& p_buffer); + Error open(const String &p_path); + Error open_buffer(const Vector<uint8_t> &p_buffer); void close(); @@ -122,4 +120,3 @@ public: }; #endif - diff --git a/core/io/zip_io.h b/core/io/zip_io.h index c994593518..4da9fc9c8d 100644 --- a/core/io/zip_io.h +++ b/core/io/zip_io.h @@ -29,69 +29,65 @@ #ifndef ZIP_IO_H #define ZIP_IO_H -#include "io/zip.h" #include "io/unzip.h" -#include "os/file_access.h" +#include "io/zip.h" #include "os/copymem.h" +#include "os/file_access.h" +static void *zipio_open(void *data, const char *p_fname, int mode) { -static void* zipio_open(void* data, const char* p_fname, int mode) { - - FileAccess *&f = *(FileAccess**)data; + FileAccess *&f = *(FileAccess **)data; String fname; fname.parse_utf8(p_fname); if (mode & ZLIB_FILEFUNC_MODE_WRITE) { - f = FileAccess::open(fname,FileAccess::WRITE); + f = FileAccess::open(fname, FileAccess::WRITE); } else { - f = FileAccess::open(fname,FileAccess::READ); + f = FileAccess::open(fname, FileAccess::READ); } if (!f) return NULL; return data; - }; -static uLong zipio_read(void* data, void* fdata, void* buf, uLong size) { - - FileAccess* f = *(FileAccess**)data; - return f->get_buffer((uint8_t*)buf, size); +static uLong zipio_read(void *data, void *fdata, void *buf, uLong size) { + FileAccess *f = *(FileAccess **)data; + return f->get_buffer((uint8_t *)buf, size); }; -static uLong zipio_write(voidpf opaque, voidpf stream, const void* buf, uLong size) { +static uLong zipio_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { - FileAccess* f = *(FileAccess**)opaque; - f->store_buffer((uint8_t*)buf, size); + FileAccess *f = *(FileAccess **)opaque; + f->store_buffer((uint8_t *)buf, size); return size; }; +static long zipio_tell(voidpf opaque, voidpf stream) { -static long zipio_tell (voidpf opaque, voidpf stream) { - - FileAccess* f = *(FileAccess**)opaque; + FileAccess *f = *(FileAccess **)opaque; return f->get_pos(); }; static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess* f = *(FileAccess**)opaque; + FileAccess *f = *(FileAccess **)opaque; int pos = offset; switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_pos() + offset; - break; - case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_len() + offset; - break; - default: - break; + case ZLIB_FILEFUNC_SEEK_CUR: + pos = f->get_pos() + offset; + break; + case ZLIB_FILEFUNC_SEEK_END: + pos = f->get_len() + offset; + break; + default: + break; }; f->seek(pos); @@ -100,36 +96,32 @@ static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { static int zipio_close(voidpf opaque, voidpf stream) { - FileAccess*& f = *(FileAccess**)opaque; + FileAccess *&f = *(FileAccess **)opaque; if (f) { f->close(); - f=NULL; + f = NULL; } return 0; }; static int zipio_testerror(voidpf opaque, voidpf stream) { - FileAccess* f = *(FileAccess**)opaque; - return (f && f->get_error()!=OK)?1:0; + FileAccess *f = *(FileAccess **)opaque; + return (f && f->get_error() != OK) ? 1 : 0; }; - - static voidpf zipio_alloc(voidpf opaque, uInt items, uInt size) { - voidpf ptr =memalloc(items*size); - zeromem(ptr,items*size); + voidpf ptr = memalloc(items * size); + zeromem(ptr, items * size); return ptr; } - static void zipio_free(voidpf opaque, voidpf address) { memfree(address); } - static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { zlib_filefunc_def io; @@ -141,11 +133,9 @@ static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { io.zseek_file = zipio_seek; io.zclose_file = zipio_close; io.zerror_file = zipio_testerror; - io.alloc_mem=zipio_alloc; - io.free_mem=zipio_free; + io.alloc_mem = zipio_alloc; + io.free_mem = zipio_free; return io; } - - #endif // ZIP_IO_H diff --git a/core/list.h b/core/list.h index c464af7475..6924580380 100644 --- a/core/list.h +++ b/core/list.h @@ -40,34 +40,33 @@ * from the iterator. */ -template <class T,class A=DefaultAllocator> +template <class T, class A = DefaultAllocator> class List { struct _Data; -public: - +public: class Element { private: - friend class List<T,A>; + friend class List<T, A>; 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<Element,A>( const_cast<Element*>(p_I) ); + memdelete_allocator<Element, A>(const_cast<Element *>(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<class T_v> - Element* find(const T_v& p_val) { + template <class T_v> + 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;i<s;i++) { + for (int i = 0; i < s; i++) { - SWAP( F->value, 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<T> >(); + sort_custom<Comparator<T> >(); } - template<class C> + template <class C> 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<class C> + template <class C> 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<class C> + template <class C> 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<Element*,AuxiliaryComparator<C> > 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]; + SortArray<Element *, AuxiliaryComparator<C> > sort; + sort.sort(aux_buffer, s); - _data->last=aux_buffer[s-1]; - aux_buffer[s-1]->prev_ptr=aux_buffer[s-2]; - aux_buffer[s-1]->next_ptr=NULL; + _data->first = aux_buffer[0]; + aux_buffer[0]->prev_ptr = NULL; + aux_buffer[0]->next_ptr = aux_buffer[1]; - for(int i=1;i<s-1;i++) { + _data->last = aux_buffer[s - 1]; + aux_buffer[s - 1]->prev_ptr = aux_buffer[s - 2]; + aux_buffer[s - 1]->next_ptr = NULL; - aux_buffer[i]->prev_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 d1a4c209ad..e9700ff371 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 K,class V,class C=Comparator<K>,class A=DefaultAllocator> +template <class K, class V, class C = Comparator<K>, class A = DefaultAllocator> class Map { enum Color { @@ -45,26 +45,25 @@ class Map { BLACK }; struct _Data; -public: +public: class Element { private: - friend class Map<K,V,C,A>; + friend class Map<K, V, C, A>; //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<Element,A>(_root); - _root=NULL; + memdelete_allocator<Element, A>(_root); + _root = NULL; } } @@ -147,7 +144,7 @@ private: _free_root(); #ifdef GLOBALNIL_DISABLED - memdelete_allocator<Element,A>(_nil); + memdelete_allocator<Element, A>(_nil); #endif //memdelete_allocator<Element,A>(_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<Element,A>(p_node); + memdelete_allocator<Element, A>(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<Element,A>( p_element ); + memdelete_allocator<Element, A>(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 { +public: + 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 7e31957e3e..110185c2d2 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, real_t 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; - } -real_t AStar::get_point_weight_scale(int p_id) const{ +real_t 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;i<p->neighbours.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<int,Point*>::Element *E=points.front();E;E=E->next()) { + for (const Map<int, Point *>::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; - real_t closest_dist=1e20; + int closest_id = -1; + real_t closest_dist = 1e20; - for (const Map<int,Point*>::Element *E=points.front();E;E=E->next()) { + for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) { real_t d = p_point.distance_squared_to(E->get()->pos); - if (closest_id<0 || d<closest_dist) { - closest_dist=d; - closest_id=E->key(); + 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 { real_t closest_dist = 1e20; - bool found=false; + bool found = false; Vector3 closest_point; + for (const Set<Segment>::Element *E = segments.front(); E; E = E->next()) { - for (const Set<Segment>::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); real_t d = p_point.distance_squared_to(p); - if (!found || d<closest_dist) { + if (!found || d < closest_dist) { - closest_point=p; - closest_dist=d; - found=true; + closest_point = p; + closest_dist = d; + found = true; } } return closest_point; } -bool AStar::_solve(Point* begin_point, Point* end_point) { +bool AStar::_solve(Point *begin_point, Point *end_point) { pass++; SelfList<Point>::List open_list; - bool found_route=false; - + bool found_route = false; - for(int i=0;i<begin_point->neighbours.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<Point> *least_cost_point=NULL; - real_t least_cost=1e30; + SelfList<Point> *least_cost_point = NULL; + real_t least_cost = 1e30; //this could be faster (cache previous results) - for (SelfList<Point> *E=open_list.first();E;E=E->next()) { + for (SelfList<Point> *E = open_list.first(); E; E = E->next()) { - Point *p=E->self(); + Point *p = E->self(); - real_t cost=p->distance; - cost+=p->pos.distance_to(end_point->pos); - cost*=p->weight_scale; + real_t cost = p->distance; + cost += p->pos.distance_to(end_point->pos); + cost *= p->weight_scale; - if (cost<least_cost) { + if (cost < least_cost) { - least_cost_point=E; - least_cost=cost; + least_cost_point = E; + least_cost = cost; } } - - Point *p=least_cost_point->self(); + Point *p = least_cost_point->self(); //open the neighbours for search int es = p->neighbours.size(); - for(int i=0;i<es;i++) { - - - Point* e=p->neighbours[i]; + for (int i = 0; i < es; i++) { + Point *e = p->neighbours[i]; real_t 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; - } PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id),PoolVector<Vector3>()); - ERR_FAIL_COND_V(!points.has(p_to_id),PoolVector<Vector3>()); - + ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<Vector3>()); + ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<Vector3>()); 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) { PoolVector<Vector3> 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 PoolVector<Vector3>(); //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; } PoolVector<Vector3> path; @@ -335,54 +312,49 @@ PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) { { PoolVector<Vector3>::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; - } - PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id),PoolVector<int>()); - ERR_FAIL_COND_V(!points.has(p_to_id),PoolVector<int>()); - + ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<int>()); + ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<int>()); 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) { PoolVector<int> 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 PoolVector<int>(); //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; } PoolVector<int> path; @@ -391,15 +363,14 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) { { PoolVector<int>::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 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) { void AStar::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_available_point_id"),&AStar::get_available_point_id); - ClassDB::bind_method(D_METHOD("add_point","id","pos","weight_scale"),&AStar::add_point,DEFVAL(1.0)); - ClassDB::bind_method(D_METHOD("get_point_pos","id"),&AStar::get_point_pos); - ClassDB::bind_method(D_METHOD("get_point_weight_scale","id"),&AStar::get_point_weight_scale); - ClassDB::bind_method(D_METHOD("remove_point","id"),&AStar::remove_point); - - ClassDB::bind_method(D_METHOD("connect_points","id","to_id"),&AStar::connect_points); - ClassDB::bind_method(D_METHOD("disconnect_points","id","to_id"),&AStar::disconnect_points); - ClassDB::bind_method(D_METHOD("are_points_connected","id","to_id"),&AStar::are_points_connected); + ClassDB::bind_method(D_METHOD("get_available_point_id"), &AStar::get_available_point_id); + ClassDB::bind_method(D_METHOD("add_point", "id", "pos", "weight_scale"), &AStar::add_point, DEFVAL(1.0)); + ClassDB::bind_method(D_METHOD("get_point_pos", "id"), &AStar::get_point_pos); + ClassDB::bind_method(D_METHOD("get_point_weight_scale", "id"), &AStar::get_point_weight_scale); + ClassDB::bind_method(D_METHOD("remove_point", "id"), &AStar::remove_point); - ClassDB::bind_method(D_METHOD("clear"),&AStar::clear); + ClassDB::bind_method(D_METHOD("connect_points", "id", "to_id"), &AStar::connect_points); + ClassDB::bind_method(D_METHOD("disconnect_points", "id", "to_id"), &AStar::disconnect_points); + ClassDB::bind_method(D_METHOD("are_points_connected", "id", "to_id"), &AStar::are_points_connected); - ClassDB::bind_method(D_METHOD("get_closest_point","to_pos"),&AStar::get_closest_point); - ClassDB::bind_method(D_METHOD("get_closest_pos_in_segment","to_pos"),&AStar::get_closest_pos_in_segment); + ClassDB::bind_method(D_METHOD("clear"), &AStar::clear); - ClassDB::bind_method(D_METHOD("get_point_path","from_id","to_id"),&AStar::get_point_path); - ClassDB::bind_method(D_METHOD("get_id_path","from_id","to_id"),&AStar::get_id_path); + ClassDB::bind_method(D_METHOD("get_closest_point", "to_pos"), &AStar::get_closest_point); + ClassDB::bind_method(D_METHOD("get_closest_pos_in_segment", "to_pos"), &AStar::get_closest_pos_in_segment); + ClassDB::bind_method(D_METHOD("get_point_path", "from_id", "to_id"), &AStar::get_point_path); + ClassDB::bind_method(D_METHOD("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 c4c955ed2d..2ac855737c 100644 --- a/core/math/a_star.h +++ b/core/math/a_star.h @@ -35,10 +35,9 @@ @author Juan Linietsky <reduzio@gmail.com> */ -class AStar: public Reference { - - GDCLASS(AStar,Reference) +class AStar : public Reference { + GDCLASS(AStar, Reference) uint64_t pass; @@ -51,16 +50,17 @@ class AStar: public Reference { real_t weight_scale; uint64_t last_pass; - Vector<Point*> neighbours; + Vector<Point *> neighbours; //used for pathfinding Point *prev_point; real_t distance; - Point() : list(this) {} + Point() + : list(this) {} }; - Map<int,Point*> points; + Map<int, Point *> 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_s.key; } - Segment() { key=0; } - Segment(int p_from,int p_to) { + bool operator<(const Segment &p_s) const { return key < p_s.key; } + Segment() { key = 0; } + Segment(int p_from, int p_to) { if (p_from > 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<Segment> 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,real_t p_weight_scale=1); + void add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale = 1); Vector3 get_point_pos(int p_id) const; real_t 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; PoolVector<Vector3> get_point_path(int p_from_id, int p_to_id); PoolVector<int> get_id_path(int p_from_id, int p_to_id); diff --git a/core/math/audio_frame.cpp b/core/math/audio_frame.cpp index aae1561a84..e56157ffef 100644 --- a/core/math/audio_frame.cpp +++ b/core/math/audio_frame.cpp @@ -27,4 +27,3 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_frame.h" - diff --git a/core/math/audio_frame.h b/core/math/audio_frame.h index e4e93f34fa..dd43f48df4 100644 --- a/core/math/audio_frame.h +++ b/core/math/audio_frame.h @@ -31,9 +31,7 @@ #include "typedefs.h" - -static inline float undenormalise(volatile float f) -{ +static inline float undenormalise(volatile float f) { union { uint32_t i; float f; @@ -46,42 +44,71 @@ static inline float undenormalise(volatile float f) return (v.i & 0x7f800000) < 0x08000000 ? 0.0f : f; } - struct AudioFrame { //left and right samples - float l,r; + float l, r; - _ALWAYS_INLINE_ const float& operator[](int idx) const { return idx==0?l:r; } - _ALWAYS_INLINE_ float& operator[](int idx) { return idx==0?l:r; } + _ALWAYS_INLINE_ const float &operator[](int idx) const { return idx == 0 ? l : r; } + _ALWAYS_INLINE_ float &operator[](int idx) { return idx == 0 ? l : r; } - _ALWAYS_INLINE_ AudioFrame operator+(const AudioFrame& p_frame) const { return AudioFrame(l+p_frame.l,r+p_frame.r); } - _ALWAYS_INLINE_ AudioFrame operator-(const AudioFrame& p_frame) const { return AudioFrame(l-p_frame.l,r-p_frame.r); } - _ALWAYS_INLINE_ AudioFrame operator*(const AudioFrame& p_frame) const { return AudioFrame(l*p_frame.l,r*p_frame.r); } - _ALWAYS_INLINE_ AudioFrame operator/(const AudioFrame& p_frame) const { return AudioFrame(l/p_frame.l,r/p_frame.r); } + _ALWAYS_INLINE_ AudioFrame operator+(const AudioFrame &p_frame) const { return AudioFrame(l + p_frame.l, r + p_frame.r); } + _ALWAYS_INLINE_ AudioFrame operator-(const AudioFrame &p_frame) const { return AudioFrame(l - p_frame.l, r - p_frame.r); } + _ALWAYS_INLINE_ AudioFrame operator*(const AudioFrame &p_frame) const { return AudioFrame(l * p_frame.l, r * p_frame.r); } + _ALWAYS_INLINE_ AudioFrame operator/(const AudioFrame &p_frame) const { return AudioFrame(l / p_frame.l, r / p_frame.r); } - _ALWAYS_INLINE_ AudioFrame operator+(float p_sample) const { return AudioFrame(l+p_sample,r+p_sample); } - _ALWAYS_INLINE_ AudioFrame operator-(float p_sample) const { return AudioFrame(l-p_sample,r-p_sample); } - _ALWAYS_INLINE_ AudioFrame operator*(float p_sample) const { return AudioFrame(l*p_sample,r*p_sample); } - _ALWAYS_INLINE_ AudioFrame operator/(float p_sample) const { return AudioFrame(l/p_sample,r/p_sample); } + _ALWAYS_INLINE_ AudioFrame operator+(float p_sample) const { return AudioFrame(l + p_sample, r + p_sample); } + _ALWAYS_INLINE_ AudioFrame operator-(float p_sample) const { return AudioFrame(l - p_sample, r - p_sample); } + _ALWAYS_INLINE_ AudioFrame operator*(float p_sample) const { return AudioFrame(l * p_sample, r * p_sample); } + _ALWAYS_INLINE_ AudioFrame operator/(float p_sample) const { return AudioFrame(l / p_sample, r / p_sample); } - _ALWAYS_INLINE_ void operator+=(const AudioFrame& p_frame) { l+=p_frame.l; r+=p_frame.r; } - _ALWAYS_INLINE_ void operator-=(const AudioFrame& p_frame) { l-=p_frame.l; r-=p_frame.r; } - _ALWAYS_INLINE_ void operator*=(const AudioFrame& p_frame) { l*=p_frame.l; r*=p_frame.r; } - _ALWAYS_INLINE_ void operator/=(const AudioFrame& p_frame) { l/=p_frame.l; r/=p_frame.r; } + _ALWAYS_INLINE_ void operator+=(const AudioFrame &p_frame) { + l += p_frame.l; + r += p_frame.r; + } + _ALWAYS_INLINE_ void operator-=(const AudioFrame &p_frame) { + l -= p_frame.l; + r -= p_frame.r; + } + _ALWAYS_INLINE_ void operator*=(const AudioFrame &p_frame) { + l *= p_frame.l; + r *= p_frame.r; + } + _ALWAYS_INLINE_ void operator/=(const AudioFrame &p_frame) { + l /= p_frame.l; + r /= p_frame.r; + } - _ALWAYS_INLINE_ void operator+=(float p_sample) { l+=p_sample; r+=p_sample; } - _ALWAYS_INLINE_ void operator-=(float p_sample) { l-=p_sample; r-=p_sample; } - _ALWAYS_INLINE_ void operator*=(float p_sample) { l*=p_sample; r*=p_sample; } - _ALWAYS_INLINE_ void operator/=(float p_sample) { l/=p_sample; r/=p_sample; } + _ALWAYS_INLINE_ void operator+=(float p_sample) { + l += p_sample; + r += p_sample; + } + _ALWAYS_INLINE_ void operator-=(float p_sample) { + l -= p_sample; + r -= p_sample; + } + _ALWAYS_INLINE_ void operator*=(float p_sample) { + l *= p_sample; + r *= p_sample; + } + _ALWAYS_INLINE_ void operator/=(float p_sample) { + l /= p_sample; + r /= p_sample; + } _ALWAYS_INLINE_ void undenormalise() { l = ::undenormalise(l); r = ::undenormalise(r); } - _ALWAYS_INLINE_ AudioFrame(float p_l, float p_r) {l=p_l; r=p_r;} - _ALWAYS_INLINE_ AudioFrame(const AudioFrame& p_frame) {l=p_frame.l; r=p_frame.r;} + _ALWAYS_INLINE_ AudioFrame(float p_l, float p_r) { + l = p_l; + r = p_r; + } + _ALWAYS_INLINE_ AudioFrame(const AudioFrame &p_frame) { + l = p_frame.l; + r = p_frame.r; + } _ALWAYS_INLINE_ AudioFrame() {} }; diff --git a/core/math/bsp_tree.cpp b/core/math/bsp_tree.cpp index 1ca6385032..ef229a0553 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 Rect3& p_aabb) { +void BSP_Tree::from_aabb(const Rect3 &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::Node> BSP_Tree::get_nodes() const { @@ -72,143 +71,136 @@ Rect3 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; real_t dist_min = p.distance_to(min); real_t 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;i<p_indices_count;i++) { + for (int i = 0; i < p_indices_count; i++) { - int index=p_indices[i]; + int index = p_indices[i]; if (p.is_point_over(p_points[index])) { // kind of slow (but cache friendly), should try something else, // but this is a corner case most of the time - for(int j=index;j<p_indices_count-1;j++) - p_indices[j]=p_indices[j+1]; + for (int j = index; j < p_indices_count - 1; j++) + p_indices[j] = p_indices[j + 1]; - p_indices[p_indices_count-1]=index; + p_indices[p_indices_count - 1] = index; } else { under_count++; } - } - int total=0; + int total = 0; - if (under_count>0) { - 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<p_point_count;i++) { + for (int i = 0; i < p_point_count; i++) { - const Vector3& point = p_points[i]; + const Vector3 &point = p_points[i]; if (!aabb.has_point(point)) { continue; } - int idx=node_count-1; + int idx = node_count - 1; - bool pass=false; + bool pass = false; - while(true) { + while (true) { - if (idx==OVER_LEAF) { - pass=false; + if (idx == OVER_LEAF) { + pass = false; break; - } else if (idx==UNDER_LEAF) { - pass=true; + } else if (idx == UNDER_LEAF) { + pass = true; break; } - uint16_t plane=nodesptr[ idx ].plane; + uint16_t plane = nodesptr[idx].plane; #ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V( plane, plane_count, false ); + ERR_FAIL_INDEX_V(plane, plane_count, false); #endif - idx = planesptr[ nodesptr[ idx ].plane ].is_point_over(point) ? nodes[ idx ].over : nodes[ idx ].under; + idx = planesptr[nodesptr[idx].plane].is_point_over(point) ? nodes[idx].over : nodes[idx].under; #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V( idx<MAX_NODES && idx>=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<p_point_count;i++) { + for (int i = 0; i < p_point_count; i++) { - indices[i]=i; - if (i==0) - bounds.pos=p_points[i]; + indices[i] = i; + if (i == 0) + bounds.pos = p_points[i]; else bounds.expand_to(p_points[i]); - } - Vector3 half_extents = bounds.size/2.0; - return _get_points_inside(nodes.size()+1,p_points,indices,bounds.pos+half_extents,half_extents,p_point_count); + Vector3 half_extents = bounds.size / 2.0; + return _get_points_inside(nodes.size() + 1, p_points, indices, bounds.pos + half_extents, half_extents, p_point_count); #endif } - - -bool BSP_Tree::point_is_inside(const Vector3& p_point) const { +bool BSP_Tree::point_is_inside(const Vector3 &p_point) const { if (!aabb.has_point(p_point)) { return false; } - int node_count=nodes.size(); + int node_count = nodes.size(); - if (node_count==0) // no nodes! + if (node_count == 0) // no nodes! return false; + const Node *nodesptr = &nodes[0]; + const Plane *planesptr = &planes[0]; + int plane_count = planes.size(); - const Node *nodesptr=&nodes[0]; - const Plane *planesptr=&planes[0]; - int plane_count=planes.size(); - - int idx=node_count-1; - int steps=0; + int idx = node_count - 1; + int steps = 0; - while(true) { + while (true) { - if (idx==OVER_LEAF) { + if (idx == OVER_LEAF) { return false; } - if (idx==UNDER_LEAF) { + if (idx == UNDER_LEAF) { return true; } - uint16_t plane=nodesptr[ idx ].plane; + uint16_t plane = nodesptr[idx].plane; #ifdef DEBUG_ENABLED - ERR_FAIL_INDEX_V( plane, plane_count, false ); + ERR_FAIL_INDEX_V(plane, plane_count, false); #endif - bool over = planesptr[ nodesptr[ idx ].plane ].is_point_over(p_point); + bool over = planesptr[nodesptr[idx].plane].is_point_over(p_point); - idx = over ? nodes[ idx ].over : nodes[ idx ].under; + idx = over ? nodes[idx].over : nodes[idx].under; #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V( idx<MAX_NODES && idx>=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<int>& p_indices,real_t p_tolerance) { +static int _bsp_find_best_half_plane(const Face3 *p_faces, const Vector<int> &p_indices, real_t p_tolerance) { int ic = p_indices.size(); - const int*indices=p_indices.ptr(); + const int *indices = p_indices.ptr(); int best_plane = -1; real_t best_plane_cost = 1e20; // Loop to find the polygon that best divides the set. - for (int i=0;i<ic;i++) { + for (int i = 0; i < ic; i++) { - const Face3& f=p_faces[ indices[i] ]; + const Face3 &f = p_faces[indices[i]]; Plane p = f.get_plane(); - int num_over=0,num_under=0,num_spanning=0; + int num_over = 0, num_under = 0, num_spanning = 0; - for(int j=0;j<ic;j++) { + for (int j = 0; j < ic; j++) { - if (i==j) + if (i == j) continue; - const Face3& g=p_faces[ indices[j] ]; - int over=0,under=0; + const Face3 &g = p_faces[indices[j]]; + int over = 0, under = 0; - for(int k=0;k<3;k++) { + for (int k = 0; k < 3; k++) { real_t d = p.distance_to(g.vertex[j]); - if (Math::abs(d)>p_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<int>& p_i num_over++; else num_under++; - } - - //real_t split_cost = num_spanning / (real_t) face_count; - real_t relation = Math::abs(num_over-num_under) / (real_t) ic; + real_t relation = Math::abs(num_over - num_under) / (real_t)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,59 +332,55 @@ static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector<int>& p_i real_t 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<best_plane_cost) { + if (plane_cost < best_plane_cost) { - best_plane=i; - best_plane_cost=plane_cost; + best_plane = i; + best_plane_cost = plane_cost; } - } return best_plane; - } +static int _bsp_create_node(const Face3 *p_faces, const Vector<int> &p_indices, Vector<Plane> &p_planes, Vector<BSP_Tree::Node> &p_nodes, real_t p_tolerance) { -static int _bsp_create_node(const Face3 *p_faces,const Vector<int>& p_indices,Vector<Plane> &p_planes, Vector<BSP_Tree::Node> &p_nodes,real_t 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<int> faces_over; Vector<int> 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;i<ic;i++) { + for (int i = 0; i < ic; i++) { - if (i==divisor_idx) + if (i == divisor_idx) continue; - const Face3& f=p_faces[ indices[i] ]; + const Face3 &f = p_faces[indices[i]]; /* if (f.get_plane().is_almost_like(divisor_plane)) continue; */ - int over_count=0; - int under_count=0; + int over_count = 0; + int under_count = 0; - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { real_t d = divisor_plane.distance_to(f.vertex[j]); - if (Math::abs(d)>p_tolerance) { + if (Math::abs(d) > p_tolerance) { if (d > 0) over_count++; @@ -411,183 +390,169 @@ static int _bsp_create_node(const Face3 *p_faces,const Vector<int>& 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 < p_planes.size(); i++) { - if (p_planes[i].is_almost_like( divisor_plane )) { - divisor_plane_idx=i; + if (p_planes[i].is_almost_like(divisor_plane)) { + divisor_plane_idx = i; break; } } - if (divisor_plane_idx==-1) { + if (divisor_plane_idx == -1) { - ERR_FAIL_COND_V( p_planes.size() == BSP_Tree::MAX_PLANES, -1 ); - divisor_plane_idx=p_planes.size(); - p_planes.push_back( divisor_plane ); + ERR_FAIL_COND_V(p_planes.size() == BSP_Tree::MAX_PLANES, -1); + divisor_plane_idx = p_planes.size(); + p_planes.push_back(divisor_plane); } BSP_Tree::Node node; - node.plane=divisor_plane_idx; - node.under=under_idx; - node.over=over_idx; + node.plane = divisor_plane_idx; + node.under = under_idx; + node.over = over_idx; p_nodes.push_back(node); - return p_nodes.size()-1; + return p_nodes.size() - 1; } - BSP_Tree::operator Variant() const { - Dictionary d; - d["error_radius"]=error_radius; + d["error_radius"] = error_radius; Vector<real_t> plane_values; - plane_values.resize(planes.size()*4); + plane_values.resize(planes.size() * 4); - for(int i=0;i<planes.size();i++) { + for (int i = 0; i < planes.size(); i++) { - plane_values[i*4+0]=planes[i].normal.x; - plane_values[i*4+1]=planes[i].normal.y; - plane_values[i*4+2]=planes[i].normal.z; - plane_values[i*4+3]=planes[i].d; + plane_values[i * 4 + 0] = planes[i].normal.x; + plane_values[i * 4 + 1] = planes[i].normal.y; + plane_values[i * 4 + 2] = planes[i].normal.z; + plane_values[i * 4 + 3] = planes[i].d; } - d["planes"]=plane_values; + d["planes"] = plane_values; PoolVector<int> dst_nodes; - dst_nodes.resize(nodes.size()*3); + dst_nodes.resize(nodes.size() * 3); - for(int i=0;i<nodes.size();i++) { + for (int i = 0; i < nodes.size(); i++) { - dst_nodes.set(i*3+0,nodes[i].over); - dst_nodes.set(i*3+1,nodes[i].under); - dst_nodes.set(i*3+2,nodes[i].plane); + dst_nodes.set(i * 3 + 0, nodes[i].over); + dst_nodes.set(i * 3 + 1, nodes[i].under); + dst_nodes.set(i * 3 + 2, nodes[i].plane); } - - d["nodes"]=dst_nodes; + d["nodes"] = dst_nodes; d["aabb"] = aabb; return Variant(d); } BSP_Tree::BSP_Tree() { - } +BSP_Tree::BSP_Tree(const Variant &p_variant) { -BSP_Tree::BSP_Tree(const Variant& p_variant) { - - Dictionary d=p_variant; + Dictionary d = p_variant; ERR_FAIL_COND(!d.has("nodes")); ERR_FAIL_COND(!d.has("planes")); ERR_FAIL_COND(!d.has("aabb")); ERR_FAIL_COND(!d.has("error_radius")); PoolVector<int> src_nodes = d["nodes"]; - ERR_FAIL_COND(src_nodes.size()%3); + ERR_FAIL_COND(src_nodes.size() % 3); + if (d["planes"].get_type() == Variant::POOL_REAL_ARRAY) { - if (d["planes"].get_type()==Variant::POOL_REAL_ARRAY) { - - PoolVector<real_t> src_planes=d["planes"]; - int plane_count=src_planes.size(); - ERR_FAIL_COND(plane_count%4); - planes.resize(plane_count/4); + PoolVector<real_t> src_planes = d["planes"]; + int plane_count = src_planes.size(); + ERR_FAIL_COND(plane_count % 4); + planes.resize(plane_count / 4); if (plane_count) { PoolVector<real_t>::Read r = src_planes.read(); - for(int i=0;i<plane_count/4;i++) { + for (int i = 0; i < plane_count / 4; i++) { - planes[i].normal.x=r[i*4+0]; - planes[i].normal.y=r[i*4+1]; - planes[i].normal.z=r[i*4+2]; - planes[i].d=r[i*4+3]; + planes[i].normal.x = r[i * 4 + 0]; + planes[i].normal.y = r[i * 4 + 1]; + planes[i].normal.z = r[i * 4 + 2]; + planes[i].d = r[i * 4 + 3]; } } - } else { planes = d["planes"]; } - error_radius = d["error"]; aabb = d["aabb"]; //int node_count = src_nodes.size(); - nodes.resize(src_nodes.size()/3); + nodes.resize(src_nodes.size() / 3); PoolVector<int>::Read r = src_nodes.read(); - for(int i=0;i<nodes.size();i++) { + for (int i = 0; i < nodes.size(); i++) { - nodes[i].over=r[i*3+0]; - nodes[i].under=r[i*3+1]; - nodes[i].plane=r[i*3+2]; + nodes[i].over = r[i * 3 + 0]; + nodes[i].under = r[i * 3 + 1]; + nodes[i].plane = r[i * 3 + 2]; } - } -BSP_Tree::BSP_Tree(const PoolVector<Face3>& p_faces,real_t p_error_radius) { +BSP_Tree::BSP_Tree(const PoolVector<Face3> &p_faces, real_t p_error_radius) { // compute aabb - int face_count=p_faces.size(); - PoolVector<Face3>::Read faces_r=p_faces.read(); + int face_count = p_faces.size(); + PoolVector<Face3>::Read faces_r = p_faces.read(); const Face3 *facesptr = faces_r.ptr(); - - bool first=true; + bool first = true; Vector<int> indices; - for (int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - const Face3& f=facesptr[i]; + const Face3 &f = facesptr[i]; if (f.is_degenerate()) continue; - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { if (first) { - aabb.pos=f.vertex[0]; - first=false; + aabb.pos = f.vertex[0]; + first = false; } else { aabb.expand_to(f.vertex[j]); @@ -595,36 +560,29 @@ BSP_Tree::BSP_Tree(const PoolVector<Face3>& p_faces,real_t 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<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3& p_aabb,real_t p_error_radius) { - - nodes=p_nodes; - planes=p_planes; - aabb=p_aabb; - error_radius=p_error_radius; +BSP_Tree::BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3 &p_aabb, real_t 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 c0071438db..4cfac35a2c 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 "dvector.h" +#include "face3.h" +#include "method_ptrcall.h" #include "plane.h" #include "rect3.h" -#include "face3.h" -#include "vector.h" -#include "dvector.h" #include "variant.h" -#include "method_ptrcall.h" +#include "vector.h" /** @author Juan Linietsky <reduzio@gmail.com> */ 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: Rect3 aabb; real_t 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<class T> - bool _test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const; + template <class T> + 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<Node> get_nodes() const; Vector<Plane> get_planes() const; Rect3 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<class T> - 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 <class T> + bool convex_is_inside(const T &p_convex) const; operator Variant() const; - void from_aabb(const Rect3& p_aabb); + void from_aabb(const Rect3 &p_aabb); BSP_Tree(); - BSP_Tree(const Variant& p_variant); - BSP_Tree(const PoolVector<Face3>& p_faces,real_t p_error_radius=0); - BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3& p_aabb,real_t p_error_radius=0); + BSP_Tree(const Variant &p_variant); + BSP_Tree(const PoolVector<Face3> &p_faces, real_t p_error_radius = 0); + BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3 &p_aabb, real_t p_error_radius = 0); ~BSP_Tree(); - }; -template<class T> -bool BSP_Tree::_test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const { +template <class T> +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]; - real_t min,max; - p_convex.project_range(p.normal,min,max); + real_t 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<class T> -bool BSP_Tree::convex_is_inside(const T& p_convex) const { +template <class T> +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<BSP_Tree> { - _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) { - BSP_Tree s( Variant( *reinterpret_cast<const Dictionary*>(p_ptr) ) ); + _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) { + BSP_Tree s(Variant(*reinterpret_cast<const Dictionary *>(p_ptr))); return s; } - _FORCE_INLINE_ static void encode(BSP_Tree p_val,void* p_ptr) { - Dictionary *d = reinterpret_cast<Dictionary*>(p_ptr); - *d=Variant(p_val); + _FORCE_INLINE_ static void encode(BSP_Tree p_val, void *p_ptr) { + Dictionary *d = reinterpret_cast<Dictionary *>(p_ptr); + *d = Variant(p_val); } }; -template<> -struct PtrToArg<const BSP_Tree&> { - _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) { - BSP_Tree s( Variant( *reinterpret_cast<const Dictionary*>(p_ptr) ) ); +template <> +struct PtrToArg<const BSP_Tree &> { + _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) { + BSP_Tree s(Variant(*reinterpret_cast<const Dictionary *>(p_ptr))); return s; } }; diff --git a/core/math/camera_matrix.cpp b/core/math/camera_matrix.cpp index 3b47a75c65..227f586c43 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) const { +Plane CameraMatrix::xform4(const Plane &p_vec4) const { Plane ret; @@ -65,11 +63,10 @@ Plane CameraMatrix::xform4(const Plane& p_vec4) const { return ret; } -void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far,bool p_flip_fov) { +void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t 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); } real_t sine, cotangent, deltaZ; @@ -78,8 +75,8 @@ void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_ 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(real_t p_fovy_degrees, real_t p_aspect, real_ matrix[2][3] = -1; matrix[3][2] = -2 * p_z_near * p_z_far / deltaZ; matrix[3][3] = 0; - } -void CameraMatrix::set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar) { - +void CameraMatrix::set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t 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(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar,bool p_flip_fov) { +void CameraMatrix::set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t 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(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_near, real_t 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(real_t p_left, real_t p_right, real_t p_bottom, r matrix[3][3]=0; #else real_t *te = &matrix[0][0]; - real_t x = 2 * p_near / ( p_right - p_left ); - real_t y = 2 * p_near / ( p_top - p_bottom ); + real_t x = 2 * p_near / (p_right - p_left); + real_t y = 2 * p_near / (p_top - p_bottom); - real_t a = ( p_right + p_left ) / ( p_right - p_left ); - real_t b = ( p_top + p_bottom ) / ( p_top - p_bottom ); - real_t c = - ( p_far + p_near ) / ( p_far - p_near ); - real_t d = - 2 * p_far * p_near / ( p_far - p_near ); + real_t a = (p_right + p_left) / (p_right - p_left); + real_t b = (p_top + p_bottom) / (p_top - p_bottom); + real_t c = -(p_far + p_near) / (p_far - p_near); + real_t d = -2 * p_far * p_near / (p_far - p_near); te[0] = x; te[1] = 0; @@ -161,120 +153,117 @@ void CameraMatrix::set_frustum(real_t p_left, real_t p_right, real_t p_bottom, r te[15] = 0; #endif - } - - real_t CameraMatrix::get_z_far() const { - const real_t * matrix = (const real_t*)this->matrix; - Plane new_plane=Plane(matrix[ 3] - matrix[ 2], - matrix[ 7] - matrix[ 6], - matrix[11] - matrix[10], - matrix[15] - matrix[14]); + const real_t *matrix = (const real_t *)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; } real_t CameraMatrix::get_z_near() const { - const real_t * matrix = (const real_t*)this->matrix; - Plane new_plane=Plane(matrix[ 3] + matrix[ 2], - matrix[ 7] + matrix[ 6], - matrix[11] + matrix[10], - -matrix[15] - matrix[14]); + const real_t *matrix = (const real_t *)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(real_t& r_width, real_t& r_height) const { +void CameraMatrix::get_viewport_size(real_t &r_width, real_t &r_height) const { - const real_t * matrix = (const real_t*)this->matrix; + const real_t *matrix = (const real_t *)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 real_t * matrix = (const real_t*)this->matrix; + const real_t *matrix = (const real_t *)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<Plane> CameraMatrix::get_projection_planes(const Transform& p_transform) const { +Vector<Plane> CameraMatrix::get_projection_planes(const Transform &p_transform) const { /** Fast Plane Extraction from combined modelview/projection matrices. * References: @@ -284,88 +273,79 @@ Vector<Plane> CameraMatrix::get_projection_planes(const Transform& p_transform) Vector<Plane> planes; - const real_t * matrix = (const real_t*)this->matrix; + const real_t *matrix = (const real_t *)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 */ - real_t pvt_val; /* Value of current pivot element */ - real_t hold; /* Temporary storage */ - real_t determinat; /* Determinant */ + int i, j, k; + int pvt_i[4], pvt_j[4]; /* Locations of pivot matrix */ + real_t pvt_val; /* Value of current pivot element */ + real_t hold; /* Temporary storage */ + real_t 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,173 +470,164 @@ CameraMatrix CameraMatrix::operator*(const CameraMatrix& p_matrix) const { void CameraMatrix::set_light_bias() { - real_t *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; - + real_t *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; } -void CameraMatrix::set_light_atlas_rect(const Rect2& p_rect) { - - real_t *m=&matrix[0][0]; - - m[0]=p_rect.size.width, - m[1]=0.0, - m[2]=0.0, - m[3]=0.0, - m[4]=0.0, - m[5]=p_rect.size.height, - m[6]=0.0, - m[7]=0.0, - m[8]=0.0, - m[9]=0.0, - m[10]=1.0, - m[11]=0.0, - m[12]=p_rect.pos.x, - m[13]=p_rect.pos.y, - m[14]=0.0, - m[15]=1.0; +void CameraMatrix::set_light_atlas_rect(const Rect2 &p_rect) { + + real_t *m = &matrix[0][0]; + + m[0] = p_rect.size.width, + m[1] = 0.0, + m[2] = 0.0, + m[3] = 0.0, + m[4] = 0.0, + m[5] = p_rect.size.height, + m[6] = 0.0, + m[7] = 0.0, + m[8] = 0.0, + m[9] = 0.0, + m[10] = 1.0, + m[11] = 0.0, + m[12] = p_rect.pos.x, + m[13] = p_rect.pos.y, + m[14] = 0.0, + 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; } real_t CameraMatrix::get_aspect() const { - real_t w,h; - get_viewport_size(w,h); - return w/h; + real_t w, h; + get_viewport_size(w, h); + return w / h; } int CameraMatrix::get_pixels_per_meter(int p_for_pixel_width) const { - - Vector3 result = xform(Vector3(1,0,-1)); + Vector3 result = xform(Vector3(1, 0, -1)); return int((result.x * 0.5 + 0.5) * p_for_pixel_width); - } real_t CameraMatrix::get_fov() const { - const real_t * matrix = (const real_t*)this->matrix; + const real_t *matrix = (const real_t *)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 Rect3& p_aabb) { +void CameraMatrix::scale_translate_to_fit(const Rect3 &p_aabb) { Vector3 min = p_aabb.pos; - 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][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][3]=0; - matrix[1][3]=0; - matrix[2][3]=0; - matrix[3][3]=1; + 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][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][3] = 0; + matrix[1][3] = 0; + matrix[2][3] = 0; + matrix[3][3] = 1; } CameraMatrix::operator Transform() const { Transform tr; - const real_t *m=&matrix[0][0]; + const real_t *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; - real_t *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; + real_t *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; } -CameraMatrix::~CameraMatrix() -{ +CameraMatrix::~CameraMatrix() { } - - diff --git a/core/math/camera_matrix.h b/core/math/camera_matrix.h index c96f8259b5..857628c703 100644 --- a/core/math/camera_matrix.h +++ b/core/math/camera_matrix.h @@ -29,14 +29,12 @@ #ifndef CAMERA_MATRIX_H #define CAMERA_MATRIX_H -#include "transform.h" #include "math_2d.h" +#include "transform.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - - struct CameraMatrix { enum Planes { @@ -48,21 +46,20 @@ struct CameraMatrix { PLANE_BOTTOM }; - real_t matrix[4][4]; - + real_t matrix[4][4]; void set_identity(); void set_zero(); void set_light_bias(); - void set_light_atlas_rect(const Rect2& p_rect); - void set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far,bool p_flip_fov=false); - void set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar); - void set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar,bool p_flip_fov=false); + void set_light_atlas_rect(const Rect2 &p_rect); + void set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov = false); + void set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar); + void set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar, bool p_flip_fov = false); void set_frustum(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_near, real_t p_far); - static real_t get_fovy(real_t p_fovx,real_t p_aspect) { + static real_t get_fovy(real_t p_fovx, real_t 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); } real_t get_z_far() const; @@ -70,40 +67,39 @@ struct CameraMatrix { real_t get_aspect() const; real_t get_fov() const; - Vector<Plane> get_projection_planes(const Transform& p_transform) const; + Vector<Plane> get_projection_planes(const Transform &p_transform) const; - bool get_endpoints(const Transform& p_transform,Vector3 *p_8points) const; - void get_viewport_size(real_t& r_width, real_t& r_height) const; + bool get_endpoints(const Transform &p_transform, Vector3 *p_8points) const; + void get_viewport_size(real_t &r_width, real_t &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) const; - _FORCE_INLINE_ Vector3 xform(const Vector3& p_vec3) const; + Plane xform4(const Plane &p_vec4) const; + _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vec3) const; operator String() const; - void scale_translate_to_fit(const Rect3& p_aabb); + void scale_translate_to_fit(const Rect3 &p_aabb); void make_scale(const Vector3 &p_scale); int get_pixels_per_meter(int p_for_pixel_width) const; 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]; real_t 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 60fab6748a..d9d99b0384 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 { - real_t a=Math::random(0,1); - real_t b=Math::random(0,1); - if (a>b) { - SWAP(a,b); + real_t a = Math::random(0, 1); + real_t 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 Rect3& p_aabb) const { +bool Face3::intersects_aabb(const Rect3 &p_aabb) const { /** TEST PLANE **/ - if (!p_aabb.intersects_plane( get_plane() )) + if (!p_aabb.intersects_plane(get_plane())) return false; - /** TEST FACE AXIS */ - -#define TEST_AXIS(m_ax)\ - {\ - real_t aabb_min=p_aabb.pos.m_ax;\ - real_t aabb_max=p_aabb.pos.m_ax+p_aabb.size.m_ax;\ - real_t 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<aabb_min || aabb_max<tri_min)\ - return false;\ +/** TEST FACE AXIS */ + +#define TEST_AXIS(m_ax) \ + { \ + real_t aabb_min = p_aabb.pos.m_ax; \ + real_t aabb_max = p_aabb.pos.m_ax + p_aabb.size.m_ax; \ + real_t 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 < aabb_min || aabb_max < tri_min) \ + return false; \ } TEST_AXIS(x); @@ -235,221 +218,188 @@ bool Face3::intersects_aabb(const Rect3& 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(); - real_t minA,maxA,minB,maxB; - p_aabb.project_range_in_plane(Plane(axis,0),minA,maxA); - project_range(axis,Transform(),minB,maxB); + real_t minA, maxA, minB, maxB; + p_aabb.project_range_in_plane(Plane(axis, 0), minA, maxA); + project_range(axis, Transform(), minB, maxB); - if (maxA<minB || maxB<minA) + if (maxA < minB || maxB < minA) return false; } } return true; - } Face3::operator String() const { - return String()+vertex[0]+", "+vertex[1]+", "+vertex[2]; + return String() + vertex[0] + ", " + vertex[1] + ", " + vertex[2]; } -void Face3::project_range(const Vector3& p_normal,const Transform& p_transform,real_t& r_min, real_t& r_max) const { +void Face3::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - Vector3 v=p_transform.xform(vertex[i]); - real_t d=p_normal.dot(v); + Vector3 v = p_transform.xform(vertex[i]); + real_t d = p_normal.dot(v); - if (i==0 || d > 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; real_t support_max; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - real_t d=n.dot(vertex[i]); + real_t 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 - real_t dot=(vertex[i]-vertex[(i+1)%3]).normalized().dot(n); - dot=ABS(dot); + // check if edge is valid as a support + real_t 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 edge0 = vertex[1] - vertex[0]; - Vector3 edge1 = vertex[2] - vertex[0]; - Vector3 v0 = vertex[0] - p_point; - - real_t a = edge0.dot( edge0 ); - real_t b = edge0.dot( edge1 ); - real_t c = edge1.dot( edge1 ); - real_t d = edge0.dot( v0 ); - real_t e = edge1.dot( v0 ); - - real_t det = a*c - b*b; - real_t s = b*e - c*d; - real_t 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; - } - else - { - s = 0.f; - t = CLAMP( -e/c, 0.f, 1.f ); +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; + + real_t a = edge0.dot(edge0); + real_t b = edge0.dot(edge1); + real_t c = edge1.dot(edge1); + real_t d = edge0.dot(v0); + real_t e = edge1.dot(v0); + + real_t det = a * c - b * b; + real_t s = b * e - c * d; + real_t 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; + } 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 - { - real_t invDet = 1.f / det; - s *= invDet; - t *= invDet; - } - } - else - { - if ( s < 0.f ) - { - real_t tmp0 = b+d; - real_t tmp1 = c+e; - if ( tmp1 > tmp0 ) - { - real_t numer = tmp1 - tmp0; - real_t 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 ) - { - real_t numer = c+e-b-d; - real_t 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 { + real_t invDet = 1.f / det; + s *= invDet; + t *= invDet; } - else - { - real_t numer = c+e-b-d; - real_t denom = a-2*b+c; - s = CLAMP( numer/denom, 0.f, 1.f ); - t = 1.f - s; + } else { + if (s < 0.f) { + real_t tmp0 = b + d; + real_t tmp1 = c + e; + if (tmp1 > tmp0) { + real_t numer = tmp1 - tmp0; + real_t 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) { + real_t numer = c + e - b - d; + real_t 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 { + real_t numer = c + e - b - d; + real_t 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 a0da588ea5..6d15c60e3b 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 "rect3.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,real_t& r_min, real_t& 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, real_t &r_min, real_t &r_max) const; - Rect3 get_aabb() const { + Rect3 get_aabb() const { - Rect3 aabb( vertex[0], Vector3() ); - aabb.expand_to( vertex[1] ); - aabb.expand_to( vertex[2] ); - return aabb; - } + Rect3 aabb(vertex[0], Vector3()); + aabb.expand_to(vertex[1]); + aabb.expand_to(vertex[2]); + return aabb; + } - bool intersects_aabb(const Rect3& p_aabb) const; - _FORCE_INLINE_ bool intersects_aabb2(const Rect3& p_aabb) const; + bool intersects_aabb(const Rect3 &p_aabb) const; + _FORCE_INLINE_ bool intersects_aabb2(const Rect3 &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 Rect3 &p_aabb) const { -bool Face3::intersects_aabb2(const Rect3& 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); real_t d = perp.dot(vertex[0]); - real_t dist_a = perp.dot(ofs+sup)-d; - real_t dist_b = perp.dot(ofs-sup)-d; + real_t dist_a = perp.dot(ofs + sup) - d; + real_t 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)\ - {\ - real_t aabb_min=p_aabb.pos.m_ax;\ - real_t aabb_max=p_aabb.pos.m_ax+p_aabb.size.m_ax;\ - real_t 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<aabb_min || aabb_max<tri_min)\ - return false;\ +#define TEST_AXIS(m_ax) \ + { \ + real_t aabb_min = p_aabb.pos.m_ax; \ + real_t aabb_max = p_aabb.pos.m_ax + p_aabb.size.m_ax; \ + real_t 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 < aabb_min || aabb_max < tri_min) \ + return false; \ } TEST_AXIS(x); @@ -139,131 +136,125 @@ bool Face3::intersects_aabb2(const Rect3& 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); - real_t maxB = axis.dot(ofs+sup2); - real_t minB = axis.dot(ofs-sup2); - if (minB>maxB) { - SWAP(maxB,minB); + real_t maxB = axis.dot(ofs + sup2); + real_t minB = axis.dot(ofs - sup2); + if (minB > maxB) { + SWAP(maxB, minB); } - real_t minT=1e20,maxT=-1e20; - for (int k=0;k<3;k++) { + real_t minT = 1e20, maxT = -1e20; + for (int k = 0; k < 3; k++) { - real_t d=axis.dot(vertex[k]); + real_t d = axis.dot(vertex[k]); if (d > maxT) - maxT=d; + maxT = d; if (d < minT) - minT=d; + minT = d; } - if (maxB<minT || maxT<minB) + if (maxB < minT || maxT < minB) return false; } } return true; - - } - //this sucks... #endif // FACE3_H diff --git a/core/math/geometry.cpp b/core/math/geometry.cpp index 6570dfe672..ec4d352a8f 100644 --- a/core/math/geometry.cpp +++ b/core/math/geometry.cpp @@ -29,58 +29,54 @@ #include "geometry.h" #include "print_string.h" - - void Geometry::MeshData::optimize_vertices() { - Map<int,int> vtx_remap; + Map<int, int> vtx_remap; - for(int i=0;i<faces.size();i++) { + for (int i = 0; i < faces.size(); i++) { - for(int j=0;j<faces[i].indices.size();j++) { + for (int j = 0; j < faces[i].indices.size(); j++) { int idx = faces[i].indices[j]; if (!vtx_remap.has(idx)) { int ni = vtx_remap.size(); - vtx_remap[idx]=ni; - - + vtx_remap[idx] = ni; } - faces[i].indices[j]=vtx_remap[idx]; + faces[i].indices[j] = vtx_remap[idx]; } } - for(int i=0;i<edges.size();i++) { + for (int i = 0; i < edges.size(); i++) { int a = edges[i].a; int b = edges[i].b; if (!vtx_remap.has(a)) { int ni = vtx_remap.size(); - vtx_remap[a]=ni; + vtx_remap[a] = ni; } if (!vtx_remap.has(b)) { int ni = vtx_remap.size(); - vtx_remap[b]=ni; + vtx_remap[b] = ni; } - edges[i].a=vtx_remap[a]; - edges[i].b=vtx_remap[b]; + edges[i].a = vtx_remap[a]; + edges[i].b = vtx_remap[b]; } Vector<Vector3> new_vertices; new_vertices.resize(vtx_remap.size()); - for(int i=0;i<vertices.size();i++) { + for (int i = 0; i < vertices.size(); i++) { if (vtx_remap.has(i)) - new_vertices[vtx_remap[i]]=vertices[i]; + new_vertices[vtx_remap[i]] = vertices[i]; } - vertices=new_vertices; + vertices = new_vertices; } -Vector< Vector<Vector2> > (*Geometry::_decompose_func)(const Vector<Vector2>& p_polygon)=NULL; +Vector<Vector<Vector2> > (*Geometry::_decompose_func)(const Vector<Vector2> &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<len;i++) { + for (int i = 0; i < len; i++) { - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { p_faces[i].links[j].clear(); } } - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (p_faces[i].group!=p_group) + if (p_faces[i].group != p_group) continue; - for (int j=i+1;j<len;j++) { + for (int j = i + 1; j < len; j++) { - if (p_faces[j].group!=p_group) + if (p_faces[j].group != p_group) continue; - for (int k=0;k<3;k++) { + for (int k = 0; k < 3; k++) { - Vector3 vi1=p_faces[i].face.vertex[k]; - Vector3 vi2=p_faces[i].face.vertex[(k+1)%3]; + Vector3 vi1 = p_faces[i].face.vertex[k]; + Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3]; - for (int l=0;l<3;l++) { + for (int l = 0; l < 3; l++) { - Vector3 vj2=p_faces[j].face.vertex[l]; - Vector3 vj1=p_faces[j].face.vertex[(l+1)%3]; + Vector3 vj2 = p_faces[j].face.vertex[l]; + Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3]; - if (vi1.distance_to(vj1)<0.00001 && - vi2.distance_to(vj2)<0.00001 - ) { - if (p_faces[i].links[k].face!=-1) { + if (vi1.distance_to(vj1) < 0.00001 && + vi2.distance_to(vj2) < 0.00001) { + if (p_faces[i].links[k].face != -1) { ERR_PRINT("already linked\n"); - error=true; + error = true; break; } - if (p_faces[j].links[l].face!=-1) { + if (p_faces[j].links[l].face != -1) { ERR_PRINT("already linked\n"); - error=true; + error = true; break; } - p_faces[i].links[k].face=j; - p_faces[i].links[k].edge=l; - p_faces[j].links[l].face=i; - p_faces[j].links[l].edge=k; - } + p_faces[i].links[k].face = j; + p_faces[i].links[k].edge = l; + p_faces[j].links[l].face = i; + p_faces[j].links[l].edge = k; + } } if (error) break; - } if (error) break; - } if (error) break; } - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - p_faces[i].valid=true; - for (int j=0;j<3;j++) { + p_faces[i].valid = true; + for (int j = 0; j < 3; j++) { - if (p_faces[i].links[j].face==-1) - p_faces[i].valid=false; + if (p_faces[i].links[j].face == -1) + p_faces[i].valid = false; } /*printf("face %i is valid: %i, group %i. connected to %i:%i,%i:%i,%i:%i\n",i,p_faces[i].valid,p_faces[i].group, p_faces[i].links[0].face, @@ -187,152 +186,146 @@ static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) { return error; } -static bool _group_face(_FaceClassify *p_faces, int len, int p_index,int p_group) { +static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) { - if (p_faces[p_index].group>=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; } +PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_array) { -PoolVector< PoolVector< Face3 > > Geometry::separate_objects( PoolVector< Face3 > p_array ) { - - PoolVector< PoolVector< Face3 > > objects; + PoolVector<PoolVector<Face3> > objects; int len = p_array.size(); - PoolVector<Face3>::Read r=p_array.read(); + PoolVector<Face3>::Read r = p_array.read(); - const Face3* arrayptr = r.ptr(); + const Face3 *arrayptr = r.ptr(); - PoolVector< _FaceClassify> fc; + PoolVector<_FaceClassify> fc; - fc.resize( len ); + fc.resize(len); - PoolVector< _FaceClassify >::Write fcw=fc.write(); + PoolVector<_FaceClassify>::Write fcw = fc.write(); - _FaceClassify * _fcptr = fcw.ptr(); + _FaceClassify *_fcptr = fcw.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - _fcptr[i].face=arrayptr[i]; + _fcptr[i].face = arrayptr[i]; } - bool error=_connect_faces(_fcptr,len,-1); + bool error = _connect_faces(_fcptr, len, -1); if (error) { - ERR_FAIL_COND_V(error, PoolVector< PoolVector< Face3 > >() ); // invalid geometry + ERR_FAIL_COND_V(error, PoolVector<PoolVector<Face3> >()); // invalid geometry } /* group connected faces in separate objects */ - int group=0; - for (int i=0;i<len;i++) { + int group = 0; + for (int i = 0; i < len; i++) { if (!_fcptr[i].valid) continue; - if (_group_face(_fcptr,len,i,group)) { + if (_group_face(_fcptr, len, i, group)) { group++; } } /* group connected faces in separate objects */ + for (int i = 0; i < len; i++) { - for (int i=0;i<len;i++) { - - _fcptr[i].face=arrayptr[i]; + _fcptr[i].face = arrayptr[i]; } - if (group>=0) { + if (group >= 0) { objects.resize(group); - PoolVector< PoolVector<Face3> >::Write obw=objects.write(); - PoolVector< Face3 > *group_faces = obw.ptr(); + PoolVector<PoolVector<Face3> >::Write obw = objects.write(); + PoolVector<Face3> *group_faces = obw.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { if (!_fcptr[i].valid) continue; - if (_fcptr[i].group>=0 && _fcptr[i].group<group) { + if (_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) { - Rect3 aabb( Vector3(x,y,z),Vector3(len_x,len_y,len_z)); - aabb.pos=aabb.pos*voxelsize; - aabb.size=aabb.size*voxelsize; + Rect3 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; - -#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 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; \ } 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<div_x;i++) { - + for (int i = 0; i < div_x; i++) { - _SPLIT(i,div_x,x,len_x,new_x,new_len_x); + _SPLIT(i, div_x, x, len_x, new_x, new_len_x); - for (int j=0;j<div_y;j++) { + for (int j = 0; j < div_y; j++) { - _SPLIT(j,div_y,y,len_y,new_y,new_len_y); + _SPLIT(j, div_y, y, len_y, new_y, new_len_y); - for (int k=0;k<div_z;k++) { + for (int k = 0; k < div_z; k++) { - _SPLIT(k,div_z,z,len_z,new_z,new_len_z); + _SPLIT(k, div_z, z, len_z, new_z, new_len_z); - _plot_face(p_cell_status,new_x,new_y,new_z,new_len_x,new_len_y,new_len_z,voxelsize,p_face); + _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face); } } } } -static inline void _mark_outside(uint8_t*** p_cell_status,int x,int y,int z,int len_x,int len_y,int len_z) { +static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) { - if (p_cell_status[x][y][z]&3) + if (p_cell_status[x][y][z] & 3) return; // nothing to do, already used and/or visited - p_cell_status[x][y][z]=_CELL_PREV_FIRST; + p_cell_status[x][y][z] = _CELL_PREV_FIRST; - while(true) { + while (true) { uint8_t &c = p_cell_status[x][y][z]; //printf("at %i,%i,%i\n",x,y,z); - if ( (c&_CELL_STEP_MASK)==_CELL_STEP_NONE) { + if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) { /* Haven't been in here, mark as outside */ - p_cell_status[x][y][z]|=_CELL_EXTERIOR; + p_cell_status[x][y][z] |= _CELL_EXTERIOR; //printf("not marked as anything, marking exterior\n"); } //printf("cell step is %i\n",(c&_CELL_STEP_MASK)); - if ( (c&_CELL_STEP_MASK)!=_CELL_STEP_DONE) { + if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) { /* if not done, increase step */ - c+=1<<2; + c += 1 << 2; //printf("incrementing cell step\n"); } - if ( (c&_CELL_STEP_MASK)==_CELL_STEP_DONE) { + if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) { /* Go back */ //printf("done, going back a cell\n"); - switch(c&_CELL_PREV_MASK) { + switch (c & _CELL_PREV_MASK) { case _CELL_PREV_FIRST: { //printf("at end, finished marking\n"); return; } break; case _CELL_PREV_Y_POS: { y++; - ERR_FAIL_COND(y>=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,PoolVector<Face3>& 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, PoolVector<Face3> &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])); } - } -PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t *p_error ) { +PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) { #define _MIN_SIZE 1.0 #define _MAX_LENGTH 20 - int face_count=p_array.size(); - PoolVector<Face3>::Read facesr=p_array.read(); + int face_count = p_array.size(); + PoolVector<Face3>::Read facesr = p_array.read(); const Face3 *faces = facesr.ptr(); Rect3 global_aabb; - for(int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - if (i==0) { + if (i == 0) { - global_aabb=faces[i].get_aabb(); + global_aabb = faces[i].get_aabb(); } else { - global_aabb.merge_with( faces[i].get_aabb() ); + global_aabb.merge_with(faces[i].get_aabb()); } } global_aabb.grow_by(0.01); // avoid numerical error // determine amount of cells in grid axis - int div_x,div_y,div_z; + int div_x, div_y, div_z; - if (global_aabb.size.x/_MIN_SIZE<_MAX_LENGTH) - div_x=(int)(global_aabb.size.x/_MIN_SIZE)+1; + if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) + div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1; else - div_x=_MAX_LENGTH; + div_x = _MAX_LENGTH; - if (global_aabb.size.y/_MIN_SIZE<_MAX_LENGTH) - div_y=(int)(global_aabb.size.y/_MIN_SIZE)+1; + if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH) + div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1; else - div_y=_MAX_LENGTH; + div_y = _MAX_LENGTH; - if (global_aabb.size.z/_MIN_SIZE<_MAX_LENGTH) - div_z=(int)(global_aabb.size.z/_MIN_SIZE)+1; + if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH) + div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1; else - div_z=_MAX_LENGTH; - - Vector3 voxelsize=global_aabb.size; - voxelsize.x/=div_x; - voxelsize.y/=div_y; - voxelsize.z/=div_z; + div_z = _MAX_LENGTH; + Vector3 voxelsize = global_aabb.size; + voxelsize.x /= div_x; + voxelsize.y /= div_y; + voxelsize.z /= div_z; // create and initialize cells to zero //print_line("Wrapper: Initializing Cells"); - uint8_t ***cell_status=memnew_arr(uint8_t**,div_x); - for(int i=0;i<div_x;i++) { + uint8_t ***cell_status = memnew_arr(uint8_t **, div_x); + for (int i = 0; i < div_x; i++) { - cell_status[i]=memnew_arr(uint8_t*,div_y); + cell_status[i] = memnew_arr(uint8_t *, div_y); - for(int j=0;j<div_y;j++) { + for (int j = 0; j < div_y; j++) { - cell_status[i][j]=memnew_arr(uint8_t,div_z); + cell_status[i][j] = memnew_arr(uint8_t, div_z); - for(int k=0;k<div_z;k++) { + for (int k = 0; k < div_z; k++) { - cell_status[i][j][k]=0; + cell_status[i][j][k] = 0; } } } @@ -650,45 +634,44 @@ PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t // plot faces into cells //print_line("Wrapper (1/6): Plotting Faces"); - for (int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - Face3 f=faces[i]; - for (int j=0;j<3;j++) { + Face3 f = faces[i]; + for (int j = 0; j < 3; j++) { - f.vertex[j]-=global_aabb.pos; + f.vertex[j] -= global_aabb.pos; } - _plot_face(cell_status,0,0,0,div_x,div_y,div_z,voxelsize,f); + _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f); } - // determine which cells connect to the outside by traversing the outside and recursively flood-fill marking //print_line("Wrapper (2/6): Flood Filling"); - for (int i=0;i<div_x;i++) { + for (int i = 0; i < div_x; i++) { - for (int j=0;j<div_y;j++) { + for (int j = 0; j < div_y; j++) { - _mark_outside(cell_status,i,j,0,div_x,div_y,div_z); - _mark_outside(cell_status,i,j,div_z-1,div_x,div_y,div_z); + _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z); + _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z); } } - for (int i=0;i<div_z;i++) { + for (int i = 0; i < div_z; i++) { - for (int j=0;j<div_y;j++) { + for (int j = 0; j < div_y; j++) { - _mark_outside(cell_status,0,j,i,div_x,div_y,div_z); - _mark_outside(cell_status,div_x-1,j,i,div_x,div_y,div_z); + _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z); + _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z); } } - for (int i=0;i<div_x;i++) { + for (int i = 0; i < div_x; i++) { - for (int j=0;j<div_z;j++) { + for (int j = 0; j < div_z; j++) { - _mark_outside(cell_status,i,0,j,div_x,div_y,div_z); - _mark_outside(cell_status,i,div_y-1,j,div_x,div_y,div_z); + _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z); + _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z); } } @@ -698,13 +681,13 @@ PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t PoolVector<Face3> wrapped_faces; - for (int i=0;i<div_x;i++) { + for (int i = 0; i < div_x; i++) { - for (int j=0;j<div_y;j++) { + for (int j = 0; j < div_y; j++) { - for (int k=0;k<div_z;k++) { + for (int k = 0; k < div_z; k++) { - _build_faces(cell_status,i,j,k,div_x,div_y,div_z,wrapped_faces); + _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces); } } } @@ -713,36 +696,36 @@ PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t // transform face vertices to global coords - int wrapped_faces_count=wrapped_faces.size(); - PoolVector<Face3>::Write wrapped_facesw=wrapped_faces.write(); - Face3* wrapped_faces_ptr=wrapped_facesw.ptr(); + int wrapped_faces_count = wrapped_faces.size(); + PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write(); + Face3 *wrapped_faces_ptr = wrapped_facesw.ptr(); - for(int i=0;i<wrapped_faces_count;i++) { + for (int i = 0; i < wrapped_faces_count; i++) { - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - Vector3& v = wrapped_faces_ptr[i].vertex[j]; - v=v*voxelsize; - v+=global_aabb.pos; + Vector3 &v = wrapped_faces_ptr[i].vertex[j]; + v = v * voxelsize; + v += global_aabb.pos; } } // clean up grid //print_line("Wrapper (5/6): Grid Cleanup"); - for(int i=0;i<div_x;i++) { + for (int i = 0; i < div_x; i++) { - for(int j=0;j<div_y;j++) { + for (int j = 0; j < div_y; j++) { - memdelete_arr( cell_status[i][j] ); + memdelete_arr(cell_status[i][j]); } - memdelete_arr( cell_status[i] ); + memdelete_arr(cell_status[i]); } memdelete_arr(cell_status); if (p_error) - *p_error=voxelsize.length(); + *p_error = voxelsize.length(); //print_line("Wrapper (6/6): Finished."); return wrapped_faces; @@ -752,131 +735,125 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes MeshData mesh; - #define SUBPLANE_SIZE 1024.0 real_t subplane_size = 1024.0; // should compute this from the actual plane - for (int i=0;i<p_planes.size();i++) { + for (int i = 0; i < p_planes.size(); i++) { - Plane p =p_planes[i]; + Plane p = p_planes[i]; - Vector3 ref=Vector3(0.0,1.0,0.0); + Vector3 ref = Vector3(0.0, 1.0, 0.0); - if (ABS(p.normal.dot(ref))>0.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<Vector3> 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<p_planes.size();j++) { + for (int j = 0; j < p_planes.size(); j++) { - if (j==i) + if (j == i) continue; + Vector<Vector3> 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<vertices.size();k++) { + for (int k = 0; k < vertices.size(); k++) { - int k_n=(k+1)%vertices.size(); + int k_n = (k + 1) % vertices.size(); - Vector3 edge0_A=vertices[k]; - Vector3 edge1_A=vertices[k_n]; + Vector3 edge0_A = vertices[k]; + Vector3 edge1_A = vertices[k_n]; real_t dist0 = clip.distance_to(edge0_A); real_t dist1 = clip.distance_to(edge1_A); - - if ( dist0 <= 0 ) { // behind plane + if (dist0 <= 0) { // behind plane new_vertices.push_back(vertices[k]); } - // check for different sides and non coplanar - if ( (dist0*dist1) < 0) { + if ((dist0 * dist1) < 0) { // calculate intersection Vector3 rel = edge1_A - edge0_A; - real_t den=clip.normal.dot( rel ); - if (Math::abs(den)<CMP_EPSILON) + real_t den = clip.normal.dot(rel); + if (Math::abs(den) < CMP_EPSILON) continue; // point too short - real_t dist=-(clip.normal.dot( edge0_A )-clip.d)/den; - Vector3 inters = edge0_A+rel*dist; + real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den; + Vector3 inters = edge0_A + rel * dist; new_vertices.push_back(inters); } } - vertices=new_vertices; + vertices = new_vertices; } - if (vertices.size()<3) + if (vertices.size() < 3) continue; - //result is a clockwise face MeshData::Face face; // add face indices - for (int j=0;j<vertices.size();j++) { - + for (int j = 0; j < vertices.size(); j++) { - int idx=-1; - for (int k=0;k<mesh.vertices.size();k++) { + int idx = -1; + for (int k = 0; k < mesh.vertices.size(); k++) { - if (mesh.vertices[k].distance_to(vertices[j])<0.001) { + if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) { - idx=k; + idx = k; break; } } - if (idx==-1) { + if (idx == -1) { - idx=mesh.vertices.size(); + idx = mesh.vertices.size(); mesh.vertices.push_back(vertices[j]); } face.indices.push_back(idx); } - face.plane=p; + face.plane = p; mesh.faces.push_back(face); //add edge - for(int j=0;j<face.indices.size();j++) { + for (int j = 0; j < face.indices.size(); j++) { - int a=face.indices[j]; - int b=face.indices[(j+1)%face.indices.size()]; + int a = face.indices[j]; + int b = face.indices[(j + 1) % face.indices.size()]; - bool found=false; - for(int k=0;k<mesh.edges.size();k++) { + bool found = false; + for (int k = 0; k < mesh.edges.size(); k++) { - if (mesh.edges[k].a==a && mesh.edges[k].b==b) { - found=true; + if (mesh.edges[k].a == a && mesh.edges[k].b == b) { + found = true; break; } - if (mesh.edges[k].b==a && mesh.edges[k].a==b) { - found=true; + if (mesh.edges[k].b == a && mesh.edges[k].a == b) { + found = true; break; } } @@ -884,28 +861,25 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &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; } - -PoolVector<Plane> Geometry::build_box_planes(const Vector3& p_extents) { +PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) { PoolVector<Plane> 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 @@ PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_heig PoolVector<Plane> planes; - for (int i=0;i<p_sides;i++) { + for (int i = 0; i < p_sides; i++) { Vector3 normal; - normal[(p_axis+1)%3]=Math::cos(i*(2.0*Math_PI)/p_sides); - normal[(p_axis+2)%3]=Math::sin(i*(2.0*Math_PI)/p_sides); + normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides); + normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides); - planes.push_back( Plane( normal, p_radius ) ); + planes.push_back(Plane(normal, p_radius)); } Vector3 axis; - axis[p_axis]=1.0; + axis[p_axis] = 1.0; - planes.push_back( Plane( axis, p_height*0.5 ) ); - planes.push_back( Plane( -axis, p_height*0.5 ) ); + planes.push_back(Plane(axis, p_height * 0.5)); + planes.push_back(Plane(-axis, p_height * 0.5)); return planes; - } -PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats,int p_lons, Vector3::Axis p_axis) { - +PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) { PoolVector<Plane> 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<p_lons;i++) { + for (int i = 0; i < p_lons; i++) { Vector3 normal; - normal[(p_axis+1)%3]=Math::cos(i*(2.0*Math_PI)/p_lons); - normal[(p_axis+2)%3]=Math::sin(i*(2.0*Math_PI)/p_lons); + normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons); + normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons); - planes.push_back( Plane( normal, p_radius ) ); + planes.push_back(Plane(normal, p_radius)); - for (int j=1;j<=p_lats;j++) { + for (int j = 1; j <= p_lats; j++) { //todo this is stupid, fix - Vector3 angle = normal.linear_interpolate(axis,j/(real_t)p_lats).normalized(); - Vector3 pos = angle*p_radius; - planes.push_back( Plane( pos, angle ) ); - planes.push_back( Plane( pos * axis_neg, angle * axis_neg) ); - + Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized(); + Vector3 pos = angle * p_radius; + planes.push_back(Plane(pos, angle)); + planes.push_back(Plane(pos * axis_neg, angle * axis_neg)); } } return planes; - } PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) { PoolVector<Plane> 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_sides;i++) { + for (int i = 0; i < p_sides; i++) { Vector3 normal; - normal[(p_axis+1)%3]=Math::cos(i*(2.0*Math_PI)/p_sides); - normal[(p_axis+2)%3]=Math::sin(i*(2.0*Math_PI)/p_sides); - - planes.push_back( Plane( normal, p_radius ) ); + normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides); + normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides); - for (int j=1;j<=p_lats;j++) { + planes.push_back(Plane(normal, p_radius)); - Vector3 angle = normal.linear_interpolate(axis,j/(real_t)p_lats).normalized(); - Vector3 pos = axis*p_height*0.5 + angle*p_radius; - planes.push_back( Plane( pos, angle ) ); - planes.push_back( Plane( pos * axis_neg, angle * axis_neg) ); + for (int j = 1; j <= p_lats; j++) { + Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized(); + Vector3 pos = axis * p_height * 0.5 + angle * p_radius; + planes.push_back(Plane(pos, angle)); + planes.push_back(Plane(pos * axis_neg, angle * axis_neg)); } } - return planes; - } - struct _AtlasWorkRect { Size2i s; Point2i p; int idx; - _FORCE_INLINE_ bool operator<(const _AtlasWorkRect& p_r) const { return s.width > 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<Size2i>& p_rects,Vector<Point2i>& r_result, Size2i& r_size) { +void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &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<Size2i>& p_rects,Vector<Point2i>& 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<p_rects.size();i++) { - wrects[i].s=p_rects[i]; - wrects[i].idx=i; + for (int i = 0; i < p_rects.size(); i++) { + wrects[i].s = p_rects[i]; + wrects[i].idx = i; } wrects.sort(); int widest = wrects[0].s.width; Vector<_AtlasWorkRectResult> results; - for(int i=0;i<=12;i++) { + for (int i = 0; i <= 12; i++) { - int w = 1<<i; - int max_h=0; - int max_w=0; - if ( w < widest ) + int w = 1 << i; + int max_h = 0; + int max_w = 0; + if (w < widest) continue; Vector<int> hmax; hmax.resize(w); - for(int j=0;j<w;j++) - hmax[j]=0; + for (int j = 0; j < w; j++) + hmax[j] = 0; //place them - int ofs=0; - int limit_h=0; - for(int j=0;j<wrects.size();j++) { - + int ofs = 0; + int limit_h = 0; + for (int j = 0; j < wrects.size(); j++) { - if (ofs+wrects[j].s.width > w) { + if (ofs + wrects[j].s.width > w) { - ofs=0; + ofs = 0; } - int from_y=0; - for(int k=0;k<wrects[j].s.width;k++) { + int from_y = 0; + for (int k = 0; k < wrects[j].s.width; k++) { - if (hmax[ofs+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<wrects[j].s.width;k++) { + for (int k = 0; k < wrects[j].s.width; k++) { - hmax[ofs+k]=end_h; + hmax[ofs + k] = end_h; } if (end_h > 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; - real_t best_aspect=1e20; + int best = -1; + real_t best_aspect = 1e20; - for(int i=0;i<results.size();i++) { + for (int i = 0; i < results.size(); i++) { real_t h = nearest_power_of_2(results[i].max_h); real_t w = nearest_power_of_2(results[i].max_w); - real_t aspect = h>w ? h/w : w/h; + real_t 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<p_rects.size();i++) { + for (int i = 0; i < p_rects.size(); i++) { - r_result[ results[best].result[i].idx ]=results[best].result[i].p; + r_result[results[best].result[i].idx] = results[best].result[i].p; } - r_size=Size2(results[best].max_w,results[best].max_h ); - + r_size = Size2(results[best].max_w, results[best].max_h); } - - - - diff --git a/core/math/geometry.h b/core/math/geometry.h index 1dd7df038d..93ab0be2e0 100644 --- a/core/math/geometry.h +++ b/core/math/geometry.h @@ -29,26 +29,23 @@ #ifndef GEOMETRY_H #define GEOMETRY_H -#include "vector3.h" -#include "face3.h" #include "dvector.h" +#include "face3.h" #include "math_2d.h" -#include "vector.h" -#include "print_string.h" #include "object.h" +#include "print_string.h" #include "triangulate.h" +#include "vector.h" +#include "vector3.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class Geometry { Geometry(); -public: - - - - static real_t get_closest_points_between_segments( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2, Vector2& c1, Vector2& c2) { +public: + static real_t 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: real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative real_t f = d2.dot(r); - real_t s,t; + real_t 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 real_t b = d1.dot(d2); - real_t denom = a*e-b*b; // Always nonnegative + real_t 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.0) { - s = CLAMP((b*f - c*e) / denom, 0.0, 1.0); + s = CLAMP((b * f - c * e) / denom, 0.0, 1.0); } else s = 0.0; // 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,12 +103,10 @@ 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) - { + static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) { #if 0 //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) ) +#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 real_t 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) ); @@ -126,25 +121,24 @@ public: c2 = q1.linear_interpolate(q2,mub); #endif - Vector3 u = p2 - p1; - Vector3 v = q2 - q1; - Vector3 w = p1 - q1; - float a = u.dot(u); - float b = u.dot(v); - float c = v.dot(v); // always >= 0 - float d = u.dot(w); - float e = v.dot(w); - float D = a*c - b*b; // always >= 0 - float sc, tc; + Vector3 u = p2 - p1; + Vector3 v = q2 - q1; + Vector3 w = p1 - q1; + float a = u.dot(u); + float b = u.dot(v); + float c = v.dot(v); // always >= 0 + float d = u.dot(w); + float e = v.dot(w); + float D = a * c - b * b; // always >= 0 + float sc, tc; // compute the line parameters of the two closest points - if (D < CMP_EPSILON) { // the lines are almost parallel + if (D < CMP_EPSILON) { // the lines are almost parallel sc = 0.0; - tc = (b>c ? d/b : e/c); // use the largest denominator - } - else { - sc = (b*e - c*d) / D; - tc = (a*e - b*d) / D; + tc = (b > c ? d / b : e / c); // use the largest denominator + } else { + sc = (b * e - c * d) / D; + tc = (a * e - b * d) / D; } c1 = w + sc * u; @@ -153,92 +147,89 @@ public: //Vector dP = w + (sc * u) - (tc * v); // = L1(sc) - L2(tc) } - static real_t 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; - } - 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; + static real_t 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; + } else if (sN > sD) { // sc > 1 => the s=1 edge is visible + sN = sD; + tN = e + b; + tD = c; + } } - } - 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; + + 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; + } } - } - // 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); @@ -249,34 +240,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); @@ -287,124 +278,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); - real_t rel_l=rel.length(); - if (rel_l<CMP_EPSILON) + Vector3 sphere_pos = p_sphere_pos - p_from; + Vector3 rel = (p_to - p_from); + real_t rel_l = rel.length(); + if (rel_l < CMP_EPSILON) return false; // both points are the same - Vector3 normal=rel/rel_l; + Vector3 normal = rel / rel_l; - real_t sphere_d=normal.dot(sphere_pos); + real_t sphere_d = normal.dot(sphere_pos); //Vector3 ray_closest=normal*sphere_d; - real_t ray_distance=sphere_pos.distance_to(normal*sphere_d); + real_t ray_distance = sphere_pos.distance_to(normal * sphere_d); - if (ray_distance>=p_sphere_radius) + if (ray_distance >= p_sphere_radius) return false; - real_t inters_d2=p_sphere_radius*p_sphere_radius - ray_distance*ray_distance; - real_t inters_d=sphere_d; + real_t inters_d2 = p_sphere_radius * p_sphere_radius - ray_distance * ray_distance; + real_t 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, real_t p_height,real_t p_radius,Vector3* r_res=0,Vector3 *r_norm=0) { + static inline bool segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, real_t p_height, real_t p_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) { - Vector3 rel=(p_to-p_from); - real_t rel_l=rel.length(); - if (rel_l<CMP_EPSILON) + Vector3 rel = (p_to - p_from); + real_t rel_l = rel.length(); + if (rel_l < CMP_EPSILON) return false; // both points are the same // first check if they are parallel - Vector3 normal=(rel/rel_l); - Vector3 crs = normal.cross(Vector3(0,0,1)); - real_t crs_l=crs.length(); + Vector3 normal = (rel / rel_l); + Vector3 crs = normal.cross(Vector3(0, 0, 1)); + real_t crs_l = crs.length(); Vector3 z_dir; - if(crs_l<CMP_EPSILON) { + if (crs_l < CMP_EPSILON) { //blahblah parallel - z_dir=Vector3(1,0,0); //any x/y vector ok + z_dir = Vector3(1, 0, 0); //any x/y vector ok } else { - z_dir=crs/crs_l; + z_dir = crs / crs_l; } - real_t dist=z_dir.dot(p_from); + real_t dist = z_dir.dot(p_from); - if (dist>=p_radius) + if (dist >= p_radius) return false; // too far away // convert to 2D - real_t w2=p_radius*p_radius-dist*dist; - if (w2<CMP_EPSILON) + real_t w2 = p_radius * p_radius - dist * dist; + if (w2 < CMP_EPSILON) return false; //avoid numerical error - Size2 size(Math::sqrt(w2),p_height*0.5); - - Vector3 x_dir=z_dir.cross(Vector3(0,0,1)).normalized(); + Size2 size(Math::sqrt(w2), p_height * 0.5); - Vector2 from2D(x_dir.dot(p_from),p_from.z); - Vector2 to2D(x_dir.dot(p_to),p_to.z); + Vector3 x_dir = z_dir.cross(Vector3(0, 0, 1)).normalized(); - real_t min=0,max=1; + Vector2 from2D(x_dir.dot(p_from), p_from.z); + Vector2 to2D(x_dir.dot(p_to), p_to.z); - int axis=-1; + real_t min = 0, max = 1; - for(int i=0;i<2;i++) { + int axis = -1; - real_t seg_from=from2D[i]; - real_t seg_to=to2D[i]; - real_t box_begin=-size[i]; - real_t box_end=size[i]; - real_t cmin,cmax; + for (int i = 0; i < 2; i++) { + real_t seg_from = from2D[i]; + real_t seg_to = to2D[i]; + real_t box_begin = -size[i]; + real_t box_end = size[i]; + real_t cmin, cmax; 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; + 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; @@ -412,254 +401,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_l<CMP_EPSILON) + if (rel_l < CMP_EPSILON) return false; - Vector3 dir=rel/rel_l; + Vector3 dir = rel / rel_l; - int min_index=-1; + int min_index = -1; - for (int i=0;i<p_plane_count;i++) { + for (int i = 0; i < p_plane_count; i++) { - const Plane&p=p_planes[i]; + const Plane &p = p_planes[i]; - real_t den=p.normal.dot( dir ); + real_t den = p.normal.dot(dir); //printf("den is %i\n",den); - if (Math::abs(den)<=CMP_EPSILON) + if (Math::abs(den) <= CMP_EPSILON) continue; // ignore parallel plane + real_t dist = -p.distance_to(p_from) / den; - real_t dist=-p.distance_to(p_from ) / den; - - if (den>0) { + if (den > 0) { //backwards facing plane - if (dist<max) - max=dist; + if (dist < max) + max = dist; } else { //front facing plane - if (dist>min) { - 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]; - real_t l =n.length(); - if (l<1e-10) + Vector3 p = p_point - p_segment[0]; + Vector3 n = p_segment[1] - p_segment[0]; + real_t l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - real_t d=n.dot(p); + real_t 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]; - real_t l =n.length(); - if (l<1e-10) + Vector3 p = p_point - p_segment[0]; + Vector3 n = p_segment[1] - p_segment[0]; + real_t l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - real_t d=n.dot(p); + real_t 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]; - real_t l =n.length(); - if (l<1e-10) + Vector2 p = p_point - p_segment[0]; + Vector2 n = p_segment[1] - p_segment[0]; + real_t l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - real_t d=n.dot(p); + real_t 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]; - real_t l =n.length(); - if (l<1e-10) + Vector2 p = p_point - p_segment[0]; + Vector2 n = p_segment[1] - p_segment[0]; + real_t l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - real_t d=n.dot(p); + real_t 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; - real_t ABpos=D.x+(C.x-D.x)*D.y/(D.y-C.y); + real_t 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 face_n = (p_v1 - p_v3).cross(p_v1 - p_v2); - Vector3 n1 = (p_point-p_v3).cross(p_point-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) { - real_t d=p_normal.dot(p_sphere_pos)-p_normal.dot(p_triangle[0]); + real_t 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 - real_t ad=axis.dot(n2); + real_t 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; } @@ -669,34 +649,34 @@ public: real_t sphere_at = n1.dot(n2); - if (sphere_at>=0 && sphere_at<n1.dot(n1)) { + if (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; } - real_t r2=p_sphere_radius*p_sphere_radius; + real_t r2 = p_sphere_radius * p_sphere_radius; - if (n2.length_squared()<r2) { + if (n2.length_squared() < r2) { - Vector3 n=(p_sphere_pos-verts[i+1]).normalized(); + Vector3 n = (p_sphere_pos - verts[i + 1]).normalized(); //r_triangle_contact=verts[i+1]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2)); - r_triangle_contact=verts[i+1]; - r_sphere_contact=p_sphere_pos-n*p_sphere_radius; + r_triangle_contact = verts[i + 1]; + r_sphere_contact = p_sphere_pos - n * p_sphere_radius; //printf("solved inside point segment 1\n"); return true; } - if (n2.distance_squared_to(n1)<r2) { - Vector3 n=(p_sphere_pos-verts[i]).normalized(); + if (n2.distance_squared_to(n1) < r2) { + Vector3 n = (p_sphere_pos - verts[i]).normalized(); //r_triangle_contact=verts[i]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2)); - r_triangle_contact=verts[i]; - r_sphere_contact=p_sphere_pos-n*p_sphere_radius; + r_triangle_contact = verts[i]; + r_sphere_contact = p_sphere_pos - n * p_sphere_radius; //printf("solved inside point segment 1\n"); return true; } @@ -707,56 +687,51 @@ public: return false; } + static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) { + Vector2 line_vec = p_to - p_from; + Vector2 vec_to_line = p_from - p_circle_pos; - static real_t segment_intersects_circle(const Vector2& p_from, const Vector2& p_to, const Vector2& p_circle_pos, real_t p_circle_radius) { - - Vector2 line_vec = p_to - p_from; - Vector2 vec_to_line = p_from - p_circle_pos; - - /* create a quadratic formula of the form ax^2 + bx + c = 0 */ - real_t a, b, c; + /* create a quadratic formula of the form ax^2 + bx + c = 0 */ + real_t a, b, c; - a = line_vec.dot(line_vec); - b = 2 * vec_to_line.dot(line_vec); - c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius; + a = line_vec.dot(line_vec); + b = 2 * vec_to_line.dot(line_vec); + c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius; - /* solve for t */ - real_t sqrtterm = b*b - 4*a*c; + /* solve for t */ + real_t sqrtterm = b * b - 4 * a * c; - /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */ - if(sqrtterm < 0) return -1; + /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */ + if (sqrtterm < 0) return -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; + /* 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<Vector3> clip_polygon(const Vector<Vector3>& polygon,const Plane& p_plane) { + static inline Vector<Vector3> clip_polygon(const Vector<Vector3> &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++) { //real_t p_plane.d = (*this) * polygon[a]; real_t 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 { @@ -785,24 +760,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]; - - Vector3 segment= v1 - v2; - real_t den=p_plane.normal.dot( segment ); - real_t dist=p_plane.distance_to( v1 ) / den; - dist=-dist; - clipped.push_back( v1 + segment * dist ); + const Vector3 &v1 = polygon[previous]; + const Vector3 &v2 = polygon[index]; + + Vector3 segment = v1 - v2; + real_t den = p_plane.normal.dot(segment); + real_t 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; - real_t den=p_plane.normal.dot( segment ); - real_t dist=p_plane.distance_to( v1 ) / den; - dist=-dist; - clipped.push_back( v1 + segment * dist ); + const Vector3 &v2 = polygon[previous]; + Vector3 segment = v1 - v2; + real_t den = p_plane.normal.dot(segment); + real_t dist = p_plane.distance_to(v1) / den; + dist = -dist; + clipped.push_back(v1 + segment * dist); } clipped.push_back(v1); @@ -814,30 +789,26 @@ public: return clipped; } - - static Vector<int> triangulate_polygon(const Vector<Vector2>& p_polygon) { + static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) { Vector<int> triangles; - if (!Triangulate::triangulate(p_polygon,triangles)) + if (!Triangulate::triangulate(p_polygon, triangles)) return Vector<int>(); //fail return triangles; } - static Vector< Vector<Vector2> > (*_decompose_func)(const Vector<Vector2>& p_polygon); - static Vector< Vector<Vector2> > decompose_polygon(const Vector<Vector2>& p_polygon) { + static Vector<Vector<Vector2> > (*_decompose_func)(const Vector<Vector2> &p_polygon); + static Vector<Vector<Vector2> > decompose_polygon(const Vector<Vector2> &p_polygon) { if (_decompose_func) return _decompose_func(p_polygon); - return Vector< Vector<Vector2> >(); - + return Vector<Vector<Vector2> >(); } + static PoolVector<PoolVector<Face3> > separate_objects(PoolVector<Face3> p_array); - static PoolVector< PoolVector< Face3 > > separate_objects( PoolVector< Face3 > p_array ); - - static PoolVector< Face3 > wrap_geometry( PoolVector< Face3 > p_array, real_t *p_error=NULL ); ///< create a "wrap" that encloses the given geometry - + static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL); ///< create a "wrap" that encloses the given geometry struct MeshData { @@ -850,94 +821,89 @@ public: struct Edge { - int a,b; + int a, b; }; Vector<Edge> edges; - Vector< Vector3 > vertices; + Vector<Vector3> 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<<p_idx); - if (p_idx<8) - ret|=24; + int mask = ret | (1 << p_idx); + if (p_idx < 8) + ret |= 24; else - ret|=mask>>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 real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) - { + static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) { return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(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<Point2> convex_hull_2d(Vector<Point2> P) - { + static Vector<Point2> convex_hull_2d(Vector<Point2> P) { int n = P.size(), k = 0; Vector<Point2> 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]; } @@ -946,16 +912,12 @@ public: } static MeshData build_convex_mesh(const PoolVector<Plane> &p_planes); - static PoolVector<Plane> build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis=Vector3::AXIS_Z); - static PoolVector<Plane> build_box_planes(const Vector3& p_extents); - static PoolVector<Plane> build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z); - static PoolVector<Plane> build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis=Vector3::AXIS_Z); - - static void make_atlas(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, Size2i& r_size); - + static PoolVector<Plane> build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z); + static PoolVector<Plane> build_box_planes(const Vector3 &p_extents); + static PoolVector<Plane> build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z); + static PoolVector<Plane> build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z); + static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size); }; - - #endif diff --git a/core/math/math_2d.cpp b/core/math/math_2d.cpp index 76eeece688..021b1fbf55 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(y,x); + return Math::atan2(y, x); } real_t Vector2::length() const { - return Math::sqrt( x*x + y*y ); + return Math::sqrt(x * x + y * y); } real_t Vector2::length_squared() const { - return x*x + y*y; + return x * x + y * y; } void Vector2::normalize() { - real_t l = x*x + y*y; - if (l!=0) { + real_t 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; } -real_t Vector2::distance_to(const Vector2& p_vector2) const { +real_t 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)); } -real_t Vector2::distance_squared_to(const Vector2& p_vector2) const { +real_t 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); } -real_t Vector2::angle_to(const Vector2& p_vector2) const { +real_t Vector2::angle_to(const Vector2 &p_vector2) const { - return Math::atan2( cross(p_vector2), dot(p_vector2) ); + return Math::atan2(cross(p_vector2), dot(p_vector2)); } -real_t Vector2::angle_to_point(const Vector2& p_vector2) const { +real_t Vector2::angle_to_point(const Vector2 &p_vector2) const { - return Math::atan2( y - p_vector2.y, x-p_vector2.x ); + return Math::atan2(y - p_vector2.y, x - p_vector2.x); } -real_t Vector2::dot(const Vector2& p_other) const { +real_t 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; } -real_t Vector2::cross(const Vector2& p_other) const { +real_t 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 real_t &rvalue) const { }; void Vector2::operator*=(const real_t &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 real_t &rvalue) const { void Vector2::operator/=(const real_t &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(real_t 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<l) { + if (l > 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,real_t p_t) const { +Vector2 Vector2::cubic_interpolate_soft(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t 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,real_t p_t) const { - - +Vector2 Vector2::cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t 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; real_t t = p_t; real_t t2 = t * t; real_t t3 = t2 * t; Vector2 out; - out = 0.5 * ( ( p1 * 2.0) + - ( -p0 + p2 ) * t + - ( 2.0 * p0 - 5.0 * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0 * p1 - 3.0 * p2 + p3 ) * t3 ); + out = 0.5 * ((p1 * 2.0) + + (-p0 + p2) * t + + (2.0 * p0 - 5.0 * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); return out; -/* + /* real_t mu = p_t; real_t 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; + real_t sign = 0; - real_t min=0,max=1; - int axis=0; - real_t 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; real_t 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,225 +389,215 @@ 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 Transform2D::invert() { // FIXME: this function assumes the basis is a rotation matrix, with no scaling. // Transform2D::affine_inverse can handle matrices with scaling, so GDScript should eventually use that. - SWAP(elements[0][1],elements[1][0]); + SWAP(elements[0][1], elements[1][0]); elements[2] = basis_xform(-elements[2]); } Transform2D Transform2D::inverse() const { - Transform2D inv=*this; + Transform2D inv = *this; inv.invert(); return inv; - } void Transform2D::affine_invert() { real_t det = basis_determinant(); - ERR_FAIL_COND(det==0); + ERR_FAIL_COND(det == 0); real_t 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]); - } Transform2D Transform2D::affine_inverse() const { - Transform2D inv=*this; + Transform2D inv = *this; inv.affine_invert(); return inv; } void Transform2D::rotate(real_t p_phi) { - *this = Transform2D(p_phi,Vector2()) * (*this); + *this = Transform2D(p_phi, Vector2()) * (*this); } real_t Transform2D::get_rotation() const { real_t det = basis_determinant(); Transform2D m = orthonormalized(); if (det < 0) { - m.scale_basis(Size2(-1,-1)); + m.scale_basis(Size2(-1, -1)); } - return Math::atan2(m[0].y,m[0].x); + return Math::atan2(m[0].y, m[0].x); } void Transform2D::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[0][1]=sr; - elements[1][0]=-sr; - elements[1][1]=cr; + elements[0][0] = cr; + elements[0][1] = sr; + elements[1][0] = -sr; + elements[1][1] = cr; } -Transform2D::Transform2D(real_t p_rot, const Vector2& p_pos) { +Transform2D::Transform2D(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[0][1]=sr; - elements[1][0]=-sr; - elements[1][1]=cr; - elements[2]=p_pos; + elements[0][0] = cr; + elements[0][1] = sr; + elements[1][0] = -sr; + elements[1][1] = cr; + elements[2] = p_pos; } Size2 Transform2D::get_scale() const { real_t det_sign = basis_determinant() > 0 ? 1 : -1; - return det_sign * Size2( elements[0].length(), elements[1].length() ); + return det_sign * Size2(elements[0].length(), elements[1].length()); } -void Transform2D::scale(const Size2& p_scale) { +void Transform2D::scale(const Size2 &p_scale) { scale_basis(p_scale); - elements[2]*=p_scale; + elements[2] *= p_scale; } -void Transform2D::scale_basis(const Size2& p_scale) { - - elements[0][0]*=p_scale.x; - elements[0][1]*=p_scale.y; - elements[1][0]*=p_scale.x; - elements[1][1]*=p_scale.y; +void Transform2D::scale_basis(const Size2 &p_scale) { + elements[0][0] *= p_scale.x; + elements[0][1] *= p_scale.y; + elements[1][0] *= p_scale.x; + elements[1][1] *= p_scale.y; } -void Transform2D::translate( real_t p_tx, real_t p_ty) { +void Transform2D::translate(real_t p_tx, real_t p_ty) { - translate(Vector2(p_tx,p_ty)); + translate(Vector2(p_tx, p_ty)); } -void Transform2D::translate( const Vector2& p_translation ) { +void Transform2D::translate(const Vector2 &p_translation) { - elements[2]+=basis_xform(p_translation); + elements[2] += basis_xform(p_translation); } void Transform2D::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; } Transform2D Transform2D::orthonormalized() const { - Transform2D on=*this; + Transform2D on = *this; on.orthonormalize(); return on; - } -bool Transform2D::operator==(const Transform2D& p_transform) const { +bool Transform2D::operator==(const Transform2D &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 Transform2D::operator!=(const Transform2D& p_transform) const { +bool Transform2D::operator!=(const Transform2D &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 Transform2D::operator*=(const Transform2D& p_transform) { +void Transform2D::operator*=(const Transform2D &p_transform) { elements[2] = xform(p_transform.elements[2]); - real_t x0,x1,y0,y1; + real_t 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; } - -Transform2D Transform2D::operator*(const Transform2D& p_transform) const { +Transform2D Transform2D::operator*(const Transform2D &p_transform) const { Transform2D t = *this; - t*=p_transform; + t *= p_transform; return t; - } -Transform2D Transform2D::scaled(const Size2& p_scale) const { +Transform2D Transform2D::scaled(const Size2 &p_scale) const { - Transform2D copy=*this; + Transform2D copy = *this; copy.scale(p_scale); return copy; - } -Transform2D Transform2D::basis_scaled(const Size2& p_scale) const { +Transform2D Transform2D::basis_scaled(const Size2 &p_scale) const { - Transform2D copy=*this; + Transform2D copy = *this; copy.scale_basis(p_scale); return copy; - } Transform2D Transform2D::untranslated() const { - Transform2D copy=*this; - copy.elements[2]=Vector2(); + Transform2D copy = *this; + copy.elements[2] = Vector2(); return copy; } -Transform2D Transform2D::translated(const Vector2& p_offset) const { +Transform2D Transform2D::translated(const Vector2 &p_offset) const { - Transform2D copy=*this; + Transform2D copy = *this; copy.translate(p_offset); return copy; - } Transform2D Transform2D::rotated(real_t p_phi) const { - Transform2D copy=*this; + Transform2D copy = *this; copy.rotate(p_phi); return copy; - } real_t Transform2D::basis_determinant() const { @@ -617,7 +605,7 @@ real_t Transform2D::basis_determinant() const { return elements[0].x * elements[1].y - elements[0].y * elements[1].x; } -Transform2D Transform2D::interpolate_with(const Transform2D& p_transform, real_t p_c) const { +Transform2D Transform2D::interpolate_with(const Transform2D &p_transform, real_t p_c) const { //extract parameters Vector2 p1 = get_origin(); @@ -642,9 +630,9 @@ Transform2D Transform2D::interpolate_with(const Transform2D& p_transform, real_t 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 @@ -655,5 +643,5 @@ Transform2D Transform2D::interpolate_with(const Transform2D& p_transform, real_t Transform2D::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 a24c4266ee..af6437d7f1 100644 --- a/core/math/math_2d.h +++ b/core/math/math_2d.h @@ -73,12 +73,11 @@ struct Vector2 { real_t height; }; - - _FORCE_INLINE_ real_t& operator[](int p_idx) { - return p_idx?y:x; + _FORCE_INLINE_ real_t &operator[](int p_idx) { + return p_idx ? y : x; } - _FORCE_INLINE_ const real_t& operator[](int p_idx) const { - return p_idx?y:x; + _FORCE_INLINE_ const real_t &operator[](int p_idx) const { + return p_idx ? y : x; } void normalize(); @@ -87,32 +86,32 @@ struct Vector2 { real_t length() const; real_t length_squared() const; - real_t distance_to(const Vector2& p_vector2) const; - real_t distance_squared_to(const Vector2& p_vector2) const; - real_t angle_to(const Vector2& p_vector2) const; - real_t angle_to_point(const Vector2& p_vector2) const; + real_t distance_to(const Vector2 &p_vector2) const; + real_t distance_squared_to(const Vector2 &p_vector2) const; + real_t angle_to(const Vector2 &p_vector2) const; + real_t angle_to_point(const Vector2 &p_vector2) const; - real_t dot(const Vector2& p_other) const; - real_t cross(const Vector2& p_other) const; + real_t dot(const Vector2 &p_other) const; + real_t 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,real_t p_t); - _FORCE_INLINE_ Vector2 linear_interpolate(const Vector2& p_b,real_t p_t) const; - Vector2 cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,real_t p_t) const; - Vector2 cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,real_t p_t) const; + _FORCE_INLINE_ static Vector2 linear_interpolate(const Vector2 &p_a, const Vector2 &p_b, real_t p_t); + _FORCE_INLINE_ Vector2 linear_interpolate(const Vector2 &p_b, real_t p_t) const; + Vector2 cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t p_t) const; + Vector2 cubic_interpolate_soft(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t 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 real_t &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_vec2.y):(x<p_vec2.x); } - bool operator<=(const Vector2& p_vec2) const { return (x==p_vec2.x)?(y<=p_vec2.y):(x<=p_vec2.x); } + bool operator<(const Vector2 &p_vec2) const { return (x == p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); } + bool operator<=(const Vector2 &p_vec2) const { return (x == p_vec2.x) ? (y <= p_vec2.y) : (x <= p_vec2.x); } real_t angle() const; void set_rotation(real_t p_radians) { - x=Math::cos(p_radians); - y=Math::sin(p_radians); + x = Math::cos(p_radians); + y = Math::sin(p_radians); } _FORCE_INLINE_ Vector2 abs() const { - return Vector2( Math::abs(x), Math::abs(y) ); + return Vector2(Math::abs(x), Math::abs(y)); } Vector2 rotated(real_t p_by) const; Vector2 tangent() const { - return Vector2(y,-x); + return Vector2(y, -x); } Vector2 floor() const; - Vector2 snapped(const Vector2& p_by) const; - real_t aspect() const { return width/height; } - + Vector2 snapped(const Vector2 &p_by) const; + real_t aspect() const { return width / height; } - operator String() const { return String::num(x)+", "+String::num(y); } + operator String() const { return String::num(x) + ", " + String::num(y); } - _FORCE_INLINE_ Vector2(real_t p_x,real_t p_y) { x=p_x; y=p_y; } - _FORCE_INLINE_ Vector2() { x=0; y=0; } + _FORCE_INLINE_ Vector2(real_t p_x, real_t p_y) { + x = p_x; + y = p_y; + } + _FORCE_INLINE_ Vector2() { + x = 0; + y = 0; + } }; -_FORCE_INLINE_ Vector2 Vector2::plane_project(real_t p_d, const Vector2& p_vec) const { +_FORCE_INLINE_ Vector2 Vector2::plane_project(real_t p_d, const Vector2 &p_vec) const { - return p_vec - *this * ( dot(p_vec) -p_d); + return p_vec - *this * (dot(p_vec) - p_d); } +_FORCE_INLINE_ Vector2 operator*(real_t p_scalar, const Vector2 &p_vec) { -_FORCE_INLINE_ Vector2 operator*(real_t p_scalar, const Vector2& p_vec) { - - return p_vec*p_scalar; + return p_vec * p_scalar; } -Vector2 Vector2::linear_interpolate(const Vector2& p_b,real_t p_t) const { +Vector2 Vector2::linear_interpolate(const Vector2 &p_b, real_t p_t) const { - Vector2 res=*this; + Vector2 res = *this; - res.x+= (p_t * (p_b.x-x)); - res.y+= (p_t * (p_b.y-y)); + res.x += (p_t * (p_b.x - x)); + res.y += (p_t * (p_b.y - y)); return res; - } -Vector2 Vector2::linear_interpolate(const Vector2& p_a, const Vector2& p_b,real_t p_t) { +Vector2 Vector2::linear_interpolate(const Vector2 &p_a, const Vector2 &p_b, real_t p_t) { - Vector2 res=p_a; + Vector2 res = p_a; - res.x+= (p_t * (p_b.x-p_a.x)); - res.y+= (p_t * (p_b.y-p_a.y)); + res.x += (p_t * (p_b.x - p_a.x)); + res.y += (p_t * (p_b.y - p_a.y)); return res; } @@ -200,170 +202,170 @@ typedef Vector2 Point2; struct Transform2D; - struct Rect2 { Point2 pos; Size2 size; - const Vector2& get_pos() const { return pos; } - void set_pos(const Vector2& p_pos) { pos=p_pos; } - const Vector2& get_size() const { return size; } - void set_size(const Vector2& p_size) { size=p_size; } + const Vector2 &get_pos() const { return pos; } + void set_pos(const Vector2 &p_pos) { pos = p_pos; } + const Vector2 &get_size() const { return size; } + void set_size(const Vector2 &p_size) { size = p_size; } - real_t get_area() const { return size.width*size.height; } + real_t get_area() const { return size.width * size.height; } - inline bool intersects(const Rect2& p_rect) const { - if ( pos.x >= (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 real_t distance_to(const Vector2& p_point) const { + inline real_t distance_to(const Vector2 &p_point) const { real_t 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 Transform2D& 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; + _FORCE_INLINE_ bool intersects_transformed(const Transform2D &p_xform, const Rect2 &p_rect) const; - inline bool encloses(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; - 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.x<begin.x) - begin.x=p_vector.x; - if (p_vector.y<begin.y) - begin.y=p_vector.y; + 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.x>end.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( real_t p_x, real_t p_y, real_t p_width, real_t 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(real_t p_x, real_t p_y, real_t p_width, real_t 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<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 { 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; - real_t get_aspect() const { return width/(real_t)height; } + real_t get_aspect() const { return width / (real_t)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,133 +434,136 @@ 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.x<begin.x) - begin.x=p_vector.x; - if (p_vector.y<begin.y) - begin.y=p_vector.y; + 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.x>end.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 Transform2D { // Warning #1: basis of Transform2D is stored differently from Basis. In terms of elements array, the basis matrix looks like "on paper": // M = (elements[0][0] elements[1][0]) @@ -558,21 +571,27 @@ struct Transform2D { // This is such that the columns, which can be interpreted as basis vectors of the coordinate system "painted" on the object, can be accessed as elements[i]. // Note that this is the opposite of the indices in mathematical texts, meaning: $M_{12}$ in a math book corresponds to elements[1][0] here. // This requires additional care when working with explicit indices. - // See https://en.wikipedia.org/wiki/Row-_and_column-major_order for further reading. + // See https://en.wikipedia.org/wiki/Row-_and_column-major_order for further reading. // Warning #2: 2D be aware that unlike 3D code, 2D code uses a left-handed coordinate system: Y-axis points down, // and angle is measure from +X to +Y in a clockwise-fashion. Vector2 elements[3]; - _FORCE_INLINE_ real_t tdotx(const Vector2& v) const { return elements[0][0] * v.x + elements[1][0] * v.y; } - _FORCE_INLINE_ real_t tdoty(const Vector2& v) const { return elements[0][1] * v.x + elements[1][1] * v.y; } + _FORCE_INLINE_ real_t tdotx(const Vector2 &v) const { return elements[0][0] * v.x + elements[1][0] * v.y; } + _FORCE_INLINE_ real_t 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(); Transform2D inverse() const; @@ -582,24 +601,24 @@ struct Transform2D { 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); real_t 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; } - Transform2D scaled(const Size2& p_scale) const; - Transform2D basis_scaled(const Size2& p_scale) const; - Transform2D translated(const Vector2& p_offset) const; + Transform2D scaled(const Size2 &p_scale) const; + Transform2D basis_scaled(const Size2 &p_scale) const; + Transform2D translated(const Vector2 &p_offset) const; Transform2D rotated(real_t p_phi) const; Transform2D untranslated() const; @@ -607,20 +626,20 @@ struct Transform2D { void orthonormalize(); Transform2D orthonormalized() const; - bool operator==(const Transform2D& p_transform) const; - bool operator!=(const Transform2D& p_transform) const; + bool operator==(const Transform2D &p_transform) const; + bool operator!=(const Transform2D &p_transform) const; - void operator*=(const Transform2D& p_transform); - Transform2D operator*(const Transform2D& p_transform) const; + void operator*=(const Transform2D &p_transform); + Transform2D operator*(const Transform2D &p_transform) const; - Transform2D interpolate_with(const Transform2D& p_transform, real_t p_c) const; + Transform2D interpolate_with(const Transform2D &p_transform, real_t 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; @@ -634,232 +653,226 @@ struct Transform2D { elements[2][1] = oy; } - Transform2D(real_t p_rot, const Vector2& p_pos); - Transform2D() { elements[0][0]=1.0; elements[1][1]=1.0; } + Transform2D(real_t p_rot, const Vector2 &p_pos); + Transform2D() { + elements[0][0] = 1.0; + elements[1][1] = 1.0; + } }; -bool Rect2::intersects_transformed(const Transform2D& p_xform, const Rect2& p_rect) const { +bool Rect2::intersects_transformed(const Transform2D &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].y<low_limit) + if (xf_points[0].y < low_limit) goto next2; - if (xf_points[1].y<low_limit) + if (xf_points[1].y < low_limit) goto next2; - if (xf_points[2].y<low_limit) + if (xf_points[2].y < low_limit) goto next2; - if (xf_points[3].y<low_limit) + if (xf_points[3].y < low_limit) goto next2; return false; - next2: +next2: - if (xf_points[0].x>pos.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<low_limit) + if (xf_points[0].x < low_limit) goto next4; - if (xf_points[1].x<low_limit) + if (xf_points[1].x < low_limit) goto next4; - if (xf_points[2].x<low_limit) + if (xf_points[2].x < low_limit) goto next4; - if (xf_points[3].x<low_limit) + if (xf_points[3].x < low_limit) goto next4; return false; - next4: +next4: - Vector2 xf_points2[4]={ + Vector2 xf_points2[4] = { pos, - Vector2(pos.x+size.x,pos.y), - Vector2(pos.x,pos.y+size.y), - Vector2(pos.x+size.x,pos.y+size.y), + Vector2(pos.x + size.x, pos.y), + Vector2(pos.x, pos.y + size.y), + Vector2(pos.x + size.x, pos.y + size.y), }; - real_t maxa=p_xform.elements[0].dot(xf_points2[0]); - real_t mina=maxa; + real_t maxa = p_xform.elements[0].dot(xf_points2[0]); + real_t mina = maxa; real_t dp = p_xform.elements[0].dot(xf_points2[1]); - maxa=MAX(dp,maxa); - mina=MIN(dp,mina); + maxa = MAX(dp, maxa); + mina = MIN(dp, mina); dp = p_xform.elements[0].dot(xf_points2[2]); - maxa=MAX(dp,maxa); - mina=MIN(dp,mina); + maxa = MAX(dp, maxa); + mina = MIN(dp, mina); dp = p_xform.elements[0].dot(xf_points2[3]); - maxa=MAX(dp,maxa); - mina=MIN(dp,mina); + maxa = MAX(dp, maxa); + mina = MIN(dp, mina); - real_t maxb=p_xform.elements[0].dot(xf_points[0]); - real_t minb=maxb; + real_t maxb = p_xform.elements[0].dot(xf_points[0]); + real_t minb = maxb; dp = p_xform.elements[0].dot(xf_points[1]); - maxb=MAX(dp,maxb); - minb=MIN(dp,minb); + maxb = MAX(dp, maxb); + minb = MIN(dp, minb); dp = p_xform.elements[0].dot(xf_points[2]); - maxb=MAX(dp,maxb); - minb=MIN(dp,minb); + maxb = MAX(dp, maxb); + minb = MIN(dp, minb); dp = p_xform.elements[0].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; - 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 Transform2D::basis_xform(const Vector2& v) const { +Vector2 Transform2D::basis_xform(const Vector2 &v) const { return Vector2( - tdotx(v), - tdoty(v) - ); + tdotx(v), + tdoty(v)); } -Vector2 Transform2D::basis_xform_inv(const Vector2& v) const{ +Vector2 Transform2D::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 Transform2D::xform(const Vector2& v) const { +Vector2 Transform2D::xform(const Vector2 &v) const { return Vector2( - tdotx(v), - tdoty(v) - ) + elements[2]; + tdotx(v), + tdoty(v)) + + elements[2]; } -Vector2 Transform2D::xform_inv(const Vector2& p_vec) const { +Vector2 Transform2D::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 Transform2D::xform(const Rect2& p_rect) const { +Rect2 Transform2D::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 Transform2D::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[1][0]=-Math::sin(p_rot)*p_scale.y; - elements[0][1]=Math::sin(p_rot)*p_scale.x; +void Transform2D::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[1][0] = -Math::sin(p_rot) * p_scale.y; + elements[0][1] = Math::sin(p_rot) * p_scale.x; } -Rect2 Transform2D::xform_inv(const Rect2& p_rect) const { +Rect2 Transform2D::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]); @@ -867,5 +880,4 @@ Rect2 Transform2D::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 feaff38a44..08f4e27e64 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 c730b4fa30..ccc463c114 100644 --- a/core/math/math_funcs.cpp +++ b/core/math/math_funcs.cpp @@ -29,7 +29,7 @@ #include "math_funcs.h" #include "core/os/os.h" -pcg32_random_t Math::default_pcg = {1, PCG_DEFAULT_INC_64}; +pcg32_random_t Math::default_pcg = { 1, PCG_DEFAULT_INC_64 }; #define PHI 0x9e3779b9 @@ -39,30 +39,29 @@ static uint32_t Q[4096]; // TODO: we should eventually expose pcg.inc too uint32_t Math::rand_from_seed(uint64_t *seed) { - pcg32_random_t pcg = {*seed, PCG_DEFAULT_INC_64}; + pcg32_random_t pcg = { *seed, PCG_DEFAULT_INC_64 }; uint32_t r = pcg32_random_r(&pcg); *seed = pcg.state; return r; } void Math::seed(uint64_t x) { - default_pcg.state=x; + default_pcg.state = x; } 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()); // TODO: can be simplified. + seed(OS::get_singleton()->get_ticks_usec() * (time.hour + 1) * (time.min + 1) * (time.sec + 1) * rand()); // TODO: can be simplified. } uint32_t Math::rand() { return pcg32_random_r(&default_pcg); } - 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, @@ -74,9 +73,9 @@ int Math::step_decimals(double p_step) { 0.000000009999 }; - double as=Math::abs(p_step); - for(int i=0;i<maxn;i++) { - if (as>=sd[i]) { + double as = Math::abs(p_step); + for (int i = 0; i < maxn; i++) { + if (as >= sd[i]) { return i; } } @@ -84,46 +83,45 @@ int Math::step_decimals(double p_step) { return maxn; } -double Math::dectime(double p_value,double p_amount, double p_step) { +double Math::dectime(double p_value, double p_amount, double p_step) { double sgn = p_value < 0 ? -1.0 : 1.0; double val = Math::abs(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::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) { - if (p_step!=0) { - p_value=Math::floor( p_value / p_step + 0.5 ) * p_step; +double Math::stepify(double p_value, double p_step) { + if (p_step != 0) { + p_value = Math::floor(p_value / p_step + 0.5) * p_step; } return p_value; } - uint32_t Math::larger_prime(uint32_t p_val) { static const uint32_t primes[] = { @@ -159,11 +157,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++; } @@ -173,14 +171,12 @@ 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; } float Math::random(float from, float to) { unsigned int r = Math::rand(); - float ret = (float)r/(float)RANDOM_MAX; - return (ret)*(to-from) + from; + float ret = (float)r / (float)RANDOM_MAX; + return (ret) * (to - from) + from; } - - diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h index ae461eda2e..3e02ac0bb8 100644 --- a/core/math/math_funcs.h +++ b/core/math/math_funcs.h @@ -29,13 +29,13 @@ #ifndef MATH_FUNCS_H #define MATH_FUNCS_H -#include "typedefs.h" #include "math_defs.h" #include "pcg.h" +#include "typedefs.h" -#include <math.h> #include <float.h> - +#include <math.h> + #define Math_PI 3.14159265358979323846 #define Math_SQRT12 0.7071067811865475244008443621048490 #define Math_LN2 0.693147180559945309417 @@ -50,10 +50,9 @@ public: Math() {} // useless to instance enum { - RANDOM_MAX=4294967295L + RANDOM_MAX = 4294967295L }; - static _ALWAYS_INLINE_ double sin(double p_x) { return ::sin(p_x); } static _ALWAYS_INLINE_ float sin(float p_x) { return ::sinf(p_x); } @@ -81,14 +80,14 @@ public: static _ALWAYS_INLINE_ double atan(double p_x) { return ::atan(p_x); } static _ALWAYS_INLINE_ float atan(float p_x) { return ::atanf(p_x); } - static _ALWAYS_INLINE_ double atan2(double p_y, double p_x) { return ::atan2(p_y,p_x); } - static _ALWAYS_INLINE_ float atan2(float p_y, float p_x) { return ::atan2f(p_y,p_x); } + static _ALWAYS_INLINE_ double atan2(double p_y, double p_x) { return ::atan2(p_y, p_x); } + static _ALWAYS_INLINE_ float atan2(float p_y, float p_x) { return ::atan2f(p_y, p_x); } static _ALWAYS_INLINE_ double sqrt(double p_x) { return ::sqrt(p_x); } static _ALWAYS_INLINE_ float sqrt(float p_x) { return ::sqrtf(p_x); } - static _ALWAYS_INLINE_ double fmod(double p_x,double p_y) { return ::fmod(p_x,p_y); } - static _ALWAYS_INLINE_ float fmod(float p_x,float p_y) { return ::fmodf(p_x,p_y); } + static _ALWAYS_INLINE_ double fmod(double p_x, double p_y) { return ::fmod(p_x, p_y); } + static _ALWAYS_INLINE_ float fmod(float p_x, float p_y) { return ::fmodf(p_x, p_y); } static _ALWAYS_INLINE_ double floor(double p_x) { return ::floor(p_x); } static _ALWAYS_INLINE_ float floor(float p_x) { return ::floorf(p_x); } @@ -96,8 +95,8 @@ public: static _ALWAYS_INLINE_ double ceil(double p_x) { return ::ceil(p_x); } static _ALWAYS_INLINE_ float ceil(float p_x) { return ::ceilf(p_x); } - static _ALWAYS_INLINE_ double pow(double p_x, double p_y) { return ::pow(p_x,p_y); } - static _ALWAYS_INLINE_ float pow(float p_x, float p_y) { return ::powf(p_x,p_y); } + static _ALWAYS_INLINE_ double pow(double p_x, double p_y) { return ::pow(p_x, p_y); } + static _ALWAYS_INLINE_ float pow(float p_x, float p_y) { return ::powf(p_x, p_y); } static _ALWAYS_INLINE_ double log(double p_x) { return ::log(p_x); } static _ALWAYS_INLINE_ float log(float p_x) { return ::logf(p_x); } @@ -105,59 +104,59 @@ public: static _ALWAYS_INLINE_ double exp(double p_x) { return ::exp(p_x); } static _ALWAYS_INLINE_ float exp(float p_x) { return ::expf(p_x); } - static _ALWAYS_INLINE_ bool is_nan(double p_val) { return (p_val!=p_val); } - static _ALWAYS_INLINE_ bool is_nan(float p_val) { return (p_val!=p_val); } + static _ALWAYS_INLINE_ bool is_nan(double p_val) { return (p_val != p_val); } + static _ALWAYS_INLINE_ bool is_nan(float p_val) { return (p_val != p_val); } static _ALWAYS_INLINE_ bool is_inf(double p_val) { - #ifdef _MSC_VER +#ifdef _MSC_VER return !_finite(p_val); - #else +#else return isinf(p_val); - #endif +#endif } - + static _ALWAYS_INLINE_ bool is_inf(float p_val) { - #ifdef _MSC_VER +#ifdef _MSC_VER return !_finite(p_val); - #else +#else return isinf(p_val); - #endif +#endif } - + static _ALWAYS_INLINE_ double abs(double g) { return absd(g); } static _ALWAYS_INLINE_ float abs(float g) { return absf(g); } static _ALWAYS_INLINE_ int abs(int g) { return g > 0 ? g : -g; } - static _ALWAYS_INLINE_ double fposmod(double p_x,double p_y) { return (p_x>=0) ? Math::fmod(p_x,p_y) : p_y-Math::fmod(-p_x,p_y); } - static _ALWAYS_INLINE_ float fposmod(float p_x,float p_y) { return (p_x>=0) ? Math::fmod(p_x,p_y) : p_y-Math::fmod(-p_x,p_y); } + static _ALWAYS_INLINE_ double fposmod(double p_x, double p_y) { return (p_x >= 0) ? Math::fmod(p_x, p_y) : p_y - Math::fmod(-p_x, p_y); } + static _ALWAYS_INLINE_ float fposmod(float p_x, float p_y) { return (p_x >= 0) ? Math::fmod(p_x, p_y) : p_y - Math::fmod(-p_x, p_y); } - static _ALWAYS_INLINE_ double deg2rad(double p_y) { return p_y*Math_PI/180.0; } - static _ALWAYS_INLINE_ float deg2rad(float p_y) { return p_y*Math_PI/180.0; } + static _ALWAYS_INLINE_ double deg2rad(double p_y) { return p_y * Math_PI / 180.0; } + static _ALWAYS_INLINE_ float deg2rad(float p_y) { return p_y * Math_PI / 180.0; } - static _ALWAYS_INLINE_ double rad2deg(double p_y) { return p_y*180.0/Math_PI; } - static _ALWAYS_INLINE_ float rad2deg(float p_y) { return p_y*180.0/Math_PI; } + static _ALWAYS_INLINE_ double rad2deg(double p_y) { return p_y * 180.0 / Math_PI; } + static _ALWAYS_INLINE_ float rad2deg(float p_y) { return p_y * 180.0 / Math_PI; } - static _ALWAYS_INLINE_ double lerp(double a, double b, double c) { return a+(b-a)*c; } - static _ALWAYS_INLINE_ float lerp(float a, float b, float c) { return a+(b-a)*c; } + static _ALWAYS_INLINE_ double lerp(double a, double b, double c) { return a + (b - a) * c; } + static _ALWAYS_INLINE_ float lerp(float a, float b, float c) { return a + (b - a) * c; } - static _ALWAYS_INLINE_ double linear2db(double p_linear) { return Math::log( p_linear ) * 8.6858896380650365530225783783321; } - static _ALWAYS_INLINE_ float linear2db(float p_linear) { return Math::log( p_linear ) * 8.6858896380650365530225783783321; } + static _ALWAYS_INLINE_ double linear2db(double p_linear) { return Math::log(p_linear) * 8.6858896380650365530225783783321; } + static _ALWAYS_INLINE_ float linear2db(float p_linear) { return Math::log(p_linear) * 8.6858896380650365530225783783321; } - static _ALWAYS_INLINE_ double db2linear(double p_db) { return Math::exp( p_db * 0.11512925464970228420089957273422 ); } - static _ALWAYS_INLINE_ float db2linear(float p_db) { return Math::exp( p_db * 0.11512925464970228420089957273422 ); } + static _ALWAYS_INLINE_ double db2linear(double p_db) { return Math::exp(p_db * 0.11512925464970228420089957273422); } + static _ALWAYS_INLINE_ float db2linear(float p_db) { return Math::exp(p_db * 0.11512925464970228420089957273422); } - static _ALWAYS_INLINE_ double round(double p_val) { return (p_val>=0) ? Math::floor(p_val+0.5) : -Math::floor(-p_val+0.5); } - static _ALWAYS_INLINE_ float round(float p_val) { return (p_val>=0) ? Math::floor(p_val+0.5) : -Math::floor(-p_val+0.5); } + static _ALWAYS_INLINE_ double round(double p_val) { return (p_val >= 0) ? Math::floor(p_val + 0.5) : -Math::floor(-p_val + 0.5); } + static _ALWAYS_INLINE_ float round(float p_val) { return (p_val >= 0) ? Math::floor(p_val + 0.5) : -Math::floor(-p_val + 0.5); } // double only, as these functions are mainly used by the editor and not performance-critical, 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 double dectime(double p_value,double p_amount, double p_step); + static double stepify(double p_value, double p_step); + static double dectime(double p_value, double p_amount, double p_step); static uint32_t larger_prime(uint32_t p_val); - static void seed(uint64_t x=0); + static void seed(uint64_t x = 0); static void randomize(); static uint32_t rand_from_seed(uint64_t *seed); static uint32_t rand(); @@ -168,17 +167,15 @@ public: static float random(float from, float to); static real_t random(int from, int to) { return (real_t)random((real_t)from, (real_t)to); } - static _ALWAYS_INLINE_ bool isequal_approx(real_t a, real_t b) { // TODO: Comparing floats for approximate-equality is non-trivial. // Using epsilon should cover the typical cases in Godot (where a == b is used to compare two reals), such as matrix and vector comparison operators. // A proper implementation in terms of ULPs should eventually replace the contents of this function. // See https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ for details. - return abs(a-b) < CMP_EPSILON; + return abs(a - b) < CMP_EPSILON; } - static _ALWAYS_INLINE_ float absf(float g) { union { @@ -186,8 +183,8 @@ public: uint32_t i; } u; - u.f=g; - u.i&=2147483647u; + u.f = g; + u.i &= 2147483647u; return u.f; } @@ -197,8 +194,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; } @@ -208,11 +205,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.0) ? (a + 0.5):(a -0.5)); + b = (int)((a > 0.0) ? (a + 0.5) : (a - 0.5)); #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) @@ -223,12 +219,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 _ALWAYS_INLINE_ int64_t dtoll(double p_double) { return (int64_t)p_double; } ///@TODO OPTIMIZE @@ -239,37 +234,35 @@ public: static _ALWAYS_INLINE_ int64_t dtoll(float p_float) { return (int64_t)p_float; } ///@TODO OPTIMIZE and rename #endif - - static _ALWAYS_INLINE_ uint32_t halfbits_to_floatbits(uint16_t h) - { - uint16_t h_exp, h_sig; - uint32_t f_sgn, f_exp, f_sig; - - h_exp = (h&0x7c00u); - f_sgn = ((uint32_t)h&0x8000u) << 16; - switch (h_exp) { - case 0x0000u: /* 0 or subnormal */ - h_sig = (h&0x03ffu); - /* Signed zero */ - if (h_sig == 0) { - return f_sgn; - } - /* Subnormal */ - h_sig <<= 1; - while ((h_sig&0x0400u) == 0) { - h_sig <<= 1; - h_exp++; - } - f_exp = ((uint32_t)(127 - 15 - h_exp)) << 23; - f_sig = ((uint32_t)(h_sig&0x03ffu)) << 13; - return f_sgn + f_exp + f_sig; - case 0x7c00u: /* inf or NaN */ - /* All-ones exponent and a copy of the significand */ - return f_sgn + 0x7f800000u + (((uint32_t)(h&0x03ffu)) << 13); - default: /* normalized */ - /* Just need to adjust the exponent and shift */ - return f_sgn + (((uint32_t)(h&0x7fffu) + 0x1c000u) << 13); - } + static _ALWAYS_INLINE_ uint32_t halfbits_to_floatbits(uint16_t h) { + uint16_t h_exp, h_sig; + uint32_t f_sgn, f_exp, f_sig; + + h_exp = (h & 0x7c00u); + f_sgn = ((uint32_t)h & 0x8000u) << 16; + switch (h_exp) { + case 0x0000u: /* 0 or subnormal */ + h_sig = (h & 0x03ffu); + /* Signed zero */ + if (h_sig == 0) { + return f_sgn; + } + /* Subnormal */ + h_sig <<= 1; + while ((h_sig & 0x0400u) == 0) { + h_sig <<= 1; + h_exp++; + } + f_exp = ((uint32_t)(127 - 15 - h_exp)) << 23; + f_sig = ((uint32_t)(h_sig & 0x03ffu)) << 13; + return f_sgn + f_exp + f_sig; + case 0x7c00u: /* inf or NaN */ + /* All-ones exponent and a copy of the significand */ + return f_sgn + 0x7f800000u + (((uint32_t)(h & 0x03ffu)) << 13); + default: /* normalized */ + /* Just need to adjust the exponent and shift */ + return f_sgn + (((uint32_t)(h & 0x7fffu) + 0x1c000u) << 13); + } } static _ALWAYS_INLINE_ float halfptr_to_float(const uint16_t *h) { @@ -279,70 +272,58 @@ public: float f32; } u; - u.u32=halfbits_to_floatbits(*h); + u.u32 = halfbits_to_floatbits(*h); return u.f32; } static _ALWAYS_INLINE_ uint16_t make_half_float(float f) { - union { - float fv; - uint32_t ui; - } ci; - ci.fv=f; - - uint32_t x = ci.ui; - uint32_t sign = (unsigned short)(x >> 31); - uint32_t mantissa; - uint32_t exp; - uint16_t hf; - - // get mantissa - mantissa = x & ((1 << 23) - 1); - // get exponent bits - exp = x & (0xFF << 23); - if (exp >= 0x47800000) - { - // check if the original single precision float number is a NaN - if (mantissa && (exp == (0xFF << 23))) - { - // we have a single precision NaN - mantissa = (1 << 23) - 1; - } - else - { - // 16-bit half-float representation stores number as Inf - mantissa = 0; + union { + float fv; + uint32_t ui; + } ci; + ci.fv = f; + + uint32_t x = ci.ui; + uint32_t sign = (unsigned short)(x >> 31); + uint32_t mantissa; + uint32_t exp; + uint16_t hf; + + // get mantissa + mantissa = x & ((1 << 23) - 1); + // get exponent bits + exp = x & (0xFF << 23); + if (exp >= 0x47800000) { + // check if the original single precision float number is a NaN + if (mantissa && (exp == (0xFF << 23))) { + // we have a single precision NaN + mantissa = (1 << 23) - 1; + } else { + // 16-bit half-float representation stores number as Inf + mantissa = 0; + } + hf = (((uint16_t)sign) << 15) | (uint16_t)((0x1F << 10)) | + (uint16_t)(mantissa >> 13); } - hf = (((uint16_t)sign) << 15) | (uint16_t)((0x1F << 10)) | - (uint16_t)(mantissa >> 13); - } - // check if exponent is <= -15 - else if (exp <= 0x38000000) - { - - /*// store a denorm half-float value or zero + // check if exponent is <= -15 + else if (exp <= 0x38000000) { + + /*// store a denorm half-float value or zero exp = (0x38000000 - exp) >> 23; mantissa >>= (14 + exp); hf = (((uint16_t)sign) << 15) | (uint16_t)(mantissa); */ - hf=0; //denormals do not work for 3D, convert to zero - } - else - { - hf = (((uint16_t)sign) << 15) | - (uint16_t)((exp - 0x38000000) >> 13) | - (uint16_t)(mantissa >> 13); - } - - return hf; - } - - + hf = 0; //denormals do not work for 3D, convert to zero + } else { + hf = (((uint16_t)sign) << 15) | + (uint16_t)((exp - 0x38000000) >> 13) | + (uint16_t)(mantissa >> 13); + } + return hf; + } }; - - #endif // MATH_FUNCS_H diff --git a/core/math/matrix3.cpp b/core/math/matrix3.cpp index 1fabfbbd4c..5f73d91ef3 100644 --- a/core/math/matrix3.cpp +++ b/core/math/matrix3.cpp @@ -30,46 +30,44 @@ #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 Basis::from_z(const Vector3& p_z) { +void Basis::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 Basis::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]; - - ERR_FAIL_COND( det == 0 ); - real_t s = 1.0/det; + real_t det = elements[0][0] * co[0] + + elements[0][1] * co[1] + + elements[0][2] * co[2]; - 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 Basis::orthonormalize() { @@ -77,20 +75,19 @@ void Basis::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); } Basis Basis::orthonormalized() const { @@ -102,16 +99,15 @@ Basis Basis::orthonormalized() const { bool Basis::is_orthogonal() const { Basis id; - Basis m = (*this)*transposed(); + Basis m = (*this) * transposed(); - return isequal_approx(id,m); + return isequal_approx(id, m); } bool Basis::is_rotation() const { return Math::isequal_approx(determinant(), 1) && is_orthogonal(); } - bool Basis::is_symmetric() const { if (Math::abs(elements[0][1] - elements[1][0]) > CMP_EPSILON) @@ -124,21 +120,20 @@ bool Basis::is_symmetric() const { return true; } - Basis Basis::diagonalize() { //NOTE: only implemented for symmetric matrices //with the Jacobi iterative method method - + ERR_FAIL_COND_V(!is_symmetric(), Basis()); const int ite_max = 1024; - real_t off_matrix_norm_2 = elements[0][1] * elements[0][1] + elements[0][2] * elements[0][2] + elements[1][2] * elements[1][2]; + real_t off_matrix_norm_2 = elements[0][1] * elements[0][1] + elements[0][2] * elements[0][2] + elements[1][2] * elements[1][2]; int ite = 0; Basis acc_rot; - while (off_matrix_norm_2 > CMP_EPSILON2 && ite++ < ite_max ) { + while (off_matrix_norm_2 > CMP_EPSILON2 && ite++ < ite_max) { real_t el01_2 = elements[0][1] * elements[0][1]; real_t el02_2 = elements[0][2] * elements[0][2]; real_t el12_2 = elements[1][2] * elements[1][2]; @@ -151,7 +146,7 @@ Basis Basis::diagonalize() { } else { i = 0; j = 1; - } + } } else { if (el12_2 > el02_2) { i = 1; @@ -163,17 +158,17 @@ Basis Basis::diagonalize() { } // Compute the rotation angle - real_t angle; + real_t angle; if (Math::abs(elements[j][j] - elements[i][i]) < CMP_EPSILON) { angle = Math_PI / 4; } else { - angle = 0.5 * Math::atan(2 * elements[i][j] / (elements[j][j] - elements[i][i])); + angle = 0.5 * Math::atan(2 * elements[i][j] / (elements[j][j] - elements[i][i])); } // Compute the rotation matrix Basis rot; rot.elements[i][i] = rot.elements[j][j] = Math::cos(angle); - rot.elements[i][j] = - (rot.elements[j][i] = Math::sin(angle)); + rot.elements[i][j] = -(rot.elements[j][i] = Math::sin(angle)); // Update the off matrix norm off_matrix_norm_2 -= elements[i][j] * elements[i][j]; @@ -188,41 +183,41 @@ Basis Basis::diagonalize() { Basis Basis::inverse() const { - Basis inv=*this; + Basis inv = *this; inv.invert(); return inv; } void Basis::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]); } Basis Basis::transposed() const { - Basis tr=*this; + Basis tr = *this; tr.transpose(); return tr; } // Multiplies the matrix from left by the scaling matrix: M -> S.M // See the comment for Basis::rotated for further explanation. -void Basis::scale(const Vector3& p_scale) { +void Basis::scale(const Vector3 &p_scale) { - elements[0][0]*=p_scale.x; - elements[0][1]*=p_scale.x; - elements[0][2]*=p_scale.x; - elements[1][0]*=p_scale.y; - elements[1][1]*=p_scale.y; - elements[1][2]*=p_scale.y; - elements[2][0]*=p_scale.z; - elements[2][1]*=p_scale.z; - elements[2][2]*=p_scale.z; + elements[0][0] *= p_scale.x; + elements[0][1] *= p_scale.x; + elements[0][2] *= p_scale.x; + elements[1][0] *= p_scale.y; + elements[1][1] *= p_scale.y; + elements[1][2] *= p_scale.y; + elements[2][0] *= p_scale.z; + elements[2][1] *= p_scale.z; + elements[2][2] *= p_scale.z; } -Basis Basis::scaled( const Vector3& p_scale ) const { +Basis Basis::scaled(const Vector3 &p_scale) const { Basis m = *this; m.scale(p_scale); @@ -236,12 +231,10 @@ Vector3 Basis::get_scale() const { // (such that it can be represented by a Quat or Euler angles), we absorb the sign flip into the scaling matrix. // As such, it works in conjuction with get_rotation(). real_t det_sign = determinant() > 0 ? 1 : -1; - return det_sign*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() - ); - + return det_sign * 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()); } // Multiplies the matrix from left by the rotation matrix: M -> R.M @@ -250,19 +243,19 @@ Vector3 Basis::get_scale() const { // The main use of Basis is as Transform.basis, which is used a the transformation matrix // of 3D object. Rotate here refers to rotation of the object (which is R * (*this)), // not the matrix itself (which is R * (*this) * R.transposed()). -Basis Basis::rotated(const Vector3& p_axis, real_t p_phi) const { +Basis Basis::rotated(const Vector3 &p_axis, real_t p_phi) const { return Basis(p_axis, p_phi) * (*this); } -void Basis::rotate(const Vector3& p_axis, real_t p_phi) { +void Basis::rotate(const Vector3 &p_axis, real_t p_phi) { *this = rotated(p_axis, p_phi); } -Basis Basis::rotated(const Vector3& p_euler) const { +Basis Basis::rotated(const Vector3 &p_euler) const { return Basis(p_euler) * (*this); } -void Basis::rotate(const Vector3& p_euler) { +void Basis::rotate(const Vector3 &p_euler) { *this = rotated(p_euler); } @@ -274,7 +267,7 @@ Vector3 Basis::get_rotation() const { real_t det = m.determinant(); if (det < 0) { // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles. - m.scale(Vector3(-1,-1,-1)); + m.scale(Vector3(-1, -1, -1)); } return m.get_euler(); @@ -304,67 +297,64 @@ Vector3 Basis::get_euler() const { ERR_FAIL_COND_V(is_rotation() == false, euler); euler.y = Math::asin(elements[0][2]); - if ( euler.y < Math_PI*0.5) { - if ( euler.y > -Math_PI*0.5) { - euler.x = Math::atan2(-elements[1][2],elements[2][2]); - euler.z = Math::atan2(-elements[0][1],elements[0][0]); + if (euler.y < Math_PI * 0.5) { + if (euler.y > -Math_PI * 0.5) { + euler.x = Math::atan2(-elements[1][2], elements[2][2]); + euler.z = Math::atan2(-elements[0][1], elements[0][0]); } else { - real_t r = Math::atan2(elements[1][0],elements[1][1]); + real_t r = Math::atan2(elements[1][0], elements[1][1]); euler.z = 0.0; euler.x = euler.z - r; - } } else { - real_t r = Math::atan2(elements[0][1],elements[1][1]); + real_t r = Math::atan2(elements[0][1], elements[1][1]); euler.z = 0; euler.x = r - euler.z; } return euler; - - } // set_euler expects a vector containing the Euler angles in the format // (c,b,a), where a is the angle of the first rotation, and c is the last. // The current implementation uses XYZ convention (Z is the first rotation). -void Basis::set_euler(const Vector3& p_euler) { +void Basis::set_euler(const Vector3 &p_euler) { real_t c, s; c = Math::cos(p_euler.x); s = Math::sin(p_euler.x); - Basis xmat(1.0,0.0,0.0,0.0,c,-s,0.0,s,c); + Basis 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); - Basis ymat(c,0.0,s,0.0,1.0,0.0,-s,0.0,c); + Basis 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); - Basis zmat(c,-s,0.0,s,c,0.0,0.0,0.0,1.0); + Basis 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 Basis::isequal_approx(const Basis& a, const Basis& b) const { +bool Basis::isequal_approx(const Basis &a, const Basis &b) const { - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { - if (Math::isequal_approx(a.elements[i][j],b.elements[i][j]) == false) - return false; - } - } + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + if (Math::isequal_approx(a.elements[i][j], b.elements[i][j]) == false) + return false; + } + } - return true; + return true; } -bool Basis::operator==(const Basis& p_matrix) const { +bool Basis::operator==(const Basis &p_matrix) const { - 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 (elements[i][j] != p_matrix.elements[i][j]) return false; } @@ -373,22 +363,22 @@ bool Basis::operator==(const Basis& p_matrix) const { return true; } -bool Basis::operator!=(const Basis& p_matrix) const { +bool Basis::operator!=(const Basis &p_matrix) const { - return (!(*this==p_matrix)); + return (!(*this == p_matrix)); } Basis::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]); } } @@ -401,21 +391,18 @@ Basis::operator Quat() const { real_t trace = elements[0][0] + elements[1][1] + 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]=((elements[2][1] - elements[1][2]) * s); - temp[1]=((elements[0][2] - elements[2][0]) * s); - temp[2]=((elements[1][0] - elements[0][1]) * s); - } - else - { + temp[0] = ((elements[2][1] - elements[1][2]) * s); + temp[1] = ((elements[0][2] - elements[2][0]) * s); + temp[2] = ((elements[1][0] - elements[0][1]) * s); + } else { int i = elements[0][0] < elements[1][1] ? - (elements[1][1] < elements[2][2] ? 2 : 1) : - (elements[0][0] < elements[2][2] ? 2 : 0); + (elements[1][1] < elements[2][2] ? 2 : 1) : + (elements[0][0] < elements[2][2] ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; @@ -428,11 +415,10 @@ Basis::operator Quat() const { temp[k] = (elements[k][i] + 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 Basis _ortho_bases[24]={ +static const Basis _ortho_bases[24] = { Basis(1, 0, 0, 0, 1, 0, 0, 0, 1), Basis(0, -1, 0, 1, 0, 0, 0, 0, 1), Basis(-1, 0, 0, 0, -1, 0, 0, 0, 1), @@ -462,164 +448,147 @@ static const Basis _ortho_bases[24]={ int Basis::get_orthogonal_index() const { //could be sped up if i come up with a way - Basis orth=*this; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Basis orth = *this; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { real_t 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 Basis::set_orthogonal_index(int p_index){ +void Basis::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 Basis::get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const { +void Basis::get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const { ERR_FAIL_COND(is_rotation() == false); + real_t angle, x, y, z; // variables for result + real_t epsilon = 0.01; // margin to allow for rounding errors + real_t epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees - real_t angle,x,y,z; // variables for result - real_t epsilon = 0.01; // margin to allow for rounding errors - real_t 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; - real_t xx = (elements[0][0]+1)/2; - real_t yy = (elements[1][1]+1)/2; - real_t zz = (elements[2][2]+1)/2; - real_t xy = (elements[1][0]+elements[0][1])/4; - real_t xz = (elements[2][0]+elements[0][2])/4; - real_t yz = (elements[2][1]+elements[1][2])/4; + real_t xx = (elements[0][0] + 1) / 2; + real_t yy = (elements[1][1] + 1) / 2; + real_t zz = (elements[2][2] + 1) / 2; + real_t xy = (elements[1][0] + elements[0][1]) / 4; + real_t xz = (elements[2][0] + elements[0][2]) / 4; + real_t 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 - real_t 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])); // s=|axis||sin(angle)|, used to normalise + real_t 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])); // s=|axis||sin(angle)|, used to normalise - angle = Math::acos(( elements[0][0] + elements[1][1] + elements[2][2] - 1)/2); + angle = Math::acos((elements[0][0] + elements[1][1] + elements[2][2] - 1) / 2); if (angle < 0) s = -s; - x = (elements[2][1] - elements[1][2])/s; - y = (elements[0][2] - elements[2][0])/s; - z = (elements[1][0] - elements[0][1])/s; + x = (elements[2][1] - elements[1][2]) / s; + y = (elements[0][2] - elements[2][0]) / s; + z = (elements[1][0] - elements[0][1]) / s; - r_axis=Vector3(x,y,z); - r_angle=angle; + r_axis = Vector3(x, y, z); + r_angle = angle; } -Basis::Basis(const Vector3& p_euler) { - - set_euler( p_euler ); +Basis::Basis(const Vector3 &p_euler) { + set_euler(p_euler); } -Basis::Basis(const Quat& p_quat) { +Basis::Basis(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)); } -Basis::Basis(const Vector3& p_axis, real_t p_phi) { +Basis::Basis(const Vector3 &p_axis, real_t p_phi) { // Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle - 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); + Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z); - 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; + real_t cosine = Math::cos(p_phi); + real_t sine = Math::sin(p_phi); - 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[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[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 abce1ee45d..0240bc8610 100644 --- a/core/math/matrix3.h +++ b/core/math/matrix3.h @@ -39,14 +39,13 @@ */ class Basis { 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]; } @@ -59,57 +58,57 @@ public: _FORCE_INLINE_ real_t 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); - Basis rotated(const Vector3& p_axis, real_t p_phi) const; + void rotate(const Vector3 &p_axis, real_t p_phi); + Basis rotated(const Vector3 &p_axis, real_t p_phi) const; - void rotate(const Vector3& p_euler); - Basis rotated(const Vector3& p_euler) const; + void rotate(const Vector3 &p_euler); + Basis rotated(const Vector3 &p_euler) const; Vector3 get_rotation() const; - void scale( const Vector3& p_scale ); - Basis scaled( const Vector3& p_scale ) const; + void scale(const Vector3 &p_scale); + Basis 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 isequal_approx(const Basis& a, const Basis& b) const; + bool isequal_approx(const Basis &a, const Basis &b) const; - bool operator==(const Basis& p_matrix) const; - bool operator!=(const Basis& p_matrix) const; + bool operator==(const Basis &p_matrix) const; + bool operator!=(const Basis &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 Basis& p_matrix); - _FORCE_INLINE_ Basis operator*(const Basis& p_matrix) const; - _FORCE_INLINE_ void operator+=(const Basis& p_matrix); - _FORCE_INLINE_ Basis operator+(const Basis& p_matrix) const; - _FORCE_INLINE_ void operator-=(const Basis& p_matrix); - _FORCE_INLINE_ Basis operator-(const Basis& 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 Basis &p_matrix); + _FORCE_INLINE_ Basis operator*(const Basis &p_matrix) const; + _FORCE_INLINE_ void operator+=(const Basis &p_matrix); + _FORCE_INLINE_ Basis operator+(const Basis &p_matrix) const; + _FORCE_INLINE_ void operator-=(const Basis &p_matrix); + _FORCE_INLINE_ Basis operator-(const Basis &p_matrix) const; _FORCE_INLINE_ void operator*=(real_t p_val); _FORCE_INLINE_ Basis operator*(real_t p_val) const; @@ -121,40 +120,39 @@ public: 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_ Vector3 get_main_diagonal() const { - return Vector3(elements[0][0],elements[1][1],elements[2][2]); + return Vector3(elements[0][0], elements[1][1], elements[2][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() { @@ -163,18 +161,17 @@ public: elements[2].zero(); } - _FORCE_INLINE_ Basis transpose_xform(const Basis& m) const - { + _FORCE_INLINE_ Basis transpose_xform(const Basis &m) const { return Basis( - 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); } Basis(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) { @@ -189,75 +186,69 @@ public: operator Quat() const; - Basis(const Quat& p_quat); // euler - Basis(const Vector3& p_euler); // euler - Basis(const Vector3& p_axis, real_t p_phi); + Basis(const Quat &p_quat); // euler + Basis(const Vector3 &p_euler); // euler + Basis(const Vector3 &p_axis, real_t p_phi); - _FORCE_INLINE_ Basis(const Vector3& row0, const Vector3& row1, const Vector3& row2) - { - elements[0]=row0; - elements[1]=row1; - elements[2]=row2; + _FORCE_INLINE_ Basis(const Vector3 &row0, const Vector3 &row1, const Vector3 &row2) { + elements[0] = row0; + elements[1] = row1; + elements[2] = row2; } _FORCE_INLINE_ Basis() { - 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 Basis::operator*=(const Basis& p_matrix) { +_FORCE_INLINE_ void Basis::operator*=(const Basis &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_ Basis Basis::operator*(const Basis& p_matrix) const { +_FORCE_INLINE_ Basis Basis::operator*(const Basis &p_matrix) const { return Basis( - 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_ void Basis::operator+=(const Basis& p_matrix) { +_FORCE_INLINE_ void Basis::operator+=(const Basis &p_matrix) { elements[0] += p_matrix.elements[0]; elements[1] += p_matrix.elements[1]; elements[2] += p_matrix.elements[2]; } -_FORCE_INLINE_ Basis Basis::operator+(const Basis& p_matrix) const { - +_FORCE_INLINE_ Basis Basis::operator+(const Basis &p_matrix) const { + Basis ret(*this); ret += p_matrix; return ret; } -_FORCE_INLINE_ void Basis::operator-=(const Basis& p_matrix) { +_FORCE_INLINE_ void Basis::operator-=(const Basis &p_matrix) { elements[0] -= p_matrix.elements[0]; elements[1] -= p_matrix.elements[1]; elements[2] -= p_matrix.elements[2]; } -_FORCE_INLINE_ Basis Basis::operator-(const Basis& p_matrix) const { - +_FORCE_INLINE_ Basis Basis::operator-(const Basis &p_matrix) const { + Basis ret(*this); ret -= p_matrix; return ret; @@ -265,40 +256,38 @@ _FORCE_INLINE_ Basis Basis::operator-(const Basis& p_matrix) const { _FORCE_INLINE_ void Basis::operator*=(real_t p_val) { - elements[0]*=p_val; - elements[1]*=p_val; - elements[2]*=p_val; + elements[0] *= p_val; + elements[1] *= p_val; + elements[2] *= p_val; } _FORCE_INLINE_ Basis Basis::operator*(real_t p_val) const { - Basis ret(*this); - ret *= p_val; - return ret; + Basis ret(*this); + ret *= p_val; + return ret; } -Vector3 Basis::xform(const Vector3& p_vector) const { +Vector3 Basis::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 Basis::xform_inv(const Vector3& p_vector) const { +Vector3 Basis::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)); } real_t Basis::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 e566df6a4f..06c5791b11 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 "rect3.h" #include "list.h" -#include "variant.h" #include "map.h" #include "print_string.h" +#include "rect3.h" +#include "variant.h" +#include "vector3.h" /** @author Juan Linietsky <reduzio@gmail.com> @@ -45,18 +45,17 @@ typedef uint32_t OctreeElementID; #define OCTREE_ELEMENT_INVALID_ID 0 #define OCTREE_SIZE_LIMIT 1e15 -template<class T,bool use_pairs=false,class AL=DefaultAllocator> +template <class T, bool use_pairs = false, class AL = DefaultAllocator> 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<p_pair.key; + return key < p_pair.key; } - _FORCE_INLINE_ PairKey( OctreeElementID p_A, OctreeElementID p_B) { + _FORCE_INLINE_ PairKey(OctreeElementID p_A, OctreeElementID p_B) { - if (p_A<p_B) { + if (p_A < p_B) { - A=p_A; - B=p_B; + A = p_A; + B = p_B; } else { - B=p_A; - A=p_B; + B = p_A; + A = p_B; } } @@ -116,16 +114,16 @@ private: int children_count; // cache for amount of childrens (fast check for removal) int parent_index; // cache for parent index (fast check for removal) - List<Element*,AL> pairable_elements; - List<Element*,AL> elements; + List<Element *, AL> pairable_elements; + List<Element *, AL> 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() { @@ -137,7 +135,6 @@ private: } }; - struct PairData; struct Element { @@ -157,28 +154,36 @@ private: Rect3 aabb; Rect3 container_aabb; - List<PairData*,AL> pair_list; + List<PairData *, AL> pair_list; struct OctantOwner { Octant *octant; - typename List<Element*,AL>::Element *E; + typename List<Element *, AL>::Element *E; }; // an element can be in max 8 octants - List<OctantOwner,AL> 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; } + List<OctantOwner, AL> 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; + } }; - struct PairData { int refcount; bool intersect; - Element *A,*B; + Element *A, *B; void *ud; - typename List<PairData*,AL>::Element *eA,*eB; + typename List<PairData *, AL>::Element *eA, *eB; }; typedef Map<OctreeElementID, Element, Comparator<OctreeElementID>, AL> ElementMap; @@ -199,58 +204,52 @@ 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) @@ -260,189 +259,178 @@ private: 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<PairData*,AL>::Element *E=p_element->pair_list.front(); - while(E) { + typename List<PairData *, AL>::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<Octant,AL>( root ); + memdelete_allocator<Octant, AL>(root); octant_count--; - root=new_root; - + root = new_root; } } - - void _insert_element(Element *p_element,Octant *p_octant); - void _ensure_valid_root(const Rect3& 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 Rect3 &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 Rect3& 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 Rect3 &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<Octant,AL>(p_octant); + memdelete_allocator<Octant, AL>(p_octant); } -public: - OctreeElementID create(T* p_userdata, const Rect3& p_aabb=Rect3(), 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 Rect3& 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 Rect3 &p_aabb = Rect3(), 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 Rect3 &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<Plane>& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask=0xFFFFFFFF); - int cull_AABB(const Rect3& 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<Plane> &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF); + int cull_AABB(const Rect3 &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<class T,bool use_pairs,class AL> -T *Octree<T,use_pairs,AL>::get(OctreeElementID p_id) const { +template <class T, bool use_pairs, class AL> +T *Octree<T, use_pairs, AL>::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<class T,bool use_pairs,class AL> -bool Octree<T,use_pairs,AL>::is_pairable(OctreeElementID p_id) const { +template <class T, bool use_pairs, class AL> +bool Octree<T, use_pairs, AL>::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<class T,bool use_pairs,class AL> -int Octree<T,use_pairs,AL>::get_subindex(OctreeElementID p_id) const { +template <class T, bool use_pairs, class AL> +int Octree<T, use_pairs, AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_insert_element(Element *p_element,Octant *p_octant) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_insert_element(Element *p_element, Octant *p_octant) { real_t 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) { @@ -454,426 +442,409 @@ void Octree<T,use_pairs,AL>::_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 */ - Rect3 aabb=p_octant->aabb; - aabb.size*=0.5; + Rect3 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*,AL>::Element *E=p_octant->pairable_elements.front(); + typename List<Element *, AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_ensure_valid_root(const Rect3& p_aabb) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_ensure_valid_root(const Rect3 &p_aabb) { if (!root) { // octre is empty - Rect3 base( Vector3(), Vector3(1.0,1.0,1.0) * unit_size); + Rect3 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 { - Rect3 base=root->aabb; + Rect3 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<class T,bool use_pairs,class AL> -bool Octree<T,use_pairs,AL>::_remove_element_from_octant(Element *p_element,Octant *p_octant,Octant *p_limit) { +template <class T, bool use_pairs, class AL> +bool Octree<T, use_pairs, AL>::_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*,AL>::Element *E=p_octant->pairable_elements.front(); - while(E) { - _pair_unreference( p_element,E->get() ); - E=E->next(); + typename List<Element *, AL>::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<Octant,AL>(p_octant); + memdelete_allocator<Octant, AL>(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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_unpair_element(Element *p_element,Octant *p_octant) { - +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_unpair_element(Element *p_element, Octant *p_octant) { // always test pairable - typename List<Element*,AL>::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 *, AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_pair_element(Element *p_element,Octant *p_octant) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_pair_element(Element *p_element, Octant *p_octant) { // always test pairable - typename List<Element*,AL>::Element *E=p_octant->pairable_elements.front(); + typename List<Element *, AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_remove_element(Element *p_element) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_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<typename Element::OctantOwner, AL>::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<class T,bool use_pairs,class AL> -OctreeElementID Octree<T,use_pairs,AL>::create(T* p_userdata, const Rect3& p_aabb, int p_subindex,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) { +template <class T, bool use_pairs, class AL> +OctreeElementID Octree<T, use_pairs, AL>::create(T *p_userdata, const Rect3 &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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& p_aabb) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::move(OctreeElementID p_id, const Rect3 &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); @@ -901,25 +872,23 @@ void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& 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=Rect3(); + e.common_parent = NULL; + e.aabb = Rect3(); _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; @@ -931,48 +900,46 @@ void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& 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; } - Rect3 combined=e.aabb; + Rect3 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<typename Element::OctantOwner,AL> owners = e.octant_owners; // save the octant owners - Octant *common_parent=e.common_parent; + List<typename Element::OctantOwner, AL> 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<typename Element::OctantOwner,AL>::Element *E=owners.front();E;) { + for (typename List<typename Element::OctantOwner, AL>::Element *E = owners.front(); E;) { - Octant *o=E->get().octant; - typename List<typename Element::OctantOwner,AL>::Element *N=E->next(); + Octant *o = E->get().octant; + typename List<typename Element::OctantOwner, AL>::Element *N = E->next(); /* if (!use_pairs) @@ -980,77 +947,70 @@ void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& p_aabb) { */ 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<typename Element::OctantOwner,AL>::Element *E=owners.front();E;E=E->next()) { + for (typename List<typename Element::OctantOwner, AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::set_pairable(OctreeElementID p_id,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::erase(OctreeElementID p_id) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::erase(OctreeElementID p_id) { typename ElementMap::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); @@ -1066,28 +1026,28 @@ void Octree<T,use_pairs,AL>::erase(OctreeElementID p_id) { _optimize(); } -template<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_cull_convex(Octant *p_octant,_CullConvexData *p_cull) { +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_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 *, AL>::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_idx<p_cull->result_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 { @@ -1100,20 +1060,20 @@ void Octree<T,use_pairs,AL>::_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 *, AL>::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_idx<p_cull->result_max) { + if (*p_cull->result_idx < p_cull->result_max) { p_cull->result_array[*p_cull->result_idx] = e->userdata; (*p_cull->result_idx)++; @@ -1125,36 +1085,35 @@ void Octree<T,use_pairs,AL>::_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 <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_cull_AABB(Octant *p_octant, const Rect3 &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) { -template<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_cull_AABB(Octant *p_octant,const Rect3& 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 *, AL>::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_idx<p_result_max) { + if (*p_result_idx < p_result_max) { p_result_array[*p_result_idx] = e->userdata; if (p_subindex_array) @@ -1171,19 +1130,19 @@ void Octree<T,use_pairs,AL>::_cull_AABB(Octant *p_octant,const Rect3& 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 *, AL>::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_idx<p_result_max) { + if (*p_result_idx < p_result_max) { p_result_array[*p_result_idx] = e->userdata; if (p_subindex_array) @@ -1197,36 +1156,35 @@ void Octree<T,use_pairs,AL>::_cull_AABB(Octant *p_octant,const Rect3& 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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_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 <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_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 *, AL>::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_idx<p_result_max) { + if (*p_result_idx < p_result_max) { p_result_array[*p_result_idx] = e->userdata; if (p_subindex_array) @@ -1243,20 +1201,20 @@ void Octree<T,use_pairs,AL>::_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 *, AL>::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_idx<p_result_max) { + if (*p_result_idx < p_result_max) { p_result_array[*p_result_idx] = e->userdata; if (p_subindex_array) @@ -1272,37 +1230,35 @@ void Octree<T,use_pairs,AL>::_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 <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::_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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::_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 *, AL>::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_idx<p_result_max) { + if (*p_result_idx < p_result_max) { p_result_array[*p_result_idx] = e->userdata; if (p_subindex_array) @@ -1319,20 +1275,20 @@ void Octree<T,use_pairs,AL>::_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 *, AL>::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_idx<p_result_max) { + if (*p_result_idx < p_result_max) { p_result_array[*p_result_idx] = e->userdata; if (p_subindex_array) @@ -1348,120 +1304,103 @@ void Octree<T,use_pairs,AL>::_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<class T,bool use_pairs,class AL> -int Octree<T,use_pairs,AL>::cull_convex(const Vector<Plane>& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask) { +template <class T, bool use_pairs, class AL> +int Octree<T, use_pairs, AL>::cull_convex(const Vector<Plane> &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<class T,bool use_pairs,class AL> -int Octree<T,use_pairs,AL>::cull_AABB(const Rect3& p_aabb,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { - +template <class T, bool use_pairs, class AL> +int Octree<T, use_pairs, AL>::cull_AABB(const Rect3 &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<class T,bool use_pairs,class AL> -int Octree<T,use_pairs,AL>::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 <class T, bool use_pairs, class AL> +int Octree<T, use_pairs, AL>::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<class T,bool use_pairs,class AL> -int Octree<T,use_pairs,AL>::cull_point(const Vector3& p_point,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { +template <class T, bool use_pairs, class AL> +int Octree<T, use_pairs, AL>::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 <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::set_pair_callback(PairCallback p_callback, void *p_userdata) { -template<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::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<class T,bool use_pairs,class AL> -void Octree<T,use_pairs,AL>::set_unpair_callback( UnpairCallback p_callback, void *p_userdata ) { - - unpair_callback=p_callback; - unpair_callback_userdata=p_userdata; +template <class T, bool use_pairs, class AL> +void Octree<T, use_pairs, AL>::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) { + unpair_callback = p_callback; + unpair_callback_userdata = p_userdata; } +template <class T, bool use_pairs, class AL> +Octree<T, use_pairs, AL>::Octree(real_t p_unit_size) { -template<class T,bool use_pairs,class AL> -Octree<T,use_pairs,AL>::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 2a97932049..29e7f2e75c 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 8235c59135..380452f6d2 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 { - - real_t dist=normal.dot(p_point) - d; - dist=ABS(dist); - return ( dist <= _epsilon); +bool Plane::has_point(const Vector3 &p_point, real_t _epsilon) const { + real_t 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 4085f9b84a..b990e9184f 100644 --- a/core/math/quat.cpp +++ b/core/math/quat.cpp @@ -33,7 +33,7 @@ // set_euler expects a vector containing the Euler angles in the format // (c,b,a), where a is the angle of the first rotation, and c is the last. // The current implementation uses XYZ convention (Z is the first rotation). -void Quat::set_euler(const Vector3& p_euler) { +void Quat::set_euler(const Vector3 &p_euler) { real_t half_a1 = p_euler.x * 0.5; real_t half_a2 = p_euler.y * 0.5; real_t half_a3 = p_euler.z * 0.5; @@ -49,10 +49,10 @@ void Quat::set_euler(const Vector3& p_euler) { real_t cos_a3 = Math::cos(half_a3); real_t sin_a3 = Math::sin(half_a3); - set(sin_a1*cos_a2*cos_a3 + sin_a2*sin_a3*cos_a1, - -sin_a1*sin_a3*cos_a2 + sin_a2*cos_a1*cos_a3, - sin_a1*sin_a2*cos_a3 + sin_a3*cos_a1*cos_a2, - -sin_a1*sin_a2*sin_a3 + cos_a1*cos_a2*cos_a3); + set(sin_a1 * cos_a2 * cos_a3 + sin_a2 * sin_a3 * cos_a1, + -sin_a1 * sin_a3 * cos_a2 + sin_a2 * cos_a1 * cos_a3, + sin_a1 * sin_a2 * cos_a3 + sin_a3 * cos_a1 * cos_a2, + -sin_a1 * sin_a2 * sin_a3 + cos_a1 * cos_a2 * cos_a3); } // get_euler returns a vector containing the Euler angles in the format @@ -63,24 +63,21 @@ Vector3 Quat::get_euler() const { return m.get_euler(); } -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()); @@ -90,17 +87,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 @@ -144,31 +139,29 @@ Quat Quat::slerp(const Quat& q, const real_t& t) const { } #else - Quat to1; - real_t omega, cosom, sinom, scale0, scale1; - + Quat to1; + real_t omega, cosom, sinom, scale0, scale1; // calc cosine cosom = dot(q); // adjust signs (if necessary) - if ( cosom <0.0 ) { + if (cosom < 0.0) { cosom = -cosom; - to1.x = - q.x; - to1.y = - q.y; - to1.z = - q.z; - to1.w = - q.w; - } else { + to1.x = -q.x; + to1.y = -q.y; + to1.z = -q.z; + to1.w = -q.w; + } else { to1.x = q.x; to1.y = q.y; to1.z = q.z; to1.w = 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); @@ -182,15 +175,14 @@ Quat Quat::slerp(const Quat& q, const real_t& t) const { } // calculate final values return Quat( - scale0 * x + scale1 * to1.x, - scale0 * y + scale1 * to1.y, - scale0 * z + scale1 * to1.z, - scale0 * w + scale1 * to1.w - ); + scale0 * x + scale1 * to1.x, + scale0 * y + scale1 * to1.y, + scale0 * z + scale1 * to1.z, + scale0 * w + scale1 * to1.w); #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; @@ -198,15 +190,15 @@ Quat Quat::slerpni(const Quat& q, const real_t& t) const { if (Math::absf(dot) > 0.9999) return from; - real_t theta = Math::acos(dot), - sinT = 1.0 / Math::sin(theta), - newFactor = Math::sin(t * theta) * sinT, - invFactor = Math::sin((1.0 - t) * theta) * sinT; + real_t theta = Math::acos(dot), + sinT = 1.0 / Math::sin(theta), + newFactor = Math::sin(t * theta) * sinT, + invFactor = Math::sin((1.0 - 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); + invFactor * from.y + newFactor * q.y, + invFactor * from.z + newFactor * q.z, + invFactor * from.w + newFactor * q.w); #if 0 real_t to1[4]; @@ -256,31 +248,29 @@ 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 :| - real_t t2 = (1.0-t)*t*2; - Quat sp = this->slerp(q,t); - Quat sq = prep.slerpni(postq,t); - return sp.slerpni(sq,t2); - + real_t 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 sin_angle = Math::sin(angle * 0.5); real_t cos_angle = Math::cos(angle * 0.5); real_t s = sin_angle / d; set(axis.x * s, axis.y * s, axis.z * s, - cos_angle); + cos_angle); } } diff --git a/core/math/quat.h b/core/math/quat.h index d3a50343a3..3fc843b83a 100644 --- a/core/math/quat.h +++ b/core/math/quat.h @@ -39,159 +39,166 @@ /** @author Juan Linietsky <reduzio@gmail.com> */ -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); + _FORCE_INLINE_ real_t dot(const Quat &q) const; + void set_euler(const Vector3 &p_euler); Vector3 get_euler() const; - 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; + 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.0 + d) * 2.0); + real_t s = Math::sqrt((1.0 + d) * 2.0); real_t rs = 1.0 / 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 { - 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 { + 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 { - 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 { + 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 32fc0e01e8..a235d1cf32 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<Vector3>& p_points, Geometry::MeshData &r_mesh) { +uint32_t QuickHull::debug_stop_after = 0xFFFFFFFF; +Error QuickHull::build(const Vector<Vector3> &p_points, Geometry::MeshData &r_mesh) { static const real_t over_tolerance = 0.0001; /* CREATE AABB VOLUME */ Rect3 aabb; - for(int i=0;i<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { - if (i==0) { - aabb.pos=p_points[i]; + if (i == 0) { + aabb.pos = p_points[i]; } else { aabb.expand_to(p_points[i]); } } - - if (aabb.size==Vector3()) { + if (aabb.size == Vector3()) { return ERR_CANT_CREATE; } - Vector<bool> valid_points; valid_points.resize(p_points.size()); Set<Vector3> valid_cache; - for(int i=0;i<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { Vector3 sp = p_points[i].snapped(0.0001); if (valid_cache.has(sp)) { - valid_points[i]=false; + valid_points[i] = false; //print_line("INVALIDATED: "+itos(i)); - }else { - valid_points[i]=true; + } else { + valid_points[i] = true; valid_cache.insert(sp); } } - - /* CREATE INITIAL SIMPLEX */ int longest_axis = aabb.get_longest_axis_index(); @@ -80,46 +75,44 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me int simplex[4]; { - real_t max,min; + real_t max, min; - for(int i=0;i<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { if (!valid_points[i]) continue; real_t d = p_points[i][longest_axis]; - if (i==0 || d < min) { + if (i == 0 || d < min) { - simplex[0]=i; - min=d; + simplex[0] = i; + min = d; } - if (i==0 || d > 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 - { real_t 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;i<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { if (!valid_points[i]) continue; - Vector3 n = rel12.cross(p_points[simplex[0]]-p_points[i]).cross(rel12).normalized(); - real_t d = Math::abs(n.dot(p_points[simplex[0]])-n.dot(p_points[i])); + Vector3 n = rel12.cross(p_points[simplex[0]] - p_points[i]).cross(rel12).normalized(); + real_t d = Math::abs(n.dot(p_points[simplex[0]]) - n.dot(p_points[i])); - if (i==0 || d>maxd) { + if (i == 0 || d > maxd) { - maxd=d; - simplex[2]=i; + maxd = d; + simplex[2] = i; } } } @@ -128,102 +121,92 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me { real_t 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;i<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { if (!valid_points[i]) continue; real_t d = Math::abs(p.distance_to(p_points[i])); - if (i==0 || d>maxd) { + 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<Face> 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<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { - if (i==simplex[0]) + if (i == simplex[0]) continue; - if (i==simplex[1]) + if (i == simplex[1]) continue; - if (i==simplex[2]) + if (i == simplex[2]) continue; - if (i==simplex[3]) + if (i == simplex[3]) continue; if (!valid_points[i]) continue; - for(List<Face>::Element *E=faces.front();E;E=E->next()) { + for (List<Face>::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<Vector3>& 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<f.points_over.size();i++) { + for (int i = 0; i < f.points_over.size(); i++) { real_t d = f.plane.distance_to(p_points[f.points_over[i]]); if (d > 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<Face>::Element* > lit_faces; //lit face is a death sentence + List<List<Face>::Element *> lit_faces; //lit face is a death sentence - Map<Edge,FaceConnect> lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot + Map<Edge, FaceConnect> lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot - for(List<Face>::Element *E=faces.front();E;E=E->next()) { + for (List<Face>::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<Edge,FaceConnect>::Element *F=lit_edges.find(e); + Map<Edge, FaceConnect>::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<Face>::Element* > new_faces; //new faces + List<List<Face>::Element *> new_faces; //new faces - for(Map<Edge,FaceConnect>::Element *E=lit_edges.front();E;E=E->next()) { + for (Map<Edge, FaceConnect>::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<Vector3>& 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<Face>::Element* >::Element *F=lit_faces.front();F;F=F->next()) { + for (List<List<Face>::Element *>::Element *F = lit_faces.front(); F; F = F->next()) { Face &lf = F->get()->get(); - for(int i=0;i<lf.points_over.size();i++) { + for (int i = 0; i < lf.points_over.size(); i++) { - if (lf.points_over[i]==f.points_over[next]) //do not add current one + if (lf.points_over[i] == f.points_over[next]) //do not add current one continue; Vector3 p = p_points[lf.points_over[i]]; - for (List< List<Face>::Element* >::Element *E=new_faces.front();E;E=E->next()) { + for (List<List<Face>::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,129 +332,115 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me //put faces that contain no points on the front - for (List< List<Face>::Element* >::Element *E=new_faces.front();E;E=E->next()) { + for (List<List<Face>::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<Edge,RetFaceConnect> ret_edges; + Map<Edge, RetFaceConnect> ret_edges; List<Geometry::MeshData::Face> ret_faces; - - for(List<Face>::Element *E=faces.front();E;E=E->next()) { + for (List<Face>::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<Geometry::MeshData::Face>::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<Edge,RetFaceConnect>::Element *G=ret_edges.find(e); + Map<Edge, RetFaceConnect>::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<Geometry::MeshData::Face>::Element *E=ret_faces.front();E;E=E->next()) { + for (List<Geometry::MeshData::Face>::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;i<f.indices.size();i++) { + for (int i = 0; i < f.indices.size(); i++) { uint32_t a = E->get().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<Edge,RetFaceConnect>::Element *F=ret_edges.find(e); + Map<Edge, RetFaceConnect>::Element *F = ret_edges.find(e); ERR_CONTINUE(!F); List<Geometry::MeshData::Face>::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;j<ois;j++) { + for (int j = 0; j < ois; j++) { //search a - if (O->get().indices[j]==a) { + if (O->get().indices[j] == a) { //append the rest - for(int k=0;k<ois;k++) { + for (int k = 0; k < ois; k++) { - 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! + 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<Edge,RetFaceConnect>::Element *F2=ret_edges.find(e2); + Map<Edge, RetFaceConnect>::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 @@ -485,26 +448,24 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me r_mesh.faces.resize(ret_faces.size()); //print_line("FACECOUNT: "+itos(r_mesh.faces.size())); - int idx=0; - for (List<Geometry::MeshData::Face>::Element *E=ret_faces.front();E;E=E->next()) { - r_mesh.faces[idx++]=E->get(); - - + int idx = 0; + for (List<Geometry::MeshData::Face>::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<Edge,RetFaceConnect>::Element *E=ret_edges.front();E;E=E->next()) { + idx = 0; + for (Map<Edge, RetFaceConnect>::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 7bd23d31f2..43a802e6bd 100644 --- a/core/math/quick_hull.h +++ b/core/math/quick_hull.h @@ -29,16 +29,14 @@ #ifndef QUICK_HULL_H #define QUICK_HULL_H +#include "geometry.h" +#include "list.h" #include "rect3.h" #include "set.h" -#include "list.h" -#include "geometry.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<int> 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<Face>::Element *left,*right; - FaceConnect() { left=NULL; right=NULL; } + List<Face>::Element *left, *right; + FaceConnect() { + left = NULL; + right = NULL; + } }; struct RetFaceConnect { - List<Geometry::MeshData::Face>::Element *left,*right; - RetFaceConnect() { left=NULL; right=NULL; } + List<Geometry::MeshData::Face>::Element *left, *right; + RetFaceConnect() { + left = NULL; + right = NULL; + } }; public: - static uint32_t debug_stop_after; - static Error build(const Vector<Vector3>& p_points,Geometry::MeshData& r_mesh); - + static Error build(const Vector<Vector3> &p_points, Geometry::MeshData &r_mesh); }; #endif // QUICK_HULL_H diff --git a/core/math/rect3.cpp b/core/math/rect3.cpp index d3f95b89e8..c0cd66d9bb 100644 --- a/core/math/rect3.cpp +++ b/core/math/rect3.cpp @@ -32,94 +32,87 @@ real_t Rect3::get_area() const { - return size.x*size.y*size.z; - + return size.x * size.y * size.z; } -bool Rect3::operator==(const Rect3& p_rval) const { - - return ((pos==p_rval.pos) && (size==p_rval.size)); +bool Rect3::operator==(const Rect3 &p_rval) const { + return ((pos == p_rval.pos) && (size == p_rval.size)); } -bool Rect3::operator!=(const Rect3& p_rval) const { - - return ((pos!=p_rval.pos) || (size!=p_rval.size)); +bool Rect3::operator!=(const Rect3 &p_rval) const { + return ((pos != p_rval.pos) || (size != p_rval.size)); } -void Rect3::merge_with(const Rect3& p_aabb) { +void Rect3::merge_with(const Rect3 &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.x<beg_2.x)?beg_1.x:beg_2.x; - min.y=(beg_1.y<beg_2.y)?beg_1.y:beg_2.y; - min.z=(beg_1.z<beg_2.z)?beg_1.z:beg_2.z; + min.x = (beg_1.x < beg_2.x) ? beg_1.x : beg_2.x; + min.y = (beg_1.y < beg_2.y) ? beg_1.y : beg_2.y; + min.z = (beg_1.z < beg_2.z) ? beg_1.z : beg_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; + 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; } -Rect3 Rect3::intersection(const Rect3& p_aabb) const { +Rect3 Rect3::intersection(const Rect3 &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 Rect3(); 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 Rect3(); 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 Rect3(); 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 Rect3( min, max-min ); + return Rect3(min, max - min); } -bool Rect3::intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* r_clip,Vector3* r_normal) const { +bool Rect3::intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *r_clip, Vector3 *r_normal) const { Vector3 c1, c2; - Vector3 end = pos+size; - real_t near=-1e20; - real_t far=1e20; - int axis=0; + Vector3 end = pos + size; + real_t near = -1e20; + real_t 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 Rect3::intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* 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 Rect3::intersects_segment(const Vector3 &p_from, const Vector3 &p_to, Vector3 *r_clip, Vector3 *r_normal) const { -bool Rect3::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; + real_t sign = 0; - real_t min=0,max=1; - int axis=0; - real_t 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; real_t 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 Rect3::intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector 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 Rect3::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 Rect3::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 Rect3::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 Rect3::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 Rect3::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; } -Rect3 Rect3::merge(const Rect3& p_with) const { +Rect3 Rect3::merge(const Rect3 &p_with) const { - Rect3 aabb=*this; + Rect3 aabb = *this; aabb.merge_with(p_with); return aabb; } -Rect3 Rect3::expand(const Vector3& p_vector) const { - Rect3 aabb=*this; +Rect3 Rect3::expand(const Vector3 &p_vector) const { + Rect3 aabb = *this; aabb.expand_to(p_vector); return aabb; - } Rect3 Rect3::grow(real_t p_by) const { - Rect3 aabb=*this; + Rect3 aabb = *this; aabb.grow_by(p_by); return aabb; } -void Rect3::get_edge(int p_edge,Vector3& r_from,Vector3& r_to) const { +void Rect3::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; - } - } Rect3::operator String() const { - return String()+pos +" - "+ size; + return String() + pos + " - " + size; } diff --git a/core/math/rect3.h b/core/math/rect3.h index 902592b02c..26198537c2 100644 --- a/core/math/rect3.h +++ b/core/math/rect3.h @@ -29,19 +29,15 @@ #ifndef AABB_H #define AABB_H - - -#include "vector3.h" -#include "plane.h" #include "math_defs.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 Rect3 { public: Vector3 pos; @@ -50,40 +46,38 @@ public: real_t 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 Rect3 &p_rval) const; + bool operator!=(const Rect3 &p_rval) const; - bool operator==(const Rect3& p_rval) const; - bool operator!=(const Rect3& p_rval) const; + _FORCE_INLINE_ bool intersects(const Rect3 &p_aabb) const; /// Both AABBs overlap + _FORCE_INLINE_ bool intersects_inclusive(const Rect3 &p_aabb) const; /// Both AABBs (or their faces) overlap + _FORCE_INLINE_ bool encloses(const Rect3 &p_aabb) const; /// p_aabb is completely inside this - _FORCE_INLINE_ bool intersects(const Rect3& p_aabb) const; /// Both AABBs overlap - _FORCE_INLINE_ bool intersects_inclusive(const Rect3& p_aabb) const; /// Both AABBs (or their faces) overlap - _FORCE_INLINE_ bool encloses(const Rect3 & p_aabb) const; /// p_aabb is completely inside this - - Rect3 merge(const Rect3& p_with) const; - void merge_with(const Rect3& p_aabb); ///merge with another AABB - Rect3 intersection(const Rect3& 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, real_t t0, real_t t1) const; + Rect3 merge(const Rect3 &p_with) const; + void merge_with(const Rect3 &p_aabb); ///merge with another AABB + Rect3 intersection(const Rect3 &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, real_t t0, real_t 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; @@ -96,98 +90,97 @@ public: Rect3 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; - Rect3 expand(const Vector3& p_vector) const; - _FORCE_INLINE_ void project_range_in_plane(const Plane& p_plane,real_t &r_min,real_t& r_max) const; - _FORCE_INLINE_ void expand_to(const Vector3& p_vector); /** expand to contain a point if necesary */ + Rect3 expand(const Vector3 &p_vector) const; + _FORCE_INLINE_ void project_range_in_plane(const Plane &p_plane, real_t &r_min, real_t &r_max) const; + _FORCE_INLINE_ void expand_to(const Vector3 &p_vector); /** expand to contain a point if necesary */ operator String() const; _FORCE_INLINE_ Rect3() {} - inline Rect3(const Vector3 &p_pos,const Vector3& p_size) { pos=p_pos; size=p_size; } + inline Rect3(const Vector3 &p_pos, const Vector3 &p_size) { + pos = p_pos; + size = p_size; + } +}; +inline bool Rect3::intersects(const Rect3 &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; -inline bool Rect3::intersects(const Rect3& 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; - - return true; + return true; } -inline bool Rect3::intersects_inclusive(const Rect3& 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; - - return true; +inline bool Rect3::intersects_inclusive(const Rect3 &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; + + return true; } -inline bool Rect3::encloses(const Rect3 & p_aabb) const { +inline bool Rect3::encloses(const Rect3 &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 Rect3::get_support(const Vector3& p_normal) const { +Vector3 Rect3::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 Rect3::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()); @@ -200,14 +193,13 @@ bool Rect3::intersects_convex_shape(const Plane *p_planes, int p_plane_count) co Vector3 half_extents = size * 0.5; Vector3 ofs = pos + half_extents; - for(int i=0;i<p_plane_count;i++) { - const Plane &p=p_planes[i]; + for (int i = 0; i < p_plane_count; i++) { + const Plane &p = p_planes[i]; Vector3 point( - (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; + (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; } @@ -215,33 +207,31 @@ bool Rect3::intersects_convex_shape(const Plane *p_planes, int p_plane_count) co 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;i<p_plane_count;i++) { //for each plane + for (int i = 0; i < p_plane_count; i++) { //for each plane - const Plane & plane=p_planes[i]; - bool all_points_over=true; + const Plane &plane = p_planes[i]; + bool all_points_over = true; //test if it has all points over! - for (int j=0;j<8;j++) { - + for (int j = 0; j < 8; j++) { - if (!plane.is_point_over( points[j] )) { + if (!plane.is_point_over(points[j])) { - all_points_over=false; + all_points_over = false; break; } - } if (all_points_over) { @@ -253,69 +243,68 @@ bool Rect3::intersects_convex_shape(const Plane *p_planes, int p_plane_count) co #endif } -bool Rect3::has_point(const Vector3& p_point) const { +bool Rect3::has_point(const Vector3 &p_point) const { - if (p_point.x<pos.x) + if (p_point.x < pos.x) return false; - if (p_point.y<pos.y) + if (p_point.y < pos.y) return false; - if (p_point.z<pos.z) + if (p_point.z < pos.z) 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; - if (p_point.z>pos.z+size.z) + if (p_point.z > pos.z + size.z) return false; return true; } +inline void Rect3::expand_to(const Vector3 &p_vector) { -inline void Rect3::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 < 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 Rect3::project_range_in_plane(const Plane& p_plane,real_t &r_min,real_t& r_max) const { +void Rect3::project_range_in_plane(const Plane &p_plane, real_t &r_min, real_t &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); real_t length = p_plane.normal.abs().dot(half_extents); - real_t distance = p_plane.distance_to( center ); + real_t distance = p_plane.distance_to(center); r_min = distance - length; r_max = distance + length; } inline real_t Rect3::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; @@ -323,75 +312,71 @@ inline real_t Rect3::get_longest_axis_size() const { inline real_t Rect3::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 Rect3::smits_intersect_ray(const Vector3 &from,const Vector3& dir, real_t t0, real_t t1) const { +bool Rect3::smits_intersect_ray(const Vector3 &from, const Vector3 &dir, real_t t0, real_t t1) const { - real_t divx=1.0/dir.x; - real_t divy=1.0/dir.y; - real_t divz=1.0/dir.z; + real_t divx = 1.0 / dir.x; + real_t divy = 1.0 / dir.y; + real_t divz = 1.0 / dir.z; - Vector3 upbound=pos+size; + Vector3 upbound = pos + size; real_t 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 Rect3::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; } - #endif // AABB_H diff --git a/core/math/transform.cpp b/core/math/transform.cpp index 6d9324c176..d35938e559 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(); @@ -56,35 +53,34 @@ void Transform::invert() { Transform Transform::inverse() const { // FIXME: this function assumes the basis is a rotation matrix, with no scaling. // Transform::affine_inverse can handle matrices with scaling, so GDScript should eventually use that. - 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 = rotated(p_axis, p_phi); } -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 Transform(Basis( p_axis, p_phi ), Vector3()) * (*this); + return Transform(Basis(p_axis, p_phi), Vector3()) * (*this); } -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; @@ -98,23 +94,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, real_t p_c) const { +Transform Transform::interpolate_with(const Transform &p_transform, real_t p_c) const { /* not sure if very "efficient" but good enough? */ @@ -127,45 +121,44 @@ Transform Transform::interpolate_with(const Transform& p_transform, real_t p_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; } @@ -182,25 +175,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; } @@ -209,11 +202,8 @@ Transform::operator String() const { return basis.operator String() + " - " + origin.operator String(); } +Transform::Transform(const Basis &p_basis, const Vector3 &p_origin) { -Transform::Transform(const Basis& 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 45d7b2a12c..e307aba129 100644 --- a/core/math/transform.h +++ b/core/math/transform.h @@ -37,7 +37,6 @@ */ class Transform { public: - Basis 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 Basis& get_basis() const { return basis; } - void set_basis(const Basis& p_basis) { basis=p_basis; } + const Basis &get_basis() const { return basis; } + void set_basis(const Basis &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_ Rect3 xform(const Rect3& p_aabb) const; - _FORCE_INLINE_ Rect3 xform_inv(const Rect3& p_aabb) const; + _FORCE_INLINE_ Rect3 xform(const Rect3 &p_aabb) const; + _FORCE_INLINE_ Rect3 xform_inv(const Rect3 &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, real_t p_c) const; + Transform interpolate_with(const Transform &p_transform, real_t 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) { - - 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; + 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; } operator String() const; - Transform(const Basis& p_basis, const Vector3& p_origin=Vector3()); + Transform(const Basis &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_ Rect3 Transform::xform(const Rect3& p_aabb) const { - /* define vertices */ +_FORCE_INLINE_ Rect3 Transform::xform(const Rect3 &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 Rect3 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_ Rect3 Transform::xform_inv(const Rect3& p_aabb) const { +_FORCE_INLINE_ Rect3 Transform::xform_inv(const Rect3 &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) }; - Rect3 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 247cb90a48..93c6b2786e 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; } - Rect3 aabb; - aabb=p_bb[p_from]->aabb; - for(int i=1;i<p_size;i++) { + aabb = p_bb[p_from]->aabb; + 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<BVH*,BVHCmpX> sort_x; - sort_x.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray<BVH *, BVHCmpX> 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<BVH*,BVHCmpY> sort_y; - sort_y.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray<BVH *, BVHCmpY> 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<BVH*,BVHCmpZ> sort_z; - sort_z.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray<BVH *, BVHCmpZ> 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 PoolVector<Vector3> &p_faces) { -void TriangleMesh::create(const PoolVector<Vector3>& 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) PoolVector<BVH>::Write bw = bvh.write(); { @@ -114,148 +106,143 @@ void TriangleMesh::create(const PoolVector<Vector3>& p_faces) { PoolVector<Vector3>::Read r = p_faces.read(); PoolVector<Triangle>::Write w = triangles.write(); - Map<Vector3,int> db; + Map<Vector3, int> db; - for(int i=0;i<fc;i++) { + for (int i = 0; i < fc; i++) { - Triangle&f=w[i]; - const Vector3 *v=&r[i*3]; + Triangle &f = w[i]; + const Vector3 *v = &r[i * 3]; - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - int vidx=-1; - Vector3 vs=v[j].snapped(0.0001); - Map<Vector3,int>::Element *E=db.find(vs); + int vidx = -1; + Vector3 vs = v[j].snapped(0.0001); + Map<Vector3, int>::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()); PoolVector<Vector3>::Write vw = vertices.write(); - for (Map<Vector3,int>::Element *E=db.front();E;E=E->next()) { - vw[E->get()]=E->key(); + for (Map<Vector3, int>::Element *E = db.front(); E; E = E->next()) { + vw[E->get()] = E->key(); } - } - PoolVector<BVH*> bwptrs; + PoolVector<BVH *> bwptrs; bwptrs.resize(fc); - PoolVector<BVH*>::Write bwp = bwptrs.write(); - for(int i=0;i<fc;i++) { + PoolVector<BVH *>::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=PoolVector<BVH>::Write(); //clearup + bw = PoolVector<BVH>::Write(); //clearup bvh.resize(max_alloc); //resize back - valid=true; - + valid = true; } +Vector3 TriangleMesh::get_area_normal(const Rect3 &p_aabb) const { -Vector3 TriangleMesh::get_area_normal(const Rect3& 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<<VISITED_BIT_SHIFT)-1, - VISITED_BIT_MASK=~NODE_IDX_MASK, - + TEST_AABB_BIT = 0, + VISIT_LEFT_BIT = 1, + VISIT_RIGHT_BIT = 2, + VISIT_DONE_BIT = 3, + VISITED_BIT_SHIFT = 29, + NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1, + VISITED_BIT_MASK = ~NODE_IDX_MASK, }; - int n_count=0; + int n_count = 0; Vector3 n; - int level=0; + int level = 0; PoolVector<Triangle>::Read trianglesr = triangles.read(); - PoolVector<Vector3>::Read verticesr=vertices.read(); - PoolVector<BVH>::Read bvhr=bvh.read(); + PoolVector<Vector3>::Read verticesr = vertices.read(); + PoolVector<BVH>::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<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - if (b.face_index>=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<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node; } } continue; } case VISIT_LEFT_BIT: { - stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.left|TEST_AABB_BIT; + stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.left | TEST_AABB_BIT; level++; continue; } case VISIT_RIGHT_BIT: { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.right|TEST_AABB_BIT; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.right | TEST_AABB_BIT; level++; continue; } case VISIT_DONE_BIT: { - if (level==0) { - done=true; + if (level == 0) { + done = true; break; } else level--; @@ -263,121 +250,111 @@ Vector3 TriangleMesh::get_area_normal(const Rect3& p_aabb) const { } } - if (done) break; } - - if (n_count>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<<VISITED_BIT_SHIFT)-1, - VISITED_BIT_MASK=~NODE_IDX_MASK, - + TEST_AABB_BIT = 0, + VISIT_LEFT_BIT = 1, + VISIT_RIGHT_BIT = 2, + VISIT_DONE_BIT = 3, + VISITED_BIT_SHIFT = 29, + NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1, + VISITED_BIT_MASK = ~NODE_IDX_MASK, }; - Vector3 n = (p_end-p_begin).normalized(); - real_t d=1e10; - bool inters=false; + Vector3 n = (p_end - p_begin).normalized(); + real_t d = 1e10; + bool inters = false; - int level=0; + int level = 0; PoolVector<Triangle>::Read trianglesr = triangles.read(); - PoolVector<Vector3>::Read verticesr=vertices.read(); - PoolVector<BVH>::Read bvhr=bvh.read(); + PoolVector<Vector3>::Read verticesr = vertices.read(); + PoolVector<BVH>::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_segment(p_begin, p_end); //bool valid = b.aabb.intersects(ray_aabb); if (!valid) { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - 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] ]); + 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)) { real_t nd = n.dot(res); - if (nd<d) { + if (nd < d) { - d=nd; - r_point=res; - r_normal=f3.get_plane().get_normal(); - inters=true; + d = nd; + r_point = res; + r_normal = f3.get_plane().get_normal(); + inters = true; } - } - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node; } } continue; } case VISIT_LEFT_BIT: { - stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.left|TEST_AABB_BIT; + stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.left | TEST_AABB_BIT; level++; continue; } case VISIT_RIGHT_BIT: { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.right|TEST_AABB_BIT; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.right | TEST_AABB_BIT; level++; continue; } case VISIT_DONE_BIT: { - if (level==0) { - done=true; + if (level == 0) { + done = true; break; } else level--; @@ -385,121 +362,112 @@ bool TriangleMesh::intersect_segment(const Vector3& p_begin,const Vector3& p_end } } - if (done) break; } - if (inters) { - if (n.dot(r_normal)>0) - 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<<VISITED_BIT_SHIFT)-1, - VISITED_BIT_MASK=~NODE_IDX_MASK, - + TEST_AABB_BIT = 0, + VISIT_LEFT_BIT = 1, + VISIT_RIGHT_BIT = 2, + VISIT_DONE_BIT = 3, + VISITED_BIT_SHIFT = 29, + NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1, + VISITED_BIT_MASK = ~NODE_IDX_MASK, }; Vector3 n = p_dir; - real_t d=1e20; - bool inters=false; + real_t d = 1e20; + bool inters = false; - int level=0; + int level = 0; PoolVector<Triangle>::Read trianglesr = triangles.read(); - PoolVector<Vector3>::Read verticesr=vertices.read(); - PoolVector<BVH>::Read bvhr=bvh.read(); + PoolVector<Vector3>::Read verticesr = vertices.read(); + PoolVector<BVH>::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<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - 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] ]); + 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)) { real_t nd = n.dot(res); - if (nd<d) { + if (nd < d) { - d=nd; - r_point=res; - r_normal=f3.get_plane().get_normal(); - inters=true; + d = nd; + r_point = res; + r_normal = f3.get_plane().get_normal(); + inters = true; } - } - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node; } } continue; } case VISIT_LEFT_BIT: { - stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.left|TEST_AABB_BIT; + stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.left | TEST_AABB_BIT; level++; continue; } case VISIT_RIGHT_BIT: { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.right|TEST_AABB_BIT; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.right | TEST_AABB_BIT; level++; continue; } case VISIT_DONE_BIT: { - if (level==0) { - done=true; + if (level == 0) { + done = true; break; } else level--; @@ -507,16 +475,14 @@ bool TriangleMesh::intersect_ray(const Vector3& p_begin,const Vector3& p_dir,Vec } } - if (done) break; } - if (inters) { - if (n.dot(r_normal)>0) - r_normal=-r_normal; + if (n.dot(r_normal) > 0) + r_normal = -r_normal; } return inters; @@ -536,13 +502,13 @@ PoolVector<Face3> TriangleMesh::get_faces() const { int ts = triangles.size(); faces.resize(triangles.size()); - PoolVector<Face3>::Write w=faces.write(); + PoolVector<Face3>::Write w = faces.write(); PoolVector<Triangle>::Read r = triangles.read(); PoolVector<Vector3>::Read rv = vertices.read(); - for(int i=0;i<ts;i++) { - for(int j=0;j<3;j++) { - w[i].vertex[j]=rv[r[i].indices[j]]; + for (int i = 0; i < ts; i++) { + for (int j = 0; j < 3; j++) { + w[i].vertex[j] = rv[r[i].indices[j]]; } } @@ -552,6 +518,6 @@ PoolVector<Face3> 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 65250c023d..7f81e54613 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 { - GDCLASS( TriangleMesh, Reference); + GDCLASS(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); PoolVector<BVH> 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 Rect3& 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 Rect3 &p_aabb) const; PoolVector<Face3> get_faces() const; - - void create(const PoolVector<Vector3>& p_faces); + void create(const PoolVector<Vector3> &p_faces); TriangleMesh(); }; diff --git a/core/math/triangulate.cpp b/core/math/triangulate.cpp index 128b6ca331..8568a963ab 100644 --- a/core/math/triangulate.cpp +++ b/core/math/triangulate.cpp @@ -28,136 +28,140 @@ /*************************************************************************/ #include "triangulate.h" -real_t Triangulate::get_area(const Vector<Vector2> &contour) -{ +real_t Triangulate::get_area(const Vector<Vector2> &contour) { - int n = contour.size(); - const Vector2 *c=&contour[0]; + int n = contour.size(); + const Vector2 *c = &contour[0]; - real_t A=0.0; + real_t A = 0.0; - for(int p=n-1,q=0; q<n; p=q++) - { - A+= c[p].cross(c[q]); - } - return A*0.5; + for (int p = n - 1, q = 0; q < n; p = q++) { + A += c[p].cross(c[q]); + } + return A * 0.5; } - /* +/* is_inside_triangle decides if a point P is Inside of the triangle defined by A, B, C. */ bool Triangulate::is_inside_triangle(real_t Ax, real_t Ay, - real_t Bx, real_t By, - real_t Cx, real_t Cy, - real_t Px, real_t Py) + real_t Bx, real_t By, + real_t Cx, real_t Cy, + real_t Px, real_t Py) { - real_t ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; - real_t cCROSSap, bCROSScp, aCROSSbp; - - ax = Cx - Bx; ay = Cy - By; - bx = Ax - Cx; by = Ay - Cy; - cx = Bx - Ax; cy = By - Ay; - apx= Px - Ax; apy= Py - Ay; - bpx= Px - Bx; bpy= Py - By; - cpx= Px - Cx; cpy= Py - Cy; - - aCROSSbp = ax*bpy - ay*bpx; - cCROSSap = cx*apy - cy*apx; - bCROSScp = bx*cpy - by*cpx; - - return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0)); + real_t ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; + real_t cCROSSap, bCROSScp, aCROSSbp; + + ax = Cx - Bx; + ay = Cy - By; + bx = Ax - Cx; + by = Ay - Cy; + cx = Bx - Ax; + cy = By - Ay; + apx = Px - Ax; + apy = Py - Ay; + bpx = Px - Bx; + bpy = Py - By; + cpx = Px - Cx; + cpy = Py - Cy; + + aCROSSbp = ax * bpy - ay * bpx; + cCROSSap = cx * apy - cy * apx; + bCROSScp = bx * cpy - by * cpx; + + return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0)); }; -bool Triangulate::snip(const Vector<Vector2> &p_contour,int u,int v,int w,int n,const Vector<int>& V) -{ - int p; - real_t Ax, Ay, Bx, By, Cx, Cy, Px, Py; - const Vector2 *contour=&p_contour[0]; +bool Triangulate::snip(const Vector<Vector2> &p_contour, int u, int v, int w, int n, const Vector<int> &V) { + int p; + real_t 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<n;p++) - { - if( (p == u) || (p == v) || (p == w) ) continue; - Px = contour[V[p]].x; - Py = contour[V[p]].y; - if (is_inside_triangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py)) return false; - } + for (p = 0; p < n; p++) { + if ((p == u) || (p == v) || (p == w)) continue; + Px = contour[V[p]].x; + Py = contour[V[p]].y; + if (is_inside_triangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py)) return false; + } - return true; + return true; } -bool Triangulate::triangulate(const Vector<Vector2> &contour,Vector<int> &result) -{ - /* allocate and initialize list of Vertices in polygon */ - - int n = contour.size(); - if ( n < 3 ) return false; +bool Triangulate::triangulate(const Vector<Vector2> &contour, Vector<int> &result) { + /* allocate and initialize list of Vertices in polygon */ + int n = contour.size(); + if (n < 3) return false; - Vector<int> V; - V.resize(n); + Vector<int> V; + V.resize(n); - /* we want a counter-clockwise polygon in V */ + /* we want a counter-clockwise polygon in V */ - if ( 0.0 < 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.0 < 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; - int nv = n; + int nv = n; - /* remove nv-2 Vertices, creating 1 triangle every time */ - int count = 2*nv; /* error detection */ + /* remove nv-2 Vertices, creating 1 triangle every time */ + int count = 2 * nv; /* error detection */ - 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; - } + 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, <u,v,w> */ - 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, <u,v,w> */ + 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]; + /* remove v from remaining polygon */ + for (s = v, t = v + 1; t < nv; s++, t++) + V[s] = V[t]; - nv--; + nv--; - /* resest error detection counter */ - count = 2*nv; - } - } + /* resest error detection counter */ + count = 2 * nv; + } + } - return true; + return true; } diff --git a/core/math/triangulate.h b/core/math/triangulate.h index ce77334519..c23d3ba27d 100644 --- a/core/math/triangulate.h +++ b/core/math/triangulate.h @@ -31,35 +31,28 @@ #include "math_2d.h" - /* http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml */ -class Triangulate -{ +class Triangulate { public: - // triangulate a contour/polygon, places results in STL vector // as series of triangles. - static bool triangulate(const Vector< Vector2 > &contour, Vector<int> &result); + static bool triangulate(const Vector<Vector2> &contour, Vector<int> &result); // compute area of a contour/polygon - static real_t get_area(const Vector< Vector2 > &contour); + static real_t get_area(const Vector<Vector2> &contour); // decide if point Px/Py is inside triangle defined by // (Ax,Ay) (Bx,By) (Cx,Cy) static bool is_inside_triangle(real_t Ax, real_t Ay, - real_t Bx, real_t By, - real_t Cx, real_t Cy, - real_t Px, real_t Py); - + real_t Bx, real_t By, + real_t Cx, real_t Cy, + real_t Px, real_t Py); private: - static bool snip(const Vector<Vector2> &p_contour,int u,int v,int w,int n,const Vector<int>& V); - + static bool snip(const Vector<Vector2> &p_contour, int u, int v, int w, int n, const Vector<int> &V); }; - - #endif diff --git a/core/math/vector3.cpp b/core/math/vector3.cpp index 2ab5fa0465..235840e06a 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, real_t p_phi) { -void Vector3::rotate(const Vector3& p_axis,real_t p_phi) { - - *this=Basis(p_axis,p_phi).xform(*this); + *this = Basis(p_axis, p_phi).xform(*this); } -Vector3 Vector3::rotated(const Vector3& p_axis,real_t p_phi) const { +Vector3 Vector3::rotated(const Vector3 &p_axis, real_t 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,27 +60,25 @@ int Vector3::max_axis() const { return x < y ? (y < z ? 2 : 1) : (x < z ? 2 : 0); } - void Vector3::snap(real_t p_val) { - x=Math::stepify(x,p_val); - y=Math::stepify(y,p_val); - z=Math::stepify(z,p_val); + x = Math::stepify(x, p_val); + y = Math::stepify(y, p_val); + z = Math::stepify(z, p_val); } Vector3 Vector3::snapped(real_t 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, real_t p_t) const { -Vector3 Vector3::cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t 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 @@ -91,44 +87,41 @@ Vector3 Vector3::cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, c real_t bc = p1.distance_to(p2); real_t 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); } - real_t t = p_t; real_t t2 = t * t; real_t t3 = t2 * t; Vector3 out; - out = 0.5 * ( ( p1 * 2.0) + - ( -p0 + p2 ) * t + - ( 2.0 * p0 - 5.0 * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0 * p1 - 3.0 * p2 + p3 ) * t3 ); + out = 0.5 * ((p1 * 2.0) + + (-p0 + p2) * t + + (2.0 * p0 - 5.0 * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); return out; - } -Vector3 Vector3::cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const { +Vector3 Vector3::cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t 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; real_t t = p_t; real_t t2 = t * t; real_t t3 = t2 * t; Vector3 out; - out = 0.5 * ( ( p1 * 2.0) + - ( -p0 + p2 ) * t + - ( 2.0 * p0 - 5.0 * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0 * p1 - 3.0 * p2 + p3 ) * t3 ); + out = 0.5 * ((p1 * 2.0) + + (-p0 + p2) * t + + (2.0 * p0 - 5.0 * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); return out; - } #if 0 @@ -175,8 +168,8 @@ Vector3 Vector3::cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, co ( -p0.z + 3.0 * p1.z - 3.0 * 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 a289f9bf4c..fc02e66c33 100644 --- a/core/math/vector3.h +++ b/core/math/vector3.h @@ -29,9 +29,9 @@ #ifndef VECTOR3_H #define VECTOR3_H -#include "typedefs.h" #include "math_defs.h" #include "math_funcs.h" +#include "typedefs.h" #include "ustring.h" class Basis; @@ -54,17 +54,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; @@ -82,63 +82,63 @@ struct Vector3 { void snap(real_t p_val); Vector3 snapped(real_t p_val) const; - void rotate(const Vector3& p_axis,real_t p_phi); - Vector3 rotated(const Vector3& p_axis,real_t p_phi) const; + void rotate(const Vector3 &p_axis, real_t p_phi); + Vector3 rotated(const Vector3 &p_axis, real_t p_phi) const; /* Static Methods between 2 vector3s */ - _FORCE_INLINE_ Vector3 linear_interpolate(const Vector3& p_b,real_t p_t) const; - Vector3 cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const; - Vector3 cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const; + _FORCE_INLINE_ Vector3 linear_interpolate(const Vector3 &p_b, real_t p_t) const; + Vector3 cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_t) const; + Vector3 cubic_interpolaten(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_t) const; - _FORCE_INLINE_ Vector3 cross(const Vector3& p_b) const; - _FORCE_INLINE_ real_t dot(const Vector3& p_b) const; - _FORCE_INLINE_ Basis outer(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_ Basis outer(const Vector3 &p_b) const; _FORCE_INLINE_ Basis to_diagonal_matrix() 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 angle_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_ 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 @@ -149,260 +149,258 @@ struct Vector3 { #include "matrix3.h" -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; } -Basis Vector3::outer(const Vector3& p_b) const { - - Vector3 row0(x*p_b.x, x*p_b.y, x*p_b.z); - Vector3 row1(y*p_b.x, y*p_b.y, y*p_b.z); - Vector3 row2(z*p_b.x, z*p_b.y, z*p_b.z); +Basis Vector3::outer(const Vector3 &p_b) const { + + Vector3 row0(x * p_b.x, x * p_b.y, x * p_b.z); + Vector3 row1(y * p_b.x, y * p_b.y, y * p_b.z); + Vector3 row2(z * p_b.x, z * p_b.y, z * p_b.z); return Basis(row0, row1, row2); } Basis Vector3::to_diagonal_matrix() const { return Basis(x, 0, 0, - 0, y, 0, - 0, 0, z); + 0, y, 0, + 0, 0, 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,real_t p_t) const { +Vector3 Vector3::linear_interpolate(const Vector3 &p_b, real_t 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 { - return (x!=p_v.x || y!=p_v.y || z!=p_v.z); +bool Vector3::operator!=(const Vector3 &p_v) const { + 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 z<p_v.z; + if (x == p_v.x) { + if (y == p_v.y) + return z < p_v.z; else - return y<p_v.y; + return y < p_v.y; } else { - return x<p_v.x; + return x < p_v.x; } } -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 z<=p_v.z; + if (x == p_v.x) { + if (y == p_v.y) + return z <= p_v.z; else - return y<p_v.y; + return y < p_v.y; } else { - return x<p_v.x; + return x < p_v.x; } } -_FORCE_INLINE_ Vector3 vec3_cross(const Vector3& p_a, const Vector3& p_b) { +_FORCE_INLINE_ Vector3 vec3_cross(const Vector3 &p_a, const Vector3 &p_b) { return p_a.cross(p_b); } -_FORCE_INLINE_ real_t vec3_dot(const Vector3& p_a, const Vector3& p_b) { +_FORCE_INLINE_ real_t vec3_dot(const Vector3 &p_a, const Vector3 &p_b) { return p_a.dot(p_b); } real_t Vector3::length() const { - real_t x2=x*x; - real_t y2=y*y; - real_t z2=z*z; + real_t x2 = x * x; + real_t y2 = y * y; + real_t z2 = z * z; - return Math::sqrt(x2+y2+z2); + return Math::sqrt(x2 + y2 + z2); } real_t Vector3::length_squared() const { - real_t x2=x*x; - real_t y2=y*y; - real_t z2=z*z; + real_t x2 = x * x; + real_t y2 = y * y; + real_t z2 = z * z; - return x2+y2+z2; + return x2 + y2 + z2; } void Vector3::normalize() { - real_t l=length(); - if (l==0) { - x=y=z=0; + real_t l = length(); + if (l == 0) { + x = y = z = 0; } else { - x/=l; - y/=l; - z/=l; + x /= l; + y /= l; + z /= l; } } Vector3 Vector3::normalized() const { - Vector3 v=*this; + Vector3 v = *this; v.normalize(); return v; } Vector3 Vector3::inverse() const { - return Vector3( 1.0/x, 1.0/y, 1.0/z ); + return Vector3(1.0 / x, 1.0 / y, 1.0 / z); } void Vector3::zero() { - x=y=z=0; + x = y = z = 0; } -Vector3 Vector3::slide(const Vector3& p_vec) const { +Vector3 Vector3::slide(const Vector3 &p_vec) const { return p_vec - *this * this->dot(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 50b52e4970..56c944081a 100644 --- a/core/message_queue.cpp +++ b/core/message_queue.cpp @@ -31,95 +31,90 @@ #include "global_config.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_class(); - print_line("failed method: "+type+":"+p_method+" target ID: "+itos(p_id)); + type = ObjectDB::get_instance(p_id)->get_class(); + 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; - - buffer_end+=sizeof(Message); + msg->type |= FLAG_SHOW_ERROR; - for(int i=0;i<p_argcount;i++) { + buffer_end += sizeof(Message); - Variant * v = memnew_placement( &buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=*p_args[i]; + for (int i = 0; i < p_argcount; i++) { + Variant *v = memnew_placement(&buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = *p_args[i]; } return OK; } -Error MessageQueue::push_call(ObjectID p_id, const StringName& p_method, VARIANT_ARG_DECLARE) { +Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; + int argc = 0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_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_class(); - print_line("failed set: "+type+":"+p_prop+" target ID: "+itos(p_id)); + type = ObjectDB::get_instance(p_id)->get_class(); + 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 ); - - Message * msg = memnew_placement( &buffer[ buffer_end ], Message ); - msg->args=1; - msg->instance_ID=p_id; - msg->target=p_prop; - msg->type=TYPE_SET; + ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY); - buffer_end+=sizeof(Message); + Message *msg = memnew_placement(&buffer[buffer_end], Message); + msg->args = 1; + msg->instance_ID = p_id; + msg->target = p_prop; + msg->type = TYPE_SET; - 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; } @@ -128,73 +123,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_class(); - print_line("failed notification: "+itos(p_notification)+" target ID: "+itos(p_id)); + type = ObjectDB::get_instance(p_id)->get_class(); + 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<StringName,int> set_count; - Map<int,int> notify_count; - Map<StringName,int> call_count; - int null_count=0; + Map<StringName, int> set_count; + Map<int, int> notify_count; + Map<StringName, int> 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]++; @@ -202,7 +190,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]++; @@ -210,12 +198,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 @@ -226,31 +213,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<StringName, int>::Element *E = set_count.front(); E; E = E->next()) { - for(Map<StringName,int>::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<StringName,int>::Element *E=call_count.front();E;E=E->next()) { + for (Map<StringName, int>::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<int,int>::Element *E=notify_count.front();E;E=E->next()) { + for (Map<int, int>::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() { @@ -299,62 +283,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;i<p_argcount;i++) { - argptrs[i]=&p_args[i]; + argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount); + for (int i = 0; i < p_argcount; i++) { + argptrs[i] = &p_args[i]; } } Variant::CallError 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)); + 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_pos<buffer_end) { + while (read_pos < buffer_end) { _THREAD_SAFE_UNLOCK_ //lock on each interation, so a call can re-add itself to the message queue - Message *message = (Message*)&buffer[ read_pos ]; + 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: { - 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;i<message->args;i++) { + for (int i = 0; i < message->args; i++) { args[i].~Variant(); } @@ -367,65 +347,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( "memory/buffers/message_queue_max_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("memory/buffers/message_queue_max_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;i<argc;i++) + if ((message->type & 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 1b1a20ba9a..e04530f24c 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 3465edff63..0f192a3b8a 100644 --- a/core/method_bind.cpp +++ b/core/method_bind.cpp @@ -32,59 +32,54 @@ #include "method_bind.h" - #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<arg_names.size())?String(arg_names[p_argument]):String("arg"+itos(p_argument)); - PropertyInfo pi( get_argument_type(p_argument), name ); - if ((pi.type==Variant::OBJECT) && name.find(":")!=-1) { - pi.hint=PROPERTY_HINT_RESOURCE_TYPE; - pi.hint_string=name.get_slicec(':',1); - pi.name=name.get_slicec(':',0); + String name = (p_argument < arg_names.size()) ? String(arg_names[p_argument]) : String("arg" + itos(p_argument)); + PropertyInfo pi(get_argument_type(p_argument), name); + if ((pi.type == Variant::OBJECT) && name.find(":") != -1) { + pi.hint = PROPERTY_HINT_RESOURCE_TYPE; + pi.hint_string = name.get_slicec(':', 1); + pi.name = name.get_slicec(':', 0); } return pi; } else { Variant::Type at = get_argument_type(-1); - if (at==Variant::OBJECT && ret_type) - return PropertyInfo( at, "ret", PROPERTY_HINT_RESOURCE_TYPE, ret_type ); + if (at == Variant::OBJECT && ret_type) + return PropertyInfo(at, "ret", PROPERTY_HINT_RESOURCE_TYPE, ret_type); else - return PropertyInfo( at, "ret" ); + return PropertyInfo(at, "ret"); } - return PropertyInfo(); } #endif void MethodBind::_set_const(bool p_const) { - _const=p_const; + _const = p_const; } void MethodBind::_set_returns(bool p_returns) { - _returns=p_returns; + _returns = p_returns; } - StringName MethodBind::get_name() const { return name; } -void MethodBind::set_name(const StringName& p_name) { - name=p_name; +void MethodBind::set_name(const StringName &p_name) { + name = p_name; } #ifdef DEBUG_METHODS_ENABLED -void MethodBind::set_argument_names(const Vector<StringName>& p_names) { - - arg_names=p_names; +void MethodBind::set_argument_names(const Vector<StringName> &p_names) { + arg_names = p_names; } Vector<StringName> MethodBind::get_argument_names() const { @@ -93,41 +88,36 @@ Vector<StringName> MethodBind::get_argument_names() const { #endif - - -void MethodBind::set_default_arguments(const Vector<Variant>& p_defargs) { - default_arguments=p_defargs; - default_argument_count=default_arguments.size(); - +void MethodBind::set_default_arguments(const Vector<Variant> &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<p_count;i++) { - argt[i+1]=_gen_argument_type(i); + Variant::Type *argt = memnew_arr(Variant::Type, p_count + 1); + argt[0] = _gen_argument_type(-1); + for (int i = 0; i < p_count; i++) { + argt[i + 1] = _gen_argument_type(i); } set_argument_types(argt); - } #endif MethodBind::MethodBind() { - static int last_id=0; - method_id=last_id++; - hint_flags=METHOD_FLAGS_DEFAULT; - argument_count=0; - default_argument_count=0; + static int last_id = 0; + method_id = last_id++; + hint_flags = METHOD_FLAGS_DEFAULT; + argument_count = 0; + default_argument_count = 0; #ifdef DEBUG_METHODS_ENABLED - argument_types=NULL; + argument_types = NULL; #endif - _const=false; - _returns=false; + _const = false; + _returns = false; } MethodBind::~MethodBind() { @@ -136,4 +126,3 @@ MethodBind::~MethodBind() { memdelete_arr(argument_types); #endif } - diff --git a/core/method_bind.h b/core/method_bind.h index 7b59e6a6b0..f915a7563e 100644 --- a/core/method_bind.h +++ b/core/method_bind.h @@ -30,10 +30,10 @@ #define METHOD_BIND_H #include "list.h" -#include "variant.h" +#include "method_ptrcall.h" #include "object.h" +#include "variant.h" #include <stdio.h> -#include "method_ptrcall.h" /** @author Juan Linietsky <reduzio@gmail.com> @@ -45,123 +45,118 @@ 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_FLAG_VARARG=128, - 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_FLAG_VARARG = 128, + METHOD_FLAGS_DEFAULT = METHOD_FLAG_NORMAL, }; -template<class T> +template <class T> struct VariantCaster { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -template<class T> -struct VariantCaster<T&> { +template <class T> +struct VariantCaster<T &> { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -template<class T> -struct VariantCaster<const T&> { +template <class T> +struct VariantCaster<const T &> { - 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<P##m_idx>::cast( (m_idx-1)>=p_arg_count?get_default_argument(m_idx-1):*p_args[m_idx-1] )) +#define _VC(m_idx) \ + (VariantCaster<P##m_idx>::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<m_enum> {\ -\ - 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<const int*>(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<m_enum> { \ + \ + 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<const int *>(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<m_enum> {\ -\ - 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<m_enum> { \ + \ + 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)<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_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( Variant::Type ); -VARIANT_ENUM_CAST( Variant::Operator ); -VARIANT_ENUM_CAST( InputEvent::Type ); +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(Variant::Type); +VARIANT_ENUM_CAST(Variant::Operator); +VARIANT_ENUM_CAST(InputEvent::Type); class MethodBind { - int method_id; uint32_t hint_flags; StringName name; @@ -176,27 +171,25 @@ class MethodBind { bool _const; bool _returns; - protected: - void _set_const(bool p_const); void _set_returns(bool p_returns); #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<Variant> 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; @@ -204,9 +197,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]; @@ -214,24 +207,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<StringName>& p_names); + void set_argument_names(const Vector<StringName> &p_names); Vector<StringName> 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)|(is_vararg()?METHOD_FLAG_VARARG:0); } - virtual String get_instance_class() 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) | (is_vararg() ? METHOD_FLAG_VARARG : 0); } + virtual String get_instance_class() const = 0; _FORCE_INLINE_ int get_argument_count() const { return argument_count; }; @@ -257,60 +249,58 @@ 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; } _FORCE_INLINE_ bool has_return() const { return _returns; } virtual bool is_vararg() const { return false; } - void set_default_arguments(const Vector<Variant>& p_defargs); + void set_default_arguments(const Vector<Variant> &p_defargs); MethodBind(); virtual ~MethodBind(); }; - -template<class T> +template <class T> class MethodBindVarArg : public MethodBind { public: - typedef Variant (T::*NativeCall)(const Variant**,int ,Variant::CallError &); -protected: + 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<T*>(p_object); - return (instance->*call_method)(p_args,p_arg_count,r_error); + T *instance = static_cast<T *>(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<StringName> names; names.resize(p_info.arguments.size()); - for(int i=0;i<p_info.arguments.size();i++) { + for (int i = 0; i < p_info.arguments.size(); i++) { - at[i+1]=p_info.arguments[i].type; - names[i]=p_info.arguments[i].name; + at[i + 1] = p_info.arguments[i].type; + names[i] = p_info.arguments[i].name; } set_argument_names(names); @@ -320,32 +310,32 @@ public: } #ifdef PTRCALL_ENABLED - virtual void ptrcall(Object* p_object,const void** p_args,void* r_ret) { + virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) { ERR_FAIL(); //can't call } //todo #endif - - void set_method(NativeCall p_method) { call_method=p_method; } + void set_method(NativeCall p_method) { call_method = p_method; } virtual bool is_const() const { return false; } virtual String get_instance_class() const { return T::get_class_static(); } virtual bool is_vararg() const { return true; } - MethodBindVarArg() { call_method=NULL; _set_returns(true);} + MethodBindVarArg() { + call_method = NULL; + _set_returns(true); + } }; +template <class T> +MethodBind *create_vararg_method_bind(Variant (T::*p_method)(const Variant **, int, Variant::CallError &), const MethodInfo &p_info) { -template<class T > -MethodBind* create_vararg_method_bind( Variant (T::*p_method)(const Variant**,int ,Variant::CallError &), const MethodInfo& p_info ) { - - MethodBindVarArg<T > * a = memnew( (MethodBindVarArg<T >) ); + MethodBindVarArg<T> *a = memnew((MethodBindVarArg<T>)); 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.. // @@ -353,7 +343,6 @@ MethodBind* create_vararg_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 3a205d5e78..26d7538bf8 100644 --- a/core/method_ptrcall.h +++ b/core/method_ptrcall.h @@ -29,71 +29,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<class T> +template <class T> struct PtrToArg { - }; -#define MAKE_PTRARG(m_type) \ -template<>\ -struct PtrToArg<m_type> {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast<const m_type*>(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_type*)p_ptr)=p_val;\ - }\ -};\ -template<>\ -struct PtrToArg<const m_type&> {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast<const m_type*>(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<m_type> {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast<const m_type*>(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_ret*)p_ptr)=p_val;\ - }\ -};\ -template<>\ -struct PtrToArg<const m_type&> {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast<const m_type*>(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<m_type> { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast<const m_type *>(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_type *)p_ptr) = p_val; \ + } \ + }; \ + template <> \ + struct PtrToArg<const m_type &> { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast<const m_type *>(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<m_type> { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast<const m_type *>(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_ret *)p_ptr) = p_val; \ + } \ + }; \ + template <> \ + struct PtrToArg<const m_type &> { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast<const m_type *>(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); @@ -122,86 +118,82 @@ MAKE_PTRARG(PoolColorArray); MAKE_PTRARG(Variant); MAKE_PTRARG(PowerState); - //this is for Object -template<class T> -struct PtrToArg< T* > { +template <class T> +struct PtrToArg<T *> { - _FORCE_INLINE_ static T* convert(const void* p_ptr) { + _FORCE_INLINE_ static T *convert(const void *p_ptr) { - return const_cast<T*>(reinterpret_cast<const T*>(p_ptr)); + return const_cast<T *>(reinterpret_cast<const T *>(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<class T> -struct PtrToArg< const T* > { +template <class T> +struct PtrToArg<const T *> { - _FORCE_INLINE_ static const T* convert(const void* p_ptr) { + _FORCE_INLINE_ static const T *convert(const void *p_ptr) { - return reinterpret_cast<const T*>(p_ptr); + return reinterpret_cast<const T *>(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<Vector<m_type> > {\ - _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\ - const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr);\ - Vector<m_type> ret;\ - int len = dvs->size();\ - ret.resize(len);\ - {\ - PoolVector<m_type>::Read r=dvs->read();\ - for(int i=0;i<len;i++) {\ - ret[i]=r[i];\ - }\ - } \ - return ret;\ - }\ - _FORCE_INLINE_ static void encode(Vector<m_type> p_vec, void* p_ptr) {\ - PoolVector<m_type> *dv = reinterpret_cast<PoolVector<m_type> *>(p_ptr);\ - int len=p_vec.size();\ - dv->resize(len);\ - {\ - PoolVector<m_type>::Write w=dv->write();\ - for(int i=0;i<len;i++) {\ - w[i]=p_vec[i];\ - }\ - } \ - }\ -};\ -template<>\ -struct PtrToArg<const Vector<m_type>& > {\ - _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\ - const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr);\ - Vector<m_type> ret;\ - int len = dvs->size();\ - ret.resize(len);\ - {\ - PoolVector<m_type>::Read r=dvs->read();\ - for(int i=0;i<len;i++) {\ - ret[i]=r[i];\ - }\ - } \ - return ret;\ - }\ -} +#define MAKE_VECARG(m_type) \ + template <> \ + struct PtrToArg<Vector<m_type> > { \ + _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \ + const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr); \ + Vector<m_type> ret; \ + int len = dvs->size(); \ + ret.resize(len); \ + { \ + PoolVector<m_type>::Read r = dvs->read(); \ + for (int i = 0; i < len; i++) { \ + ret[i] = r[i]; \ + } \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(Vector<m_type> p_vec, void *p_ptr) { \ + PoolVector<m_type> *dv = reinterpret_cast<PoolVector<m_type> *>(p_ptr); \ + int len = p_vec.size(); \ + dv->resize(len); \ + { \ + PoolVector<m_type>::Write w = dv->write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = p_vec[i]; \ + } \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg<const Vector<m_type> &> { \ + _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \ + const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr); \ + Vector<m_type> ret; \ + int len = dvs->size(); \ + ret.resize(len); \ + { \ + PoolVector<m_type>::Read r = dvs->read(); \ + for (int i = 0; i < len; i++) { \ + ret[i] = r[i]; \ + } \ + } \ + return ret; \ + } \ + } MAKE_VECARG(String); MAKE_VECARG(uint8_t); @@ -212,172 +204,170 @@ MAKE_VECARG(Vector3); MAKE_VECARG(Color); //for stuff that gets converted to Array vectors -#define MAKE_VECARR(m_type) \ -template<>\ -struct PtrToArg<Vector<m_type> > {\ - _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast<const Array *>(p_ptr);\ - Vector<m_type> 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<m_type> p_vec, void* p_ptr) {\ - Array *arr = reinterpret_cast<Array *>(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<const Vector<m_type>& > {\ - _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast<const Array *>(p_ptr);\ - Vector<m_type> ret;\ - int len = arr->size();\ - ret.resize(len);\ - for(int i=0;i<len;i++) {\ - ret[i]=(*arr)[i];\ - }\ - return ret;\ - }\ -} - +#define MAKE_VECARR(m_type) \ + template <> \ + struct PtrToArg<Vector<m_type> > { \ + _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast<const Array *>(p_ptr); \ + Vector<m_type> 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<m_type> p_vec, void *p_ptr) { \ + Array *arr = reinterpret_cast<Array *>(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<const Vector<m_type> &> { \ + _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast<const Array *>(p_ptr); \ + Vector<m_type> 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<PoolVector<m_type> > {\ - _FORCE_INLINE_ static PoolVector<m_type> convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast<const Array *>(p_ptr);\ - PoolVector<m_type> ret;\ - int len = arr->size();\ - ret.resize(len);\ - {\ - PoolVector<m_type>::Write w=ret.write();\ - for(int i=0;i<len;i++) {\ - w[i]=(*arr)[i];\ - }\ - }\ - return ret;\ - }\ - _FORCE_INLINE_ static void encode(PoolVector<m_type> p_vec, void* p_ptr) {\ - Array *arr = reinterpret_cast<Array *>(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len);\ - {\ - PoolVector<m_type>::Read r=p_vec.read();\ - for(int i=0;i<len;i++) {\ - (*arr)[i]=r[i];\ - }\ - }\ - } \ -};\ -template<>\ -struct PtrToArg<const PoolVector<m_type>& > {\ - _FORCE_INLINE_ static PoolVector<m_type> convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast<const Array *>(p_ptr);\ - PoolVector<m_type> ret;\ - int len = arr->size();\ - ret.resize(len);\ - {\ - PoolVector<m_type>::Write w=ret.write();\ - for(int i=0;i<len;i++) {\ - w[i]=(*arr)[i];\ - }\ - }\ - return ret;\ - }\ -} +#define MAKE_DVECARR(m_type) \ + template <> \ + struct PtrToArg<PoolVector<m_type> > { \ + _FORCE_INLINE_ static PoolVector<m_type> convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast<const Array *>(p_ptr); \ + PoolVector<m_type> ret; \ + int len = arr->size(); \ + ret.resize(len); \ + { \ + PoolVector<m_type>::Write w = ret.write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = (*arr)[i]; \ + } \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(PoolVector<m_type> p_vec, void *p_ptr) { \ + Array *arr = reinterpret_cast<Array *>(p_ptr); \ + int len = p_vec.size(); \ + arr->resize(len); \ + { \ + PoolVector<m_type>::Read r = p_vec.read(); \ + for (int i = 0; i < len; i++) { \ + (*arr)[i] = r[i]; \ + } \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg<const PoolVector<m_type> &> { \ + _FORCE_INLINE_ static PoolVector<m_type> convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast<const Array *>(p_ptr); \ + PoolVector<m_type> ret; \ + int len = arr->size(); \ + ret.resize(len); \ + { \ + PoolVector<m_type>::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<m_type> {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - m_type s = *reinterpret_cast<const String*>(p_ptr);\ - return s;\ - }\ - _FORCE_INLINE_ static void encode(m_type p_vec, void* p_ptr) {\ - String *arr = reinterpret_cast<String *>(p_ptr);\ - *arr=p_vec;\ - }\ -};\ -\ -template<>\ -struct PtrToArg<const m_type&> {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - m_type s = *reinterpret_cast<const String*>(p_ptr);\ - return s;\ - }\ -} +#define MAKE_STRINGCONV(m_type) \ + template <> \ + struct PtrToArg<m_type> { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + m_type s = *reinterpret_cast<const String *>(p_ptr); \ + return s; \ + } \ + _FORCE_INLINE_ static void encode(m_type p_vec, void *p_ptr) { \ + String *arr = reinterpret_cast<String *>(p_ptr); \ + *arr = p_vec; \ + } \ + }; \ + \ + template <> \ + struct PtrToArg<const m_type &> { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + m_type s = *reinterpret_cast<const String *>(p_ptr); \ + return s; \ + } \ + } MAKE_STRINGCONV(StringName); MAKE_STRINGCONV(IP_Address); -template<> +template <> struct PtrToArg<PoolVector<Face3> > { - _FORCE_INLINE_ static PoolVector<Face3> convert(const void* p_ptr) { + _FORCE_INLINE_ static PoolVector<Face3> convert(const void *p_ptr) { const PoolVector<Vector3> *dvs = reinterpret_cast<const PoolVector<Vector3> *>(p_ptr); PoolVector<Face3> ret; - int len = dvs->size()/3; + int len = dvs->size() / 3; ret.resize(len); { - PoolVector<Vector3>::Read r=dvs->read(); - PoolVector<Face3>::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]; + PoolVector<Vector3>::Read r = dvs->read(); + PoolVector<Face3>::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(PoolVector<Face3> p_vec, void* p_ptr) {\ - PoolVector<Vector3> *arr = reinterpret_cast<PoolVector<Vector3> *>(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len*3);\ - {\ - PoolVector<Face3>::Read r=p_vec.read();\ - PoolVector<Vector3>::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];\ - }\ - }\ - } \ + _FORCE_INLINE_ static void encode(PoolVector<Face3> p_vec, void *p_ptr) { + PoolVector<Vector3> *arr = reinterpret_cast<PoolVector<Vector3> *>(p_ptr); + int len = p_vec.size(); + arr->resize(len * 3); + { + PoolVector<Face3>::Read r = p_vec.read(); + PoolVector<Vector3>::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<const PoolVector<Face3>& > { - _FORCE_INLINE_ static PoolVector<Face3> convert(const void* p_ptr) { +template <> +struct PtrToArg<const PoolVector<Face3> &> { + _FORCE_INLINE_ static PoolVector<Face3> convert(const void *p_ptr) { const PoolVector<Vector3> *dvs = reinterpret_cast<const PoolVector<Vector3> *>(p_ptr); PoolVector<Face3> ret; - int len = dvs->size()/3; + int len = dvs->size() / 3; ret.resize(len); { - PoolVector<Vector3>::Read r=dvs->read(); - PoolVector<Face3>::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]; + PoolVector<Vector3>::Read r = dvs->read(); + PoolVector<Face3>::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 79905a6be6..e9b332fafa 100644 --- a/core/object.cpp +++ b/core/object.cpp @@ -28,14 +28,14 @@ /*************************************************************************/ #include "object.h" -#include "print_string.h" #include "class_db.h" -#include "script_language.h" -#include "message_queue.h" #include "core_string_names.h" -#include "translation.h" +#include "message_queue.h" #include "os/os.h" +#include "print_string.h" #include "resource.h" +#include "script_language.h" +#include "translation.h" #ifdef DEBUG_ENABLED @@ -44,7 +44,7 @@ struct _ObjectDebugLock { Object *obj; _ObjectDebugLock(Object *p_obj) { - obj=p_obj; + obj = p_obj; obj->_lock_index.ref(); } ~_ObjectDebugLock() { @@ -60,48 +60,44 @@ struct _ObjectDebugLock { #endif - PropertyInfo::operator Dictionary() const { Dictionary d; - d["name"]=name; - d["type"]=type; - d["hint"]=hint; - d["hint_string"]=hint_string; - d["usage"]=usage; + d["name"] = name; + d["type"] = type; + d["hint"] = hint; + d["hint_string"] = hint_string; + d["usage"] = usage; return d; - } -PropertyInfo PropertyInfo::from_dict(const Dictionary& p_dict) { +PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) { PropertyInfo pi; if (p_dict.has("type")) - pi.type=Variant::Type(int(p_dict["type"])); + pi.type = Variant::Type(int(p_dict["type"])); if (p_dict.has("name")) - pi.name=p_dict["name"]; + pi.name = p_dict["name"]; if (p_dict.has("hint")) - pi.hint=PropertyHint(int(p_dict["hint"])); + pi.hint = PropertyHint(int(p_dict["hint"])); if (p_dict.has("hint_string")) - pi.hint_string=p_dict["hint_string"]; + pi.hint_string = p_dict["hint_string"]; if (p_dict.has("usage")) - pi.usage=p_dict["usage"]; + pi.usage = p_dict["usage"]; return pi; } - -Array convert_property_list(const List<PropertyInfo> * p_list) { +Array convert_property_list(const List<PropertyInfo> *p_list) { Array va; - for (const List<PropertyInfo>::Element *E=p_list->front();E;E=E->next()) { - + for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) { va.push_back(Dictionary(E->get())); } @@ -111,201 +107,198 @@ Array convert_property_list(const List<PropertyInfo> * p_list) { MethodInfo::operator Dictionary() const { - Dictionary d; - d["name"]=name; - d["args"]=convert_property_list(&arguments); + d["name"] = name; + d["args"] = convert_property_list(&arguments); Array da; - for(int i=0;i<default_arguments.size();i++) + for (int i = 0; i < default_arguments.size(); i++) da.push_back(default_arguments[i]); - d["default_args"]=da; - d["flags"]=flags; - d["id"]=id; + d["default_args"] = da; + d["flags"] = flags; + d["id"] = id; Dictionary r = return_val; - d["return"]=r; + d["return"] = r; return d; - } MethodInfo::MethodInfo() { - id=0; - flags=METHOD_FLAG_NORMAL; + id = 0; + flags = METHOD_FLAG_NORMAL; } -MethodInfo MethodInfo::from_dict(const Dictionary& p_dict) { +MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) { MethodInfo mi; if (p_dict.has("name")) - mi.name=p_dict["name"]; + mi.name = p_dict["name"]; Array args; if (p_dict.has("args")) { - args=p_dict["args"]; + args = p_dict["args"]; } - for(int i=0;i<args.size();i++) { + for (int i = 0; i < args.size(); i++) { Dictionary d = args[i]; mi.arguments.push_back(PropertyInfo::from_dict(d)); } Array defargs; if (p_dict.has("default_args")) { - defargs=p_dict["default_args"]; + defargs = p_dict["default_args"]; } - for(int i=0;i<defargs.size();i++) { + for (int i = 0; i < defargs.size(); i++) { mi.default_arguments.push_back(defargs[i]); } if (p_dict.has("return")) { - mi.return_val=PropertyInfo::from_dict(p_dict["return"]); + mi.return_val = PropertyInfo::from_dict(p_dict["return"]); } if (p_dict.has("flags")) - mi.flags=p_dict["flags"]; + mi.flags = p_dict["flags"]; return mi; } -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; @@ -316,52 +309,45 @@ bool Object::Connection::operator<(const Connection& p_conn) const { } else return signal < p_conn.signal; } else { - return source<p_conn.source; + return source < p_conn.source; } } -Object::Connection::Connection(const Variant& p_variant) { +Object::Connection::Connection(const Variant &p_variant) { - Dictionary d=p_variant; + Dictionary d = p_variant; if (d.has("source")) - source=d["source"]; + source = d["source"]; if (d.has("signal")) - signal=d["signal"]; + signal = d["signal"]; if (d.has("target")) - target=d["target"]; + target = d["target"]; if (d.has("method")) - method=d["method"]; + method = d["method"]; if (d.has("flags")) - flags=d["flags"]; + flags = d["flags"]; if (d.has("binds")) - binds=d["binds"]; + binds = d["binds"]; } - bool Object::_predelete() { - _predelete_ok=1; - notification(NOTIFICATION_PREDELETE,true); + _predelete_ok = 1; + notification(NOTIFICATION_PREDELETE, true); if (_predelete_ok) { - _class_ptr=NULL; //must restore so destructors can access class ptr correctly + _class_ptr = NULL; //must restore so destructors can access class ptr correctly } return _predelete_ok; - } void Object::_postinitialize() { - _class_ptr=_get_class_namev(); + _class_ptr = _get_class_namev(); _initialize_classv(); notification(NOTIFICATION_POSTINITIALIZE); - } void Object::get_valid_parents_static(List<String> *p_parents) { - - } void Object::_get_valid_parents_static(List<String> *p_parents) { - - } #if 0 //old style set, deprecated @@ -393,26 +379,25 @@ 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 (ClassDB::set_property(this,p_name,p_value,r_valid)) { + if (ClassDB::set_property(this, p_name, p_value, r_valid)) { /* if (r_valid) *r_valid=true; @@ -421,85 +406,76 @@ void Object::set(const StringName& p_name, const Variant& p_value, bool *r_valid } } - - 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 (ClassDB::get_property(const_cast<Object*>(this),p_name,ret)) { + if (ClassDB::get_property(const_cast<Object *>(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 { @@ -528,86 +504,78 @@ Variant Object::get(const String& p_name) const { } #endif -void Object::get_property_list(List<PropertyInfo> *p_list,bool p_reversed) const { +void Object::get_property_list(List<PropertyInfo> *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 (!is_class("Script")) // can still be set, but this is for userfriendlyness - p_list->push_back( PropertyInfo( Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NONZERO)); + p_list->push_back(PropertyInfo(Variant::OBJECT, "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<MethodInfo> *p_list) const { - ClassDB::get_method_list(get_class_name(),p_list); + ClassDB::get_method_list(get_class_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 @@ -627,10 +595,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; @@ -638,37 +605,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<Reference>()) { ERR_EXPLAIN("Can't 'free' a reference."); @@ -676,8 +642,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; @@ -695,59 +660,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=ClassDB::get_method(get_class_name(),p_method); + MethodBind *method = ClassDB::get_method(get_class_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=ClassDB::get_method(get_class_name(),p_method); + MethodBind *method = ClassDB::get_method(get_class_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=ClassDB::get_method(get_class_name(),p_method); + MethodBind *method = ClassDB::get_method(get_class_name(), p_method); if (method) { return true; @@ -756,42 +713,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<Variant> args; args.resize(p_args.size()); - Vector<const Variant*> argptrs; + Vector<const Variant *> argptrs; argptrs.resize(p_args.size()); - for(int i=0;i<p_args.size();i++) { - args[i]=p_args[i]; - argptrs[i]=&args[i]; + for (int i = 0; i < p_args.size(); i++) { + args[i] = p_args[i]; + argptrs[i] = &args[i]; } Variant::CallError ce; - return call(p_method,argptrs.ptr(),p_args.size(),ce); - + return call(p_method, argptrs.ptr(), p_args.size(), ce); } -Variant Object::call(const StringName& p_name, VARIANT_ARG_DECLARE) { +Variant Object::call(const StringName &p_name, VARIANT_ARG_DECLARE) { #if 0 if (p_name==CoreStringNames::get_singleton()->_free) { #ifdef DEBUG_ENABLED @@ -843,23 +797,22 @@ Variant Object::call(const StringName& p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_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 @@ -904,62 +857,58 @@ void Object::call_multilevel(const StringName& p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_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<Reference>()) { - 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; @@ -969,45 +918,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=ClassDB::get_method(get_class_name(),p_method); + MethodBind *method = ClassDB::get_method(get_class_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); } @@ -1019,47 +964,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<Script> s(script); - if (!s.is_null() && s->can_instance() ) { + if (!s.is_null() && s->can_instance()) { OBJ_DEBUG_LOCK script_instance = s->instance_create(this); - } _change_notify("script"); emit_signal(CoreStringNames::get_singleton()->script_changed); - } void Object::set_script_instance(ScriptInstance *p_instance) { - if (script_instance==p_instance) + if (script_instance == p_instance) return; if (script_instance) memdelete(script_instance); - script_instance=p_instance; + script_instance = p_instance; if (p_instance) - script=p_instance->get_script().get_ref_ptr(); + script = p_instance->get_script().get_ref_ptr(); else - script=RefPtr(); + script = RefPtr(); } RefPtr Object::get_script() const { @@ -1067,28 +1010,27 @@ RefPtr Object::get_script() const { return script; } -bool Object::has_meta(const String& p_name) const { +bool Object::has_meta(const String &p_name) const { return metadata.has(p_name); } -void Object::set_meta(const String& p_name, const Variant& p_value ) { +void Object::set_meta(const String &p_name, const Variant &p_value) { if (p_value.get_type() == Variant::NIL) { metadata.erase(p_name); return; }; - metadata[p_name]=p_value; + metadata[p_name] = p_value; } -Variant Object::get_meta(const String& p_name) const { +Variant Object::get_meta(const String &p_name) const { - ERR_FAIL_COND_V(!metadata.has(p_name),Variant()); + ERR_FAIL_COND_V(!metadata.has(p_name), Variant()); return metadata[p_name]; } - Array Object::_get_property_list_bind() const { List<PropertyInfo> lpi; @@ -1096,15 +1038,13 @@ Array Object::_get_property_list_bind() const { return convert_property_list(&lpi); } - - Array Object::_get_method_list_bind() const { List<MethodInfo> ml; get_method_list(&ml); Array ret; - for(List<MethodInfo>::Element *E=ml.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) { Dictionary d = E->get(); //va.push_back(d); @@ -1112,7 +1052,6 @@ Array Object::_get_method_list_bind() const { } return ret; - } PoolVector<String> Object::_get_meta_list_bind() const { @@ -1121,7 +1060,7 @@ PoolVector<String> Object::_get_meta_list_bind() const { List<Variant> keys; metadata.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _metaret.push_back(E->get()); } @@ -1132,27 +1071,27 @@ void Object::get_meta_list(List<String> *p_list) const { List<Variant> keys; metadata.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { p_list->push_back(E->get()); } } -void Object::add_user_signal(const MethodInfo& p_signal) { +void Object::add_user_signal(const MethodInfo &p_signal) { - ERR_FAIL_COND(p_signal.name==""); - ERR_FAIL_COND( ClassDB::has_signal(get_class_name(),p_signal.name ) ); + ERR_FAIL_COND(p_signal.name == ""); + ERR_FAIL_COND(ClassDB::has_signal(get_class_name(), p_signal.name)); ERR_FAIL_COND(signal_map.has(p_signal.name)); Signal s; - s.user=p_signal; - signal_map[p_signal.name]=s; + s.user = p_signal; + signal_map[p_signal.name] = s; } -bool Object::_has_user_signal(const StringName& p_name) const { +bool Object::_has_user_signal(const StringName &p_name) const { if (!signal_map.has(p_name)) return false; - return signal_map[p_name].user.name.length()>0; + return signal_map[p_name].user.name.length() > 0; } struct _ObjectSignalDisconnectData { @@ -1160,7 +1099,6 @@ struct _ObjectSignalDisconnectData { StringName signal; Object *target; StringName method; - }; #if 0 @@ -1179,39 +1117,35 @@ void Object::_emit_signal(const StringName& p_name,const Array& p_pargs){ #endif -Variant Object::_emit_signal(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { - +Variant Object::_emit_signal(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - ERR_FAIL_COND_V(p_argcount<1,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; - ERR_FAIL_COND_V(p_args[0]->get_type()!=Variant::STRING,Variant()); + ERR_FAIL_COND_V(p_argcount < 1, 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; + ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING, Variant()); } - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; StringName signal = *p_args[0]; + const Variant **args = NULL; - const Variant**args=NULL; - - int argc=p_argcount-1; + int argc = p_argcount - 1; if (argc) { - args=&p_args[1]; + args = &p_args[1]; } - emit_signal(signal,args,argc); + emit_signal(signal, args, argc); return Variant(); - } - -void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_argcount) { +void Object::emit_signal(const StringName &p_name, const Variant **p_args, int p_argcount) { if (_block_signals) return; //no emit, signals blocked @@ -1219,10 +1153,10 @@ void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_a Signal *s = signal_map.getptr(p_name); if (!s) { #ifdef DEBUG_ENABLED - bool signal_is_valid = ClassDB::has_signal(get_class_name(),p_name); + bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name); //check in script if (!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name)) { - ERR_EXPLAIN("Can't emit non-existing signal " + String("\"")+p_name+"\"."); + ERR_EXPLAIN("Can't emit non-existing signal " + String("\"") + p_name + "\"."); ERR_FAIL(); } #endif @@ -1230,23 +1164,20 @@ void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_a return; } - List<_ObjectSignalDisconnectData> disconnect_data; - //copy on write will ensure that disconnecting the signal or even deleting the object will not affect the signal calling. //this happens automatically and will not change the performance of calling. //awesome, isn't it? - VMap<Signal::Target,Signal::Slot> slot_map = s->slot_map; + VMap<Signal::Target, Signal::Slot> slot_map = s->slot_map; int ssize = slot_map.size(); OBJ_DEBUG_LOCK - Vector<const Variant*> bind_mem; - + Vector<const Variant *> bind_mem; - for(int i=0;i<ssize;i++) { + for (int i = 0; i < ssize; i++) { const Connection &c = slot_map.getv(i).conn; @@ -1255,107 +1186,97 @@ void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_a target = ObjectDB::get_instance(slot_map.getk(i)._id); ERR_CONTINUE(!target); #else - target=c.target; + target = c.target; #endif - - const Variant **args=p_args; - int argc=p_argcount; + const Variant **args = p_args; + int argc = p_argcount; if (c.binds.size()) { //handle binds - bind_mem.resize(p_argcount+c.binds.size()); + bind_mem.resize(p_argcount + c.binds.size()); - for(int j=0;j<p_argcount;j++) { - bind_mem[j]=p_args[j]; + for (int j = 0; j < p_argcount; j++) { + bind_mem[j] = p_args[j]; } - for(int j=0;j<c.binds.size();j++) { - bind_mem[p_argcount+j]=&c.binds[j]; + for (int j = 0; j < c.binds.size(); j++) { + bind_mem[p_argcount + j] = &c.binds[j]; } - args=bind_mem.ptr(); - argc=bind_mem.size(); + args = bind_mem.ptr(); + argc = bind_mem.size(); } - if (c.flags&CONNECT_DEFERRED) { - MessageQueue::get_singleton()->push_call(target->get_instance_ID(),c.method,args,argc,true); + if (c.flags & CONNECT_DEFERRED) { + MessageQueue::get_singleton()->push_call(target->get_instance_ID(), c.method, args, argc, true); } else { Variant::CallError ce; - target->call( c.method, args, argc,ce ); - if (ce.error!=Variant::CallError::CALL_OK) { + target->call(c.method, args, argc, ce); + if (ce.error != Variant::CallError::CALL_OK) { - if (ce.error==Variant::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists( target->get_class_name() ) ) { + if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) { //most likely object is not initialized yet, do not throw error. } else { - ERR_PRINTS("Error calling method from signal '"+String(p_name)+"': "+Variant::get_call_error_text(target,c.method,args,argc,ce)); + ERR_PRINTS("Error calling method from signal '" + String(p_name) + "': " + Variant::get_call_error_text(target, c.method, args, argc, ce)); } } } - if (c.flags&CONNECT_ONESHOT) { + if (c.flags & CONNECT_ONESHOT) { _ObjectSignalDisconnectData dd; - dd.signal=p_name; - dd.target=target; - dd.method=c.method; + dd.signal = p_name; + dd.target = target; + dd.method = c.method; disconnect_data.push_back(dd); } - } - while (!disconnect_data.empty()) { const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get(); - disconnect(dd.signal,dd.target,dd.method); + disconnect(dd.signal, dd.target, dd.method); disconnect_data.pop_front(); } - } -void Object::emit_signal(const StringName& p_name,VARIANT_ARG_DECLARE) { +void Object::emit_signal(const StringName &p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; + int argc = 0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_type()==Variant::NIL) + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + if (argptr[i]->get_type() == Variant::NIL) break; argc++; } - - emit_signal(p_name,argptr,argc); - + emit_signal(p_name, argptr, argc); } - -void Object::_add_user_signal(const String& p_name, const Array& p_args) { +void Object::_add_user_signal(const String &p_name, const Array &p_args) { // this version of add_user_signal is meant to be used from scripts or external apis // without access to ADD_SIGNAL in bind_methods // added events are per instance, as opposed to the other ones, which are global - - MethodInfo mi; - mi.name=p_name; + mi.name = p_name; - for(int i=0;i<p_args.size();i++) { + for (int i = 0; i < p_args.size(); i++) { - Dictionary d=p_args[i]; + Dictionary d = p_args[i]; PropertyInfo param; if (d.has("name")) - param.name=d["name"]; + param.name = d["name"]; if (d.has("type")) - param.type=(Variant::Type)(int)d["type"]; + param.type = (Variant::Type)(int)d["type"]; mi.arguments.push_back(param); } add_user_signal(mi); - } #if 0 void Object::_emit_signal(const StringName& p_name,const Array& p_pargs){ @@ -1372,105 +1293,99 @@ void Object::_emit_signal(const StringName& p_name,const Array& p_pargs){ } #endif -Array Object::_get_signal_list() const{ +Array Object::_get_signal_list() const { List<MethodInfo> signal_list; get_signal_list(&signal_list); Array ret; - for (List<MethodInfo>::Element *E=signal_list.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = signal_list.front(); E; E = E->next()) { ret.push_back(Dictionary(E->get())); } return ret; } -Array Object::_get_signal_connection_list(const String& p_signal) const{ +Array Object::_get_signal_connection_list(const String &p_signal) const { List<Connection> conns; get_all_signal_connections(&conns); Array ret; - for (List<Connection>::Element *E=conns.front();E;E=E->next()) { + for (List<Connection>::Element *E = conns.front(); E; E = E->next()) { - Connection &c=E->get(); - if (c.signal == p_signal){ + Connection &c = E->get(); + if (c.signal == p_signal) { Dictionary rc; - rc["signal"]=c.signal; - rc["method"]=c.method; - rc["source"]=c.source; - rc["target"]=c.target; - rc["binds"]=c.binds; - rc["flags"]=c.flags; + rc["signal"] = c.signal; + rc["method"] = c.method; + rc["source"] = c.source; + rc["target"] = c.target; + rc["binds"] = c.binds; + rc["flags"] = c.flags; ret.push_back(rc); } } return ret; - } - -void Object::get_signal_list(List<MethodInfo> *p_signals ) const { +void Object::get_signal_list(List<MethodInfo> *p_signals) const { if (!script.is_null()) { Ref<Script>(script)->get_script_signal_list(p_signals); } - ClassDB::get_signal_list(get_class_name(),p_signals); + ClassDB::get_signal_list(get_class_name(), p_signals); //find maybe usersignals? - const StringName *S=NULL; + const StringName *S = NULL; - while((S=signal_map.next(S))) { + while ((S = signal_map.next(S))) { - if (signal_map[*S].user.name!="") { + if (signal_map[*S].user.name != "") { //user signal p_signals->push_back(signal_map[*S].user); } } - } - void Object::get_all_signal_connections(List<Connection> *p_connections) const { - const StringName *S=NULL; + const StringName *S = NULL; - while((S=signal_map.next(S))) { + while ((S = signal_map.next(S))) { - const Signal *s=&signal_map[*S]; + const Signal *s = &signal_map[*S]; - for(int i=0;i<s->slot_map.size();i++) { + for (int i = 0; i < s->slot_map.size(); i++) { p_connections->push_back(s->slot_map.getv(i).conn); } } - } -void Object::get_signal_connection_list(const StringName& p_signal,List<Connection> *p_connections) const { +void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const { - const Signal *s=signal_map.getptr(p_signal); + const Signal *s = signal_map.getptr(p_signal); if (!s) return; //nothing - for(int i=0;i<s->slot_map.size();i++) + for (int i = 0; i < s->slot_map.size(); i++) p_connections->push_back(s->slot_map.getv(i).conn); - } bool Object::has_persistent_signal_connections() const { - const StringName *S=NULL; + const StringName *S = NULL; - while((S=signal_map.next(S))) { + while ((S = signal_map.next(S))) { - const Signal *s=&signal_map[*S]; + const Signal *s = &signal_map[*S]; - for(int i=0;i<s->slot_map.size();i++) { + for (int i = 0; i < s->slot_map.size(); i++) { - if (s->slot_map.getv(i).conn.flags&CONNECT_PERSIST) + if (s->slot_map.getv(i).conn.flags & CONNECT_PERSIST) return true; } } @@ -1480,128 +1395,125 @@ bool Object::has_persistent_signal_connections() const { void Object::get_signals_connected_to_this(List<Connection> *p_connections) const { - for (const List<Connection>::Element *E=connections.front();E;E=E->next()) { + for (const List<Connection>::Element *E = connections.front(); E; E = E->next()) { p_connections->push_back(E->get()); } } +Error Object::connect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method, const Vector<Variant> &p_binds, uint32_t p_flags) { -Error Object::connect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method,const Vector<Variant>& p_binds,uint32_t p_flags) { - - ERR_FAIL_NULL_V(p_to_object,ERR_INVALID_PARAMETER); + ERR_FAIL_NULL_V(p_to_object, ERR_INVALID_PARAMETER); Signal *s = signal_map.getptr(p_signal); if (!s) { - bool signal_is_valid = ClassDB::has_signal(get_class_name(),p_signal); + bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal); //check in script if (!signal_is_valid && !script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) - signal_is_valid=true; + signal_is_valid = true; if (!signal_is_valid) { - ERR_EXPLAIN("In Object of type '"+String(get_class())+"': Attempt to connect nonexistent signal '"+p_signal+"' to method '"+p_to_object->get_class()+"."+p_to_method+"'"); - ERR_FAIL_COND_V(!signal_is_valid,ERR_INVALID_PARAMETER); + ERR_EXPLAIN("In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to method '" + p_to_object->get_class() + "." + p_to_method + "'"); + ERR_FAIL_COND_V(!signal_is_valid, ERR_INVALID_PARAMETER); } - signal_map[p_signal]=Signal(); - s=&signal_map[p_signal]; + signal_map[p_signal] = Signal(); + s = &signal_map[p_signal]; } - Signal::Target target(p_to_object->get_instance_ID(),p_to_method); + Signal::Target target(p_to_object->get_instance_ID(), p_to_method); if (s->slot_map.has(target)) { - ERR_EXPLAIN("Signal '"+p_signal+"'' already connected to given method '"+p_to_method+"' in that object."); - ERR_FAIL_COND_V(s->slot_map.has(target),ERR_INVALID_PARAMETER); + ERR_EXPLAIN("Signal '" + p_signal + "'' already connected to given method '" + p_to_method + "' in that object."); + ERR_FAIL_COND_V(s->slot_map.has(target), ERR_INVALID_PARAMETER); } Signal::Slot slot; Connection conn; - conn.source=this; - conn.target=p_to_object; - conn.method=p_to_method; - conn.signal=p_signal; - conn.flags=p_flags; - conn.binds=p_binds; - slot.conn=conn; - slot.cE=p_to_object->connections.push_back(conn); - s->slot_map[target]=slot; + conn.source = this; + conn.target = p_to_object; + conn.method = p_to_method; + conn.signal = p_signal; + conn.flags = p_flags; + conn.binds = p_binds; + slot.conn = conn; + slot.cE = p_to_object->connections.push_back(conn); + s->slot_map[target] = slot; return OK; } -bool Object::is_connected(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method) const { +bool Object::is_connected(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) const { - ERR_FAIL_NULL_V(p_to_object,false); + ERR_FAIL_NULL_V(p_to_object, false); const Signal *s = signal_map.getptr(p_signal); if (!s) { - bool signal_is_valid = ClassDB::has_signal(get_class_name(),p_signal); + bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal); if (signal_is_valid) return false; if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) return false; - ERR_EXPLAIN("Nonexistent signal: "+p_signal); - ERR_FAIL_COND_V(!s,false); + ERR_EXPLAIN("Nonexistent signal: " + p_signal); + ERR_FAIL_COND_V(!s, false); } - Signal::Target target(p_to_object->get_instance_ID(),p_to_method); + Signal::Target target(p_to_object->get_instance_ID(), p_to_method); return s->slot_map.has(target); //const Map<Signal::Target,Signal::Slot>::Element *E = s->slot_map.find(target); //return (E!=NULL); - } -void Object::disconnect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method) { +void Object::disconnect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) { ERR_FAIL_NULL(p_to_object); Signal *s = signal_map.getptr(p_signal); if (!s) { - ERR_EXPLAIN("Nonexistent signal: "+p_signal); + ERR_EXPLAIN("Nonexistent signal: " + p_signal); ERR_FAIL_COND(!s); } - if (s->lock>0) { - ERR_EXPLAIN("Attempt to disconnect signal '"+p_signal+"' while emitting (locks: "+itos(s->lock)+")"); - ERR_FAIL_COND(s->lock>0); + if (s->lock > 0) { + ERR_EXPLAIN("Attempt to disconnect signal '" + p_signal + "' while emitting (locks: " + itos(s->lock) + ")"); + ERR_FAIL_COND(s->lock > 0); } - Signal::Target target(p_to_object->get_instance_ID(),p_to_method); + Signal::Target target(p_to_object->get_instance_ID(), p_to_method); if (!s->slot_map.has(target)) { - ERR_EXPLAIN("Disconnecting nonexistent signal '"+p_signal+"', slot: "+itos(target._id)+":"+target.method); + ERR_EXPLAIN("Disconnecting nonexistent signal '" + p_signal + "', slot: " + itos(target._id) + ":" + target.method); ERR_FAIL(); } p_to_object->connections.erase(s->slot_map[target].cE); s->slot_map.erase(target); - if (s->slot_map.empty() && ClassDB::has_signal(get_class_name(),p_signal )) { + if (s->slot_map.empty() && ClassDB::has_signal(get_class_name(), p_signal)) { //not user signal, delete signal_map.erase(p_signal); } } +void Object::_set_bind(const String &p_set, const Variant &p_value) { -void Object::_set_bind(const String& p_set,const Variant& p_value) { - - set(p_set,p_value); + set(p_set, p_value); } -Variant Object::_get_bind(const String& p_name) const { +Variant Object::_get_bind(const String &p_name) const { return get(p_name); } void Object::initialize_class() { - static bool initialized=false; + static bool initialized = false; if (initialized) return; ClassDB::_add_class<Object>(); _bind_methods(); - initialized=true; + initialized = true; } -StringName Object::XL_MESSAGE(const StringName& p_message) const { +StringName Object::XL_MESSAGE(const StringName &p_message) const { if (!_can_translate || !TranslationServer::get_singleton()) return p_message; @@ -1609,16 +1521,14 @@ StringName Object::XL_MESSAGE(const StringName& p_message) const { return TranslationServer::get_singleton()->translate(p_message); } -StringName Object::tr(const StringName& p_message) const { +StringName Object::tr(const StringName &p_message) const { return XL_MESSAGE(p_message); - } - void Object::_clear_internal_resource_paths(const Variant &p_var) { - switch(p_var.get_type()) { + switch (p_var.get_type()) { case Variant::OBJECT: { @@ -1626,10 +1536,10 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) { if (!r.is_valid()) return; - if (!r->get_path().begins_with("res://") || r->get_path().find("::")==-1) + if (!r->get_path().begins_with("res://") || r->get_path().find("::") == -1) return; //not an internal resource - Object *object=p_var; + Object *object = p_var; if (!object) return; @@ -1638,19 +1548,19 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) { } break; case Variant::ARRAY: { - Array a=p_var; - for(int i=0;i<a.size();i++) { + Array a = p_var; + for (int i = 0; i < a.size(); i++) { _clear_internal_resource_paths(a[i]); } } break; case Variant::DICTIONARY: { - Dictionary d=p_var; + Dictionary d = p_var; List<Variant> keys; d.get_key_list(&keys); - for (List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _clear_internal_resource_paths(E->get()); _clear_internal_resource_paths(d[E->get()]); @@ -1658,7 +1568,6 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) { } break; default: {} } - } void Object::clear_internal_resource_paths() { @@ -1667,7 +1576,7 @@ void Object::clear_internal_resource_paths() { get_property_list(&pinfo); - for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { _clear_internal_resource_paths(get(E->get().name)); } @@ -1675,122 +1584,116 @@ void Object::clear_internal_resource_paths() { void Object::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_class"),&Object::get_class); - ClassDB::bind_method(D_METHOD("is_class","type"),&Object::is_class); - ClassDB::bind_method(D_METHOD("set","property","value"),&Object::_set_bind); - ClassDB::bind_method(D_METHOD("get","property"),&Object::_get_bind); - ClassDB::bind_method(D_METHOD("get_property_list"),&Object::_get_property_list_bind); - ClassDB::bind_method(D_METHOD("get_method_list"),&Object::_get_method_list_bind); - ClassDB::bind_method(D_METHOD("notification","what","reversed"),&Object::notification,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_instance_ID"),&Object::get_instance_ID); + ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class); + ClassDB::bind_method(D_METHOD("is_class", "type"), &Object::is_class); + ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind); + ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind); + ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind); + ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind); + ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_instance_ID"), &Object::get_instance_ID); - ClassDB::bind_method(D_METHOD("set_script","script:Script"),&Object::set_script); - ClassDB::bind_method(D_METHOD("get_script:Script"),&Object::get_script); + ClassDB::bind_method(D_METHOD("set_script", "script:Script"), &Object::set_script); + ClassDB::bind_method(D_METHOD("get_script:Script"), &Object::get_script); - ClassDB::bind_method(D_METHOD("set_meta","name","value"),&Object::set_meta); - ClassDB::bind_method(D_METHOD("get_meta","name","value"),&Object::get_meta); - ClassDB::bind_method(D_METHOD("has_meta","name"),&Object::has_meta); - ClassDB::bind_method(D_METHOD("get_meta_list"),&Object::_get_meta_list_bind); + ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta); + ClassDB::bind_method(D_METHOD("get_meta", "name", "value"), &Object::get_meta); + ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta); + ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind); //todo reimplement this per language so all 5 arguments can be called //ClassDB::bind_method(D_METHOD("call","method","arg1","arg2","arg3","arg4"),&Object::_call_bind,DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant())); //ClassDB::bind_method(D_METHOD("call_deferred","method","arg1","arg2","arg3","arg4"),&Object::_call_deferred_bind,DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("add_user_signal","signal","arguments"),&Object::_add_user_signal,DEFVAL(Array())); - ClassDB::bind_method(D_METHOD("has_user_signal","signal"),&Object::_has_user_signal); + ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal); //ClassDB::bind_method(D_METHOD("emit_signal","signal","arguments"),&Object::_emit_signal,DEFVAL(Array())); - { MethodInfo mi; - mi.name="emit_signal"; - mi.arguments.push_back( PropertyInfo( Variant::STRING, "signal")); + mi.name = "emit_signal"; + mi.arguments.push_back(PropertyInfo(Variant::STRING, "signal")); - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"emit_signal",&Object::_emit_signal,mi); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi); } { MethodInfo mi; - mi.name="call"; - mi.arguments.push_back( PropertyInfo( Variant::STRING, "method")); + mi.name = "call"; + mi.arguments.push_back(PropertyInfo(Variant::STRING, "method")); - - - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call:Variant",&Object::_call_bind,mi); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call:Variant", &Object::_call_bind, mi); } { MethodInfo mi; - mi.name="call_deferred"; - mi.arguments.push_back( PropertyInfo( Variant::STRING, "method")); + mi.name = "call_deferred"; + mi.arguments.push_back(PropertyInfo(Variant::STRING, "method")); - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call_deferred",&Object::_call_deferred_bind,mi); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi); } - ClassDB::bind_method(D_METHOD("callv:Variant","method","arg_array"),&Object::callv); + ClassDB::bind_method(D_METHOD("callv:Variant", "method", "arg_array"), &Object::callv); - ClassDB::bind_method(D_METHOD("has_method","method"),&Object::has_method); + ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method); - ClassDB::bind_method(D_METHOD("get_signal_list"),&Object::_get_signal_list); - ClassDB::bind_method(D_METHOD("get_signal_connection_list","signal"),&Object::_get_signal_connection_list); + ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list); + ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list); - ClassDB::bind_method(D_METHOD("connect","signal","target:Object","method","binds","flags"),&Object::connect,DEFVAL(Array()),DEFVAL(0)); - ClassDB::bind_method(D_METHOD("disconnect","signal","target:Object","method"),&Object::disconnect); - ClassDB::bind_method(D_METHOD("is_connected","signal","target:Object","method"),&Object::is_connected); + ClassDB::bind_method(D_METHOD("connect", "signal", "target:Object", "method", "binds", "flags"), &Object::connect, DEFVAL(Array()), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("disconnect", "signal", "target:Object", "method"), &Object::disconnect); + ClassDB::bind_method(D_METHOD("is_connected", "signal", "target:Object", "method"), &Object::is_connected); - ClassDB::bind_method(D_METHOD("set_block_signals","enable"),&Object::set_block_signals); - ClassDB::bind_method(D_METHOD("is_blocking_signals"),&Object::is_blocking_signals); - ClassDB::bind_method(D_METHOD("set_message_translation","enable"),&Object::set_message_translation); - ClassDB::bind_method(D_METHOD("can_translate_messages"),&Object::can_translate_messages); - ClassDB::bind_method(D_METHOD("property_list_changed_notify"),&Object::property_list_changed_notify); + ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals); + ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals); + ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation); + ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages); + ClassDB::bind_method(D_METHOD("property_list_changed_notify"), &Object::property_list_changed_notify); - ClassDB::bind_method(D_METHOD("XL_MESSAGE","message"),&Object::XL_MESSAGE); - ClassDB::bind_method(D_METHOD("tr","message"),&Object::tr); + ClassDB::bind_method(D_METHOD("XL_MESSAGE", "message"), &Object::XL_MESSAGE); + ClassDB::bind_method(D_METHOD("tr", "message"), &Object::tr); - ClassDB::bind_method(D_METHOD("is_queued_for_deletion"),&Object::is_queued_for_deletion); + ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion); - ClassDB::add_virtual_method("Object",MethodInfo("free"),false); + ClassDB::add_virtual_method("Object", MethodInfo("free"), false); - ADD_SIGNAL( MethodInfo("script_changed")); + ADD_SIGNAL(MethodInfo("script_changed")); - BIND_VMETHOD( MethodInfo("_notification",PropertyInfo(Variant::INT,"what")) ); - BIND_VMETHOD( MethodInfo("_set",PropertyInfo(Variant::STRING,"property"),PropertyInfo(Variant::NIL,"value")) ); + BIND_VMETHOD(MethodInfo("_notification", PropertyInfo(Variant::INT, "what"))); + BIND_VMETHOD(MethodInfo("_set", PropertyInfo(Variant::STRING, "property"), PropertyInfo(Variant::NIL, "value"))); #ifdef TOOLS_ENABLED - MethodInfo miget("_get",PropertyInfo(Variant::STRING,"property") ); - miget.return_val.name="var"; - BIND_VMETHOD( miget ); + MethodInfo miget("_get", PropertyInfo(Variant::STRING, "property")); + miget.return_val.name = "var"; + BIND_VMETHOD(miget); MethodInfo plget("_get_property_list"); - plget.return_val.type=Variant::ARRAY; - BIND_VMETHOD( plget ); + plget.return_val.type = Variant::ARRAY; + BIND_VMETHOD(plget); #endif - BIND_VMETHOD( MethodInfo("_init") ); - - - - BIND_CONSTANT( NOTIFICATION_POSTINITIALIZE ); - BIND_CONSTANT( NOTIFICATION_PREDELETE ); + BIND_VMETHOD(MethodInfo("_init")); - BIND_CONSTANT( CONNECT_DEFERRED ); - BIND_CONSTANT( CONNECT_PERSIST ); - BIND_CONSTANT( CONNECT_ONESHOT ); + BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE); + BIND_CONSTANT(NOTIFICATION_PREDELETE); + BIND_CONSTANT(CONNECT_DEFERRED); + BIND_CONSTANT(CONNECT_PERSIST); + BIND_CONSTANT(CONNECT_ONESHOT); } -void Object::call_deferred(const StringName& p_method,VARIANT_ARG_DECLARE) { +void Object::call_deferred(const StringName &p_method, VARIANT_ARG_DECLARE) { - MessageQueue::get_singleton()->push_call(this,p_method,VARIANT_ARG_PASS); + MessageQueue::get_singleton()->push_call(this, p_method, VARIANT_ARG_PASS); } void Object::set_block_signals(bool p_block) { - _block_signals=p_block; + _block_signals = p_block; } -bool Object::is_blocking_signals() const{ +bool Object::is_blocking_signals() const { return _block_signals; } @@ -1800,39 +1703,37 @@ void Object::get_translatable_strings(List<String> *p_strings) const { List<PropertyInfo> plist; get_property_list(&plist); - for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - if (!(E->get().usage&PROPERTY_USAGE_INTERNATIONALIZED)) + if (!(E->get().usage & PROPERTY_USAGE_INTERNATIONALIZED)) continue; - String text = get( E->get().name ); + String text = get(E->get().name); - if (text=="") + if (text == "") continue; p_strings->push_back(text); } - } -Variant::Type Object::get_static_property_type(const StringName& p_property, bool *r_valid) const { +Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const { bool valid; - Variant::Type t = ClassDB::get_property_type(get_class_name(),p_property,&valid); + Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid); if (valid) { if (r_valid) - *r_valid=true; + *r_valid = true; return t; } if (get_script_instance()) { - return get_script_instance()->get_property_type(p_property,r_valid); + return get_script_instance()->get_property_type(p_property, r_valid); } if (r_valid) - *r_valid=false; + *r_valid = false; return Variant::NIL; - } bool Object::is_queued_for_deletion() const { @@ -1842,14 +1743,13 @@ bool Object::is_queued_for_deletion() const { #ifdef TOOLS_ENABLED void Object::set_edited(bool p_edited) { - _edited=p_edited; + _edited = p_edited; _edited_version++; } bool Object::is_edited() const { return _edited; - } uint32_t Object::get_edited_version() const { @@ -1860,76 +1760,66 @@ uint32_t Object::get_edited_version() const { Object::Object() { - _class_ptr=NULL; - _block_signals=false; - _predelete_ok=0; - _instance_ID=0; + _class_ptr = NULL; + _block_signals = false; + _predelete_ok = 0; + _instance_ID = 0; _instance_ID = ObjectDB::add_instance(this); - _can_translate=true; - _is_queued_for_deletion=false; - script_instance=NULL; + _can_translate = true; + _is_queued_for_deletion = false; + script_instance = NULL; #ifdef TOOLS_ENABLED - _edited=false; - _edited_version=0; + _edited = false; + _edited_version = 0; #endif #ifdef DEBUG_ENABLED _lock_index.init(1); #endif - - - } - Object::~Object() { - - if (script_instance) memdelete(script_instance); - script_instance=NULL; - + script_instance = NULL; List<Connection> sconnections; - const StringName *S=NULL; + const StringName *S = NULL; - while((S=signal_map.next(S))) { + while ((S = signal_map.next(S))) { - Signal *s=&signal_map[*S]; + Signal *s = &signal_map[*S]; ERR_EXPLAIN("Attempt to delete an object in the middle of a signal emission from it"); - ERR_CONTINUE(s->lock>0); + ERR_CONTINUE(s->lock > 0); - for(int i=0;i<s->slot_map.size();i++) { + for (int i = 0; i < s->slot_map.size(); i++) { sconnections.push_back(s->slot_map.getv(i).conn); } } - for(List<Connection>::Element *E=sconnections.front();E;E=E->next()) { + for (List<Connection>::Element *E = sconnections.front(); E; E = E->next()) { Connection &c = E->get(); - ERR_CONTINUE(c.source!=this); //bug? + ERR_CONTINUE(c.source != this); //bug? - this->disconnect(c.signal,c.target,c.method); + this->disconnect(c.signal, c.target, c.method); } - while(connections.size()) { + while (connections.size()) { Connection c = connections.front()->get(); - c.source->disconnect(c.signal,c.target,c.method); + c.source->disconnect(c.signal, c.target, c.method); } ObjectDB::remove_instance(this); - _instance_ID=0; - _predelete_ok=2; - + _instance_ID = 0; + _predelete_ok = 2; } - - bool predelete_handler(Object *p_object) { return p_object->_predelete(); @@ -1940,18 +1830,17 @@ void postinitialize_handler(Object *p_object) { p_object->_postinitialize(); } -HashMap<uint32_t,Object*> ObjectDB::instances; -uint32_t ObjectDB::instance_counter=1; -HashMap<Object*,ObjectID,ObjectDB::ObjectPtrHash> ObjectDB::instance_checks; +HashMap<uint32_t, Object *> ObjectDB::instances; +uint32_t ObjectDB::instance_counter = 1; +HashMap<Object *, ObjectID, ObjectDB::ObjectPtrHash> ObjectDB::instance_checks; uint32_t ObjectDB::add_instance(Object *p_object) { - - ERR_FAIL_COND_V( p_object->get_instance_ID()!=0, 0 ); + ERR_FAIL_COND_V(p_object->get_instance_ID() != 0, 0); rw_lock->write_lock(); - instances[++instance_counter]=p_object; + instances[++instance_counter] = p_object; #ifdef DEBUG_ENABLED - instance_checks[p_object]=instance_counter; + instance_checks[p_object] = instance_counter; #endif rw_lock->write_unlock(); @@ -1960,10 +1849,9 @@ uint32_t ObjectDB::add_instance(Object *p_object) { void ObjectDB::remove_instance(Object *p_object) { - rw_lock->write_lock(); - instances.erase( p_object->get_instance_ID() ); + instances.erase(p_object->get_instance_ID()); #ifdef DEBUG_ENABLED instance_checks.erase(p_object); #endif @@ -1973,7 +1861,7 @@ void ObjectDB::remove_instance(Object *p_object) { Object *ObjectDB::get_instance(uint32_t p_instance_ID) { rw_lock->read_lock(); - Object**obj=instances.getptr(p_instance_ID); + Object **obj = instances.getptr(p_instance_ID); rw_lock->read_unlock(); if (!obj) @@ -1985,34 +1873,28 @@ void ObjectDB::debug_objects(DebugFunc p_func) { rw_lock->read_lock(); - const uint32_t *K=NULL; - while((K=instances.next(K))) { + const uint32_t *K = NULL; + while ((K = instances.next(K))) { p_func(instances[*K]); } rw_lock->read_unlock(); - } - -void Object::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const { - - +void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { } int ObjectDB::get_object_count() { rw_lock->read_lock(); - int count =instances.size(); + int count = instances.size(); rw_lock->read_unlock(); return count; - } -RWLock *ObjectDB::rw_lock=NULL; - +RWLock *ObjectDB::rw_lock = NULL; void ObjectDB::setup() { @@ -2021,21 +1903,20 @@ void ObjectDB::setup() { void ObjectDB::cleanup() { - rw_lock->write_lock(); if (instances.size()) { WARN_PRINT("ObjectDB Instances still exist!"); if (OS::get_singleton()->is_stdout_verbose()) { - const uint32_t *K=NULL; - while((K=instances.next(K))) { + const uint32_t *K = NULL; + while ((K = instances.next(K))) { String node_name; if (instances[*K]->is_class("Node")) - node_name=" - Node Name: "+String(instances[*K]->call("get_name")); + node_name = " - Node Name: " + String(instances[*K]->call("get_name")); if (instances[*K]->is_class("Resoucre")) - node_name=" - Resource Name: "+String(instances[*K]->call("get_name"))+" Path: "+String(instances[*K]->call("get_path")); - print_line("Leaked Instance: "+String(instances[*K]->get_class())+":"+itos(*K)+node_name); + node_name = " - Resource Name: " + String(instances[*K]->call("get_name")) + " Path: " + String(instances[*K]->call("get_path")); + print_line("Leaked Instance: " + String(instances[*K]->get_class()) + ":" + itos(*K) + node_name); } } } diff --git a/core/object.h b/core/object.h index 3fe31bee6b..a5836b74ff 100644 --- a/core/object.h +++ b/core/object.h @@ -30,19 +30,19 @@ #define OBJECT_H #include "list.h" -#include "variant.h" -#include "set.h" #include "map.h" -#include "vmap.h" #include "os/rw_lock.h" +#include "set.h" +#include "variant.h" +#include "vmap.h" -#define VARIANT_ARG_LIST const Variant& p_arg1=Variant(),const Variant& p_arg2=Variant(),const Variant& p_arg3=Variant(),const Variant& p_arg4=Variant(),const Variant& p_arg5=Variant() -#define VARIANT_ARG_PASS p_arg1,p_arg2,p_arg3,p_arg4,p_arg5 -#define VARIANT_ARG_DECLARE const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4,const Variant& p_arg5 +#define VARIANT_ARG_LIST const Variant &p_arg1 = Variant(), const Variant &p_arg2 = Variant(), const Variant &p_arg3 = Variant(), const Variant &p_arg4 = Variant(), const Variant &p_arg5 = Variant() +#define VARIANT_ARG_PASS p_arg1, p_arg2, p_arg3, p_arg4, p_arg5 +#define VARIANT_ARG_DECLARE const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5 #define VARIANT_ARG_MAX 5 -#define VARIANT_ARGPTRS const Variant *argptr[5]={&p_arg1,&p_arg2,&p_arg3,&p_arg4,&p_arg5}; -#define VARIANT_ARGPTRS_PASS *argptr[0],*argptr[1],*argptr[2],*argptr[3],*argptr[4] -#define VARIANT_ARGS_FROM_ARRAY(m_arr) m_arr[0],m_arr[1],m_arr[2],m_arr[3],m_arr[4] +#define VARIANT_ARGPTRS const Variant *argptr[5] = { &p_arg1, &p_arg2, &p_arg3, &p_arg4, &p_arg5 }; +#define VARIANT_ARGPTRS_PASS *argptr[0], *argptr[1], *argptr[2], *argptr[3], *argptr[4] +#define VARIANT_ARGS_FROM_ARRAY(m_arr) m_arr[0], m_arr[1], m_arr[2], m_arr[3], m_arr[4] /** @author Juan Linietsky <reduzio@gmail.com> @@ -87,40 +87,37 @@ enum PropertyHint { enum PropertyUsageFlags { - PROPERTY_USAGE_STORAGE=1, - PROPERTY_USAGE_EDITOR=2, - PROPERTY_USAGE_NETWORK=4, - PROPERTY_USAGE_EDITOR_HELPER=8, - PROPERTY_USAGE_CHECKABLE=16, //used for editing global variables - PROPERTY_USAGE_CHECKED=32, //used for editing global variables - PROPERTY_USAGE_INTERNATIONALIZED=64, //hint for internationalized strings - PROPERTY_USAGE_GROUP=128, //used for grouping props in the editor - PROPERTY_USAGE_CATEGORY=256, - PROPERTY_USAGE_STORE_IF_NONZERO=512, //only store if nonzero - PROPERTY_USAGE_STORE_IF_NONONE=1024, //only store if false - PROPERTY_USAGE_NO_INSTANCE_STATE=2048, - PROPERTY_USAGE_RESTART_IF_CHANGED=4096, - PROPERTY_USAGE_SCRIPT_VARIABLE=8192, - PROPERTY_USAGE_STORE_IF_NULL=16384, - PROPERTY_USAGE_ANIMATE_AS_TRIGGER=32768, - PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED=65536, - - PROPERTY_USAGE_DEFAULT=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_NETWORK, - PROPERTY_USAGE_DEFAULT_INTL=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_NETWORK|PROPERTY_USAGE_INTERNATIONALIZED, - PROPERTY_USAGE_NOEDITOR=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_NETWORK, + PROPERTY_USAGE_STORAGE = 1, + PROPERTY_USAGE_EDITOR = 2, + PROPERTY_USAGE_NETWORK = 4, + PROPERTY_USAGE_EDITOR_HELPER = 8, + PROPERTY_USAGE_CHECKABLE = 16, //used for editing global variables + PROPERTY_USAGE_CHECKED = 32, //used for editing global variables + PROPERTY_USAGE_INTERNATIONALIZED = 64, //hint for internationalized strings + PROPERTY_USAGE_GROUP = 128, //used for grouping props in the editor + PROPERTY_USAGE_CATEGORY = 256, + PROPERTY_USAGE_STORE_IF_NONZERO = 512, //only store if nonzero + PROPERTY_USAGE_STORE_IF_NONONE = 1024, //only store if false + PROPERTY_USAGE_NO_INSTANCE_STATE = 2048, + PROPERTY_USAGE_RESTART_IF_CHANGED = 4096, + PROPERTY_USAGE_SCRIPT_VARIABLE = 8192, + PROPERTY_USAGE_STORE_IF_NULL = 16384, + PROPERTY_USAGE_ANIMATE_AS_TRIGGER = 32768, + PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED = 65536, + + PROPERTY_USAGE_DEFAULT = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_NETWORK, + PROPERTY_USAGE_DEFAULT_INTL = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_NETWORK | PROPERTY_USAGE_INTERNATIONALIZED, + PROPERTY_USAGE_NOEDITOR = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_NETWORK, }; - - - -#define ADD_SIGNAL( m_signal ) ClassDB::add_signal( get_class_static(), m_signal ) -#define ADD_PROPERTY( m_property, m_setter, m_getter ) ClassDB::add_property( get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter) ) -#define ADD_PROPERTYI( m_property, m_setter, m_getter, m_index ) ClassDB::add_property( get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter), m_index ) -#define ADD_PROPERTYNZ( m_property, m_setter, m_getter ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter) ) -#define ADD_PROPERTYINZ( m_property, m_setter, m_getter, m_index ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter), m_index ) -#define ADD_PROPERTYNO( m_property, m_setter, m_getter ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter) ) -#define ADD_PROPERTYINO( m_property, m_setter, m_getter, m_index ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter), m_index ) -#define ADD_GROUP( m_name, m_prefix ) ClassDB::add_property_group( get_class_static(), m_name, m_prefix ) +#define ADD_SIGNAL(m_signal) ClassDB::add_signal(get_class_static(), m_signal) +#define ADD_PROPERTY(m_property, m_setter, m_getter) ClassDB::add_property(get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter)) +#define ADD_PROPERTYI(m_property, m_setter, m_getter, m_index) ClassDB::add_property(get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter), m_index) +#define ADD_PROPERTYNZ(m_property, m_setter, m_getter) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter)) +#define ADD_PROPERTYINZ(m_property, m_setter, m_getter, m_index) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter), m_index) +#define ADD_PROPERTYNO(m_property, m_setter, m_getter) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter)) +#define ADD_PROPERTYINO(m_property, m_setter, m_getter, m_index) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter), m_index) +#define ADD_GROUP(m_name, m_prefix) ClassDB::add_property_group(get_class_static(), m_name, m_prefix) struct PropertyInfo { @@ -130,25 +127,34 @@ struct PropertyInfo { String hint_string; uint32_t usage; - _FORCE_INLINE_ PropertyInfo added_usage(int p_fl) const { PropertyInfo pi=*this; pi.usage|=p_fl; return pi; } - + _FORCE_INLINE_ PropertyInfo added_usage(int p_fl) const { + PropertyInfo pi = *this; + pi.usage |= p_fl; + return pi; + } operator Dictionary() const; - static PropertyInfo from_dict(const Dictionary& p_dict); + static PropertyInfo from_dict(const Dictionary &p_dict); - PropertyInfo() { type=Variant::NIL; hint=PROPERTY_HINT_NONE; usage = PROPERTY_USAGE_DEFAULT; } - PropertyInfo( Variant::Type p_type, const String p_name, PropertyHint p_hint=PROPERTY_HINT_NONE, const String& p_hint_string="",uint32_t p_usage=PROPERTY_USAGE_DEFAULT) { - type=p_type; name=p_name; hint=p_hint; hint_string=p_hint_string; usage=p_usage; + PropertyInfo() { + type = Variant::NIL; + hint = PROPERTY_HINT_NONE; + usage = PROPERTY_USAGE_DEFAULT; + } + PropertyInfo(Variant::Type p_type, const String p_name, PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_string = "", uint32_t p_usage = PROPERTY_USAGE_DEFAULT) { + type = p_type; + name = p_name; + hint = p_hint; + hint_string = p_hint_string; + usage = p_usage; } - bool operator<(const PropertyInfo& p_info) const { - return name<p_info.name; + bool operator<(const PropertyInfo &p_info) const { + return name < p_info.name; } }; - - -Array convert_property_list(const List<PropertyInfo> * p_list); +Array convert_property_list(const List<PropertyInfo> *p_list); struct MethodInfo { @@ -159,25 +165,25 @@ struct MethodInfo { uint32_t flags; int id; - inline bool operator<(const MethodInfo& p_method) const { return id==p_method.id?(name < p_method.name):(id<p_method.id); } + inline bool operator<(const MethodInfo &p_method) const { return id == p_method.id ? (name < p_method.name) : (id < p_method.id); } operator Dictionary() const; - static MethodInfo from_dict(const Dictionary& p_dict); + static MethodInfo from_dict(const Dictionary &p_dict); MethodInfo(); - MethodInfo(const String& p_name); - MethodInfo(const String& p_name, const PropertyInfo& p_param1); - MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2); - MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3); - MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4); - 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); + MethodInfo(const String &p_name); + MethodInfo(const String &p_name, const PropertyInfo &p_param1); + MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2); + MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3); + MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4); + 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); MethodInfo(Variant::Type ret); - MethodInfo(Variant::Type ret,const String& p_name); - MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1); - MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2); - MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3); - 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(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); + MethodInfo(Variant::Type ret, const String &p_name); + MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1); + MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2); + MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3); + 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(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); }; // old cast_to @@ -190,154 +196,156 @@ struct MethodInfo { the following is an uncomprehensible blob of hacks and workarounds to compensate for many of the fallencies in C++. As a plus, this macro pretty much alone defines the object model. */ -#define REVERSE_GET_PROPERTY_LIST \ -public:\ -_FORCE_INLINE_ bool _is_gpl_reversed() const { return true; };\ +#define REVERSE_GET_PROPERTY_LIST \ +public: \ + _FORCE_INLINE_ bool _is_gpl_reversed() const { return true; }; \ + \ private: -#define UNREVERSE_GET_PROPERTY_LIST \ -public:\ -_FORCE_INLINE_ bool _is_gpl_reversed() const { return false; };\ +#define UNREVERSE_GET_PROPERTY_LIST \ +public: \ + _FORCE_INLINE_ bool _is_gpl_reversed() const { return false; }; \ + \ private: - - -#define GDCLASS( m_class, m_inherits )\ -private:\ - void operator=(const m_class& p_rval) {}\ - mutable StringName _class_name;\ - friend class ClassDB;\ -public:\ -virtual String get_class() const { \ - return String(#m_class);\ -}\ -virtual const StringName* _get_class_namev() const { \ - if (!_class_name)\ - _class_name=get_class_static();\ - return &_class_name;\ -}\ -static _FORCE_INLINE_ void* get_class_ptr_static() { \ - static int ptr;\ - return &ptr;\ -}\ -static _FORCE_INLINE_ String get_class_static() { \ - return String(#m_class);\ -}\ -static _FORCE_INLINE_ String get_parent_class_static() { \ - return m_inherits::get_class_static();\ -}\ -static void get_inheritance_list_static(List<String>* p_inheritance_list) { \ - m_inherits::get_inheritance_list_static(p_inheritance_list);\ - p_inheritance_list->push_back(String(#m_class));\ -}\ -static String get_category_static() { \ - String category = m_inherits::get_category_static();\ - if (_get_category!=m_inherits::_get_category) {\ - if (category!="")\ - category+="/";\ - category+=_get_category();\ - }\ - return category;\ -}\ -static String inherits_static() {\ - return String(#m_inherits);\ -}\ -virtual bool is_class(const String& p_class) const { return (p_class==(#m_class))?true:m_inherits::is_class(p_class); }\ -virtual bool is_class_ptr(void *p_ptr) const { return (p_ptr==get_class_ptr_static())?true:m_inherits::is_class_ptr(p_ptr); }\ -\ -\ -static void get_valid_parents_static(List<String> *p_parents) {\ -\ - if (m_class::_get_valid_parents_static!=m_inherits::_get_valid_parents_static) { \ - m_class::_get_valid_parents_static(p_parents);\ - }\ -\ - m_inherits::get_valid_parents_static(p_parents);\ -}\ -protected:\ -_FORCE_INLINE_ static void (*_get_bind_methods())() {\ - return &m_class::_bind_methods;\ -}\ -public:\ -static void initialize_class() {\ - static bool initialized=false;\ - if (initialized)\ - return;\ - m_inherits::initialize_class();\ - ClassDB::_add_class<m_class>();\ - if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods())\ - _bind_methods();\ - initialized=true;\ -}\ -protected:\ -virtual void _initialize_classv() {\ - initialize_class();\ -}\ -_FORCE_INLINE_ bool (Object::* (_get_get() const))(const StringName& p_name,Variant&) const {\ - return (bool (Object::*)(const StringName&,Variant&)const) &m_class::_get;\ -}\ -virtual bool _getv(const StringName& p_name, Variant& r_ret) const { \ - if (m_class::_get_get() != m_inherits::_get_get()) {\ - if (_get(p_name,r_ret))\ - return true;\ - }\ - return m_inherits::_getv(p_name,r_ret);\ -}\ -_FORCE_INLINE_ bool (Object::* (_get_set() const))(const StringName& p_name,const Variant &p_property) {\ - return (bool (Object::*)(const StringName&, const Variant&))&m_class::_set;\ -}\ -virtual bool _setv(const StringName& p_name,const Variant &p_property) { \ - if (m_inherits::_setv(p_name,p_property)) return true;\ - if (m_class::_get_set() != m_inherits::_get_set()) {\ - return _set(p_name,p_property);\ - \ - }\ - return false;\ -}\ -_FORCE_INLINE_ void (Object::* (_get_get_property_list() const))(List<PropertyInfo> *p_list) const{\ - return (void (Object::*)(List<PropertyInfo>*)const)&m_class::_get_property_list;\ -}\ -virtual void _get_property_listv(List<PropertyInfo> *p_list,bool p_reversed) const { \ - if (!p_reversed) {\ - m_inherits::_get_property_listv(p_list,p_reversed);\ - }\ - p_list->push_back( PropertyInfo(Variant::NIL,get_class_static(),PROPERTY_HINT_NONE,String(),PROPERTY_USAGE_CATEGORY));\ - if (!_is_gpl_reversed())\ - ClassDB::get_property_list(#m_class,p_list,true,this);\ - if (m_class::_get_get_property_list() != m_inherits::_get_get_property_list()) {\ - _get_property_list(p_list);\ - }\ - if (_is_gpl_reversed())\ - ClassDB::get_property_list(#m_class,p_list,true,this);\ - if (p_reversed) {\ - m_inherits::_get_property_listv(p_list,p_reversed);\ - }\ -\ -}\ -_FORCE_INLINE_ void (Object::* (_get_notification() const))(int){\ - return (void (Object::*)(int)) &m_class::_notification;\ -}\ -virtual void _notificationv(int p_notification,bool p_reversed) { \ - if (!p_reversed) \ - m_inherits::_notificationv(p_notification,p_reversed);\ - if (m_class::_get_notification() != m_inherits::_get_notification()) {\ - _notification(p_notification);\ - }\ - if (p_reversed)\ - m_inherits::_notificationv(p_notification,p_reversed);\ -}\ -\ +#define GDCLASS(m_class, m_inherits) \ +private: \ + void operator=(const m_class &p_rval) {} \ + mutable StringName _class_name; \ + friend class ClassDB; \ + \ +public: \ + virtual String get_class() const { \ + return String(#m_class); \ + } \ + virtual const StringName *_get_class_namev() const { \ + if (!_class_name) \ + _class_name = get_class_static(); \ + return &_class_name; \ + } \ + static _FORCE_INLINE_ void *get_class_ptr_static() { \ + static int ptr; \ + return &ptr; \ + } \ + static _FORCE_INLINE_ String get_class_static() { \ + return String(#m_class); \ + } \ + static _FORCE_INLINE_ String get_parent_class_static() { \ + return m_inherits::get_class_static(); \ + } \ + static void get_inheritance_list_static(List<String> *p_inheritance_list) { \ + m_inherits::get_inheritance_list_static(p_inheritance_list); \ + p_inheritance_list->push_back(String(#m_class)); \ + } \ + static String get_category_static() { \ + String category = m_inherits::get_category_static(); \ + if (_get_category != m_inherits::_get_category) { \ + if (category != "") \ + category += "/"; \ + category += _get_category(); \ + } \ + return category; \ + } \ + static String inherits_static() { \ + return String(#m_inherits); \ + } \ + virtual bool is_class(const String &p_class) const { return (p_class == (#m_class)) ? true : m_inherits::is_class(p_class); } \ + virtual bool is_class_ptr(void *p_ptr) const { return (p_ptr == get_class_ptr_static()) ? true : m_inherits::is_class_ptr(p_ptr); } \ + \ + static void get_valid_parents_static(List<String> *p_parents) { \ + \ + if (m_class::_get_valid_parents_static != m_inherits::_get_valid_parents_static) { \ + m_class::_get_valid_parents_static(p_parents); \ + } \ + \ + m_inherits::get_valid_parents_static(p_parents); \ + } \ + \ +protected: \ + _FORCE_INLINE_ static void (*_get_bind_methods())() { \ + return &m_class::_bind_methods; \ + } \ + \ +public: \ + static void initialize_class() { \ + static bool initialized = false; \ + if (initialized) \ + return; \ + m_inherits::initialize_class(); \ + ClassDB::_add_class<m_class>(); \ + if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods()) \ + _bind_methods(); \ + initialized = true; \ + } \ + \ +protected: \ + virtual void _initialize_classv() { \ + initialize_class(); \ + } \ + _FORCE_INLINE_ bool (Object::*(_get_get() const))(const StringName &p_name, Variant &) const { \ + return (bool (Object::*)(const StringName &, Variant &) const) & m_class::_get; \ + } \ + virtual bool _getv(const StringName &p_name, Variant &r_ret) const { \ + if (m_class::_get_get() != m_inherits::_get_get()) { \ + if (_get(p_name, r_ret)) \ + return true; \ + } \ + return m_inherits::_getv(p_name, r_ret); \ + } \ + _FORCE_INLINE_ bool (Object::*(_get_set() const))(const StringName &p_name, const Variant &p_property) { \ + return (bool (Object::*)(const StringName &, const Variant &)) & m_class::_set; \ + } \ + virtual bool _setv(const StringName &p_name, const Variant &p_property) { \ + if (m_inherits::_setv(p_name, p_property)) return true; \ + if (m_class::_get_set() != m_inherits::_get_set()) { \ + return _set(p_name, p_property); \ + } \ + return false; \ + } \ + _FORCE_INLINE_ void (Object::*(_get_get_property_list() const))(List<PropertyInfo> * p_list) const { \ + return (void (Object::*)(List<PropertyInfo> *) const) & m_class::_get_property_list; \ + } \ + virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const { \ + if (!p_reversed) { \ + m_inherits::_get_property_listv(p_list, p_reversed); \ + } \ + p_list->push_back(PropertyInfo(Variant::NIL, get_class_static(), PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY)); \ + if (!_is_gpl_reversed()) \ + ClassDB::get_property_list(#m_class, p_list, true, this); \ + if (m_class::_get_get_property_list() != m_inherits::_get_get_property_list()) { \ + _get_property_list(p_list); \ + } \ + if (_is_gpl_reversed()) \ + ClassDB::get_property_list(#m_class, p_list, true, this); \ + if (p_reversed) { \ + m_inherits::_get_property_listv(p_list, p_reversed); \ + } \ + } \ + _FORCE_INLINE_ void (Object::*(_get_notification() const))(int) { \ + return (void (Object::*)(int)) & m_class::_notification; \ + } \ + virtual void _notificationv(int p_notification, bool p_reversed) { \ + if (!p_reversed) \ + m_inherits::_notificationv(p_notification, p_reversed); \ + if (m_class::_get_notification() != m_inherits::_get_notification()) { \ + _notification(p_notification); \ + } \ + if (p_reversed) \ + m_inherits::_notificationv(p_notification, p_reversed); \ + } \ + \ private: - -#define OBJ_CATEGORY(m_category)\ -protected:\ -_FORCE_INLINE_ static String _get_category() { return m_category; }\ +#define OBJ_CATEGORY(m_category) \ +protected: \ + _FORCE_INLINE_ static String _get_category() { return m_category; } \ + \ private: -#define OBJ_SAVE_TYPE(m_class) \ -public: \ -virtual String get_save_class() const { return #m_class; }\ +#define OBJ_SAVE_TYPE(m_class) \ +public: \ + virtual String get_save_class() const { return #m_class; } \ + \ private: class ScriptInstance; @@ -345,12 +353,11 @@ typedef uint32_t ObjectID; class Object { public: - enum ConnectFlags { - CONNECT_DEFERRED=1, - CONNECT_PERSIST=2, // hint for scene to save this connection - CONNECT_ONESHOT=4 + CONNECT_DEFERRED = 1, + CONNECT_PERSIST = 2, // hint for scene to save this connection + CONNECT_ONESHOT = 4 }; struct Connection { @@ -361,19 +368,23 @@ public: StringName method; uint32_t flags; Vector<Variant> binds; - bool operator<(const Connection& p_conn) const; + bool operator<(const Connection &p_conn) const; operator Variant() const; - Connection() { source=NULL; target=NULL; flags=0; } - Connection(const Variant& p_variant); + Connection() { + source = NULL; + target = NULL; + flags = 0; + } + Connection(const Variant &p_variant); }; + private: #ifdef DEBUG_ENABLED -friend class _ObjectDebugLock; + friend class _ObjectDebugLock; #endif -friend bool predelete_handler(Object*); -friend void postinitialize_handler(Object*); - + friend bool predelete_handler(Object *); + friend void postinitialize_handler(Object *); struct Signal { @@ -382,10 +393,13 @@ friend void postinitialize_handler(Object*); ObjectID _id; StringName method; - _FORCE_INLINE_ bool operator<(const Target& p_target) const { return (_id==p_target._id)?(method<p_target.method):(_id<p_target._id); } + _FORCE_INLINE_ bool operator<(const Target &p_target) const { return (_id == p_target._id) ? (method < p_target.method) : (_id < p_target._id); } - Target(const ObjectID& p_id, const StringName& p_method) { _id=p_id; method=p_method; } - Target() { _id=0; } + Target(const ObjectID &p_id, const StringName &p_method) { + _id = p_id; + method = p_method; + } + Target() { _id = 0; } }; struct Slot { @@ -395,21 +409,19 @@ friend void postinitialize_handler(Object*); }; MethodInfo user; - VMap<Target,Slot> slot_map; + VMap<Target, Slot> slot_map; int lock; - Signal() { lock=0; } - + Signal() { lock = 0; } }; - - HashMap< StringName, Signal, StringNameHasher> signal_map; + HashMap<StringName, Signal, StringNameHasher> signal_map; List<Connection> connections; #ifdef DEBUG_ENABLED SafeRefCount _lock_index; #endif bool _block_signals; int _predelete_ok; - Set<Object*> change_receptors; + Set<Object *> change_receptors; uint32_t _instance_ID; bool _predelete(); void _postinitialize(); @@ -422,67 +434,63 @@ friend void postinitialize_handler(Object*); RefPtr script; Dictionary metadata; mutable StringName _class_name; - mutable const StringName* _class_ptr; + mutable const StringName *_class_ptr; - void _add_user_signal(const String& p_name, const Array& p_pargs=Array()); - bool _has_user_signal(const StringName& p_name) const; - Variant _emit_signal(const Variant** p_args, int p_argcount, Variant::CallError& r_error); + void _add_user_signal(const String &p_name, const Array &p_pargs = Array()); + bool _has_user_signal(const StringName &p_name) const; + Variant _emit_signal(const Variant **p_args, int p_argcount, Variant::CallError &r_error); Array _get_signal_list() const; - Array _get_signal_connection_list(const String& p_signal) const; - void _set_bind(const String& p_set,const Variant& p_value); - Variant _get_bind(const String& p_name) const; + Array _get_signal_connection_list(const String &p_signal) const; + void _set_bind(const String &p_set, const Variant &p_value); + Variant _get_bind(const String &p_name) const; void property_list_changed_notify(); protected: - - virtual void _initialize_classv() { initialize_class(); } - virtual bool _setv(const StringName& p_name,const Variant &p_property) { return false; }; - virtual bool _getv(const StringName& p_name,Variant &r_property) const { return false; }; - virtual void _get_property_listv(List<PropertyInfo> *p_list,bool p_reversed) const {}; - virtual void _notificationv(int p_notification,bool p_reversed) {}; + virtual bool _setv(const StringName &p_name, const Variant &p_property) { return false; }; + virtual bool _getv(const StringName &p_name, Variant &r_property) const { return false; }; + virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const {}; + virtual void _notificationv(int p_notification, bool p_reversed){}; static String _get_category() { return ""; } static void _bind_methods(); - bool _set(const StringName& p_name,const Variant &p_property) { return false; }; - bool _get(const StringName& p_name,Variant &r_property) const { return false; }; + bool _set(const StringName &p_name, const Variant &p_property) { return false; }; + bool _get(const StringName &p_name, Variant &r_property) const { return false; }; void _get_property_list(List<PropertyInfo> *p_list) const {}; - void _notification(int p_notification) {}; + void _notification(int p_notification){}; _FORCE_INLINE_ static void (*_get_bind_methods())() { return &Object::_bind_methods; } - _FORCE_INLINE_ bool (Object::* (_get_get() const))(const StringName& p_name,Variant &r_ret) const { + _FORCE_INLINE_ bool (Object::*(_get_get() const))(const StringName &p_name, Variant &r_ret) const { return &Object::_get; } - _FORCE_INLINE_ bool (Object::* (_get_set() const))(const StringName& p_name,const Variant &p_property) { - return &Object::_set; + _FORCE_INLINE_ bool (Object::*(_get_set() const))(const StringName &p_name, const Variant &p_property) { + return &Object::_set; } - _FORCE_INLINE_ void (Object::* (_get_get_property_list() const))(List<PropertyInfo> *p_list) const{ - return &Object::_get_property_list; + _FORCE_INLINE_ void (Object::*(_get_get_property_list() const))(List<PropertyInfo> *p_list) const { + return &Object::_get_property_list; } - _FORCE_INLINE_ void (Object::* (_get_notification() const))(int){ - return &Object::_notification; + _FORCE_INLINE_ void (Object::*(_get_notification() const))(int) { + return &Object::_notification; } static void get_valid_parents_static(List<String> *p_parents); static void _get_valid_parents_static(List<String> *p_parents); - void cancel_delete(); - virtual void _changed_callback(Object *p_changed,const char *p_prop); + virtual void _changed_callback(Object *p_changed, const char *p_prop); //Variant _call_bind(const StringName& p_name, const Variant& p_arg1 = Variant(), const Variant& p_arg2 = Variant(), const Variant& p_arg3 = Variant(), const Variant& p_arg4 = Variant()); //void _call_deferred_bind(const StringName& p_name, const Variant& p_arg1 = Variant(), const Variant& p_arg2 = Variant(), const Variant& p_arg3 = Variant(), const Variant& p_arg4 = Variant()); - Variant _call_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error); - Variant _call_deferred_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error); - + Variant _call_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error); + Variant _call_deferred_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error); - virtual const StringName* _get_class_namev() const { + virtual const StringName *_get_class_namev() const { if (!_class_name) - _class_name=get_class_static(); + _class_name = get_class_static(); return &_class_name; } @@ -492,21 +500,24 @@ protected: void _clear_internal_resource_paths(const Variant &p_var); -friend class ClassDB; - virtual void _validate_property(PropertyInfo& property) const; + friend class ClassDB; + virtual void _validate_property(PropertyInfo &property) const; public: //should be protected, but bug in clang++ static void initialize_class(); - _FORCE_INLINE_ static void register_custom_data_to_otdb() {}; + _FORCE_INLINE_ static void register_custom_data_to_otdb(){}; public: - #ifdef TOOLS_ENABLED - _FORCE_INLINE_ void _change_notify(const char *p_property="") { _edited=true; for(Set<Object*>::Element *E=change_receptors.front();E;E=E->next()) ((Object*)(E->get()))->_changed_callback(this,p_property); } + _FORCE_INLINE_ void _change_notify(const char *p_property = "") { + _edited = true; + for (Set<Object *>::Element *E = change_receptors.front(); E; E = E->next()) + ((Object *)(E->get()))->_changed_callback(this, p_property); + } #else - _FORCE_INLINE_ void _change_notify(const char *p_what="") { } + _FORCE_INLINE_ void _change_notify(const char *p_what = "") {} #endif - static void* get_class_ptr_static() { + static void *get_class_ptr_static() { static int ptr; return &ptr; } @@ -516,34 +527,34 @@ public: _FORCE_INLINE_ ObjectID get_instance_ID() const { return _instance_ID; } // this is used for editors - void add_change_receptor( Object *p_receptor ); - void remove_change_receptor( Object *p_receptor ); + void add_change_receptor(Object *p_receptor); + void remove_change_receptor(Object *p_receptor); - template<class T> + template <class T> T *cast_to() { #ifndef NO_SAFE_CAST - return SAFE_CAST<T*>(this); + return SAFE_CAST<T *>(this); #else if (!this) return NULL; if (is_class_ptr(T::get_class_ptr_static())) - return static_cast<T*>(this); + return static_cast<T *>(this); else return NULL; #endif } - template<class T> + template <class T> const T *cast_to() const { #ifndef NO_SAFE_CAST - return SAFE_CAST<const T*>(this); + return SAFE_CAST<const T *>(this); #else if (!this) return NULL; if (is_class_ptr(T::get_class_ptr_static())) - return static_cast<const T*>(this); + return static_cast<const T *>(this); else return NULL; #endif @@ -551,27 +562,24 @@ public: enum { - NOTIFICATION_POSTINITIALIZE=0, - NOTIFICATION_PREDELETE=1 + NOTIFICATION_POSTINITIALIZE = 0, + NOTIFICATION_PREDELETE = 1 }; /* TYPE API */ - static void get_inheritance_list_static(List<String>* p_inheritance_list) { p_inheritance_list->push_back("Object"); } + static void get_inheritance_list_static(List<String> *p_inheritance_list) { p_inheritance_list->push_back("Object"); } static String get_class_static() { return "Object"; } static String get_parent_class_static() { return String(); } static String get_category_static() { return String(); } - virtual String get_class() const { return "Object"; } virtual String get_save_class() const { return get_class(); } //class stored when saving + virtual bool is_class(const String &p_class) const { return (p_class == "Object"); } + virtual bool is_class_ptr(void *p_ptr) const { return get_class_ptr_static() == p_ptr; } - - virtual bool is_class(const String& p_class) const { return (p_class=="Object"); } - virtual bool is_class_ptr(void *p_ptr) const { return get_class_ptr_static()==p_ptr; } - - _FORCE_INLINE_ const StringName& get_class_name() const { + _FORCE_INLINE_ const StringName &get_class_name() const { if (!_class_ptr) { return *_get_class_namev(); } else { @@ -583,36 +591,36 @@ public: //void set(const String& p_name, const Variant& p_value); //Variant get(const String& p_name) const; - void set(const StringName& p_name, const Variant& p_value, bool *r_valid=NULL); - Variant get(const StringName& p_name, bool *r_valid=NULL) const; + void set(const StringName &p_name, const Variant &p_value, bool *r_valid = NULL); + Variant get(const StringName &p_name, bool *r_valid = NULL) const; - void get_property_list(List<PropertyInfo> *p_list,bool p_reversed=false) const; + void get_property_list(List<PropertyInfo> *p_list, bool p_reversed = false) const; - bool has_method(const StringName& p_method) const; + bool has_method(const StringName &p_method) const; void get_method_list(List<MethodInfo> *p_list) const; - Variant callv(const StringName& p_method,const Array& p_args); - virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error); - virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); - virtual void call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount); - Variant call(const StringName& p_name, VARIANT_ARG_LIST); // C++ helper - void call_multilevel(const StringName& p_name, VARIANT_ARG_LIST); // C++ helper + Variant callv(const StringName &p_method, const Array &p_args); + virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); + virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount); + virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount); + Variant call(const StringName &p_name, VARIANT_ARG_LIST); // C++ helper + void call_multilevel(const StringName &p_name, VARIANT_ARG_LIST); // C++ helper - void notification(int p_notification,bool p_reversed=false); + void notification(int p_notification, bool p_reversed = false); //used mainly by script, get and set all INCLUDING string - virtual Variant getvar(const Variant& p_key, bool *r_valid=NULL) const; - virtual void setvar(const Variant& p_key, const Variant& p_value,bool *r_valid=NULL); + virtual Variant getvar(const Variant &p_key, bool *r_valid = NULL) const; + virtual void setvar(const Variant &p_key, const Variant &p_value, bool *r_valid = NULL); /* SCRIPT */ - void set_script(const RefPtr& p_script); + void set_script(const RefPtr &p_script); RefPtr get_script() const; /* SCRIPT */ - bool has_meta(const String& p_name) const; - void set_meta(const String& p_name, const Variant& p_value ); - Variant get_meta(const String& p_name) const; + bool has_meta(const String &p_name) const; + void set_meta(const String &p_name, const Variant &p_value); + Variant get_meta(const String &p_name) const; void get_meta_list(List<String> *p_list) const; #ifdef TOOLS_ENABLED @@ -622,50 +630,47 @@ public: #endif void set_script_instance(ScriptInstance *p_instance); - _FORCE_INLINE_ ScriptInstance* get_script_instance() const { return script_instance; } - + _FORCE_INLINE_ ScriptInstance *get_script_instance() const { return script_instance; } - void add_user_signal(const MethodInfo& p_signal); - void emit_signal(const StringName& p_name,VARIANT_ARG_LIST); - void emit_signal(const StringName& p_name, const Variant** p_args, int p_argcount); - void get_signal_list(List<MethodInfo> *p_signals ) const; - void get_signal_connection_list(const StringName& p_signal,List<Connection> *p_connections) const; + void add_user_signal(const MethodInfo &p_signal); + void emit_signal(const StringName &p_name, VARIANT_ARG_LIST); + void emit_signal(const StringName &p_name, const Variant **p_args, int p_argcount); + void get_signal_list(List<MethodInfo> *p_signals) const; + void get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const; void get_all_signal_connections(List<Connection> *p_connections) const; bool has_persistent_signal_connections() const; void get_signals_connected_to_this(List<Connection> *p_connections) const; - Error connect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method,const Vector<Variant>& p_binds=Vector<Variant>(),uint32_t p_flags=0); - void disconnect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method); - bool is_connected(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method) const; + Error connect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method, const Vector<Variant> &p_binds = Vector<Variant>(), uint32_t p_flags = 0); + void disconnect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method); + bool is_connected(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) const; - void call_deferred(const StringName& p_method,VARIANT_ARG_LIST); + void call_deferred(const StringName &p_method, VARIANT_ARG_LIST); void set_block_signals(bool p_block); bool is_blocking_signals() const; - Variant::Type get_static_property_type(const StringName& p_property,bool *r_valid=NULL) const; + Variant::Type get_static_property_type(const StringName &p_property, bool *r_valid = NULL) const; virtual void get_translatable_strings(List<String> *p_strings) const; - virtual void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const; + virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const; - StringName XL_MESSAGE(const StringName& p_message) const; //translate message (internationalization) - StringName tr(const StringName& p_message) const; //translate message (alternative) + StringName XL_MESSAGE(const StringName &p_message) const; //translate message (internationalization) + StringName tr(const StringName &p_message) const; //translate message (alternative) bool _is_queued_for_deletion; // set to true by SceneTree::queue_delete() bool is_queued_for_deletion() const; - _FORCE_INLINE_ void set_message_translation(bool p_enable) { _can_translate=p_enable; } + _FORCE_INLINE_ void set_message_translation(bool p_enable) { _can_translate = p_enable; } _FORCE_INLINE_ bool can_translate_messages() const { return _can_translate; } void clear_internal_resource_paths(); Object(); virtual ~Object(); - }; - bool predelete_handler(Object *p_object); void postinitialize_handler(Object *p_object); @@ -676,31 +681,29 @@ class ObjectDB { static _FORCE_INLINE_ uint32_t hash(const Object *p_obj) { union { - const Object*p; + const Object *p; unsigned long i; } u; - u.p=p_obj; + u.p = p_obj; return HashMapHasherDefault::hash((uint64_t)u.i); } }; - static HashMap<uint32_t,Object*> instances; - static HashMap<Object*,ObjectID,ObjectPtrHash> instance_checks; + static HashMap<uint32_t, Object *> instances; + static HashMap<Object *, ObjectID, ObjectPtrHash> instance_checks; static uint32_t instance_counter; -friend class Object; -friend void unregister_core_types(); - + friend class Object; + friend void unregister_core_types(); static RWLock *rw_lock; static void cleanup(); static uint32_t add_instance(Object *p_object); static void remove_instance(Object *p_object); -friend void register_core_types(); + friend void register_core_types(); static void setup(); public: - typedef void (*DebugFunc)(Object *p_obj); static Object *get_instance(uint32_t p_instance_ID); @@ -708,17 +711,14 @@ public: static int get_object_count(); #ifdef DEBUG_ENABLED - _FORCE_INLINE_ static bool instance_validate(Object* p_ptr) { + _FORCE_INLINE_ static bool instance_validate(Object *p_ptr) { return instance_checks.has(p_ptr); } #else - _FORCE_INLINE_ static bool instance_validate(Object* p_ptr) { return true; } + _FORCE_INLINE_ static bool instance_validate(Object *p_ptr) { return true; } #endif - - - }; //needed by macros diff --git a/core/os/copymem.h b/core/os/copymem.h index 0452b1a36c..9b13d6c731 100644 --- a/core/os/copymem.h +++ b/core/os/copymem.h @@ -39,7 +39,7 @@ #include <string.h> -#define copymem(to,from,count) memcpy(to,from,count) +#define copymem(to, from, count) memcpy(to, from, count) #define zeromem(to, count) memset(to, 0, count) #define movemem(to, from, count) memmove(to, from, count) diff --git a/core/os/dir_access.cpp b/core/os/dir_access.cpp index 974225a3e8..6f7255372f 100644 --- a/core/os/dir_access.cpp +++ b/core/os/dir_access.cpp @@ -27,15 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "dir_access.h" +#include "global_config.h" #include "os/file_access.h" #include "os/memory.h" #include "os/os.h" -#include "global_config.h" - String DirAccess::_get_root_path() const { - switch(_access_type) { + switch (_access_type) { case ACCESS_RESOURCES: return GlobalConfig::get_singleton()->get_resource_path(); case ACCESS_USERDATA: return OS::get_singleton()->get_data_dir(); @@ -46,7 +45,7 @@ String DirAccess::_get_root_path() const { } String DirAccess::_get_root_string() const { - switch(_access_type) { + switch (_access_type) { case ACCESS_RESOURCES: return "res://"; case ACCESS_USERDATA: return "user://"; @@ -59,7 +58,7 @@ String DirAccess::_get_root_string() const { int DirAccess::get_current_drive() { String path = get_current_dir().to_lower(); - for(int i=0;i<get_drive_count();i++) { + for (int i = 0; i < get_drive_count(); i++) { String d = get_drive(i).to_lower(); if (path.begins_with(d)) return i; @@ -75,9 +74,9 @@ static Error _erase_recursive(DirAccess *da) { da->list_dir_begin(); String n = da->get_next(); - while(n!=String()) { + while (n != String()) { - if (n!="." && n!="..") { + if (n != "." && n != "..") { if (da->current_is_dir()) dirs.push_back(n); @@ -85,43 +84,43 @@ static Error _erase_recursive(DirAccess *da) { files.push_back(n); } - n=da->get_next(); + n = da->get_next(); } da->list_dir_end(); - for(List<String>::Element *E=dirs.front();E;E=E->next()) { + for (List<String>::Element *E = dirs.front(); E; E = E->next()) { Error err = da->change_dir(E->get()); - if (err==OK) { + if (err == OK) { err = _erase_recursive(da); if (err) { - print_line("err recurso "+E->get()); + print_line("err recurso " + E->get()); return err; } err = da->change_dir(".."); if (err) { - print_line("no go back "+E->get()); + print_line("no go back " + E->get()); return err; } err = da->remove(da->get_current_dir().plus_file(E->get())); if (err) { - print_line("no remove dir"+E->get()); + print_line("no remove dir" + E->get()); return err; } } else { - print_line("no change to "+E->get()); + print_line("no change to " + E->get()); return err; } } - for(List<String>::Element *E=files.front();E;E=E->next()) { + for (List<String>::Element *E = files.front(); E; E = E->next()) { Error err = da->remove(da->get_current_dir().plus_file(E->get())); if (err) { - print_line("no remove file"+E->get()); + print_line("no remove file" + E->get()); return err; } } @@ -129,13 +128,11 @@ static Error _erase_recursive(DirAccess *da) { return OK; } - Error DirAccess::erase_contents_recursive() { return _erase_recursive(this); } - Error DirAccess::make_dir_recursive(String p_dir) { if (p_dir.length() < 1) { @@ -145,39 +142,39 @@ Error DirAccess::make_dir_recursive(String p_dir) { String full_dir; if (p_dir.is_rel_path()) { - //append current - full_dir=get_current_dir().plus_file(p_dir); + //append current + full_dir = get_current_dir().plus_file(p_dir); } else { - full_dir=p_dir; + full_dir = p_dir; } - full_dir=full_dir.replace("\\","/"); + full_dir = full_dir.replace("\\", "/"); //int slices = full_dir.get_slice_count("/"); String base; if (full_dir.begins_with("res://")) - base="res://"; + base = "res://"; else if (full_dir.begins_with("user://")) - base="user://"; + base = "user://"; else if (full_dir.begins_with("/")) - base="/"; - else if (full_dir.find(":/")!=-1) { - base=full_dir.substr(0,full_dir.find(":/")+2); + base = "/"; + else if (full_dir.find(":/") != -1) { + base = full_dir.substr(0, full_dir.find(":/") + 2); } else { ERR_FAIL_V(ERR_INVALID_PARAMETER); } - full_dir=full_dir.replace_first(base,"").simplify_path(); + full_dir = full_dir.replace_first(base, "").simplify_path(); - Vector<String> subdirs=full_dir.split("/"); + Vector<String> subdirs = full_dir.split("/"); - String curpath=base; - for(int i=0;i<subdirs.size();i++) { + String curpath = base; + for (int i = 0; i < subdirs.size(); i++) { - curpath=curpath.plus_file(subdirs[i]); + curpath = curpath.plus_file(subdirs[i]); Error err = make_dir(curpath); if (err != OK && err != ERR_ALREADY_EXISTS) { @@ -188,19 +185,17 @@ Error DirAccess::make_dir_recursive(String p_dir) { return OK; } +String DirAccess::get_next(bool *p_is_dir) { - -String DirAccess::get_next(bool* p_is_dir) { - - String next=get_next(); + String next = get_next(); if (p_is_dir) - *p_is_dir=current_is_dir(); + *p_is_dir = current_is_dir(); return next; } String DirAccess::fix_path(String p_path) const { - switch(_access_type) { + switch (_access_type) { case ACCESS_RESOURCES: { @@ -210,23 +205,21 @@ String DirAccess::fix_path(String p_path) const { String resource_path = GlobalConfig::get_singleton()->get_resource_path(); if (resource_path != "") { - return p_path.replace_first("res:/",resource_path); + return p_path.replace_first("res:/", resource_path); }; return p_path.replace_first("res://", ""); } } - } break; case ACCESS_USERDATA: { - if (p_path.begins_with("user://")) { - String data_dir=OS::get_singleton()->get_data_dir(); + String data_dir = OS::get_singleton()->get_data_dir(); if (data_dir != "") { - return p_path.replace_first("user:/",data_dir); + return p_path.replace_first("user:/", data_dir); }; return p_path.replace_first("user://", ""); } @@ -241,35 +234,34 @@ String DirAccess::fix_path(String p_path) const { return p_path; } +DirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX] = { 0, 0, 0 }; -DirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX]={0,0,0}; +DirAccess *DirAccess::create_for_path(const String &p_path) { -DirAccess *DirAccess::create_for_path(const String& p_path) { - - DirAccess *da=NULL; + DirAccess *da = NULL; if (p_path.begins_with("res://")) { - da=create(ACCESS_RESOURCES); + da = create(ACCESS_RESOURCES); } else if (p_path.begins_with("user://")) { - da=create(ACCESS_USERDATA); + da = create(ACCESS_USERDATA); } else { - da=create(ACCESS_FILESYSTEM); + da = create(ACCESS_FILESYSTEM); } return da; } -DirAccess *DirAccess::open(const String& p_path,Error *r_error) { +DirAccess *DirAccess::open(const String &p_path, Error *r_error) { - DirAccess *da=create_for_path(p_path); + DirAccess *da = create_for_path(p_path); - ERR_FAIL_COND_V(!da,NULL); + ERR_FAIL_COND_V(!da, NULL); Error err = da->change_dir(p_path); if (r_error) - *r_error=err; - if (err!=OK) { + *r_error = err; + if (err != OK) { memdelete(da); return NULL; } @@ -279,63 +271,61 @@ DirAccess *DirAccess::open(const String& p_path,Error *r_error) { DirAccess *DirAccess::create(AccessType p_access) { - DirAccess * da = create_func[p_access]?create_func[p_access]():NULL; + DirAccess *da = create_func[p_access] ? create_func[p_access]() : NULL; if (da) { - da->_access_type=p_access; + da->_access_type = p_access; } return da; }; +String DirAccess::get_full_path(const String &p_path, AccessType p_access) { -String DirAccess::get_full_path(const String& p_path,AccessType p_access) { - - DirAccess *d=DirAccess::create(p_access); + DirAccess *d = DirAccess::create(p_access); if (!d) return p_path; d->change_dir(p_path); - String full=d->get_current_dir(); + String full = d->get_current_dir(); memdelete(d); return full; } -Error DirAccess::copy(String p_from,String p_to) { +Error DirAccess::copy(String p_from, String p_to) { //printf("copy %s -> %s\n",p_from.ascii().get_data(),p_to.ascii().get_data()); Error err; - FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ,&err); + FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V( err, err ); + ERR_FAIL_COND_V(err, err); } - - FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE,&err ); + FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE, &err); if (err) { fsrc->close(); - memdelete( fsrc ); - ERR_FAIL_COND_V( err, err ); + memdelete(fsrc); + ERR_FAIL_COND_V(err, err); } fsrc->seek_end(0); int size = fsrc->get_pos(); fsrc->seek(0); err = OK; - while(size--) { + while (size--) { - if (fsrc->get_error()!=OK) { - err= fsrc->get_error(); + if (fsrc->get_error() != OK) { + err = fsrc->get_error(); break; } - if (fdst->get_error()!=OK) { - err= fdst->get_error(); + if (fdst->get_error() != OK) { + err = fdst->get_error(); break; } - fdst->store_8( fsrc->get_8() ); + fdst->store_8(fsrc->get_8()); } memdelete(fsrc); @@ -346,21 +336,16 @@ Error DirAccess::copy(String p_from,String p_to) { bool DirAccess::exists(String p_dir) { - DirAccess* da = DirAccess::create_for_path(p_dir); - bool valid = da->change_dir(p_dir)==OK; + DirAccess *da = DirAccess::create_for_path(p_dir); + bool valid = da->change_dir(p_dir) == OK; memdelete(da); return valid; - } -DirAccess::DirAccess(){ +DirAccess::DirAccess() { - _access_type=ACCESS_FILESYSTEM; + _access_type = ACCESS_FILESYSTEM; } - DirAccess::~DirAccess() { - } - - diff --git a/core/os/dir_access.h b/core/os/dir_access.h index 7c173fc780..1ac2d0e03a 100644 --- a/core/os/dir_access.h +++ b/core/os/dir_access.h @@ -29,7 +29,6 @@ #ifndef DIR_ACCESS_H #define DIR_ACCESS_H - #include "typedefs.h" #include "ustring.h" @@ -40,7 +39,6 @@ //@ TOOD, excellent candidate for THREAD_SAFE MACRO, should go through all these and add THREAD_SAFE where it applies class DirAccess { public: - enum AccessType { ACCESS_RESOURCES, ACCESS_USERDATA, @@ -48,13 +46,9 @@ public: ACCESS_MAX }; - - - typedef DirAccess*(*CreateFunc)(); + typedef DirAccess *(*CreateFunc)(); private: - - AccessType _access_type; static CreateFunc create_func[ACCESS_MAX]; ///< set this to instance a filesystem object protected: @@ -64,45 +58,44 @@ protected: String fix_path(String p_path) const; bool next_is_dir; - template<class T> - static DirAccess* _create_builtin() { + template <class T> + static DirAccess *_create_builtin() { - return memnew( T ); + return memnew(T); } public: + virtual Error list_dir_begin() = 0; ///< This starts dir listing + virtual String get_next(bool *p_is_dir); // compatibility + virtual String get_next() = 0; + virtual bool current_is_dir() const = 0; + virtual bool current_is_hidden() const = 0; - virtual Error list_dir_begin()=0; ///< This starts dir listing - virtual String get_next(bool* p_is_dir); // compatibility - virtual String get_next()=0; - virtual bool current_is_dir() const=0; - virtual bool current_is_hidden() const=0; - - virtual void list_dir_end()=0; ///< + virtual void list_dir_end() = 0; ///< - virtual int get_drive_count()=0; - virtual String get_drive(int p_drive)=0; + virtual int get_drive_count() = 0; + virtual String get_drive(int p_drive) = 0; virtual int get_current_drive(); - virtual Error change_dir(String p_dir)=0; ///< can be relative or absolute, return false on success - virtual String get_current_dir()=0; ///< return current dir location - virtual Error make_dir(String p_dir)=0; + virtual Error change_dir(String p_dir) = 0; ///< can be relative or absolute, return false on success + virtual String get_current_dir() = 0; ///< return current dir location + virtual Error make_dir(String p_dir) = 0; virtual Error make_dir_recursive(String p_dir); virtual Error erase_contents_recursive(); //super dangerous, use with care! - virtual bool file_exists(String p_file)=0; - virtual bool dir_exists(String p_dir)=0; + virtual bool file_exists(String p_file) = 0; + virtual bool dir_exists(String p_dir) = 0; static bool exists(String p_dir); - virtual size_t get_space_left()=0; + virtual size_t get_space_left() = 0; - virtual Error copy(String p_from,String p_to); - virtual Error rename(String p_from, String p_to)=0; - virtual Error remove(String p_name)=0; + virtual Error copy(String p_from, String p_to); + virtual Error rename(String p_from, String p_to) = 0; + virtual Error remove(String p_name) = 0; - static String get_full_path(const String& p_path,AccessType p_access); - static DirAccess *create_for_path(const String& p_path); + static String get_full_path(const String &p_path, AccessType p_access); + static DirAccess *create_for_path(const String &p_path); -/* + /* enum DirType { FILE_TYPE_INVALID, @@ -114,30 +107,31 @@ public: */ static DirAccess *create(AccessType p_access); - template<class T> + template <class T> static void make_default(AccessType p_access) { - create_func[p_access]=_create_builtin<T>; + create_func[p_access] = _create_builtin<T>; } - static DirAccess *open(const String& p_path,Error *r_error=NULL); + static DirAccess *open(const String &p_path, Error *r_error = NULL); DirAccess(); virtual ~DirAccess(); - }; struct DirAccessRef { - _FORCE_INLINE_ DirAccess* operator->() { + _FORCE_INLINE_ DirAccess *operator->() { return f; } - operator bool() const { return f!=NULL; } + operator bool() const { return f != NULL; } DirAccess *f; DirAccessRef(DirAccess *fa) { f = fa; } - ~DirAccessRef() { if (f) memdelete(f); } + ~DirAccessRef() { + if (f) memdelete(f); + } }; #endif diff --git a/core/os/file_access.cpp b/core/os/file_access.cpp index ae592720e8..3aac1f6f21 100644 --- a/core/os/file_access.cpp +++ b/core/os/file_access.cpp @@ -27,42 +27,39 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "file_access.h" -#include "global_config.h" -#include "os/os.h" +#include "core/io/file_access_pack.h" #include "core/io/marshalls.h" +#include "global_config.h" #include "io/md5.h" #include "io/sha256.h" -#include "core/io/file_access_pack.h" - -FileAccess::CreateFunc FileAccess::create_func[ACCESS_MAX]={0,0}; +#include "os/os.h" -FileAccess::FileCloseFailNotify FileAccess::close_fail_notify=NULL; +FileAccess::CreateFunc FileAccess::create_func[ACCESS_MAX] = { 0, 0 }; +FileAccess::FileCloseFailNotify FileAccess::close_fail_notify = NULL; -bool FileAccess::backup_save=false; +bool FileAccess::backup_save = false; -FileAccess *FileAccess::create(AccessType p_access){ +FileAccess *FileAccess::create(AccessType p_access) { - ERR_FAIL_COND_V( !create_func, 0 ); - ERR_FAIL_INDEX_V( p_access,ACCESS_MAX, 0 ); + ERR_FAIL_COND_V(!create_func, 0); + ERR_FAIL_INDEX_V(p_access, ACCESS_MAX, 0); FileAccess *ret = create_func[p_access](); ret->_set_access_type(p_access); return ret; } -bool FileAccess::exists(const String& p_name) { +bool FileAccess::exists(const String &p_name) { if (PackedData::get_singleton()->has_path(p_name)) return true; - FileAccess *f=open(p_name,READ); + FileAccess *f = open(p_name, READ); if (!f) return false; memdelete(f); return true; - - } void FileAccess::_set_access_type(AccessType p_access) { @@ -70,9 +67,9 @@ void FileAccess::_set_access_type(AccessType p_access) { _access_type = p_access; }; -FileAccess *FileAccess::create_for_path(const String& p_path) { +FileAccess *FileAccess::create_for_path(const String &p_path) { - FileAccess *ret=NULL; + FileAccess *ret = NULL; if (p_path.begins_with("res://")) { ret = create(ACCESS_RESOURCES); @@ -86,56 +83,52 @@ FileAccess *FileAccess::create_for_path(const String& p_path) { } return ret; - - } -Error FileAccess::reopen(const String& p_path, int p_mode_flags) { +Error FileAccess::reopen(const String &p_path, int p_mode_flags) { return _open(p_path, p_mode_flags); }; - -FileAccess *FileAccess::open(const String& p_path, int p_mode_flags, Error *r_error) { +FileAccess *FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) { //try packed data first - FileAccess *ret=NULL; - if (!(p_mode_flags&WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) { + FileAccess *ret = NULL; + if (!(p_mode_flags & WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) { ret = PackedData::get_singleton()->try_open_path(p_path); if (ret) { if (r_error) - *r_error=OK; + *r_error = OK; return ret; } } - ret=create_for_path(p_path); - Error err = ret->_open(p_path,p_mode_flags); + ret = create_for_path(p_path); + Error err = ret->_open(p_path, p_mode_flags); if (r_error) - *r_error=err; - if (err!=OK) { + *r_error = err; + if (err != OK) { memdelete(ret); - ret=NULL; + ret = NULL; } return ret; } - FileAccess::CreateFunc FileAccess::get_create_func(AccessType p_access) { return create_func[p_access]; }; -String FileAccess::fix_path(const String& p_path) const { +String FileAccess::fix_path(const String &p_path) const { //helper used by file accesses that use a single filesystem String r_path = p_path.replace("\\", "/"); - switch(_access_type) { + switch (_access_type) { case ACCESS_RESOURCES: { @@ -145,23 +138,21 @@ String FileAccess::fix_path(const String& p_path) const { String resource_path = GlobalConfig::get_singleton()->get_resource_path(); if (resource_path != "") { - return r_path.replace("res:/",resource_path); + return r_path.replace("res:/", resource_path); }; return r_path.replace("res://", ""); } } - } break; case ACCESS_USERDATA: { - if (r_path.begins_with("user://")) { - String data_dir=OS::get_singleton()->get_data_dir(); + String data_dir = OS::get_singleton()->get_data_dir(); if (data_dir != "") { - return r_path.replace("user:/",data_dir); + return r_path.replace("user:/", data_dir); }; return r_path.replace("user://", ""); } @@ -178,63 +169,62 @@ String FileAccess::fix_path(const String& p_path) const { /* these are all implemented for ease of porting, then can later be optimized */ -uint16_t FileAccess::get_16()const { +uint16_t FileAccess::get_16() const { uint16_t res; - uint8_t a,b; + uint8_t a, b; - a=get_8(); - b=get_8(); + a = get_8(); + b = get_8(); if (endian_swap) { - SWAP( a,b ); + SWAP(a, b); } - res=b; - res<<=8; - res|=a; + res = b; + res <<= 8; + res |= a; return res; } -uint32_t FileAccess::get_32() const{ +uint32_t FileAccess::get_32() const { uint32_t res; - uint16_t a,b; + uint16_t a, b; - a=get_16(); - b=get_16(); + a = get_16(); + b = get_16(); if (endian_swap) { - SWAP( a,b ); + SWAP(a, b); } - res=b; - res<<=16; - res|=a; + res = b; + res <<= 16; + res |= a; return res; } -uint64_t FileAccess::get_64()const { +uint64_t FileAccess::get_64() const { uint64_t res; - uint32_t a,b; + uint32_t a, b; - a=get_32(); - b=get_32(); + a = get_32(); + b = get_32(); if (endian_swap) { - SWAP( a,b ); + SWAP(a, b); } - res=b; - res<<=32; - res|=a; + res = b; + res <<= 32; + res |= a; return res; - } float FileAccess::get_float() const { @@ -250,7 +240,6 @@ real_t FileAccess::get_real() const { return get_double(); else return get_float(); - } double FileAccess::get_double() const { @@ -264,17 +253,17 @@ String FileAccess::get_line() const { CharString line; - CharType c=get_8(); + CharType c = get_8(); - while(!eof_reached()) { + while (!eof_reached()) { - if (c=='\n' || c=='\0') { + if (c == '\n' || c == '\0') { line.push_back(0); return String::utf8(line.get_data()); - } else if (c!='\r') + } else if (c != '\r') line.push_back(c); - c=get_8(); + c = get_8(); } line.push_back(0); return String::utf8(line.get_data()); @@ -282,51 +271,48 @@ String FileAccess::get_line() const { Vector<String> FileAccess::get_csv_line(String delim) const { - ERR_FAIL_COND_V(delim.length()!=1,Vector<String>()); + ERR_FAIL_COND_V(delim.length() != 1, Vector<String>()); String l; - int qc=0; + int qc = 0; do { - l+=get_line()+"\n"; - qc=0; - for(int i=0;i<l.length();i++) { + l += get_line() + "\n"; + qc = 0; + for (int i = 0; i < l.length(); i++) { - if (l[i]=='"') + if (l[i] == '"') qc++; } + } while (qc % 2); - } while (qc%2); - - l=l.substr(0, l.length()-1); + l = l.substr(0, l.length() - 1); Vector<String> strings; - bool in_quote=false; + bool in_quote = false; String current; - for(int i=0;i<l.length();i++) { + for (int i = 0; i < l.length(); i++) { CharType c = l[i]; - CharType s[2]={0,0}; - + CharType s[2] = { 0, 0 }; - if (!in_quote && c==delim[0]) { + if (!in_quote && c == delim[0]) { strings.push_back(current); - current=String(); - } else if (c=='"') { - if (l[i+1]=='"') { - s[0]='"'; - current+=s; + current = String(); + } else if (c == '"') { + if (l[i + 1] == '"') { + s[0] = '"'; + current += s; i++; } else { - in_quote=!in_quote; + in_quote = !in_quote; } } else { - s[0]=c; - current+=s; + s[0] = c; + current += s; } - } strings.push_back(current); @@ -334,73 +320,67 @@ Vector<String> FileAccess::get_csv_line(String delim) const { return strings; } +int FileAccess::get_buffer(uint8_t *p_dst, int p_length) const { -int FileAccess::get_buffer(uint8_t *p_dst,int p_length) const{ - - int i=0; - for (i=0; i<p_length && !eof_reached(); i++) - p_dst[i]=get_8(); + int i = 0; + for (i = 0; i < p_length && !eof_reached(); i++) + p_dst[i] = get_8(); return i; } void FileAccess::store_16(uint16_t p_dest) { - uint8_t a,b; + uint8_t a, b; - a=p_dest&0xFF; - b=p_dest>>8; + a = p_dest & 0xFF; + b = p_dest >> 8; if (endian_swap) { - SWAP( a,b ); + SWAP(a, b); } store_8(a); store_8(b); - } void FileAccess::store_32(uint32_t p_dest) { + uint16_t a, b; - uint16_t a,b; - - a=p_dest&0xFFFF; - b=p_dest>>16; + a = p_dest & 0xFFFF; + b = p_dest >> 16; if (endian_swap) { - SWAP( a,b ); + SWAP(a, b); } store_16(a); store_16(b); - } void FileAccess::store_64(uint64_t p_dest) { - uint32_t a,b; + uint32_t a, b; - a=p_dest&0xFFFFFFFF; - b=p_dest>>32; + a = p_dest & 0xFFFFFFFF; + b = p_dest >> 32; if (endian_swap) { - SWAP( a,b ); + SWAP(a, b); } store_32(a); store_32(b); - } void FileAccess::store_real(real_t p_real) { - if (sizeof(real_t)==4) + if (sizeof(real_t) == 4) store_float(p_real); else store_double(p_real); - } void FileAccess::store_float(float p_dest) { @@ -417,40 +397,39 @@ void FileAccess::store_double(double p_dest) { store_64(m.l); }; -uint64_t FileAccess::get_modified_time(const String& p_file) { +uint64_t FileAccess::get_modified_time(const String &p_file) { FileAccess *fa = create_for_path(p_file); - ERR_FAIL_COND_V(!fa,0); + ERR_FAIL_COND_V(!fa, 0); uint64_t mt = fa->_get_modified_time(p_file); memdelete(fa); return mt; } -void FileAccess::store_string(const String& p_string) { +void FileAccess::store_string(const String &p_string) { - if (p_string.length()==0) + if (p_string.length() == 0) return; - CharString cs=p_string.utf8(); - store_buffer((uint8_t*)&cs[0],cs.length()); - + CharString cs = p_string.utf8(); + store_buffer((uint8_t *)&cs[0], cs.length()); } -void FileAccess::store_pascal_string(const String& p_string) { +void FileAccess::store_pascal_string(const String &p_string) { CharString cs = p_string.utf8(); store_32(cs.length()); - store_buffer((uint8_t*)&cs[0], cs.length()); + store_buffer((uint8_t *)&cs[0], cs.length()); }; String FileAccess::get_pascal_string() { uint32_t sl = get_32(); CharString cs; - cs.resize(sl+1); - get_buffer((uint8_t*)cs.ptr(),sl); - cs[sl]=0; + cs.resize(sl + 1); + get_buffer((uint8_t *)cs.ptr(), sl); + cs[sl] = 0; String ret; ret.parse_utf8(cs.ptr()); @@ -458,35 +437,32 @@ String FileAccess::get_pascal_string() { return ret; }; - -void FileAccess::store_line(const String& p_line) { +void FileAccess::store_line(const String &p_line) { store_string(p_line); store_8('\n'); } -void FileAccess::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccess::store_buffer(const uint8_t *p_src, int p_length) { - for (int i=0;i<p_length;i++) + for (int i = 0; i < p_length; i++) store_8(p_src[i]); } -Vector<uint8_t> FileAccess::get_file_as_array(const String& p_file) { +Vector<uint8_t> FileAccess::get_file_as_array(const String &p_file) { - FileAccess *f=FileAccess::open(p_file,READ); - ERR_FAIL_COND_V(!f,Vector<uint8_t>()); + FileAccess *f = FileAccess::open(p_file, READ); + ERR_FAIL_COND_V(!f, Vector<uint8_t>()); Vector<uint8_t> data; data.resize(f->get_len()); - f->get_buffer(data.ptr(),data.size()); + f->get_buffer(data.ptr(), data.size()); memdelete(f); return data; - - } -String FileAccess::get_md5(const String& p_file) { +String FileAccess::get_md5(const String &p_file) { - FileAccess *f=FileAccess::open(p_file,READ); + FileAccess *f = FileAccess::open(p_file, READ); if (!f) return String(); @@ -495,32 +471,28 @@ String FileAccess::get_md5(const String& p_file) { unsigned char step[32768]; - while(true) { + while (true) { - int br = f->get_buffer(step,32768); - if (br>0) { + int br = f->get_buffer(step, 32768); + if (br > 0) { - MD5Update(&md5,step,br); + MD5Update(&md5, step, br); } if (br < 4096) break; - } MD5Final(&md5); String ret = String::md5(md5.digest); - - memdelete(f); return ret; - } -String FileAccess::get_sha256(const String& p_file) { +String FileAccess::get_sha256(const String &p_file) { - FileAccess *f=FileAccess::open(p_file,READ); + FileAccess *f = FileAccess::open(p_file, READ); if (!f) return String(); @@ -529,16 +501,15 @@ String FileAccess::get_sha256(const String& p_file) { unsigned char step[32768]; - while(true) { + while (true) { - int br = f->get_buffer(step,32768); - if (br>0) { + int br = f->get_buffer(step, 32768); + if (br > 0) { - sha256_hash(&sha256,step,br); + sha256_hash(&sha256, step, br); } if (br < 4096) break; - } unsigned char hash[32]; @@ -547,12 +518,11 @@ String FileAccess::get_sha256(const String& p_file) { memdelete(f); return String::hex_encode_buffer(hash, 32); - } FileAccess::FileAccess() { - endian_swap=false; - real_is_double=false; - _access_type=ACCESS_FILESYSTEM; + endian_swap = false; + real_is_double = false; + _access_type = ACCESS_FILESYSTEM; }; diff --git a/core/os/file_access.h b/core/os/file_access.h index 7d61099bc2..10d3ffebbb 100644 --- a/core/os/file_access.h +++ b/core/os/file_access.h @@ -29,10 +29,10 @@ #ifndef FILE_ACCESS_H #define FILE_ACCESS_H +#include "math_defs.h" +#include "os/memory.h" #include "typedefs.h" #include "ustring.h" -#include "os/memory.h" -#include "math_defs.h" /** * Multi-Platform abstraction for accessing to files. */ @@ -47,57 +47,54 @@ public: ACCESS_MAX }; - typedef void (*FileCloseFailNotify)(const String&); + typedef void (*FileCloseFailNotify)(const String &); - typedef FileAccess*(*CreateFunc)(); + typedef FileAccess *(*CreateFunc)(); bool endian_swap; bool real_is_double; -protected: - String fix_path(const String& p_path) const; - virtual Error _open(const String& p_path, int p_mode_flags)=0; ///< open a file - virtual uint64_t _get_modified_time(const String& p_file)=0; +protected: + String fix_path(const String &p_path) const; + virtual Error _open(const String &p_path, int p_mode_flags) = 0; ///< open a file + virtual uint64_t _get_modified_time(const String &p_file) = 0; static FileCloseFailNotify close_fail_notify; -private: +private: static bool backup_save; AccessType _access_type; static CreateFunc create_func[ACCESS_MAX]; /** default file access creation function for a platform */ - template<class T> - static FileAccess* _create_builtin() { + template <class T> + static FileAccess *_create_builtin() { - return memnew( T ); + return memnew(T); } - - public: - - static void set_file_close_fail_notify_callback(FileCloseFailNotify p_cbk) { close_fail_notify=p_cbk; } + static void set_file_close_fail_notify_callback(FileCloseFailNotify p_cbk) { close_fail_notify = p_cbk; } virtual void _set_access_type(AccessType p_access); - enum ModeFlags { + enum ModeFlags { - READ=1, - WRITE=2, - READ_WRITE=3, - WRITE_READ=7, + READ = 1, + WRITE = 2, + READ_WRITE = 3, + WRITE_READ = 7, }; - virtual void close()=0; ///< close a file - virtual bool is_open() const=0; ///< true when file is open + virtual void close() = 0; ///< close a file + virtual bool is_open() const = 0; ///< true when file is open - virtual void seek(size_t p_position)=0; ///< seek to a given position - virtual void seek_end(int64_t p_position=0)=0; ///< seek from the end of file - virtual size_t get_pos() const=0; ///< get position in the file - virtual size_t get_len() const=0; ///< get size of the file + virtual void seek(size_t p_position) = 0; ///< seek to a given position + virtual void seek_end(int64_t p_position = 0) = 0; ///< seek from the end of file + virtual size_t get_pos() const = 0; ///< get position in the file + virtual size_t get_len() const = 0; ///< get size of the file - virtual bool eof_reached() const=0; ///< reading passed EOF + virtual bool eof_reached() const = 0; ///< reading passed EOF - virtual uint8_t get_8() const=0; ///< get a byte + virtual uint8_t get_8() const = 0; ///< get a byte virtual uint16_t get_16() const; ///< get 16 bits uint virtual uint32_t get_32() const; ///< get 32 bits uint virtual uint64_t get_64() const; ///< get 64 bits uint @@ -106,21 +103,21 @@ public: virtual double get_double() const; virtual real_t get_real() 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 String get_line() const; - virtual Vector<String> get_csv_line(String delim=",") const; + virtual Vector<String> get_csv_line(String delim = ",") const; /**< use this for files WRITTEN in _big_ endian machines (ie, amiga/mac) * It's not about the current CPU type but file formats. * this flags get reset to false (little endian) on each open */ - virtual void set_endian_swap(bool p_swap) { endian_swap=p_swap; } + virtual void set_endian_swap(bool p_swap) { endian_swap = p_swap; } inline bool get_endian_swap() const { return endian_swap; } - virtual Error get_error() const=0; ///< get last error + virtual Error get_error() const = 0; ///< get last error - virtual void store_8(uint8_t p_dest)=0; ///< store a byte + virtual void store_8(uint8_t p_dest) = 0; ///< store a byte virtual void store_16(uint16_t p_dest); ///< store 16 bits uint virtual void store_32(uint32_t p_dest); ///< store 32 bits uint virtual void store_64(uint64_t p_dest); ///< store 64 bits uint @@ -129,58 +126,56 @@ public: virtual void store_double(double p_dest); virtual void store_real(real_t p_real); - virtual void store_string(const String& p_string); - virtual void store_line(const String& p_string); + virtual void store_string(const String &p_string); + virtual 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(); - 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)=0; ///< return true if a file exists + virtual bool file_exists(const String &p_name) = 0; ///< return true if a file exists - virtual Error reopen(const String& p_path, int p_mode_flags); ///< does not change the AccessType + virtual Error reopen(const String &p_path, int p_mode_flags); ///< does not change the AccessType static FileAccess *create(AccessType p_access); /// Create a file access (for the current platform) this is the only portable way of accessing files. - static FileAccess *create_for_path(const String& p_path); - static FileAccess *open(const String& p_path, int p_mode_flags, Error *r_error=NULL); /// Create a file access (for the current platform) this is the only portable way of accessing files. + static FileAccess *create_for_path(const String &p_path); + static FileAccess *open(const String &p_path, int p_mode_flags, Error *r_error = NULL); /// Create a file access (for the current platform) this is the only portable way of accessing files. static CreateFunc get_create_func(AccessType p_access); - static bool exists(const String& p_name); ///< return true if a file exists - static uint64_t get_modified_time(const String& p_file); - + static bool exists(const String &p_name); ///< return true if a file exists + static uint64_t get_modified_time(const String &p_file); - static void set_backup_save(bool p_enable) { backup_save=p_enable; }; + static void set_backup_save(bool p_enable) { backup_save = p_enable; }; static bool is_backup_save_enabled() { return backup_save; }; - static String get_md5(const String& p_file); - static String get_sha256(const String& p_file); + static String get_md5(const String &p_file); + static String get_sha256(const String &p_file); - static Vector<uint8_t> get_file_as_array(const String& p_path); + static Vector<uint8_t> get_file_as_array(const String &p_path); - - template<class T> + template <class T> static void make_default(AccessType p_access) { - create_func[p_access]=_create_builtin<T>; + create_func[p_access] = _create_builtin<T>; } FileAccess(); - virtual ~FileAccess(){} - + virtual ~FileAccess() {} }; - struct FileAccessRef { - _FORCE_INLINE_ FileAccess* operator->() { + _FORCE_INLINE_ FileAccess *operator->() { return f; } - operator bool() const { return f!=NULL; } + operator bool() const { return f != NULL; } FileAccess *f; FileAccessRef(FileAccess *fa) { f = fa; } - ~FileAccessRef() { if (f) memdelete(f); } + ~FileAccessRef() { + if (f) memdelete(f); + } }; #endif diff --git a/core/os/input.cpp b/core/os/input.cpp index 34883e63ba..63efbe4d11 100644 --- a/core/os/input.cpp +++ b/core/os/input.cpp @@ -27,10 +27,10 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "input.h" +#include "global_config.h" #include "input_map.h" #include "os/os.h" -#include "global_config.h" -Input *Input::singleton=NULL; +Input *Input::singleton = NULL; Input *Input::get_singleton() { @@ -38,7 +38,7 @@ Input *Input::get_singleton() { } void Input::set_mouse_mode(MouseMode p_mode) { - ERR_FAIL_INDEX(p_mode,4); + ERR_FAIL_INDEX(p_mode, 4); OS::get_singleton()->set_mouse_mode((OS::MouseMode)p_mode); } @@ -49,19 +49,19 @@ Input::MouseMode Input::get_mouse_mode() const { void Input::_bind_methods() { - ClassDB::bind_method(D_METHOD("is_key_pressed","scancode"),&Input::is_key_pressed); - ClassDB::bind_method(D_METHOD("is_mouse_button_pressed","button"),&Input::is_mouse_button_pressed); - ClassDB::bind_method(D_METHOD("is_joy_button_pressed","device","button"),&Input::is_joy_button_pressed); - ClassDB::bind_method(D_METHOD("is_action_pressed","action"),&Input::is_action_pressed); - ClassDB::bind_method(D_METHOD("is_action_just_pressed","action"),&Input::is_action_just_pressed); - ClassDB::bind_method(D_METHOD("is_action_just_released","action"),&Input::is_action_just_released); - ClassDB::bind_method(D_METHOD("add_joy_mapping","mapping", "update_existing"),&Input::add_joy_mapping, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("remove_joy_mapping","guid"),&Input::remove_joy_mapping); - ClassDB::bind_method(D_METHOD("is_joy_known","device"),&Input::is_joy_known); - ClassDB::bind_method(D_METHOD("get_joy_axis","device","axis"),&Input::get_joy_axis); - ClassDB::bind_method(D_METHOD("get_joy_name","device"),&Input::get_joy_name); - ClassDB::bind_method(D_METHOD("get_joy_guid","device"),&Input::get_joy_guid); - ClassDB::bind_method(D_METHOD("get_connected_joypads"),&Input::get_connected_joypads); + ClassDB::bind_method(D_METHOD("is_key_pressed", "scancode"), &Input::is_key_pressed); + ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed); + ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed); + ClassDB::bind_method(D_METHOD("is_action_pressed", "action"), &Input::is_action_pressed); + ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action"), &Input::is_action_just_pressed); + ClassDB::bind_method(D_METHOD("is_action_just_released", "action"), &Input::is_action_just_released); + ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping); + ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known); + ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis); + ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name); + ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid); + ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads); ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength); ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration); ClassDB::bind_method(D_METHOD("get_joy_button_string", "button_index"), &Input::get_joy_button_string); @@ -70,57 +70,53 @@ void Input::_bind_methods() { ClassDB::bind_method(D_METHOD("get_joy_axis_index_from_string", "axis"), &Input::get_joy_axis_index_from_string); ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0)); ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration); - ClassDB::bind_method(D_METHOD("get_gravity"),&Input::get_gravity); - ClassDB::bind_method(D_METHOD("get_accelerometer"),&Input::get_accelerometer); - ClassDB::bind_method(D_METHOD("get_magnetometer"),&Input::get_magnetometer); - ClassDB::bind_method(D_METHOD("get_gyroscope"),&Input::get_gyroscope); + ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity); + ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer); + ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer); + ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope); //ClassDB::bind_method(D_METHOD("get_mouse_pos"),&Input::get_mouse_pos); - this is not the function you want - ClassDB::bind_method(D_METHOD("get_last_mouse_speed"),&Input::get_last_mouse_speed); - ClassDB::bind_method(D_METHOD("get_mouse_button_mask"),&Input::get_mouse_button_mask); - ClassDB::bind_method(D_METHOD("set_mouse_mode","mode"),&Input::set_mouse_mode); - ClassDB::bind_method(D_METHOD("get_mouse_mode"),&Input::get_mouse_mode); - ClassDB::bind_method(D_METHOD("warp_mouse_pos","to"),&Input::warp_mouse_pos); - ClassDB::bind_method(D_METHOD("action_press","action"),&Input::action_press); - ClassDB::bind_method(D_METHOD("action_release","action"),&Input::action_release); - ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor","image:Texture","hotspot"),&Input::set_custom_mouse_cursor,DEFVAL(Vector2())); - - BIND_CONSTANT( MOUSE_MODE_VISIBLE ); - BIND_CONSTANT( MOUSE_MODE_HIDDEN ); - BIND_CONSTANT( MOUSE_MODE_CAPTURED ); - BIND_CONSTANT( MOUSE_MODE_CONFINED ); - - ADD_SIGNAL( MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "connected")) ); + ClassDB::bind_method(D_METHOD("get_last_mouse_speed"), &Input::get_last_mouse_speed); + ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask); + ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode); + ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode); + ClassDB::bind_method(D_METHOD("warp_mouse_pos", "to"), &Input::warp_mouse_pos); + ClassDB::bind_method(D_METHOD("action_press", "action"), &Input::action_press); + ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release); + ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image:Texture", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(Vector2())); + + BIND_CONSTANT(MOUSE_MODE_VISIBLE); + BIND_CONSTANT(MOUSE_MODE_HIDDEN); + BIND_CONSTANT(MOUSE_MODE_CAPTURED); + BIND_CONSTANT(MOUSE_MODE_CONFINED); + + ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "connected"))); } -void Input::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const { +void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { #ifdef TOOLS_ENABLED - String pf=p_function; - if (p_idx==0 && (pf=="is_action_pressed" || pf=="action_press" || pf=="action_release" || pf=="is_action_just_pressed" || pf=="is_action_just_released")) { + String pf = p_function; + if (p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" || pf == "is_action_just_pressed" || pf == "is_action_just_released")) { List<PropertyInfo> pinfo; GlobalConfig::get_singleton()->get_property_list(&pinfo); - for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { - const PropertyInfo &pi=E->get(); + for (List<PropertyInfo>::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()); - r_options->push_back("\""+name+"\""); - + String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length()); + r_options->push_back("\"" + name + "\""); } } #endif - } Input::Input() { - singleton=this; + singleton = this; } - ////////////////////////////////////////////////////////// - diff --git a/core/os/input.h b/core/os/input.h index 2cea154a50..86755e632c 100644 --- a/core/os/input.h +++ b/core/os/input.h @@ -30,20 +30,19 @@ #define INPUT_H #include "object.h" -#include "os/thread_safe.h" #include "os/main_loop.h" +#include "os/thread_safe.h" class Input : public Object { - GDCLASS( Input, Object ); + GDCLASS(Input, Object); static Input *singleton; protected: - static void _bind_methods(); -public: +public: enum MouseMode { MOUSE_MODE_VISIBLE, MOUSE_MODE_HIDDEN, @@ -56,57 +55,56 @@ public: static Input *get_singleton(); - virtual bool is_key_pressed(int p_scancode) const=0; - virtual bool is_mouse_button_pressed(int p_button) const=0; - virtual bool is_joy_button_pressed(int p_device, int p_button) const=0; - virtual bool is_action_pressed(const StringName& p_action) const=0; - virtual bool is_action_just_pressed(const StringName& p_action) const=0; - virtual bool is_action_just_released(const StringName& p_action) const=0; - - virtual float get_joy_axis(int p_device,int p_axis) const=0; - virtual String get_joy_name(int p_idx)=0; - virtual Array get_connected_joypads()=0; - virtual void joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid)=0; - virtual void add_joy_mapping(String p_mapping, bool p_update_existing=false)=0; - virtual void remove_joy_mapping(String p_guid)=0; - virtual bool is_joy_known(int p_device)=0; - virtual String get_joy_guid(int p_device) const=0; - virtual Vector2 get_joy_vibration_strength(int p_device)=0; - virtual float get_joy_vibration_duration(int p_device)=0; - virtual uint64_t get_joy_vibration_timestamp(int p_device)=0; - virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration=0)=0; - virtual void stop_joy_vibration(int p_device)=0; - - virtual Point2 get_mouse_pos() const=0; - virtual Point2 get_last_mouse_speed() const=0; - virtual int get_mouse_button_mask() const=0; - - virtual void warp_mouse_pos(const Vector2& p_to)=0; - - virtual Vector3 get_gravity() const=0; - virtual Vector3 get_accelerometer() const=0; - virtual Vector3 get_magnetometer() const=0; - virtual Vector3 get_gyroscope() const=0; - - virtual void action_press(const StringName& p_action)=0; - virtual void action_release(const StringName& p_action)=0; - - void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const; - - virtual bool is_emulating_touchscreen() const=0; - - virtual void set_custom_mouse_cursor(const RES& p_cursor,const Vector2& p_hotspot=Vector2())=0; - virtual void set_mouse_in_window(bool p_in_window)=0; - - virtual String get_joy_button_string(int p_button)=0; - virtual String get_joy_axis_string(int p_axis)=0; - virtual int get_joy_button_index_from_string(String p_button)=0; - virtual int get_joy_axis_index_from_string(String p_axis)=0; + virtual bool is_key_pressed(int p_scancode) const = 0; + virtual bool is_mouse_button_pressed(int p_button) const = 0; + virtual bool is_joy_button_pressed(int p_device, int p_button) const = 0; + virtual bool is_action_pressed(const StringName &p_action) const = 0; + virtual bool is_action_just_pressed(const StringName &p_action) const = 0; + virtual bool is_action_just_released(const StringName &p_action) const = 0; + + virtual float get_joy_axis(int p_device, int p_axis) const = 0; + virtual String get_joy_name(int p_idx) = 0; + virtual Array get_connected_joypads() = 0; + virtual void joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) = 0; + virtual void add_joy_mapping(String p_mapping, bool p_update_existing = false) = 0; + virtual void remove_joy_mapping(String p_guid) = 0; + virtual bool is_joy_known(int p_device) = 0; + virtual String get_joy_guid(int p_device) const = 0; + virtual Vector2 get_joy_vibration_strength(int p_device) = 0; + virtual float get_joy_vibration_duration(int p_device) = 0; + virtual uint64_t get_joy_vibration_timestamp(int p_device) = 0; + virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration = 0) = 0; + virtual void stop_joy_vibration(int p_device) = 0; + + virtual Point2 get_mouse_pos() const = 0; + virtual Point2 get_last_mouse_speed() const = 0; + virtual int get_mouse_button_mask() const = 0; + + virtual void warp_mouse_pos(const Vector2 &p_to) = 0; + + virtual Vector3 get_gravity() const = 0; + virtual Vector3 get_accelerometer() const = 0; + virtual Vector3 get_magnetometer() const = 0; + virtual Vector3 get_gyroscope() const = 0; + + virtual void action_press(const StringName &p_action) = 0; + virtual void action_release(const StringName &p_action) = 0; + + void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const; + + virtual bool is_emulating_touchscreen() const = 0; + + virtual void set_custom_mouse_cursor(const RES &p_cursor, const Vector2 &p_hotspot = Vector2()) = 0; + virtual void set_mouse_in_window(bool p_in_window) = 0; + + virtual String get_joy_button_string(int p_button) = 0; + virtual String get_joy_axis_string(int p_axis) = 0; + virtual int get_joy_button_index_from_string(String p_button) = 0; + virtual int get_joy_axis_index_from_string(String p_axis) = 0; Input(); }; VARIANT_ENUM_CAST(Input::MouseMode); - #endif // INPUT_H diff --git a/core/os/input_event.cpp b/core/os/input_event.cpp index 4ef99558ad..ebb1f4ed01 100644 --- a/core/os/input_event.cpp +++ b/core/os/input_event.cpp @@ -34,11 +34,11 @@ */ bool InputEvent::operator==(const InputEvent &p_event) const { - if (type != p_event.type){ + if (type != p_event.type) { return false; } - switch(type) { + switch (type) { /** Current clang-format style doesn't play well with the aligned return values of that switch. */ /* clang-format off */ case NONE: @@ -91,9 +91,9 @@ bool InputEvent::operator==(const InputEvent &p_event) const { } InputEvent::operator String() const { - String str="Device "+itos(device)+" ID "+itos(ID)+" "; + String str = "Device " + itos(device) + " ID " + itos(ID) + " "; - switch(type) { + switch (type) { case NONE: { @@ -101,108 +101,107 @@ InputEvent::operator String() const { } break; case KEY: { - str+= "Event: Key "; - str=str+"Unicode: "+String::chr(key.unicode)+" Scan: "+itos( key.scancode )+" Echo: "+String(key.echo?"True":"False")+" Pressed"+String(key.pressed?"True":"False")+" Mod: "; + str += "Event: Key "; + str = str + "Unicode: " + String::chr(key.unicode) + " Scan: " + itos(key.scancode) + " Echo: " + String(key.echo ? "True" : "False") + " Pressed" + String(key.pressed ? "True" : "False") + " Mod: "; if (key.mod.shift) - str+="S"; + str += "S"; if (key.mod.control) - str+="C"; + str += "C"; if (key.mod.alt) - str+="A"; + str += "A"; if (key.mod.meta) - str+="M"; + str += "M"; return str; } break; case MOUSE_MOTION: { - str+= "Event: Motion "; - str=str+" Pos: " +itos(mouse_motion.x)+","+itos(mouse_motion.y)+" Rel: "+itos(mouse_motion.relative_x)+","+itos(mouse_motion.relative_y)+" Mask: "; - for (int i=0;i<8;i++) { + str += "Event: Motion "; + str = str + " Pos: " + itos(mouse_motion.x) + "," + itos(mouse_motion.y) + " Rel: " + itos(mouse_motion.relative_x) + "," + itos(mouse_motion.relative_y) + " Mask: "; + for (int i = 0; i < 8; i++) { - if ((1<<i)&mouse_motion.button_mask) - str+=itos(i+1); + if ((1 << i) & mouse_motion.button_mask) + str += itos(i + 1); } - str+=" Mod: "; + str += " Mod: "; if (key.mod.shift) - str+="S"; + str += "S"; if (key.mod.control) - str+="C"; + str += "C"; if (key.mod.alt) - str+="A"; + str += "A"; if (key.mod.meta) - str+="M"; + str += "M"; return str; } break; case MOUSE_BUTTON: { - str+= "Event: Button "; - str=str+"Pressed: "+itos(mouse_button.pressed)+" Pos: " +itos(mouse_button.x)+","+itos(mouse_button.y)+" Button: "+itos(mouse_button.button_index)+" Mask: "; - for (int i=0;i<8;i++) { + str += "Event: Button "; + str = str + "Pressed: " + itos(mouse_button.pressed) + " Pos: " + itos(mouse_button.x) + "," + itos(mouse_button.y) + " Button: " + itos(mouse_button.button_index) + " Mask: "; + for (int i = 0; i < 8; i++) { - if ((1<<i)&mouse_button.button_mask) - str+=itos(i+1); + if ((1 << i) & mouse_button.button_mask) + str += itos(i + 1); } - str+=" Mod: "; + str += " Mod: "; if (key.mod.shift) - str+="S"; + str += "S"; if (key.mod.control) - str+="C"; + str += "C"; if (key.mod.alt) - str+="A"; + str += "A"; if (key.mod.meta) - str+="M"; + str += "M"; - str+=String(" DoubleClick: ")+(mouse_button.doubleclick?"Yes":"No"); + str += String(" DoubleClick: ") + (mouse_button.doubleclick ? "Yes" : "No"); return str; } break; case JOYPAD_MOTION: { - str+= "Event: JoypadMotion "; - str=str+"Axis: "+itos(joy_motion.axis)+" Value: " +rtos(joy_motion.axis_value); + str += "Event: JoypadMotion "; + str = str + "Axis: " + itos(joy_motion.axis) + " Value: " + rtos(joy_motion.axis_value); return str; } break; case JOYPAD_BUTTON: { - str+= "Event: JoypadButton "; - str=str+"Pressed: "+itos(joy_button.pressed)+" Index: " +itos(joy_button.button_index)+" pressure "+rtos(joy_button.pressure); + str += "Event: JoypadButton "; + str = str + "Pressed: " + itos(joy_button.pressed) + " Index: " + itos(joy_button.button_index) + " pressure " + rtos(joy_button.pressure); return str; } break; case SCREEN_TOUCH: { - str+= "Event: ScreenTouch "; - str=str+"Pressed: "+itos(screen_touch.pressed)+" Index: " +itos(screen_touch.index)+" pos "+rtos(screen_touch.x)+","+rtos(screen_touch.y); + str += "Event: ScreenTouch "; + str = str + "Pressed: " + itos(screen_touch.pressed) + " Index: " + itos(screen_touch.index) + " pos " + rtos(screen_touch.x) + "," + rtos(screen_touch.y); return str; } break; case SCREEN_DRAG: { - str+= "Event: ScreenDrag "; - str=str+" Index: " +itos(screen_drag.index)+" pos "+rtos(screen_drag.x)+","+rtos(screen_drag.y); + str += "Event: ScreenDrag "; + str = str + " Index: " + itos(screen_drag.index) + " pos " + rtos(screen_drag.x) + "," + rtos(screen_drag.y); return str; } break; case ACTION: { - str+= "Event: Action: "+InputMap::get_singleton()->get_action_from_id(action.action)+" Pressed: "+itos(action.pressed); + str += "Event: Action: " + InputMap::get_singleton()->get_action_from_id(action.action) + " Pressed: " + itos(action.pressed); return str; } break; - } return ""; } -void InputEvent::set_as_action(const String& p_action, bool p_pressed) { +void InputEvent::set_as_action(const String &p_action, bool p_pressed) { - type=ACTION; - action.action=InputMap::get_singleton()->get_action_id(p_action); - action.pressed=p_pressed; + type = ACTION; + action.action = InputMap::get_singleton()->get_action_id(p_action); + action.pressed = p_pressed; } bool InputEvent::is_pressed() const { - switch(type) { + switch (type) { case KEY: return key.pressed; case MOUSE_BUTTON: return mouse_button.pressed; @@ -218,93 +217,89 @@ bool InputEvent::is_pressed() const { bool InputEvent::is_echo() const { - return (type==KEY && key.echo); + return (type == KEY && key.echo); } -bool InputEvent::is_action(const String& p_action) const { +bool InputEvent::is_action(const String &p_action) const { - return InputMap::get_singleton()->event_is_action(*this,p_action); + return InputMap::get_singleton()->event_is_action(*this, p_action); } -bool InputEvent::is_action_pressed(const String& p_action) const { +bool InputEvent::is_action_pressed(const String &p_action) const { return is_action(p_action) && is_pressed() && !is_echo(); } -bool InputEvent::is_action_released(const String& p_action) const { +bool InputEvent::is_action_released(const String &p_action) const { return is_action(p_action) && !is_pressed(); } uint32_t InputEventKey::get_scancode_with_modifiers() const { - uint32_t sc=scancode; + uint32_t sc = scancode; if (mod.control) - sc|=KEY_MASK_CTRL; + sc |= KEY_MASK_CTRL; if (mod.alt) - sc|=KEY_MASK_ALT; + sc |= KEY_MASK_ALT; if (mod.shift) - sc|=KEY_MASK_SHIFT; + sc |= KEY_MASK_SHIFT; if (mod.meta) - sc|=KEY_MASK_META; + sc |= KEY_MASK_META; return sc; - } -InputEvent InputEvent::xform_by(const Transform2D& p_xform) const { - +InputEvent InputEvent::xform_by(const Transform2D &p_xform) const { - InputEvent ev=*this; + InputEvent ev = *this; - switch(ev.type) { + switch (ev.type) { case InputEvent::MOUSE_BUTTON: { - Vector2 g = p_xform.xform(Vector2(ev.mouse_button.global_x,ev.mouse_button.global_y)); - Vector2 l = p_xform.xform(Vector2(ev.mouse_button.x,ev.mouse_button.y)); - ev.mouse_button.x=l.x; - ev.mouse_button.y=l.y; - ev.mouse_button.global_x=g.x; - ev.mouse_button.global_y=g.y; + Vector2 g = p_xform.xform(Vector2(ev.mouse_button.global_x, ev.mouse_button.global_y)); + Vector2 l = p_xform.xform(Vector2(ev.mouse_button.x, ev.mouse_button.y)); + ev.mouse_button.x = l.x; + ev.mouse_button.y = l.y; + ev.mouse_button.global_x = g.x; + ev.mouse_button.global_y = g.y; } break; case InputEvent::MOUSE_MOTION: { - Vector2 g = p_xform.xform(Vector2(ev.mouse_motion.global_x,ev.mouse_motion.global_y)); - Vector2 l = p_xform.xform(Vector2(ev.mouse_motion.x,ev.mouse_motion.y)); - Vector2 r = p_xform.basis_xform(Vector2(ev.mouse_motion.relative_x,ev.mouse_motion.relative_y)); - Vector2 s = p_xform.basis_xform(Vector2(ev.mouse_motion.speed_x,ev.mouse_motion.speed_y)); - ev.mouse_motion.x=l.x; - ev.mouse_motion.y=l.y; - ev.mouse_motion.global_x=g.x; - ev.mouse_motion.global_y=g.y; - ev.mouse_motion.relative_x=r.x; - ev.mouse_motion.relative_y=r.y; - ev.mouse_motion.speed_x=s.x; - ev.mouse_motion.speed_y=s.y; + Vector2 g = p_xform.xform(Vector2(ev.mouse_motion.global_x, ev.mouse_motion.global_y)); + Vector2 l = p_xform.xform(Vector2(ev.mouse_motion.x, ev.mouse_motion.y)); + Vector2 r = p_xform.basis_xform(Vector2(ev.mouse_motion.relative_x, ev.mouse_motion.relative_y)); + Vector2 s = p_xform.basis_xform(Vector2(ev.mouse_motion.speed_x, ev.mouse_motion.speed_y)); + ev.mouse_motion.x = l.x; + ev.mouse_motion.y = l.y; + ev.mouse_motion.global_x = g.x; + ev.mouse_motion.global_y = g.y; + ev.mouse_motion.relative_x = r.x; + ev.mouse_motion.relative_y = r.y; + ev.mouse_motion.speed_x = s.x; + ev.mouse_motion.speed_y = s.y; } break; case InputEvent::SCREEN_TOUCH: { - - Vector2 t = p_xform.xform(Vector2(ev.screen_touch.x,ev.screen_touch.y)); - ev.screen_touch.x=t.x; - ev.screen_touch.y=t.y; + Vector2 t = p_xform.xform(Vector2(ev.screen_touch.x, ev.screen_touch.y)); + ev.screen_touch.x = t.x; + ev.screen_touch.y = t.y; } break; case InputEvent::SCREEN_DRAG: { - - Vector2 t = p_xform.xform(Vector2(ev.screen_drag.x,ev.screen_drag.y)); - Vector2 r = p_xform.basis_xform(Vector2(ev.screen_drag.relative_x,ev.screen_drag.relative_y)); - Vector2 s = p_xform.basis_xform(Vector2(ev.screen_drag.speed_x,ev.screen_drag.speed_y)); - ev.screen_drag.x=t.x; - ev.screen_drag.y=t.y; - ev.screen_drag.relative_x=r.x; - ev.screen_drag.relative_y=r.y; - ev.screen_drag.speed_x=s.x; - ev.screen_drag.speed_y=s.y; + Vector2 t = p_xform.xform(Vector2(ev.screen_drag.x, ev.screen_drag.y)); + Vector2 r = p_xform.basis_xform(Vector2(ev.screen_drag.relative_x, ev.screen_drag.relative_y)); + Vector2 s = p_xform.basis_xform(Vector2(ev.screen_drag.speed_x, ev.screen_drag.speed_y)); + ev.screen_drag.x = t.x; + ev.screen_drag.y = t.y; + ev.screen_drag.relative_x = r.x; + ev.screen_drag.relative_y = r.y; + ev.screen_drag.speed_x = s.x; + ev.screen_drag.speed_y = s.y; } break; } diff --git a/core/os/input_event.h b/core/os/input_event.h index 1af4ef20c2..fd3f8c4cec 100644 --- a/core/os/input_event.h +++ b/core/os/input_event.h @@ -29,33 +29,30 @@ #ifndef INPUT_EVENT_H #define INPUT_EVENT_H - -#include "typedefs.h" +#include "math_2d.h" #include "os/copymem.h" +#include "typedefs.h" #include "ustring.h" -#include "math_2d.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - - /** * Input Event classes. These are used in the main loop. * The events are pretty obvious. */ enum { - BUTTON_LEFT=1, - BUTTON_RIGHT=2, - BUTTON_MIDDLE=3, - BUTTON_WHEEL_UP=4, - BUTTON_WHEEL_DOWN=5, - BUTTON_WHEEL_LEFT=6, - BUTTON_WHEEL_RIGHT=7, - BUTTON_MASK_LEFT=(1<<(BUTTON_LEFT-1)), - BUTTON_MASK_RIGHT=(1<<(BUTTON_RIGHT-1)), - BUTTON_MASK_MIDDLE=(1<<(BUTTON_MIDDLE-1)), + BUTTON_LEFT = 1, + BUTTON_RIGHT = 2, + BUTTON_MIDDLE = 3, + BUTTON_WHEEL_UP = 4, + BUTTON_WHEEL_DOWN = 5, + BUTTON_WHEEL_LEFT = 6, + BUTTON_WHEEL_RIGHT = 7, + BUTTON_MASK_LEFT = (1 << (BUTTON_LEFT - 1)), + BUTTON_MASK_RIGHT = (1 << (BUTTON_RIGHT - 1)), + BUTTON_MASK_MIDDLE = (1 << (BUTTON_MIDDLE - 1)), }; @@ -99,20 +96,20 @@ enum { JOY_SNES_Y = JOY_BUTTON_2, JOY_SNES_X = JOY_BUTTON_3, - JOY_SONY_CIRCLE=JOY_SNES_A, - JOY_SONY_X=JOY_SNES_B, - JOY_SONY_SQUARE=JOY_SNES_Y, - JOY_SONY_TRIANGLE=JOY_SNES_X, + JOY_SONY_CIRCLE = JOY_SNES_A, + JOY_SONY_X = JOY_SNES_B, + JOY_SONY_SQUARE = JOY_SNES_Y, + JOY_SONY_TRIANGLE = JOY_SNES_X, - JOY_SEGA_B=JOY_SNES_A, - JOY_SEGA_A=JOY_SNES_B, - JOY_SEGA_X=JOY_SNES_Y, - JOY_SEGA_Y=JOY_SNES_X, + JOY_SEGA_B = JOY_SNES_A, + JOY_SEGA_A = JOY_SNES_B, + JOY_SEGA_X = JOY_SNES_Y, + JOY_SEGA_Y = JOY_SNES_X, - JOY_XBOX_B=JOY_SEGA_B, - JOY_XBOX_A=JOY_SEGA_A, - JOY_XBOX_X=JOY_SEGA_X, - JOY_XBOX_Y=JOY_SEGA_Y, + JOY_XBOX_B = JOY_SEGA_B, + JOY_XBOX_A = JOY_SEGA_A, + JOY_XBOX_X = JOY_SEGA_X, + JOY_XBOX_Y = JOY_SEGA_Y, JOY_DS_A = JOY_SNES_A, JOY_DS_B = JOY_SNES_B, @@ -127,15 +124,15 @@ enum { // end of history - JOY_AXIS_0=0, - JOY_AXIS_1=1, - JOY_AXIS_2=2, - JOY_AXIS_3=3, - JOY_AXIS_4=4, - JOY_AXIS_5=5, - JOY_AXIS_6=6, - JOY_AXIS_7=7, - JOY_AXIS_MAX=8, + JOY_AXIS_0 = 0, + JOY_AXIS_1 = 1, + JOY_AXIS_2 = 2, + JOY_AXIS_3 = 3, + JOY_AXIS_4 = 4, + JOY_AXIS_5 = 5, + JOY_AXIS_6 = 6, + JOY_AXIS_7 = 7, + JOY_AXIS_MAX = 8, JOY_ANALOG_0_X = JOY_AXIS_0, JOY_ANALOG_0_Y = JOY_AXIS_1, @@ -150,7 +147,6 @@ enum { JOY_ANALOG_R2 = JOY_AXIS_7, }; - /** * Input Modifier Status * for keyboard/mouse events. @@ -161,32 +157,27 @@ struct InputModifierState { bool alt; #ifdef APPLE_STYLE_KEYS union { - bool command; - bool meta; //< windows/mac key + bool command; + bool meta; //< windows/mac key }; bool control; #else union { - bool command; //< windows/mac key - bool control; + bool command; //< windows/mac key + bool control; }; bool meta; //< windows/mac key #endif - bool operator==(const InputModifierState& rvalue) const { + bool operator==(const InputModifierState &rvalue) const { - return ( (shift==rvalue.shift) && (alt==rvalue.alt) && (control==rvalue.control) && (meta==rvalue.meta)); + return ((shift == rvalue.shift) && (alt == rvalue.alt) && (control == rvalue.control) && (meta == rvalue.meta)); } }; - - - - - -struct InputEventKey { +struct InputEventKey { InputModifierState mod; @@ -200,66 +191,61 @@ struct InputEventKey { bool echo; /// true if this is an echo key }; - -struct InputEventMouse { +struct InputEventMouse { InputModifierState mod; int button_mask; - float x,y; - float global_x,global_y; + float x, y; + float global_x, global_y; int pointer_index; }; struct InputEventMouseButton : public InputEventMouse { - int button_index; bool pressed; //otherwise released bool doubleclick; //last even less than doubleclick time - }; struct InputEventMouseMotion : public InputEventMouse { - float relative_x,relative_y; - float speed_x,speed_y; + float relative_x, relative_y; + float speed_x, speed_y; }; -struct InputEventJoypadMotion { +struct InputEventJoypadMotion { int axis; ///< Joypad axis float axis_value; ///< -1 to 1 }; -struct InputEventJoypadButton { +struct InputEventJoypadButton { int button_index; bool pressed; float pressure; //0 to 1 }; -struct InputEventScreenTouch { +struct InputEventScreenTouch { int index; - float x,y; + float x, y; bool pressed; }; -struct InputEventScreenDrag { +struct InputEventScreenDrag { int index; - float x,y; - float relative_x,relative_y; - float speed_x,speed_y; + float x, y; + float relative_x, relative_y; + float speed_x, speed_y; }; -struct InputEventAction { +struct InputEventAction { int action; bool pressed; }; - - struct InputEvent { enum Type { @@ -291,18 +277,16 @@ struct InputEvent { }; bool is_pressed() const; - bool is_action(const String& p_action) const; - bool is_action_pressed(const String& p_action) const; - bool is_action_released(const String& p_action) const; + bool is_action(const String &p_action) const; + bool is_action_pressed(const String &p_action) const; + bool is_action_released(const String &p_action) const; bool is_echo() const; - void set_as_action(const String& p_action, bool p_pressed); + void set_as_action(const String &p_action, bool p_pressed); - - InputEvent xform_by(const Transform2D& p_xform) const; + InputEvent xform_by(const Transform2D &p_xform) const; bool operator==(const InputEvent &p_event) const; operator String() const; - InputEvent() { zeromem(this,sizeof(InputEvent)); } + InputEvent() { zeromem(this, sizeof(InputEvent)); } }; - #endif diff --git a/core/os/keyboard.cpp b/core/os/keyboard.cpp index 40fa86d09f..a5f8bfa144 100644 --- a/core/os/keyboard.cpp +++ b/core/os/keyboard.cpp @@ -34,9 +34,9 @@ struct _KeyCodeText { const char *text; }; -static const _KeyCodeText _keycodes[]={ +static const _KeyCodeText _keycodes[] = { - /* clang-format off */ + /* clang-format off */ {KEY_ESCAPE ,"Escape"}, {KEY_TAB ,"Tab"}, {KEY_BACKTAB ,"BackTab"}, @@ -283,25 +283,105 @@ static const _KeyCodeText _keycodes[]={ {KEY_DIVISION ,"Division"}, {KEY_YDIAERESIS ,"Ydiaeresis"}, {0 ,0} - /* clang-format on */ + /* clang-format on */ }; bool keycode_has_unicode(uint32_t p_keycode) { - - switch(p_keycode) { - - case KEY_ESCAPE: case KEY_TAB: case KEY_BACKTAB: case KEY_BACKSPACE: case KEY_RETURN: case KEY_ENTER: case KEY_INSERT: case KEY_DELETE: case KEY_PAUSE: - case KEY_PRINT: case KEY_SYSREQ: case KEY_CLEAR: case KEY_HOME: case KEY_END: case KEY_LEFT: case KEY_UP: case KEY_RIGHT: case KEY_DOWN: case KEY_PAGEUP: - case KEY_PAGEDOWN: case KEY_SHIFT: case KEY_CONTROL: case KEY_META: case KEY_ALT: case KEY_CAPSLOCK: case KEY_NUMLOCK: case KEY_SCROLLLOCK: case KEY_F1: - case KEY_F2: case KEY_F3: case KEY_F4: case KEY_F5: case KEY_F6: case KEY_F7: case KEY_F8: case KEY_F9: case KEY_F10: case KEY_F11: case KEY_F12: case KEY_F13: case KEY_F14: - case KEY_F15: case KEY_F16: case KEY_KP_ENTER: case KEY_SUPER_L: case KEY_SUPER_R: case KEY_MENU: case KEY_HYPER_L: case KEY_HYPER_R: case KEY_HELP: - case KEY_DIRECTION_L: case KEY_DIRECTION_R: case KEY_BACK: case KEY_FORWARD: case KEY_STOP: case KEY_REFRESH: case KEY_VOLUMEDOWN: case KEY_VOLUMEMUTE: - case KEY_VOLUMEUP: case KEY_BASSBOOST: case KEY_BASSUP: case KEY_BASSDOWN: case KEY_TREBLEUP: case KEY_TREBLEDOWN: case KEY_MEDIAPLAY: case KEY_MEDIASTOP: - case KEY_MEDIAPREVIOUS: case KEY_MEDIANEXT: case KEY_MEDIARECORD: case KEY_HOMEPAGE: case KEY_FAVORITES: case KEY_SEARCH: case KEY_STANDBY: - case KEY_OPENURL: case KEY_LAUNCHMAIL: case KEY_LAUNCHMEDIA: case KEY_LAUNCH0: case KEY_LAUNCH1: case KEY_LAUNCH2: case KEY_LAUNCH3: case KEY_LAUNCH4: - case KEY_LAUNCH5: case KEY_LAUNCH6: case KEY_LAUNCH7: case KEY_LAUNCH8: case KEY_LAUNCH9: case KEY_LAUNCHA: case KEY_LAUNCHB: case KEY_LAUNCHC: case KEY_LAUNCHD: - case KEY_LAUNCHE: case KEY_LAUNCHF: + switch (p_keycode) { + + case KEY_ESCAPE: + case KEY_TAB: + case KEY_BACKTAB: + case KEY_BACKSPACE: + case KEY_RETURN: + case KEY_ENTER: + case KEY_INSERT: + case KEY_DELETE: + case KEY_PAUSE: + case KEY_PRINT: + case KEY_SYSREQ: + case KEY_CLEAR: + case KEY_HOME: + case KEY_END: + case KEY_LEFT: + case KEY_UP: + case KEY_RIGHT: + case KEY_DOWN: + case KEY_PAGEUP: + case KEY_PAGEDOWN: + case KEY_SHIFT: + case KEY_CONTROL: + case KEY_META: + case KEY_ALT: + case KEY_CAPSLOCK: + case KEY_NUMLOCK: + case KEY_SCROLLLOCK: + case KEY_F1: + case KEY_F2: + case KEY_F3: + case KEY_F4: + case KEY_F5: + case KEY_F6: + case KEY_F7: + case KEY_F8: + case KEY_F9: + case KEY_F10: + case KEY_F11: + case KEY_F12: + case KEY_F13: + case KEY_F14: + case KEY_F15: + case KEY_F16: + case KEY_KP_ENTER: + case KEY_SUPER_L: + case KEY_SUPER_R: + case KEY_MENU: + case KEY_HYPER_L: + case KEY_HYPER_R: + case KEY_HELP: + case KEY_DIRECTION_L: + case KEY_DIRECTION_R: + case KEY_BACK: + case KEY_FORWARD: + case KEY_STOP: + case KEY_REFRESH: + case KEY_VOLUMEDOWN: + case KEY_VOLUMEMUTE: + case KEY_VOLUMEUP: + case KEY_BASSBOOST: + case KEY_BASSUP: + case KEY_BASSDOWN: + case KEY_TREBLEUP: + case KEY_TREBLEDOWN: + case KEY_MEDIAPLAY: + case KEY_MEDIASTOP: + case KEY_MEDIAPREVIOUS: + case KEY_MEDIANEXT: + case KEY_MEDIARECORD: + case KEY_HOMEPAGE: + case KEY_FAVORITES: + case KEY_SEARCH: + case KEY_STANDBY: + case KEY_OPENURL: + case KEY_LAUNCHMAIL: + case KEY_LAUNCHMEDIA: + case KEY_LAUNCH0: + case KEY_LAUNCH1: + case KEY_LAUNCH2: + case KEY_LAUNCH3: + case KEY_LAUNCH4: + case KEY_LAUNCH5: + case KEY_LAUNCH6: + case KEY_LAUNCH7: + case KEY_LAUNCH8: + case KEY_LAUNCH9: + case KEY_LAUNCHA: + case KEY_LAUNCHB: + case KEY_LAUNCHC: + case KEY_LAUNCHD: + case KEY_LAUNCHE: + case KEY_LAUNCHF: return false; } @@ -311,133 +391,127 @@ bool keycode_has_unicode(uint32_t p_keycode) { String keycode_get_string(uint32_t p_code) { String codestr; - if (p_code&KEY_MASK_SHIFT) - codestr+="Shift+"; - if (p_code&KEY_MASK_ALT) - codestr+="Alt+"; - if (p_code&KEY_MASK_CTRL) - codestr+="Ctrl+"; - if (p_code&KEY_MASK_META) - codestr+="Meta+"; + if (p_code & KEY_MASK_SHIFT) + codestr += "Shift+"; + if (p_code & KEY_MASK_ALT) + codestr += "Alt+"; + if (p_code & KEY_MASK_CTRL) + codestr += "Ctrl+"; + if (p_code & KEY_MASK_META) + codestr += "Meta+"; - p_code&=KEY_CODE_MASK; + p_code &= KEY_CODE_MASK; - const _KeyCodeText *kct =&_keycodes[0]; + const _KeyCodeText *kct = &_keycodes[0]; - while(kct->text) { + while (kct->text) { - if (kct->code==(int)p_code) { + if (kct->code == (int)p_code) { - codestr+=kct->text; + codestr += kct->text; return codestr; } kct++; } - codestr+=String::chr(p_code); + codestr += String::chr(p_code); return codestr; - } -int find_keycode(const String& p_code) { +int find_keycode(const String &p_code) { - const _KeyCodeText *kct =&_keycodes[0]; + const _KeyCodeText *kct = &_keycodes[0]; - while(kct->text) { + while (kct->text) { - if (p_code.nocasecmp_to(kct->text)==0) { + if (p_code.nocasecmp_to(kct->text) == 0) { return kct->code; - } kct++; } return 0; - } - - - struct _KeyCodeReplace { int from; int to; }; -static const _KeyCodeReplace _keycode_replace_qwertz[]={ -{KEY_Y,KEY_Z}, -{KEY_Z,KEY_Y}, -{0,0} +static const _KeyCodeReplace _keycode_replace_qwertz[] = { + { KEY_Y, KEY_Z }, + { KEY_Z, KEY_Y }, + { 0, 0 } }; -static const _KeyCodeReplace _keycode_replace_azerty[]={ -{KEY_W,KEY_Z}, -{KEY_Z,KEY_W}, -{KEY_A,KEY_Q}, -{KEY_Q,KEY_A}, -{KEY_SEMICOLON,KEY_M}, -{KEY_M,KEY_SEMICOLON}, -{0,0} +static const _KeyCodeReplace _keycode_replace_azerty[] = { + { KEY_W, KEY_Z }, + { KEY_Z, KEY_W }, + { KEY_A, KEY_Q }, + { KEY_Q, KEY_A }, + { KEY_SEMICOLON, KEY_M }, + { KEY_M, KEY_SEMICOLON }, + { 0, 0 } }; -static const _KeyCodeReplace _keycode_replace_qzerty[]={ -{KEY_W,KEY_Z}, -{KEY_Z,KEY_W}, -{KEY_SEMICOLON,KEY_M}, -{KEY_M,KEY_SEMICOLON}, -{0,0} +static const _KeyCodeReplace _keycode_replace_qzerty[] = { + { KEY_W, KEY_Z }, + { KEY_Z, KEY_W }, + { KEY_SEMICOLON, KEY_M }, + { KEY_M, KEY_SEMICOLON }, + { 0, 0 } }; -static const _KeyCodeReplace _keycode_replace_dvorak[]={ -{KEY_UNDERSCORE,KEY_BRACELEFT}, -{KEY_EQUAL,KEY_BRACERIGHT}, -{KEY_Q,KEY_APOSTROPHE}, -{KEY_W,KEY_COMMA}, -{KEY_E,KEY_PERIOD}, -{KEY_R,KEY_P}, -{KEY_T,KEY_Y}, -{KEY_Y,KEY_F}, -{KEY_U,KEY_G}, -{KEY_I,KEY_C}, -{KEY_O,KEY_R}, -{KEY_P,KEY_L}, -{KEY_BRACELEFT,KEY_SLASH}, -{KEY_BRACERIGHT,KEY_EQUAL}, -{KEY_A,KEY_A}, -{KEY_S,KEY_O}, -{KEY_D,KEY_E}, -{KEY_F,KEY_U}, -{KEY_G,KEY_I}, -{KEY_H,KEY_D}, -{KEY_J,KEY_H}, -{KEY_K,KEY_T}, -{KEY_L,KEY_N}, -{KEY_SEMICOLON,KEY_S}, -{KEY_APOSTROPHE,KEY_UNDERSCORE}, -{KEY_Z,KEY_SEMICOLON}, -{KEY_X,KEY_Q}, -{KEY_C,KEY_J}, -{KEY_V,KEY_K}, -{KEY_B,KEY_X}, -{KEY_N,KEY_B}, -{KEY_M,KEY_M}, -{KEY_COMMA,KEY_W}, -{KEY_PERIOD,KEY_V}, -{KEY_SLASH,KEY_Z}, -{0,0} +static const _KeyCodeReplace _keycode_replace_dvorak[] = { + { KEY_UNDERSCORE, KEY_BRACELEFT }, + { KEY_EQUAL, KEY_BRACERIGHT }, + { KEY_Q, KEY_APOSTROPHE }, + { KEY_W, KEY_COMMA }, + { KEY_E, KEY_PERIOD }, + { KEY_R, KEY_P }, + { KEY_T, KEY_Y }, + { KEY_Y, KEY_F }, + { KEY_U, KEY_G }, + { KEY_I, KEY_C }, + { KEY_O, KEY_R }, + { KEY_P, KEY_L }, + { KEY_BRACELEFT, KEY_SLASH }, + { KEY_BRACERIGHT, KEY_EQUAL }, + { KEY_A, KEY_A }, + { KEY_S, KEY_O }, + { KEY_D, KEY_E }, + { KEY_F, KEY_U }, + { KEY_G, KEY_I }, + { KEY_H, KEY_D }, + { KEY_J, KEY_H }, + { KEY_K, KEY_T }, + { KEY_L, KEY_N }, + { KEY_SEMICOLON, KEY_S }, + { KEY_APOSTROPHE, KEY_UNDERSCORE }, + { KEY_Z, KEY_SEMICOLON }, + { KEY_X, KEY_Q }, + { KEY_C, KEY_J }, + { KEY_V, KEY_K }, + { KEY_B, KEY_X }, + { KEY_N, KEY_B }, + { KEY_M, KEY_M }, + { KEY_COMMA, KEY_W }, + { KEY_PERIOD, KEY_V }, + { KEY_SLASH, KEY_Z }, + { 0, 0 } }; -static const _KeyCodeReplace _keycode_replace_neo[]={ -{0,0} +static const _KeyCodeReplace _keycode_replace_neo[] = { + { 0, 0 } }; int keycode_get_count() { - const _KeyCodeText *kct =&_keycodes[0]; + const _KeyCodeText *kct = &_keycodes[0]; - int count=0; - while(kct->text) { + int count = 0; + while (kct->text) { count++; kct++; @@ -449,22 +523,21 @@ int keycode_get_value_by_index(int p_index) { return _keycodes[p_index].code; } -const char* keycode_get_name_by_index(int p_index) { +const char *keycode_get_name_by_index(int p_index) { return _keycodes[p_index].text; } - int latin_keyboard_keycode_convert(int p_keycode) { - const _KeyCodeReplace *kcr=NULL; - switch(OS::get_singleton()->get_latin_keyboard_variant()) { + const _KeyCodeReplace *kcr = NULL; + switch (OS::get_singleton()->get_latin_keyboard_variant()) { case OS::LATIN_KEYBOARD_QWERTY: return p_keycode; break; - case OS::LATIN_KEYBOARD_QWERTZ: kcr=_keycode_replace_qwertz; break; - case OS::LATIN_KEYBOARD_AZERTY: kcr=_keycode_replace_azerty; break; - case OS::LATIN_KEYBOARD_QZERTY: kcr=_keycode_replace_qzerty; break; - case OS::LATIN_KEYBOARD_DVORAK: kcr=_keycode_replace_dvorak; break; - case OS::LATIN_KEYBOARD_NEO: kcr=_keycode_replace_neo; break; + case OS::LATIN_KEYBOARD_QWERTZ: kcr = _keycode_replace_qwertz; break; + case OS::LATIN_KEYBOARD_AZERTY: kcr = _keycode_replace_azerty; break; + case OS::LATIN_KEYBOARD_QZERTY: kcr = _keycode_replace_qzerty; break; + case OS::LATIN_KEYBOARD_DVORAK: kcr = _keycode_replace_dvorak; break; + case OS::LATIN_KEYBOARD_NEO: kcr = _keycode_replace_neo; break; default: return p_keycode; } @@ -472,8 +545,8 @@ int latin_keyboard_keycode_convert(int p_keycode) { return p_keycode; } - while(kcr->from) { - if (kcr->from==p_keycode) + while (kcr->from) { + if (kcr->from == p_keycode) return kcr->to; kcr++; } diff --git a/core/os/keyboard.h b/core/os/keyboard.h index 1357cc8b8e..1f6bc77334 100644 --- a/core/os/keyboard.h +++ b/core/os/keyboard.h @@ -47,290 +47,288 @@ modifiers. This way everything (char/keycode) can fit nicely in one 32 bits unsigned integer. */ enum { - SPKEY = (1<<24) + SPKEY = (1 << 24) }; enum KeyList { -/* CURSOR/FUNCTION/BROWSER/MULTIMEDIA/MISC KEYS */ - KEY_ESCAPE=SPKEY | 0x01, - KEY_TAB=SPKEY | 0x02, - KEY_BACKTAB=SPKEY | 0x03, - KEY_BACKSPACE=SPKEY | 0x04, - KEY_RETURN=SPKEY | 0x05, - KEY_ENTER=SPKEY | 0x06, - KEY_INSERT=SPKEY | 0x07, - KEY_DELETE=SPKEY | 0x08, - KEY_PAUSE=SPKEY | 0x09, - KEY_PRINT=SPKEY | 0x0A, - KEY_SYSREQ=SPKEY | 0x0B, - KEY_CLEAR=SPKEY | 0x0C, - KEY_HOME=SPKEY | 0x0D, - KEY_END=SPKEY | 0x0E, - KEY_LEFT=SPKEY | 0x0F, - KEY_UP=SPKEY | 0x10, - KEY_RIGHT=SPKEY | 0x11, - KEY_DOWN=SPKEY | 0x12, - KEY_PAGEUP=SPKEY | 0x13, - KEY_PAGEDOWN=SPKEY | 0x14, - KEY_SHIFT=SPKEY | 0x15, - KEY_CONTROL=SPKEY | 0x16, - KEY_META=SPKEY | 0x17, - KEY_ALT=SPKEY | 0x18, - KEY_CAPSLOCK=SPKEY | 0x19, - KEY_NUMLOCK=SPKEY | 0x1A, - KEY_SCROLLLOCK=SPKEY | 0x1B, - KEY_F1=SPKEY | 0x1C, - KEY_F2=SPKEY | 0x1D, - KEY_F3=SPKEY | 0x1E, - KEY_F4=SPKEY | 0x1F, - KEY_F5=SPKEY | 0x20, - KEY_F6=SPKEY | 0x21, - KEY_F7=SPKEY | 0x22, - KEY_F8=SPKEY | 0x23, - KEY_F9=SPKEY | 0x24, - KEY_F10=SPKEY | 0x25, - KEY_F11=SPKEY | 0x26, - KEY_F12=SPKEY | 0x27, - KEY_F13=SPKEY | 0x28, - KEY_F14=SPKEY | 0x29, - KEY_F15=SPKEY | 0x2A, - KEY_F16=SPKEY | 0x2B, - KEY_KP_ENTER=SPKEY | 0x80, - KEY_KP_MULTIPLY=SPKEY | 0x81, - KEY_KP_DIVIDE=SPKEY | 0x82, - KEY_KP_SUBTRACT=SPKEY | 0x83, - KEY_KP_PERIOD=SPKEY | 0x84, - KEY_KP_ADD=SPKEY | 0x85, - KEY_KP_0=SPKEY | 0x86, - KEY_KP_1=SPKEY | 0x87, - KEY_KP_2=SPKEY | 0x88, - KEY_KP_3=SPKEY | 0x89, - KEY_KP_4=SPKEY | 0x8A, - KEY_KP_5=SPKEY | 0x8B, - KEY_KP_6=SPKEY | 0x8C, - KEY_KP_7=SPKEY | 0x8D, - KEY_KP_8=SPKEY | 0x8E, - KEY_KP_9=SPKEY | 0x8F, - KEY_SUPER_L=SPKEY | 0x2C, - KEY_SUPER_R=SPKEY | 0x2D, - KEY_MENU=SPKEY | 0x2E, - KEY_HYPER_L=SPKEY | 0x2F, - KEY_HYPER_R=SPKEY | 0x30, - KEY_HELP=SPKEY | 0x31, - KEY_DIRECTION_L=SPKEY | 0x32, - KEY_DIRECTION_R=SPKEY | 0x33, - KEY_BACK=SPKEY | 0x40, - KEY_FORWARD=SPKEY | 0x41, - KEY_STOP=SPKEY | 0x42, - KEY_REFRESH=SPKEY | 0x43, - KEY_VOLUMEDOWN=SPKEY | 0x44, - KEY_VOLUMEMUTE=SPKEY | 0x45, - KEY_VOLUMEUP=SPKEY | 0x46, - KEY_BASSBOOST=SPKEY | 0x47, - KEY_BASSUP=SPKEY | 0x48, - KEY_BASSDOWN=SPKEY | 0x49, - KEY_TREBLEUP=SPKEY | 0x4A, - KEY_TREBLEDOWN=SPKEY | 0x4B, - KEY_MEDIAPLAY=SPKEY | 0x4C, - KEY_MEDIASTOP=SPKEY | 0x4D, - KEY_MEDIAPREVIOUS=SPKEY | 0x4E, - KEY_MEDIANEXT=SPKEY | 0x4F, - KEY_MEDIARECORD= SPKEY | 0x50, - KEY_HOMEPAGE=SPKEY | 0x51, - KEY_FAVORITES=SPKEY | 0x52, - KEY_SEARCH=SPKEY | 0x53, - KEY_STANDBY=SPKEY | 0x54, - KEY_OPENURL=SPKEY | 0x55, - KEY_LAUNCHMAIL=SPKEY | 0x56, - KEY_LAUNCHMEDIA=SPKEY | 0x57, - KEY_LAUNCH0=SPKEY | 0x58, - KEY_LAUNCH1=SPKEY | 0x59, - KEY_LAUNCH2=SPKEY | 0x5A, - KEY_LAUNCH3=SPKEY | 0x5B, - KEY_LAUNCH4=SPKEY | 0x5C, - KEY_LAUNCH5=SPKEY | 0x5D, - KEY_LAUNCH6=SPKEY | 0x5E, - KEY_LAUNCH7=SPKEY | 0x5F, - KEY_LAUNCH8=SPKEY | 0x60, - KEY_LAUNCH9=SPKEY | 0x61, - KEY_LAUNCHA=SPKEY | 0x62, - KEY_LAUNCHB=SPKEY | 0x63, - KEY_LAUNCHC=SPKEY | 0x64, - KEY_LAUNCHD=SPKEY | 0x65, - KEY_LAUNCHE=SPKEY | 0x66, - KEY_LAUNCHF=SPKEY | 0x67, + /* CURSOR/FUNCTION/BROWSER/MULTIMEDIA/MISC KEYS */ + KEY_ESCAPE = SPKEY | 0x01, + KEY_TAB = SPKEY | 0x02, + KEY_BACKTAB = SPKEY | 0x03, + KEY_BACKSPACE = SPKEY | 0x04, + KEY_RETURN = SPKEY | 0x05, + KEY_ENTER = SPKEY | 0x06, + KEY_INSERT = SPKEY | 0x07, + KEY_DELETE = SPKEY | 0x08, + KEY_PAUSE = SPKEY | 0x09, + KEY_PRINT = SPKEY | 0x0A, + KEY_SYSREQ = SPKEY | 0x0B, + KEY_CLEAR = SPKEY | 0x0C, + KEY_HOME = SPKEY | 0x0D, + KEY_END = SPKEY | 0x0E, + KEY_LEFT = SPKEY | 0x0F, + KEY_UP = SPKEY | 0x10, + KEY_RIGHT = SPKEY | 0x11, + KEY_DOWN = SPKEY | 0x12, + KEY_PAGEUP = SPKEY | 0x13, + KEY_PAGEDOWN = SPKEY | 0x14, + KEY_SHIFT = SPKEY | 0x15, + KEY_CONTROL = SPKEY | 0x16, + KEY_META = SPKEY | 0x17, + KEY_ALT = SPKEY | 0x18, + KEY_CAPSLOCK = SPKEY | 0x19, + KEY_NUMLOCK = SPKEY | 0x1A, + KEY_SCROLLLOCK = SPKEY | 0x1B, + KEY_F1 = SPKEY | 0x1C, + KEY_F2 = SPKEY | 0x1D, + KEY_F3 = SPKEY | 0x1E, + KEY_F4 = SPKEY | 0x1F, + KEY_F5 = SPKEY | 0x20, + KEY_F6 = SPKEY | 0x21, + KEY_F7 = SPKEY | 0x22, + KEY_F8 = SPKEY | 0x23, + KEY_F9 = SPKEY | 0x24, + KEY_F10 = SPKEY | 0x25, + KEY_F11 = SPKEY | 0x26, + KEY_F12 = SPKEY | 0x27, + KEY_F13 = SPKEY | 0x28, + KEY_F14 = SPKEY | 0x29, + KEY_F15 = SPKEY | 0x2A, + KEY_F16 = SPKEY | 0x2B, + KEY_KP_ENTER = SPKEY | 0x80, + KEY_KP_MULTIPLY = SPKEY | 0x81, + KEY_KP_DIVIDE = SPKEY | 0x82, + KEY_KP_SUBTRACT = SPKEY | 0x83, + KEY_KP_PERIOD = SPKEY | 0x84, + KEY_KP_ADD = SPKEY | 0x85, + KEY_KP_0 = SPKEY | 0x86, + KEY_KP_1 = SPKEY | 0x87, + KEY_KP_2 = SPKEY | 0x88, + KEY_KP_3 = SPKEY | 0x89, + KEY_KP_4 = SPKEY | 0x8A, + KEY_KP_5 = SPKEY | 0x8B, + KEY_KP_6 = SPKEY | 0x8C, + KEY_KP_7 = SPKEY | 0x8D, + KEY_KP_8 = SPKEY | 0x8E, + KEY_KP_9 = SPKEY | 0x8F, + KEY_SUPER_L = SPKEY | 0x2C, + KEY_SUPER_R = SPKEY | 0x2D, + KEY_MENU = SPKEY | 0x2E, + KEY_HYPER_L = SPKEY | 0x2F, + KEY_HYPER_R = SPKEY | 0x30, + KEY_HELP = SPKEY | 0x31, + KEY_DIRECTION_L = SPKEY | 0x32, + KEY_DIRECTION_R = SPKEY | 0x33, + KEY_BACK = SPKEY | 0x40, + KEY_FORWARD = SPKEY | 0x41, + KEY_STOP = SPKEY | 0x42, + KEY_REFRESH = SPKEY | 0x43, + KEY_VOLUMEDOWN = SPKEY | 0x44, + KEY_VOLUMEMUTE = SPKEY | 0x45, + KEY_VOLUMEUP = SPKEY | 0x46, + KEY_BASSBOOST = SPKEY | 0x47, + KEY_BASSUP = SPKEY | 0x48, + KEY_BASSDOWN = SPKEY | 0x49, + KEY_TREBLEUP = SPKEY | 0x4A, + KEY_TREBLEDOWN = SPKEY | 0x4B, + KEY_MEDIAPLAY = SPKEY | 0x4C, + KEY_MEDIASTOP = SPKEY | 0x4D, + KEY_MEDIAPREVIOUS = SPKEY | 0x4E, + KEY_MEDIANEXT = SPKEY | 0x4F, + KEY_MEDIARECORD = SPKEY | 0x50, + KEY_HOMEPAGE = SPKEY | 0x51, + KEY_FAVORITES = SPKEY | 0x52, + KEY_SEARCH = SPKEY | 0x53, + KEY_STANDBY = SPKEY | 0x54, + KEY_OPENURL = SPKEY | 0x55, + KEY_LAUNCHMAIL = SPKEY | 0x56, + KEY_LAUNCHMEDIA = SPKEY | 0x57, + KEY_LAUNCH0 = SPKEY | 0x58, + KEY_LAUNCH1 = SPKEY | 0x59, + KEY_LAUNCH2 = SPKEY | 0x5A, + KEY_LAUNCH3 = SPKEY | 0x5B, + KEY_LAUNCH4 = SPKEY | 0x5C, + KEY_LAUNCH5 = SPKEY | 0x5D, + KEY_LAUNCH6 = SPKEY | 0x5E, + KEY_LAUNCH7 = SPKEY | 0x5F, + KEY_LAUNCH8 = SPKEY | 0x60, + KEY_LAUNCH9 = SPKEY | 0x61, + KEY_LAUNCHA = SPKEY | 0x62, + KEY_LAUNCHB = SPKEY | 0x63, + KEY_LAUNCHC = SPKEY | 0x64, + KEY_LAUNCHD = SPKEY | 0x65, + KEY_LAUNCHE = SPKEY | 0x66, + KEY_LAUNCHF = SPKEY | 0x67, - KEY_UNKNOWN=SPKEY | 0xFFFFFF, + KEY_UNKNOWN = SPKEY | 0xFFFFFF, -/* PRINTABLE LATIN 1 CODES */ + /* PRINTABLE LATIN 1 CODES */ - KEY_SPACE=0x0020, - KEY_EXCLAM=0x0021, - KEY_QUOTEDBL=0x0022, - KEY_NUMBERSIGN=0x0023, - KEY_DOLLAR=0x0024, - KEY_PERCENT=0x0025, - KEY_AMPERSAND=0x0026, - KEY_APOSTROPHE=0x0027, - KEY_PARENLEFT=0x0028, - KEY_PARENRIGHT=0x0029, - KEY_ASTERISK=0x002A, - KEY_PLUS=0x002B, - KEY_COMMA=0x002C, - KEY_MINUS=0x002D, - KEY_PERIOD=0x002E, - KEY_SLASH=0x002F, - KEY_0=0x0030, - KEY_1=0x0031, - KEY_2=0x0032, - KEY_3=0x0033, - KEY_4=0x0034, - KEY_5=0x0035, - KEY_6=0x0036, - KEY_7=0x0037, - KEY_8=0x0038, - KEY_9=0x0039, - KEY_COLON=0x003A, - KEY_SEMICOLON=0x003B, - KEY_LESS=0x003C, - KEY_EQUAL=0x003D, - KEY_GREATER=0x003E, - KEY_QUESTION=0x003F, - KEY_AT=0x0040, - KEY_A=0x0041, - KEY_B=0x0042, - KEY_C=0x0043, - KEY_D=0x0044, - KEY_E=0x0045, - KEY_F=0x0046, - KEY_G=0x0047, - KEY_H=0x0048, - KEY_I=0x0049, - KEY_J=0x004A, - KEY_K=0x004B, - KEY_L=0x004C, - KEY_M=0x004D, - KEY_N=0x004E, - KEY_O=0x004F, - KEY_P=0x0050, - KEY_Q=0x0051, - KEY_R=0x0052, - KEY_S=0x0053, - KEY_T=0x0054, - KEY_U=0x0055, - KEY_V=0x0056, - KEY_W=0x0057, - KEY_X=0x0058, - KEY_Y=0x0059, - KEY_Z=0x005A, - KEY_BRACKETLEFT=0x005B, - KEY_BACKSLASH=0x005C, - KEY_BRACKETRIGHT=0x005D, - KEY_ASCIICIRCUM=0x005E, - KEY_UNDERSCORE=0x005F, - KEY_QUOTELEFT=0x0060, - KEY_BRACELEFT=0x007B, - KEY_BAR=0x007C, - KEY_BRACERIGHT=0x007D, - KEY_ASCIITILDE=0x007E, - KEY_NOBREAKSPACE=0x00A0, - KEY_EXCLAMDOWN=0x00A1, - KEY_CENT=0x00A2, - KEY_STERLING=0x00A3, - KEY_CURRENCY=0x00A4, - KEY_YEN=0x00A5, - KEY_BROKENBAR=0x00A6, - KEY_SECTION=0x00A7, - KEY_DIAERESIS=0x00A8, - KEY_COPYRIGHT=0x00A9, - KEY_ORDFEMININE=0x00AA, - KEY_GUILLEMOTLEFT=0x00AB, - KEY_NOTSIGN=0x00AC, - KEY_HYPHEN=0x00AD, - KEY_REGISTERED=0x00AE, - KEY_MACRON=0x00AF, - KEY_DEGREE=0x00B0, - KEY_PLUSMINUS=0x00B1, - KEY_TWOSUPERIOR=0x00B2, - KEY_THREESUPERIOR=0x00B3, - KEY_ACUTE=0x00B4, - KEY_MU=0x00B5, - KEY_PARAGRAPH=0x00B6, - KEY_PERIODCENTERED=0x00B7, - KEY_CEDILLA=0x00B8, - KEY_ONESUPERIOR=0x00B9, - KEY_MASCULINE=0x00BA, - KEY_GUILLEMOTRIGHT=0x00BB, - KEY_ONEQUARTER=0x00BC, - KEY_ONEHALF=0x00BD, - KEY_THREEQUARTERS=0x00BE, - KEY_QUESTIONDOWN=0x00BF, - KEY_AGRAVE=0x00C0, - KEY_AACUTE=0x00C1, - KEY_ACIRCUMFLEX=0x00C2, - KEY_ATILDE=0x00C3, - KEY_ADIAERESIS=0x00C4, - KEY_ARING=0x00C5, - KEY_AE=0x00C6, - KEY_CCEDILLA=0x00C7, - KEY_EGRAVE=0x00C8, - KEY_EACUTE=0x00C9, - KEY_ECIRCUMFLEX=0x00CA, - KEY_EDIAERESIS=0x00CB, - KEY_IGRAVE=0x00CC, - KEY_IACUTE=0x00CD, - KEY_ICIRCUMFLEX=0x00CE, - KEY_IDIAERESIS=0x00CF, - KEY_ETH=0x00D0, - KEY_NTILDE=0x00D1, - KEY_OGRAVE=0x00D2, - KEY_OACUTE=0x00D3, - KEY_OCIRCUMFLEX=0x00D4, - KEY_OTILDE=0x00D5, - KEY_ODIAERESIS=0x00D6, - KEY_MULTIPLY=0x00D7, - KEY_OOBLIQUE=0x00D8, - KEY_UGRAVE=0x00D9, - KEY_UACUTE=0x00DA, - KEY_UCIRCUMFLEX=0x00DB, - KEY_UDIAERESIS=0x00DC, - KEY_YACUTE=0x00DD, - KEY_THORN=0x00DE, - KEY_SSHARP=0x00DF, - - KEY_DIVISION=0x00F7, - KEY_YDIAERESIS=0x00FF, + KEY_SPACE = 0x0020, + KEY_EXCLAM = 0x0021, + KEY_QUOTEDBL = 0x0022, + KEY_NUMBERSIGN = 0x0023, + KEY_DOLLAR = 0x0024, + KEY_PERCENT = 0x0025, + KEY_AMPERSAND = 0x0026, + KEY_APOSTROPHE = 0x0027, + KEY_PARENLEFT = 0x0028, + KEY_PARENRIGHT = 0x0029, + KEY_ASTERISK = 0x002A, + KEY_PLUS = 0x002B, + KEY_COMMA = 0x002C, + KEY_MINUS = 0x002D, + KEY_PERIOD = 0x002E, + KEY_SLASH = 0x002F, + KEY_0 = 0x0030, + KEY_1 = 0x0031, + KEY_2 = 0x0032, + KEY_3 = 0x0033, + KEY_4 = 0x0034, + KEY_5 = 0x0035, + KEY_6 = 0x0036, + KEY_7 = 0x0037, + KEY_8 = 0x0038, + KEY_9 = 0x0039, + KEY_COLON = 0x003A, + KEY_SEMICOLON = 0x003B, + KEY_LESS = 0x003C, + KEY_EQUAL = 0x003D, + KEY_GREATER = 0x003E, + KEY_QUESTION = 0x003F, + KEY_AT = 0x0040, + KEY_A = 0x0041, + KEY_B = 0x0042, + KEY_C = 0x0043, + KEY_D = 0x0044, + KEY_E = 0x0045, + KEY_F = 0x0046, + KEY_G = 0x0047, + KEY_H = 0x0048, + KEY_I = 0x0049, + KEY_J = 0x004A, + KEY_K = 0x004B, + KEY_L = 0x004C, + KEY_M = 0x004D, + KEY_N = 0x004E, + KEY_O = 0x004F, + KEY_P = 0x0050, + KEY_Q = 0x0051, + KEY_R = 0x0052, + KEY_S = 0x0053, + KEY_T = 0x0054, + KEY_U = 0x0055, + KEY_V = 0x0056, + KEY_W = 0x0057, + KEY_X = 0x0058, + KEY_Y = 0x0059, + KEY_Z = 0x005A, + KEY_BRACKETLEFT = 0x005B, + KEY_BACKSLASH = 0x005C, + KEY_BRACKETRIGHT = 0x005D, + KEY_ASCIICIRCUM = 0x005E, + KEY_UNDERSCORE = 0x005F, + KEY_QUOTELEFT = 0x0060, + KEY_BRACELEFT = 0x007B, + KEY_BAR = 0x007C, + KEY_BRACERIGHT = 0x007D, + KEY_ASCIITILDE = 0x007E, + KEY_NOBREAKSPACE = 0x00A0, + KEY_EXCLAMDOWN = 0x00A1, + KEY_CENT = 0x00A2, + KEY_STERLING = 0x00A3, + KEY_CURRENCY = 0x00A4, + KEY_YEN = 0x00A5, + KEY_BROKENBAR = 0x00A6, + KEY_SECTION = 0x00A7, + KEY_DIAERESIS = 0x00A8, + KEY_COPYRIGHT = 0x00A9, + KEY_ORDFEMININE = 0x00AA, + KEY_GUILLEMOTLEFT = 0x00AB, + KEY_NOTSIGN = 0x00AC, + KEY_HYPHEN = 0x00AD, + KEY_REGISTERED = 0x00AE, + KEY_MACRON = 0x00AF, + KEY_DEGREE = 0x00B0, + KEY_PLUSMINUS = 0x00B1, + KEY_TWOSUPERIOR = 0x00B2, + KEY_THREESUPERIOR = 0x00B3, + KEY_ACUTE = 0x00B4, + KEY_MU = 0x00B5, + KEY_PARAGRAPH = 0x00B6, + KEY_PERIODCENTERED = 0x00B7, + KEY_CEDILLA = 0x00B8, + KEY_ONESUPERIOR = 0x00B9, + KEY_MASCULINE = 0x00BA, + KEY_GUILLEMOTRIGHT = 0x00BB, + KEY_ONEQUARTER = 0x00BC, + KEY_ONEHALF = 0x00BD, + KEY_THREEQUARTERS = 0x00BE, + KEY_QUESTIONDOWN = 0x00BF, + KEY_AGRAVE = 0x00C0, + KEY_AACUTE = 0x00C1, + KEY_ACIRCUMFLEX = 0x00C2, + KEY_ATILDE = 0x00C3, + KEY_ADIAERESIS = 0x00C4, + KEY_ARING = 0x00C5, + KEY_AE = 0x00C6, + KEY_CCEDILLA = 0x00C7, + KEY_EGRAVE = 0x00C8, + KEY_EACUTE = 0x00C9, + KEY_ECIRCUMFLEX = 0x00CA, + KEY_EDIAERESIS = 0x00CB, + KEY_IGRAVE = 0x00CC, + KEY_IACUTE = 0x00CD, + KEY_ICIRCUMFLEX = 0x00CE, + KEY_IDIAERESIS = 0x00CF, + KEY_ETH = 0x00D0, + KEY_NTILDE = 0x00D1, + KEY_OGRAVE = 0x00D2, + KEY_OACUTE = 0x00D3, + KEY_OCIRCUMFLEX = 0x00D4, + KEY_OTILDE = 0x00D5, + KEY_ODIAERESIS = 0x00D6, + KEY_MULTIPLY = 0x00D7, + KEY_OOBLIQUE = 0x00D8, + KEY_UGRAVE = 0x00D9, + KEY_UACUTE = 0x00DA, + KEY_UCIRCUMFLEX = 0x00DB, + KEY_UDIAERESIS = 0x00DC, + KEY_YACUTE = 0x00DD, + KEY_THORN = 0x00DE, + KEY_SSHARP = 0x00DF, + KEY_DIVISION = 0x00F7, + KEY_YDIAERESIS = 0x00FF, }; - enum KeyModifierMask { - KEY_CODE_MASK=((1<<25)-1), ///< Apply this mask to any keycode to remove modifiers. - KEY_MODIFIER_MASK=(0xFF<<24), ///< Apply this mask to isolate modifiers. - KEY_MASK_SHIFT = (1<<25), - KEY_MASK_ALT = (1<<26), - KEY_MASK_META = (1<<27), - KEY_MASK_CTRL = (1<<28), + KEY_CODE_MASK = ((1 << 25) - 1), ///< Apply this mask to any keycode to remove modifiers. + KEY_MODIFIER_MASK = (0xFF << 24), ///< Apply this mask to isolate modifiers. + KEY_MASK_SHIFT = (1 << 25), + KEY_MASK_ALT = (1 << 26), + KEY_MASK_META = (1 << 27), + KEY_MASK_CTRL = (1 << 28), #ifdef APPLE_STYLE_KEYS KEY_MASK_CMD = KEY_MASK_META, #else KEY_MASK_CMD = KEY_MASK_CTRL, #endif - KEY_MASK_KPAD = (1<<29), - KEY_MASK_GROUP_SWITCH = (1<<30) + KEY_MASK_KPAD = (1 << 29), + KEY_MASK_GROUP_SWITCH = (1 << 30) // bit 31 can't be used because variant uses regular 32 bits int as datatype }; String keycode_get_string(uint32_t p_code); bool keycode_has_unicode(uint32_t p_unicode); -int find_keycode(const String& p_code); +int find_keycode(const String &p_code); int keycode_get_count(); int keycode_get_value_by_index(int p_index); -const char* keycode_get_name_by_index(int p_index); +const char *keycode_get_name_by_index(int p_index); int latin_keyboard_keycode_convert(int p_keycode); #endif diff --git a/core/os/main_loop.cpp b/core/os/main_loop.cpp index dcda8e8952..644536d940 100644 --- a/core/os/main_loop.cpp +++ b/core/os/main_loop.cpp @@ -31,20 +31,20 @@ void MainLoop::_bind_methods() { - ClassDB::bind_method(D_METHOD("input_event","ev"),&MainLoop::input_event); - ClassDB::bind_method(D_METHOD("input_text","text"),&MainLoop::input_text); - ClassDB::bind_method(D_METHOD("init"),&MainLoop::init); - ClassDB::bind_method(D_METHOD("iteration","delta"),&MainLoop::iteration); - ClassDB::bind_method(D_METHOD("idle","delta"),&MainLoop::idle); - ClassDB::bind_method(D_METHOD("finish"),&MainLoop::finish); - - BIND_VMETHOD( MethodInfo("_input_event",PropertyInfo(Variant::INPUT_EVENT,"ev")) ); - BIND_VMETHOD( MethodInfo("_input_text",PropertyInfo(Variant::STRING,"text")) ); - BIND_VMETHOD( MethodInfo("_initialize") ); - BIND_VMETHOD( MethodInfo("_iteration",PropertyInfo(Variant::REAL,"delta")) ); - BIND_VMETHOD( MethodInfo("_idle",PropertyInfo(Variant::REAL,"delta")) ); - BIND_VMETHOD( MethodInfo("_drop_files",PropertyInfo(Variant::POOL_STRING_ARRAY,"files"),PropertyInfo(Variant::INT,"screen")) ); - BIND_VMETHOD( MethodInfo("_finalize") ); + ClassDB::bind_method(D_METHOD("input_event", "ev"), &MainLoop::input_event); + ClassDB::bind_method(D_METHOD("input_text", "text"), &MainLoop::input_text); + ClassDB::bind_method(D_METHOD("init"), &MainLoop::init); + ClassDB::bind_method(D_METHOD("iteration", "delta"), &MainLoop::iteration); + ClassDB::bind_method(D_METHOD("idle", "delta"), &MainLoop::idle); + ClassDB::bind_method(D_METHOD("finish"), &MainLoop::finish); + + BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::INPUT_EVENT, "ev"))); + BIND_VMETHOD(MethodInfo("_input_text", PropertyInfo(Variant::STRING, "text"))); + BIND_VMETHOD(MethodInfo("_initialize")); + BIND_VMETHOD(MethodInfo("_iteration", PropertyInfo(Variant::REAL, "delta"))); + BIND_VMETHOD(MethodInfo("_idle", PropertyInfo(Variant::REAL, "delta"))); + BIND_VMETHOD(MethodInfo("_drop_files", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen"))); + BIND_VMETHOD(MethodInfo("_finalize")); BIND_CONSTANT(NOTIFICATION_WM_MOUSE_ENTER); BIND_CONSTANT(NOTIFICATION_WM_MOUSE_EXIT); @@ -53,36 +53,29 @@ void MainLoop::_bind_methods() { BIND_CONSTANT(NOTIFICATION_WM_QUIT_REQUEST); BIND_CONSTANT(NOTIFICATION_WM_UNFOCUS_REQUEST); BIND_CONSTANT(NOTIFICATION_OS_MEMORY_WARNING); - }; -void MainLoop::set_init_script(const Ref<Script>& p_init_script) { +void MainLoop::set_init_script(const Ref<Script> &p_init_script) { - init_script=p_init_script; + init_script = p_init_script; } MainLoop::MainLoop() { } - -MainLoop::~MainLoop() -{ +MainLoop::~MainLoop() { } - - -void MainLoop::input_text( const String& p_text ) { +void MainLoop::input_text(const String &p_text) { if (get_script_instance()) - get_script_instance()->call("_input_text",p_text); - + get_script_instance()->call("_input_text", p_text); } -void MainLoop::input_event( const InputEvent& p_event ) { +void MainLoop::input_event(const InputEvent &p_event) { if (get_script_instance()) - get_script_instance()->call("_input_event",p_event); - + get_script_instance()->call("_input_event", p_event); } void MainLoop::init() { @@ -92,30 +85,26 @@ void MainLoop::init() { if (get_script_instance()) get_script_instance()->call("_initialize"); - } bool MainLoop::iteration(float p_time) { if (get_script_instance()) - return get_script_instance()->call("_iteration",p_time); + return get_script_instance()->call("_iteration", p_time); return false; - } bool MainLoop::idle(float p_time) { if (get_script_instance()) - return get_script_instance()->call("_idle",p_time); + return get_script_instance()->call("_idle", p_time); return false; } -void MainLoop::drop_files(const Vector<String>& p_files,int p_from_screen) { - +void MainLoop::drop_files(const Vector<String> &p_files, int p_from_screen) { if (get_script_instance()) - get_script_instance()->call("_drop_files",p_files,p_from_screen); - + get_script_instance()->call("_drop_files", p_files, p_from_screen); } void MainLoop::finish() { @@ -124,7 +113,4 @@ void MainLoop::finish() { get_script_instance()->call("_finalize"); set_script(RefPtr()); //clear script } - - } - diff --git a/core/os/main_loop.h b/core/os/main_loop.h index 456a6be4d3..a33aeb9762 100644 --- a/core/os/main_loop.h +++ b/core/os/main_loop.h @@ -37,15 +37,15 @@ */ class MainLoop : public Object { - GDCLASS( MainLoop, Object ); + GDCLASS(MainLoop, Object); OBJ_CATEGORY("Main Loop"); Ref<Script> init_script; + protected: static void _bind_methods(); public: - enum { NOTIFICATION_WM_MOUSE_ENTER = 2, NOTIFICATION_WM_MOUSE_EXIT = 3, @@ -58,22 +58,20 @@ public: NOTIFICATION_TRANSLATION_CHANGED = 10, }; - virtual void input_event( const InputEvent& p_event ); - virtual void input_text( const String& p_text ); + virtual void input_event(const InputEvent &p_event); + virtual void input_text(const String &p_text); virtual void init(); virtual bool iteration(float p_time); virtual bool idle(float p_time); virtual void finish(); - virtual void drop_files(const Vector<String>& p_files,int p_from_screen=0); + virtual void drop_files(const Vector<String> &p_files, int p_from_screen = 0); - void set_init_script(const Ref<Script>& p_init_script); + void set_init_script(const Ref<Script> &p_init_script); MainLoop(); virtual ~MainLoop(); - - }; #endif diff --git a/core/os/memory.cpp b/core/os/memory.cpp index 37a523b763..b6866561fc 100644 --- a/core/os/memory.cpp +++ b/core/os/memory.cpp @@ -27,19 +27,17 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "memory.h" -#include "error_macros.h" #include "copymem.h" +#include "error_macros.h" #include <stdio.h> #include <stdlib.h> +void *operator new(size_t p_size, const char *p_description) { - -void * operator new(size_t p_size,const char *p_description) { - - return Memory::alloc_static( p_size, false ); + return Memory::alloc_static(p_size, false); } -void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)) { +void *operator new(size_t p_size, void *(*p_allocfunc)(size_t p_size)) { return p_allocfunc(p_size); } @@ -47,38 +45,36 @@ void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)) { #include <stdio.h> #ifdef DEBUG_ENABLED -size_t Memory::mem_usage=0; -size_t Memory::max_usage=0; +size_t Memory::mem_usage = 0; +size_t Memory::max_usage = 0; #endif -size_t Memory::alloc_count=0; - - -void * Memory::alloc_static(size_t p_bytes,bool p_pad_align) { +size_t Memory::alloc_count = 0; +void *Memory::alloc_static(size_t p_bytes, bool p_pad_align) { #ifdef DEBUG_ENABLED - bool prepad=true; + bool prepad = true; #else - bool prepad=p_pad_align; + bool prepad = p_pad_align; #endif - void * mem = malloc( p_bytes + (prepad?PAD_ALIGN:0)); + void *mem = malloc(p_bytes + (prepad ? PAD_ALIGN : 0)); alloc_count++; - ERR_FAIL_COND_V(!mem,NULL); + ERR_FAIL_COND_V(!mem, NULL); if (prepad) { - uint64_t *s = (uint64_t*)mem; - *s=p_bytes; + uint64_t *s = (uint64_t *)mem; + *s = p_bytes; - uint8_t *s8 = (uint8_t*)mem; + uint8_t *s8 = (uint8_t *)mem; #ifdef DEBUG_ENABLED - mem_usage+=p_bytes; - if (mem_usage>max_usage) { - max_usage=mem_usage; + mem_usage += p_bytes; + if (mem_usage > max_usage) { + max_usage = mem_usage; } #endif return s8 + PAD_ALIGN; @@ -87,74 +83,74 @@ void * Memory::alloc_static(size_t p_bytes,bool p_pad_align) { } } -void * Memory::realloc_static(void *p_memory,size_t p_bytes,bool p_pad_align) { +void *Memory::realloc_static(void *p_memory, size_t p_bytes, bool p_pad_align) { - if (p_memory==NULL) { - return alloc_static(p_bytes,p_pad_align); + if (p_memory == NULL) { + return alloc_static(p_bytes, p_pad_align); } - uint8_t *mem = (uint8_t*)p_memory; + uint8_t *mem = (uint8_t *)p_memory; #ifdef DEBUG_ENABLED - bool prepad=true; + bool prepad = true; #else - bool prepad=p_pad_align; + bool prepad = p_pad_align; #endif if (prepad) { - mem-=PAD_ALIGN; - uint64_t *s = (uint64_t*)mem; + mem -= PAD_ALIGN; + uint64_t *s = (uint64_t *)mem; #ifdef DEBUG_ENABLED - mem_usage-=*s; - mem_usage+=p_bytes; + mem_usage -= *s; + mem_usage += p_bytes; #endif - if (p_bytes==0) { + if (p_bytes == 0) { free(mem); return NULL; } else { - *s=p_bytes; + *s = p_bytes; - mem = (uint8_t*)realloc(mem,p_bytes+PAD_ALIGN); - ERR_FAIL_COND_V(!mem,NULL); + mem = (uint8_t *)realloc(mem, p_bytes + PAD_ALIGN); + ERR_FAIL_COND_V(!mem, NULL); - s = (uint64_t*)mem; + s = (uint64_t *)mem; - *s=p_bytes; + *s = p_bytes; - return mem+PAD_ALIGN; + return mem + PAD_ALIGN; } } else { - mem = (uint8_t*)realloc(mem,p_bytes); + mem = (uint8_t *)realloc(mem, p_bytes); - ERR_FAIL_COND_V(mem==NULL && p_bytes>0,NULL); + ERR_FAIL_COND_V(mem == NULL && p_bytes > 0, NULL); return mem; } } -void Memory::free_static(void *p_ptr,bool p_pad_align) { +void Memory::free_static(void *p_ptr, bool p_pad_align) { - ERR_FAIL_COND(p_ptr==NULL); + ERR_FAIL_COND(p_ptr == NULL); - uint8_t *mem = (uint8_t*)p_ptr; + uint8_t *mem = (uint8_t *)p_ptr; #ifdef DEBUG_ENABLED - bool prepad=true; + bool prepad = true; #else - bool prepad=p_pad_align; + bool prepad = p_pad_align; #endif alloc_count--; if (prepad) { - mem-=PAD_ALIGN; - uint64_t *s = (uint64_t*)mem; + mem -= PAD_ALIGN; + uint64_t *s = (uint64_t *)mem; #ifdef DEBUG_ENABLED - mem_usage-=*s; + mem_usage -= *s; #endif free(mem); @@ -162,23 +158,21 @@ void Memory::free_static(void *p_ptr,bool p_pad_align) { free(mem); } - } size_t Memory::get_mem_available() { return 0xFFFFFFFFFFFFF; - } -size_t Memory::get_mem_usage(){ +size_t Memory::get_mem_usage() { #ifdef DEBUG_ENABLED return mem_usage; #else return 0; #endif } -size_t Memory::get_mem_max_usage(){ +size_t Memory::get_mem_max_usage() { #ifdef DEBUG_ENABLED return max_usage; #else @@ -186,16 +180,12 @@ size_t Memory::get_mem_max_usage(){ #endif } - - - _GlobalNil::_GlobalNil() { - color=1; - left=this; - right=this; - parent=this; + color = 1; + left = this; + right = this; + parent = this; } _GlobalNil _GlobalNilClass::_nil; - diff --git a/core/os/memory.h b/core/os/memory.h index 49424037ff..b788068f53 100644 --- a/core/os/memory.h +++ b/core/os/memory.h @@ -29,9 +29,8 @@ #ifndef MEMORY_H #define MEMORY_H -#include <stddef.h> #include "safe_refcount.h" - +#include <stddef.h> /** @author Juan Linietsky <reduzio@gmail.com> @@ -41,9 +40,7 @@ #define PAD_ALIGN 16 //must always be greater than this at much #endif - - -class Memory{ +class Memory { Memory(); #ifdef DEBUG_ENABLED @@ -54,72 +51,65 @@ class Memory{ static size_t alloc_count; public: - - static void * alloc_static(size_t p_bytes,bool p_pad_align=false); - static void * realloc_static(void *p_memory,size_t p_bytes,bool p_pad_align=false); - static void free_static(void *p_ptr,bool p_pad_align=false); + static void *alloc_static(size_t p_bytes, bool p_pad_align = false); + static void *realloc_static(void *p_memory, size_t p_bytes, bool p_pad_align = false); + static void free_static(void *p_ptr, bool p_pad_align = false); static size_t get_mem_available(); static size_t get_mem_usage(); static size_t get_mem_max_usage(); - - }; class DefaultAllocator { public: _FORCE_INLINE_ static void *alloc(size_t p_memory) { return Memory::alloc_static(p_memory, false); } - _FORCE_INLINE_ static void free(void *p_ptr) { return Memory::free_static(p_ptr,false); } - + _FORCE_INLINE_ static void free(void *p_ptr) { return Memory::free_static(p_ptr, false); } }; +void *operator new(size_t p_size, const char *p_description); ///< operator new that takes a description and uses MemoryStaticPool +void *operator new(size_t p_size, void *(*p_allocfunc)(size_t p_size)); ///< operator new that takes a description and uses MemoryStaticPool -void * operator new(size_t p_size,const char *p_description); ///< operator new that takes a description and uses MemoryStaticPool -void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)); ///< operator new that takes a description and uses MemoryStaticPool - -void * operator new(size_t p_size,void *p_pointer,size_t check, const char *p_description); ///< operator new that takes a description and uses a pointer to the preallocated memory +void *operator new(size_t p_size, void *p_pointer, size_t check, const char *p_description); ///< operator new that takes a description and uses a pointer to the preallocated memory #define memalloc(m_size) Memory::alloc_static(m_size) -#define memrealloc(m_mem,m_size) Memory::realloc_static(m_mem,m_size) +#define memrealloc(m_mem, m_size) Memory::realloc_static(m_mem, m_size) #define memfree(m_size) Memory::free_static(m_size) - _ALWAYS_INLINE_ void postinitialize_handler(void *) {} - -template<class T> +template <class T> _ALWAYS_INLINE_ T *_post_initialize(T *p_obj) { postinitialize_handler(p_obj); return p_obj; } -#define memnew(m_class) _post_initialize(new("") m_class) +#define memnew(m_class) _post_initialize(new ("") m_class) -_ALWAYS_INLINE_ void * operator new(size_t p_size,void *p_pointer,size_t check, const char *p_description) { +_ALWAYS_INLINE_ void *operator new(size_t p_size, void *p_pointer, size_t check, const char *p_description) { //void *failptr=0; //ERR_FAIL_COND_V( check < p_size , failptr); /** bug, or strange compiler, most likely */ return p_pointer; } +#define memnew_allocator(m_class, m_allocator) _post_initialize(new (m_allocator::alloc) m_class) +#define memnew_placement(m_placement, m_class) _post_initialize(new (m_placement, sizeof(m_class), "") m_class) -#define memnew_allocator(m_class,m_allocator) _post_initialize(new(m_allocator::alloc) m_class) -#define memnew_placement(m_placement,m_class) _post_initialize(new(m_placement,sizeof(m_class),"") m_class) - - -_ALWAYS_INLINE_ bool predelete_handler(void *) { return true; } +_ALWAYS_INLINE_ bool predelete_handler(void *) { + return true; +} -template<class T> +template <class T> void memdelete(T *p_class) { if (!predelete_handler(p_class)) return; // doesn't want to be deleted p_class->~T(); - Memory::free_static(p_class,false); + Memory::free_static(p_class, false); } -template<class T,class A> +template <class T, class A> void memdelete_allocator(T *p_class) { if (!predelete_handler(p_class)) @@ -128,33 +118,35 @@ void memdelete_allocator(T *p_class) { A::free(p_class); } -#define memdelete_notnull(m_v) { if (m_v) memdelete(m_v); } - -#define memnew_arr( m_class, m_count ) memnew_arr_template<m_class>(m_count) +#define memdelete_notnull(m_v) \ + { \ + if (m_v) memdelete(m_v); \ + } +#define memnew_arr(m_class, m_count) memnew_arr_template<m_class>(m_count) -template<typename T> -T* memnew_arr_template(size_t p_elements,const char *p_descr="") { +template <typename T> +T *memnew_arr_template(size_t p_elements, const char *p_descr = "") { - if (p_elements==0) + if (p_elements == 0) return 0; /** overloading operator new[] cannot be done , because it may not return the real allocated address (it may pad the 'element count' before the actual array). Because of that, it must be done by hand. This is the same strategy used by std::vector, and the PoolVector class, so it should be safe.*/ size_t len = sizeof(T) * p_elements; - uint64_t *mem = (uint64_t*)Memory::alloc_static( len , true ); - T *failptr=0; //get rid of a warning - ERR_FAIL_COND_V( !mem, failptr ); - *(mem-1)=p_elements; + uint64_t *mem = (uint64_t *)Memory::alloc_static(len, true); + T *failptr = 0; //get rid of a warning + ERR_FAIL_COND_V(!mem, failptr); + *(mem - 1) = p_elements; - T* elems = (T*)mem; + T *elems = (T *)mem; /* call operator new */ - for (size_t i=0;i<p_elements;i++) { - new(&elems[i],sizeof(T),p_descr) T; + for (size_t i = 0; i < p_elements; i++) { + new (&elems[i], sizeof(T), p_descr) T; } - return (T*)mem; + return (T *)mem; } /** @@ -162,28 +154,27 @@ T* memnew_arr_template(size_t p_elements,const char *p_descr="") { * an allocated-with memnew_arr() array */ -template<typename T> +template <typename T> size_t memarr_len(const T *p_class) { - uint64_t* ptr = (uint64_t*)p_class; - return *(ptr-1); + uint64_t *ptr = (uint64_t *)p_class; + return *(ptr - 1); } -template<typename T> +template <typename T> void memdelete_arr(T *p_class) { - uint64_t* ptr = (uint64_t*)p_class; + uint64_t *ptr = (uint64_t *)p_class; - uint64_t elem_count = *(ptr-1); + uint64_t elem_count = *(ptr - 1); - for (uint64_t i=0;i<elem_count;i++) { + for (uint64_t i = 0; i < elem_count; i++) { p_class[i].~T(); }; - Memory::free_static(ptr,true); + Memory::free_static(ptr, true); } - struct _GlobalNil { int color; @@ -192,7 +183,6 @@ struct _GlobalNil { _GlobalNil *parent; _GlobalNil(); - }; struct _GlobalNilClass { @@ -200,6 +190,4 @@ struct _GlobalNilClass { static _GlobalNil _nil; }; - - #endif diff --git a/core/os/mutex.cpp b/core/os/mutex.cpp index acdcb492d9..cdc18effdd 100644 --- a/core/os/mutex.cpp +++ b/core/os/mutex.cpp @@ -30,24 +30,19 @@ #include "error_macros.h" #include <stddef.h> - - -Mutex* (*Mutex::create_func)(bool)=0; +Mutex *(*Mutex::create_func)(bool) = 0; Mutex *Mutex::create(bool p_recursive) { - ERR_FAIL_COND_V( !create_func, 0 ); + ERR_FAIL_COND_V(!create_func, 0); return create_func(p_recursive); } - Mutex::~Mutex() { - - } -Mutex *_global_mutex=NULL; +Mutex *_global_mutex = NULL; void _global_lock() { @@ -59,4 +54,3 @@ void _global_unlock() { if (_global_mutex) _global_mutex->unlock(); } - diff --git a/core/os/mutex.h b/core/os/mutex.h index a1004965bb..8ec4f573b7 100644 --- a/core/os/mutex.h +++ b/core/os/mutex.h @@ -31,7 +31,6 @@ #include "error_list.h" - /** * @class Mutex * @author Juan Linietsky @@ -41,18 +40,16 @@ * Lockp( mutex ); */ - class Mutex { protected: - static Mutex* (*create_func)(bool); + static Mutex *(*create_func)(bool); public: + virtual void lock() = 0; ///< Lock the mutex, block if locked by someone else + virtual void unlock() = 0; ///< Unlock the mutex, let other threads continue + virtual Error try_lock() = 0; ///< Attempt to lock the mutex, OK on success, ERROR means it can't lock. - virtual void lock()=0; ///< Lock the mutex, block if locked by someone else - virtual void unlock()=0; ///< Unlock the mutex, let other threads continue - virtual Error try_lock()=0; ///< Attempt to lock the mutex, OK on success, ERROR means it can't lock. - - static Mutex * create(bool p_recursive=true); ///< Create a mutex + static Mutex *create(bool p_recursive = true); ///< Create a mutex virtual ~Mutex(); }; @@ -60,11 +57,15 @@ public: class MutexLock { Mutex *mutex; -public: - - MutexLock(Mutex* p_mutex) { mutex=p_mutex; if (mutex) mutex->lock(); } - ~MutexLock() { if (mutex) mutex->unlock(); } +public: + MutexLock(Mutex *p_mutex) { + mutex = p_mutex; + if (mutex) mutex->lock(); + } + ~MutexLock() { + if (mutex) mutex->unlock(); + } }; #endif diff --git a/core/os/os.cpp b/core/os/os.cpp index 1d670b4466..03b48f4554 100644 --- a/core/os/os.cpp +++ b/core/os/os.cpp @@ -35,15 +35,16 @@ #include <stdarg.h> -OS* OS::singleton=NULL; +OS *OS::singleton = NULL; -OS* OS::get_singleton() { +OS *OS::get_singleton() { return singleton; } -uint32_t OS::get_ticks_msec() const -{ return get_ticks_usec()/1000; } +uint32_t OS::get_ticks_msec() const { + return get_ticks_usec() / 1000; +} uint64_t OS::get_splash_tick_msec() const { return _msec_splash; @@ -55,29 +56,27 @@ uint64_t OS::get_unix_time() const { uint64_t OS::get_system_time_secs() const { return 0; } -void OS::debug_break() { +void OS::debug_break(){ // something }; +void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) { -void OS::print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type) { - - const char* err_type; - switch(p_type) { - case ERR_ERROR: err_type="**ERROR**"; break; - case ERR_WARNING: err_type="**WARNING**"; break; - case ERR_SCRIPT: err_type="**SCRIPT ERROR**"; break; - case ERR_SHADER: err_type="**SHADER ERROR**"; break; + const char *err_type; + switch (p_type) { + case ERR_ERROR: err_type = "**ERROR**"; break; + case ERR_WARNING: err_type = "**WARNING**"; break; + case ERR_SCRIPT: err_type = "**SCRIPT ERROR**"; break; + case ERR_SHADER: err_type = "**SHADER ERROR**"; break; } if (p_rationale && *p_rationale) - print("%s: %s\n ",err_type,p_rationale); - print("%s: At: %s:%i:%s() - %s\n",err_type,p_file,p_line,p_function,p_code); + print("%s: %s\n ", err_type, p_rationale); + print("%s: At: %s:%i:%s() - %s\n", err_type, p_file, p_line, p_function, p_code); } -void OS::print(const char* p_format, ...) { - +void OS::print(const char *p_format, ...) { va_list argp; va_start(argp, p_format); @@ -87,7 +86,7 @@ void OS::print(const char* p_format, ...) { va_end(argp); }; -void OS::printerr(const char* p_format, ...) { +void OS::printerr(const char *p_format, ...) { va_list argp; va_start(argp, p_format); @@ -97,9 +96,8 @@ void OS::printerr(const char* p_format, ...) { va_end(argp); }; - void OS::set_keep_screen_on(bool p_enabled) { - _keep_screen_on=p_enabled; + _keep_screen_on = p_enabled; } bool OS::is_keep_screen_on() const { @@ -108,7 +106,7 @@ bool OS::is_keep_screen_on() const { void OS::set_low_processor_usage_mode(bool p_enabled) { - low_processor_usage_mode=p_enabled; + low_processor_usage_mode = p_enabled; } bool OS::is_in_low_processor_usage_mode() const { @@ -116,9 +114,9 @@ bool OS::is_in_low_processor_usage_mode() const { return low_processor_usage_mode; } -void OS::set_clipboard(const String& p_text) { +void OS::set_clipboard(const String &p_text) { - _local_clipboard=p_text; + _local_clipboard = p_text; } String OS::get_clipboard() const { @@ -135,41 +133,40 @@ int OS::get_process_ID() const { return -1; }; - bool OS::is_stdout_verbose() const { return _verbose_stdout; } -void OS::set_last_error(const char* p_error) { +void OS::set_last_error(const char *p_error) { GLOBAL_LOCK_FUNCTION - if (p_error==NULL) - p_error="Unknown Error"; + if (p_error == NULL) + p_error = "Unknown Error"; if (last_error) memfree(last_error); - last_error=NULL; - int len =0; - while(p_error[len++]); - - last_error=(char*)memalloc(len); - for(int i=0;i<len;i++) - last_error[i]=p_error[i]; + last_error = NULL; + int len = 0; + while (p_error[len++]) + ; + last_error = (char *)memalloc(len); + for (int i = 0; i < len; i++) + last_error[i] = p_error[i]; } const char *OS::get_last_error() const { GLOBAL_LOCK_FUNCTION - return last_error?last_error:""; + return last_error ? last_error : ""; } -void OS::dump_memory_to_file(const char* p_file) { +void OS::dump_memory_to_file(const char *p_file) { //Memory::dump_static_mem_to_file(p_file); } -static FileAccess *_OSPRF=NULL; +static FileAccess *_OSPRF = NULL; static void _OS_printres(Object *p_obj) { @@ -177,12 +174,11 @@ static void _OS_printres(Object *p_obj) { if (!res) return; - String str = itos(res->get_instance_ID())+String(res->get_class())+":"+String(res->get_name())+" - "+res->get_path(); + String str = itos(res->get_instance_ID()) + String(res->get_class()) + ":" + String(res->get_name()) + " - " + res->get_path(); if (_OSPRF) _OSPRF->store_line(str); else print_line(str); - } bool OS::has_virtual_keyboard() const { @@ -190,61 +186,56 @@ bool OS::has_virtual_keyboard() const { return false; } -void OS::show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect) { - +void OS::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) { } -void OS::hide_virtual_keyboard(){ - +void OS::hide_virtual_keyboard() { } void OS::print_all_resources(String p_to_file) { - ERR_FAIL_COND(p_to_file!="" && _OSPRF); - if (p_to_file!="") { + ERR_FAIL_COND(p_to_file != "" && _OSPRF); + if (p_to_file != "") { Error err; - _OSPRF=FileAccess::open(p_to_file,FileAccess::WRITE,&err); - if (err!=OK) { - _OSPRF=NULL; - ERR_FAIL_COND(err!=OK); + _OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err); + if (err != OK) { + _OSPRF = NULL; + ERR_FAIL_COND(err != OK); } } ObjectDB::debug_objects(_OS_printres); - if (p_to_file!="") { + if (p_to_file != "") { if (_OSPRF) memdelete(_OSPRF); - _OSPRF=NULL; + _OSPRF = NULL; } } void OS::print_resources_in_use(bool p_short) { - - ResourceCache::dump(NULL,p_short); + ResourceCache::dump(NULL, p_short); } -void OS::dump_resources_to_file(const char* p_file) { +void OS::dump_resources_to_file(const char *p_file) { ResourceCache::dump(p_file); } - void OS::clear_last_error() { GLOBAL_LOCK_FUNCTION if (last_error) memfree(last_error); - last_error=NULL; + last_error = NULL; } - void OS::set_no_window_mode(bool p_enable) { - _no_window=p_enable; + _no_window = p_enable; } bool OS::is_no_window_mode_enabled() const { @@ -258,7 +249,7 @@ int OS::get_exit_code() const { } void OS::set_exit_code(int p_code) { - _exit_code=p_code; + _exit_code = p_code; } String OS::get_locale() const { @@ -271,7 +262,6 @@ String OS::get_resource_dir() const { return GlobalConfig::get_singleton()->get_resource_path(); } - String OS::get_system_dir(SystemDir p_dir) const { return "."; @@ -280,8 +270,8 @@ String OS::get_system_dir(SystemDir p_dir) const { String OS::get_safe_application_name() const { String an = GlobalConfig::get_singleton()->get("application/name"); Vector<String> invalid_char = String("\\ / : * ? \" < > |").split(" "); - for (int i=0;i<invalid_char.size();i++) { - an = an.replace(invalid_char[i],"-"); + for (int i = 0; i < invalid_char.size(); i++) { + an = an.replace(invalid_char[i], "-"); } return an; } @@ -296,14 +286,14 @@ Error OS::shell_open(String p_uri) { }; // implement these with the canvas? -Error OS::dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object* p_obj, String p_callback) { +Error OS::dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object *p_obj, String p_callback) { while (true) { print("%ls\n--------\n%ls\n", p_title.c_str(), p_description.c_str()); - for (int i=0; i<p_buttons.size(); i++) { - if (i>0) print(", "); - print("%i=%ls", i+1, p_buttons[i].c_str()); + for (int i = 0; i < p_buttons.size(); i++) { + if (i > 0) print(", "); + print("%i=%ls", i + 1, p_buttons[i].c_str()); }; print("\n"); String res = get_stdin_string().strip_edges(); @@ -319,7 +309,7 @@ Error OS::dialog_show(String p_title, String p_description, Vector<String> p_but return OK; }; -Error OS::dialog_input_text(String p_title, String p_description, String p_partial, Object* p_obj, String p_callback) { +Error OS::dialog_input_text(String p_title, String p_description, String p_partial, Object *p_obj, String p_callback) { ERR_FAIL_COND_V(!p_obj, FAILED); ERR_FAIL_COND_V(p_callback == "", FAILED); @@ -340,7 +330,7 @@ int OS::get_static_memory_usage() const { return Memory::get_mem_usage(); } -int OS::get_dynamic_memory_usage() const{ +int OS::get_dynamic_memory_usage() const { return MemoryPool::total_memory; } @@ -350,7 +340,7 @@ int OS::get_static_memory_peak_usage() const { return Memory::get_mem_max_usage(); } -Error OS::set_cwd(const String& p_cwd) { +Error OS::set_cwd(const String &p_cwd) { return ERR_CANT_OPEN; } @@ -367,13 +357,11 @@ int OS::get_free_static_memory() const { } void OS::yield() { - - } void OS::set_screen_orientation(ScreenOrientation p_orientation) { - _orientation=p_orientation; + _orientation = p_orientation; } OS::ScreenOrientation OS::get_screen_orientation() const { @@ -381,7 +369,6 @@ OS::ScreenOrientation OS::get_screen_orientation() const { return (OS::ScreenOrientation)_orientation; } - void OS::_ensure_data_dir() { String dd = get_data_dir(); @@ -393,45 +380,35 @@ void OS::_ensure_data_dir() { da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = da->make_dir_recursive(dd); - if (err!=OK) { - ERR_EXPLAIN("Error attempting to create data dir: "+dd); + if (err != OK) { + ERR_EXPLAIN("Error attempting to create data dir: " + dd); } - ERR_FAIL_COND(err!=OK); + ERR_FAIL_COND(err != OK); memdelete(da); - - } -void OS::set_icon(const Image& p_icon) { - - +void OS::set_icon(const Image &p_icon) { } String OS::get_model_name() const { - return "GenericDevice"; + return "GenericDevice"; } - -void OS::set_cmdline(const char* p_execpath, const List<String>& p_args) { +void OS::set_cmdline(const char *p_execpath, const List<String> &p_args) { _execpath = p_execpath; _cmdline = p_args; }; void OS::release_rendering_thread() { - - } void OS::make_rendering_thread() { - - } void OS::swap_buffers() { - } String OS::get_unique_ID() const { @@ -454,20 +431,19 @@ bool OS::native_video_is_playing() const { return false; }; -void OS::native_video_pause() { +void OS::native_video_pause(){ }; -void OS::native_video_unpause() { +void OS::native_video_unpause(){ }; -void OS::native_video_stop() { +void OS::native_video_stop(){ }; void OS::set_mouse_mode(MouseMode p_mode) { - } bool OS::can_use_threads() const { @@ -479,19 +455,16 @@ bool OS::can_use_threads() const { #endif } -OS::MouseMode OS::get_mouse_mode() const{ +OS::MouseMode OS::get_mouse_mode() const { return MOUSE_MODE_VISIBLE; } - OS::LatinKeyboardVariant OS::get_latin_keyboard_variant() const { return LATIN_KEYBOARD_QWERTY; } - - bool OS::is_joy_known(int p_device) { return true; } @@ -501,18 +474,15 @@ String OS::get_joy_guid(int p_device) const { } void OS::set_context(int p_context) { - } void OS::set_use_vsync(bool p_enable) { - } -bool OS::is_vsync_enabled() const{ +bool OS::is_vsync_enabled() const { return true; } - PowerState OS::get_power_state() { return POWERSTATE_UNKNOWN; } @@ -524,26 +494,22 @@ int OS::get_power_percent_left() { } OS::OS() { - last_error=NULL; - singleton=this; - _keep_screen_on=true; // set default value to true, because this had been true before godot 2.0. - low_processor_usage_mode=false; - _verbose_stdout=false; - _no_window=false; - _exit_code=0; - _orientation=SCREEN_LANDSCAPE; - - _render_thread_mode=RENDER_THREAD_SAFE; - - - _allow_hidpi=true; + last_error = NULL; + singleton = this; + _keep_screen_on = true; // set default value to true, because this had been true before godot 2.0. + low_processor_usage_mode = false; + _verbose_stdout = false; + _no_window = false; + _exit_code = 0; + _orientation = SCREEN_LANDSCAPE; + + _render_thread_mode = RENDER_THREAD_SAFE; + + _allow_hidpi = true; Math::seed(1234567); } - OS::~OS() { - singleton=NULL; + singleton = NULL; } - - diff --git a/core/os/os.h b/core/os/os.h index 7c8100679a..46e57e5186 100644 --- a/core/os/os.h +++ b/core/os/os.h @@ -29,22 +29,21 @@ #ifndef OS_H #define OS_H -#include "ustring.h" -#include "list.h" -#include "vector.h" #include "engine.h" +#include "list.h" #include "os/main_loop.h" #include "power.h" +#include "ustring.h" +#include "vector.h" #include <stdarg.h> - /** @author Juan Linietsky <reduzio@gmail.com> */ class OS { - static OS* singleton; + static OS *singleton; String _execpath; List<String> _cmdline; bool _keep_screen_on; @@ -57,7 +56,6 @@ class OS { int _orientation; bool _allow_hidpi; - char *last_error; public: @@ -69,45 +67,51 @@ public: }; struct VideoMode { - int width,height; + int width, height; bool fullscreen; bool resizable; bool borderless_window; - float get_aspect() const { return (float)width/(float)height; } - VideoMode(int p_width=1024,int p_height=600,bool p_fullscreen=false, bool p_resizable = true,bool p_borderless_window=false) { width=p_width; height=p_height; fullscreen=p_fullscreen; resizable = p_resizable; borderless_window=p_borderless_window; } + float get_aspect() const { return (float)width / (float)height; } + VideoMode(int p_width = 1024, int p_height = 600, bool p_fullscreen = false, bool p_resizable = true, bool p_borderless_window = false) { + width = p_width; + height = p_height; + fullscreen = p_fullscreen; + resizable = p_resizable; + borderless_window = p_borderless_window; + } }; + protected: -friend class Main; + friend class Main; RenderThreadMode _render_thread_mode; // functions used by main to initialize/deintialize the OS - virtual int get_video_driver_count() const=0; - virtual const char * get_video_driver_name(int p_driver) const=0; + virtual int get_video_driver_count() const = 0; + virtual const char *get_video_driver_name(int p_driver) const = 0; - virtual VideoMode get_default_video_mode() const=0; + virtual VideoMode get_default_video_mode() const = 0; - virtual int get_audio_driver_count() const=0; - virtual const char * get_audio_driver_name(int p_driver) const=0; + virtual int get_audio_driver_count() const = 0; + virtual const char *get_audio_driver_name(int p_driver) const = 0; - virtual void initialize_core()=0; - virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver)=0; + virtual void initialize_core() = 0; + virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) = 0; - virtual void set_main_loop( MainLoop * p_main_loop )=0; - virtual void delete_main_loop()=0; + virtual void set_main_loop(MainLoop *p_main_loop) = 0; + virtual void delete_main_loop() = 0; - virtual void finalize()=0; - virtual void finalize_core()=0; + virtual void finalize() = 0; + virtual void finalize_core() = 0; - virtual void set_cmdline(const char* p_execpath, const List<String>& p_args); + virtual void set_cmdline(const char *p_execpath, const List<String> &p_args); void _ensure_data_dir(); public: - typedef int64_t ProcessID; - static OS* get_singleton(); + static OS *get_singleton(); enum ErrorType { ERR_ERROR, @@ -116,20 +120,18 @@ public: ERR_SHADER }; - virtual void print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type=ERR_ERROR); + virtual void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR); - virtual void print(const char *p_format, ... ); - virtual void printerr(const char *p_format, ... ); - virtual void vprint(const char* p_format, va_list p_list, bool p_stderr=false)=0; - virtual void alert(const String& p_alert,const String& p_title="ALERT!")=0; - virtual String get_stdin_string(bool p_block = true)=0; + virtual void print(const char *p_format, ...); + virtual void printerr(const char *p_format, ...); + virtual void vprint(const char *p_format, va_list p_list, bool p_stderr = false) = 0; + virtual void alert(const String &p_alert, const String &p_title = "ALERT!") = 0; + virtual String get_stdin_string(bool p_block = true) = 0; - virtual void set_last_error(const char* p_error); + virtual void set_last_error(const char *p_error); virtual const char *get_last_error() const; virtual void clear_last_error(); - - enum MouseMode { MOUSE_MODE_VISIBLE, MOUSE_MODE_HIDDEN, @@ -140,30 +142,28 @@ public: virtual void set_mouse_mode(MouseMode p_mode); virtual MouseMode get_mouse_mode() const; + virtual void warp_mouse_pos(const Point2 &p_to) {} + virtual Point2 get_mouse_pos() const = 0; + virtual int get_mouse_button_state() const = 0; + virtual void set_window_title(const String &p_title) = 0; - virtual void warp_mouse_pos(const Point2& p_to) {} - virtual Point2 get_mouse_pos() const=0; - virtual int get_mouse_button_state() const=0; - virtual void set_window_title(const String& p_title)=0; - - virtual void set_clipboard(const String& p_text); + virtual void set_clipboard(const String &p_text); virtual String get_clipboard() const; - virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0)=0; - virtual VideoMode get_video_mode(int p_screen=0) const=0; - virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const=0; + virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0) = 0; + virtual VideoMode get_video_mode(int p_screen = 0) const = 0; + virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const = 0; - - virtual int get_screen_count() const{ return 1; } + virtual int get_screen_count() const { return 1; } virtual int get_current_screen() const { return 0; } - virtual void set_current_screen(int p_screen) { } - virtual Point2 get_screen_position(int p_screen=0) const { return Point2(); } - virtual Size2 get_screen_size(int p_screen=0) const { return get_window_size(); } - virtual int get_screen_dpi(int p_screen=0) const { return 72; } + virtual void set_current_screen(int p_screen) {} + virtual Point2 get_screen_position(int p_screen = 0) const { return Point2(); } + virtual Size2 get_screen_size(int p_screen = 0) const { return get_window_size(); } + virtual int get_screen_dpi(int p_screen = 0) const { return 72; } virtual Point2 get_window_position() const { return Vector2(); } - virtual void set_window_position(const Point2& p_position) {} - virtual Size2 get_window_size() const=0; - virtual void set_window_size(const Size2 p_size){} + virtual void set_window_position(const Point2 &p_position) {} + virtual Size2 get_window_size() const = 0; + virtual void set_window_size(const Size2 p_size) {} virtual void set_window_fullscreen(bool p_enabled) {} virtual bool is_window_fullscreen() const { return true; } virtual void set_window_resizable(bool p_enabled) {} @@ -172,12 +172,11 @@ public: virtual bool is_window_minimized() const { return false; } virtual void set_window_maximized(bool p_enabled) {} virtual bool is_window_maximized() const { return true; } - virtual void request_attention() { } + virtual void request_attention() {} virtual void set_borderless_window(int p_borderless) {} virtual bool get_borderless_window() { return 0; } - virtual void set_keep_screen_on(bool p_enabled); virtual bool is_keep_screen_on() const; virtual void set_low_processor_usage_mode(bool p_enabled); @@ -185,22 +184,21 @@ public: virtual String get_installed_templates_path() const { return ""; } virtual String get_executable_path() const; - virtual Error execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id=NULL,String* r_pipe=NULL,int *r_exitcode=NULL)=0; - virtual Error kill(const ProcessID& p_pid)=0; + virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL) = 0; + virtual Error kill(const ProcessID &p_pid) = 0; virtual int get_process_ID() const; virtual Error shell_open(String p_uri); - virtual Error set_cwd(const String& p_cwd); + virtual Error set_cwd(const String &p_cwd); - virtual bool has_environment(const String& p_var) const=0; - virtual String get_environment(const String& p_var) const=0; + virtual bool has_environment(const String &p_var) const = 0; + virtual String get_environment(const String &p_var) const = 0; - virtual String get_name()=0; + virtual String get_name() = 0; virtual List<String> get_cmdline_args() const { return _cmdline; } - virtual String get_model_name() const; - - virtual MainLoop *get_main_loop() const=0; + virtual String get_model_name() const; + virtual MainLoop *get_main_loop() const = 0; virtual void yield(); @@ -252,18 +250,17 @@ public: String name; }; - virtual Date get_date(bool local=false) const=0; - virtual Time get_time(bool local=false) const=0; - virtual TimeZoneInfo get_time_zone_info() const=0; + virtual Date get_date(bool local = false) const = 0; + virtual Time get_time(bool local = false) const = 0; + virtual TimeZoneInfo get_time_zone_info() const = 0; virtual uint64_t get_unix_time() const; virtual uint64_t get_system_time_secs() const; - virtual void delay_usec(uint32_t p_usec) const=0; - virtual uint64_t get_ticks_usec() const=0; + virtual void delay_usec(uint32_t p_usec) const = 0; + virtual uint64_t get_ticks_usec() const = 0; uint32_t get_ticks_msec() const; uint64_t get_splash_tick_msec() const; - virtual bool can_draw() const = 0; bool is_stdout_verbose() const; @@ -289,18 +286,17 @@ public: CURSOR_MAX }; - virtual bool has_virtual_keyboard() const; - virtual void show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect=Rect2()); + virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2()); virtual void hide_virtual_keyboard(); - virtual void set_cursor_shape(CursorShape p_shape)=0; + virtual void set_cursor_shape(CursorShape p_shape) = 0; virtual bool get_swap_ok_cancel() { return false; } - virtual void dump_memory_to_file(const char* p_file); - virtual void dump_resources_to_file(const char* p_file); - virtual void print_resources_in_use(bool p_short=false); - virtual void print_all_resources(String p_to_file=""); + virtual void dump_memory_to_file(const char *p_file); + virtual void dump_resources_to_file(const char *p_file); + virtual void print_resources_in_use(bool p_short = false); + virtual void print_all_resources(String p_to_file = ""); virtual int get_static_memory_usage() const; virtual int get_static_memory_peak_usage() const; @@ -328,7 +324,6 @@ public: virtual String get_system_dir(SystemDir p_dir) const; - virtual void set_no_window_mode(bool p_enable); virtual bool is_no_window_mode_enabled() const; @@ -357,8 +352,7 @@ public: virtual void make_rendering_thread(); virtual void swap_buffers(); - - virtual void set_icon(const Image& p_icon); + virtual void set_icon(const Image &p_icon); virtual int get_exit_code() const; virtual void set_exit_code(int p_code); @@ -375,9 +369,8 @@ public: virtual bool can_use_threads() const; - virtual Error dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object* p_obj, String p_callback); - virtual Error dialog_input_text(String p_title, String p_description, String p_partial, Object* p_obj, String p_callback); - + virtual Error dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object *p_obj, String p_callback); + virtual Error dialog_input_text(String p_title, String p_description, String p_partial, Object *p_obj, String p_callback); enum LatinKeyboardVariant { LATIN_KEYBOARD_QWERTY, @@ -388,12 +381,10 @@ public: LATIN_KEYBOARD_NEO, }; - virtual LatinKeyboardVariant get_latin_keyboard_variant() const; - virtual bool is_joy_known(int p_device); - virtual String get_joy_guid(int p_device)const; + virtual String get_joy_guid(int p_device) const; enum EngineContext { CONTEXT_EDITOR, @@ -404,18 +395,16 @@ public: virtual void set_use_vsync(bool p_enable); virtual bool is_vsync_enabled() const; - + virtual PowerState get_power_state(); virtual int get_power_seconds_left(); virtual int get_power_percent_left(); - virtual bool check_feature_support(const String& p_feature)=0; + virtual bool check_feature_support(const String &p_feature) = 0; bool is_hidpi_allowed() const { return _allow_hidpi; } OS(); virtual ~OS(); - }; #endif - diff --git a/core/os/power.h b/core/os/power.h index c92348ff50..9e70e82f5d 100644 --- a/core/os/power.h +++ b/core/os/power.h @@ -30,15 +30,12 @@ #ifndef CORE_OS_POWER_H_ #define CORE_OS_POWER_H_ - -typedef enum -{ - POWERSTATE_UNKNOWN, /**< cannot determine power status */ - POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */ - POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */ - POWERSTATE_CHARGING, /**< Plugged in, charging battery */ - POWERSTATE_CHARGED /**< Plugged in, battery charged */ +typedef enum { + POWERSTATE_UNKNOWN, /**< cannot determine power status */ + POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */ + POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */ + POWERSTATE_CHARGING, /**< Plugged in, charging battery */ + POWERSTATE_CHARGED /**< Plugged in, battery charged */ } PowerState; - #endif /* CORE_OS_POWER_H_ */ diff --git a/core/os/rw_lock.cpp b/core/os/rw_lock.cpp index 3af62aa8da..83f8a9ffde 100644 --- a/core/os/rw_lock.cpp +++ b/core/os/rw_lock.cpp @@ -32,19 +32,14 @@ #include <stddef.h> - -RWLock* (*RWLock::create_func)()=0; +RWLock *(*RWLock::create_func)() = 0; RWLock *RWLock::create() { - ERR_FAIL_COND_V( !create_func, 0 ); + ERR_FAIL_COND_V(!create_func, 0); return create_func(); } - RWLock::~RWLock() { - - } - diff --git a/core/os/rw_lock.h b/core/os/rw_lock.h index 6b4af83bf9..6d3079df51 100644 --- a/core/os/rw_lock.h +++ b/core/os/rw_lock.h @@ -33,42 +33,48 @@ class RWLock { protected: - static RWLock* (*create_func)(); + static RWLock *(*create_func)(); public: + virtual void read_lock() = 0; ///< Lock the rwlock, block if locked by someone else + virtual void read_unlock() = 0; ///< Unlock the rwlock, let other threads continue + virtual Error read_try_lock() = 0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock. - virtual void read_lock()=0; ///< Lock the rwlock, block if locked by someone else - virtual void read_unlock()=0; ///< Unlock the rwlock, let other threads continue - virtual Error read_try_lock()=0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock. + virtual void write_lock() = 0; ///< Lock the rwlock, block if locked by someone else + virtual void write_unlock() = 0; ///< Unlock the rwlock, let other thwrites continue + virtual Error write_try_lock() = 0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock. - virtual void write_lock()=0; ///< Lock the rwlock, block if locked by someone else - virtual void write_unlock()=0; ///< Unlock the rwlock, let other thwrites continue - virtual Error write_try_lock()=0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock. - - static RWLock * create(); ///< Create a rwlock + static RWLock *create(); ///< Create a rwlock virtual ~RWLock(); }; - class RWLockRead { RWLock *lock; -public: - - RWLockRead(RWLock* p_lock) { lock=p_lock; if (lock) lock->read_lock(); } - ~RWLockRead() { if (lock) lock->read_unlock(); } +public: + RWLockRead(RWLock *p_lock) { + lock = p_lock; + if (lock) lock->read_lock(); + } + ~RWLockRead() { + if (lock) lock->read_unlock(); + } }; class RWLockWrite { RWLock *lock; -public: - - RWLockWrite(RWLock* p_lock) { lock=p_lock; if (lock) lock->write_lock(); } - ~RWLockWrite() { if (lock) lock->write_unlock(); } +public: + RWLockWrite(RWLock *p_lock) { + lock = p_lock; + if (lock) lock->write_lock(); + } + ~RWLockWrite() { + if (lock) lock->write_unlock(); + } }; #endif // RWLOCK_H diff --git a/core/os/semaphore.cpp b/core/os/semaphore.cpp index fe476c5888..6bbae72f63 100644 --- a/core/os/semaphore.cpp +++ b/core/os/semaphore.cpp @@ -29,16 +29,14 @@ #include "semaphore.h" #include "error_macros.h" -Semaphore* (*Semaphore::create_func)()=0; +Semaphore *(*Semaphore::create_func)() = 0; Semaphore *Semaphore::create() { - ERR_FAIL_COND_V( !create_func, 0 ); + ERR_FAIL_COND_V(!create_func, 0); return create_func(); } - Semaphore::~Semaphore() { - } diff --git a/core/os/semaphore.h b/core/os/semaphore.h index e0b4460b22..8956fb7c39 100644 --- a/core/os/semaphore.h +++ b/core/os/semaphore.h @@ -36,18 +36,16 @@ */ class Semaphore { protected: - static Semaphore* (*create_func)(); + static Semaphore *(*create_func)(); public: + virtual Error wait() = 0; ///< wait until semaphore has positive value, then decrement and pass + virtual Error post() = 0; ///< unlock the semaphore, incrementing the value + virtual int get() const = 0; ///< get semaphore value - virtual Error wait()=0; ///< wait until semaphore has positive value, then decrement and pass - virtual Error post()=0; ///< unlock the semaphore, incrementing the value - virtual int get() const=0; ///< get semaphore value - - static Semaphore * create(); ///< Create a mutex + static Semaphore *create(); ///< Create a mutex virtual ~Semaphore(); }; - #endif diff --git a/core/os/shell.cpp b/core/os/shell.cpp index 60f4203dbe..77726afd9d 100644 --- a/core/os/shell.cpp +++ b/core/os/shell.cpp @@ -28,24 +28,17 @@ /*************************************************************************/ #include "shell.h" +Shell *Shell::singleton = NULL; -Shell * Shell::singleton=NULL; - - -Shell * Shell::get_singleton() { +Shell *Shell::get_singleton() { return singleton; } - Shell::~Shell() { - } Shell::Shell() { - singleton=this; + singleton = this; } - - - diff --git a/core/os/shell.h b/core/os/shell.h index f26f01846e..b2b0aa2260 100644 --- a/core/os/shell.h +++ b/core/os/shell.h @@ -37,11 +37,11 @@ */ class Shell { - static Shell * singleton; -public: + static Shell *singleton; - static Shell * get_singleton(); - virtual void execute(String p_path)=0; +public: + static Shell *get_singleton(); + virtual void execute(String p_path) = 0; Shell(); virtual ~Shell(); diff --git a/core/os/thread.cpp b/core/os/thread.cpp index 689fed7537..1c6ccaa504 100644 --- a/core/os/thread.cpp +++ b/core/os/thread.cpp @@ -28,13 +28,12 @@ /*************************************************************************/ #include "thread.h" +Thread *(*Thread::create_func)(ThreadCreateCallback, void *, const Settings &) = NULL; +Thread::ID (*Thread::get_thread_ID_func)() = NULL; +void (*Thread::wait_to_finish_func)(Thread *) = NULL; +Error (*Thread::set_name_func)(const String &) = NULL; -Thread* (*Thread::create_func)(ThreadCreateCallback,void *,const Settings&)=NULL; -Thread::ID (*Thread::get_thread_ID_func)()=NULL; -void (*Thread::wait_to_finish_func)(Thread*)=NULL; -Error (*Thread::set_name_func)(const String&)=NULL; - -Thread::ID Thread::_main_thread_id=0; +Thread::ID Thread::_main_thread_id = 0; Thread::ID Thread::get_caller_ID() { @@ -43,11 +42,11 @@ Thread::ID Thread::get_caller_ID() { return 0; } -Thread* Thread::create(ThreadCreateCallback p_callback,void * p_user,const Settings& p_settings) { +Thread *Thread::create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings) { if (create_func) { - return create_func(p_callback,p_user,p_settings); + return create_func(p_callback, p_user, p_settings); } return NULL; } @@ -56,7 +55,6 @@ void Thread::wait_to_finish(Thread *p_thread) { if (wait_to_finish_func) wait_to_finish_func(p_thread); - } Error Thread::set_name(const String &p_name) { @@ -67,13 +65,8 @@ Error Thread::set_name(const String &p_name) { return ERR_UNAVAILABLE; }; -Thread::Thread() -{ +Thread::Thread() { } - -Thread::~Thread() -{ +Thread::~Thread() { } - - diff --git a/core/os/thread.h b/core/os/thread.h index 23ed76d486..9e0ab93cb9 100644 --- a/core/os/thread.h +++ b/core/os/thread.h @@ -29,7 +29,6 @@ #ifndef THREAD_H #define THREAD_H - #include "typedefs.h" /** @author Juan Linietsky <reduzio@gmail.com> @@ -39,54 +38,45 @@ typedef void (*ThreadCreateCallback)(void *p_userdata); - - class Thread { public: - enum Priority { PRIORITY_LOW, - PRIORITY_NORMAL, + PRIORITY_NORMAL, PRIORITY_HIGH }; struct Settings { Priority priority; - Settings() { priority=PRIORITY_NORMAL; } + Settings() { priority = PRIORITY_NORMAL; } }; - - typedef uint64_t ID; protected: - static Thread* (*create_func)(ThreadCreateCallback p_callback,void *,const Settings&); + static Thread *(*create_func)(ThreadCreateCallback p_callback, void *, const Settings &); static ID (*get_thread_ID_func)(); - static void (*wait_to_finish_func)(Thread*); - static Error (*set_name_func)(const String&); + static void (*wait_to_finish_func)(Thread *); + static Error (*set_name_func)(const String &); friend class Main; static ID _main_thread_id; - Thread(); -public: - virtual ID get_ID() const=0; +public: + virtual ID get_ID() const = 0; static Error set_name(const String &p_name); _FORCE_INLINE_ static ID get_main_ID() { return _main_thread_id; } ///< get the ID of the main thread static ID get_caller_ID(); ///< get the ID of the caller function ID static void wait_to_finish(Thread *p_thread); ///< waits until thread is finished, and deallocates it. - static Thread * create(ThreadCreateCallback p_callback,void * p_user,const Settings& p_settings=Settings()); ///< Static function to create a thread, will call p_callback - + static Thread *create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings = Settings()); ///< Static function to create a thread, will call p_callback virtual ~Thread(); - }; #endif - diff --git a/core/os/thread_dummy.cpp b/core/os/thread_dummy.cpp index 93a020b7a8..a17f7f09a8 100644 --- a/core/os/thread_dummy.cpp +++ b/core/os/thread_dummy.cpp @@ -30,7 +30,7 @@ #include "memory.h" -Thread* ThreadDummy::create(ThreadCreateCallback p_callback,void * p_user,const Thread::Settings& p_settings) { +Thread *ThreadDummy::create(ThreadCreateCallback p_callback, void *p_user, const Thread::Settings &p_settings) { return memnew(ThreadDummy); }; @@ -38,7 +38,7 @@ void ThreadDummy::make_default() { Thread::create_func = &ThreadDummy::create; }; -Mutex* MutexDummy::create(bool p_recursive) { +Mutex *MutexDummy::create(bool p_recursive) { return memnew(MutexDummy); }; @@ -46,14 +46,10 @@ void MutexDummy::make_default() { Mutex::create_func = &MutexDummy::create; }; - -Semaphore* SemaphoreDummy::create() { +Semaphore *SemaphoreDummy::create() { return memnew(SemaphoreDummy); }; void SemaphoreDummy::make_default() { Semaphore::create_func = &SemaphoreDummy::create; }; - - - diff --git a/core/os/thread_dummy.h b/core/os/thread_dummy.h index 01e366e2fa..8d0ca0340d 100644 --- a/core/os/thread_dummy.h +++ b/core/os/thread_dummy.h @@ -29,13 +29,13 @@ #ifndef THREAD_DUMMY_H #define THREAD_DUMMY_H -#include "thread.h" #include "mutex.h" #include "semaphore.h" +#include "thread.h" class ThreadDummy : public Thread { - static Thread* create(ThreadCreateCallback p_callback,void * p_user,const Settings& p_settings=Settings()); + static Thread *create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings = Settings()); public: virtual ID get_ID() const { return 0; }; @@ -45,12 +45,11 @@ public: class MutexDummy : public Mutex { - static Mutex* create(bool p_recursive); + static Mutex *create(bool p_recursive); public: - - virtual void lock() {}; - virtual void unlock() {}; + virtual void lock(){}; + virtual void unlock(){}; virtual Error try_lock() { return OK; }; static void make_default(); @@ -58,7 +57,7 @@ public: class SemaphoreDummy : public Semaphore { - static Semaphore* create(); + static Semaphore *create(); public: virtual Error wait() { return OK; }; @@ -66,7 +65,6 @@ public: virtual int get() const { return 0; }; ///< get semaphore value static void make_default(); - }; #endif diff --git a/core/os/thread_safe.cpp b/core/os/thread_safe.cpp index a0bfb86c82..ebdf86733c 100644 --- a/core/os/thread_safe.cpp +++ b/core/os/thread_safe.cpp @@ -42,5 +42,5 @@ ThreadSafe::ThreadSafe() { ThreadSafe::~ThreadSafe() { if (mutex) - memdelete( mutex ); + memdelete(mutex); } diff --git a/core/os/thread_safe.h b/core/os/thread_safe.h index c9a832b41b..a60773e8ed 100644 --- a/core/os/thread_safe.h +++ b/core/os/thread_safe.h @@ -29,41 +29,42 @@ #ifndef THREAD_SAFE_H #define THREAD_SAFE_H - #include "os/mutex.h" class ThreadSafe { Mutex *mutex; -public: - inline void lock() const { if (mutex) mutex->lock(); } - inline void unlock() const { if (mutex) mutex->unlock(); } +public: + inline void lock() const { + if (mutex) mutex->lock(); + } + inline void unlock() const { + if (mutex) mutex->unlock(); + } ThreadSafe(); ~ThreadSafe(); - }; - class ThreadSafeMethod { const ThreadSafe *_ts; + public: ThreadSafeMethod(const ThreadSafe *p_ts) { - _ts=p_ts; + _ts = p_ts; _ts->lock(); } ~ThreadSafeMethod() { _ts->unlock(); } }; - #ifndef NO_THREADS #define _THREAD_SAFE_CLASS_ ThreadSafe __thread__safe__; -#define _THREAD_SAFE_METHOD_ ThreadSafeMethod __thread_safe_method__(&__thread__safe__); +#define _THREAD_SAFE_METHOD_ ThreadSafeMethod __thread_safe_method__(&__thread__safe__); #define _THREAD_SAFE_LOCK_ __thread__safe__.lock(); #define _THREAD_SAFE_UNLOCK_ __thread__safe__.unlock(); @@ -76,7 +77,4 @@ public: #endif - - - #endif diff --git a/core/packed_data_container.cpp b/core/packed_data_container.cpp index 803a217fca..b2922a6173 100644 --- a/core/packed_data_container.cpp +++ b/core/packed_data_container.cpp @@ -28,16 +28,15 @@ /*************************************************************************/ #include "packed_data_container.h" -#include "io/marshalls.h" #include "core_string_names.h" +#include "io/marshalls.h" +Variant PackedDataContainer::getvar(const Variant &p_key, bool *r_valid) const { -Variant PackedDataContainer::getvar(const Variant& p_key, bool *r_valid) const { - - bool err=false; - Variant ret = _key_at_ofs(0,p_key,err); + bool err = false; + Variant ret = _key_at_ofs(0, p_key, err); if (r_valid) - *r_valid=!err; + *r_valid = !err; return ret; } @@ -46,93 +45,88 @@ int PackedDataContainer::size() const { return _size(0); }; -Variant PackedDataContainer::_iter_init_ofs(const Array& p_iter,uint32_t p_offset) { +Variant PackedDataContainer::_iter_init_ofs(const Array &p_iter, uint32_t p_offset) { - Array ref=p_iter; + Array ref = p_iter; uint32_t size = _size(p_offset); - if (size==0 || ref.size()!=1) + if (size == 0 || ref.size() != 1) return false; else { - ref[0]=0; + ref[0] = 0; return true; } - - } -Variant PackedDataContainer::_iter_next_ofs(const Array& p_iter,uint32_t p_offset){ +Variant PackedDataContainer::_iter_next_ofs(const Array &p_iter, uint32_t p_offset) { - Array ref=p_iter; + Array ref = p_iter; uint32_t size = _size(p_offset); - if (ref.size()!=1) + if (ref.size() != 1) return false; int pos = ref[0]; - if (pos<0 || pos>=size) + if (pos < 0 || pos >= size) return false; - pos+=1; - ref[0]=pos; - return pos!=size; - + pos += 1; + ref[0] = pos; + return pos != size; } -Variant PackedDataContainer::_iter_get_ofs(const Variant& p_iter,uint32_t p_offset){ +Variant PackedDataContainer::_iter_get_ofs(const Variant &p_iter, uint32_t p_offset) { uint32_t size = _size(p_offset); - int pos=p_iter; - if (pos<0 || pos>=size) + int pos = p_iter; + if (pos < 0 || pos >= size) return Variant(); - PoolVector<uint8_t>::Read rd=data.read(); - const uint8_t *r=&rd[p_offset]; + PoolVector<uint8_t>::Read rd = data.read(); + const uint8_t *r = &rd[p_offset]; uint32_t type = decode_uint32(r); - bool err=false; - if (type==TYPE_ARRAY) { + bool err = false; + if (type == TYPE_ARRAY) { - uint32_t vpos = decode_uint32(rd.ptr() + p_offset+8+pos*4); - return _get_at_ofs(vpos,rd.ptr(),err); + uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 4); + return _get_at_ofs(vpos, rd.ptr(), err); - } else if (type==TYPE_DICT) { + } else if (type == TYPE_DICT) { - uint32_t vpos = decode_uint32(rd.ptr() + p_offset+8+pos*12+4); - return _get_at_ofs(vpos,rd.ptr(),err); + uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 12 + 4); + return _get_at_ofs(vpos, rd.ptr(), err); } else { ERR_FAIL_V(Variant()); } } - -Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs,const uint8_t *p_buf,bool &err) const { +Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, bool &err) const { uint32_t type = decode_uint32(p_buf + p_ofs); - if (type==TYPE_ARRAY || type==TYPE_DICT) { + if (type == TYPE_ARRAY || type == TYPE_DICT) { - Ref<PackedDataContainerRef> pdcr = memnew( PackedDataContainerRef ); - Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer*)this); + Ref<PackedDataContainerRef> pdcr = memnew(PackedDataContainerRef); + Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer *)this); - pdcr->from=pdc; - pdcr->offset=p_ofs; + pdcr->from = pdc; + pdcr->offset = p_ofs; return pdcr; } else { Variant v; - Error rerr = decode_variant(v,p_buf + p_ofs,datalen-p_ofs,NULL); + Error rerr = decode_variant(v, p_buf + p_ofs, datalen - p_ofs, NULL); - if (rerr!=OK) { + if (rerr != OK) { - err=true; - ERR_FAIL_COND_V(err!=OK,Variant()); + err = true; + ERR_FAIL_COND_V(err != OK, Variant()); } return v; } - } uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const { - PoolVector<uint8_t>::Read rd=data.read(); - const uint8_t *r=&rd[p_ofs]; + PoolVector<uint8_t>::Read rd = data.read(); + const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); return type; @@ -140,87 +134,84 @@ uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const { int PackedDataContainer::_size(uint32_t p_ofs) const { - PoolVector<uint8_t>::Read rd=data.read(); - const uint8_t *r=&rd[p_ofs]; + PoolVector<uint8_t>::Read rd = data.read(); + const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); - if (type==TYPE_ARRAY) { + if (type == TYPE_ARRAY) { - uint32_t len = decode_uint32(r+4); + uint32_t len = decode_uint32(r + 4); return len; - } else if (type==TYPE_DICT) { + } else if (type == TYPE_DICT) { - uint32_t len = decode_uint32(r+4); + uint32_t len = decode_uint32(r + 4); return len; }; return -1; }; -Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs,const Variant& p_key,bool &err) const { +Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const { - PoolVector<uint8_t>::Read rd=data.read(); - const uint8_t *r=&rd[p_ofs]; + PoolVector<uint8_t>::Read rd = data.read(); + const uint8_t *r = &rd[p_ofs]; uint32_t type = decode_uint32(r); - - if (type==TYPE_ARRAY) { + if (type == TYPE_ARRAY) { if (p_key.is_num()) { - int idx=p_key; - uint32_t len = decode_uint32(r+4); - if (idx<0 || idx>=len) { - err=true; + int idx = p_key; + uint32_t len = decode_uint32(r + 4); + if (idx < 0 || idx >= len) { + err = true; return Variant(); } - uint32_t ofs = decode_uint32(r+8+4*idx); - return _get_at_ofs(ofs,rd.ptr(),err); + uint32_t ofs = decode_uint32(r + 8 + 4 * idx); + return _get_at_ofs(ofs, rd.ptr(), err); } else { - err=true; + err = true; return Variant(); } - } else if (type==TYPE_DICT) { + } else if (type == TYPE_DICT) { - uint32_t hash=p_key.hash(); - uint32_t len = decode_uint32(r+4); + uint32_t hash = p_key.hash(); + uint32_t len = decode_uint32(r + 4); - bool found=false; - for(int i=0;i<len;i++) { - uint32_t khash=decode_uint32(r+8+i*12+0); - if (khash==hash) { - Variant key = _get_at_ofs(decode_uint32(r+8+i*12+4),rd.ptr(),err); + bool found = false; + for (int i = 0; i < len; i++) { + uint32_t khash = decode_uint32(r + 8 + i * 12 + 0); + if (khash == hash) { + Variant key = _get_at_ofs(decode_uint32(r + 8 + i * 12 + 4), rd.ptr(), err); if (err) return Variant(); - if (key==p_key) { + if (key == p_key) { //key matches, return value - return _get_at_ofs(decode_uint32(r+8+i*12+8),rd.ptr(),err); + return _get_at_ofs(decode_uint32(r + 8 + i * 12 + 8), rd.ptr(), err); } - found=true; + found = true; } else { if (found) break; } } - err=true; + err = true; return Variant(); } else { - err=true; + err = true; return Variant(); } - - } -uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpdata, Map<String,uint32_t>& string_cache) { +uint32_t PackedDataContainer::_pack(const Variant &p_data, Vector<uint8_t> &tmpdata, Map<String, uint32_t> &string_cache) { - switch(p_data.get_type()) { + switch (p_data.get_type()) { case Variant::STRING: { @@ -229,7 +220,7 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd return string_cache[s]; } - string_cache[s]=tmpdata.size(); + string_cache[s] = tmpdata.size(); }; //fallthrough case Variant::NIL: @@ -258,9 +249,9 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd uint32_t pos = tmpdata.size(); int len; - encode_variant(p_data,NULL,len); - tmpdata.resize(tmpdata.size()+len); - encode_variant(p_data,&tmpdata[pos],len); + encode_variant(p_data, NULL, len); + tmpdata.resize(tmpdata.size() + len); + encode_variant(p_data, &tmpdata[pos], len); return pos; } break; @@ -268,67 +259,64 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd case Variant::_RID: case Variant::OBJECT: { - return _pack(Variant(),tmpdata,string_cache); + return _pack(Variant(), tmpdata, string_cache); } break; case Variant::DICTIONARY: { - Dictionary d=p_data; + Dictionary d = p_data; //size is known, use sort uint32_t pos = tmpdata.size(); - int len=d.size(); - tmpdata.resize(tmpdata.size()+len*12+8); - encode_uint32(TYPE_DICT,&tmpdata[pos+0]); - encode_uint32(len,&tmpdata[pos+4]); + int len = d.size(); + tmpdata.resize(tmpdata.size() + len * 12 + 8); + encode_uint32(TYPE_DICT, &tmpdata[pos + 0]); + encode_uint32(len, &tmpdata[pos + 4]); List<Variant> keys; d.get_key_list(&keys); List<DictKey> sortk; - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { DictKey dk; - dk.hash=E->get().hash(); - dk.key=E->get(); + dk.hash = E->get().hash(); + dk.key = E->get(); sortk.push_back(dk); } sortk.sort(); - int idx=0; - for(List<DictKey>::Element *E=sortk.front();E;E=E->next()) { + int idx = 0; + for (List<DictKey>::Element *E = sortk.front(); E; E = E->next()) { - encode_uint32(E->get().hash,&tmpdata[pos+8+idx*12+0]); - uint32_t ofs = _pack(E->get().key,tmpdata,string_cache); - encode_uint32(ofs,&tmpdata[pos+8+idx*12+4]); - ofs = _pack(d[E->get().key],tmpdata,string_cache); - encode_uint32(ofs,&tmpdata[pos+8+idx*12+8]); + encode_uint32(E->get().hash, &tmpdata[pos + 8 + idx * 12 + 0]); + uint32_t ofs = _pack(E->get().key, tmpdata, string_cache); + encode_uint32(ofs, &tmpdata[pos + 8 + idx * 12 + 4]); + ofs = _pack(d[E->get().key], tmpdata, string_cache); + encode_uint32(ofs, &tmpdata[pos + 8 + idx * 12 + 8]); idx++; } return pos; - - } break; case Variant::ARRAY: { - Array a=p_data; + Array a = p_data; //size is known, use sort uint32_t pos = tmpdata.size(); - int len=a.size(); - tmpdata.resize(tmpdata.size()+len*4+8); - encode_uint32(TYPE_ARRAY,&tmpdata[pos+0]); - encode_uint32(len,&tmpdata[pos+4]); + int len = a.size(); + tmpdata.resize(tmpdata.size() + len * 4 + 8); + encode_uint32(TYPE_ARRAY, &tmpdata[pos + 0]); + encode_uint32(len, &tmpdata[pos + 4]); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - uint32_t ofs = _pack(a[i],tmpdata,string_cache); - encode_uint32(ofs,&tmpdata[pos+8+i*4]); + uint32_t ofs = _pack(a[i], tmpdata, string_cache); + encode_uint32(ofs, &tmpdata[pos + 8 + i * 4]); } return pos; - } break; default: {} @@ -337,86 +325,75 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd return OK; } -Error PackedDataContainer::pack(const Variant& p_data) { +Error PackedDataContainer::pack(const Variant &p_data) { Vector<uint8_t> tmpdata; - Map<String,uint32_t> string_cache; - _pack(p_data,tmpdata,string_cache); - datalen=tmpdata.size(); + Map<String, uint32_t> string_cache; + _pack(p_data, tmpdata, string_cache); + datalen = tmpdata.size(); data.resize(tmpdata.size()); PoolVector<uint8_t>::Write w = data.write(); - copymem(w.ptr(),tmpdata.ptr(),tmpdata.size()); + copymem(w.ptr(), tmpdata.ptr(), tmpdata.size()); return OK; } +void PackedDataContainer::_set_data(const PoolVector<uint8_t> &p_data) { -void PackedDataContainer::_set_data(const PoolVector<uint8_t>& p_data) { - - data=p_data; - datalen=data.size(); - + data = p_data; + datalen = data.size(); } PoolVector<uint8_t> PackedDataContainer::_get_data() const { return data; } +Variant PackedDataContainer::_iter_init(const Array &p_iter) { -Variant PackedDataContainer::_iter_init(const Array& p_iter) { - - - return _iter_init_ofs(p_iter,0); + return _iter_init_ofs(p_iter, 0); } -Variant PackedDataContainer::_iter_next(const Array& p_iter){ - - return _iter_next_ofs(p_iter,0); +Variant PackedDataContainer::_iter_next(const Array &p_iter) { + return _iter_next_ofs(p_iter, 0); } -Variant PackedDataContainer::_iter_get(const Variant& p_iter){ +Variant PackedDataContainer::_iter_get(const Variant &p_iter) { - return _iter_get_ofs(p_iter,0); + return _iter_get_ofs(p_iter, 0); } - void PackedDataContainer::_bind_methods() { - ClassDB::bind_method(D_METHOD("_set_data"),&PackedDataContainer::_set_data); - ClassDB::bind_method(D_METHOD("_get_data"),&PackedDataContainer::_get_data); - ClassDB::bind_method(D_METHOD("_iter_init"),&PackedDataContainer::_iter_init); - ClassDB::bind_method(D_METHOD("_iter_get"),&PackedDataContainer::_iter_get); - ClassDB::bind_method(D_METHOD("_iter_next"),&PackedDataContainer::_iter_next); - ClassDB::bind_method(D_METHOD("pack:Error","value"),&PackedDataContainer::pack); - ClassDB::bind_method(D_METHOD("size"),&PackedDataContainer::size); + ClassDB::bind_method(D_METHOD("_set_data"), &PackedDataContainer::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &PackedDataContainer::_get_data); + ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainer::_iter_init); + ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainer::_iter_get); + ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainer::_iter_next); + ClassDB::bind_method(D_METHOD("pack:Error", "value"), &PackedDataContainer::pack); + ClassDB::bind_method(D_METHOD("size"), &PackedDataContainer::size); - ADD_PROPERTY( PropertyInfo(Variant::POOL_BYTE_ARRAY,"__data__"),"_set_data","_get_data"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "__data__"), "_set_data", "_get_data"); } - PackedDataContainer::PackedDataContainer() { - datalen=0; + datalen = 0; } - ////////////////// +Variant PackedDataContainerRef::_iter_init(const Array &p_iter) { -Variant PackedDataContainerRef::_iter_init(const Array& p_iter) { - - - return from->_iter_init_ofs(p_iter,offset); + return from->_iter_init_ofs(p_iter, offset); } -Variant PackedDataContainerRef::_iter_next(const Array& p_iter){ - - return from->_iter_next_ofs(p_iter,offset); +Variant PackedDataContainerRef::_iter_next(const Array &p_iter) { + return from->_iter_next_ofs(p_iter, offset); } -Variant PackedDataContainerRef::_iter_get(const Variant& p_iter){ +Variant PackedDataContainerRef::_iter_get(const Variant &p_iter) { - return from->_iter_get_ofs(p_iter,offset); + return from->_iter_get_ofs(p_iter, offset); } bool PackedDataContainerRef::_is_dictionary() const { @@ -426,20 +403,19 @@ bool PackedDataContainerRef::_is_dictionary() const { void PackedDataContainerRef::_bind_methods() { - ClassDB::bind_method(D_METHOD("size"),&PackedDataContainerRef::size); - ClassDB::bind_method(D_METHOD("_iter_init"),&PackedDataContainerRef::_iter_init); - ClassDB::bind_method(D_METHOD("_iter_get"),&PackedDataContainerRef::_iter_get); - ClassDB::bind_method(D_METHOD("_iter_next"),&PackedDataContainerRef::_iter_next); - ClassDB::bind_method(D_METHOD("_is_dictionary"),&PackedDataContainerRef::_is_dictionary); + ClassDB::bind_method(D_METHOD("size"), &PackedDataContainerRef::size); + ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainerRef::_iter_init); + ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainerRef::_iter_get); + ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainerRef::_iter_next); + ClassDB::bind_method(D_METHOD("_is_dictionary"), &PackedDataContainerRef::_is_dictionary); } +Variant PackedDataContainerRef::getvar(const Variant &p_key, bool *r_valid) const { -Variant PackedDataContainerRef::getvar(const Variant& p_key, bool *r_valid) const { - - bool err=false; - Variant ret = from->_key_at_ofs(offset,p_key,err); + bool err = false; + Variant ret = from->_key_at_ofs(offset, p_key, err); if (r_valid) - *r_valid=!err; + *r_valid = !err; return ret; } @@ -449,5 +425,4 @@ int PackedDataContainerRef::size() const { }; PackedDataContainerRef::PackedDataContainerRef() { - } diff --git a/core/packed_data_container.h b/core/packed_data_container.h index f8ff43f9b0..b7ce505836 100644 --- a/core/packed_data_container.h +++ b/core/packed_data_container.h @@ -29,57 +29,50 @@ #ifndef PACKED_DATA_CONTAINER_H #define PACKED_DATA_CONTAINER_H - #include "resource.h" - - class PackedDataContainer : public Resource { - GDCLASS(PackedDataContainer,Resource); + GDCLASS(PackedDataContainer, Resource); enum { - TYPE_DICT=0xFFFFFFFF, - TYPE_ARRAY=0xFFFFFFFE, + TYPE_DICT = 0xFFFFFFFF, + TYPE_ARRAY = 0xFFFFFFFE, }; struct DictKey { uint32_t hash; Variant key; - bool operator<(const DictKey& p_key) const { return hash < p_key.hash; } + bool operator<(const DictKey &p_key) const { return hash < p_key.hash; } }; - PoolVector<uint8_t> data; int datalen; + uint32_t _pack(const Variant &p_data, Vector<uint8_t> &tmpdata, Map<String, uint32_t> &string_cache); - uint32_t _pack(const Variant& p_data,Vector<uint8_t>& tmpdata,Map<String,uint32_t>& string_cache); - + Variant _iter_init_ofs(const Array &p_iter, uint32_t p_offset); + Variant _iter_next_ofs(const Array &p_iter, uint32_t p_offset); + Variant _iter_get_ofs(const Variant &p_iter, uint32_t p_offset); - Variant _iter_init_ofs(const Array& p_iter,uint32_t p_offset); - Variant _iter_next_ofs(const Array& p_iter,uint32_t p_offset); - Variant _iter_get_ofs(const Variant& p_iter,uint32_t p_offset); + Variant _iter_init(const Array &p_iter); + Variant _iter_next(const Array &p_iter); + Variant _iter_get(const Variant &p_iter); - Variant _iter_init(const Array& p_iter); - Variant _iter_next(const Array& p_iter); - Variant _iter_get(const Variant& p_iter); - -friend class PackedDataContainerRef; - Variant _key_at_ofs(uint32_t p_ofs,const Variant& p_key,bool &err) const; + friend class PackedDataContainerRef; + Variant _key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const; Variant _get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, bool &err) const; uint32_t _type_at_ofs(uint32_t p_ofs) const; int _size(uint32_t p_ofs) const; protected: - - void _set_data(const PoolVector<uint8_t>& p_data); + void _set_data(const PoolVector<uint8_t> &p_data); PoolVector<uint8_t> _get_data() const; static void _bind_methods(); -public: - virtual Variant getvar(const Variant& p_key, bool *r_valid=NULL) const; - Error pack(const Variant& p_data); +public: + virtual Variant getvar(const Variant &p_key, bool *r_valid = NULL) const; + Error pack(const Variant &p_data); int size() const; @@ -87,9 +80,9 @@ public: }; class PackedDataContainerRef : public Reference { - GDCLASS(PackedDataContainerRef,Reference); + GDCLASS(PackedDataContainerRef, Reference); -friend class PackedDataContainer; + friend class PackedDataContainer; uint32_t offset; Ref<PackedDataContainer> from; @@ -97,14 +90,13 @@ protected: static void _bind_methods(); public: - - Variant _iter_init(const Array& p_iter); - Variant _iter_next(const Array& p_iter); - Variant _iter_get(const Variant& p_iter); + Variant _iter_init(const Array &p_iter); + Variant _iter_next(const Array &p_iter); + Variant _iter_get(const Variant &p_iter); bool _is_dictionary() const; int size() const; - virtual Variant getvar(const Variant& p_key, bool *r_valid=NULL) const; + virtual Variant getvar(const Variant &p_key, bool *r_valid = NULL) const; PackedDataContainerRef(); }; diff --git a/core/pair.h b/core/pair.h index 174ffb3883..faa3febfd4 100644 --- a/core/pair.h +++ b/core/pair.h @@ -29,23 +29,25 @@ #ifndef PAIR_H #define PAIR_H -template<class F,class S> +template <class F, class S> struct Pair { F first; S second; Pair() {} - Pair( F p_first, S p_second) { first=p_first; second=p_second; } + Pair(F p_first, S p_second) { + first = p_first; + second = p_second; + } }; -template<class F,class S> +template <class F, class S> struct PairSort { - bool operator()(const Pair<F,S>& A, const Pair<F,S>& B) const { + bool operator()(const Pair<F, S> &A, const Pair<F, S> &B) const { return A.first < B.first; } }; - #endif // PAIR_H diff --git a/core/path_db.cpp b/core/path_db.cpp index 679372898c..239a2d7654 100644 --- a/core/path_db.cpp +++ b/core/path_db.cpp @@ -38,25 +38,24 @@ uint32_t NodePath::hash() const { uint32_t h = data->absolute ? 1 : 0; int pc = data->path.size(); const StringName *sn = data->path.ptr(); - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { h = h ^ sn[i].hash(); } int spc = data->subpath.size(); const StringName *ssn = data->subpath.ptr(); - for(int i=0;i<spc;i++) { + for (int i = 0; i < spc; i++) { h = h ^ ssn[i].hash(); } h = h ^ data->property.hash(); return h; - } void NodePath::prepend_period() { - if (data->path.size() && data->path[0].operator String()!=".") { - data->path.insert(0,"."); + if (data->path.size() && data->path[0].operator String() != ".") { + data->path.insert(0, "."); } } @@ -66,7 +65,6 @@ bool NodePath::is_absolute() const { return false; return data->absolute; - } int NodePath::get_name_count() const { @@ -74,12 +72,11 @@ int NodePath::get_name_count() const { return 0; return data->path.size(); - } StringName NodePath::get_name(int p_idx) const { - ERR_FAIL_COND_V(!data,StringName()); - ERR_FAIL_INDEX_V(p_idx,data->path.size(),StringName()); + ERR_FAIL_COND_V(!data, StringName()); + ERR_FAIL_INDEX_V(p_idx, data->path.size(), StringName()); return data->path[p_idx]; } @@ -96,29 +93,26 @@ int NodePath::get_subname_count() const { return 0; return data->subpath.size(); - } StringName NodePath::get_subname(int p_idx) const { - ERR_FAIL_COND_V(!data,StringName()); - ERR_FAIL_INDEX_V(p_idx,data->subpath.size(),StringName()); + ERR_FAIL_COND_V(!data, StringName()); + ERR_FAIL_INDEX_V(p_idx, data->subpath.size(), StringName()); return data->subpath[p_idx]; } - void NodePath::unref() { if (data && data->refcount.unref()) { memdelete(data); } - data=NULL; - + data = NULL; } -bool NodePath::operator==(const NodePath& p_path) const { +bool NodePath::operator==(const NodePath &p_path) const { - if (data==p_path.data) + if (data == p_path.data) return true; if (!data || !p_path.data) @@ -136,36 +130,35 @@ bool NodePath::operator==(const NodePath& p_path) const { if (data->property != p_path.data->property) return false; - for (int i=0;i<data->path.size();i++) { + for (int i = 0; i < data->path.size(); i++) { - if (data->path[i]!=p_path.data->path[i]) + if (data->path[i] != p_path.data->path[i]) return false; } - for (int i=0;i<data->subpath.size();i++) { + for (int i = 0; i < data->subpath.size(); i++) { - if (data->subpath[i]!=p_path.data->subpath[i]) + if (data->subpath[i] != p_path.data->subpath[i]) return false; } return true; } -bool NodePath::operator!=(const NodePath& p_path) const { +bool NodePath::operator!=(const NodePath &p_path) const { return (!(*this == p_path)); } +void NodePath::operator=(const NodePath &p_path) { -void NodePath::operator=(const NodePath& p_path) { - - if (this==&p_path) + if (this == &p_path) return; unref(); if (p_path.data && p_path.data->refcount.ref()) { - data=p_path.data; + data = p_path.data; } } @@ -176,33 +169,32 @@ NodePath::operator String() const { String ret; if (data->absolute) - ret="/"; + ret = "/"; - for (int i=0;i<data->path.size();i++) { + for (int i = 0; i < data->path.size(); i++) { - if (i>0) - ret+="/"; - ret+=data->path[i].operator String(); + if (i > 0) + ret += "/"; + ret += data->path[i].operator String(); } - for (int i=0;i<data->subpath.size();i++) { + for (int i = 0; i < data->subpath.size(); i++) { - ret+=":"+data->subpath[i].operator String(); + ret += ":" + data->subpath[i].operator String(); } - if (data->property.operator String()!="") - ret+=":"+String(data->property); + if (data->property.operator String() != "") + ret += ":" + String(data->property); return ret; } +NodePath::NodePath(const NodePath &p_path) { -NodePath::NodePath(const NodePath& p_path) { - - data=NULL; + data = NULL; if (p_path.data && p_path.data->refcount.ref()) { - data=p_path.data; + data = p_path.data; } } @@ -212,32 +204,30 @@ Vector<StringName> NodePath::get_names() const { return data->path; return Vector<StringName>(); } -Vector<StringName> NodePath::get_subnames() const{ +Vector<StringName> NodePath::get_subnames() const { if (data) return data->subpath; return Vector<StringName>(); - } +NodePath NodePath::rel_path_to(const NodePath &p_np) const { -NodePath NodePath::rel_path_to(const NodePath& p_np) const { - - ERR_FAIL_COND_V( !is_absolute(), NodePath() ); - ERR_FAIL_COND_V( !p_np.is_absolute(), NodePath() ); + ERR_FAIL_COND_V(!is_absolute(), NodePath()); + ERR_FAIL_COND_V(!p_np.is_absolute(), NodePath()); Vector<StringName> src_dirs = get_names(); Vector<StringName> dst_dirs = p_np.get_names(); //find common parent - int common_parent=0; + int common_parent = 0; - while(true) { - if (src_dirs.size()==common_parent) + while (true) { + if (src_dirs.size() == common_parent) break; - if (dst_dirs.size()==common_parent) + if (dst_dirs.size() == common_parent) break; - if (src_dirs[common_parent]!=dst_dirs[common_parent]) + if (src_dirs[common_parent] != dst_dirs[common_parent]) break; common_parent++; } @@ -246,69 +236,67 @@ NodePath NodePath::rel_path_to(const NodePath& p_np) const { Vector<StringName> relpath; - for(int i=src_dirs.size()-1;i>common_parent;i--) { + for (int i = src_dirs.size() - 1; i > common_parent; i--) { relpath.push_back(".."); } - for(int i=common_parent+1;i<dst_dirs.size();i++) { + for (int i = common_parent + 1; i < dst_dirs.size(); i++) { relpath.push_back(dst_dirs[i]); } - if (relpath.size()==0) + if (relpath.size() == 0) relpath.push_back("."); - return NodePath(relpath,p_np.get_subnames(),false,p_np.get_property()); + return NodePath(relpath, p_np.get_subnames(), false, p_np.get_property()); } +NodePath::NodePath(const Vector<StringName> &p_path, bool p_absolute, const String &p_property) { -NodePath::NodePath(const Vector<StringName>& p_path,bool p_absolute,const String& p_property) { + data = NULL; - data=NULL; - - if (p_path.size()==0) + if (p_path.size() == 0) return; - data = memnew( Data ); + data = memnew(Data); data->refcount.init(); - data->absolute=p_absolute; - data->path=p_path; - data->property=p_property; + data->absolute = p_absolute; + data->path = p_path; + data->property = p_property; } -NodePath::NodePath(const Vector<StringName>& p_path,const Vector<StringName>& p_subpath,bool p_absolute,const String& p_property) { +NodePath::NodePath(const Vector<StringName> &p_path, const Vector<StringName> &p_subpath, bool p_absolute, const String &p_property) { - data=NULL; + data = NULL; - if (p_path.size()==0) + if (p_path.size() == 0) return; - data = memnew( Data ); + data = memnew(Data); data->refcount.init(); - data->absolute=p_absolute; - data->path=p_path; - data->subpath=p_subpath; - data->property=p_property; + data->absolute = p_absolute; + data->path = p_path; + data->subpath = p_subpath; + data->property = p_property; } - void NodePath::simplify() { if (!data) return; - for(int i=0;i<data->path.size();i++) { - if (data->path.size()==1) + for (int i = 0; i < data->path.size(); i++) { + if (data->path.size() == 1) break; - if (data->path[i].operator String()==".") { + if (data->path[i].operator String() == ".") { data->path.remove(i); i--; - } else if (data->path[i].operator String()==".." && i>0 && data->path[i-1].operator String()!="." && data->path[i-1].operator String()!="..") { + } else if (data->path[i].operator String() == ".." && i > 0 && data->path[i - 1].operator String() != "." && data->path[i - 1].operator String() != "..") { //remove both - data->path.remove(i-1); - data->path.remove(i-1); - i-=2; - if (data->path.size()==0) { + data->path.remove(i - 1); + data->path.remove(i - 1); + i -= 2; + if (data->path.size() == 0) { data->path.push_back("."); break; } @@ -318,108 +306,100 @@ void NodePath::simplify() { NodePath NodePath::simplified() const { - NodePath np=*this; + NodePath np = *this; np.simplify(); return np; } -NodePath::NodePath(const String& p_path) { +NodePath::NodePath(const String &p_path) { - data=NULL; + data = NULL; - if (p_path.length()==0) + if (p_path.length() == 0) return; - String path=p_path; + String path = p_path; StringName property; Vector<StringName> subpath; - int absolute=(path[0]=='/')?1:0; - bool last_is_slash=true; - int slices=0; - int subpath_pos=path.find(":"); - + int absolute = (path[0] == '/') ? 1 : 0; + bool last_is_slash = true; + int slices = 0; + int subpath_pos = path.find(":"); + if (subpath_pos != -1) { - if (subpath_pos!=-1) { + int from = subpath_pos + 1; - int from=subpath_pos+1; + for (int i = from; i <= path.length(); i++) { - for (int i=from;i<=path.length();i++) { + if (path[i] == ':' || path[i] == 0) { - if (path[i]==':' || path[i]==0) { - - String str = path.substr(from,i-from); - if (path[i]==':') { - if (str=="") { - ERR_EXPLAIN("Invalid NodePath: "+p_path); + String str = path.substr(from, i - from); + if (path[i] == ':') { + if (str == "") { + ERR_EXPLAIN("Invalid NodePath: " + p_path); ERR_FAIL(); } subpath.push_back(str); } else { //property can be empty - property=str; + property = str; } - from=i+1; + from = i + 1; } - } - path=path.substr(0,subpath_pos); + path = path.substr(0, subpath_pos); } - for (int i=absolute;i<path.length();i++) { + for (int i = absolute; i < path.length(); i++) { - if (path[i]=='/') { + if (path[i] == '/') { - last_is_slash=true; + last_is_slash = true; } else { if (last_is_slash) slices++; - last_is_slash=false; + last_is_slash = false; } - - } - if (slices==0 && !absolute && !property) + if (slices == 0 && !absolute && !property) return; - data = memnew( Data ); + data = memnew(Data); data->refcount.init(); - data->absolute=absolute?true:false; - data->property=property; - data->subpath=subpath; + data->absolute = absolute ? true : false; + data->property = property; + data->subpath = subpath; - if (slices==0) + if (slices == 0) return; data->path.resize(slices); - last_is_slash=true; - int from=absolute; - int slice=0; + last_is_slash = true; + int from = absolute; + int slice = 0; - for (int i=absolute;i<path.length()+1;i++) { + for (int i = absolute; i < path.length() + 1; i++) { - if (path[i]=='/' || path[i]==0) { + if (path[i] == '/' || path[i] == 0) { if (!last_is_slash) { - String name=path.substr(from,i-from); - ERR_FAIL_INDEX( slice,data->path.size() ); - data->path[slice++]=name; + String name = path.substr(from, i - from); + ERR_FAIL_INDEX(slice, data->path.size()); + data->path[slice++] = name; } - from=i+1; - last_is_slash=true; + from = i + 1; + last_is_slash = true; } else { - last_is_slash=false; + last_is_slash = false; } - } - - } bool NodePath::is_empty() const { @@ -428,7 +408,7 @@ bool NodePath::is_empty() const { } NodePath::NodePath() { - data=NULL; + data = NULL; } NodePath::~NodePath() { diff --git a/core/path_db.h b/core/path_db.h index db756c3420..eec29676e2 100644 --- a/core/path_db.h +++ b/core/path_db.h @@ -29,15 +29,12 @@ #ifndef PATH_DB_H #define PATH_DB_H - -#include "ustring.h" #include "string_db.h" +#include "ustring.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - - class NodePath { struct Data { @@ -51,11 +48,11 @@ class NodePath { Data *data; void unref(); -public: +public: _FORCE_INLINE_ StringName get_sname() const { - if (data && data->path.size()==1 && data->subpath.empty() && !data->property) { + if (data && data->path.size() == 1 && data->subpath.empty() && !data->property) { return data->path[0]; } else { return operator String(); @@ -70,7 +67,7 @@ public: Vector<StringName> get_names() const; Vector<StringName> get_subnames() const; - NodePath rel_path_to(const NodePath& p_np) const; + NodePath rel_path_to(const NodePath &p_np) const; void prepend_period(); @@ -83,17 +80,17 @@ public: operator String() const; bool is_empty() const; - bool operator==(const NodePath& p_path) const; - bool operator!=(const NodePath& p_path) const; - void operator=(const NodePath& p_path); + bool operator==(const NodePath &p_path) const; + bool operator!=(const NodePath &p_path) const; + void operator=(const NodePath &p_path); void simplify(); NodePath simplified() const; - NodePath(const Vector<StringName>& p_path,bool p_absolute,const String& p_property=""); - NodePath(const Vector<StringName>& p_path,const Vector<StringName>& p_subpath,bool p_absolute,const String& p_property=""); - NodePath(const NodePath& p_path); - NodePath(const String& p_path); + NodePath(const Vector<StringName> &p_path, bool p_absolute, const String &p_property = ""); + NodePath(const Vector<StringName> &p_path, const Vector<StringName> &p_subpath, bool p_absolute, const String &p_property = ""); + NodePath(const NodePath &p_path); + NodePath(const String &p_path); NodePath(); ~NodePath(); }; diff --git a/core/path_remap.cpp b/core/path_remap.cpp index bbaba71bba..bd76790b85 100644 --- a/core/path_remap.cpp +++ b/core/path_remap.cpp @@ -27,4 +27,3 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "path_remap.h" - diff --git a/core/pool_allocator.cpp b/core/pool_allocator.cpp index 3260225ac3..68de05a765 100644 --- a/core/pool_allocator.cpp +++ b/core/pool_allocator.cpp @@ -28,43 +28,39 @@ /*************************************************************************/ #include "pool_allocator.h" -#include "error_macros.h" #include "core/os/os.h" -#include "os/memory.h" +#include "error_macros.h" #include "os/copymem.h" +#include "os/memory.h" #include "print_string.h" #include <assert.h> -#define COMPACT_CHUNK( m_entry , m_to_pos ) \ -do { \ - void *_dst=&((unsigned char*)pool)[m_to_pos]; \ - void *_src=&((unsigned char*)pool)[(m_entry).pos]; \ - movemem(_dst,_src,aligned((m_entry).len)); \ - (m_entry).pos=m_to_pos; \ -} while (0); +#define COMPACT_CHUNK(m_entry, m_to_pos) \ + do { \ + void *_dst = &((unsigned char *)pool)[m_to_pos]; \ + void *_src = &((unsigned char *)pool)[(m_entry).pos]; \ + movemem(_dst, _src, aligned((m_entry).len)); \ + (m_entry).pos = m_to_pos; \ + } while (0); void PoolAllocator::mt_lock() const { - } void PoolAllocator::mt_unlock() const { - } +bool PoolAllocator::get_free_entry(EntryArrayPos *p_pos) { -bool PoolAllocator::get_free_entry(EntryArrayPos* p_pos) { - - if (entry_count==entry_max) + if (entry_count == entry_max) return false; - for (int i=0;i<entry_max;i++) { + for (int i = 0; i < entry_max; i++) { - if (entry_array[i].len==0) { - *p_pos=i; + if (entry_array[i].len == 0) { + *p_pos = i; return true; } - } ERR_PRINT("Out of memory Chunks!"); @@ -82,134 +78,121 @@ bool PoolAllocator::find_hole(EntryArrayPos *p_pos, int p_for_size) { /* position where previous entry ends. Defaults to zero (begin of pool) */ - int prev_entry_end_pos=0; + int prev_entry_end_pos = 0; - for (int i=0;i<entry_count;i++) { + for (int i = 0; i < entry_count; i++) { - - Entry &entry=entry_array[ entry_indices[ i ] ]; + Entry &entry = entry_array[entry_indices[i]]; /* determine hole size to previous entry */ - int hole_size=entry.pos-prev_entry_end_pos; + int hole_size = entry.pos - prev_entry_end_pos; /* detemine if what we want fits in that hole */ - if (hole_size>=p_for_size) { - *p_pos=i; + if (hole_size >= p_for_size) { + *p_pos = i; return true; } /* prepare for next one */ - prev_entry_end_pos=entry_end(entry); + prev_entry_end_pos = entry_end(entry); } /* No holes between entrys, check at the end..*/ - if ( (pool_size-prev_entry_end_pos)>=p_for_size ) { - *p_pos=entry_count; + if ((pool_size - prev_entry_end_pos) >= p_for_size) { + *p_pos = entry_count; return true; } return false; - } - void PoolAllocator::compact(int p_up_to) { - uint32_t prev_entry_end_pos=0; - - if (p_up_to<0) - p_up_to=entry_count; - for (int i=0;i<p_up_to;i++) { + uint32_t prev_entry_end_pos = 0; + if (p_up_to < 0) + p_up_to = entry_count; + for (int i = 0; i < p_up_to; i++) { - Entry &entry=entry_array[ entry_indices[ i ] ]; + Entry &entry = entry_array[entry_indices[i]]; /* determine hole size to previous entry */ - int hole_size=entry.pos-prev_entry_end_pos; + int hole_size = entry.pos - prev_entry_end_pos; /* if we can compact, do it */ - if (hole_size>0 && !entry.lock) { - - COMPACT_CHUNK(entry,prev_entry_end_pos); + if (hole_size > 0 && !entry.lock) { + COMPACT_CHUNK(entry, prev_entry_end_pos); } /* prepare for next one */ - prev_entry_end_pos=entry_end(entry); + prev_entry_end_pos = entry_end(entry); } - - } void PoolAllocator::compact_up(int p_from) { - uint32_t next_entry_end_pos=pool_size; // - static_area_size; + uint32_t next_entry_end_pos = pool_size; // - static_area_size; - for (int i=entry_count-1;i>=p_from;i--) { + for (int i = entry_count - 1; i >= p_from; i--) { - - Entry &entry=entry_array[ entry_indices[ i ] ]; + Entry &entry = entry_array[entry_indices[i]]; /* determine hole size to nextious entry */ - int hole_size=next_entry_end_pos-(entry.pos+aligned(entry.len)); + int hole_size = next_entry_end_pos - (entry.pos + aligned(entry.len)); /* if we can compact, do it */ - if (hole_size>0 && !entry.lock) { - - COMPACT_CHUNK(entry,(next_entry_end_pos-aligned(entry.len))); + if (hole_size > 0 && !entry.lock) { + COMPACT_CHUNK(entry, (next_entry_end_pos - aligned(entry.len))); } /* prepare for next one */ - next_entry_end_pos=entry.pos; + next_entry_end_pos = entry.pos; } - } +bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry) { -bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos,Entry *p_entry) { + EntryArrayPos entry_pos = entry_max; - EntryArrayPos entry_pos=entry_max; + for (int i = 0; i < entry_count; i++) { - for (int i=0;i<entry_count;i++) { + if (&entry_array[entry_indices[i]] == p_entry) { - if (&entry_array[ entry_indices[ i ] ]==p_entry) { - - entry_pos=i; + entry_pos = i; break; } } - if (entry_pos==entry_max) + if (entry_pos == entry_max) return false; - *p_map_pos=entry_pos; + *p_map_pos = entry_pos; return true; - } PoolAllocator::ID PoolAllocator::alloc(int p_size) { - ERR_FAIL_COND_V(p_size<1,POOL_ALLOCATOR_INVALID_ID); + ERR_FAIL_COND_V(p_size < 1, POOL_ALLOCATOR_INVALID_ID); #ifdef DEBUG_ENABLED if (p_size > free_mem) OS::get_singleton()->debug_break(); #endif - ERR_FAIL_COND_V(p_size>free_mem,POOL_ALLOCATOR_INVALID_ID); + ERR_FAIL_COND_V(p_size > free_mem, POOL_ALLOCATOR_INVALID_ID); mt_lock(); - if (entry_count==entry_max) { + if (entry_count == entry_max) { mt_unlock(); ERR_PRINT("entry_count==entry_max"); return POOL_ALLOCATOR_INVALID_ID; } - - int size_to_alloc=aligned(p_size); + int size_to_alloc = aligned(p_size); EntryIndicesPos new_entry_indices_pos; @@ -228,60 +211,59 @@ PoolAllocator::ID PoolAllocator::alloc(int p_size) { EntryArrayPos new_entry_array_pos; - bool found_free_entry=get_free_entry(&new_entry_array_pos); + bool found_free_entry = get_free_entry(&new_entry_array_pos); if (!found_free_entry) { mt_unlock(); - ERR_FAIL_COND_V( !found_free_entry , POOL_ALLOCATOR_INVALID_ID ); + ERR_FAIL_COND_V(!found_free_entry, POOL_ALLOCATOR_INVALID_ID); } /* move all entry indices up, make room for this one */ - for (int i=entry_count;i>new_entry_indices_pos;i-- ) { + for (int i = entry_count; i > new_entry_indices_pos; i--) { - entry_indices[i]=entry_indices[i-1]; + entry_indices[i] = entry_indices[i - 1]; } - entry_indices[new_entry_indices_pos]=new_entry_array_pos; + entry_indices[new_entry_indices_pos] = new_entry_array_pos; entry_count++; - Entry &entry=entry_array[ entry_indices[ new_entry_indices_pos ] ]; + Entry &entry = entry_array[entry_indices[new_entry_indices_pos]]; - entry.len=p_size; - entry.pos=(new_entry_indices_pos==0)?0:entry_end(entry_array[ entry_indices[ new_entry_indices_pos-1 ] ]); //alloc either at begining or end of previous - entry.lock=0; - entry.check=(check_count++)&CHECK_MASK; - free_mem-=size_to_alloc; - if (free_mem<free_mem_peak) - free_mem_peak=free_mem; + entry.len = p_size; + entry.pos = (new_entry_indices_pos == 0) ? 0 : entry_end(entry_array[entry_indices[new_entry_indices_pos - 1]]); //alloc either at begining or end of previous + entry.lock = 0; + entry.check = (check_count++) & CHECK_MASK; + free_mem -= size_to_alloc; + if (free_mem < free_mem_peak) + free_mem_peak = free_mem; - ID retval = (entry_indices[ new_entry_indices_pos ]<<CHECK_BITS)|entry.check; + ID retval = (entry_indices[new_entry_indices_pos] << CHECK_BITS) | entry.check; mt_unlock(); //ERR_FAIL_COND_V( (uintptr_t)get(retval)%align != 0, retval ); return retval; - } -PoolAllocator::Entry * PoolAllocator::get_entry(ID p_mem) { +PoolAllocator::Entry *PoolAllocator::get_entry(ID p_mem) { - unsigned int check=p_mem&CHECK_MASK; - int entry=p_mem>>CHECK_BITS; - ERR_FAIL_INDEX_V(entry,entry_max,NULL); - ERR_FAIL_COND_V(entry_array[entry].check!=check,NULL); - ERR_FAIL_COND_V(entry_array[entry].len==0,NULL); + unsigned int check = p_mem & CHECK_MASK; + int entry = p_mem >> CHECK_BITS; + ERR_FAIL_INDEX_V(entry, entry_max, NULL); + ERR_FAIL_COND_V(entry_array[entry].check != check, NULL); + ERR_FAIL_COND_V(entry_array[entry].len == 0, NULL); return &entry_array[entry]; } -const PoolAllocator::Entry * PoolAllocator::get_entry(ID p_mem) const { +const PoolAllocator::Entry *PoolAllocator::get_entry(ID p_mem) const { - unsigned int check=p_mem&CHECK_MASK; - int entry=p_mem>>CHECK_BITS; - ERR_FAIL_INDEX_V(entry,entry_max,NULL); - ERR_FAIL_COND_V(entry_array[entry].check!=check,NULL); - ERR_FAIL_COND_V(entry_array[entry].len==0,NULL); + unsigned int check = p_mem & CHECK_MASK; + int entry = p_mem >> CHECK_BITS; + ERR_FAIL_INDEX_V(entry, entry_max, NULL); + ERR_FAIL_COND_V(entry_array[entry].check != check, NULL); + ERR_FAIL_COND_V(entry_array[entry].len == 0, NULL); return &entry_array[entry]; } @@ -289,7 +271,7 @@ const PoolAllocator::Entry * PoolAllocator::get_entry(ID p_mem) const { void PoolAllocator::free(ID p_mem) { mt_lock(); - Entry *e=get_entry(p_mem); + Entry *e = get_entry(p_mem); if (!e) { mt_unlock(); ERR_PRINT("!e"); @@ -303,22 +285,20 @@ void PoolAllocator::free(ID p_mem) { EntryIndicesPos entry_indices_pos; - bool index_found = find_entry_index(&entry_indices_pos,e); + bool index_found = find_entry_index(&entry_indices_pos, e); if (!index_found) { mt_unlock(); ERR_FAIL_COND(!index_found); } + for (int i = entry_indices_pos; i < (entry_count - 1); i++) { - - for (int i=entry_indices_pos;i<(entry_count-1);i++) { - - entry_indices[ i ] = entry_indices[ i+1 ]; + entry_indices[i] = entry_indices[i + 1]; } entry_count--; - free_mem+=aligned(e->len); + free_mem += aligned(e->len); e->clear(); mt_unlock(); } @@ -328,7 +308,7 @@ int PoolAllocator::get_size(ID p_mem) const { int size; mt_lock(); - const Entry *e=get_entry(p_mem); + const Entry *e = get_entry(p_mem); if (!e) { mt_unlock(); @@ -336,40 +316,40 @@ int PoolAllocator::get_size(ID p_mem) const { return 0; } - size=e->len; + size = e->len; mt_unlock(); return size; } -Error PoolAllocator::resize(ID p_mem,int p_new_size) { +Error PoolAllocator::resize(ID p_mem, int p_new_size) { mt_lock(); - Entry *e=get_entry(p_mem); + Entry *e = get_entry(p_mem); if (!e) { mt_unlock(); - ERR_FAIL_COND_V(!e,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!e, ERR_INVALID_PARAMETER); } if (needs_locking && e->lock) { mt_unlock(); - ERR_FAIL_COND_V(e->lock,ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(e->lock, ERR_ALREADY_IN_USE); } int alloc_size = aligned(p_new_size); - if (aligned(e->len)==alloc_size) { + if (aligned(e->len) == alloc_size) { - e->len=p_new_size; + e->len = p_new_size; mt_unlock(); return OK; - } else if (e->len>(uint32_t)p_new_size) { + } else if (e->len > (uint32_t)p_new_size) { free_mem += aligned(e->len); free_mem -= alloc_size; - e->len=p_new_size; + e->len = p_new_size; mt_unlock(); return OK; } @@ -379,77 +359,74 @@ Error PoolAllocator::resize(ID p_mem,int p_new_size) { if ((_free + aligned(e->len)) - alloc_size < 0) { mt_unlock(); - ERR_FAIL_V( ERR_OUT_OF_MEMORY ); + ERR_FAIL_V(ERR_OUT_OF_MEMORY); }; EntryIndicesPos entry_indices_pos; - bool index_found = find_entry_index(&entry_indices_pos,e); + bool index_found = find_entry_index(&entry_indices_pos, e); if (!index_found) { mt_unlock(); - ERR_FAIL_COND_V(!index_found,ERR_BUG); + ERR_FAIL_COND_V(!index_found, ERR_BUG); } //no need to move stuff around, it fits before the next block int next_pos; - if (entry_indices_pos+1 == entry_count) { + if (entry_indices_pos + 1 == entry_count) { next_pos = pool_size; // - static_area_size; } else { - next_pos = entry_array[entry_indices[entry_indices_pos+1]].pos; + next_pos = entry_array[entry_indices[entry_indices_pos + 1]].pos; }; if ((next_pos - e->pos) > alloc_size) { - free_mem+=aligned(e->len); - e->len=p_new_size; - free_mem-=alloc_size; + free_mem += aligned(e->len); + e->len = p_new_size; + free_mem -= alloc_size; mt_unlock(); return OK; } //it doesn't fit, compact around BEFORE current index (make room behind) - compact(entry_indices_pos+1); - + compact(entry_indices_pos + 1); if ((next_pos - e->pos) > alloc_size) { //now fits! hooray! - free_mem+=aligned(e->len); - e->len=p_new_size; - free_mem-=alloc_size; + free_mem += aligned(e->len); + e->len = p_new_size; + free_mem -= alloc_size; mt_unlock(); - if (free_mem<free_mem_peak) - free_mem_peak=free_mem; + if (free_mem < free_mem_peak) + free_mem_peak = free_mem; return OK; } //STILL doesn't fit, compact around AFTER current index (make room after) - compact_up(entry_indices_pos+1); + compact_up(entry_indices_pos + 1); - if ((entry_array[entry_indices[entry_indices_pos+1]].pos - e->pos) > alloc_size) { + if ((entry_array[entry_indices[entry_indices_pos + 1]].pos - e->pos) > alloc_size) { //now fits! hooray! - free_mem+=aligned(e->len); - e->len=p_new_size; - free_mem-=alloc_size; + free_mem += aligned(e->len); + e->len = p_new_size; + free_mem -= alloc_size; mt_unlock(); - if (free_mem<free_mem_peak) - free_mem_peak=free_mem; + if (free_mem < free_mem_peak) + free_mem_peak = free_mem; return OK; } mt_unlock(); ERR_FAIL_V(ERR_OUT_OF_MEMORY); - } - Error PoolAllocator::lock(ID p_mem) { if (!needs_locking) return OK; mt_lock(); - Entry *e=get_entry(p_mem); + Entry *e = get_entry(p_mem); if (!e) { mt_unlock(); @@ -467,7 +444,7 @@ bool PoolAllocator::is_locked(ID p_mem) const { return false; mt_lock(); - const Entry *e=((PoolAllocator*)(this))->get_entry(p_mem); + const Entry *e = ((PoolAllocator *)(this))->get_entry(p_mem); if (!e) { mt_unlock(); @@ -483,91 +460,87 @@ const void *PoolAllocator::get(ID p_mem) const { if (!needs_locking) { - const Entry *e=get_entry(p_mem); - ERR_FAIL_COND_V(!e,NULL); + const Entry *e = get_entry(p_mem); + ERR_FAIL_COND_V(!e, NULL); return &pool[e->pos]; - } mt_lock(); - const Entry *e=get_entry(p_mem); + const Entry *e = get_entry(p_mem); if (!e) { mt_unlock(); - ERR_FAIL_COND_V(!e,NULL); + ERR_FAIL_COND_V(!e, NULL); } - if (e->lock==0) { + if (e->lock == 0) { mt_unlock(); - ERR_PRINT( "e->lock == 0" ); + ERR_PRINT("e->lock == 0"); return NULL; } - if ((int)e->pos>=pool_size) { + if ((int)e->pos >= pool_size) { mt_unlock(); ERR_PRINT("e->pos<0 || e->pos>=pool_size"); return NULL; } - const void *ptr=&pool[e->pos]; + const void *ptr = &pool[e->pos]; mt_unlock(); return ptr; - } void *PoolAllocator::get(ID p_mem) { if (!needs_locking) { - Entry *e=get_entry(p_mem); + Entry *e = get_entry(p_mem); if (!e) { - ERR_FAIL_COND_V(!e,NULL); + ERR_FAIL_COND_V(!e, NULL); }; return &pool[e->pos]; - } mt_lock(); - Entry *e=get_entry(p_mem); + Entry *e = get_entry(p_mem); if (!e) { mt_unlock(); - ERR_FAIL_COND_V(!e,NULL); + ERR_FAIL_COND_V(!e, NULL); } - if (e->lock==0) { + if (e->lock == 0) { //assert(0); mt_unlock(); - ERR_PRINT( "e->lock == 0" ); + ERR_PRINT("e->lock == 0"); return NULL; } - if ((int)e->pos>=pool_size) { + if ((int)e->pos >= pool_size) { mt_unlock(); ERR_PRINT("e->pos<0 || e->pos>=pool_size"); return NULL; } - void *ptr=&pool[e->pos]; + void *ptr = &pool[e->pos]; mt_unlock(); return ptr; - } void PoolAllocator::unlock(ID p_mem) { if (!needs_locking) return; mt_lock(); - Entry *e=get_entry(p_mem); - if (e->lock == 0 ) { + Entry *e = get_entry(p_mem); + if (e->lock == 0) { mt_unlock(); - ERR_PRINT( "e->lock == 0" ); + ERR_PRINT("e->lock == 0"); return; } e->lock--; @@ -576,7 +549,7 @@ void PoolAllocator::unlock(ID p_mem) { int PoolAllocator::get_used_mem() const { - return pool_size-free_mem; + return pool_size - free_mem; } int PoolAllocator::get_free_peak() { @@ -589,72 +562,69 @@ int PoolAllocator::get_free_mem() { return free_mem; } -void PoolAllocator::create_pool(void * p_mem,int p_size,int p_max_entries) { +void PoolAllocator::create_pool(void *p_mem, int p_size, int p_max_entries) { - pool=(uint8_t*)p_mem; - pool_size=p_size; + pool = (uint8_t *)p_mem; + pool_size = p_size; - entry_array = memnew_arr( Entry, p_max_entries ); - entry_indices = memnew_arr( int, p_max_entries ); + entry_array = memnew_arr(Entry, p_max_entries); + entry_indices = memnew_arr(int, p_max_entries); entry_max = p_max_entries; - entry_count=0; + entry_count = 0; - free_mem=p_size; - free_mem_peak=p_size; + free_mem = p_size; + free_mem_peak = p_size; - check_count=0; + check_count = 0; } -PoolAllocator::PoolAllocator(int p_size,bool p_needs_locking,int p_max_entries) { +PoolAllocator::PoolAllocator(int p_size, bool p_needs_locking, int p_max_entries) { - mem_ptr=memalloc( p_size); + mem_ptr = memalloc(p_size); ERR_FAIL_COND(!mem_ptr); - align=1; - create_pool(mem_ptr,p_size,p_max_entries); - needs_locking=p_needs_locking; - + align = 1; + create_pool(mem_ptr, p_size, p_max_entries); + needs_locking = p_needs_locking; } -PoolAllocator::PoolAllocator(void * p_mem,int p_size, int p_align ,bool p_needs_locking,int p_max_entries) { +PoolAllocator::PoolAllocator(void *p_mem, int p_size, int p_align, bool p_needs_locking, int p_max_entries) { if (p_align > 1) { - uint8_t *mem8=(uint8_t*)p_mem; + uint8_t *mem8 = (uint8_t *)p_mem; uint64_t ofs = (uint64_t)mem8; - if (ofs%p_align) { - int dif = p_align-(ofs%p_align); - mem8+=p_align-(ofs%p_align); + if (ofs % p_align) { + int dif = p_align - (ofs % p_align); + mem8 += p_align - (ofs % p_align); p_size -= dif; - p_mem = (void*)mem8; + p_mem = (void *)mem8; }; }; - create_pool( p_mem,p_size,p_max_entries); - needs_locking=p_needs_locking; - align=p_align; - mem_ptr=NULL; + create_pool(p_mem, p_size, p_max_entries); + needs_locking = p_needs_locking; + align = p_align; + mem_ptr = NULL; } -PoolAllocator::PoolAllocator(int p_align,int p_size,bool p_needs_locking,int p_max_entries) { +PoolAllocator::PoolAllocator(int p_align, int p_size, bool p_needs_locking, int p_max_entries) { - ERR_FAIL_COND(p_align<1); - mem_ptr=Memory::alloc_static( p_size+p_align,"PoolAllocator()"); - uint8_t *mem8=(uint8_t*)mem_ptr; + ERR_FAIL_COND(p_align < 1); + mem_ptr = Memory::alloc_static(p_size + p_align, "PoolAllocator()"); + uint8_t *mem8 = (uint8_t *)mem_ptr; uint64_t ofs = (uint64_t)mem8; - if (ofs%p_align) - mem8+=p_align-(ofs%p_align); - create_pool( mem8 ,p_size,p_max_entries); - needs_locking=p_needs_locking; - align=p_align; + if (ofs % p_align) + mem8 += p_align - (ofs % p_align); + create_pool(mem8, p_size, p_max_entries); + needs_locking = p_needs_locking; + align = p_align; } PoolAllocator::~PoolAllocator() { if (mem_ptr) - memfree( mem_ptr ); - - memdelete_arr( entry_array ); - memdelete_arr( entry_indices ); + memfree(mem_ptr); + memdelete_arr(entry_array); + memdelete_arr(entry_indices); } - diff --git a/core/pool_allocator.h b/core/pool_allocator.h index a5911688f7..1dc6167ceb 100644 --- a/core/pool_allocator.h +++ b/core/pool_allocator.h @@ -42,21 +42,21 @@ enum { - POOL_ALLOCATOR_INVALID_ID=-1 ///< default invalid value. use INVALID_ID( id ) to test + POOL_ALLOCATOR_INVALID_ID = -1 ///< default invalid value. use INVALID_ID( id ) to test }; class PoolAllocator { public: typedef int ID; + private: enum { - CHECK_BITS=8, - CHECK_LEN=(1<<CHECK_BITS), - CHECK_MASK=CHECK_LEN-1 + CHECK_BITS = 8, + CHECK_LEN = (1 << CHECK_BITS), + CHECK_MASK = CHECK_LEN - 1 }; - struct Entry { unsigned int pos; @@ -64,11 +64,15 @@ private: unsigned int lock; unsigned int check; - inline void clear() { pos=0; len=0; lock=0; check=0; } + inline void clear() { + pos = 0; + len = 0; + lock = 0; + check = 0; + } Entry() { clear(); } }; - typedef int EntryArrayPos; typedef int EntryIndicesPos; @@ -89,40 +93,40 @@ private: bool needs_locking; - inline int entry_end(const Entry& p_entry) const { - return p_entry.pos+aligned(p_entry.len); + inline int entry_end(const Entry &p_entry) const { + return p_entry.pos + aligned(p_entry.len); } inline int aligned(int p_size) const { - int rem=p_size%align; + int rem = p_size % align; if (rem) - p_size+=align-rem; + p_size += align - rem; return p_size; } - void compact(int p_up_to=-1); - void compact_up(int p_from=0); - bool get_free_entry(EntryArrayPos* p_pos); + void compact(int p_up_to = -1); + void compact_up(int p_from = 0); + bool get_free_entry(EntryArrayPos *p_pos); bool find_hole(EntryArrayPos *p_pos, int p_for_size); - bool find_entry_index(EntryIndicesPos *p_map_pos,Entry *p_entry); - Entry* get_entry(ID p_mem); - const Entry* get_entry(ID p_mem) const; + bool find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry); + Entry *get_entry(ID p_mem); + const Entry *get_entry(ID p_mem) const; + + void create_pool(void *p_mem, int p_size, int p_max_entries); - void create_pool(void * p_mem,int p_size,int p_max_entries); protected: virtual void mt_lock() const; ///< Reimplement for custom mt locking virtual void mt_unlock() const; ///< Reimplement for custom mt locking public: - enum { - DEFAULT_MAX_ALLOCS=4096, + DEFAULT_MAX_ALLOCS = 4096, }; ID alloc(int p_size); ///< Alloc memory, get an ID on success, POOL_ALOCATOR_INVALID_ID on failure void free(ID p_mem); ///< Free allocated memory - Error resize(ID p_mem,int p_new_size); ///< resize a memory chunk + Error resize(ID p_mem, int p_new_size); ///< resize a memory chunk int get_size(ID p_mem) const; int get_free_mem(); ///< get free memory @@ -135,12 +139,11 @@ public: void unlock(ID p_mem); bool is_locked(ID p_mem) const; - PoolAllocator(int p_size,bool p_needs_locking=false,int p_max_entries=DEFAULT_MAX_ALLOCS); - PoolAllocator(void * p_mem,int p_size, int p_align = 1, bool p_needs_locking=false,int p_max_entries=DEFAULT_MAX_ALLOCS); - PoolAllocator(int p_align,int p_size,bool p_needs_locking=false,int p_max_entries=DEFAULT_MAX_ALLOCS); + PoolAllocator(int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS); + PoolAllocator(void *p_mem, int p_size, int p_align = 1, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS); + PoolAllocator(int p_align, int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS); virtual ~PoolAllocator(); - }; #endif diff --git a/core/print_string.cpp b/core/print_string.cpp index 36316af619..1cb07802c5 100644 --- a/core/print_string.cpp +++ b/core/print_string.cpp @@ -32,15 +32,15 @@ #include <stdio.h> -static PrintHandlerList *print_handler_list=NULL; -bool _print_line_enabled=true; +static PrintHandlerList *print_handler_list = NULL; +bool _print_line_enabled = true; bool _print_error_enabled = true; void add_print_handler(PrintHandlerList *p_handler) { _global_lock(); - p_handler->next=print_handler_list; - print_handler_list=p_handler; + p_handler->next = print_handler_list; + print_handler_list = p_handler; _global_unlock(); } @@ -51,43 +51,39 @@ void remove_print_handler(PrintHandlerList *p_handler) { PrintHandlerList *prev = NULL; PrintHandlerList *l = print_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 - print_handler_list=l->next; + print_handler_list = l->next; break; } - prev=l; - l=l->next; - + prev = l; + l = l->next; } //OS::get_singleton()->print("print handler list is %p\n",print_handler_list); - ERR_FAIL_COND(l==NULL); + ERR_FAIL_COND(l == NULL); _global_unlock(); - } - void print_line(String p_string) { if (!_print_line_enabled) return; - OS::get_singleton()->print("%s\n",p_string.utf8().get_data()); + OS::get_singleton()->print("%s\n", p_string.utf8().get_data()); _global_lock(); PrintHandlerList *l = print_handler_list; - while(l) { + while (l) { - l->printfunc(l->userdata,p_string); - l=l->next; + l->printfunc(l->userdata, p_string); + l = l->next; } _global_unlock(); - } diff --git a/core/print_string.h b/core/print_string.h index a13abd4e38..ddbe55f8ed 100644 --- a/core/print_string.h +++ b/core/print_string.h @@ -33,21 +33,22 @@ extern void (*_print_func)(String); - -typedef void (*PrintHandlerFunc)(void*,const String& p_string); +typedef void (*PrintHandlerFunc)(void *, const String &p_string); struct PrintHandlerList { PrintHandlerFunc printfunc; void *userdata; - PrintHandlerList*next; + PrintHandlerList *next; - PrintHandlerList() { printfunc=0; next=0; userdata=0; } + PrintHandlerList() { + printfunc = 0; + next = 0; + userdata = 0; + } }; - - void add_print_handler(PrintHandlerList *p_handler); void remove_print_handler(PrintHandlerList *p_handler); diff --git a/core/ref_ptr.cpp b/core/ref_ptr.cpp index 29ffe974d2..867d0b9246 100644 --- a/core/ref_ptr.cpp +++ b/core/ref_ptr.cpp @@ -31,43 +31,41 @@ #include "reference.h" #include "resource.h" -void RefPtr::operator=(const RefPtr& p_other) { +void RefPtr::operator=(const RefPtr &p_other) { - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); - Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference>*>( const_cast<char*>(&p_other.data[0]) ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); + Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference> *>(const_cast<char *>(&p_other.data[0])); *ref = *ref_other; } -bool RefPtr::operator==(const RefPtr& p_other) const { +bool RefPtr::operator==(const RefPtr &p_other) const { - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); - Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference>*>( const_cast<char*>(&p_other.data[0]) ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); + Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference> *>(const_cast<char *>(&p_other.data[0])); return *ref == *ref_other; } -RefPtr::RefPtr(const RefPtr& p_other) { +RefPtr::RefPtr(const RefPtr &p_other) { - memnew_placement(&data[0],Ref<Reference>); + memnew_placement(&data[0], Ref<Reference>); - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); - Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference>*>( const_cast<char*>(&p_other.data[0]) ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); + Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference> *>(const_cast<char *>(&p_other.data[0])); *ref = *ref_other; } bool RefPtr::is_null() const { - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); return ref->is_null(); - - } RID RefPtr::get_rid() const { - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); if (ref->is_null()) return RID(); Resource *res = (*ref)->cast_to<Resource>(); @@ -78,21 +76,18 @@ RID RefPtr::get_rid() const { void RefPtr::unref() { - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); ref->unref(); } RefPtr::RefPtr() { - ERR_FAIL_COND(sizeof(Ref<Reference>)>DATASIZE); - memnew_placement(&data[0],Ref<Reference>); + ERR_FAIL_COND(sizeof(Ref<Reference>) > DATASIZE); + memnew_placement(&data[0], Ref<Reference>); } - RefPtr::~RefPtr() { - Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] ); + Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]); ref->~Ref<Reference>(); } - - diff --git a/core/ref_ptr.h b/core/ref_ptr.h index c9824639dc..04c7bb51ed 100644 --- a/core/ref_ptr.h +++ b/core/ref_ptr.h @@ -36,27 +36,24 @@ #include "rid.h" - class RefPtr { enum { - DATASIZE=sizeof(void*) //*4 -ref was shrunk + DATASIZE = sizeof(void *) //*4 -ref was shrunk }; mutable char data[DATASIZE]; // too much probably, virtual class + pointer public: - bool is_null() const; - void operator=(const RefPtr& p_other); - bool operator==(const RefPtr& p_other) const; + void operator=(const RefPtr &p_other); + bool operator==(const RefPtr &p_other) const; RID get_rid() const; void unref(); _FORCE_INLINE_ void *get_data() const { return data; } - RefPtr(const RefPtr& p_other); + RefPtr(const RefPtr &p_other); RefPtr(); ~RefPtr(); - }; #endif // REF_PTR_H diff --git a/core/reference.cpp b/core/reference.cpp index 5e8244d2ca..5285888f78 100644 --- a/core/reference.cpp +++ b/core/reference.cpp @@ -30,7 +30,6 @@ #include "script_language.h" - bool Reference::init_ref() { if (refcount.ref()) { @@ -39,7 +38,7 @@ bool Reference::init_ref() { // at the same time, which is never likely to happen (would be crazy to do) // so don't do it. - if (refcount_init.get()>0) { + if (refcount_init.get() > 0) { refcount_init.unref(); refcount.unref(); // first referencing is already 1, so compensate for the ref above } @@ -49,30 +48,27 @@ bool Reference::init_ref() { return false; } - } - void Reference::_bind_methods() { - ClassDB::bind_method(D_METHOD("init_ref"),&Reference::init_ref); - ClassDB::bind_method(D_METHOD("reference"),&Reference::reference); - ClassDB::bind_method(D_METHOD("unreference"),&Reference::unreference); + ClassDB::bind_method(D_METHOD("init_ref"), &Reference::init_ref); + ClassDB::bind_method(D_METHOD("reference"), &Reference::reference); + ClassDB::bind_method(D_METHOD("unreference"), &Reference::unreference); } int Reference::reference_get_count() const { return refcount.get(); } -void Reference::reference(){ +void Reference::reference() { refcount.ref(); if (get_script_instance()) { get_script_instance()->refcount_incremented(); } - } -bool Reference::unreference(){ +bool Reference::unreference() { bool die = refcount.unref(); @@ -81,7 +77,6 @@ bool Reference::unreference(){ } return die; - } Reference::Reference() { @@ -90,14 +85,12 @@ Reference::Reference() { refcount_init.init(); } - Reference::~Reference() { - } Variant WeakRef::get_ref() const { - if (ref==0) + if (ref == 0) return Variant(); Object *obj = ObjectDB::get_instance(ref); @@ -113,21 +106,21 @@ Variant WeakRef::get_ref() const { } void WeakRef::set_obj(Object *p_object) { - ref=p_object ? p_object->get_instance_ID() : 0; + ref = p_object ? p_object->get_instance_ID() : 0; } -void WeakRef::set_ref(const REF& p_ref) { +void WeakRef::set_ref(const REF &p_ref) { - ref=p_ref.is_valid() ? p_ref->get_instance_ID() : 0; + ref = p_ref.is_valid() ? p_ref->get_instance_ID() : 0; } WeakRef::WeakRef() { - ref=0; + ref = 0; } void WeakRef::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_ref:Object"),&WeakRef::get_ref); + ClassDB::bind_method(D_METHOD("get_ref:Object"), &WeakRef::get_ref); } #if 0 diff --git a/core/reference.h b/core/reference.h index e130b4c2b4..af7071a198 100644 --- a/core/reference.h +++ b/core/reference.h @@ -29,27 +29,26 @@ #ifndef REFERENCE_H #define REFERENCE_H +#include "class_db.h" #include "object.h" -#include "safe_refcount.h" #include "ref_ptr.h" -#include "class_db.h" +#include "safe_refcount.h" /** @author Juan Linietsky <reduzio@gmail.com> */ -class Reference : public Object{ +class Reference : public Object { - GDCLASS( Reference, Object ); -friend class RefBase; + GDCLASS(Reference, Object); + friend class RefBase; SafeRefCount refcount; SafeRefCount refcount_init; -protected: +protected: static void _bind_methods(); -public: - - _FORCE_INLINE_ bool is_referenced() const { return refcount_init.get()<1; } +public: + _FORCE_INLINE_ bool is_referenced() const { return refcount_init.get() < 1; } bool init_ref(); void reference(); bool unreference(); @@ -74,73 +73,71 @@ public: }; #endif -template<class T> +template <class T> class Ref { T *reference; - void ref( const Ref& p_from ) { + void ref(const Ref &p_from) { - if (p_from.reference==reference) + if (p_from.reference == reference) return; unref(); - reference=p_from.reference; + reference = p_from.reference; if (reference) reference->reference(); } - void ref_pointer( T* p_ref ) { + void ref_pointer(T *p_ref) { ERR_FAIL_COND(!p_ref); if (p_ref->init_ref()) - reference=p_ref; + reference = p_ref; } //virtual Reference * get_reference() const { return reference; } public: + _FORCE_INLINE_ bool operator<(const Ref<T> &p_r) const { - - _FORCE_INLINE_ bool operator<(const Ref<T>& p_r) const { - - return reference<p_r.reference; + return reference < p_r.reference; } - _FORCE_INLINE_ bool operator==(const Ref<T>& p_r) const { + _FORCE_INLINE_ bool operator==(const Ref<T> &p_r) const { - return reference==p_r.reference; + return reference == p_r.reference; } - _FORCE_INLINE_ bool operator!=(const Ref<T>& p_r) const { + _FORCE_INLINE_ bool operator!=(const Ref<T> &p_r) const { - return reference!=p_r.reference; + return reference != p_r.reference; } - _FORCE_INLINE_ T* operator->() { + _FORCE_INLINE_ T *operator->() { return reference; } - _FORCE_INLINE_ T* operator*() { + _FORCE_INLINE_ T *operator*() { return reference; } - _FORCE_INLINE_ const T* operator->() const { + _FORCE_INLINE_ const T *operator->() const { return reference; } - _FORCE_INLINE_ const T* ptr() const { + _FORCE_INLINE_ const T *ptr() const { return reference; } - _FORCE_INLINE_ T* ptr() { + _FORCE_INLINE_ T *ptr() { return reference; } - _FORCE_INLINE_ const T* operator*() const { + _FORCE_INLINE_ const T *operator*() const { return reference; } @@ -148,7 +145,7 @@ public: RefPtr get_ref_ptr() const { RefPtr refptr; - Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( refptr.get_data() ); + Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(refptr.get_data()); *irr = *this; return refptr; }; @@ -164,123 +161,120 @@ public: #if 1 operator Variant() const { - return Variant( get_ref_ptr() ); + return Variant(get_ref_ptr()); } #endif - void operator=( const Ref& p_from ) { + void operator=(const Ref &p_from) { ref(p_from); } - template<class T_Other> - void operator=( const Ref<T_Other>& p_from ) { + template <class T_Other> + void operator=(const Ref<T_Other> &p_from) { - Reference *refb = const_cast<Reference*>(static_cast<const Reference*>(p_from.ptr())); + Reference *refb = const_cast<Reference *>(static_cast<const Reference *>(p_from.ptr())); if (!refb) { unref(); return; } Ref r; - r.reference=refb->cast_to<T>(); + r.reference = refb->cast_to<T>(); ref(r); - r.reference=NULL; + r.reference = NULL; } - void operator=( const RefPtr& p_refptr ) { + void operator=(const RefPtr &p_refptr) { - Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( p_refptr.get_data() ); + Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(p_refptr.get_data()); Reference *refb = irr->ptr(); if (!refb) { unref(); return; } Ref r; - r.reference=refb->cast_to<T>(); + r.reference = refb->cast_to<T>(); ref(r); - r.reference=NULL; + r.reference = NULL; } + void operator=(const Variant &p_variant) { - void operator=( const Variant& p_variant ) { - - RefPtr refptr=p_variant; - Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( refptr.get_data() ); + RefPtr refptr = p_variant; + Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(refptr.get_data()); Reference *refb = irr->ptr(); if (!refb) { unref(); return; } Ref r; - r.reference=refb->cast_to<T>(); + r.reference = refb->cast_to<T>(); ref(r); - r.reference=NULL; + r.reference = NULL; } - Ref( const Ref& p_from ) { + Ref(const Ref &p_from) { - reference=NULL; + reference = NULL; ref(p_from); } - template<class T_Other> - Ref( const Ref<T_Other>& p_from ) { + template <class T_Other> + Ref(const Ref<T_Other> &p_from) { - reference=NULL; - Reference *refb = const_cast<Reference*>(static_cast<const Reference*>(p_from.ptr())); + reference = NULL; + Reference *refb = const_cast<Reference *>(static_cast<const Reference *>(p_from.ptr())); if (!refb) { unref(); return; } Ref r; - r.reference=refb->cast_to<T>(); + r.reference = refb->cast_to<T>(); ref(r); - r.reference=NULL; + r.reference = NULL; } - Ref( T* p_reference ) { + Ref(T *p_reference) { if (p_reference) ref_pointer(p_reference); else - reference=NULL; + reference = NULL; } - Ref( const Variant& p_variant) { + Ref(const Variant &p_variant) { - RefPtr refptr=p_variant; - Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( refptr.get_data() ); - reference=NULL; + RefPtr refptr = p_variant; + Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(refptr.get_data()); + reference = NULL; Reference *refb = irr->ptr(); if (!refb) { unref(); return; } Ref r; - r.reference=refb->cast_to<T>(); + r.reference = refb->cast_to<T>(); ref(r); - r.reference=NULL; + r.reference = NULL; } + Ref(const RefPtr &p_refptr) { - - Ref( const RefPtr& p_refptr) { - - Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( p_refptr.get_data() ); - reference=NULL; + Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(p_refptr.get_data()); + reference = NULL; Reference *refb = irr->ptr(); if (!refb) { unref(); return; } Ref r; - r.reference=refb->cast_to<T>(); + r.reference = refb->cast_to<T>(); ref(r); - r.reference=NULL; + r.reference = NULL; } - inline bool is_valid() const { return reference!=NULL; } - inline bool is_null() const { return reference==NULL; } + inline bool is_valid() const { return reference != NULL; } + inline bool is_null() const { return reference == NULL; } void unref() { //TODO this should be moved to mutexes, since this engine does not really @@ -291,99 +285,92 @@ public: memdelete(reference); } - reference=NULL; + reference = NULL; } void instance() { - ref( memnew( T )); + ref(memnew(T)); } Ref() { - reference=NULL; + reference = NULL; } ~Ref() { unref(); } - }; typedef Ref<Reference> REF; - class WeakRef : public Reference { - GDCLASS(WeakRef,Reference); + GDCLASS(WeakRef, Reference); ObjectID ref; + protected: static void _bind_methods(); public: Variant get_ref() const; void set_obj(Object *p_object); - void set_ref(const REF& p_ref); + void set_ref(const REF &p_ref); WeakRef(); }; #ifdef PTRCALL_ENABLED -template<class T> -struct PtrToArg< Ref<T> > { +template <class T> +struct PtrToArg<Ref<T> > { - _FORCE_INLINE_ static Ref<T> convert(const void* p_ptr) { + _FORCE_INLINE_ static Ref<T> convert(const void *p_ptr) { - return Ref<T>(reinterpret_cast<const T*>(p_ptr)); + return Ref<T>(reinterpret_cast<const T *>(p_ptr)); } - _FORCE_INLINE_ static void encode(Ref<T> p_val,const void* p_ptr) { + _FORCE_INLINE_ static void encode(Ref<T> p_val, const void *p_ptr) { - *(Ref<Reference>*)p_ptr=p_val; + *(Ref<Reference> *)p_ptr = p_val; } - }; +template <class T> +struct PtrToArg<const Ref<T> &> { -template<class T> -struct PtrToArg< const Ref<T>& > { + _FORCE_INLINE_ static Ref<T> convert(const void *p_ptr) { - _FORCE_INLINE_ static Ref<T> convert(const void* p_ptr) { - - return Ref<T>(reinterpret_cast<const T*>(p_ptr)); + return Ref<T>(reinterpret_cast<const T *>(p_ptr)); } - }; - //this is for RefPtr -template<> -struct PtrToArg< RefPtr > { +template <> +struct PtrToArg<RefPtr> { - _FORCE_INLINE_ static RefPtr convert(const void* p_ptr) { + _FORCE_INLINE_ static RefPtr convert(const void *p_ptr) { - return Ref<Reference>(reinterpret_cast<const Reference*>(p_ptr)).get_ref_ptr(); + return Ref<Reference>(reinterpret_cast<const Reference *>(p_ptr)).get_ref_ptr(); } - _FORCE_INLINE_ static void encode(RefPtr p_val,const void* p_ptr) { + _FORCE_INLINE_ static void encode(RefPtr p_val, const void *p_ptr) { Ref<Reference> r = p_val; - *(Ref<Reference>*)p_ptr=r; + *(Ref<Reference> *)p_ptr = r; } - }; -template<> -struct PtrToArg< const RefPtr& > { +template <> +struct PtrToArg<const RefPtr &> { - _FORCE_INLINE_ static RefPtr convert(const void* p_ptr) { + _FORCE_INLINE_ static RefPtr convert(const void *p_ptr) { - return Ref<Reference>(reinterpret_cast<const Reference*>(p_ptr)).get_ref_ptr(); + return Ref<Reference>(reinterpret_cast<const Reference *>(p_ptr)).get_ref_ptr(); } - }; #endif diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp index 00f6f8662f..7ebacb5b5d 100644 --- a/core/register_core_types.cpp +++ b/core/register_core_types.cpp @@ -28,90 +28,82 @@ /*************************************************************************/ #include "register_core_types.h" -#include "io/tcp_server.h" -#include "io/packet_peer_udp.h" -#include "io/config_file.h" -#include "os/main_loop.h" -#include "io/packet_peer.h" -#include "math/a_star.h" -#include "math/triangle_mesh.h" -#include "global_config.h" -#include "class_db.h" -#include "geometry.h" #include "bind/core_bind.h" -#include "core_string_names.h" -#include "path_remap.h" -#include "translation.h" +#include "class_db.h" #include "compressed_translation.h" -#include "io/translation_loader_po.h" +#include "core/io/xml_parser.h" +#include "core_string_names.h" +#include "func_ref.h" +#include "geometry.h" +#include "global_config.h" +#include "input_map.h" +#include "io/config_file.h" +#include "io/http_client.h" +#include "io/packet_peer.h" +#include "io/packet_peer_udp.h" +#include "io/pck_packer.h" #include "io/resource_format_binary.h" #include "io/resource_import.h" #include "io/stream_peer_ssl.h" +#include "io/tcp_server.h" +#include "io/translation_loader_po.h" +#include "math/a_star.h" +#include "math/triangle_mesh.h" #include "os/input.h" -#include "core/io/xml_parser.h" -#include "io/http_client.h" -#include "io/pck_packer.h" +#include "os/main_loop.h" #include "packed_data_container.h" -#include "func_ref.h" -#include "input_map.h" +#include "path_remap.h" +#include "translation.h" #include "undo_redo.h" -static ResourceFormatSaverBinary *resource_saver_binary=NULL; -static ResourceFormatLoaderBinary *resource_loader_binary=NULL; -static ResourceFormatImporter *resource_format_importer=NULL; +static ResourceFormatSaverBinary *resource_saver_binary = NULL; +static ResourceFormatLoaderBinary *resource_loader_binary = NULL; +static ResourceFormatImporter *resource_format_importer = NULL; -static _ResourceLoader *_resource_loader=NULL; -static _ResourceSaver *_resource_saver=NULL; -static _OS *_os=NULL; -static _Engine *_engine=NULL; -static _ClassDB *_classdb=NULL; +static _ResourceLoader *_resource_loader = NULL; +static _ResourceSaver *_resource_saver = NULL; +static _OS *_os = NULL; +static _Engine *_engine = NULL; +static _ClassDB *_classdb = NULL; static _Marshalls *_marshalls = NULL; -static TranslationLoaderPO *resource_format_po=NULL; +static TranslationLoaderPO *resource_format_po = NULL; -static IP* ip = NULL; +static IP *ip = NULL; -static _Geometry *_geometry=NULL; +static _Geometry *_geometry = NULL; extern Mutex *_global_mutex; - - extern void register_variant_methods(); extern void unregister_variant_methods(); - void register_core_types() { ObjectDB::setup(); ResourceCache::setup(); MemoryPool::setup(); - _global_mutex=Mutex::create(); - + _global_mutex = Mutex::create(); StringName::setup(); - register_variant_methods(); - CoreStringNames::create(); - resource_format_po = memnew( TranslationLoaderPO ); - ResourceLoader::add_resource_format_loader( resource_format_po ); - + resource_format_po = memnew(TranslationLoaderPO); + ResourceLoader::add_resource_format_loader(resource_format_po); - resource_saver_binary = memnew( ResourceFormatSaverBinary ); + resource_saver_binary = memnew(ResourceFormatSaverBinary); ResourceSaver::add_resource_format_saver(resource_saver_binary); - resource_loader_binary = memnew( ResourceFormatLoaderBinary ); + resource_loader_binary = memnew(ResourceFormatLoaderBinary); ResourceLoader::add_resource_format_loader(resource_loader_binary); - resource_format_importer = memnew( ResourceFormatImporter ); + resource_format_importer = memnew(ResourceFormatImporter); ResourceLoader::add_resource_format_loader(resource_format_importer); ClassDB::register_class<Object>(); - ClassDB::register_class<Reference>(); ClassDB::register_class<WeakRef>(); ClassDB::register_class<Resource>(); @@ -153,58 +145,47 @@ void register_core_types() { ip = IP::create(); - _geometry = memnew(_Geometry); - - _resource_loader=memnew(_ResourceLoader); - _resource_saver=memnew(_ResourceSaver); - _os=memnew(_OS); - _engine=memnew(_Engine); - _classdb=memnew(_ClassDB); + _resource_loader = memnew(_ResourceLoader); + _resource_saver = memnew(_ResourceSaver); + _os = memnew(_OS); + _engine = memnew(_Engine); + _classdb = memnew(_ClassDB); _marshalls = memnew(_Marshalls); - - - } void register_core_settings() { //since in register core types, globals may not e present - GLOBAL_DEF( "network/packets/packet_stream_peer_max_buffer_po2",(16)); - + GLOBAL_DEF("network/packets/packet_stream_peer_max_buffer_po2", (16)); } void register_core_singletons() { - - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("GlobalConfig",GlobalConfig::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("IP",IP::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Geometry",_Geometry::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("ResourceLoader",_ResourceLoader::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("ResourceSaver",_ResourceSaver::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("OS",_OS::get_singleton() ) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Engine",_Engine::get_singleton() ) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("ClassDB",_classdb ) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Marshalls",_Marshalls::get_singleton() ) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("TranslationServer",TranslationServer::get_singleton() ) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Input",Input::get_singleton() ) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("InputMap",InputMap::get_singleton() ) ); - - + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("GlobalConfig", GlobalConfig::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("IP", IP::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Geometry", _Geometry::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ResourceLoader", _ResourceLoader::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ResourceSaver", _ResourceSaver::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("OS", _OS::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Engine", _Engine::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ClassDB", _classdb)); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Marshalls", _Marshalls::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("TranslationServer", TranslationServer::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Input", Input::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("InputMap", InputMap::get_singleton())); } void unregister_core_types() { + memdelete(_resource_loader); + memdelete(_resource_saver); + memdelete(_os); + memdelete(_engine); + memdelete(_classdb); + memdelete(_marshalls); - - memdelete( _resource_loader ); - memdelete( _resource_saver ); - memdelete( _os); - memdelete( _engine ); - memdelete( _classdb ); - memdelete( _marshalls ); - - memdelete( _geometry ); + memdelete(_geometry); if (resource_saver_binary) memdelete(resource_saver_binary); @@ -213,13 +194,11 @@ void unregister_core_types() { if (resource_format_importer) memdelete(resource_format_importer); - - memdelete( resource_format_po ); + memdelete(resource_format_po); if (ip) memdelete(ip); - ObjectDB::cleanup(); unregister_variant_methods(); @@ -231,9 +210,8 @@ void unregister_core_types() { if (_global_mutex) { memdelete(_global_mutex); - _global_mutex=NULL; //still needed at a few places + _global_mutex = NULL; //still needed at a few places }; MemoryPool::cleanup(); - } diff --git a/core/resource.cpp b/core/resource.cpp index fe3cb2df92..e9ce4038d9 100644 --- a/core/resource.cpp +++ b/core/resource.cpp @@ -29,40 +29,36 @@ #include "resource.h" #include "core_string_names.h" -#include "os/file_access.h" #include "io/resource_loader.h" +#include "os/file_access.h" #include "script_language.h" #include <stdio.h> - void Resource::emit_changed() { emit_signal(CoreStringNames::get_singleton()->changed); } - void Resource::_resource_path_changed() { - - } -void Resource::set_path(const String& p_path, bool p_take_over) { +void Resource::set_path(const String &p_path, bool p_take_over) { - if (path_cache==p_path) + if (path_cache == p_path) return; - if (path_cache!="") { + if (path_cache != "") { ResourceCache::lock->write_lock(); ResourceCache::resources.erase(path_cache); ResourceCache::lock->write_unlock(); } - path_cache=""; + path_cache = ""; ResourceCache::lock->read_lock(); - bool has_path = ResourceCache::resources.has( p_path ); + bool has_path = ResourceCache::resources.has(p_path); ResourceCache::lock->read_unlock(); if (has_path) { @@ -72,28 +68,26 @@ void Resource::set_path(const String& p_path, bool p_take_over) { ResourceCache::resources.get(p_path)->set_name(""); ResourceCache::lock->write_unlock(); } else { - ERR_EXPLAIN("Another resource is loaded from path: "+p_path); + ERR_EXPLAIN("Another resource is loaded from path: " + p_path); ResourceCache::lock->read_lock(); - bool exists = ResourceCache::resources.has( p_path ); + bool exists = ResourceCache::resources.has(p_path); ResourceCache::lock->read_unlock(); - ERR_FAIL_COND( exists ); + ERR_FAIL_COND(exists); } - } - path_cache=p_path; + path_cache = p_path; - if (path_cache!="") { + if (path_cache != "") { ResourceCache::lock->write_lock(); - ResourceCache::resources[path_cache]=this; + ResourceCache::resources[path_cache] = this; ResourceCache::lock->write_unlock(); } _change_notify("resource_path"); _resource_path_changed(); - } String Resource::get_path() const { @@ -103,20 +97,18 @@ String Resource::get_path() const { void Resource::set_subindex(int p_sub_index) { - subindex=p_sub_index; + subindex = p_sub_index; } -int Resource::get_subindex() const{ +int Resource::get_subindex() const { return subindex; } +void Resource::set_name(const String &p_name) { -void Resource::set_name(const String& p_name) { - - name=p_name; + name = p_name; _change_notify("resource_name"); - } String Resource::get_name() const { @@ -130,12 +122,11 @@ bool Resource::editor_can_reload_from_file() { void Resource::reload_from_file() { - - String path=get_path(); + String path = get_path(); if (!path.is_resource_file()) return; - Ref<Resource> s = ResourceLoader::load(path,get_class(),true); + Ref<Resource> s = ResourceLoader::load(path, get_class(), true); if (!s.is_valid()) return; @@ -143,56 +134,51 @@ void Resource::reload_from_file() { List<PropertyInfo> pi; s->get_property_list(&pi); - for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) { - if (!(E->get().usage&PROPERTY_USAGE_STORAGE)) + if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; - if (E->get().name=="resource_path") + if (E->get().name == "resource_path") continue; //do not change path - set(E->get().name,s->get(E->get().name)); - + set(E->get().name, s->get(E->get().name)); } } - Ref<Resource> Resource::duplicate_for_local_scene(Node *p_for_scene, Map<Ref<Resource>, Ref<Resource> > &remap_cache) { - List<PropertyInfo> plist; get_property_list(&plist); + Resource *r = (Resource *)ClassDB::instance(get_class()); + ERR_FAIL_COND_V(!r, Ref<Resource>()); - Resource *r = (Resource*)ClassDB::instance(get_class()); - ERR_FAIL_COND_V(!r,Ref<Resource>()); - - r->local_scene=p_for_scene; + r->local_scene = p_for_scene; - for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - if (!(E->get().usage&PROPERTY_USAGE_STORAGE)) + if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; Variant p = get(E->get().name); - if (p.get_type()==Variant::OBJECT) { + if (p.get_type() == Variant::OBJECT) { RES sr = p; if (sr.is_valid()) { if (sr->is_local_to_scene()) { if (remap_cache.has(sr)) { - p=remap_cache[sr]; + p = remap_cache[sr]; } else { - - RES dupe = sr->duplicate_for_local_scene(p_for_scene,remap_cache); - p=dupe; - remap_cache[sr]=dupe; + RES dupe = sr->duplicate_for_local_scene(p_for_scene, remap_cache); + p = dupe; + remap_cache[sr] = dupe; } } } } - r->set(E->get().name,p); + r->set(E->get().name, p); } return Ref<Resource>(r); @@ -200,50 +186,45 @@ Ref<Resource> Resource::duplicate_for_local_scene(Node *p_for_scene, Map<Ref<Res Ref<Resource> Resource::duplicate(bool p_subresources) { - List<PropertyInfo> plist; get_property_list(&plist); + Resource *r = (Resource *)ClassDB::instance(get_class()); + ERR_FAIL_COND_V(!r, Ref<Resource>()); - Resource *r = (Resource*)ClassDB::instance(get_class()); - ERR_FAIL_COND_V(!r,Ref<Resource>()); - - for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - if (!(E->get().usage&PROPERTY_USAGE_STORAGE)) + if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; Variant p = get(E->get().name); - if (p.get_type()==Variant::OBJECT && p_subresources) { + if (p.get_type() == Variant::OBJECT && p_subresources) { RES sr = p; if (sr.is_valid()) - p=sr->duplicate(true); + p = sr->duplicate(true); } - r->set(E->get().name,p); + r->set(E->get().name, p); } return Ref<Resource>(r); } +void Resource::_set_path(const String &p_path) { -void Resource::_set_path(const String& p_path) { - - set_path(p_path,false); + set_path(p_path, false); } -void Resource::_take_over_path(const String& p_path) { +void Resource::_take_over_path(const String &p_path) { - set_path(p_path,true); + set_path(p_path, true); } - RID Resource::get_rid() const { return RID(); } - void Resource::register_owner(Object *p_owner) { owners.insert(p_owner->get_instance_ID()); @@ -252,23 +233,20 @@ void Resource::register_owner(Object *p_owner) { void Resource::unregister_owner(Object *p_owner) { owners.erase(p_owner->get_instance_ID()); - } - void Resource::notify_change_to_owners() { - for(Set<ObjectID>::Element *E=owners.front();E;E=E->next()) { + for (Set<ObjectID>::Element *E = owners.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->get()); ERR_EXPLAIN("Object was deleted, while still owning a resource"); ERR_CONTINUE(!obj); //wtf //TODO store string - obj->call("resource_changed",RES(this)); + obj->call("resource_changed", RES(this)); } } - #ifdef TOOLS_ENABLED uint32_t Resource::hash_edited_version() const { @@ -278,25 +256,24 @@ uint32_t Resource::hash_edited_version() const { List<PropertyInfo> plist; get_property_list(&plist); - for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - if (E->get().type==Variant::OBJECT && E->get().hint==PROPERTY_HINT_RESOURCE_TYPE) { + if (E->get().type == Variant::OBJECT && E->get().hint == PROPERTY_HINT_RESOURCE_TYPE) { RES res = get(E->get().name); if (res.is_valid()) { - hash = hash_djb2_one_32(res->hash_edited_version(),hash); + hash = hash_djb2_one_32(res->hash_edited_version(), hash); } } } return hash; - } #endif void Resource::set_local_to_scene(bool p_enable) { - local_to_scene=p_enable; + local_to_scene = p_enable; } bool Resource::is_local_to_scene() const { @@ -304,7 +281,7 @@ bool Resource::is_local_to_scene() const { return local_to_scene; } -Node* Resource::get_local_scene() const { +Node *Resource::get_local_scene() const { if (local_scene) return local_scene; @@ -322,51 +299,46 @@ void Resource::setup_local_to_scene() { get_script_instance()->call("_setup_local_to_scene"); } -Node* (*Resource::_get_local_scene_func)()=NULL; - +Node *(*Resource::_get_local_scene_func)() = NULL; void Resource::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_path","path"),&Resource::_set_path); - ClassDB::bind_method(D_METHOD("take_over_path","path"),&Resource::_take_over_path); - ClassDB::bind_method(D_METHOD("get_path"),&Resource::get_path); - ClassDB::bind_method(D_METHOD("set_name","name"),&Resource::set_name); - ClassDB::bind_method(D_METHOD("get_name"),&Resource::get_name); - ClassDB::bind_method(D_METHOD("get_rid"),&Resource::get_rid); - ClassDB::bind_method(D_METHOD("set_local_to_scene","enable"),&Resource::set_local_to_scene); - ClassDB::bind_method(D_METHOD("is_local_to_scene"),&Resource::is_local_to_scene); - ClassDB::bind_method(D_METHOD("get_local_scene:Node"),&Resource::get_local_scene); - ClassDB::bind_method(D_METHOD("setup_local_to_scene"),&Resource::setup_local_to_scene); - - ClassDB::bind_method(D_METHOD("duplicate","subresources"),&Resource::duplicate,DEFVAL(false)); - ADD_SIGNAL( MethodInfo("changed") ); - ADD_GROUP("Resource","resource_"); - ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"resource_local_to_scene" ), "set_local_to_scene","is_local_to_scene"); - ADD_PROPERTY( PropertyInfo(Variant::STRING,"resource_path",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR ), "set_path","get_path"); - ADD_PROPERTYNZ( PropertyInfo(Variant::STRING,"resource_name"), "set_name","get_name"); + ClassDB::bind_method(D_METHOD("set_path", "path"), &Resource::_set_path); + ClassDB::bind_method(D_METHOD("take_over_path", "path"), &Resource::_take_over_path); + ClassDB::bind_method(D_METHOD("get_path"), &Resource::get_path); + ClassDB::bind_method(D_METHOD("set_name", "name"), &Resource::set_name); + ClassDB::bind_method(D_METHOD("get_name"), &Resource::get_name); + ClassDB::bind_method(D_METHOD("get_rid"), &Resource::get_rid); + ClassDB::bind_method(D_METHOD("set_local_to_scene", "enable"), &Resource::set_local_to_scene); + ClassDB::bind_method(D_METHOD("is_local_to_scene"), &Resource::is_local_to_scene); + ClassDB::bind_method(D_METHOD("get_local_scene:Node"), &Resource::get_local_scene); + ClassDB::bind_method(D_METHOD("setup_local_to_scene"), &Resource::setup_local_to_scene); - BIND_VMETHOD( MethodInfo("_setup_local_to_scene") ); + ClassDB::bind_method(D_METHOD("duplicate", "subresources"), &Resource::duplicate, DEFVAL(false)); + ADD_SIGNAL(MethodInfo("changed")); + ADD_GROUP("Resource", "resource_"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "resource_local_to_scene"), "set_local_to_scene", "is_local_to_scene"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "resource_path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_path", "get_path"); + ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "resource_name"), "set_name", "get_name"); + BIND_VMETHOD(MethodInfo("_setup_local_to_scene")); } Resource::Resource() { #ifdef TOOLS_ENABLED - last_modified_time=0; - import_last_modified_time=0; + last_modified_time = 0; + import_last_modified_time = 0; #endif - subindex=0; - local_to_scene=false; - local_scene=NULL; + subindex = 0; + local_to_scene = false; + local_scene = NULL; } - - - Resource::~Resource() { - if (path_cache!="") { + if (path_cache != "") { ResourceCache::lock->write_lock(); ResourceCache::resources.erase(path_cache); ResourceCache::lock->write_unlock(); @@ -376,9 +348,9 @@ Resource::~Resource() { } } -HashMap<String,Resource*> ResourceCache::resources; +HashMap<String, Resource *> ResourceCache::resources; -RWLock *ResourceCache::lock=NULL; +RWLock *ResourceCache::lock = NULL; void ResourceCache::setup() { @@ -393,7 +365,6 @@ void ResourceCache::clear() { memdelete(lock); } - void ResourceCache::reload_externals() { /* @@ -404,16 +375,15 @@ void ResourceCache::reload_externals() { */ } -bool ResourceCache::has(const String& p_path) { +bool ResourceCache::has(const String &p_path) { lock->read_lock(); bool b = resources.has(p_path); lock->read_unlock(); - return b; } -Resource *ResourceCache::get(const String& p_path) { +Resource *ResourceCache::get(const String &p_path) { lock->read_lock(); @@ -428,20 +398,16 @@ Resource *ResourceCache::get(const String& p_path) { return *res; } - void ResourceCache::get_cached_resources(List<Ref<Resource> > *p_resources) { - lock->read_lock(); - const String* K=NULL; - while((K=resources.next(K))) { + const String *K = NULL; + while ((K = resources.next(K))) { Resource *r = resources[*K]; - p_resources->push_back( Ref<Resource>( r )); - + p_resources->push_back(Ref<Resource>(r)); } lock->read_unlock(); - } int ResourceCache::get_cached_resource_count() { @@ -453,42 +419,39 @@ int ResourceCache::get_cached_resource_count() { return rc; } -void ResourceCache::dump(const char* p_file,bool p_short) { +void ResourceCache::dump(const char *p_file, bool p_short) { #ifdef DEBUG_ENABLED lock->read_lock(); - Map<String,int> type_count; - + Map<String, int> type_count; - FileAccess *f=NULL; + FileAccess *f = NULL; if (p_file) { - f = FileAccess::open(p_file,FileAccess::WRITE); + f = FileAccess::open(p_file, FileAccess::WRITE); ERR_FAIL_COND(!f); - } - const String* K=NULL; - while((K=resources.next(K))) { + const String *K = NULL; + while ((K = resources.next(K))) { Resource *r = resources[*K]; if (!type_count.has(r->get_class())) { - type_count[r->get_class()]=0; + type_count[r->get_class()] = 0; } - type_count[r->get_class()]++; if (!p_short) { if (f) - f->store_line(r->get_class()+": "+r->get_path()); + f->store_line(r->get_class() + ": " + r->get_path()); } } - for(Map<String,int>::Element *E=type_count.front();E;E=E->next()) { + for (Map<String, int>::Element *E = type_count.front(); E; E = E->next()) { if (f) - f->store_line(E->key()+" count: "+itos(E->get())); + f->store_line(E->key() + " count: " + itos(E->get())); } if (f) { f->close(); diff --git a/core/resource.h b/core/resource.h index b29077a3b8..96a3a16fc5 100644 --- a/core/resource.h +++ b/core/resource.h @@ -29,34 +29,33 @@ #ifndef RESOURCE_H #define RESOURCE_H +#include "class_db.h" #include "object.h" -#include "safe_refcount.h" #include "ref_ptr.h" #include "reference.h" -#include "class_db.h" +#include "safe_refcount.h" /** @author Juan Linietsky <reduzio@gmail.com> */ -#define RES_BASE_EXTENSION(m_ext)\ -public:\ -static void register_custom_data_to_otdb() { ClassDB::add_resource_base_extension(m_ext,get_class_static()); }\ -virtual String get_base_extension() const { return m_ext; }\ +#define RES_BASE_EXTENSION(m_ext) \ +public: \ + static void register_custom_data_to_otdb() { ClassDB::add_resource_base_extension(m_ext, get_class_static()); } \ + virtual String get_base_extension() const { return m_ext; } \ + \ private: - - class Resource : public Reference { - GDCLASS( Resource, Reference ); + GDCLASS(Resource, Reference); OBJ_CATEGORY("Resources"); RES_BASE_EXTENSION("res"); Set<ObjectID> owners; -friend class ResBase; -friend class ResourceCache; + friend class ResBase; + friend class ResourceCache; String name; String path_cache; @@ -71,11 +70,10 @@ friend class ResourceCache; #endif bool local_to_scene; -friend class SceneState; - Node* local_scene; + friend class SceneState; + Node *local_scene; protected: - void emit_changed(); void notify_change_to_owners(); @@ -83,11 +81,11 @@ protected: virtual void _resource_path_changed(); static void _bind_methods(); - void _set_path(const String& p_path); - void _take_over_path(const String& p_path); -public: + void _set_path(const String &p_path); + void _take_over_path(const String &p_path); - static Node* (*_get_local_scene_func)(); //used by editor +public: + static Node *(*_get_local_scene_func)(); //used by editor virtual bool editor_can_reload_from_file(); virtual void reload_from_file(); @@ -95,35 +93,35 @@ public: void register_owner(Object *p_owner); void unregister_owner(Object *p_owner); - void set_name(const String& p_name); + void set_name(const String &p_name); String get_name() const; - virtual void set_path(const String& p_path,bool p_take_over=false); + virtual void set_path(const String &p_path, bool p_take_over = false); String get_path() const; void set_subindex(int p_sub_index); int get_subindex() const; - Ref<Resource> duplicate(bool p_subresources=false); - Ref<Resource> duplicate_for_local_scene(Node *p_scene,Map<Ref<Resource>,Ref<Resource> >& remap_cache); + Ref<Resource> duplicate(bool p_subresources = false); + Ref<Resource> duplicate_for_local_scene(Node *p_scene, Map<Ref<Resource>, Ref<Resource> > &remap_cache); void set_local_to_scene(bool p_enable); bool is_local_to_scene() const; virtual void setup_local_to_scene(); - Node* get_local_scene() const; + Node *get_local_scene() const; #ifdef TOOLS_ENABLED uint32_t hash_edited_version() const; - virtual void set_last_modified_time(uint64_t p_time) { last_modified_time=p_time; } + virtual void set_last_modified_time(uint64_t p_time) { last_modified_time = p_time; } uint64_t get_last_modified_time() const { return last_modified_time; } - virtual void set_import_last_modified_time(uint64_t p_time) { import_last_modified_time=p_time; } + virtual void set_import_last_modified_time(uint64_t p_time) { import_last_modified_time = p_time; } uint64_t get_import_last_modified_time() const { return import_last_modified_time; } - void set_import_path(const String& p_path) { import_path=p_path; } + void set_import_path(const String &p_path) { import_path = p_path; } String get_import_path() const { return import_path; } #endif @@ -132,29 +130,26 @@ public: Resource(); ~Resource(); - }; - typedef Ref<Resource> RES; class ResourceCache { -friend class Resource; + friend class Resource; static RWLock *lock; - static HashMap<String,Resource*> resources; -friend void unregister_core_types(); + static HashMap<String, Resource *> resources; + friend void unregister_core_types(); static void clear(); -friend void register_core_types(); + friend void register_core_types(); static void setup(); -public: +public: static void reload_externals(); - static bool has(const String& p_path); - static Resource* get(const String& p_path); - static void dump(const char* p_file=NULL,bool p_short=false); + static bool has(const String &p_path); + static Resource *get(const String &p_path); + static void dump(const char *p_file = NULL, bool p_short = false); static void get_cached_resources(List<Ref<Resource> > *p_resources); static int get_cached_resource_count(); - }; #endif diff --git a/core/rid.cpp b/core/rid.cpp index c7e487f91a..1c673f8ba2 100644 --- a/core/rid.cpp +++ b/core/rid.cpp @@ -28,13 +28,9 @@ /*************************************************************************/ #include "rid.h" - - RID_Data::~RID_Data() { - } - SafeRefCount RID_OwnerBase::refcount; void RID_OwnerBase::init_rid() { diff --git a/core/rid.h b/core/rid.h index 8dc535c9c1..2711ac6598 100644 --- a/core/rid.h +++ b/core/rid.h @@ -29,169 +29,151 @@ #ifndef RID_H #define RID_H - -#include "safe_refcount.h" -#include "typedefs.h" +#include "list.h" #include "os/memory.h" +#include "safe_refcount.h" #include "set.h" -#include "list.h" +#include "typedefs.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - class RID_OwnerBase; class RID_Data { -friend class RID_OwnerBase; + friend class RID_OwnerBase; #ifndef DEBUG_ENABLED RID_OwnerBase *_owner; #endif uint32_t _id; + public: _FORCE_INLINE_ uint32_t get_id() const { return _id; } virtual ~RID_Data(); }; - class RID { -friend class RID_OwnerBase; + friend class RID_OwnerBase; mutable RID_Data *_data; public: - _FORCE_INLINE_ RID_Data *get_data() const { return _data; } - _FORCE_INLINE_ bool operator==(const RID& p_rid) const { + _FORCE_INLINE_ bool operator==(const RID &p_rid) const { - return _data==p_rid._data; + return _data == p_rid._data; } - _FORCE_INLINE_ bool operator<(const RID& p_rid) const { + _FORCE_INLINE_ bool operator<(const RID &p_rid) const { return _data < p_rid._data; } - _FORCE_INLINE_ bool operator<=(const RID& p_rid) const { + _FORCE_INLINE_ bool operator<=(const RID &p_rid) const { return _data <= p_rid._data; } - _FORCE_INLINE_ bool operator>(const RID& p_rid) const { + _FORCE_INLINE_ bool operator>(const RID &p_rid) const { return _data > p_rid._data; } - _FORCE_INLINE_ bool operator!=(const RID& p_rid) const { + _FORCE_INLINE_ bool operator!=(const RID &p_rid) const { - return _data!=p_rid._data; + return _data != p_rid._data; } - _FORCE_INLINE_ bool is_valid() const { return _data!=NULL; } + _FORCE_INLINE_ bool is_valid() const { return _data != NULL; } - _FORCE_INLINE_ uint32_t get_id() const { return _data?_data->get_id():0; } + _FORCE_INLINE_ uint32_t get_id() const { return _data ? _data->get_id() : 0; } _FORCE_INLINE_ RID() { - _data=NULL; + _data = NULL; } - }; - class RID_OwnerBase { protected: - static SafeRefCount refcount; - _FORCE_INLINE_ void _set_data(RID& p_rid, RID_Data* p_data) { - p_rid._data=p_data; + _FORCE_INLINE_ void _set_data(RID &p_rid, RID_Data *p_data) { + p_rid._data = p_data; refcount.ref(); - p_data->_id=refcount.get(); + p_data->_id = refcount.get(); #ifndef DEBUG_ENABLED - p_data->_owner=this; + p_data->_owner = this; #endif } #ifndef DEBUG_ENABLED - _FORCE_INLINE_ bool _is_owner(const RID& p_rid) const { - - return this==p_rid._data->_owner; + _FORCE_INLINE_ bool _is_owner(const RID &p_rid) const { + return this == p_rid._data->_owner; } - _FORCE_INLINE_ void _remove_owner(RID& p_rid) { - - p_rid._data->_owner=NULL; + _FORCE_INLINE_ void _remove_owner(RID &p_rid) { + p_rid._data->_owner = NULL; } # #endif - public: - - - virtual void get_owned_list(List<RID> *p_owned)=0; + virtual void get_owned_list(List<RID> *p_owned) = 0; static void init_rid(); virtual ~RID_OwnerBase() {} }; -template<class T> +template <class T> class RID_Owner : public RID_OwnerBase { public: #ifdef DEBUG_ENABLED - mutable Set<RID_Data*> id_map; + mutable Set<RID_Data *> id_map; #endif public: - - _FORCE_INLINE_ RID make_rid(T * p_data) { - + _FORCE_INLINE_ RID make_rid(T *p_data) { RID rid; - _set_data(rid,p_data); + _set_data(rid, p_data); #ifdef DEBUG_ENABLED - id_map.insert(p_data) ; + id_map.insert(p_data); #endif return rid; } - _FORCE_INLINE_ T * get(const RID& p_rid) { + _FORCE_INLINE_ T *get(const RID &p_rid) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!p_rid.is_valid(),NULL); - ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()),NULL); + ERR_FAIL_COND_V(!p_rid.is_valid(), NULL); + ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()), NULL); #endif - return static_cast<T*>(p_rid.get_data()); - + return static_cast<T *>(p_rid.get_data()); } - _FORCE_INLINE_ T * getornull(const RID& p_rid) { + _FORCE_INLINE_ T *getornull(const RID &p_rid) { #ifdef DEBUG_ENABLED if (p_rid.get_data()) { - ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()),NULL); + ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()), NULL); } #endif - return static_cast<T*>(p_rid.get_data()); - + return static_cast<T *>(p_rid.get_data()); } + _FORCE_INLINE_ T *getptr(const RID &p_rid) { - _FORCE_INLINE_ T * getptr(const RID& p_rid) { - - return static_cast<T*>(p_rid.get_data()); - + return static_cast<T *>(p_rid.get_data()); } + _FORCE_INLINE_ bool owns(const RID &p_rid) const { - _FORCE_INLINE_ bool owns(const RID& p_rid) const { - - if (p_rid.get_data()==NULL) + if (p_rid.get_data() == NULL) return false; #ifdef DEBUG_ENABLED return id_map.has(p_rid.get_data()); @@ -211,20 +193,15 @@ public: void get_owned_list(List<RID> *p_owned) { - - #ifdef DEBUG_ENABLED - for (typename Set<RID_Data*>::Element *E=id_map.front();E;E=E->next()) { + for (typename Set<RID_Data *>::Element *E = id_map.front(); E; E = E->next()) { RID r; - _set_data(r,static_cast<T*>(E->get())); + _set_data(r, static_cast<T *>(E->get())); p_owned->push_back(r); } #endif - } - }; - #endif diff --git a/core/ring_buffer.h b/core/ring_buffer.h index a4da0086e0..3c13cb8d1e 100644 --- a/core/ring_buffer.h +++ b/core/ring_buffer.h @@ -39,31 +39,30 @@ class RingBuffer { int write_pos; int size_mask; - inline int inc(int& p_var, int p_size) { + inline int inc(int &p_var, int p_size) { int ret = p_var; p_var += p_size; - p_var = p_var&size_mask; + p_var = p_var & size_mask; return ret; }; public: - T read() { ERR_FAIL_COND_V(space_left() < 1, T()); return data[inc(read_pos, 1)]; }; - int read(T* p_buf, int p_size, bool p_advance=true) { + int read(T *p_buf, int p_size, bool p_advance = true) { int left = data_left(); p_size = MIN(left, p_size); int pos = read_pos; int to_read = p_size; int dst = 0; - while(to_read) { + while (to_read) { int end = pos + to_read; end = MIN(end, size()); int total = end - pos; - for (int i=0; i<total; i++) { + for (int i = 0; i < total; i++) { p_buf[dst++] = data[pos + i]; }; to_read -= total; @@ -75,24 +74,24 @@ public: return p_size; }; - int copy(T* p_buf, int p_offset, int p_size) { + int copy(T *p_buf, int p_offset, int p_size) { int left = data_left(); - if ((p_offset+p_size)>left) { - p_size-=left-p_offset; - if (p_size<=0) + if ((p_offset + p_size) > left) { + p_size -= left - p_offset; + if (p_size <= 0) return 0; } p_size = MIN(left, p_size); int pos = read_pos; - inc(pos,p_offset); + inc(pos, p_offset); int to_read = p_size; int dst = 0; - while(to_read) { + while (to_read) { int end = pos + to_read; end = MIN(end, size()); int total = end - pos; - for (int i=0; i<total; i++) { + for (int i = 0; i < total; i++) { p_buf[dst++] = data[pos + i]; }; to_read -= total; @@ -107,13 +106,13 @@ public: return p_n; }; - Error write(const T& p_v) { - ERR_FAIL_COND_V( space_left() < 1, FAILED); + Error write(const T &p_v) { + ERR_FAIL_COND_V(space_left() < 1, FAILED); data[inc(write_pos, 1)] = p_v; return OK; }; - int write(const T* p_buf, int p_size) { + int write(const T *p_buf, int p_size) { int left = space_left(); p_size = MIN(left, p_size); @@ -127,8 +126,8 @@ public: end = MIN(end, size()); int total = end - pos; - for (int i=0; i<total; i++) { - data[pos+i] = p_buf[src++]; + for (int i = 0; i < total; i++) { + data[pos + i] = p_buf[src++]; }; to_write -= total; pos = 0; @@ -144,9 +143,9 @@ public: return size() + left - 1; }; if (left == 0) { - return size()-1; + return size() - 1; }; - return left -1; + return left - 1; }; inline int data_left() { return size() - space_left() - 1; @@ -159,17 +158,16 @@ public: inline void clear() { read_pos = 0; write_pos = 0; - } void resize(int p_power) { int old_size = size(); - int new_size = 1<<p_power; + int new_size = 1 << p_power; int mask = new_size - 1; - data.resize(1<<p_power); + data.resize(1 << p_power); if (old_size < new_size && read_pos > write_pos) { - for (int i=0; i<write_pos; i++) { - data[(old_size + i)&mask] = data[i]; + for (int i = 0; i < write_pos; i++) { + data[(old_size + i) & mask] = data[i]; }; write_pos = (old_size + write_pos) & mask; } else { @@ -180,12 +178,12 @@ public: size_mask = mask; }; - RingBuffer<T>(int p_power=0) { + RingBuffer<T>(int p_power = 0) { read_pos = 0; write_pos = 0; resize(p_power); }; - ~RingBuffer<T>() {}; + ~RingBuffer<T>(){}; }; #endif diff --git a/core/safe_refcount.cpp b/core/safe_refcount.cpp index 50617f2062..cbd79a322f 100644 --- a/core/safe_refcount.cpp +++ b/core/safe_refcount.cpp @@ -28,15 +28,13 @@ /*************************************************************************/ #include "safe_refcount.h" - // Atomic functions, these are used for multithread safe reference counters! #ifdef NO_THREADS +uint32_t atomic_conditional_increment(register uint32_t *pw) { -uint32_t atomic_conditional_increment( register uint32_t * pw ) { - - if (*pw==0) + if (*pw == 0) return 0; (*pw)++; @@ -44,20 +42,18 @@ uint32_t atomic_conditional_increment( register uint32_t * pw ) { return *pw; } -uint32_t atomic_increment( register uint32_t * pw ) { +uint32_t atomic_increment(register uint32_t *pw) { (*pw)++; return *pw; - } -uint32_t atomic_decrement( register uint32_t * pw ) { +uint32_t atomic_decrement(register uint32_t *pw) { (*pw)--; return *pw; - } #else @@ -66,54 +62,52 @@ uint32_t atomic_decrement( register uint32_t * pw ) { // don't pollute my namespace! #include <windows.h> -uint32_t atomic_conditional_increment( register uint32_t * pw ) { +uint32_t atomic_conditional_increment(register uint32_t *pw) { /* try to increment until it actually works */ // taken from boost while (true) { - uint32_t tmp = static_cast< uint32_t const volatile& >( *pw ); - if( tmp == 0 ) - return 0; // if zero, can't add to it anymore - if( InterlockedCompareExchange( (LONG volatile*)pw, tmp + 1, tmp ) == tmp ) - return tmp+1; + uint32_t tmp = static_cast<uint32_t const volatile &>(*pw); + if (tmp == 0) + return 0; // if zero, can't add to it anymore + if (InterlockedCompareExchange((LONG volatile *)pw, tmp + 1, tmp) == tmp) + return tmp + 1; } } -uint32_t atomic_decrement( register uint32_t * pw ) { - return InterlockedDecrement( (LONG volatile*)pw ); +uint32_t atomic_decrement(register uint32_t *pw) { + return InterlockedDecrement((LONG volatile *)pw); } -uint32_t atomic_increment( register uint32_t * pw ) { - return InterlockedIncrement( (LONG volatile*)pw ); +uint32_t atomic_increment(register uint32_t *pw) { + return InterlockedIncrement((LONG volatile *)pw); } #elif defined(__GNUC__) -uint32_t atomic_conditional_increment( register uint32_t * pw ) { +uint32_t atomic_conditional_increment(register uint32_t *pw) { while (true) { - uint32_t tmp = static_cast< uint32_t const volatile& >( *pw ); - if( tmp == 0 ) - return 0; // if zero, can't add to it anymore - if( __sync_val_compare_and_swap( pw, tmp, tmp + 1 ) == tmp ) - return tmp+1; + uint32_t tmp = static_cast<uint32_t const volatile &>(*pw); + if (tmp == 0) + return 0; // if zero, can't add to it anymore + if (__sync_val_compare_and_swap(pw, tmp, tmp + 1) == tmp) + return tmp + 1; } } -uint32_t atomic_decrement( register uint32_t * pw ) { - - return __sync_sub_and_fetch(pw,1); +uint32_t atomic_decrement(register uint32_t *pw) { + return __sync_sub_and_fetch(pw, 1); } -uint32_t atomic_increment( register uint32_t * pw ) { - - return __sync_add_and_fetch(pw,1); +uint32_t atomic_increment(register uint32_t *pw) { + return __sync_add_and_fetch(pw, 1); } #else - //no threads supported? +//no threads supported? #error Must provide atomic functions for this platform or compiler! #endif diff --git a/core/safe_refcount.h b/core/safe_refcount.h index 6e349d89d8..eeadeea8cf 100644 --- a/core/safe_refcount.h +++ b/core/safe_refcount.h @@ -35,34 +35,30 @@ #include "platform_config.h" #include "typedefs.h" - -uint32_t atomic_conditional_increment( register uint32_t * counter ); -uint32_t atomic_decrement( register uint32_t * pw ); -uint32_t atomic_increment( register uint32_t * pw ); - - +uint32_t atomic_conditional_increment(register uint32_t *counter); +uint32_t atomic_decrement(register uint32_t *pw); +uint32_t atomic_increment(register uint32_t *pw); struct SafeRefCount { - uint32_t count; + uint32_t count; public: - // destroy() is called when weak_count_ drops to zero. - bool ref() { //true on success + bool ref() { //true on success - return atomic_conditional_increment( &count ) != 0; + return atomic_conditional_increment(&count) != 0; } - uint32_t refval() { //true on success + uint32_t refval() { //true on success - return atomic_conditional_increment( &count ); + return atomic_conditional_increment(&count); } bool unref() { // true if must be disposed of - if( atomic_decrement ( &count ) == 0 ) { + if (atomic_decrement(&count) == 0) { return true; } @@ -74,13 +70,10 @@ public: return count; } - void init(uint32_t p_value=1) { + void init(uint32_t p_value = 1) { - count=p_value; + count = p_value; } - }; - - #endif diff --git a/core/script_debugger_local.cpp b/core/script_debugger_local.cpp index 22aceac4c5..b5ed9773f0 100644 --- a/core/script_debugger_local.cpp +++ b/core/script_debugger_local.cpp @@ -30,91 +30,91 @@ #include "os/os.h" -void ScriptDebuggerLocal::debug(ScriptLanguage *p_script,bool p_can_continue) { +void ScriptDebuggerLocal::debug(ScriptLanguage *p_script, bool p_can_continue) { - print_line("Debugger Break, Reason: '"+p_script->debug_get_error()+"'"); - print_line("*Frame "+itos(0)+" - "+p_script->debug_get_stack_level_source(0)+":"+itos(p_script->debug_get_stack_level_line(0))+" in function '"+p_script->debug_get_stack_level_function(0)+"'"); + print_line("Debugger Break, Reason: '" + p_script->debug_get_error() + "'"); + print_line("*Frame " + itos(0) + " - " + p_script->debug_get_stack_level_source(0) + ":" + itos(p_script->debug_get_stack_level_line(0)) + " in function '" + p_script->debug_get_stack_level_function(0) + "'"); print_line("Enter \"help\" for assistance."); - int current_frame=0; - int total_frames=p_script->debug_get_stack_level_count(); - while(true) { + int current_frame = 0; + int total_frames = p_script->debug_get_stack_level_count(); + while (true) { OS::get_singleton()->print("debug> "); String line = OS::get_singleton()->get_stdin_string().strip_edges(); - if (line=="") { - print_line("Debugger Break, Reason: '"+p_script->debug_get_error()+"'"); - print_line("*Frame "+itos(current_frame)+" - "+p_script->debug_get_stack_level_source(current_frame)+":"+itos(p_script->debug_get_stack_level_line(current_frame))+" in function '"+p_script->debug_get_stack_level_function(current_frame)+"'"); + if (line == "") { + print_line("Debugger Break, Reason: '" + p_script->debug_get_error() + "'"); + print_line("*Frame " + itos(current_frame) + " - " + p_script->debug_get_stack_level_source(current_frame) + ":" + itos(p_script->debug_get_stack_level_line(current_frame)) + " in function '" + p_script->debug_get_stack_level_function(current_frame) + "'"); print_line("Enter \"help\" for assistance."); - } else if (line=="c" || line=="continue") + } else if (line == "c" || line == "continue") break; - else if (line=="bt" || line=="breakpoint") { + else if (line == "bt" || line == "breakpoint") { - for(int i=0;i<total_frames;i++) { + for (int i = 0; i < total_frames; i++) { - String cfi=(current_frame==i)?"*":" "; //current frame indicator - print_line(cfi+"Frame "+itos(i)+" - "+p_script->debug_get_stack_level_source(i)+":"+itos(p_script->debug_get_stack_level_line(i))+" in function '"+p_script->debug_get_stack_level_function(i)+"'"); + String cfi = (current_frame == i) ? "*" : " "; //current frame indicator + print_line(cfi + "Frame " + itos(i) + " - " + p_script->debug_get_stack_level_source(i) + ":" + itos(p_script->debug_get_stack_level_line(i)) + " in function '" + p_script->debug_get_stack_level_function(i) + "'"); } } else if (line.begins_with("fr") || line.begins_with("frame")) { - if (line.get_slice_count(" ")==1) { - print_line("*Frame "+itos(current_frame)+" - "+p_script->debug_get_stack_level_source(current_frame)+":"+itos(p_script->debug_get_stack_level_line(current_frame))+" in function '"+p_script->debug_get_stack_level_function(current_frame)+"'"); + if (line.get_slice_count(" ") == 1) { + print_line("*Frame " + itos(current_frame) + " - " + p_script->debug_get_stack_level_source(current_frame) + ":" + itos(p_script->debug_get_stack_level_line(current_frame)) + " in function '" + p_script->debug_get_stack_level_function(current_frame) + "'"); } else { - int frame = line.get_slicec(' ',1).to_int(); - if (frame<0 || frame >=total_frames) { + int frame = line.get_slicec(' ', 1).to_int(); + if (frame < 0 || frame >= total_frames) { print_line("Error: Invalid frame."); } else { - current_frame=frame; - print_line("*Frame "+itos(frame)+" - "+p_script->debug_get_stack_level_source(frame)+":"+itos(p_script->debug_get_stack_level_line(frame))+" in function '"+p_script->debug_get_stack_level_function(frame)+"'"); + current_frame = frame; + print_line("*Frame " + itos(frame) + " - " + p_script->debug_get_stack_level_source(frame) + ":" + itos(p_script->debug_get_stack_level_line(frame)) + " in function '" + p_script->debug_get_stack_level_function(frame) + "'"); } } - } else if (line=="lv" || line=="locals") { + } else if (line == "lv" || line == "locals") { List<String> locals; List<Variant> values; - p_script->debug_get_stack_level_locals(current_frame,&locals, &values); - List<Variant>::Element* V = values.front(); - for (List<String>::Element *E=locals.front();E;E=E->next()) { + p_script->debug_get_stack_level_locals(current_frame, &locals, &values); + List<Variant>::Element *V = values.front(); + for (List<String>::Element *E = locals.front(); E; E = E->next()) { print_line(E->get() + ": " + String(V->get())); V = V->next(); } - } else if (line=="gv" || line=="globals") { + } else if (line == "gv" || line == "globals") { List<String> locals; List<Variant> values; p_script->debug_get_globals(&locals, &values); - List<Variant>::Element* V = values.front(); - for (List<String>::Element *E=locals.front();E;E=E->next()) { + List<Variant>::Element *V = values.front(); + for (List<String>::Element *E = locals.front(); E; E = E->next()) { print_line(E->get() + ": " + String(V->get())); V = V->next(); } - } else if (line=="mv" || line=="members") { + } else if (line == "mv" || line == "members") { List<String> locals; List<Variant> values; - p_script->debug_get_stack_level_members(current_frame,&locals, &values); - List<Variant>::Element* V = values.front(); - for (List<String>::Element *E=locals.front();E;E=E->next()) { + p_script->debug_get_stack_level_members(current_frame, &locals, &values); + List<Variant>::Element *V = values.front(); + for (List<String>::Element *E = locals.front(); E; E = E->next()) { print_line(E->get() + ": " + String(V->get())); V = V->next(); } } else if (line.begins_with("p") || line.begins_with("print")) { - if (line.get_slice_count(" ")<=1) { + if (line.get_slice_count(" ") <= 1) { print_line("Usage: print <expre>"); } else { - String expr = line.get_slicec(' ',2); - String res = p_script->debug_parse_stack_level_expression(current_frame,expr); + String expr = line.get_slicec(' ', 2); + String res = p_script->debug_parse_stack_level_expression(current_frame, expr); print_line(res); } - } else if (line=="s" || line=="step") { + } else if (line == "s" || line == "step") { set_depth(-1); set_lines_left(1); @@ -126,41 +126,39 @@ void ScriptDebuggerLocal::debug(ScriptLanguage *p_script,bool p_can_continue) { break; } else if (line.begins_with("br") || line.begins_with("break")) { - if (line.get_slice_count(" ")<=1) { + if (line.get_slice_count(" ") <= 1) { //show breakpoints } else { - - String bppos=line.get_slicec(' ',1); - String source=bppos.get_slicec(':',0).strip_edges(); - int line=bppos.get_slicec(':',1).strip_edges().to_int(); + String bppos = line.get_slicec(' ', 1); + String source = bppos.get_slicec(':', 0).strip_edges(); + int line = bppos.get_slicec(':', 1).strip_edges().to_int(); source = breakpoint_find_source(source); - insert_breakpoint(line,source); + insert_breakpoint(line, source); - print_line("BreakPoint at "+source+":"+itos(line)); + print_line("BreakPoint at " + source + ":" + itos(line)); } } else if (line.begins_with("delete")) { - if (line.get_slice_count(" ")<=1) { + if (line.get_slice_count(" ") <= 1) { clear_breakpoints(); } else { - String bppos=line.get_slicec(' ',1); - String source=bppos.get_slicec(':',0).strip_edges(); - int line=bppos.get_slicec(':',1).strip_edges().to_int(); + String bppos = line.get_slicec(' ', 1); + String source = bppos.get_slicec(':', 0).strip_edges(); + int line = bppos.get_slicec(':', 1).strip_edges().to_int(); source = breakpoint_find_source(source); - remove_breakpoint(line,source); - - print_line("Removed BreakPoint at "+source+":"+itos(line)); + remove_breakpoint(line, source); + print_line("Removed BreakPoint at " + source + ":" + itos(line)); } - } else if (line=="h" || line=="help") { + } else if (line == "h" || line == "help") { print_line("Built-In Debugger command list:\n"); print_line("\tc,continue :\t\t Continue execution."); @@ -182,20 +180,17 @@ void ScriptDebuggerLocal::debug(ScriptLanguage *p_script,bool p_can_continue) { struct _ScriptDebuggerLocalProfileInfoSort { - bool operator()(const ScriptLanguage::ProfilingInfo &A,const ScriptLanguage::ProfilingInfo &B) const { + bool operator()(const ScriptLanguage::ProfilingInfo &A, const ScriptLanguage::ProfilingInfo &B) const { return A.total_time > B.total_time; } }; -void ScriptDebuggerLocal::profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time) { - - - frame_time=p_frame_time; - idle_time=p_idle_time; - fixed_time=p_fixed_time; - fixed_frame_time=p_fixed_frame_time; - +void ScriptDebuggerLocal::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time) { + frame_time = p_frame_time; + idle_time = p_idle_time; + fixed_time = p_fixed_time; + fixed_frame_time = p_fixed_frame_time; } void ScriptDebuggerLocal::idle_poll() { @@ -205,107 +200,100 @@ void ScriptDebuggerLocal::idle_poll() { uint64_t diff = OS::get_singleton()->get_ticks_usec() - idle_accum; - if (diff<1000000) //show every one second + if (diff < 1000000) //show every one second return; idle_accum = OS::get_singleton()->get_ticks_usec(); - int ofs=0; - for(int i=0;i<ScriptServer::get_language_count();i++) { - ofs+=ScriptServer::get_language(i)->profiling_get_frame_data(&pinfo[ofs],pinfo.size()-ofs); + int ofs = 0; + for (int i = 0; i < ScriptServer::get_language_count(); i++) { + ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&pinfo[ofs], pinfo.size() - ofs); } - SortArray<ScriptLanguage::ProfilingInfo,_ScriptDebuggerLocalProfileInfoSort> sort; - sort.sort(pinfo.ptr(),ofs); + SortArray<ScriptLanguage::ProfilingInfo, _ScriptDebuggerLocalProfileInfoSort> sort; + sort.sort(pinfo.ptr(), ofs); //falta el frame time - uint64_t script_time_us=0; + uint64_t script_time_us = 0; - for(int i=0;i<ofs;i++) { + for (int i = 0; i < ofs; i++) { - script_time_us+=pinfo[i].self_time; + script_time_us += pinfo[i].self_time; } + float script_time = USEC_TO_SEC(script_time_us); - float script_time=USEC_TO_SEC(script_time_us); - - float total_time=frame_time; + float total_time = frame_time; //print script total - print_line("FRAME: total: "+rtos(frame_time)+" script: "+rtos(script_time)+"/"+itos(script_time*100/total_time)+" %"); + print_line("FRAME: total: " + rtos(frame_time) + " script: " + rtos(script_time) + "/" + itos(script_time * 100 / total_time) + " %"); - for(int i=0;i<ofs;i++) { + for (int i = 0; i < ofs; i++) { - print_line(itos(i)+":"+pinfo[i].signature); - float tt=USEC_TO_SEC(pinfo[i].total_time); - float st=USEC_TO_SEC(pinfo[i].self_time); - print_line("\ttotal: "+rtos(tt)+"/"+itos(tt*100/total_time)+" % \tself: "+rtos(st)+"/"+itos(st*100/total_time)+" % tcalls: "+itos(pinfo[i].call_count)); + print_line(itos(i) + ":" + pinfo[i].signature); + float tt = USEC_TO_SEC(pinfo[i].total_time); + float st = USEC_TO_SEC(pinfo[i].self_time); + print_line("\ttotal: " + rtos(tt) + "/" + itos(tt * 100 / total_time) + " % \tself: " + rtos(st) + "/" + itos(st * 100 / total_time) + " % tcalls: " + itos(pinfo[i].call_count)); } - - - } void ScriptDebuggerLocal::profiling_start() { - for(int i=0;i<ScriptServer::get_language_count();i++) { + for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->profiling_start(); } - print_line("BEGIN PROFILING"); - profiling=true; + profiling = true; pinfo.resize(32768); - frame_time=0; - fixed_time=0; - idle_time=0; - fixed_frame_time=0; - + frame_time = 0; + fixed_time = 0; + idle_time = 0; + fixed_frame_time = 0; } - void ScriptDebuggerLocal::profiling_end() { - int ofs=0; + int ofs = 0; - for(int i=0;i<ScriptServer::get_language_count();i++) { - ofs+=ScriptServer::get_language(i)->profiling_get_accumulated_data(&pinfo[ofs],pinfo.size()-ofs); + for (int i = 0; i < ScriptServer::get_language_count(); i++) { + ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&pinfo[ofs], pinfo.size() - ofs); } - SortArray<ScriptLanguage::ProfilingInfo,_ScriptDebuggerLocalProfileInfoSort> sort; - sort.sort(pinfo.ptr(),ofs); + SortArray<ScriptLanguage::ProfilingInfo, _ScriptDebuggerLocalProfileInfoSort> sort; + sort.sort(pinfo.ptr(), ofs); - uint64_t total_us=0; - for(int i=0;i<ofs;i++) { - total_us+=pinfo[i].self_time; + uint64_t total_us = 0; + for (int i = 0; i < ofs; i++) { + total_us += pinfo[i].self_time; } - float total_time=total_us/1000000.0; + float total_time = total_us / 1000000.0; - for(int i=0;i<ofs;i++) { + for (int i = 0; i < ofs; i++) { - print_line(itos(i)+":"+pinfo[i].signature); - float tt=USEC_TO_SEC(pinfo[i].total_time); - float st=USEC_TO_SEC(pinfo[i].self_time); - print_line("\ttotal_ms: "+rtos(tt)+"\tself_ms: "+rtos(st)+"total%: "+itos(tt*100/total_time)+"\tself%: "+itos(st*100/total_time)+"\tcalls: "+itos(pinfo[i].call_count)); + print_line(itos(i) + ":" + pinfo[i].signature); + float tt = USEC_TO_SEC(pinfo[i].total_time); + float st = USEC_TO_SEC(pinfo[i].self_time); + print_line("\ttotal_ms: " + rtos(tt) + "\tself_ms: " + rtos(st) + "total%: " + itos(tt * 100 / total_time) + "\tself%: " + itos(st * 100 / total_time) + "\tcalls: " + itos(pinfo[i].call_count)); } - for(int i=0;i<ScriptServer::get_language_count();i++) { + for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->profiling_stop(); } - profiling=false; + profiling = false; } -void ScriptDebuggerLocal::send_message(const String& p_message, const Array &p_args) { +void ScriptDebuggerLocal::send_message(const String &p_message, const Array &p_args) { - print_line("MESSAGE: '"+p_message+"' - "+String(Variant(p_args))); + print_line("MESSAGE: '" + p_message + "' - " + String(Variant(p_args))); } ScriptDebuggerLocal::ScriptDebuggerLocal() { - profiling=false; - idle_accum=OS::get_singleton()->get_ticks_usec(); + profiling = false; + idle_accum = OS::get_singleton()->get_ticks_usec(); } diff --git a/core/script_debugger_local.h b/core/script_debugger_local.h index 6e2057ef45..b3b323c7a6 100644 --- a/core/script_debugger_local.h +++ b/core/script_debugger_local.h @@ -34,26 +34,23 @@ class ScriptDebuggerLocal : public ScriptDebugger { bool profiling; - float frame_time,idle_time,fixed_time,fixed_frame_time; + float frame_time, idle_time, fixed_time, fixed_frame_time; uint64_t idle_accum; Vector<ScriptLanguage::ProfilingInfo> pinfo; - public: - - void debug(ScriptLanguage *p_script,bool p_can_continue); - virtual void send_message(const String& p_message, const Array& p_args); + void debug(ScriptLanguage *p_script, bool p_can_continue); + virtual void send_message(const String &p_message, const Array &p_args); virtual bool is_profiling() const { return profiling; } - virtual void add_profiling_frame_data(const StringName& p_name,const Array& p_data) {} + virtual void add_profiling_frame_data(const StringName &p_name, const Array &p_data) {} virtual void idle_poll(); virtual void profiling_start(); virtual void profiling_end(); - virtual void profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time); - + virtual void profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time); ScriptDebuggerLocal(); }; diff --git a/core/script_debugger_remote.cpp b/core/script_debugger_remote.cpp index b14eb51b6c..bb7ed22c28 100644 --- a/core/script_debugger_remote.cpp +++ b/core/script_debugger_remote.cpp @@ -28,10 +28,10 @@ /*************************************************************************/ #include "script_debugger_remote.h" -#include "os/os.h" -#include "io/ip.h" #include "global_config.h" +#include "io/ip.h" #include "os/input.h" +#include "os/os.h" void ScriptDebuggerRemote::_send_video_memory() { @@ -42,70 +42,66 @@ void ScriptDebuggerRemote::_send_video_memory() { usage.sort(); packet_peer_stream->put_var("message:video_mem"); - packet_peer_stream->put_var(usage.size()*4); - + packet_peer_stream->put_var(usage.size() * 4); - for(List<ResourceUsage>::Element *E=usage.front();E;E=E->next()) { + for (List<ResourceUsage>::Element *E = usage.front(); E; E = E->next()) { packet_peer_stream->put_var(E->get().path); packet_peer_stream->put_var(E->get().type); packet_peer_stream->put_var(E->get().format); packet_peer_stream->put_var(E->get().vram); } - } -Error ScriptDebuggerRemote::connect_to_host(const String& p_host,uint16_t p_port) { - - - IP_Address ip; - if (p_host.is_valid_ip_address()) - ip=p_host; - else - ip = IP::get_singleton()->resolve_hostname(p_host); +Error ScriptDebuggerRemote::connect_to_host(const String &p_host, uint16_t p_port) { + IP_Address ip; + if (p_host.is_valid_ip_address()) + ip = p_host; + else + ip = IP::get_singleton()->resolve_hostname(p_host); - int port = p_port; + int port = p_port; - int tries = 3; - tcp_client->connect_to_host(ip, port); + int tries = 3; + tcp_client->connect_to_host(ip, port); - while (tries--) { + while (tries--) { - if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) { - break; - } else { + if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) { + break; + } else { - OS::get_singleton()->delay_usec(1000000); - print_line("Remote Debugger: Connection failed with status: " + String::num(tcp_client->get_status())+"'', retrying in 1 sec."); - }; - }; + OS::get_singleton()->delay_usec(1000000); + print_line("Remote Debugger: Connection failed with status: " + String::num(tcp_client->get_status()) + "'', retrying in 1 sec."); + }; + }; - if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) { + if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) { - print_line("Remote Debugger: Unable to connect"); - return FAILED; - }; + print_line("Remote Debugger: Unable to connect"); + return FAILED; + }; -// print_line("Remote Debugger: Connection OK!"); - packet_peer_stream->set_stream_peer(tcp_client); + // print_line("Remote Debugger: Connection OK!"); + packet_peer_stream->set_stream_peer(tcp_client); - return OK; + return OK; } -static int _ScriptDebuggerRemote_found_id=0; -static Object* _ScriptDebuggerRemote_find=NULL; +static int _ScriptDebuggerRemote_found_id = 0; +static Object *_ScriptDebuggerRemote_find = NULL; static void _ScriptDebuggerRemote_debug_func(Object *p_obj) { - if (_ScriptDebuggerRemote_find==p_obj) { - _ScriptDebuggerRemote_found_id=p_obj->get_instance_ID(); + if (_ScriptDebuggerRemote_find == p_obj) { + _ScriptDebuggerRemote_found_id = p_obj->get_instance_ID(); } } -static ObjectID safe_get_instance_id(const Variant& p_v) { +static ObjectID safe_get_instance_id(const Variant &p_v) { Object *o = p_v; - if (o==NULL) + if (o == NULL) return 0; else { @@ -115,22 +111,19 @@ static ObjectID safe_get_instance_id(const Variant& p_v) { return r->get_instance_ID(); } else { - - _ScriptDebuggerRemote_found_id=0; - _ScriptDebuggerRemote_find=NULL; + _ScriptDebuggerRemote_found_id = 0; + _ScriptDebuggerRemote_find = NULL; ObjectDB::debug_objects(_ScriptDebuggerRemote_debug_func); return _ScriptDebuggerRemote_found_id; - } } } -void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) { +void ScriptDebuggerRemote::debug(ScriptLanguage *p_script, bool p_can_continue) { //this function is called when there is a debugger break (bug on script) //or when execution is paused from editor - if (!tcp_client->is_connected_to_host()) { ERR_EXPLAIN("Script Debugger failed to connect, but being used anyway."); ERR_FAIL(); @@ -143,86 +136,81 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) { packet_peer_stream->put_var(p_can_continue); packet_peer_stream->put_var(p_script->debug_get_error()); - skip_profile_frame=true; // to avoid super long frame time for the frame + skip_profile_frame = true; // to avoid super long frame time for the frame - Input::MouseMode mouse_mode=Input::get_singleton()->get_mouse_mode(); - if (mouse_mode!=Input::MOUSE_MODE_VISIBLE) + Input::MouseMode mouse_mode = Input::get_singleton()->get_mouse_mode(); + if (mouse_mode != Input::MOUSE_MODE_VISIBLE) Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); - - while(true) { + while (true) { _get_output(); - if (packet_peer_stream->get_available_packet_count()>0) { + if (packet_peer_stream->get_available_packet_count() > 0) { Variant var; Error err = packet_peer_stream->get_var(var); - ERR_CONTINUE( err != OK); - ERR_CONTINUE( var.get_type()!=Variant::ARRAY ); + ERR_CONTINUE(err != OK); + ERR_CONTINUE(var.get_type() != Variant::ARRAY); Array cmd = var; - ERR_CONTINUE( cmd.size()==0); - ERR_CONTINUE( cmd[0].get_type()!=Variant::STRING ); + ERR_CONTINUE(cmd.size() == 0); + ERR_CONTINUE(cmd[0].get_type() != Variant::STRING); String command = cmd[0]; - - - if (command=="get_stack_dump") { + if (command == "get_stack_dump") { packet_peer_stream->put_var("stack_dump"); int slc = p_script->debug_get_stack_level_count(); - packet_peer_stream->put_var( slc ); + packet_peer_stream->put_var(slc); - for(int i=0;i<slc;i++) { + for (int i = 0; i < slc; i++) { Dictionary d; - d["file"]=p_script->debug_get_stack_level_source(i); - d["line"]=p_script->debug_get_stack_level_line(i); - d["function"]=p_script->debug_get_stack_level_function(i); + d["file"] = p_script->debug_get_stack_level_source(i); + d["line"] = p_script->debug_get_stack_level_line(i); + d["function"] = p_script->debug_get_stack_level_function(i); //d["id"]=p_script->debug_get_stack_level_ - d["id"]=0; + d["id"] = 0; - packet_peer_stream->put_var( d ); + packet_peer_stream->put_var(d); } - } else if (command=="get_stack_frame_vars") { + } else if (command == "get_stack_frame_vars") { cmd.remove(0); - ERR_CONTINUE( cmd.size()!=1 ); + ERR_CONTINUE(cmd.size() != 1); int lv = cmd[0]; List<String> members; List<Variant> member_vals; - p_script->debug_get_stack_level_members(lv,&members,&member_vals); - + p_script->debug_get_stack_level_members(lv, &members, &member_vals); - - ERR_CONTINUE( members.size() !=member_vals.size() ); + ERR_CONTINUE(members.size() != member_vals.size()); List<String> locals; List<Variant> local_vals; - p_script->debug_get_stack_level_locals(lv,&locals,&local_vals); + p_script->debug_get_stack_level_locals(lv, &locals, &local_vals); - ERR_CONTINUE( locals.size() !=local_vals.size() ); + ERR_CONTINUE(locals.size() != local_vals.size()); packet_peer_stream->put_var("stack_frame_vars"); - packet_peer_stream->put_var(2+locals.size()*2+members.size()*2); + packet_peer_stream->put_var(2 + locals.size() * 2 + members.size() * 2); { //members packet_peer_stream->put_var(members.size()); - List<String>::Element *E=members.front(); - List<Variant>::Element *F=member_vals.front(); + List<String>::Element *E = members.front(); + List<Variant>::Element *F = member_vals.front(); - while(E) { + while (E) { - if (F->get().get_type()==Variant::OBJECT) { - packet_peer_stream->put_var("*"+E->get()); + if (F->get().get_type() == Variant::OBJECT) { + packet_peer_stream->put_var("*" + E->get()); String pretty_print = F->get().operator String(); packet_peer_stream->put_var(pretty_print.ascii().get_data()); } else { @@ -230,23 +218,21 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) { packet_peer_stream->put_var(F->get()); } - E=E->next(); - F=F->next(); + E = E->next(); + F = F->next(); } - } - { //locals packet_peer_stream->put_var(locals.size()); - List<String>::Element *E=locals.front(); - List<Variant>::Element *F=local_vals.front(); + List<String>::Element *E = locals.front(); + List<Variant>::Element *F = local_vals.front(); - while(E) { + while (E) { - if (F->get().get_type()==Variant::OBJECT) { - packet_peer_stream->put_var("*"+E->get()); + if (F->get().get_type() == Variant::OBJECT) { + packet_peer_stream->put_var("*" + E->get()); String pretty_print = F->get().operator String(); packet_peer_stream->put_var(pretty_print.ascii().get_data()); } else { @@ -254,116 +240,107 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) { packet_peer_stream->put_var(F->get()); } - E=E->next(); - F=F->next(); + E = E->next(); + F = F->next(); } - } - - - } else if (command=="step") { + } else if (command == "step") { set_depth(-1); set_lines_left(1); break; - } else if (command=="next") { + } else if (command == "next") { set_depth(0); set_lines_left(1); break; - } else if (command=="continue") { + } else if (command == "continue") { set_depth(-1); set_lines_left(-1); OS::get_singleton()->move_window_to_foreground(); break; - } else if (command=="break") { + } else if (command == "break") { ERR_PRINT("Got break when already broke!"); break; - } else if (command=="request_scene_tree") { + } else if (command == "request_scene_tree") { if (request_scene_tree) request_scene_tree(request_scene_tree_ud); - } else if (command=="request_video_mem") { + } else if (command == "request_video_mem") { _send_video_memory(); - } else if (command=="inspect_object") { + } else if (command == "inspect_object") { ObjectID id = cmd[1]; _send_object_id(id); - } else if (command=="set_object_property") { + } else if (command == "set_object_property") { - _set_object_property(cmd[1],cmd[2],cmd[3]); + _set_object_property(cmd[1], cmd[2], cmd[3]); - } else if (command=="reload_scripts") { - reload_all_scripts=true; - } else if (command=="breakpoint") { + } else if (command == "reload_scripts") { + reload_all_scripts = true; + } else if (command == "breakpoint") { bool set = cmd[3]; if (set) - insert_breakpoint(cmd[2],cmd[1]); + insert_breakpoint(cmd[2], cmd[1]); else - remove_breakpoint(cmd[2],cmd[1]); + remove_breakpoint(cmd[2], cmd[1]); } else { _parse_live_edit(cmd); } - - } else { OS::get_singleton()->delay_usec(10000); } - } packet_peer_stream->put_var("debug_exit"); packet_peer_stream->put_var(0); - if (mouse_mode!=Input::MOUSE_MODE_VISIBLE) + if (mouse_mode != Input::MOUSE_MODE_VISIBLE) Input::get_singleton()->set_mouse_mode(mouse_mode); - } - void ScriptDebuggerRemote::_get_output() { mutex->lock(); if (output_strings.size()) { - locking=true; + locking = true; packet_peer_stream->put_var("output"); - packet_peer_stream->put_var(output_strings .size()); + packet_peer_stream->put_var(output_strings.size()); - while(output_strings.size()) { + while (output_strings.size()) { packet_peer_stream->put_var(output_strings.front()->get()); output_strings.pop_front(); } - locking=false; - + locking = false; } while (messages.size()) { - locking=true; - packet_peer_stream->put_var("message:"+messages.front()->get().message); + locking = true; + packet_peer_stream->put_var("message:" + messages.front()->get().message); packet_peer_stream->put_var(messages.front()->get().data.size()); - for(int i=0;i<messages.front()->get().data.size();i++) { + for (int i = 0; i < messages.front()->get().data.size(); i++) { packet_peer_stream->put_var(messages.front()->get().data[i]); } messages.pop_front(); - locking=false; + locking = false; } while (errors.size()) { - locking=true; + locking = true; packet_peer_stream->put_var("error"); OutputError oe = errors.front()->get(); - packet_peer_stream->put_var(oe.callstack.size()+2); + packet_peer_stream->put_var(oe.callstack.size() + 2); Array error_data; @@ -379,14 +356,12 @@ void ScriptDebuggerRemote::_get_output() { error_data.push_back(oe.warning); packet_peer_stream->put_var(error_data); packet_peer_stream->put_var(oe.callstack.size()); - for(int i=0;i<oe.callstack.size();i++) { + for (int i = 0; i < oe.callstack.size(); i++) { packet_peer_stream->put_var(oe.callstack[i]); - } errors.pop_front(); - locking=false; - + locking = false; } mutex->unlock(); } @@ -395,56 +370,53 @@ void ScriptDebuggerRemote::line_poll() { //the purpose of this is just processing events every now and then when the script might get too busy //otherwise bugs like infinite loops cant be catched - if (poll_every%2048==0) + if (poll_every % 2048 == 0) _poll_events(); poll_every++; - } +void ScriptDebuggerRemote::_err_handler(void *ud, const char *p_func, const char *p_file, int p_line, const char *p_err, const char *p_descr, ErrorHandlerType p_type) { -void ScriptDebuggerRemote::_err_handler(void* ud,const char* p_func,const char*p_file,int p_line,const char *p_err, const char * p_descr,ErrorHandlerType p_type) { - - if (p_type==ERR_HANDLER_SCRIPT) + if (p_type == ERR_HANDLER_SCRIPT) return; //ignore script errors, those go through debugger - ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote*)ud; + ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)ud; OutputError oe; - oe.error=p_err; - oe.error_descr=p_descr; - oe.source_file=p_file; - oe.source_line=p_line; - oe.source_func=p_func; - oe.warning=p_type==ERR_HANDLER_WARNING; + oe.error = p_err; + oe.error_descr = p_descr; + oe.source_file = p_file; + oe.source_line = p_line; + oe.source_func = p_func; + oe.warning = p_type == ERR_HANDLER_WARNING; uint64_t time = OS::get_singleton()->get_ticks_msec(); - oe.hr=time/3600000; - oe.min=(time/60000)%60; - oe.sec=(time/1000)%60; - oe.msec=time%1000; + oe.hr = time / 3600000; + oe.min = (time / 60000) % 60; + oe.sec = (time / 1000) % 60; + oe.msec = time % 1000; Array cstack; Vector<ScriptLanguage::StackInfo> si; - for(int i=0;i<ScriptServer::get_language_count();i++) { - si=ScriptServer::get_language(i)->debug_get_current_stack_info(); + for (int i = 0; i < ScriptServer::get_language_count(); i++) { + si = ScriptServer::get_language(i)->debug_get_current_stack_info(); if (si.size()) break; } - cstack.resize(si.size()*2); - for(int i=0;i<si.size();i++) { + cstack.resize(si.size() * 2); + for (int i = 0; i < si.size(); i++) { String path; - int line=0; + int line = 0; if (si[i].script.is_valid()) { - path=si[i].script->get_path(); - line=si[i].line; + path = si[i].script->get_path(); + line = si[i].line; } - cstack[i*2+0]=path; - cstack[i*2+1]=line; + cstack[i * 2 + 0] = path; + cstack[i * 2 + 1] = line; } - oe.callstack=cstack; - + oe.callstack = cstack; sdr->mutex->lock(); @@ -456,97 +428,95 @@ void ScriptDebuggerRemote::_err_handler(void* ud,const char* p_func,const char*p sdr->mutex->unlock(); } - -bool ScriptDebuggerRemote::_parse_live_edit(const Array& cmd) { +bool ScriptDebuggerRemote::_parse_live_edit(const Array &cmd) { String cmdstr = cmd[0]; if (!live_edit_funcs || !cmdstr.begins_with("live_")) return false; - //print_line(Variant(cmd).get_construct_string()); - if (cmdstr=="live_set_root") { + if (cmdstr == "live_set_root") { if (!live_edit_funcs->root_func) return true; //print_line("root: "+Variant(cmd).get_construct_string()); - live_edit_funcs->root_func(live_edit_funcs->udata,cmd[1],cmd[2]); + live_edit_funcs->root_func(live_edit_funcs->udata, cmd[1], cmd[2]); - } else if (cmdstr=="live_node_path") { + } else if (cmdstr == "live_node_path") { if (!live_edit_funcs->node_path_func) return true; //print_line("path: "+Variant(cmd).get_construct_string()); - live_edit_funcs->node_path_func(live_edit_funcs->udata,cmd[1],cmd[2]); + live_edit_funcs->node_path_func(live_edit_funcs->udata, cmd[1], cmd[2]); - } else if (cmdstr=="live_res_path") { + } else if (cmdstr == "live_res_path") { if (!live_edit_funcs->res_path_func) return true; - live_edit_funcs->res_path_func(live_edit_funcs->udata,cmd[1],cmd[2]); + live_edit_funcs->res_path_func(live_edit_funcs->udata, cmd[1], cmd[2]); - } else if (cmdstr=="live_node_prop_res") { + } else if (cmdstr == "live_node_prop_res") { if (!live_edit_funcs->node_set_res_func) return true; - live_edit_funcs->node_set_res_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->node_set_res_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_node_prop") { + } else if (cmdstr == "live_node_prop") { if (!live_edit_funcs->node_set_func) return true; - live_edit_funcs->node_set_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->node_set_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_res_prop_res") { + } else if (cmdstr == "live_res_prop_res") { if (!live_edit_funcs->res_set_res_func) return true; - live_edit_funcs->res_set_res_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->res_set_res_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_res_prop") { + } else if (cmdstr == "live_res_prop") { if (!live_edit_funcs->res_set_func) return true; - live_edit_funcs->res_set_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->res_set_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_node_call") { + } else if (cmdstr == "live_node_call") { if (!live_edit_funcs->node_call_func) return true; - live_edit_funcs->node_call_func(live_edit_funcs->udata,cmd[1],cmd[2], cmd[3],cmd[4],cmd[5],cmd[6],cmd[7]); + live_edit_funcs->node_call_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6], cmd[7]); - } else if (cmdstr=="live_res_call") { + } else if (cmdstr == "live_res_call") { if (!live_edit_funcs->res_call_func) return true; - live_edit_funcs->res_call_func(live_edit_funcs->udata,cmd[1],cmd[2], cmd[3],cmd[4],cmd[5],cmd[6],cmd[7]); + live_edit_funcs->res_call_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6], cmd[7]); - } else if (cmdstr=="live_create_node") { + } else if (cmdstr == "live_create_node") { - live_edit_funcs->tree_create_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->tree_create_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_instance_node") { + } else if (cmdstr == "live_instance_node") { - live_edit_funcs->tree_instance_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->tree_instance_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_remove_node") { + } else if (cmdstr == "live_remove_node") { - live_edit_funcs->tree_remove_node_func(live_edit_funcs->udata,cmd[1]); + live_edit_funcs->tree_remove_node_func(live_edit_funcs->udata, cmd[1]); - } else if (cmdstr=="live_remove_and_keep_node") { + } else if (cmdstr == "live_remove_and_keep_node") { - live_edit_funcs->tree_remove_and_keep_node_func(live_edit_funcs->udata,cmd[1],cmd[2]); - } else if (cmdstr=="live_restore_node") { + live_edit_funcs->tree_remove_and_keep_node_func(live_edit_funcs->udata, cmd[1], cmd[2]); + } else if (cmdstr == "live_restore_node") { - live_edit_funcs->tree_restore_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]); + live_edit_funcs->tree_restore_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]); - } else if (cmdstr=="live_duplicate_node") { + } else if (cmdstr == "live_duplicate_node") { - live_edit_funcs->tree_duplicate_node_func(live_edit_funcs->udata,cmd[1],cmd[2]); - } else if (cmdstr=="live_reparent_node") { + live_edit_funcs->tree_duplicate_node_func(live_edit_funcs->udata, cmd[1], cmd[2]); + } else if (cmdstr == "live_reparent_node") { - live_edit_funcs->tree_reparent_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3],cmd[4]); + live_edit_funcs->tree_reparent_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3], cmd[4]); } else { @@ -556,26 +526,25 @@ bool ScriptDebuggerRemote::_parse_live_edit(const Array& cmd) { return true; } - void ScriptDebuggerRemote::_send_object_id(ObjectID p_id) { - Object* obj = ObjectDB::get_instance(p_id); + Object *obj = ObjectDB::get_instance(p_id); if (!obj) return; List<PropertyInfo> pinfo; - obj->get_property_list(&pinfo,true); + obj->get_property_list(&pinfo, true); - int props_to_send=0; - for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { + int props_to_send = 0; + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage&(PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CATEGORY)) { + if (E->get().usage & (PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CATEGORY)) { props_to_send++; } } packet_peer_stream->put_var("message:inspect_object"); - packet_peer_stream->put_var(props_to_send*5+4); + packet_peer_stream->put_var(props_to_send * 5 + 4); packet_peer_stream->put_var(p_id); packet_peer_stream->put_var(obj->get_class()); if (obj->is_class("Resource") || obj->is_class("Node")) @@ -585,58 +554,56 @@ void ScriptDebuggerRemote::_send_object_id(ObjectID p_id) { packet_peer_stream->put_var(props_to_send); - for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage&(PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CATEGORY)) { + if (E->get().usage & (PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CATEGORY)) { - if (E->get().usage&PROPERTY_USAGE_CATEGORY) { - packet_peer_stream->put_var("*"+E->get().name); + if (E->get().usage & PROPERTY_USAGE_CATEGORY) { + packet_peer_stream->put_var("*" + E->get().name); } else { packet_peer_stream->put_var(E->get().name); } Variant var = obj->get(E->get().name); - if (E->get().type==Variant::OBJECT || var.get_type()==Variant::OBJECT) { + if (E->get().type == Variant::OBJECT || var.get_type() == Variant::OBJECT) { ObjectID id2; - Object *obj=var; + Object *obj = var; if (obj) { - id2=obj->get_instance_ID(); + id2 = obj->get_instance_ID(); } else { - id2=0; + id2 = 0; } packet_peer_stream->put_var(Variant::INT); //hint string packet_peer_stream->put_var(PROPERTY_HINT_OBJECT_ID); //hint packet_peer_stream->put_var(E->get().hint_string); //hint string - packet_peer_stream->put_var(id2); //value + packet_peer_stream->put_var(id2); //value } else { packet_peer_stream->put_var(E->get().type); packet_peer_stream->put_var(E->get().hint); packet_peer_stream->put_var(E->get().hint_string); //only send information that can be sent.. - if (var.get_type()==Variant::IMAGE) { - var=Image(); + if (var.get_type() == Variant::IMAGE) { + var = Image(); } - if (var.get_type()>=Variant::DICTIONARY) { - var=Array(); //send none for now, may be to big + if (var.get_type() >= Variant::DICTIONARY) { + var = Array(); //send none for now, may be to big } packet_peer_stream->put_var(var); } - } } - } -void ScriptDebuggerRemote::_set_object_property(ObjectID p_id, const String& p_property, const Variant& p_value) { +void ScriptDebuggerRemote::_set_object_property(ObjectID p_id, const String &p_property, const Variant &p_value) { - Object* obj = ObjectDB::get_instance(p_id); + Object *obj = ObjectDB::get_instance(p_id); if (!obj) return; - obj->set(p_property,p_value); + obj->set(p_property, p_value); } void ScriptDebuggerRemote::_poll_events() { @@ -644,7 +611,7 @@ void ScriptDebuggerRemote::_poll_events() { //this si called from ::idle_poll, happens only when running the game, //does not get called while on debug break - while(packet_peer_stream->get_available_packet_count()>0) { + while (packet_peer_stream->get_available_packet_count() > 0) { _get_output(); @@ -653,105 +620,99 @@ void ScriptDebuggerRemote::_poll_events() { Variant var; Error err = packet_peer_stream->get_var(var); - ERR_CONTINUE( err != OK); - ERR_CONTINUE( var.get_type()!=Variant::ARRAY ); + ERR_CONTINUE(err != OK); + ERR_CONTINUE(var.get_type() != Variant::ARRAY); Array cmd = var; - ERR_CONTINUE( cmd.size()==0); - ERR_CONTINUE( cmd[0].get_type()!=Variant::STRING ); + ERR_CONTINUE(cmd.size() == 0); + ERR_CONTINUE(cmd[0].get_type() != Variant::STRING); String command = cmd[0]; //cmd.remove(0); - if (command=="break") { + if (command == "break") { if (get_break_language()) debug(get_break_language()); - } else if (command=="request_scene_tree") { + } else if (command == "request_scene_tree") { if (request_scene_tree) request_scene_tree(request_scene_tree_ud); - } else if (command=="request_video_mem") { + } else if (command == "request_video_mem") { _send_video_memory(); - } else if (command=="inspect_object") { + } else if (command == "inspect_object") { ObjectID id = cmd[1]; _send_object_id(id); - } else if (command=="set_object_property") { + } else if (command == "set_object_property") { - _set_object_property(cmd[1],cmd[2],cmd[3]); + _set_object_property(cmd[1], cmd[2], cmd[3]); - } else if (command=="start_profiling") { + } else if (command == "start_profiling") { - for(int i=0;i<ScriptServer::get_language_count();i++) { + for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->profiling_start(); } - max_frame_functions=cmd[1]; + max_frame_functions = cmd[1]; profiler_function_signature_map.clear(); - profiling=true; - frame_time=0; - idle_time=0; - fixed_time=0; - fixed_frame_time=0; + profiling = true; + frame_time = 0; + idle_time = 0; + fixed_time = 0; + fixed_frame_time = 0; print_line("PROFILING ALRIGHT!"); - } else if (command=="stop_profiling") { + } else if (command == "stop_profiling") { - for(int i=0;i<ScriptServer::get_language_count();i++) { + for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->profiling_stop(); } - profiling=false; + profiling = false; _send_profiling_data(false); print_line("PROFILING END!"); - } else if (command=="reload_scripts") { - reload_all_scripts=true; - } else if (command=="breakpoint") { + } else if (command == "reload_scripts") { + reload_all_scripts = true; + } else if (command == "breakpoint") { bool set = cmd[3]; if (set) - insert_breakpoint(cmd[2],cmd[1]); + insert_breakpoint(cmd[2], cmd[1]); else - remove_breakpoint(cmd[2],cmd[1]); + remove_breakpoint(cmd[2], cmd[1]); } else { _parse_live_edit(cmd); } - } - } - void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) { + int ofs = 0; - - - int ofs=0; - - for(int i=0;i<ScriptServer::get_language_count();i++) { + for (int i = 0; i < ScriptServer::get_language_count(); i++) { if (p_for_frame) - ofs+=ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info[ofs],profile_info.size()-ofs); + ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info[ofs], profile_info.size() - ofs); else - ofs+=ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info[ofs],profile_info.size()-ofs); + ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info[ofs], profile_info.size() - ofs); } - for(int i=0;i<ofs;i++) { - profile_info_ptrs[i]=&profile_info[i]; + for (int i = 0; i < ofs; i++) { + profile_info_ptrs[i] = &profile_info[i]; } - SortArray<ScriptLanguage::ProfilingInfo*,ProfileInfoSort> sa; - sa.sort(profile_info_ptrs.ptr(),ofs); + SortArray<ScriptLanguage::ProfilingInfo *, ProfileInfoSort> sa; + sa.sort(profile_info_ptrs.ptr(), ofs); - int to_send=MIN(ofs,max_frame_functions); + int to_send = MIN(ofs, max_frame_functions); //check signatures first - uint64_t total_script_time=0; + uint64_t total_script_time = 0; - for(int i=0;i<to_send;i++) { + for (int i = 0; i < to_send; i++) { if (!profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) { @@ -761,25 +722,22 @@ void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) { packet_peer_stream->put_var(profile_info_ptrs[i]->signature); packet_peer_stream->put_var(idx); - profiler_function_signature_map[profile_info_ptrs[i]->signature]=idx; - - + profiler_function_signature_map[profile_info_ptrs[i]->signature] = idx; } - total_script_time+=profile_info_ptrs[i]->self_time; + total_script_time += profile_info_ptrs[i]->self_time; } //send frames then if (p_for_frame) { packet_peer_stream->put_var("profile_frame"); - packet_peer_stream->put_var(8+profile_frame_data.size()*2+to_send*4); + packet_peer_stream->put_var(8 + profile_frame_data.size() * 2 + to_send * 4); } else { packet_peer_stream->put_var("profile_total"); - packet_peer_stream->put_var(8+to_send*4); + packet_peer_stream->put_var(8 + to_send * 4); } - packet_peer_stream->put_var(Engine::get_singleton()->get_frames_drawn()); //total frame time packet_peer_stream->put_var(frame_time); //total frame time packet_peer_stream->put_var(idle_time); //idle frame time @@ -790,10 +748,9 @@ void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) { if (p_for_frame) { - packet_peer_stream->put_var(profile_frame_data.size()); //how many profile framedatas to send + packet_peer_stream->put_var(profile_frame_data.size()); //how many profile framedatas to send packet_peer_stream->put_var(to_send); //how many script functions to send - for (int i=0;i<profile_frame_data.size();i++) { - + for (int i = 0; i < profile_frame_data.size(); i++) { packet_peer_stream->put_var(profile_frame_data[i].name); packet_peer_stream->put_var(profile_frame_data[i].data); @@ -803,28 +760,23 @@ void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) { packet_peer_stream->put_var(to_send); //how many script functions to send } + for (int i = 0; i < to_send; i++) { - - for(int i=0;i<to_send;i++) { - - int sig_id=-1; + int sig_id = -1; if (profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) { - sig_id=profiler_function_signature_map[profile_info_ptrs[i]->signature]; + sig_id = profiler_function_signature_map[profile_info_ptrs[i]->signature]; } - - packet_peer_stream->put_var(sig_id); packet_peer_stream->put_var(profile_info_ptrs[i]->call_count); - packet_peer_stream->put_var(profile_info_ptrs[i]->total_time/1000000.0); - packet_peer_stream->put_var(profile_info_ptrs[i]->self_time/1000000.0); + packet_peer_stream->put_var(profile_info_ptrs[i]->total_time / 1000000.0); + packet_peer_stream->put_var(profile_info_ptrs[i]->self_time / 1000000.0); } if (p_for_frame) { profile_frame_data.clear(); } - } void ScriptDebuggerRemote::idle_poll() { @@ -832,101 +784,94 @@ void ScriptDebuggerRemote::idle_poll() { // this function is called every frame, except when there is a debugger break (::debug() in this class) // execution stops and remains in the ::debug function - _get_output(); - + _get_output(); - if (requested_quit) { - - packet_peer_stream->put_var("kill_me"); - packet_peer_stream->put_var(0); - requested_quit=false; - - } + if (requested_quit) { + packet_peer_stream->put_var("kill_me"); + packet_peer_stream->put_var(0); + requested_quit = false; + } - if (performance) { + if (performance) { uint64_t pt = OS::get_singleton()->get_ticks_msec(); - if (pt-last_perf_time > 1000) { + if (pt - last_perf_time > 1000) { - last_perf_time=pt; + last_perf_time = pt; int max = performance->get("MONITOR_MAX"); Array arr; arr.resize(max); - for(int i=0;i<max;i++) { - arr[i]=performance->call("get_monitor",i); + for (int i = 0; i < max; i++) { + arr[i] = performance->call("get_monitor", i); } packet_peer_stream->put_var("performance"); packet_peer_stream->put_var(1); packet_peer_stream->put_var(arr); - } - } + } - if (profiling) { + if (profiling) { - if (skip_profile_frame) { - skip_profile_frame=false; - } else { + if (skip_profile_frame) { + skip_profile_frame = false; + } else { //send profiling info normally _send_profiling_data(true); - } - } - - if (reload_all_scripts) { + } + } - for(int i=0;i<ScriptServer::get_language_count();i++) { - ScriptServer::get_language(i)->reload_all_scripts(); - } - reload_all_scripts=false; - } + if (reload_all_scripts) { - _poll_events(); + for (int i = 0; i < ScriptServer::get_language_count(); i++) { + ScriptServer::get_language(i)->reload_all_scripts(); + } + reload_all_scripts = false; + } + _poll_events(); } - -void ScriptDebuggerRemote::send_message(const String& p_message, const Array &p_args) { +void ScriptDebuggerRemote::send_message(const String &p_message, const Array &p_args) { mutex->lock(); if (!locking && tcp_client->is_connected_to_host()) { Message msg; - msg.message=p_message; - msg.data=p_args; + msg.message = p_message; + msg.data = p_args; messages.push_back(msg); } mutex->unlock(); } +void ScriptDebuggerRemote::_print_handler(void *p_this, const String &p_string) { -void ScriptDebuggerRemote::_print_handler(void *p_this,const String& p_string) { - - ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote*)p_this; + ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)p_this; - uint64_t ticks = OS::get_singleton()->get_ticks_usec()/1000; - sdr->msec_count+=ticks-sdr->last_msec; - sdr->last_msec=ticks; + uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000; + sdr->msec_count += ticks - sdr->last_msec; + sdr->last_msec = ticks; - if (sdr->msec_count>1000) { - sdr->char_count=0; - sdr->msec_count=0; + if (sdr->msec_count > 1000) { + sdr->char_count = 0; + sdr->msec_count = 0; } String s = p_string; - int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count,0), s.length()); + int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count, 0), s.length()); - if (allowed_chars==0) + if (allowed_chars == 0) return; - if (allowed_chars<s.length()) { - s=s.substr(0,allowed_chars); + if (allowed_chars < s.length()) { + s = s.substr(0, allowed_chars); } - sdr->char_count+=allowed_chars; + sdr->char_count += allowed_chars; - if (sdr->char_count>=sdr->max_cps) { - s+="\n[output overflow, print less text!]\n"; + if (sdr->char_count >= sdr->max_cps) { + s += "\n[output overflow, print less text!]\n"; } sdr->mutex->lock(); @@ -939,42 +884,42 @@ void ScriptDebuggerRemote::_print_handler(void *p_this,const String& p_string) { void ScriptDebuggerRemote::request_quit() { - requested_quit=true; + requested_quit = true; } void ScriptDebuggerRemote::set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata) { - request_scene_tree=p_func; - request_scene_tree_ud=p_udata; + request_scene_tree = p_func; + request_scene_tree_ud = p_udata; } void ScriptDebuggerRemote::set_live_edit_funcs(LiveEditFuncs *p_funcs) { - live_edit_funcs=p_funcs; + live_edit_funcs = p_funcs; } bool ScriptDebuggerRemote::is_profiling() const { return profiling; } -void ScriptDebuggerRemote::add_profiling_frame_data(const StringName& p_name,const Array& p_data){ +void ScriptDebuggerRemote::add_profiling_frame_data(const StringName &p_name, const Array &p_data) { - int idx=-1; - for(int i=0;i<profile_frame_data.size();i++) { - if (profile_frame_data[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < profile_frame_data.size(); i++) { + if (profile_frame_data[i].name == p_name) { + idx = i; break; } } FrameData fd; - fd.name=p_name; - fd.data=p_data; + fd.name = p_name; + fd.data = p_data; - if (idx==-1) { + if (idx == -1) { profile_frame_data.push_back(fd); } else { - profile_frame_data[idx]=fd; + profile_frame_data[idx] = fd; } } @@ -988,50 +933,46 @@ void ScriptDebuggerRemote::profiling_end() { void ScriptDebuggerRemote::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time) { - frame_time=p_frame_time; - idle_time=p_idle_time; - fixed_time=p_fixed_time; - fixed_frame_time=p_fixed_frame_time; - - + frame_time = p_frame_time; + idle_time = p_idle_time; + fixed_time = p_fixed_time; + fixed_frame_time = p_fixed_frame_time; } - -ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func=NULL; +ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func = NULL; ScriptDebuggerRemote::ScriptDebuggerRemote() { - tcp_client = StreamPeerTCP::create_ref(); - packet_peer_stream = Ref<PacketPeerStream>( memnew(PacketPeerStream) ); + tcp_client = StreamPeerTCP::create_ref(); + packet_peer_stream = Ref<PacketPeerStream>(memnew(PacketPeerStream)); packet_peer_stream->set_stream_peer(tcp_client); mutex = Mutex::create(); - locking=false; + locking = false; - phl.printfunc=_print_handler; - phl.userdata=this; + phl.printfunc = _print_handler; + phl.userdata = this; add_print_handler(&phl); - requested_quit=false; + requested_quit = false; performance = GlobalConfig::get_singleton()->get_singleton_object("Performance"); - last_perf_time=0; - poll_every=0; - request_scene_tree=NULL; - live_edit_funcs=NULL; - max_cps = GLOBAL_DEF("network/debug/max_remote_stdout_chars_per_second",2048); - char_count=0; - msec_count=0; - last_msec=0; - skip_profile_frame=false; - - eh.errfunc=_err_handler; - eh.userdata=this; + last_perf_time = 0; + poll_every = 0; + request_scene_tree = NULL; + live_edit_funcs = NULL; + max_cps = GLOBAL_DEF("network/debug/max_remote_stdout_chars_per_second", 2048); + char_count = 0; + msec_count = 0; + last_msec = 0; + skip_profile_frame = false; + + eh.errfunc = _err_handler; + eh.userdata = this; add_error_handler(&eh); - profile_info.resize(CLAMP(int(GlobalConfig::get_singleton()->get("debug/profiler/max_functions")),128,65535)); + profile_info.resize(CLAMP(int(GlobalConfig::get_singleton()->get("debug/profiler/max_functions")), 128, 65535)); profile_info_ptrs.resize(profile_info.size()); - profiling=false; - max_frame_functions=16; - reload_all_scripts=false; - + profiling = false; + max_frame_functions = 16; + reload_all_scripts = false; } ScriptDebuggerRemote::~ScriptDebuggerRemote() { @@ -1039,6 +980,4 @@ ScriptDebuggerRemote::~ScriptDebuggerRemote() { remove_print_handler(&phl); remove_error_handler(&eh); memdelete(mutex); - - } diff --git a/core/script_debugger_remote.h b/core/script_debugger_remote.h index 4b991e2f0c..9bdf116495 100644 --- a/core/script_debugger_remote.h +++ b/core/script_debugger_remote.h @@ -29,11 +29,10 @@ #ifndef SCRIPT_DEBUGGER_REMOTE_H #define SCRIPT_DEBUGGER_REMOTE_H - -#include "script_language.h" -#include "io/stream_peer_tcp.h" #include "io/packet_peer.h" +#include "io/stream_peer_tcp.h" #include "list.h" +#include "script_language.h" class ScriptDebuggerRemote : public ScriptDebugger { @@ -43,26 +42,24 @@ class ScriptDebuggerRemote : public ScriptDebugger { Array data; }; - struct ProfileInfoSort { - bool operator()(ScriptLanguage::ProfilingInfo*A,ScriptLanguage::ProfilingInfo*B) const { + bool operator()(ScriptLanguage::ProfilingInfo *A, ScriptLanguage::ProfilingInfo *B) const { return A->total_time < B->total_time; } }; Vector<ScriptLanguage::ProfilingInfo> profile_info; - Vector<ScriptLanguage::ProfilingInfo*> profile_info_ptrs; + Vector<ScriptLanguage::ProfilingInfo *> profile_info_ptrs; - Map<StringName,int> profiler_function_signature_map; - float frame_time,idle_time,fixed_time,fixed_frame_time; + Map<StringName, int> profiler_function_signature_map; + float frame_time, idle_time, fixed_time, fixed_frame_time; bool profiling; int max_frame_functions; bool skip_profile_frame; bool reload_all_scripts; - Ref<StreamPeerTCP> tcp_client; Ref<PacketPeerStream> packet_peer_stream; @@ -84,7 +81,6 @@ class ScriptDebuggerRemote : public ScriptDebugger { String error_descr; bool warning; Array callstack; - }; List<String> output_strings; @@ -97,7 +93,7 @@ class ScriptDebuggerRemote : public ScriptDebugger { uint64_t msec_count; bool locking; //hack to avoid a deadloop - static void _print_handler(void *p_this,const String& p_string); + static void _print_handler(void *p_this, const String &p_string); PrintHandlerList phl; @@ -105,25 +101,22 @@ class ScriptDebuggerRemote : public ScriptDebugger { void _poll_events(); uint32_t poll_every; - - bool _parse_live_edit(const Array &p_command); RequestSceneTreeMessageFunc request_scene_tree; void *request_scene_tree_ud; - void _set_object_property(ObjectID p_id, const String& p_property, const Variant& p_value); + void _set_object_property(ObjectID p_id, const String &p_property, const Variant &p_value); void _send_object_id(ObjectID p_id); void _send_video_memory(); LiveEditFuncs *live_edit_funcs; ErrorHandlerList eh; - static void _err_handler(void*,const char*,const char*,int p_line,const char *, const char *,ErrorHandlerType p_type); + static void _err_handler(void *, const char *, const char *, int p_line, const char *, const char *, ErrorHandlerType p_type); void _send_profiling_data(bool p_for_frame); - struct FrameData { StringName name; @@ -132,9 +125,7 @@ class ScriptDebuggerRemote : public ScriptDebugger { Vector<FrameData> profile_frame_data; - public: - struct ResourceUsage { String path; @@ -142,33 +133,32 @@ public: String type; RID id; int vram; - bool operator<(const ResourceUsage& p_img) const { return vram==p_img.vram ? id<p_img.id : vram > p_img.vram; } + bool operator<(const ResourceUsage &p_img) const { return vram == p_img.vram ? id < p_img.id : vram > p_img.vram; } }; - typedef void (*ResourceUsageFunc)(List<ResourceUsage>*); + typedef void (*ResourceUsageFunc)(List<ResourceUsage> *); static ResourceUsageFunc resource_usage_func; - Error connect_to_host(const String& p_host,uint16_t p_port); - virtual void debug(ScriptLanguage *p_script,bool p_can_continue=true); + Error connect_to_host(const String &p_host, uint16_t p_port); + virtual void debug(ScriptLanguage *p_script, bool p_can_continue = true); virtual void idle_poll(); virtual void line_poll(); virtual bool is_remote() const { return true; } virtual void request_quit(); - virtual void send_message(const String& p_message, const Array& p_args); + virtual void send_message(const String &p_message, const Array &p_args); virtual void set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata); virtual void set_live_edit_funcs(LiveEditFuncs *p_funcs); virtual bool is_profiling() const; - virtual void add_profiling_frame_data(const StringName& p_name,const Array& p_data); + virtual void add_profiling_frame_data(const StringName &p_name, const Array &p_data); virtual void profiling_start(); virtual void profiling_end(); - virtual void profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time); - + virtual void profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time); ScriptDebuggerRemote(); ~ScriptDebuggerRemote(); diff --git a/core/script_language.cpp b/core/script_language.cpp index 32db35d018..2d565571a7 100644 --- a/core/script_language.cpp +++ b/core/script_language.cpp @@ -29,15 +29,15 @@ #include "script_language.h" ScriptLanguage *ScriptServer::_languages[MAX_LANGUAGES]; -int ScriptServer::_language_count=0; +int ScriptServer::_language_count = 0; -bool ScriptServer::scripting_enabled=true; -bool ScriptServer::reload_scripts_on_save=false; -ScriptEditRequestFunction ScriptServer::edit_request_func=NULL; +bool ScriptServer::scripting_enabled = true; +bool ScriptServer::reload_scripts_on_save = false; +ScriptEditRequestFunction ScriptServer::edit_request_func = NULL; -void Script::_notification( int p_what) { +void Script::_notification(int p_what) { - if (p_what==NOTIFICATION_POSTINITIALIZE) { + if (p_what == NOTIFICATION_POSTINITIALIZE) { if (ScriptDebugger::get_singleton()) ScriptDebugger::get_singleton()->set_break_language(get_language()); @@ -46,19 +46,18 @@ void Script::_notification( int p_what) { void Script::_bind_methods() { - ClassDB::bind_method(D_METHOD("can_instance"),&Script::can_instance); + ClassDB::bind_method(D_METHOD("can_instance"), &Script::can_instance); //ClassDB::bind_method(D_METHOD("instance_create","base_object"),&Script::instance_create); - ClassDB::bind_method(D_METHOD("instance_has","base_object"),&Script::instance_has); - ClassDB::bind_method(D_METHOD("has_source_code"),&Script::has_source_code); - ClassDB::bind_method(D_METHOD("get_source_code"),&Script::get_source_code); - ClassDB::bind_method(D_METHOD("set_source_code","source"),&Script::set_source_code); - ClassDB::bind_method(D_METHOD("reload","keep_state"),&Script::reload,DEFVAL(false)); - + ClassDB::bind_method(D_METHOD("instance_has", "base_object"), &Script::instance_has); + ClassDB::bind_method(D_METHOD("has_source_code"), &Script::has_source_code); + ClassDB::bind_method(D_METHOD("get_source_code"), &Script::get_source_code); + ClassDB::bind_method(D_METHOD("set_source_code", "source"), &Script::set_source_code); + ClassDB::bind_method(D_METHOD("reload", "keep_state"), &Script::reload, DEFVAL(false)); } void ScriptServer::set_scripting_enabled(bool p_enabled) { - scripting_enabled=p_enabled; + scripting_enabled = p_enabled; } bool ScriptServer::is_scripting_enabled() { @@ -66,34 +65,31 @@ bool ScriptServer::is_scripting_enabled() { return scripting_enabled; } - int ScriptServer::get_language_count() { return _language_count; - } -ScriptLanguage* ScriptServer::get_language(int p_idx) { +ScriptLanguage *ScriptServer::get_language(int p_idx) { - ERR_FAIL_INDEX_V(p_idx,_language_count,NULL); + ERR_FAIL_INDEX_V(p_idx, _language_count, NULL); return _languages[p_idx]; } void ScriptServer::register_language(ScriptLanguage *p_language) { - ERR_FAIL_COND( _language_count >= MAX_LANGUAGES ); - _languages[_language_count++]=p_language; + ERR_FAIL_COND(_language_count >= MAX_LANGUAGES); + _languages[_language_count++] = p_language; } void ScriptServer::unregister_language(ScriptLanguage *p_language) { - - for(int i=0;i<_language_count;i++) { - if (_languages[i]==p_language) { + for (int i = 0; i < _language_count; i++) { + if (_languages[i] == p_language) { _language_count--; - if (i<_language_count) { - SWAP(_languages[i],_languages[_language_count]); + if (i < _language_count) { + SWAP(_languages[i], _languages[_language_count]); } return; } @@ -102,14 +98,14 @@ void ScriptServer::unregister_language(ScriptLanguage *p_language) { void ScriptServer::init_languages() { - for(int i=0;i<_language_count;i++) { + for (int i = 0; i < _language_count; i++) { _languages[i]->init(); } } void ScriptServer::set_reload_scripts_on_save(bool p_enable) { - reload_scripts_on_save=p_enable; + reload_scripts_on_save = p_enable; } bool ScriptServer::is_reload_scripts_on_save_enabled() { @@ -119,99 +115,87 @@ bool ScriptServer::is_reload_scripts_on_save_enabled() { void ScriptServer::thread_enter() { - for(int i=0;i<_language_count;i++) { + for (int i = 0; i < _language_count; i++) { _languages[i]->thread_enter(); } } void ScriptServer::thread_exit() { - for(int i=0;i<_language_count;i++) { + for (int i = 0; i < _language_count; i++) { _languages[i]->thread_exit(); } - } - void ScriptInstance::get_property_state(List<Pair<StringName, Variant> > &state) { List<PropertyInfo> pinfo; get_property_list(&pinfo); - for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage&PROPERTY_USAGE_STORAGE) { - Pair<StringName,Variant> p; - p.first=E->get().name; - if (get(p.first,p.second)) + if (E->get().usage & PROPERTY_USAGE_STORAGE) { + Pair<StringName, Variant> p; + p.first = E->get().name; + if (get(p.first, p.second)) state.push_back(p); } } } - -Variant ScriptInstance::call(const StringName& p_method,VARIANT_ARG_DECLARE) { +Variant ScriptInstance::call(const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_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; - return call(p_method,argptr,argc,error); + return call(p_method, argptr, argc, error); } - -void ScriptInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) { +void ScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) { Variant::CallError ce; - call(p_method,p_args,p_argcount,ce); // script may not support multilevel calls + call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls } -void ScriptInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) { +void ScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) { Variant::CallError ce; - call(p_method,p_args,p_argcount,ce); // script may not support multilevel calls + call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls } -void ScriptInstance::call_multilevel(const StringName& p_method,VARIANT_ARG_DECLARE) { +void ScriptInstance::call_multilevel(const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_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_method,argptr,argc); + call_multilevel(p_method, argptr, argc); } ScriptInstance::~ScriptInstance() { - - } - -ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton=NULL; +ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton = NULL; ScriptCodeCompletionCache::ScriptCodeCompletionCache() { - singleton=this; + singleton = this; } - - void ScriptLanguage::frame() { - - } -ScriptDebugger * ScriptDebugger::singleton=NULL; - +ScriptDebugger *ScriptDebugger::singleton = NULL; void ScriptDebugger::set_lines_left(int p_left) { - lines_left=p_left; + lines_left = p_left; } int ScriptDebugger::get_lines_left() const { @@ -221,7 +205,7 @@ int ScriptDebugger::get_lines_left() const { void ScriptDebugger::set_depth(int p_depth) { - depth=p_depth; + depth = p_depth; } int ScriptDebugger::get_depth() const { @@ -229,38 +213,34 @@ int ScriptDebugger::get_depth() const { return depth; } -void ScriptDebugger::insert_breakpoint(int p_line, const StringName& p_source) { +void ScriptDebugger::insert_breakpoint(int p_line, const StringName &p_source) { if (!breakpoints.has(p_line)) - breakpoints[p_line]=Set<StringName>(); + breakpoints[p_line] = Set<StringName>(); breakpoints[p_line].insert(p_source); - } -void ScriptDebugger::remove_breakpoint(int p_line, const StringName& p_source) { +void ScriptDebugger::remove_breakpoint(int p_line, const StringName &p_source) { if (!breakpoints.has(p_line)) return; breakpoints[p_line].erase(p_source); - if (breakpoints[p_line].size()==0) + if (breakpoints[p_line].size() == 0) breakpoints.erase(p_line); } -bool ScriptDebugger::is_breakpoint(int p_line,const StringName& p_source) const { +bool ScriptDebugger::is_breakpoint(int p_line, const StringName &p_source) const { if (!breakpoints.has(p_line)) return false; return breakpoints[p_line].has(p_source); - } bool ScriptDebugger::is_breakpoint_line(int p_line) const { return breakpoints.has(p_line); - } - -String ScriptDebugger::breakpoint_find_source(const String& p_source) const { +String ScriptDebugger::breakpoint_find_source(const String &p_source) const { return p_source; } @@ -271,116 +251,108 @@ void ScriptDebugger::clear_breakpoints() { } void ScriptDebugger::idle_poll() { - - } - void ScriptDebugger::line_poll() { - - } void ScriptDebugger::set_break_language(ScriptLanguage *p_lang) { - break_lang=p_lang; + break_lang = p_lang; } -ScriptLanguage* ScriptDebugger::get_break_language() const{ +ScriptLanguage *ScriptDebugger::get_break_language() const { return break_lang; } - ScriptDebugger::ScriptDebugger() { - singleton=this; - lines_left=-1; - depth=-1; - break_lang=NULL; + singleton = this; + lines_left = -1; + depth = -1; + break_lang = NULL; } - -bool PlaceHolderScriptInstance::set(const StringName& p_name, const Variant& p_value) { +bool PlaceHolderScriptInstance::set(const StringName &p_name, const Variant &p_value) { if (values.has(p_name)) { - values[p_name]=p_value; + values[p_name] = p_value; return true; } return false; } -bool PlaceHolderScriptInstance::get(const StringName& p_name, Variant &r_ret) const { +bool PlaceHolderScriptInstance::get(const StringName &p_name, Variant &r_ret) const { if (values.has(p_name)) { - r_ret=values[p_name]; + r_ret = values[p_name]; return true; - } return false; + } + return false; } void PlaceHolderScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { - for(const List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) { + for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { p_properties->push_back(E->get()); } } -Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const { +Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { - if (values.has(p_name)) { + if (values.has(p_name)) { if (r_is_valid) - *r_is_valid=true; + *r_is_valid = true; return values[p_name].get_type(); } if (r_is_valid) - *r_is_valid=false; + *r_is_valid = false; return Variant::NIL; } - -void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties,const Map<StringName,Variant>& p_values) { - +void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values) { Set<StringName> new_values; - for(const List<PropertyInfo>::Element *E=p_properties.front();E;E=E->next()) { + for (const List<PropertyInfo>::Element *E = p_properties.front(); E; E = E->next()) { StringName n = E->get().name; new_values.insert(n); - if (!values.has(n) || values[n].get_type()!=E->get().type) { + if (!values.has(n) || values[n].get_type() != E->get().type) { if (p_values.has(n)) - values[n]=p_values[n]; + values[n] = p_values[n]; } } - properties=p_properties; + properties = p_properties; List<StringName> to_remove; - for(Map<StringName,Variant>::Element *E=values.front();E;E=E->next()) { + for (Map<StringName, Variant>::Element *E = values.front(); E; E = E->next()) { if (!new_values.has(E->key())) to_remove.push_back(E->key()); } - while(to_remove.size()) { + while (to_remove.size()) { values.erase(to_remove.front()->get()); to_remove.pop_front(); } - if (owner && owner->get_script_instance()==this) { + if (owner && owner->get_script_instance() == this) { owner->_change_notify(); } //change notify } -PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script,Object *p_owner) { +PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner) { - language=p_language; - script=p_script; - owner=p_owner; + language = p_language; + script = p_script; + owner = p_owner; } PlaceHolderScriptInstance::~PlaceHolderScriptInstance() { diff --git a/core/script_language.h b/core/script_language.h index fd96541b18..6c37074639 100644 --- a/core/script_language.h +++ b/core/script_language.h @@ -29,29 +29,29 @@ #ifndef SCRIPT_LANGUAGE_H #define SCRIPT_LANGUAGE_H -#include "resource.h" #include "map.h" #include "pair.h" +#include "resource.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class ScriptLanguage; -typedef void (*ScriptEditRequestFunction)(const String& p_path); +typedef void (*ScriptEditRequestFunction)(const String &p_path); class ScriptServer { enum { - MAX_LANGUAGES=4 + MAX_LANGUAGES = 4 }; static ScriptLanguage *_languages[MAX_LANGUAGES]; static int _language_count; static bool scripting_enabled; static bool reload_scripts_on_save; -public: +public: static ScriptEditRequestFunction edit_request_func; static void set_scripting_enabled(bool p_enabled); @@ -70,82 +70,76 @@ public: static void init_languages(); }; - - class ScriptInstance; class PlaceHolderScriptInstance; class Script : public Resource { - GDCLASS( Script, Resource ); - OBJ_SAVE_TYPE( Script ); + GDCLASS(Script, Resource); + OBJ_SAVE_TYPE(Script); protected: - virtual bool editor_can_reload_from_file() { return false; } // this is handled by editor better - void _notification( int p_what); + void _notification(int p_what); static void _bind_methods(); -friend class PlaceHolderScriptInstance; + friend class PlaceHolderScriptInstance; virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {} -public: - - virtual bool can_instance() const=0; - virtual Ref<Script> get_base_script() const=0; //for script inheritance +public: + virtual bool can_instance() const = 0; - virtual StringName get_instance_base_type() const=0; // this may not work in all scripts, will return empty if so - virtual ScriptInstance* instance_create(Object *p_this)=0; - virtual bool instance_has(const Object *p_this) const=0; + virtual Ref<Script> get_base_script() const = 0; //for script inheritance + virtual StringName get_instance_base_type() const = 0; // this may not work in all scripts, will return empty if so + virtual ScriptInstance *instance_create(Object *p_this) = 0; + virtual bool instance_has(const Object *p_this) const = 0; - virtual bool has_source_code() const=0; - virtual String get_source_code() const=0; - virtual void set_source_code(const String& p_code)=0; - virtual Error reload(bool p_keep_state=false)=0; + virtual bool has_source_code() const = 0; + virtual String get_source_code() const = 0; + virtual void set_source_code(const String &p_code) = 0; + virtual Error reload(bool p_keep_state = false) = 0; - virtual bool has_method(const StringName& p_method) const=0; - virtual MethodInfo get_method_info(const StringName& p_method) const=0; + virtual bool has_method(const StringName &p_method) const = 0; + virtual MethodInfo get_method_info(const StringName &p_method) const = 0; - virtual bool is_tool() const=0; + virtual bool is_tool() const = 0; - virtual String get_node_type() const=0; + virtual String get_node_type() const = 0; - virtual ScriptLanguage *get_language() const=0; + virtual ScriptLanguage *get_language() const = 0; - virtual bool has_script_signal(const StringName& p_signal) const=0; - virtual void get_script_signal_list(List<MethodInfo> *r_signals) const=0; + virtual bool has_script_signal(const StringName &p_signal) const = 0; + virtual void get_script_signal_list(List<MethodInfo> *r_signals) const = 0; - virtual bool get_property_default_value(const StringName& p_property,Variant& r_value) const=0; + virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const = 0; virtual void update_exports() {} //editor tool - virtual void get_script_method_list(List<MethodInfo> *p_list) const=0; - virtual void get_script_property_list(List<PropertyInfo> *p_list) const=0; + virtual void get_script_method_list(List<MethodInfo> *p_list) const = 0; + virtual void get_script_property_list(List<PropertyInfo> *p_list) const = 0; - virtual int get_member_line(const StringName& p_member) const { return 0; } + virtual int get_member_line(const StringName &p_member) const { return 0; } Script() {} }; class ScriptInstance { public: - - - virtual bool set(const StringName& p_name, const Variant& p_value)=0; - virtual bool get(const StringName& p_name, Variant &r_ret) const=0; - virtual void get_property_list(List<PropertyInfo> *p_properties) const=0; - virtual Variant::Type get_property_type(const StringName& p_name,bool *r_is_valid=NULL) const=0; - - virtual void get_property_state(List<Pair<StringName,Variant> > &state); - - virtual void get_method_list(List<MethodInfo> *p_list) const=0; - virtual bool has_method(const StringName& p_method) const=0; - virtual Variant call(const StringName& p_method,VARIANT_ARG_LIST); - virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error)=0; - virtual void call_multilevel(const StringName& p_method,VARIANT_ARG_LIST); - virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); - virtual void call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount); - virtual void notification(int p_notification)=0; + virtual bool set(const StringName &p_name, const Variant &p_value) = 0; + virtual bool get(const StringName &p_name, Variant &r_ret) const = 0; + virtual void get_property_list(List<PropertyInfo> *p_properties) const = 0; + virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const = 0; + + virtual void get_property_state(List<Pair<StringName, Variant> > &state); + + virtual void get_method_list(List<MethodInfo> *p_list) const = 0; + virtual bool has_method(const StringName &p_method) const = 0; + virtual Variant call(const StringName &p_method, VARIANT_ARG_LIST); + virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) = 0; + virtual void call_multilevel(const StringName &p_method, VARIANT_ARG_LIST); + virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount); + virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount); + virtual void notification(int p_notification) = 0; //this is used by script languages that keep a reference counter of their own //you can make make Ref<> not die when it reaches zero, so deleting the reference @@ -154,7 +148,7 @@ public: virtual void refcount_incremented() {} virtual bool refcount_decremented() { return true; } //return true if it can die - virtual Ref<Script> get_script() const=0; + virtual Ref<Script> get_script() const = 0; virtual bool is_placeholder() const { return false; } @@ -166,50 +160,48 @@ public: RPC_MODE_SLAVE, }; - virtual RPCMode get_rpc_mode(const StringName& p_method) const=0; - virtual RPCMode get_rset_mode(const StringName& p_variable) const=0; + virtual RPCMode get_rpc_mode(const StringName &p_method) const = 0; + virtual RPCMode get_rset_mode(const StringName &p_variable) const = 0; - virtual ScriptLanguage *get_language()=0; + virtual ScriptLanguage *get_language() = 0; virtual ~ScriptInstance(); }; class ScriptCodeCompletionCache { static ScriptCodeCompletionCache *singleton; -public: - virtual RES get_cached_resource(const String& p_path)=0; +public: + virtual RES get_cached_resource(const String &p_path) = 0; - static ScriptCodeCompletionCache* get_sigleton() { return singleton; } + static ScriptCodeCompletionCache *get_sigleton() { return singleton; } ScriptCodeCompletionCache(); - }; class ScriptLanguage { public: - - virtual String get_name() const=0; + virtual String get_name() const = 0; /* LANGUAGE FUNCTIONS */ - virtual void init()=0; - virtual String get_type() const=0; - virtual String get_extension() const=0; - virtual Error execute_file(const String& p_path) =0; - virtual void finish()=0; + virtual void init() = 0; + virtual String get_type() const = 0; + virtual String get_extension() const = 0; + virtual Error execute_file(const String &p_path) = 0; + virtual void finish() = 0; /* EDITOR FUNCTIONS */ - virtual void get_reserved_words(List<String> *p_words) const=0; - virtual void get_comment_delimiters(List<String> *p_delimiters) const=0; - virtual void get_string_delimiters(List<String> *p_delimiters) const=0; - virtual Ref<Script> get_template(const String& p_class_name, const String& p_base_class_name) const=0; - virtual bool validate(const String& p_script, int &r_line_error,int &r_col_error,String& r_test_error, const String& p_path="",List<String> *r_functions=NULL) const=0; - virtual Script *create_script() const=0; - virtual bool has_named_classes() const=0; - virtual int find_function(const String& p_function,const String& p_code) const=0; - virtual String make_function(const String& p_class,const String& p_name,const PoolStringArray& p_args) const=0; - - virtual Error complete_code(const String& p_code, const String& p_base_path, Object*p_owner,List<String>* r_options,String& r_call_hint) { return ERR_UNAVAILABLE; } + virtual void get_reserved_words(List<String> *p_words) const = 0; + virtual void get_comment_delimiters(List<String> *p_delimiters) const = 0; + virtual void get_string_delimiters(List<String> *p_delimiters) const = 0; + virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const = 0; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const = 0; + virtual Script *create_script() const = 0; + virtual bool has_named_classes() const = 0; + virtual int find_function(const String &p_function, const String &p_code) const = 0; + virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const = 0; + + virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return ERR_UNAVAILABLE; } struct LookupResult { enum Type { @@ -226,10 +218,10 @@ public: int location; }; - virtual Error lookup_code(const String& p_code, const String& p_symbol,const String& p_base_path, Object*p_owner,LookupResult& r_result) { return ERR_UNAVAILABLE; } + virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result) { return ERR_UNAVAILABLE; } - virtual void auto_indent_code(String& p_code,int p_from_line,int p_to_line) const=0; - virtual void add_global_constant(const StringName& p_variable,const Variant& p_value)=0; + virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const = 0; + virtual void add_global_constant(const StringName &p_variable, const Variant &p_value) = 0; /* MULTITHREAD FUNCTIONS */ @@ -239,15 +231,15 @@ public: /* DEBUGGER FUNCTIONS */ - virtual String debug_get_error() const=0; - virtual int debug_get_stack_level_count() const=0; - virtual int debug_get_stack_level_line(int p_level) const=0; - virtual String debug_get_stack_level_function(int p_level) const=0; - virtual String debug_get_stack_level_source(int p_level) const=0; - virtual void debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1)=0; - virtual void debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1)=0; - virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1)=0; - virtual String debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems=-1,int p_max_depth=-1)=0; + virtual String debug_get_error() const = 0; + virtual int debug_get_stack_level_count() const = 0; + virtual int debug_get_stack_level_line(int p_level) const = 0; + virtual String debug_get_stack_level_function(int p_level) const = 0; + virtual String debug_get_stack_level_source(int p_level) const = 0; + virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) = 0; + virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) = 0; + virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) = 0; + virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1) = 0; struct StackInfo { Ref<Script> script; @@ -256,32 +248,30 @@ public: virtual Vector<StackInfo> debug_get_current_stack_info() { return Vector<StackInfo>(); } - virtual void reload_all_scripts()=0; - virtual void reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload)=0; + virtual void reload_all_scripts() = 0; + virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) = 0; /* LOADER FUNCTIONS */ - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - virtual void get_public_functions(List<MethodInfo> *p_functions) const=0; - virtual void get_public_constants(List<Pair<String,Variant> > *p_constants) const=0; + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + virtual void get_public_functions(List<MethodInfo> *p_functions) const = 0; + virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const = 0; struct ProfilingInfo { StringName signature; uint64_t call_count; uint64_t total_time; uint64_t self_time; - }; - virtual void profiling_start()=0; - virtual void profiling_stop()=0; - - virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max)=0; - virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max)=0; + virtual void profiling_start() = 0; + virtual void profiling_stop() = 0; + virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) = 0; + virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) = 0; virtual void frame(); - virtual ~ScriptLanguage() {}; + virtual ~ScriptLanguage(){}; }; extern uint8_t script_encryption_key[32]; @@ -290,42 +280,42 @@ class PlaceHolderScriptInstance : public ScriptInstance { Object *owner; List<PropertyInfo> properties; - Map<StringName,Variant> values; + Map<StringName, Variant> values; ScriptLanguage *language; Ref<Script> script; public: - virtual bool set(const StringName& p_name, const Variant& p_value); - virtual bool get(const StringName& p_name, Variant &r_ret) const; + virtual bool set(const StringName &p_name, const Variant &p_value); + virtual bool get(const StringName &p_name, Variant &r_ret) const; virtual void get_property_list(List<PropertyInfo> *p_properties) const; - virtual Variant::Type get_property_type(const StringName& p_name,bool *r_is_valid=NULL) const; + virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const; virtual void get_method_list(List<MethodInfo> *p_list) const {} - virtual bool has_method(const StringName& p_method) const { return false; } - virtual Variant call(const StringName& p_method,VARIANT_ARG_LIST) { return Variant();} - virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } + virtual bool has_method(const StringName &p_method) const { return false; } + virtual Variant call(const StringName &p_method, VARIANT_ARG_LIST) { return Variant(); } + virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + return Variant(); + } //virtual void call_multilevel(const StringName& p_method,VARIANT_ARG_LIST) { return Variant(); } //virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { return Variant(); } virtual void notification(int p_notification) {} - virtual Ref<Script> get_script() const { return script; } virtual ScriptLanguage *get_language() { return language; } Object *get_owner() { return owner; } - void update(const List<PropertyInfo> &p_properties,const Map<StringName,Variant>& p_values); //likely changed in editor + void update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values); //likely changed in editor virtual bool is_placeholder() const { return true; } - virtual RPCMode get_rpc_mode(const StringName& p_method) const { return RPC_MODE_DISABLED; } - virtual RPCMode get_rset_mode(const StringName& p_variable) const { return RPC_MODE_DISABLED; } + virtual RPCMode get_rpc_mode(const StringName &p_method) const { return RPC_MODE_DISABLED; } + virtual RPCMode get_rset_mode(const StringName &p_variable) const { return RPC_MODE_DISABLED; } - PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script,Object *p_owner); + PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner); ~PlaceHolderScriptInstance(); - - }; class ScriptDebugger { @@ -333,64 +323,59 @@ class ScriptDebugger { int lines_left; int depth; - static ScriptDebugger * singleton; - Map<int,Set<StringName> > breakpoints; + static ScriptDebugger *singleton; + Map<int, Set<StringName> > breakpoints; ScriptLanguage *break_lang; -public: +public: typedef void (*RequestSceneTreeMessageFunc)(void *); struct LiveEditFuncs { void *udata; - void (*node_path_func)(void *,const NodePath &p_path,int p_id); - void (*res_path_func)(void *,const String &p_path,int p_id); - - void (*node_set_func)(void *,int p_id,const StringName& p_prop,const Variant& p_value); - void (*node_set_res_func)(void *,int p_id,const StringName& p_prop,const String& p_value); - void (*node_call_func)(void *,int p_id,const StringName& p_method,VARIANT_ARG_DECLARE); - void (*res_set_func)(void *,int p_id,const StringName& p_prop,const Variant& p_value); - void (*res_set_res_func)(void *,int p_id,const StringName& p_prop,const String& p_value); - void (*res_call_func)(void *,int p_id,const StringName& p_method,VARIANT_ARG_DECLARE); - void (*root_func)(void*, const NodePath& p_scene_path,const String& p_scene_from); - - void (*tree_create_node_func)(void*,const NodePath& p_parent,const String& p_type,const String& p_name); - void (*tree_instance_node_func)(void*,const NodePath& p_parent,const String& p_path,const String& p_name); - void (*tree_remove_node_func)(void*,const NodePath& p_at); - void (*tree_remove_and_keep_node_func)(void*,const NodePath& p_at,ObjectID p_keep_id); - void (*tree_restore_node_func)(void*,ObjectID p_id,const NodePath& p_at,int p_at_pos); - void (*tree_duplicate_node_func)(void*,const NodePath& p_at,const String& p_new_name); - void (*tree_reparent_node_func)(void*,const NodePath& p_at,const NodePath& p_new_place,const String& p_new_name,int p_at_pos); - + void (*node_path_func)(void *, const NodePath &p_path, int p_id); + void (*res_path_func)(void *, const String &p_path, int p_id); + + void (*node_set_func)(void *, int p_id, const StringName &p_prop, const Variant &p_value); + void (*node_set_res_func)(void *, int p_id, const StringName &p_prop, const String &p_value); + void (*node_call_func)(void *, int p_id, const StringName &p_method, VARIANT_ARG_DECLARE); + void (*res_set_func)(void *, int p_id, const StringName &p_prop, const Variant &p_value); + void (*res_set_res_func)(void *, int p_id, const StringName &p_prop, const String &p_value); + void (*res_call_func)(void *, int p_id, const StringName &p_method, VARIANT_ARG_DECLARE); + void (*root_func)(void *, const NodePath &p_scene_path, const String &p_scene_from); + + void (*tree_create_node_func)(void *, const NodePath &p_parent, const String &p_type, const String &p_name); + void (*tree_instance_node_func)(void *, const NodePath &p_parent, const String &p_path, const String &p_name); + void (*tree_remove_node_func)(void *, const NodePath &p_at); + void (*tree_remove_and_keep_node_func)(void *, const NodePath &p_at, ObjectID p_keep_id); + void (*tree_restore_node_func)(void *, ObjectID p_id, const NodePath &p_at, int p_at_pos); + void (*tree_duplicate_node_func)(void *, const NodePath &p_at, const String &p_new_name); + void (*tree_reparent_node_func)(void *, const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos); }; - - - _FORCE_INLINE_ static ScriptDebugger * get_singleton() { return singleton; } + _FORCE_INLINE_ static ScriptDebugger *get_singleton() { return singleton; } void set_lines_left(int p_left); int get_lines_left() const; void set_depth(int p_depth); int get_depth() const; - String breakpoint_find_source(const String& p_source) const; - void insert_breakpoint(int p_line, const StringName& p_source); - void remove_breakpoint(int p_line, const StringName& p_source); - bool is_breakpoint(int p_line,const StringName& p_source) const; + String breakpoint_find_source(const String &p_source) const; + void insert_breakpoint(int p_line, const StringName &p_source); + void remove_breakpoint(int p_line, const StringName &p_source); + bool is_breakpoint(int p_line, const StringName &p_source) const; bool is_breakpoint_line(int p_line) const; void clear_breakpoints(); - - virtual void debug(ScriptLanguage *p_script,bool p_can_continue=true)=0; + virtual void debug(ScriptLanguage *p_script, bool p_can_continue = true) = 0; virtual void idle_poll(); virtual void line_poll(); - void set_break_language(ScriptLanguage *p_lang); - ScriptLanguage* get_break_language() const; + ScriptLanguage *get_break_language() const; - virtual void send_message(const String& p_message, const Array& p_args)=0; + virtual void send_message(const String &p_message, const Array &p_args) = 0; virtual bool is_remote() const { return false; } virtual void request_quit() {} @@ -398,18 +383,14 @@ public: virtual void set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata) {} virtual void set_live_edit_funcs(LiveEditFuncs *p_funcs) {} - virtual bool is_profiling() const=0; - virtual void add_profiling_frame_data(const StringName& p_name,const Array& p_data)=0; - virtual void profiling_start()=0; - virtual void profiling_end()=0; - virtual void profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time)=0; - + virtual bool is_profiling() const = 0; + virtual void add_profiling_frame_data(const StringName &p_name, const Array &p_data) = 0; + virtual void profiling_start() = 0; + virtual void profiling_end() = 0; + virtual void profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time) = 0; ScriptDebugger(); - virtual ~ScriptDebugger() {singleton=NULL;} - + virtual ~ScriptDebugger() { singleton = NULL; } }; - - #endif diff --git a/core/self_list.h b/core/self_list.h index aec3c33adc..45986d77e9 100644 --- a/core/self_list.h +++ b/core/self_list.h @@ -31,78 +31,74 @@ #include "typedefs.h" -template<class T> +template <class T> class SelfList { public: - - - class List { - SelfList<T> *_first; + public: void add(SelfList<T> *p_elem) { ERR_FAIL_COND(p_elem->_root); - p_elem->_root=this; - p_elem->_next=_first; - p_elem->_prev=NULL; + p_elem->_root = this; + p_elem->_next = _first; + p_elem->_prev = NULL; if (_first) - _first->_prev=p_elem; - _first=p_elem; + _first->_prev = p_elem; + _first = p_elem; } void remove(SelfList<T> *p_elem) { - ERR_FAIL_COND(p_elem->_root!=this); + ERR_FAIL_COND(p_elem->_root != this); if (p_elem->_next) { - p_elem->_next->_prev=p_elem->_prev; + p_elem->_next->_prev = p_elem->_prev; } if (p_elem->_prev) { - p_elem->_prev->_next=p_elem->_next; + p_elem->_prev->_next = p_elem->_next; } - if (_first==p_elem) { + if (_first == p_elem) { - _first=p_elem->_next; + _first = p_elem->_next; } - p_elem->_next=NULL; - p_elem->_prev=NULL; - p_elem->_root=NULL; + p_elem->_next = NULL; + p_elem->_prev = NULL; + p_elem->_root = NULL; } _FORCE_INLINE_ SelfList<T> *first() { return _first; } _FORCE_INLINE_ const SelfList<T> *first() const { return _first; } - _FORCE_INLINE_ List() { _first=NULL; } - _FORCE_INLINE_ ~List() { ERR_FAIL_COND(_first!=NULL); } - + _FORCE_INLINE_ List() { _first = NULL; } + _FORCE_INLINE_ ~List() { ERR_FAIL_COND(_first != NULL); } }; + private: List *_root; T *_self; SelfList<T> *_next; SelfList<T> *_prev; -public: +public: _FORCE_INLINE_ bool in_list() const { return _root; } _FORCE_INLINE_ SelfList<T> *next() { return _next; } _FORCE_INLINE_ SelfList<T> *prev() { return _prev; } _FORCE_INLINE_ const SelfList<T> *next() const { return _next; } _FORCE_INLINE_ const SelfList<T> *prev() const { return _prev; } - _FORCE_INLINE_ T*self() const { return _self; } - + _FORCE_INLINE_ T *self() const { return _self; } _FORCE_INLINE_ SelfList(T *p_self) { - _self=p_self; - _next=NULL; - _prev=NULL; - _root=NULL; + _self = p_self; + _next = NULL; + _prev = NULL; + _root = NULL; } _FORCE_INLINE_ ~SelfList() { @@ -110,7 +106,6 @@ public: if (_root) _root->remove(this); } - }; #endif // SELF_LIST_H diff --git a/core/set.h b/core/set.h index a921fc661f..e6ec64e787 100644 --- a/core/set.h +++ b/core/set.h @@ -29,18 +29,17 @@ #ifndef SET_H #define SET_H -#include "typedefs.h" #include "os/memory.h" +#include "typedefs.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - // 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 T,class C=Comparator<T>,class A=DefaultAllocator > +template <class T, class C = Comparator<T>, class A = DefaultAllocator> class Set { enum Color { @@ -48,25 +47,22 @@ class Set { BLACK }; struct _Data; -public: - - +public: class Element { private: - friend class Set<T,C,A>; + friend class Set<T, C, A>; int color; - Element* right; - Element* left; - Element* parent; - Element* _next; - Element* _prev; + Element *right; + Element *left; + Element *parent; + Element *_next; + Element *_prev; T value; //_Data *data; public: - const Element *next() const { return _next; @@ -83,55 +79,52 @@ public: return _prev; } - const T& get() const { + const T &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; - _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; + 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<Element,A>(_root); - _root=NULL; + memdelete_allocator<Element, A>(_root); + _root = NULL; } } @@ -139,7 +132,7 @@ private: _free_root(); #ifdef GLOBALNIL_DISABLED - memdelete_allocator<Element,A>(_nil); + memdelete_allocator<Element, A>(_nil); #endif //memdelete_allocator<Element,A>(_root); } @@ -149,58 +142,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; @@ -208,70 +199,69 @@ 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 T& p_value) const { + Element *_find(const T &p_value) const { Element *node = _data._root->left; C less; - while(node!=_data._nil) { + while (node != _data._nil) { - if (less(p_value,node->value)) - node=node->left; - else if (less(node->value,p_value)) - node=node->right; + if (less(p_value, node->value)) + node = node->left; + else if (less(node->value, p_value)) + node = node->right; else break; // found } - return (node!=_data._nil)?node:NULL; + return (node != _data._nil) ? node : NULL; } - Element *_lower_bound(const T& p_value) const { + Element *_lower_bound(const T &p_value) 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_value,node->value)) - node=node->left; - else if (less(node->value,p_value)) - node=node->right; + if (less(p_value, node->value)) + node = node->left; + else if (less(node->value, p_value)) + node = node->right; else break; // found } - if (node==_data._nil) { - if (prev==NULL) + if (node == _data._nil) { + if (prev == NULL) return NULL; - if (less(prev->value,p_value)) { + if (less(prev->value, p_value)) { - prev=prev->_next; + prev = prev->_next; } return prev; @@ -280,308 +270,299 @@ private: return node; } + Element *_insert(const T &p_value, bool &r_exists) { - Element *_insert(const T& p_value, 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_value,node->value)) - node=node->left; - else if (less(node->value,p_value)) - node=node->right; + if (less(p_value, node->value)) + node = node->left; + else if (less(node->value, p_value)) + 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->value=p_value; + new_node->parent = new_parent; + new_node->right = _data._nil; + new_node->left = _data._nil; + new_node->value = p_value; //new_node->data=_data; - if (new_parent==_data._root || less(p_value,new_parent->value)) { + if (new_parent == _data._root || less(p_value, new_parent->value)) { - 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 T& p_value) { + Element *_insert_rb(const T &p_value) { - bool exists=false; - Element *new_node = _insert(p_value,exists); + bool exists = false; + Element *new_node = _insert(p_value, exists); 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<Element,A>(p_node); + memdelete_allocator<Element, A>(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<Element,A>( p_element ); + memdelete_allocator<Element, A>(p_element); } - void _copy_from( const Set& p_set) { + void _copy_from(const Set &p_set) { clear(); // not the fastest way, but safeset to write. - for(Element *I=p_set.front();I;I=I->next()) { + for (Element *I = p_set.front(); I; I = I->next()) { insert(I->get()); } } -public: - const Element *find(const T& p_value) const { +public: + const Element *find(const T &p_value) const { if (!_data._root) return NULL; - const Element *res=_find(p_value); + const Element *res = _find(p_value); return res; } - Element *find(const T& p_value) { + Element *find(const T &p_value) { if (!_data._root) return NULL; - Element *res=_find(p_value); + Element *res = _find(p_value); return res; } - bool has(const T& p_value) const { + bool has(const T &p_value) const { if (!_data._root) return false; - return find(p_value)!=NULL; + return find(p_value) != NULL; } - Element *insert(const T& p_value) { + Element *insert(const T &p_value) { if (!_data._root) _data._create_root(); return _insert_rb(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 T& p_value) { + bool erase(const T &p_value) { if (!_data._root) return false; - Element *e=find(p_value); + Element *e = find(p_value); if (!e) return false; _erase(e); - if (_data.size_cache==0 && _data._root) + if (_data.size_cache == 0 && _data._root) _data._free_root(); return true; } @@ -590,12 +571,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; } @@ -604,29 +585,28 @@ 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; } - Element *lower_bound(const T& p_value) const { + Element *lower_bound(const T &p_value) const { return _lower_bound(p_value); } - 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; } @@ -636,32 +616,28 @@ public: 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 Set& p_set) { + void operator=(const Set &p_set) { - _copy_from( p_set ); + _copy_from(p_set); } - Set(const Set& p_set) { + Set(const Set &p_set) { - _copy_from( p_set ); + _copy_from(p_set); } _FORCE_INLINE_ Set() { - - } - ~Set() { clear(); } - }; #endif diff --git a/core/simple_type.h b/core/simple_type.h index 6d4a1ba455..b5182559d7 100644 --- a/core/simple_type.h +++ b/core/simple_type.h @@ -31,89 +31,85 @@ /* Batch of specializations to obtain the actual simple type */ -template<class T> +template <class T> struct GetSimpleType { T type; }; -template<class T> +template <class T> struct GetSimpleTypeT { typedef T type_t; }; -template<class T> -struct GetSimpleType<T&> { +template <class T> +struct GetSimpleType<T &> { T type; - }; -template<class T> -struct GetSimpleTypeT<T&> { +template <class T> +struct GetSimpleTypeT<T &> { typedef T type_t; }; -template<class T> +template <class T> struct GetSimpleType<T const> { T type; - _FORCE_INLINE_ GetSimpleType() { } - + _FORCE_INLINE_ GetSimpleType() {} }; -template<class T> +template <class T> struct GetSimpleTypeT<T const> { typedef T type_t; }; -template<class T> -struct GetSimpleType<const T&> { +template <class T> +struct GetSimpleType<const T &> { T type; - _FORCE_INLINE_ GetSimpleType() { } - + _FORCE_INLINE_ GetSimpleType() {} }; -template<class T> -struct GetSimpleType<T*> { +template <class T> +struct GetSimpleType<T *> { T *type; - _FORCE_INLINE_ GetSimpleType() { type=NULL; } + _FORCE_INLINE_ GetSimpleType() { type = NULL; } }; -template<class T> -struct GetSimpleType<const T*> { +template <class T> +struct GetSimpleType<const T *> { T *type; - _FORCE_INLINE_ GetSimpleType() { type=NULL; } + _FORCE_INLINE_ GetSimpleType() { type = NULL; } }; - -#define SIMPLE_NUMERIC_TYPE(m_type)\ -template<>\ -struct GetSimpleType<m_type> { \ - m_type type;\ - _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \ -};\ -template<>\ -struct GetSimpleType<m_type const> { \ - m_type type;\ - _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \ -};\ -template<>\ -struct GetSimpleType<m_type&> { \ - m_type type;\ - _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \ -};\ -template<>\ -struct GetSimpleType<const m_type&> { \ - m_type type;\ - _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \ -};\ +#define SIMPLE_NUMERIC_TYPE(m_type) \ + template <> \ + struct GetSimpleType<m_type> { \ + m_type type; \ + _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \ + }; \ + template <> \ + struct GetSimpleType<m_type const> { \ + m_type type; \ + _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \ + }; \ + template <> \ + struct GetSimpleType<m_type &> { \ + m_type type; \ + _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \ + }; \ + template <> \ + struct GetSimpleType<const m_type &> { \ + m_type type; \ + _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \ + }; SIMPLE_NUMERIC_TYPE(bool); SIMPLE_NUMERIC_TYPE(uint8_t); @@ -127,8 +123,4 @@ SIMPLE_NUMERIC_TYPE(uint64_t); SIMPLE_NUMERIC_TYPE(float); SIMPLE_NUMERIC_TYPE(double); - - - #endif - diff --git a/core/sort.h b/core/sort.h index fd3b57251a..8ec1cc6bd1 100644 --- a/core/sort.h +++ b/core/sort.h @@ -34,26 +34,24 @@ @author ,,, <red@lunatea> */ -template<class T> +template <class T> struct _DefaultComparator { - inline bool operator()(const T&a,const T&b) const { return (a<b); } + inline bool operator()(const T &a, const T &b) const { return (a < b); } }; -template<class T, class Comparator=_DefaultComparator<T> > +template <class T, class Comparator = _DefaultComparator<T> > class SortArray { enum { - INTROSORT_TRESHOLD=16 + INTROSORT_TRESHOLD = 16 }; public: - Comparator compare; - - inline const T& median_of_3(const T& a, const T& b, const T& c) const { + inline const T &median_of_3(const T &a, const T &b, const T &c) const { if (compare(a, b)) if (compare(b, c)) @@ -70,8 +68,6 @@ public: return b; } - - inline int bitlog(int n) const { int k; for (k = 0; n != 1; n >>= 1) @@ -79,10 +75,9 @@ public: return k; } - /* Heap / Heapsort functions */ - inline void push_heap(int p_first,int p_hole_idx,int p_top_index,T p_value,T* p_array) const { + inline void push_heap(int p_first, int p_hole_idx, int p_top_index, T p_value, T *p_array) const { int parent = (p_hole_idx - 1) / 2; while (p_hole_idx > p_top_index && compare(p_array[p_first + parent], p_value)) { @@ -94,25 +89,24 @@ public: p_array[p_first + p_hole_idx] = p_value; } - inline void pop_heap(int p_first, int p_last, int p_result, T p_value, T* p_array) const { + inline void pop_heap(int p_first, int p_last, int p_result, T p_value, T *p_array) const { - p_array[p_result]=p_array[p_first]; - adjust_heap(p_first,0,p_last-p_first,p_value,p_array); + p_array[p_result] = p_array[p_first]; + adjust_heap(p_first, 0, p_last - p_first, p_value, p_array); } - inline void pop_heap(int p_first,int p_last,T* p_array) const { + inline void pop_heap(int p_first, int p_last, T *p_array) const { - pop_heap(p_first,p_last-1,p_last-1,p_array[p_last-1],p_array); + pop_heap(p_first, p_last - 1, p_last - 1, p_array[p_last - 1], p_array); } - inline void adjust_heap(int p_first,int p_hole_idx,int p_len,T p_value,T* p_array) const { - + inline void adjust_heap(int p_first, int p_hole_idx, int p_len, T p_value, T *p_array) const { int top_index = p_hole_idx; int second_child = 2 * p_hole_idx + 2; while (second_child < p_len) { - if (compare(p_array[p_first + second_child],p_array[p_first + (second_child - 1)])) + if (compare(p_array[p_first + second_child], p_array[p_first + (second_child - 1)])) second_child--; p_array[p_first + p_hole_idx] = p_array[p_first + second_child]; @@ -124,22 +118,22 @@ public: p_array[p_first + p_hole_idx] = p_array[p_first + (second_child - 1)]; p_hole_idx = second_child - 1; } - push_heap(p_first, p_hole_idx, top_index, p_value,p_array); + push_heap(p_first, p_hole_idx, top_index, p_value, p_array); } - inline void sort_heap(int p_first,int p_last,T* p_array) const { + inline void sort_heap(int p_first, int p_last, T *p_array) const { - while(p_last-p_first > 1) { + while (p_last - p_first > 1) { - pop_heap(p_first,p_last--,p_array); + pop_heap(p_first, p_last--, p_array); } } - inline void make_heap(int p_first, int p_last,T* p_array) const { + inline void make_heap(int p_first, int p_last, T *p_array) const { if (p_last - p_first < 2) return; int len = p_last - p_first; - int parent = (len - 2)/2; + int parent = (len - 2) / 2; while (true) { adjust_heap(p_first, parent, len, p_array[p_first + parent], p_array); @@ -149,174 +143,163 @@ public: } } - inline void partial_sort(int p_first,int p_last,int p_middle,T* p_array) const { + inline void partial_sort(int p_first, int p_last, int p_middle, T *p_array) const { - make_heap(p_first,p_middle,p_array); - for(int i=p_middle;i<p_last;i++) - if (compare( p_array[i],p_array[p_first])) - pop_heap(p_first,p_middle,i,p_array[i],p_array); - sort_heap(p_first,p_middle,p_array); + make_heap(p_first, p_middle, p_array); + for (int i = p_middle; i < p_last; i++) + if (compare(p_array[i], p_array[p_first])) + pop_heap(p_first, p_middle, i, p_array[i], p_array); + sort_heap(p_first, p_middle, p_array); } - inline void partial_select(int p_first,int p_last,int p_middle,T* p_array) const { + inline void partial_select(int p_first, int p_last, int p_middle, T *p_array) const { - make_heap(p_first,p_middle,p_array); - for(int i=p_middle;i<p_last;i++) - if (compare( p_array[i],p_array[p_first])) - pop_heap(p_first,p_middle,i,p_array[i],p_array); + make_heap(p_first, p_middle, p_array); + for (int i = p_middle; i < p_last; i++) + if (compare(p_array[i], p_array[p_first])) + pop_heap(p_first, p_middle, i, p_array[i], p_array); } - inline int partitioner(int p_first, int p_last, T p_pivot, T* p_array) const { + inline int partitioner(int p_first, int p_last, T p_pivot, T *p_array) const { while (true) { - while (compare(p_array[p_first],p_pivot)) + while (compare(p_array[p_first], p_pivot)) p_first++; p_last--; - while (compare(p_pivot,p_array[p_last])) + while (compare(p_pivot, p_array[p_last])) p_last--; if (!(p_first < p_last)) return p_first; - SWAP(p_array[p_first],p_array[p_last]); + SWAP(p_array[p_first], p_array[p_last]); p_first++; } } - inline void introsort(int p_first, int p_last, T* p_array, int p_max_depth) const { + inline void introsort(int p_first, int p_last, T *p_array, int p_max_depth) const { - while( p_last - p_first > INTROSORT_TRESHOLD ) { + while (p_last - p_first > INTROSORT_TRESHOLD) { if (p_max_depth == 0) { - partial_sort(p_first,p_last,p_last,p_array); + partial_sort(p_first, p_last, p_last, p_array); return; } p_max_depth--; int cut = partitioner( - p_first, - p_last, - median_of_3( - p_array[p_first], - p_array[p_first + (p_last-p_first)/2], - p_array[p_last-1] - ), - p_array - ); - - introsort(cut,p_last,p_array,p_max_depth); - p_last=cut; - + p_first, + p_last, + median_of_3( + p_array[p_first], + p_array[p_first + (p_last - p_first) / 2], + p_array[p_last - 1]), + p_array); + + introsort(cut, p_last, p_array, p_max_depth); + p_last = cut; } - } + } - inline void introselect(int p_first, int p_nth, int p_last, T* p_array, int p_max_depth) const { + inline void introselect(int p_first, int p_nth, int p_last, T *p_array, int p_max_depth) const { - while( p_last - p_first > 3 ) { + while (p_last - p_first > 3) { if (p_max_depth == 0) { - partial_select(p_first,p_nth+1,p_last,p_array); - SWAP(p_first,p_nth); + partial_select(p_first, p_nth + 1, p_last, p_array); + SWAP(p_first, p_nth); return; } p_max_depth--; int cut = partitioner( - p_first, - p_last, - median_of_3( - p_array[p_first], - p_array[p_first + (p_last-p_first)/2], - p_array[p_last-1] - ), - p_array - ); - - if (cut<=p_nth) - p_first=cut; + p_first, + p_last, + median_of_3( + p_array[p_first], + p_array[p_first + (p_last - p_first) / 2], + p_array[p_last - 1]), + p_array); + + if (cut <= p_nth) + p_first = cut; else - p_last=cut; - + p_last = cut; } - insertion_sort(p_first,p_last,p_array); + insertion_sort(p_first, p_last, p_array); } - inline void unguarded_linear_insert(int p_last,T p_value,T* p_array) const { + inline void unguarded_linear_insert(int p_last, T p_value, T *p_array) const { - int next = p_last-1; - while (compare(p_value,p_array[next])) { - p_array[p_last]=p_array[next]; + int next = p_last - 1; + while (compare(p_value, p_array[next])) { + p_array[p_last] = p_array[next]; p_last = next; next--; } p_array[p_last] = p_value; } - inline void linear_insert(int p_first,int p_last,T*p_array) const { + inline void linear_insert(int p_first, int p_last, T *p_array) const { T val = p_array[p_last]; if (compare(val, p_array[p_first])) { - for (int i=p_last; i>p_first; i--) - p_array[i]=p_array[i-1]; + for (int i = p_last; i > p_first; i--) + p_array[i] = p_array[i - 1]; p_array[p_first] = val; } else unguarded_linear_insert(p_last, val, p_array); } - inline void insertion_sort(int p_first,int p_last,T* p_array) const { + inline void insertion_sort(int p_first, int p_last, T *p_array) const { - if (p_first==p_last) + if (p_first == p_last) return; - for (int i=p_first+1; i!=p_last ; i++) - linear_insert(p_first,i,p_array); + for (int i = p_first + 1; i != p_last; i++) + linear_insert(p_first, i, p_array); } - inline void unguarded_insertion_sort(int p_first,int p_last,T* p_array) const { + inline void unguarded_insertion_sort(int p_first, int p_last, T *p_array) const { - for (int i=p_first; i!=p_last ; i++) - unguarded_linear_insert(i,p_array[i],p_array); + for (int i = p_first; i != p_last; i++) + unguarded_linear_insert(i, p_array[i], p_array); } - inline void final_insertion_sort(int p_first,int p_last,T* p_array) const { + inline void final_insertion_sort(int p_first, int p_last, T *p_array) const { if (p_last - p_first > INTROSORT_TRESHOLD) { - insertion_sort(p_first,p_first+INTROSORT_TRESHOLD,p_array); - unguarded_insertion_sort(p_first+INTROSORT_TRESHOLD,p_last,p_array); + insertion_sort(p_first, p_first + INTROSORT_TRESHOLD, p_array); + unguarded_insertion_sort(p_first + INTROSORT_TRESHOLD, p_last, p_array); } else { - insertion_sort(p_first,p_last,p_array); - + insertion_sort(p_first, p_last, p_array); } - } + } - inline void sort_range(int p_first, int p_last,T* p_array) const { + inline void sort_range(int p_first, int p_last, T *p_array) const { if (p_first != p_last) { - introsort(p_first, p_last,p_array,bitlog(p_last - p_first) * 2); + introsort(p_first, p_last, p_array, bitlog(p_last - p_first) * 2); final_insertion_sort(p_first, p_last, p_array); } } - inline void sort(T* p_array,int p_len) const { + inline void sort(T *p_array, int p_len) const { - sort_range(0,p_len,p_array); + sort_range(0, p_len, p_array); } - inline void nth_element(int p_first,int p_last,int p_nth,T* p_array) const { + inline void nth_element(int p_first, int p_last, int p_nth, T *p_array) const { - if (p_first==p_last || p_nth==p_last) + if (p_first == p_last || p_nth == p_last) return; - introselect(p_first,p_nth,p_last,p_array,bitlog(p_last - p_first) * 2); + introselect(p_first, p_nth, p_last, p_array, bitlog(p_last - p_first) * 2); } - }; - - - #endif diff --git a/core/string_db.cpp b/core/string_db.cpp index 004b07b9e5..54535fa06b 100644 --- a/core/string_db.cpp +++ b/core/string_db.cpp @@ -28,61 +28,63 @@ /*************************************************************************/ #include "string_db.h" -#include "print_string.h" #include "os/os.h" +#include "print_string.h" StaticCString StaticCString::create(const char *p_ptr) { - StaticCString scs; scs.ptr=p_ptr; return scs; + StaticCString scs; + scs.ptr = p_ptr; + return scs; } StringName::_Data *StringName::_table[STRING_TABLE_LEN]; StringName _scs_create(const char *p_chr) { - return (p_chr[0]?StringName(StaticCString::create(p_chr)):StringName()); + return (p_chr[0] ? StringName(StaticCString::create(p_chr)) : StringName()); } -bool StringName::configured=false; -Mutex* StringName::lock=NULL; +bool StringName::configured = false; +Mutex *StringName::lock = NULL; void StringName::setup() { lock = Mutex::create(); ERR_FAIL_COND(configured); - for(int i=0;i<STRING_TABLE_LEN;i++) { + for (int i = 0; i < STRING_TABLE_LEN; i++) { - _table[i]=NULL; + _table[i] = NULL; } - configured=true; + configured = true; } void StringName::cleanup() { lock->lock(); - int lost_strings=0; - for(int i=0;i<STRING_TABLE_LEN;i++) { + int lost_strings = 0; + for (int i = 0; i < STRING_TABLE_LEN; i++) { - while(_table[i]) { + while (_table[i]) { - _Data*d=_table[i]; + _Data *d = _table[i]; lost_strings++; if (OS::get_singleton()->is_stdout_verbose()) { if (d->cname) { - print_line("Orphan StringName: "+String(d->cname)); + print_line("Orphan StringName: " + String(d->cname)); } else { - print_line("Orphan StringName: "+String(d->name)); + print_line("Orphan StringName: " + String(d->name)); } } - _table[i]=_table[i]->next; + _table[i] = _table[i]->next; memdelete(d); } } if (OS::get_singleton()->is_stdout_verbose() && lost_strings) { - print_line("StringName: "+itos(lost_strings)+" unclaimed string names at exit."); + print_line("StringName: " + itos(lost_strings) + " unclaimed string names at exit."); } lock->unlock(); @@ -98,65 +100,59 @@ void StringName::unref() { lock->lock(); if (_data->prev) { - _data->prev->next=_data->next; + _data->prev->next = _data->next; } else { - if (_table[_data->idx]!=_data) { + if (_table[_data->idx] != _data) { ERR_PRINT("BUG!"); } - _table[_data->idx]=_data->next; + _table[_data->idx] = _data->next; } if (_data->next) { - _data->next->prev=_data->prev; - + _data->next->prev = _data->prev; } memdelete(_data); lock->unlock(); } - _data=NULL; - + _data = NULL; } -bool StringName::operator==(const String& p_name) const { +bool StringName::operator==(const String &p_name) const { if (!_data) { - return (p_name.length()==0); + return (p_name.length() == 0); } - return (_data->get_name()==p_name); + return (_data->get_name() == p_name); } -bool StringName::operator==(const char* p_name) const { +bool StringName::operator==(const char *p_name) const { if (!_data) { - return (p_name[0]==0); + return (p_name[0] == 0); } - return (_data->get_name()==p_name); + return (_data->get_name() == p_name); } -bool StringName::operator!=(const String& p_name) const { +bool StringName::operator!=(const String &p_name) const { return !(operator==(p_name)); } - - -bool StringName::operator!=(const StringName& p_name) const { +bool StringName::operator!=(const StringName &p_name) const { // the real magic of all this mess happens here. // this is why path comparisons are very fast - return _data!=p_name._data; - + return _data != p_name._data; } +void StringName::operator=(const StringName &p_name) { -void StringName::operator=(const StringName& p_name) { - - if (this==&p_name) + if (this == &p_name) return; unref(); @@ -175,10 +171,10 @@ StringName::operator String() const { return ""; } */ -StringName::StringName(const StringName& p_name) { +StringName::StringName(const StringName &p_name) { ERR_FAIL_COND(!configured); - _data=NULL; + _data = NULL; if (p_name._data && p_name._data->refcount.ref()) { _data = p_name._data; @@ -187,168 +183,154 @@ StringName::StringName(const StringName& p_name) { StringName::StringName(const char *p_name) { - _data=NULL; + _data = NULL; ERR_FAIL_COND(!configured); - if (!p_name || p_name[0]==0) + if (!p_name || p_name[0] == 0) return; //empty, ignore lock->lock(); uint32_t hash = String::hash(p_name); - uint32_t idx=hash&STRING_TABLE_MASK; + uint32_t idx = hash & STRING_TABLE_MASK; - _data=_table[idx]; + _data = _table[idx]; - while(_data) { + while (_data) { // compare hash first - if (_data->hash==hash && _data->get_name()==p_name) + if (_data->hash == hash && _data->get_name() == p_name) break; - _data=_data->next; + _data = _data->next; } - if (_data) { if (_data->refcount.ref()) { // exists lock->unlock(); return; } else { - } } - _data = memnew( _Data ); - _data->name=p_name; + _data = memnew(_Data); + _data->name = p_name; _data->refcount.init(); - _data->hash=hash; - _data->idx=idx; - _data->cname=NULL; - _data->next=_table[idx]; - _data->prev=NULL; + _data->hash = hash; + _data->idx = idx; + _data->cname = NULL; + _data->next = _table[idx]; + _data->prev = NULL; if (_table[idx]) - _table[idx]->prev=_data; - _table[idx]=_data; - + _table[idx]->prev = _data; + _table[idx] = _data; lock->unlock(); } -StringName::StringName(const StaticCString& p_static_string) { +StringName::StringName(const StaticCString &p_static_string) { - _data=NULL; + _data = NULL; ERR_FAIL_COND(!configured); - ERR_FAIL_COND( !p_static_string.ptr || !p_static_string.ptr[0]); + ERR_FAIL_COND(!p_static_string.ptr || !p_static_string.ptr[0]); lock->lock(); uint32_t hash = String::hash(p_static_string.ptr); - uint32_t idx=hash&STRING_TABLE_MASK; + uint32_t idx = hash & STRING_TABLE_MASK; - _data=_table[idx]; + _data = _table[idx]; - while(_data) { + while (_data) { // compare hash first - if (_data->hash==hash && _data->get_name()==p_static_string.ptr) + if (_data->hash == hash && _data->get_name() == p_static_string.ptr) break; - _data=_data->next; + _data = _data->next; } - if (_data) { if (_data->refcount.ref()) { // exists lock->unlock(); return; } else { - } } - _data = memnew( _Data ); + _data = memnew(_Data); _data->refcount.init(); - _data->hash=hash; - _data->idx=idx; - _data->cname=p_static_string.ptr; - _data->next=_table[idx]; - _data->prev=NULL; + _data->hash = hash; + _data->idx = idx; + _data->cname = p_static_string.ptr; + _data->next = _table[idx]; + _data->prev = NULL; if (_table[idx]) - _table[idx]->prev=_data; - _table[idx]=_data; - + _table[idx]->prev = _data; + _table[idx] = _data; lock->unlock(); - - } +StringName::StringName(const String &p_name) { -StringName::StringName(const String& p_name) { - - _data=NULL; + _data = NULL; ERR_FAIL_COND(!configured); - if (p_name==String()) + if (p_name == String()) return; lock->lock(); uint32_t hash = p_name.hash(); - uint32_t idx=hash&STRING_TABLE_MASK; + uint32_t idx = hash & STRING_TABLE_MASK; - _data=_table[idx]; + _data = _table[idx]; - while(_data) { + while (_data) { - if (_data->hash==hash && _data->get_name()==p_name) + if (_data->hash == hash && _data->get_name() == p_name) break; - _data=_data->next; + _data = _data->next; } - if (_data) { if (_data->refcount.ref()) { // exists lock->unlock(); return; } else { - - } } - - _data = memnew( _Data ); - _data->name=p_name; + _data = memnew(_Data); + _data->name = p_name; _data->refcount.init(); - _data->hash=hash; - _data->idx=idx; - _data->cname=NULL; - _data->next=_table[idx]; - _data->prev=NULL; + _data->hash = hash; + _data->idx = idx; + _data->cname = NULL; + _data->next = _table[idx]; + _data->prev = NULL; if (_table[idx]) - _table[idx]->prev=_data; - _table[idx]=_data; + _table[idx]->prev = _data; + _table[idx] = _data; lock->unlock(); - } StringName StringName::search(const char *p_name) { - ERR_FAIL_COND_V(!configured,StringName()); + ERR_FAIL_COND_V(!configured, StringName()); - ERR_FAIL_COND_V( !p_name, StringName() ); + ERR_FAIL_COND_V(!p_name, StringName()); if (!p_name[0]) return StringName(); @@ -356,36 +338,33 @@ StringName StringName::search(const char *p_name) { uint32_t hash = String::hash(p_name); - uint32_t idx=hash&STRING_TABLE_MASK; + uint32_t idx = hash & STRING_TABLE_MASK; - _Data *_data=_table[idx]; + _Data *_data = _table[idx]; - while(_data) { + while (_data) { // compare hash first - if (_data->hash==hash && _data->get_name()==p_name) + if (_data->hash == hash && _data->get_name() == p_name) break; - _data=_data->next; + _data = _data->next; } if (_data && _data->refcount.ref()) { lock->unlock(); return StringName(_data); - } lock->unlock(); return StringName(); //does not exist - - } StringName StringName::search(const CharType *p_name) { - ERR_FAIL_COND_V(!configured,StringName()); + ERR_FAIL_COND_V(!configured, StringName()); - ERR_FAIL_COND_V( !p_name, StringName() ); + ERR_FAIL_COND_V(!p_name, StringName()); if (!p_name[0]) return StringName(); @@ -393,67 +372,61 @@ StringName StringName::search(const CharType *p_name) { uint32_t hash = String::hash(p_name); - uint32_t idx=hash&STRING_TABLE_MASK; + uint32_t idx = hash & STRING_TABLE_MASK; - _Data *_data=_table[idx]; + _Data *_data = _table[idx]; - while(_data) { + while (_data) { // compare hash first - if (_data->hash==hash && _data->get_name()==p_name) + if (_data->hash == hash && _data->get_name() == p_name) break; - _data=_data->next; + _data = _data->next; } if (_data && _data->refcount.ref()) { lock->unlock(); return StringName(_data); - } lock->unlock(); return StringName(); //does not exist - } StringName StringName::search(const String &p_name) { - ERR_FAIL_COND_V( p_name=="", StringName() ); + ERR_FAIL_COND_V(p_name == "", StringName()); lock->lock(); uint32_t hash = p_name.hash(); - uint32_t idx=hash&STRING_TABLE_MASK; + uint32_t idx = hash & STRING_TABLE_MASK; - _Data *_data=_table[idx]; + _Data *_data = _table[idx]; - while(_data) { + while (_data) { // compare hash first - if (_data->hash==hash && p_name==_data->get_name()) + if (_data->hash == hash && p_name == _data->get_name()) break; - _data=_data->next; + _data = _data->next; } if (_data && _data->refcount.ref()) { lock->unlock(); return StringName(_data); - } lock->unlock(); return StringName(); //does not exist - } - StringName::StringName() { - _data=NULL; + _data = NULL; } StringName::~StringName() { unref(); } - diff --git a/core/string_db.h b/core/string_db.h index 2c5262adaa..b8f8d6f3dc 100644 --- a/core/string_db.h +++ b/core/string_db.h @@ -30,9 +30,9 @@ #define STRING_DB_H #include "hash_map.h" -#include "ustring.h" -#include "safe_refcount.h" #include "os/mutex.h" +#include "safe_refcount.h" +#include "ustring.h" /** @author Juan Linietsky <reduzio@gmail.com> */ @@ -43,32 +43,32 @@ struct StaticCString { static StaticCString create(const char *p_ptr); }; - - class StringName { - enum { - STRING_TABLE_BITS=12, - STRING_TABLE_LEN=1<<STRING_TABLE_BITS, - STRING_TABLE_MASK=STRING_TABLE_LEN-1 + STRING_TABLE_BITS = 12, + STRING_TABLE_LEN = 1 << STRING_TABLE_BITS, + STRING_TABLE_MASK = STRING_TABLE_LEN - 1 }; struct _Data { SafeRefCount refcount; - const char* cname; + const char *cname; String name; - String get_name() const { return cname?String(cname):name; } + String get_name() const { return cname ? String(cname) : name; } int idx; uint32_t hash; _Data *prev; _Data *next; - _Data() { cname=NULL; next=prev=NULL; hash=0; } + _Data() { + cname = NULL; + next = prev = NULL; + hash = 0; + } }; - static _Data *_table[STRING_TABLE_LEN]; _Data *_data; @@ -80,31 +80,30 @@ class StringName { }; void unref(); -friend void register_core_types(); -friend void unregister_core_types(); + friend void register_core_types(); + friend void unregister_core_types(); static Mutex *lock; static void setup(); static void cleanup(); static bool configured; - StringName(_Data *p_data) { _data=p_data; } -public: - + StringName(_Data *p_data) { _data = p_data; } - operator const void*() const { return (_data && (_data->cname || !_data->name.empty()))?(void*)1:0; } +public: + operator const void *() const { return (_data && (_data->cname || !_data->name.empty())) ? (void *)1 : 0; } - bool operator==(const String& p_name) const; - bool operator==(const char* p_name) const; - bool operator!=(const String& p_name) const; - _FORCE_INLINE_ bool operator<(const StringName& p_name) const { + bool operator==(const String &p_name) const; + bool operator==(const char *p_name) const; + bool operator!=(const String &p_name) const; + _FORCE_INLINE_ bool operator<(const StringName &p_name) const { - return _data<p_name._data; + return _data < p_name._data; } - _FORCE_INLINE_ bool operator==(const StringName& p_name) const { + _FORCE_INLINE_ bool operator==(const StringName &p_name) const { // the real magic of all this mess happens here. // this is why path comparisons are very fast - return _data==p_name._data; + return _data == p_name._data; } _FORCE_INLINE_ uint32_t hash() const { @@ -113,12 +112,12 @@ public: else return 0; } - bool operator!=(const StringName& p_name) const; + bool operator!=(const StringName &p_name) const; _FORCE_INLINE_ operator String() const { if (_data) { - if (_data->cname ) + if (_data->cname) return String(_data->cname); else return _data->name; @@ -133,17 +132,17 @@ public: struct AlphCompare { - _FORCE_INLINE_ bool operator()(const StringName& l,const StringName& r) const { + _FORCE_INLINE_ bool operator()(const StringName &l, const StringName &r) const { return l.operator String() < r.operator String(); } }; - void operator=(const StringName& p_name); + void operator=(const StringName &p_name); StringName(const char *p_name); - StringName(const StringName& p_name); - StringName(const String& p_name); - StringName(const StaticCString& p_static_string); + StringName(const StringName &p_name); + StringName(const String &p_name); + StringName(const StaticCString &p_static_string); StringName(); ~StringName(); }; diff --git a/core/translation.cpp b/core/translation.cpp index d9d4fe7784..013f46f54f 100644 --- a/core/translation.cpp +++ b/core/translation.cpp @@ -32,746 +32,745 @@ #include "io/resource_loader.h" #include "os/os.h" -static const char* locale_list[]={ -"aa", // Afar -"aa_DJ", // Afar (Djibouti) -"aa_ER", // Afar (Eritrea) -"aa_ET", // Afar (Ethiopia) -"af", // Afrikaans -"af_ZA", // Afrikaans (South Africa) -"agr_PE", // Aguaruna (Peru) -"ak_GH", // Akan (Ghana) -"am_ET", // Amharic (Ethiopia) -"an_ES", // Aragonese (Spain) -"anp_IN", // Angika (India) -"ar", // Arabic -"ar_AE", // Arabic (United Arab Emirates) -"ar_BH", // Arabic (Bahrain) -"ar_DZ", // Arabic (Algeria) -"ar_EG", // Arabic (Egypt) -"ar_IN", // Arabic (India) -"ar_IQ", // Arabic (Iraq) -"ar_JO", // Arabic (Jordan) -"ar_KW", // Arabic (Kuwait) -"ar_LB", // Arabic (Lebanon) -"ar_LY", // Arabic (Libya) -"ar_MA", // Arabic (Morocco) -"ar_OM", // Arabic (Oman) -"ar_QA", // Arabic (Qatar) -"ar_SA", // Arabic (Saudi Arabia) -"ar_SD", // Arabic (Sudan) -"ar_SS", // Arabic (South Soudan) -"ar_SY", // Arabic (Syria) -"ar_TN", // Arabic (Tunisia) -"ar_YE", // Arabic (Yemen) -"as_IN", // Assamese (India) -"ast_ES", // Asturian (Spain) -"ayc_PE", // Southern Aymara (Peru) -"ay_PE", // Aymara (Peru) -"az_AZ", // Azerbaijani (Azerbaijan) -"be", // Belarusian -"be_BY", // Belarusian (Belarus) -"bem_ZM", // Bemba (Zambia) -"ber_DZ", // Berber languages (Algeria) -"ber_MA", // Berber languages (Morocco) -"bg", // Bulgarian -"bg_BG", // Bulgarian (Bulgaria) -"bhb_IN", // Bhili (India) -"bho_IN", // Bhojpuri (India) -"bi_TV", // Bislama (Tuvalu) -"bn", // Bengali -"bn_BD", // Bengali (Bangladesh) -"bn_IN", // Bengali (India) -"bo", // Tibetan -"bo_CN", // Tibetan (China) -"bo_IN", // Tibetan (India) -"br_FR", // Breton (France) -"brx_IN", // Bodo (India) -"bs_BA", // Bosnian (Bosnia and Herzegovina) -"byn_ER", // Bilin (Eritrea) -"ca", // Catalan -"ca_AD", // Catalan (Andorra) -"ca_ES", // Catalan (Spain) -"ca_FR", // Catalan (France) -"ca_IT", // Catalan (Italy) -"ce_RU", // Chechen (Russia) -"chr_US", // Cherokee (United States) -"cmn_TW", // Mandarin Chinese (Taiwan) -"crh_UA", // Crimean Tatar (Ukraine) -"csb_PL", // Kashubian (Poland) -"cs", // Czech -"cs_CZ", // Czech (Czech Republic) -"cv_RU", // Chuvash (Russia) -"cy_GB", // Welsh (United Kingdom) -"da", // Danish -"da_DK", // Danish (Denmark) -"de", // German -"de_AT", // German (Austria) -"de_BE", // German (Belgium) -"de_CH", // German (Switzerland) -"de_DE", // German (Germany) -"de_IT", // German (Italy) -"de_LU", // German (Luxembourg) -"doi_IN", // Dogri (India) -"dv_MV", // Dhivehi (Maldives) -"dz_BT", // Dzongkha (Bhutan) -"el", // Greek -"el_CY", // Greek (Cyprus) -"el_GR", // Greek (Greece) -"en", // English -"en_AG", // English (Antigua and Barbuda) -"en_AU", // English (Australia) -"en_BW", // English (Botswana) -"en_CA", // English (Canada) -"en_DK", // English (Denmark) -"en_GB", // English (United Kingdom) -"en_HK", // English (Hong Kong) -"en_IE", // English (Ireland) -"en_IL", // English (Israel) -"en_IN", // English (India) -"en_NG", // English (Nigeria) -"en_NZ", // English (New Zealand) -"en_PH", // English (Philippines) -"en_SG", // English (Singapore) -"en_US", // English (United States) -"en_ZA", // English (South Africa) -"en_ZM", // English (Zambia) -"en_ZW", // English (Zimbabwe) -"eo", // Esperanto -"es", // Spanish -"es_AR", // Spanish (Argentina) -"es_BO", // Spanish (Bolivia) -"es_CL", // Spanish (Chile) -"es_CO", // Spanish (Colombia) -"es_CR", // Spanish (Costa Rica) -"es_CU", // Spanish (Cuba) -"es_DO", // Spanish (Dominican Republic) -"es_EC", // Spanish (Ecuador) -"es_ES", // Spanish (Spain) -"es_GT", // Spanish (Guatemala) -"es_HN", // Spanish (Honduras) -"es_MX", // Spanish (Mexico) -"es_NI", // Spanish (Nicaragua) -"es_PA", // Spanish (Panama) -"es_PE", // Spanish (Peru) -"es_PR", // Spanish (Puerto Rico) -"es_PY", // Spanish (Paraguay) -"es_SV", // Spanish (El Salvador) -"es_US", // Spanish (United States) -"es_UY", // Spanish (Uruguay) -"es_VE", // Spanish (Venezuela) -"et", // Estonian -"et_EE", // Estonian (Estonia) -"eu", // Basque -"eu_ES", // Basque (Spain) -"fa", // Persian -"fa_IR", // Persian (Iran) -"ff_SN", // Fulah (Senegal) -"fi", // Finnish -"fi_FI", // Finnish (Finland) -"fil_PH", // Filipino (Philippines) -"fo_FO", // Faroese (Faroe Islands) -"fr", // French -"fr_BE", // French (Belgium) -"fr_CA", // French (Canada) -"fr_CH", // French (Switzerland) -"fr_FR", // French (France) -"fr_LU", // French (Luxembourg) -"fur_IT", // Friulian (Italy) -"fy_DE", // Western Frisian (Germany) -"fy_NL", // Western Frisian (Netherlands) -"ga", // Irish -"ga_IE", // Irish (Ireland) -"gd_GB", // Scottish Gaelic (United Kingdom) -"gez_ER", // Geez (Eritrea) -"gez_ET", // Geez (Ethiopia) -"gl_ES", // Galician (Spain) -"gu_IN", // Gujarati (India) -"gv_GB", // Manx (United Kingdom) -"hak_TW", // Hakka Chinese (Taiwan) -"ha_NG", // Hausa (Nigeria) -"he", // Hebrew -"he_IL", // Hebrew (Israel) -"hi", // Hindi -"hi_IN", // Hindi (India) -"hne_IN", // Chhattisgarhi (India) -"hr", // Croatian -"hr_HR", // Croatian (Croatia) -"hsb_DE", // Upper Sorbian (Germany) -"ht_HT", // Haitian (Haiti) -"hu", // Hungarian -"hu_HU", // Hungarian (Hungary) -"hus_MX", // Huastec (Mexico) -"hy_AM", // Armenian (Armenia) -"ia_FR", // Interlingua (France) -"id", // Indonesian -"id_ID", // Indonesian (Indonesia) -"ig_NG", // Igbo (Nigeria) -"ik_CA", // Inupiaq (Canada) -"is", // Icelandic -"is_IS", // Icelandic (Iceland) -"it", // Italian -"it_CH", // Italian (Switzerland) -"it_IT", // Italian (Italy) -"iu_CA", // Inuktitut (Canada) -"ja", // Japanese -"ja_JP", // Japanese (Japan) -"kab_DZ", // Kabyle (Algeria) -"ka_GE", // Georgian (Georgia) -"kk_KZ", // Kazakh (Kazakhstan) -"kl_GL", // Kalaallisut (Greenland) -"km_KH", // Central Khmer (Cambodia) -"kn_IN", // Kannada (India) -"kok_IN", // Konkani (India) -"ko", // Korean -"ko_KR", // Korean (South Korea) -"ks_IN", // Kashmiri (India) -"ku", // Kurdish -"ku_TR", // Kurdish (Turkey) -"kw_GB", // Cornish (United Kingdom) -"ky_KG", // Kirghiz (Kyrgyzstan) -"lb_LU", // Luxembourgish (Luxembourg) -"lg_UG", // Ganda (Uganda) -"li_BE", // Limburgan (Belgium) -"li_NL", // Limburgan (Netherlands) -"lij_IT", // Ligurian (Italy) -"ln_CD", // Lingala (Congo) -"lo_LA", // Lao (Laos) -"lt", // Lithuanian -"lt_LT", // Lithuanian (Lithuania) -"lv", // Latvian -"lv_LV", // Latvian (Latvia) -"lzh_TW", // Literary Chinese (Taiwan) -"mag_IN", // Magahi (India) -"mai_IN", // Maithili (India) -"mg_MG", // Malagasy (Madagascar) -"mh_MH", // Marshallese (Marshall Islands) -"mhr_RU", // Eastern Mari (Russia) -"mi_NZ", // Maori (New Zealand) -"miq_NI", // MÃskito (Nicaragua) -"mk", // Macedonian -"mk_MK", // Macedonian (Macedonia) -"ml_IN", // Malayalam (India) -"mni_IN", // Manipuri (India) -"mn_MN", // Mongolian (Mongolia) -"mr_IN", // Marathi (India) -"ms", // Malay -"ms_MY", // Malay (Malaysia) -"mt", // Maltese -"mt_MT", // Maltese (Malta) -"my_MM", // Burmese (Myanmar) -"myv_RU", // Erzya (Russia) -"nah_MX", // Nahuatl languages (Mexico) -"nan_TW", // Min Nan Chinese (Taiwan) -"nb", // Norwegian BokmÃ¥l -"nb_NO", // Norwegian BokmÃ¥l (Norway) -"nds_DE", // Low German (Germany) -"nds_NL", // Low German (Netherlands) -"ne_NP", // Nepali (Nepal) -"nhn_MX", // Central Nahuatl (Mexico) -"niu_NU", // Niuean (Niue) -"niu_NZ", // Niuean (New Zealand) -"nl", // Dutch -"nl_AW", // Dutch (Aruba) -"nl_BE", // Dutch (Belgium) -"nl_NL", // Dutch (Netherlands) -"nn", // Norwegian Nynorsk -"nn_NO", // Norwegian Nynorsk (Norway) -"nr_ZA", // South Ndebele (South Africa) -"nso_ZA", // Pedi (South Africa) -"oc_FR", // Occitan (France) -"om", // Oromo -"om_ET", // Oromo (Ethiopia) -"om_KE", // Oromo (Kenya) -"or_IN", // Oriya (India) -"os_RU", // Ossetian (Russia) -"pa_IN", // Panjabi (India) -"pap", // Papiamento -"pap_AN", // Papiamento (Netherlands Antilles) -"pap_AW", // Papiamento (Aruba) -"pap_CW", // Papiamento (Curaçao) -"pa_PK", // Panjabi (Pakistan) -"pl", // Polish -"pl_PL", // Polish (Poland) -"pr", // Pirate -"ps_AF", // Pushto (Afghanistan) -"pt", // Portuguese -"pt_BR", // Portuguese (Brazil) -"pt_PT", // Portuguese (Portugal) -"quy_PE", // Ayacucho Quechua (Peru) -"quz_PE", // Cusco Quechua (Peru) -"raj_IN", // Rajasthani (India) -"ro", // Romanian -"ro_RO", // Romanian (Romania) -"ru", // Russian -"ru_RU", // Russian (Russia) -"ru_UA", // Russian (Ukraine) -"rw_RW", // Kinyarwanda (Rwanda) -"sa_IN", // Sanskrit (India) -"sat_IN", // Santali (India) -"sc_IT", // Sardinian (Italy) -"sco", // Scots -"sd_IN", // Sindhi (India) -"se_NO", // Northern Sami (Norway) -"sgs_LT", // Samogitian (Lithuania) -"shs_CA", // Shuswap (Canada) -"sid_ET", // Sidamo (Ethiopia) -"si_LK", // Sinhala (Sri Lanka) -"sk", // Slovak -"sk_SK", // Slovak (Slovakia) -"sl", // Slovenian -"sl_SI", // Slovenian (Slovenia) -"so", // Somali -"so_DJ", // Somali (Djibouti) -"so_ET", // Somali (Ethiopia) -"so_KE", // Somali (Kenya) -"so_SO", // Somali (Somalia) -"son_ML", // Songhai languages (Mali) -"sq", // Albanian -"sq_AL", // Albanian (Albania) -"sq_KV", // Albanian (Kosovo) -"sq_MK", // Albanian (Macedonia) -"sr", // Serbian -"sr_ME", // Serbian (Montenegro) -"sr_RS", // Serbian (Serbia) -"ss_ZA", // Swati (South Africa) -"st_ZA", // Southern Sotho (South Africa) -"sv", // Swedish -"sv_FI", // Swedish (Finland) -"sv_SE", // Swedish (Sweden) -"sw_KE", // Swahili (Kenya) -"sw_TZ", // Swahili (Tanzania) -"szl_PL", // Silesian (Poland) -"ta", // Tamil -"ta_IN", // Tamil (India) -"ta_LK", // Tamil (Sri Lanka) -"tcy_IN", // Tulu (India) -"te_IN", // Telugu (India) -"tg_TJ", // Tajik (Tajikistan) -"the_NP", // Chitwania Tharu (Nepal) -"th", // Thai -"th_TH", // Thai (Thailand) -"ti", // Tigrinya -"ti_ER", // Tigrinya (Eritrea) -"ti_ET", // Tigrinya (Ethiopia) -"tig_ER", // Tigre (Eritrea) -"tk_TM", // Turkmen (Turkmenistan) -"tl_PH", // Tagalog (Philippines) -"tn_ZA", // Tswana (South Africa) -"tr", // Turkish -"tr_CY", // Turkish (Cyprus) -"tr_TR", // Turkish (Turkey) -"ts_ZA", // Tsonga (South Africa) -"tt_RU", // Tatar (Russia) -"ug_CN", // Uighur (China) -"uk", // Ukrainian -"uk_UA", // Ukrainian (Ukraine) -"unm_US", // Unami (United States) -"ur", // Urdu -"ur_IN", // Urdu (India) -"ur_PK", // Urdu (Pakistan) -"uz", // Uzbek -"uz_UZ", // Uzbek (Uzbekistan) -"ve_ZA", // Venda (South Africa) -"vi", // Vietnamese -"vi_VN", // Vietnamese (Vietnam) -"wa_BE", // Walloon (Belgium) -"wae_CH", // Walser (Switzerland) -"wal_ET", // Wolaytta (Ethiopia) -"wo_SN", // Wolof (Senegal) -"xh_ZA", // Xhosa (South Africa) -"yi_US", // Yiddish (United States) -"yo_NG", // Yoruba (Nigeria) -"yue_HK", // Yue Chinese (Hong Kong) -"zh", // Chinese -"zh_CN", // Chinese (China) -"zh_HK", // Chinese (Hong Kong) -"zh_SG", // Chinese (Singapore) -"zh_TW", // Chinese (Taiwan) -"zu_ZA", // Zulu (South Africa) -0 +static const char *locale_list[] = { + "aa", // Afar + "aa_DJ", // Afar (Djibouti) + "aa_ER", // Afar (Eritrea) + "aa_ET", // Afar (Ethiopia) + "af", // Afrikaans + "af_ZA", // Afrikaans (South Africa) + "agr_PE", // Aguaruna (Peru) + "ak_GH", // Akan (Ghana) + "am_ET", // Amharic (Ethiopia) + "an_ES", // Aragonese (Spain) + "anp_IN", // Angika (India) + "ar", // Arabic + "ar_AE", // Arabic (United Arab Emirates) + "ar_BH", // Arabic (Bahrain) + "ar_DZ", // Arabic (Algeria) + "ar_EG", // Arabic (Egypt) + "ar_IN", // Arabic (India) + "ar_IQ", // Arabic (Iraq) + "ar_JO", // Arabic (Jordan) + "ar_KW", // Arabic (Kuwait) + "ar_LB", // Arabic (Lebanon) + "ar_LY", // Arabic (Libya) + "ar_MA", // Arabic (Morocco) + "ar_OM", // Arabic (Oman) + "ar_QA", // Arabic (Qatar) + "ar_SA", // Arabic (Saudi Arabia) + "ar_SD", // Arabic (Sudan) + "ar_SS", // Arabic (South Soudan) + "ar_SY", // Arabic (Syria) + "ar_TN", // Arabic (Tunisia) + "ar_YE", // Arabic (Yemen) + "as_IN", // Assamese (India) + "ast_ES", // Asturian (Spain) + "ayc_PE", // Southern Aymara (Peru) + "ay_PE", // Aymara (Peru) + "az_AZ", // Azerbaijani (Azerbaijan) + "be", // Belarusian + "be_BY", // Belarusian (Belarus) + "bem_ZM", // Bemba (Zambia) + "ber_DZ", // Berber languages (Algeria) + "ber_MA", // Berber languages (Morocco) + "bg", // Bulgarian + "bg_BG", // Bulgarian (Bulgaria) + "bhb_IN", // Bhili (India) + "bho_IN", // Bhojpuri (India) + "bi_TV", // Bislama (Tuvalu) + "bn", // Bengali + "bn_BD", // Bengali (Bangladesh) + "bn_IN", // Bengali (India) + "bo", // Tibetan + "bo_CN", // Tibetan (China) + "bo_IN", // Tibetan (India) + "br_FR", // Breton (France) + "brx_IN", // Bodo (India) + "bs_BA", // Bosnian (Bosnia and Herzegovina) + "byn_ER", // Bilin (Eritrea) + "ca", // Catalan + "ca_AD", // Catalan (Andorra) + "ca_ES", // Catalan (Spain) + "ca_FR", // Catalan (France) + "ca_IT", // Catalan (Italy) + "ce_RU", // Chechen (Russia) + "chr_US", // Cherokee (United States) + "cmn_TW", // Mandarin Chinese (Taiwan) + "crh_UA", // Crimean Tatar (Ukraine) + "csb_PL", // Kashubian (Poland) + "cs", // Czech + "cs_CZ", // Czech (Czech Republic) + "cv_RU", // Chuvash (Russia) + "cy_GB", // Welsh (United Kingdom) + "da", // Danish + "da_DK", // Danish (Denmark) + "de", // German + "de_AT", // German (Austria) + "de_BE", // German (Belgium) + "de_CH", // German (Switzerland) + "de_DE", // German (Germany) + "de_IT", // German (Italy) + "de_LU", // German (Luxembourg) + "doi_IN", // Dogri (India) + "dv_MV", // Dhivehi (Maldives) + "dz_BT", // Dzongkha (Bhutan) + "el", // Greek + "el_CY", // Greek (Cyprus) + "el_GR", // Greek (Greece) + "en", // English + "en_AG", // English (Antigua and Barbuda) + "en_AU", // English (Australia) + "en_BW", // English (Botswana) + "en_CA", // English (Canada) + "en_DK", // English (Denmark) + "en_GB", // English (United Kingdom) + "en_HK", // English (Hong Kong) + "en_IE", // English (Ireland) + "en_IL", // English (Israel) + "en_IN", // English (India) + "en_NG", // English (Nigeria) + "en_NZ", // English (New Zealand) + "en_PH", // English (Philippines) + "en_SG", // English (Singapore) + "en_US", // English (United States) + "en_ZA", // English (South Africa) + "en_ZM", // English (Zambia) + "en_ZW", // English (Zimbabwe) + "eo", // Esperanto + "es", // Spanish + "es_AR", // Spanish (Argentina) + "es_BO", // Spanish (Bolivia) + "es_CL", // Spanish (Chile) + "es_CO", // Spanish (Colombia) + "es_CR", // Spanish (Costa Rica) + "es_CU", // Spanish (Cuba) + "es_DO", // Spanish (Dominican Republic) + "es_EC", // Spanish (Ecuador) + "es_ES", // Spanish (Spain) + "es_GT", // Spanish (Guatemala) + "es_HN", // Spanish (Honduras) + "es_MX", // Spanish (Mexico) + "es_NI", // Spanish (Nicaragua) + "es_PA", // Spanish (Panama) + "es_PE", // Spanish (Peru) + "es_PR", // Spanish (Puerto Rico) + "es_PY", // Spanish (Paraguay) + "es_SV", // Spanish (El Salvador) + "es_US", // Spanish (United States) + "es_UY", // Spanish (Uruguay) + "es_VE", // Spanish (Venezuela) + "et", // Estonian + "et_EE", // Estonian (Estonia) + "eu", // Basque + "eu_ES", // Basque (Spain) + "fa", // Persian + "fa_IR", // Persian (Iran) + "ff_SN", // Fulah (Senegal) + "fi", // Finnish + "fi_FI", // Finnish (Finland) + "fil_PH", // Filipino (Philippines) + "fo_FO", // Faroese (Faroe Islands) + "fr", // French + "fr_BE", // French (Belgium) + "fr_CA", // French (Canada) + "fr_CH", // French (Switzerland) + "fr_FR", // French (France) + "fr_LU", // French (Luxembourg) + "fur_IT", // Friulian (Italy) + "fy_DE", // Western Frisian (Germany) + "fy_NL", // Western Frisian (Netherlands) + "ga", // Irish + "ga_IE", // Irish (Ireland) + "gd_GB", // Scottish Gaelic (United Kingdom) + "gez_ER", // Geez (Eritrea) + "gez_ET", // Geez (Ethiopia) + "gl_ES", // Galician (Spain) + "gu_IN", // Gujarati (India) + "gv_GB", // Manx (United Kingdom) + "hak_TW", // Hakka Chinese (Taiwan) + "ha_NG", // Hausa (Nigeria) + "he", // Hebrew + "he_IL", // Hebrew (Israel) + "hi", // Hindi + "hi_IN", // Hindi (India) + "hne_IN", // Chhattisgarhi (India) + "hr", // Croatian + "hr_HR", // Croatian (Croatia) + "hsb_DE", // Upper Sorbian (Germany) + "ht_HT", // Haitian (Haiti) + "hu", // Hungarian + "hu_HU", // Hungarian (Hungary) + "hus_MX", // Huastec (Mexico) + "hy_AM", // Armenian (Armenia) + "ia_FR", // Interlingua (France) + "id", // Indonesian + "id_ID", // Indonesian (Indonesia) + "ig_NG", // Igbo (Nigeria) + "ik_CA", // Inupiaq (Canada) + "is", // Icelandic + "is_IS", // Icelandic (Iceland) + "it", // Italian + "it_CH", // Italian (Switzerland) + "it_IT", // Italian (Italy) + "iu_CA", // Inuktitut (Canada) + "ja", // Japanese + "ja_JP", // Japanese (Japan) + "kab_DZ", // Kabyle (Algeria) + "ka_GE", // Georgian (Georgia) + "kk_KZ", // Kazakh (Kazakhstan) + "kl_GL", // Kalaallisut (Greenland) + "km_KH", // Central Khmer (Cambodia) + "kn_IN", // Kannada (India) + "kok_IN", // Konkani (India) + "ko", // Korean + "ko_KR", // Korean (South Korea) + "ks_IN", // Kashmiri (India) + "ku", // Kurdish + "ku_TR", // Kurdish (Turkey) + "kw_GB", // Cornish (United Kingdom) + "ky_KG", // Kirghiz (Kyrgyzstan) + "lb_LU", // Luxembourgish (Luxembourg) + "lg_UG", // Ganda (Uganda) + "li_BE", // Limburgan (Belgium) + "li_NL", // Limburgan (Netherlands) + "lij_IT", // Ligurian (Italy) + "ln_CD", // Lingala (Congo) + "lo_LA", // Lao (Laos) + "lt", // Lithuanian + "lt_LT", // Lithuanian (Lithuania) + "lv", // Latvian + "lv_LV", // Latvian (Latvia) + "lzh_TW", // Literary Chinese (Taiwan) + "mag_IN", // Magahi (India) + "mai_IN", // Maithili (India) + "mg_MG", // Malagasy (Madagascar) + "mh_MH", // Marshallese (Marshall Islands) + "mhr_RU", // Eastern Mari (Russia) + "mi_NZ", // Maori (New Zealand) + "miq_NI", // MÃskito (Nicaragua) + "mk", // Macedonian + "mk_MK", // Macedonian (Macedonia) + "ml_IN", // Malayalam (India) + "mni_IN", // Manipuri (India) + "mn_MN", // Mongolian (Mongolia) + "mr_IN", // Marathi (India) + "ms", // Malay + "ms_MY", // Malay (Malaysia) + "mt", // Maltese + "mt_MT", // Maltese (Malta) + "my_MM", // Burmese (Myanmar) + "myv_RU", // Erzya (Russia) + "nah_MX", // Nahuatl languages (Mexico) + "nan_TW", // Min Nan Chinese (Taiwan) + "nb", // Norwegian BokmÃ¥l + "nb_NO", // Norwegian BokmÃ¥l (Norway) + "nds_DE", // Low German (Germany) + "nds_NL", // Low German (Netherlands) + "ne_NP", // Nepali (Nepal) + "nhn_MX", // Central Nahuatl (Mexico) + "niu_NU", // Niuean (Niue) + "niu_NZ", // Niuean (New Zealand) + "nl", // Dutch + "nl_AW", // Dutch (Aruba) + "nl_BE", // Dutch (Belgium) + "nl_NL", // Dutch (Netherlands) + "nn", // Norwegian Nynorsk + "nn_NO", // Norwegian Nynorsk (Norway) + "nr_ZA", // South Ndebele (South Africa) + "nso_ZA", // Pedi (South Africa) + "oc_FR", // Occitan (France) + "om", // Oromo + "om_ET", // Oromo (Ethiopia) + "om_KE", // Oromo (Kenya) + "or_IN", // Oriya (India) + "os_RU", // Ossetian (Russia) + "pa_IN", // Panjabi (India) + "pap", // Papiamento + "pap_AN", // Papiamento (Netherlands Antilles) + "pap_AW", // Papiamento (Aruba) + "pap_CW", // Papiamento (Curaçao) + "pa_PK", // Panjabi (Pakistan) + "pl", // Polish + "pl_PL", // Polish (Poland) + "pr", // Pirate + "ps_AF", // Pushto (Afghanistan) + "pt", // Portuguese + "pt_BR", // Portuguese (Brazil) + "pt_PT", // Portuguese (Portugal) + "quy_PE", // Ayacucho Quechua (Peru) + "quz_PE", // Cusco Quechua (Peru) + "raj_IN", // Rajasthani (India) + "ro", // Romanian + "ro_RO", // Romanian (Romania) + "ru", // Russian + "ru_RU", // Russian (Russia) + "ru_UA", // Russian (Ukraine) + "rw_RW", // Kinyarwanda (Rwanda) + "sa_IN", // Sanskrit (India) + "sat_IN", // Santali (India) + "sc_IT", // Sardinian (Italy) + "sco", // Scots + "sd_IN", // Sindhi (India) + "se_NO", // Northern Sami (Norway) + "sgs_LT", // Samogitian (Lithuania) + "shs_CA", // Shuswap (Canada) + "sid_ET", // Sidamo (Ethiopia) + "si_LK", // Sinhala (Sri Lanka) + "sk", // Slovak + "sk_SK", // Slovak (Slovakia) + "sl", // Slovenian + "sl_SI", // Slovenian (Slovenia) + "so", // Somali + "so_DJ", // Somali (Djibouti) + "so_ET", // Somali (Ethiopia) + "so_KE", // Somali (Kenya) + "so_SO", // Somali (Somalia) + "son_ML", // Songhai languages (Mali) + "sq", // Albanian + "sq_AL", // Albanian (Albania) + "sq_KV", // Albanian (Kosovo) + "sq_MK", // Albanian (Macedonia) + "sr", // Serbian + "sr_ME", // Serbian (Montenegro) + "sr_RS", // Serbian (Serbia) + "ss_ZA", // Swati (South Africa) + "st_ZA", // Southern Sotho (South Africa) + "sv", // Swedish + "sv_FI", // Swedish (Finland) + "sv_SE", // Swedish (Sweden) + "sw_KE", // Swahili (Kenya) + "sw_TZ", // Swahili (Tanzania) + "szl_PL", // Silesian (Poland) + "ta", // Tamil + "ta_IN", // Tamil (India) + "ta_LK", // Tamil (Sri Lanka) + "tcy_IN", // Tulu (India) + "te_IN", // Telugu (India) + "tg_TJ", // Tajik (Tajikistan) + "the_NP", // Chitwania Tharu (Nepal) + "th", // Thai + "th_TH", // Thai (Thailand) + "ti", // Tigrinya + "ti_ER", // Tigrinya (Eritrea) + "ti_ET", // Tigrinya (Ethiopia) + "tig_ER", // Tigre (Eritrea) + "tk_TM", // Turkmen (Turkmenistan) + "tl_PH", // Tagalog (Philippines) + "tn_ZA", // Tswana (South Africa) + "tr", // Turkish + "tr_CY", // Turkish (Cyprus) + "tr_TR", // Turkish (Turkey) + "ts_ZA", // Tsonga (South Africa) + "tt_RU", // Tatar (Russia) + "ug_CN", // Uighur (China) + "uk", // Ukrainian + "uk_UA", // Ukrainian (Ukraine) + "unm_US", // Unami (United States) + "ur", // Urdu + "ur_IN", // Urdu (India) + "ur_PK", // Urdu (Pakistan) + "uz", // Uzbek + "uz_UZ", // Uzbek (Uzbekistan) + "ve_ZA", // Venda (South Africa) + "vi", // Vietnamese + "vi_VN", // Vietnamese (Vietnam) + "wa_BE", // Walloon (Belgium) + "wae_CH", // Walser (Switzerland) + "wal_ET", // Wolaytta (Ethiopia) + "wo_SN", // Wolof (Senegal) + "xh_ZA", // Xhosa (South Africa) + "yi_US", // Yiddish (United States) + "yo_NG", // Yoruba (Nigeria) + "yue_HK", // Yue Chinese (Hong Kong) + "zh", // Chinese + "zh_CN", // Chinese (China) + "zh_HK", // Chinese (Hong Kong) + "zh_SG", // Chinese (Singapore) + "zh_TW", // Chinese (Taiwan) + "zu_ZA", // Zulu (South Africa) + 0 }; -static const char* locale_names[]={ -"Afar", -"Afar (Djibouti)", -"Afar (Eritrea)", -"Afar (Ethiopia)", -"Afrikaans", -"Afrikaans (South Africa)", -"Aguaruna (Peru)", -"Akan (Ghana)", -"Amharic (Ethiopia)", -"Aragonese (Spain)", -"Angika (India)", -"Arabic", -"Arabic (United Arab Emirates)", -"Arabic (Bahrain)", -"Arabic (Algeria)", -"Arabic (Egypt)", -"Arabic (India)", -"Arabic (Iraq)", -"Arabic (Jordan)", -"Arabic (Kuwait)", -"Arabic (Lebanon)", -"Arabic (Libya)", -"Arabic (Morocco)", -"Arabic (Oman)", -"Arabic (Qatar)", -"Arabic (Saudi Arabia)", -"Arabic (Sudan)", -"Arabic (South Soudan)", -"Arabic (Syria)", -"Arabic (Tunisia)", -"Arabic (Yemen)", -"Assamese (India)", -"Asturian (Spain)", -"Southern Aymara (Peru)", -"Aymara (Peru)", -"Azerbaijani (Azerbaijan)", -"Belarusian", -"Belarusian (Belarus)", -"Bemba (Zambia)", -"Berber languages (Algeria)", -"Berber languages (Morocco)", -"Bulgarian", -"Bulgarian (Bulgaria)", -"Bhili (India)", -"Bhojpuri (India)", -"Bislama (Tuvalu)", -"Bengali", -"Bengali (Bangladesh)", -"Bengali (India)", -"Tibetan", -"Tibetan (China)", -"Tibetan (India)", -"Breton (France)", -"Bodo (India)", -"Bosnian (Bosnia and Herzegovina)", -"Bilin (Eritrea)", -"Catalan", -"Catalan (Andorra)", -"Catalan (Spain)", -"Catalan (France)", -"Catalan (Italy)", -"Chechen (Russia)", -"Cherokee (United States)", -"Mandarin Chinese (Taiwan)", -"Crimean Tatar (Ukraine)", -"Kashubian (Poland)", -"Czech", -"Czech (Czech Republic)", -"Chuvash (Russia)", -"Welsh (United Kingdom)", -"Danish", -"Danish (Denmark)", -"German", -"German (Austria)", -"German (Belgium)", -"German (Switzerland)", -"German (Germany)", -"German (Italy)", -"German (Luxembourg)", -"Dogri (India)", -"Dhivehi (Maldives)", -"Dzongkha (Bhutan)", -"Greek", -"Greek (Cyprus)", -"Greek (Greece)", -"English", -"English (Antigua and Barbuda)", -"English (Australia)", -"English (Botswana)", -"English (Canada)", -"English (Denmark)", -"English (United Kingdom)", -"English (Hong Kong)", -"English (Ireland)", -"English (Israel)", -"English (India)", -"English (Nigeria)", -"English (New Zealand)", -"English (Philippines)", -"English (Singapore)", -"English (United States)", -"English (South Africa)", -"English (Zambia)", -"English (Zimbabwe)", -"Esperanto", -"Spanish", -"Spanish (Argentina)", -"Spanish (Bolivia)", -"Spanish (Chile)", -"Spanish (Colombia)", -"Spanish (Costa Rica)", -"Spanish (Cuba)", -"Spanish (Dominican Republic)", -"Spanish (Ecuador)", -"Spanish (Spain)", -"Spanish (Guatemala)", -"Spanish (Honduras)", -"Spanish (Mexico)", -"Spanish (Nicaragua)", -"Spanish (Panama)", -"Spanish (Peru)", -"Spanish (Puerto Rico)", -"Spanish (Paraguay)", -"Spanish (El Salvador)", -"Spanish (United States)", -"Spanish (Uruguay)", -"Spanish (Venezuela)", -"Estonian", -"Estonian (Estonia)", -"Basque", -"Basque (Spain)", -"Persian", -"Persian (Iran)", -"Fulah (Senegal)", -"Finnish", -"Finnish (Finland)", -"Filipino (Philippines)", -"Faroese (Faroe Islands)", -"French", -"French (Belgium)", -"French (Canada)", -"French (Switzerland)", -"French (France)", -"French (Luxembourg)", -"Friulian (Italy)", -"Western Frisian (Germany)", -"Western Frisian (Netherlands)", -"Irish", -"Irish (Ireland)", -"Scottish Gaelic (United Kingdom)", -"Geez (Eritrea)", -"Geez (Ethiopia)", -"Galician (Spain)", -"Gujarati (India)", -"Manx (United Kingdom)", -"Hakka Chinese (Taiwan)", -"Hausa (Nigeria)", -"Hebrew", -"Hebrew (Israel)", -"Hindi", -"Hindi (India)", -"Chhattisgarhi (India)", -"Croatian", -"Croatian (Croatia)", -"Upper Sorbian (Germany)", -"Haitian (Haiti)", -"Hungarian", -"Hungarian (Hungary)", -"Huastec (Mexico)", -"Armenian (Armenia)", -"Interlingua (France)", -"Indonesian", -"Indonesian (Indonesia)", -"Igbo (Nigeria)", -"Inupiaq (Canada)", -"Icelandic", -"Icelandic (Iceland)", -"Italian", -"Italian (Switzerland)", -"Italian (Italy)", -"Inuktitut (Canada)", -"Japanese", -"Japanese (Japan)", -"Kabyle (Algeria)", -"Georgian (Georgia)", -"Kazakh (Kazakhstan)", -"Kalaallisut (Greenland)", -"Central Khmer (Cambodia)", -"Kannada (India)", -"Konkani (India)", -"Korean", -"Korean (South Korea)", -"Kashmiri (India)", -"Kurdish", -"Kurdish (Turkey)", -"Cornish (United Kingdom)", -"Kirghiz (Kyrgyzstan)", -"Luxembourgish (Luxembourg)", -"Ganda (Uganda)", -"Limburgan (Belgium)", -"Limburgan (Netherlands)", -"Ligurian (Italy)", -"Lingala (Congo)", -"Lao (Laos)", -"Lithuanian", -"Lithuanian (Lithuania)", -"Latvian", -"Latvian (Latvia)", -"Literary Chinese (Taiwan)", -"Magahi (India)", -"Maithili (India)", -"Malagasy (Madagascar)", -"Marshallese (Marshall Islands)", -"Eastern Mari (Russia)", -"Maori (New Zealand)", -"MÃskito (Nicaragua)", -"Macedonian", -"Macedonian (Macedonia)", -"Malayalam (India)", -"Manipuri (India)", -"Mongolian (Mongolia)", -"Marathi (India)", -"Malay", -"Malay (Malaysia)", -"Maltese", -"Maltese (Malta)", -"Burmese (Myanmar)", -"Erzya (Russia)", -"Nahuatl languages (Mexico)", -"Min Nan Chinese (Taiwan)", -"Norwegian BokmÃ¥l", -"Norwegian BokmÃ¥l (Norway)", -"Low German (Germany)", -"Low German (Netherlands)", -"Nepali (Nepal)", -"Central Nahuatl (Mexico)", -"Niuean (Niue)", -"Niuean (New Zealand)", -"Dutch", -"Dutch (Aruba)", -"Dutch (Belgium)", -"Dutch (Netherlands)", -"Norwegian Nynorsk", -"Norwegian Nynorsk (Norway)", -"South Ndebele (South Africa)", -"Pedi (South Africa)", -"Occitan (France)", -"Oromo", -"Oromo (Ethiopia)", -"Oromo (Kenya)", -"Oriya (India)", -"Ossetian (Russia)", -"Panjabi (India)", -"Papiamento", -"Papiamento (Netherlands Antilles)", -"Papiamento (Aruba)", -"Papiamento (Curaçao)", -"Panjabi (Pakistan)", -"Polish", -"Polish (Poland)", -"Pirate", -"Pushto (Afghanistan)", -"Portuguese", -"Portuguese (Brazil)", -"Portuguese (Portugal)", -"Ayacucho Quechua (Peru)", -"Cusco Quechua (Peru)", -"Rajasthani (India)", -"Romanian", -"Romanian (Romania)", -"Russian", -"Russian (Russia)", -"Russian (Ukraine)", -"Kinyarwanda (Rwanda)", -"Sanskrit (India)", -"Santali (India)", -"Sardinian (Italy)", -"Scots (Scotland)", -"Sindhi (India)", -"Northern Sami (Norway)", -"Samogitian (Lithuania)", -"Shuswap (Canada)", -"Sidamo (Ethiopia)", -"Sinhala (Sri Lanka)", -"Slovak", -"Slovak (Slovakia)", -"Slovenian", -"Slovenian (Slovenia)", -"Somali", -"Somali (Djibouti)", -"Somali (Ethiopia)", -"Somali (Kenya)", -"Somali (Somalia)", -"Songhai languages (Mali)", -"Albanian", -"Albanian (Albania)", -"Albanian (Kosovo)", -"Albanian (Macedonia)", -"Serbian", -"Serbian (Montenegro)", -"Serbian (Serbia)", -"Swati (South Africa)", -"Southern Sotho (South Africa)", -"Swedish", -"Swedish (Finland)", -"Swedish (Sweden)", -"Swahili (Kenya)", -"Swahili (Tanzania)", -"Silesian (Poland)", -"Tamil", -"Tamil (India)", -"Tamil (Sri Lanka)", -"Tulu (India)", -"Telugu (India)", -"Tajik (Tajikistan)", -"Chitwania Tharu (Nepal)", -"Thai", -"Thai (Thailand)", -"Tigrinya", -"Tigrinya (Eritrea)", -"Tigrinya (Ethiopia)", -"Tigre (Eritrea)", -"Turkmen (Turkmenistan)", -"Tagalog (Philippines)", -"Tswana (South Africa)", -"Turkish", -"Turkish (Cyprus)", -"Turkish (Turkey)", -"Tsonga (South Africa)", -"Tatar (Russia)", -"Uighur (China)", -"Ukrainian", -"Ukrainian (Ukraine)", -"Unami (United States)", -"Urdu", -"Urdu (India)", -"Urdu (Pakistan)", -"Uzbek", -"Uzbek (Uzbekistan)", -"Venda (South Africa)", -"Vietnamese", -"Vietnamese (Vietnam)", -"Walloon (Belgium)", -"Walser (Switzerland)", -"Wolaytta (Ethiopia)", -"Wolof (Senegal)", -"Xhosa (South Africa)", -"Yiddish (United States)", -"Yoruba (Nigeria)", -"Yue Chinese (Hong Kong)", -"Chinese", -"Chinese (China)", -"Chinese (Hong Kong)", -"Chinese (Singapore)", -"Chinese (Taiwan)", -"Zulu (South Africa)", -0 +static const char *locale_names[] = { + "Afar", + "Afar (Djibouti)", + "Afar (Eritrea)", + "Afar (Ethiopia)", + "Afrikaans", + "Afrikaans (South Africa)", + "Aguaruna (Peru)", + "Akan (Ghana)", + "Amharic (Ethiopia)", + "Aragonese (Spain)", + "Angika (India)", + "Arabic", + "Arabic (United Arab Emirates)", + "Arabic (Bahrain)", + "Arabic (Algeria)", + "Arabic (Egypt)", + "Arabic (India)", + "Arabic (Iraq)", + "Arabic (Jordan)", + "Arabic (Kuwait)", + "Arabic (Lebanon)", + "Arabic (Libya)", + "Arabic (Morocco)", + "Arabic (Oman)", + "Arabic (Qatar)", + "Arabic (Saudi Arabia)", + "Arabic (Sudan)", + "Arabic (South Soudan)", + "Arabic (Syria)", + "Arabic (Tunisia)", + "Arabic (Yemen)", + "Assamese (India)", + "Asturian (Spain)", + "Southern Aymara (Peru)", + "Aymara (Peru)", + "Azerbaijani (Azerbaijan)", + "Belarusian", + "Belarusian (Belarus)", + "Bemba (Zambia)", + "Berber languages (Algeria)", + "Berber languages (Morocco)", + "Bulgarian", + "Bulgarian (Bulgaria)", + "Bhili (India)", + "Bhojpuri (India)", + "Bislama (Tuvalu)", + "Bengali", + "Bengali (Bangladesh)", + "Bengali (India)", + "Tibetan", + "Tibetan (China)", + "Tibetan (India)", + "Breton (France)", + "Bodo (India)", + "Bosnian (Bosnia and Herzegovina)", + "Bilin (Eritrea)", + "Catalan", + "Catalan (Andorra)", + "Catalan (Spain)", + "Catalan (France)", + "Catalan (Italy)", + "Chechen (Russia)", + "Cherokee (United States)", + "Mandarin Chinese (Taiwan)", + "Crimean Tatar (Ukraine)", + "Kashubian (Poland)", + "Czech", + "Czech (Czech Republic)", + "Chuvash (Russia)", + "Welsh (United Kingdom)", + "Danish", + "Danish (Denmark)", + "German", + "German (Austria)", + "German (Belgium)", + "German (Switzerland)", + "German (Germany)", + "German (Italy)", + "German (Luxembourg)", + "Dogri (India)", + "Dhivehi (Maldives)", + "Dzongkha (Bhutan)", + "Greek", + "Greek (Cyprus)", + "Greek (Greece)", + "English", + "English (Antigua and Barbuda)", + "English (Australia)", + "English (Botswana)", + "English (Canada)", + "English (Denmark)", + "English (United Kingdom)", + "English (Hong Kong)", + "English (Ireland)", + "English (Israel)", + "English (India)", + "English (Nigeria)", + "English (New Zealand)", + "English (Philippines)", + "English (Singapore)", + "English (United States)", + "English (South Africa)", + "English (Zambia)", + "English (Zimbabwe)", + "Esperanto", + "Spanish", + "Spanish (Argentina)", + "Spanish (Bolivia)", + "Spanish (Chile)", + "Spanish (Colombia)", + "Spanish (Costa Rica)", + "Spanish (Cuba)", + "Spanish (Dominican Republic)", + "Spanish (Ecuador)", + "Spanish (Spain)", + "Spanish (Guatemala)", + "Spanish (Honduras)", + "Spanish (Mexico)", + "Spanish (Nicaragua)", + "Spanish (Panama)", + "Spanish (Peru)", + "Spanish (Puerto Rico)", + "Spanish (Paraguay)", + "Spanish (El Salvador)", + "Spanish (United States)", + "Spanish (Uruguay)", + "Spanish (Venezuela)", + "Estonian", + "Estonian (Estonia)", + "Basque", + "Basque (Spain)", + "Persian", + "Persian (Iran)", + "Fulah (Senegal)", + "Finnish", + "Finnish (Finland)", + "Filipino (Philippines)", + "Faroese (Faroe Islands)", + "French", + "French (Belgium)", + "French (Canada)", + "French (Switzerland)", + "French (France)", + "French (Luxembourg)", + "Friulian (Italy)", + "Western Frisian (Germany)", + "Western Frisian (Netherlands)", + "Irish", + "Irish (Ireland)", + "Scottish Gaelic (United Kingdom)", + "Geez (Eritrea)", + "Geez (Ethiopia)", + "Galician (Spain)", + "Gujarati (India)", + "Manx (United Kingdom)", + "Hakka Chinese (Taiwan)", + "Hausa (Nigeria)", + "Hebrew", + "Hebrew (Israel)", + "Hindi", + "Hindi (India)", + "Chhattisgarhi (India)", + "Croatian", + "Croatian (Croatia)", + "Upper Sorbian (Germany)", + "Haitian (Haiti)", + "Hungarian", + "Hungarian (Hungary)", + "Huastec (Mexico)", + "Armenian (Armenia)", + "Interlingua (France)", + "Indonesian", + "Indonesian (Indonesia)", + "Igbo (Nigeria)", + "Inupiaq (Canada)", + "Icelandic", + "Icelandic (Iceland)", + "Italian", + "Italian (Switzerland)", + "Italian (Italy)", + "Inuktitut (Canada)", + "Japanese", + "Japanese (Japan)", + "Kabyle (Algeria)", + "Georgian (Georgia)", + "Kazakh (Kazakhstan)", + "Kalaallisut (Greenland)", + "Central Khmer (Cambodia)", + "Kannada (India)", + "Konkani (India)", + "Korean", + "Korean (South Korea)", + "Kashmiri (India)", + "Kurdish", + "Kurdish (Turkey)", + "Cornish (United Kingdom)", + "Kirghiz (Kyrgyzstan)", + "Luxembourgish (Luxembourg)", + "Ganda (Uganda)", + "Limburgan (Belgium)", + "Limburgan (Netherlands)", + "Ligurian (Italy)", + "Lingala (Congo)", + "Lao (Laos)", + "Lithuanian", + "Lithuanian (Lithuania)", + "Latvian", + "Latvian (Latvia)", + "Literary Chinese (Taiwan)", + "Magahi (India)", + "Maithili (India)", + "Malagasy (Madagascar)", + "Marshallese (Marshall Islands)", + "Eastern Mari (Russia)", + "Maori (New Zealand)", + "MÃskito (Nicaragua)", + "Macedonian", + "Macedonian (Macedonia)", + "Malayalam (India)", + "Manipuri (India)", + "Mongolian (Mongolia)", + "Marathi (India)", + "Malay", + "Malay (Malaysia)", + "Maltese", + "Maltese (Malta)", + "Burmese (Myanmar)", + "Erzya (Russia)", + "Nahuatl languages (Mexico)", + "Min Nan Chinese (Taiwan)", + "Norwegian BokmÃ¥l", + "Norwegian BokmÃ¥l (Norway)", + "Low German (Germany)", + "Low German (Netherlands)", + "Nepali (Nepal)", + "Central Nahuatl (Mexico)", + "Niuean (Niue)", + "Niuean (New Zealand)", + "Dutch", + "Dutch (Aruba)", + "Dutch (Belgium)", + "Dutch (Netherlands)", + "Norwegian Nynorsk", + "Norwegian Nynorsk (Norway)", + "South Ndebele (South Africa)", + "Pedi (South Africa)", + "Occitan (France)", + "Oromo", + "Oromo (Ethiopia)", + "Oromo (Kenya)", + "Oriya (India)", + "Ossetian (Russia)", + "Panjabi (India)", + "Papiamento", + "Papiamento (Netherlands Antilles)", + "Papiamento (Aruba)", + "Papiamento (Curaçao)", + "Panjabi (Pakistan)", + "Polish", + "Polish (Poland)", + "Pirate", + "Pushto (Afghanistan)", + "Portuguese", + "Portuguese (Brazil)", + "Portuguese (Portugal)", + "Ayacucho Quechua (Peru)", + "Cusco Quechua (Peru)", + "Rajasthani (India)", + "Romanian", + "Romanian (Romania)", + "Russian", + "Russian (Russia)", + "Russian (Ukraine)", + "Kinyarwanda (Rwanda)", + "Sanskrit (India)", + "Santali (India)", + "Sardinian (Italy)", + "Scots (Scotland)", + "Sindhi (India)", + "Northern Sami (Norway)", + "Samogitian (Lithuania)", + "Shuswap (Canada)", + "Sidamo (Ethiopia)", + "Sinhala (Sri Lanka)", + "Slovak", + "Slovak (Slovakia)", + "Slovenian", + "Slovenian (Slovenia)", + "Somali", + "Somali (Djibouti)", + "Somali (Ethiopia)", + "Somali (Kenya)", + "Somali (Somalia)", + "Songhai languages (Mali)", + "Albanian", + "Albanian (Albania)", + "Albanian (Kosovo)", + "Albanian (Macedonia)", + "Serbian", + "Serbian (Montenegro)", + "Serbian (Serbia)", + "Swati (South Africa)", + "Southern Sotho (South Africa)", + "Swedish", + "Swedish (Finland)", + "Swedish (Sweden)", + "Swahili (Kenya)", + "Swahili (Tanzania)", + "Silesian (Poland)", + "Tamil", + "Tamil (India)", + "Tamil (Sri Lanka)", + "Tulu (India)", + "Telugu (India)", + "Tajik (Tajikistan)", + "Chitwania Tharu (Nepal)", + "Thai", + "Thai (Thailand)", + "Tigrinya", + "Tigrinya (Eritrea)", + "Tigrinya (Ethiopia)", + "Tigre (Eritrea)", + "Turkmen (Turkmenistan)", + "Tagalog (Philippines)", + "Tswana (South Africa)", + "Turkish", + "Turkish (Cyprus)", + "Turkish (Turkey)", + "Tsonga (South Africa)", + "Tatar (Russia)", + "Uighur (China)", + "Ukrainian", + "Ukrainian (Ukraine)", + "Unami (United States)", + "Urdu", + "Urdu (India)", + "Urdu (Pakistan)", + "Uzbek", + "Uzbek (Uzbekistan)", + "Venda (South Africa)", + "Vietnamese", + "Vietnamese (Vietnam)", + "Walloon (Belgium)", + "Walser (Switzerland)", + "Wolaytta (Ethiopia)", + "Wolof (Senegal)", + "Xhosa (South Africa)", + "Yiddish (United States)", + "Yoruba (Nigeria)", + "Yue Chinese (Hong Kong)", + "Chinese", + "Chinese (China)", + "Chinese (Hong Kong)", + "Chinese (Singapore)", + "Chinese (Taiwan)", + "Zulu (South Africa)", + 0 }; -bool TranslationServer::is_locale_valid(const String& p_locale) { +bool TranslationServer::is_locale_valid(const String &p_locale) { - const char **ptr=locale_list; + const char **ptr = locale_list; while (*ptr) { - if (*ptr==p_locale) + if (*ptr == p_locale) return true; ptr++; } return false; - } Vector<String> TranslationServer::get_all_locales() { Vector<String> locales; - const char **ptr=locale_list; + const char **ptr = locale_list; while (*ptr) { locales.push_back(*ptr); @@ -779,14 +778,13 @@ Vector<String> TranslationServer::get_all_locales() { } return locales; - } -Vector<String> TranslationServer::get_all_locale_names(){ +Vector<String> TranslationServer::get_all_locale_names() { Vector<String> locales; - const char **ptr=locale_names; + const char **ptr = locale_names; while (*ptr) { locales.push_back(*ptr); @@ -794,21 +792,19 @@ Vector<String> TranslationServer::get_all_locale_names(){ } return locales; - } +static String get_trimmed_locale(const String &p_locale) { -static String get_trimmed_locale(const String& p_locale) { - - return p_locale.substr(0,2); + return p_locale.substr(0, 2); } -static bool is_valid_locale(const String& p_locale) { +static bool is_valid_locale(const String &p_locale) { - const char **ptr=locale_list; + const char **ptr = locale_list; while (*ptr) { - if (p_locale==*ptr) + if (p_locale == *ptr) return true; ptr++; } @@ -819,13 +815,13 @@ static bool is_valid_locale(const String& p_locale) { PoolVector<String> Translation::_get_messages() const { PoolVector<String> msgs; - msgs.resize(translation_map.size()*2); - int idx=0; - for (const Map<StringName, StringName>::Element *E=translation_map.front();E;E=E->next()) { + msgs.resize(translation_map.size() * 2); + int idx = 0; + for (const Map<StringName, StringName>::Element *E = translation_map.front(); E; E = E->next()) { - msgs.set(idx+0,E->key()); - msgs.set(idx+1,E->get()); - idx+=2; + msgs.set(idx + 0, E->key()); + msgs.set(idx + 1, E->get()); + idx += 2; } return msgs; @@ -835,76 +831,70 @@ PoolVector<String> Translation::_get_message_list() const { PoolVector<String> msgs; msgs.resize(translation_map.size()); - int idx=0; - for (const Map<StringName, StringName>::Element *E=translation_map.front();E;E=E->next()) { + int idx = 0; + for (const Map<StringName, StringName>::Element *E = translation_map.front(); E; E = E->next()) { - msgs.set(idx,E->key()); - idx+=1; + msgs.set(idx, E->key()); + idx += 1; } return msgs; - } -void Translation::_set_messages(const PoolVector<String>& p_messages){ +void Translation::_set_messages(const PoolVector<String> &p_messages) { - int msg_count=p_messages.size(); - ERR_FAIL_COND(msg_count%2); + int msg_count = p_messages.size(); + ERR_FAIL_COND(msg_count % 2); PoolVector<String>::Read r = p_messages.read(); - for(int i=0;i<msg_count;i+=2) { + for (int i = 0; i < msg_count; i += 2) { - add_message( r[i+0], r[i+1] ); + add_message(r[i + 0], r[i + 1]); } - } - -void Translation::set_locale(const String& p_locale) { +void Translation::set_locale(const String &p_locale) { // replaces '-' with '_' for macOS Sierra-style locales String univ_locale = p_locale.replace("-", "_"); - - if(!is_valid_locale(univ_locale)) { + + if (!is_valid_locale(univ_locale)) { String trimmed_locale = get_trimmed_locale(univ_locale); - - ERR_EXPLAIN("Invalid Locale: "+trimmed_locale); + + ERR_EXPLAIN("Invalid Locale: " + trimmed_locale); ERR_FAIL_COND(!is_valid_locale(trimmed_locale)); - - locale=trimmed_locale; - } - else { - locale=univ_locale; + + locale = trimmed_locale; + } else { + locale = univ_locale; } } -void Translation::add_message( const StringName& p_src_text, const StringName& p_xlated_text ) { - - translation_map[p_src_text]=p_xlated_text; +void Translation::add_message(const StringName &p_src_text, const StringName &p_xlated_text) { + translation_map[p_src_text] = p_xlated_text; } -StringName Translation::get_message(const StringName& p_src_text) const { +StringName Translation::get_message(const StringName &p_src_text) const { - const Map<StringName, StringName>::Element *E=translation_map.find(p_src_text); + const Map<StringName, StringName>::Element *E = translation_map.find(p_src_text); if (!E) return StringName(); return E->get(); } -void Translation::erase_message(const StringName& p_src_text) { +void Translation::erase_message(const StringName &p_src_text) { translation_map.erase(p_src_text); } void Translation::get_message_list(List<StringName> *r_messages) const { - for (const Map<StringName, StringName>::Element *E=translation_map.front();E;E=E->next()) { + for (const Map<StringName, StringName>::Element *E = translation_map.front(); E; E = E->next()) { r_messages->push_back(E->key()); } - } int Translation::get_message_count() const { @@ -912,48 +902,43 @@ int Translation::get_message_count() const { return translation_map.size(); }; - void Translation::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_locale","locale"),&Translation::set_locale); - ClassDB::bind_method(D_METHOD("get_locale"),&Translation::get_locale); - ClassDB::bind_method(D_METHOD("add_message","src_message","xlated_message"),&Translation::add_message); - ClassDB::bind_method(D_METHOD("get_message","src_message"),&Translation::get_message); - ClassDB::bind_method(D_METHOD("erase_message","src_message"),&Translation::erase_message); - ClassDB::bind_method(D_METHOD("get_message_list"),&Translation::_get_message_list); - ClassDB::bind_method(D_METHOD("get_message_count"),&Translation::get_message_count); - ClassDB::bind_method(D_METHOD("_set_messages"),&Translation::_set_messages); - ClassDB::bind_method(D_METHOD("_get_messages"),&Translation::_get_messages); - - ADD_PROPERTY( PropertyInfo(Variant::POOL_STRING_ARRAY,"messages",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_messages", "_get_messages") ; - ADD_PROPERTY( PropertyInfo(Variant::STRING,"locale"), "set_locale", "get_locale") ; + ClassDB::bind_method(D_METHOD("set_locale", "locale"), &Translation::set_locale); + ClassDB::bind_method(D_METHOD("get_locale"), &Translation::get_locale); + ClassDB::bind_method(D_METHOD("add_message", "src_message", "xlated_message"), &Translation::add_message); + ClassDB::bind_method(D_METHOD("get_message", "src_message"), &Translation::get_message); + ClassDB::bind_method(D_METHOD("erase_message", "src_message"), &Translation::erase_message); + ClassDB::bind_method(D_METHOD("get_message_list"), &Translation::_get_message_list); + ClassDB::bind_method(D_METHOD("get_message_count"), &Translation::get_message_count); + ClassDB::bind_method(D_METHOD("_set_messages"), &Translation::_set_messages); + ClassDB::bind_method(D_METHOD("_get_messages"), &Translation::_get_messages); + + ADD_PROPERTY(PropertyInfo(Variant::POOL_STRING_ARRAY, "messages", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_messages", "_get_messages"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "locale"), "set_locale", "get_locale"); } Translation::Translation() { - locale="en"; + locale = "en"; } - - /////////////////////////////////////////////// - -void TranslationServer::set_locale(const String& p_locale) { +void TranslationServer::set_locale(const String &p_locale) { // replaces '-' with '_' for macOS Sierra-style locales String univ_locale = p_locale.replace("-", "_"); - - if(!is_valid_locale(univ_locale)) { + + if (!is_valid_locale(univ_locale)) { String trimmed_locale = get_trimmed_locale(univ_locale); - - ERR_EXPLAIN("Invalid Locale: "+trimmed_locale); + + ERR_EXPLAIN("Invalid Locale: " + trimmed_locale); ERR_FAIL_COND(!is_valid_locale(trimmed_locale)); - - locale=trimmed_locale; - } - else { - locale=univ_locale; + + locale = trimmed_locale; + } else { + locale = univ_locale; } if (OS::get_singleton()->get_main_loop()) { @@ -964,13 +949,11 @@ void TranslationServer::set_locale(const String& p_locale) { String TranslationServer::get_locale() const { return locale; - } void TranslationServer::add_translation(const Ref<Translation> &p_translation) { translations.insert(p_translation); - } void TranslationServer::remove_translation(const Ref<Translation> &p_translation) { @@ -982,7 +965,7 @@ void TranslationServer::clear() { translations.clear(); }; -StringName TranslationServer::translate(const StringName& p_message) const { +StringName TranslationServer::translate(const StringName &p_message) const { //translate using locale @@ -990,93 +973,88 @@ StringName TranslationServer::translate(const StringName& p_message) const { return p_message; StringName res; - bool near_match=false; - const CharType *lptr=&locale[0]; + bool near_match = false; + const CharType *lptr = &locale[0]; + for (const Set<Ref<Translation> >::Element *E = translations.front(); E; E = E->next()) { - for (const Set< Ref<Translation> >::Element *E=translations.front();E;E=E->next()) { - - const Ref<Translation>& t = E->get(); + const Ref<Translation> &t = E->get(); String l = t->get_locale(); - if (lptr[0]!=l[0] || lptr[1]!=l[1]) + if (lptr[0] != l[0] || lptr[1] != l[1]) continue; // locale not match //near match - bool match = (l!=locale); + bool match = (l != locale); if (near_match && !match) continue; //only near-match once - StringName r=t->get_message(p_message); - + StringName r = t->get_message(p_message); if (!r) continue; - res=r; + res = r; if (match) break; else - near_match=true; - + near_match = true; } if (!res) { //try again with fallback - if (fallback.length()>=2) { + if (fallback.length() >= 2) { - const CharType *fptr=&fallback[0]; - bool near_match=false; - for (const Set< Ref<Translation> >::Element *E=translations.front();E;E=E->next()) { + const CharType *fptr = &fallback[0]; + bool near_match = false; + for (const Set<Ref<Translation> >::Element *E = translations.front(); E; E = E->next()) { - const Ref<Translation>& t = E->get(); + const Ref<Translation> &t = E->get(); String l = t->get_locale(); - if (fptr[0]!=l[0] || fptr[1]!=l[1]) + if (fptr[0] != l[0] || fptr[1] != l[1]) continue; // locale not match //near match - bool match = (l!=fallback); + bool match = (l != fallback); if (near_match && !match) continue; //only near-match once - StringName r=t->get_message(p_message); + StringName r = t->get_message(p_message); if (!r) continue; - res=r; + res = r; if (match) break; else - near_match=true; - + near_match = true; } } } - if (!res) return p_message; return res; } -TranslationServer *TranslationServer::singleton=NULL; +TranslationServer *TranslationServer::singleton = NULL; -bool TranslationServer::_load_translations(const String& p_from) { +bool TranslationServer::_load_translations(const String &p_from) { if (GlobalConfig::get_singleton()->has(p_from)) { - PoolVector<String> translations=GlobalConfig::get_singleton()->get(p_from); + PoolVector<String> translations = GlobalConfig::get_singleton()->get(p_from); - int tcount=translations.size(); + int tcount = translations.size(); if (tcount) { PoolVector<String>::Read r = translations.read(); - for(int i=0;i<tcount;i++) { + for (int i = 0; i < tcount; i++) { //print_line( "Loading translation from " + r[i] ); Ref<Translation> tr = ResourceLoader::load(r[i]); @@ -1092,36 +1070,35 @@ bool TranslationServer::_load_translations(const String& p_from) { void TranslationServer::setup() { - String test = GLOBAL_DEF("locale/test",""); - test=test.strip_edges(); - if (test!="") - set_locale( test ); + String test = GLOBAL_DEF("locale/test", ""); + test = test.strip_edges(); + if (test != "") + set_locale(test); else - set_locale( OS::get_singleton()->get_locale() ); - fallback = GLOBAL_DEF("locale/fallback","en"); + set_locale(OS::get_singleton()->get_locale()); + fallback = GLOBAL_DEF("locale/fallback", "en"); #ifdef TOOLS_ENABLED { - String options=""; - int idx=0; - while(locale_list[idx]) { - if (idx>0) - options+=", "; - options+=locale_list[idx]; + String options = ""; + int idx = 0; + while (locale_list[idx]) { + if (idx > 0) + options += ", "; + options += locale_list[idx]; idx++; } - GlobalConfig::get_singleton()->set_custom_property_info("locale/fallback",PropertyInfo(Variant::STRING,"locale/fallback",PROPERTY_HINT_ENUM,options)); + GlobalConfig::get_singleton()->set_custom_property_info("locale/fallback", PropertyInfo(Variant::STRING, "locale/fallback", PROPERTY_HINT_ENUM, options)); } #endif //load translations - } -void TranslationServer::set_tool_translation(const Ref<Translation>& p_translation) { - tool_translation=p_translation; +void TranslationServer::set_tool_translation(const Ref<Translation> &p_translation) { + tool_translation = p_translation; } -StringName TranslationServer::tool_translate(const StringName& p_message) const { +StringName TranslationServer::tool_translate(const StringName &p_message) const { if (tool_translation.is_valid()) { StringName r = tool_translation->get_message(p_message); @@ -1134,19 +1111,17 @@ StringName TranslationServer::tool_translate(const StringName& p_message) const return p_message; } - void TranslationServer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_locale","locale"),&TranslationServer::set_locale); - ClassDB::bind_method(D_METHOD("get_locale"),&TranslationServer::get_locale); - - ClassDB::bind_method(D_METHOD("translate","message"),&TranslationServer::translate); + ClassDB::bind_method(D_METHOD("set_locale", "locale"), &TranslationServer::set_locale); + ClassDB::bind_method(D_METHOD("get_locale"), &TranslationServer::get_locale); - ClassDB::bind_method(D_METHOD("add_translation","translation:Translation"),&TranslationServer::add_translation); - ClassDB::bind_method(D_METHOD("remove_translation","translation:Translation"),&TranslationServer::remove_translation); + ClassDB::bind_method(D_METHOD("translate", "message"), &TranslationServer::translate); - ClassDB::bind_method(D_METHOD("clear"),&TranslationServer::clear); + ClassDB::bind_method(D_METHOD("add_translation", "translation:Translation"), &TranslationServer::add_translation); + ClassDB::bind_method(D_METHOD("remove_translation", "translation:Translation"), &TranslationServer::remove_translation); + ClassDB::bind_method(D_METHOD("clear"), &TranslationServer::clear); } void TranslationServer::load_translations() { @@ -1154,21 +1129,17 @@ void TranslationServer::load_translations() { String locale = get_locale(); bool found = _load_translations("locale/translations"); //all - if (_load_translations("locale/translations_"+locale.substr(0,2))) - found=true; - if ( locale.substr(0,2) != locale ) { - if (_load_translations("locale/translations_"+locale)) - found=true; + if (_load_translations("locale/translations_" + locale.substr(0, 2))) + found = true; + if (locale.substr(0, 2) != locale) { + if (_load_translations("locale/translations_" + locale)) + found = true; } - - } TranslationServer::TranslationServer() { - - singleton=this; - locale="en"; - enabled=true; - + singleton = this; + locale = "en"; + enabled = true; } diff --git a/core/translation.h b/core/translation.h index feed352549..90ec3fddce 100644 --- a/core/translation.h +++ b/core/translation.h @@ -31,12 +31,10 @@ #include "resource.h" - class Translation : public Resource { - - GDCLASS( Translation, Resource ); - OBJ_SAVE_TYPE( Translation ); + GDCLASS(Translation, Resource); + OBJ_SAVE_TYPE(Translation); RES_BASE_EXTENSION("xl"); String locale; @@ -45,19 +43,18 @@ class Translation : public Resource { PoolVector<String> _get_message_list() const; PoolVector<String> _get_messages() const; - void _set_messages(const PoolVector<String>& p_messages); + void _set_messages(const PoolVector<String> &p_messages); + protected: static void _bind_methods(); public: - - - void set_locale(const String& p_locale); + void set_locale(const String &p_locale); _FORCE_INLINE_ String get_locale() const { return locale; } - void add_message( const StringName& p_src_text, const StringName& p_xlated_text ); - virtual StringName get_message(const StringName& p_src_text) const; //overridable for other implementations - void erase_message(const StringName& p_src_text); + void add_message(const StringName &p_src_text, const StringName &p_xlated_text); + virtual StringName get_message(const StringName &p_src_text) const; //overridable for other implementations + void erase_message(const StringName &p_src_text); void get_message_list(List<StringName> *r_messages) const; int get_message_count() const; @@ -65,7 +62,6 @@ public: Translation(); }; - class TranslationServer : public Object { GDCLASS(TranslationServer, Object); @@ -73,39 +69,38 @@ class TranslationServer : public Object { String locale; String fallback; - - Set< Ref<Translation> > translations; + Set<Ref<Translation> > translations; Ref<Translation> tool_translation; bool enabled; static TranslationServer *singleton; - bool _load_translations(const String& p_from); + bool _load_translations(const String &p_from); static void _bind_methods(); -public: +public: _FORCE_INLINE_ static TranslationServer *get_singleton() { return singleton; } //yes, portuguese is supported! - void set_enabled(bool p_enabled) { enabled=p_enabled; } + void set_enabled(bool p_enabled) { enabled = p_enabled; } _FORCE_INLINE_ bool is_enabled() const { return enabled; } - void set_locale(const String& p_locale); + void set_locale(const String &p_locale); String get_locale() const; void add_translation(const Ref<Translation> &p_translation); void remove_translation(const Ref<Translation> &p_translation); - StringName translate(const StringName& p_message) const; + StringName translate(const StringName &p_message) const; static Vector<String> get_all_locales(); static Vector<String> get_all_locale_names(); - static bool is_locale_valid(const String& p_locale); + static bool is_locale_valid(const String &p_locale); - void set_tool_translation(const Ref<Translation>& p_translation); - StringName tool_translate(const StringName& p_message) const; + void set_tool_translation(const Ref<Translation> &p_translation); + StringName tool_translate(const StringName &p_message) const; void setup(); diff --git a/core/typedefs.h b/core/typedefs.h index c630887924..469c9ebd95 100644 --- a/core/typedefs.h +++ b/core/typedefs.h @@ -52,10 +52,9 @@ #endif // VERSION_PATCH #define VERSION_FULL_NAME "" _MKSTR(VERSION_NAME) " v" VERSION_MKSTRING - #ifndef _ALWAYS_INLINE_ -#if defined(__GNUC__) && (__GNUC__ >= 4 ) +#if defined(__GNUC__) && (__GNUC__ >= 4) #define _ALWAYS_INLINE_ __attribute__((always_inline)) inline #elif defined(__llvm__) #define _ALWAYS_INLINE_ __attribute__((always_inline)) inline @@ -75,13 +74,15 @@ #endif #endif - //custom, gcc-safe offsetof, because gcc complains a lot. -template<class T> -T *_nullptr() { T*t=NULL; return t; } +template <class T> +T *_nullptr() { + T *t = NULL; + return t; +} #define OFFSET_OF(st, m) \ -((size_t) ( (char *)&(_nullptr<st>()->m) - (char *)0 )) + ((size_t)((char *)&(_nullptr<st>()->m) - (char *)0)) /** * Some platforms (devices) not define NULL */ @@ -107,43 +108,43 @@ T *_nullptr() { T*t=NULL; return t; } #undef OK #endif -#include "error_macros.h" #include "error_list.h" +#include "error_macros.h" #include "int_types.h" /** Generic ABS function, for math uses please use Math::abs */ #ifndef ABS -#define ABS(m_v) ((m_v<0)?(-(m_v)):(m_v)) +#define ABS(m_v) ((m_v < 0) ? (-(m_v)) : (m_v)) #endif #ifndef SGN -#define SGN(m_v) ((m_v<0)?(-1.0):(+1.0)) +#define SGN(m_v) ((m_v < 0) ? (-1.0) : (+1.0)) #endif #ifndef MIN -#define MIN(m_a,m_b) (((m_a)<(m_b))?(m_a):(m_b)) +#define MIN(m_a, m_b) (((m_a) < (m_b)) ? (m_a) : (m_b)) #endif #ifndef MAX -#define MAX(m_a,m_b) (((m_a)>(m_b))?(m_a):(m_b)) +#define MAX(m_a, m_b) (((m_a) > (m_b)) ? (m_a) : (m_b)) #endif #ifndef CLAMP -#define CLAMP(m_a,m_min,m_max) (((m_a)<(m_min))?(m_min):(((m_a)>(m_max))?m_max:m_a)) +#define CLAMP(m_a, m_min, m_max) (((m_a) < (m_min)) ? (m_min) : (((m_a) > (m_max)) ? m_max : m_a)) #endif /** Generic swap template */ #ifndef SWAP -#define SWAP(m_x,m_y) __swap_tmpl(m_x,m_y) -template<class T> -inline void __swap_tmpl(T &x, T &y ) { +#define SWAP(m_x, m_y) __swap_tmpl(m_x, m_y) +template <class T> +inline void __swap_tmpl(T &x, T &y) { - T aux=x; - x=y; - y=aux; + T aux = x; + x = y; + y = aux; } #endif //swap @@ -171,7 +172,6 @@ inline void __swap_tmpl(T &x, T &y ) { #define _add_overflow __builtin_add_overflow #endif - /** Function to find the nearest (bigger) power of 2 to an integer */ static _FORCE_INLINE_ unsigned int nearest_power_of_2(unsigned int x) { @@ -189,7 +189,7 @@ static _FORCE_INLINE_ unsigned int nearest_power_of_2(unsigned int x) { // We need this definition inside the function below. static inline int get_shift_from_power_of_2(unsigned int p_pixel); -template<class T> +template <class T> static _FORCE_INLINE_ T nearest_power_of_2_templated(T x) { --x; @@ -211,23 +211,22 @@ static _FORCE_INLINE_ T nearest_power_of_2_templated(T x) { static inline unsigned int nearest_shift(unsigned int p_number) { - for (int i=30;i>=0;i--) { + for (int i = 30; i >= 0; i--) { - if (p_number&(1<<i)) - return i+1; + if (p_number & (1 << i)) + return i + 1; } return 0; } /** get a shift value from a power of 2 */ -static inline int get_shift_from_power_of_2( unsigned int p_pixel ) { +static inline int get_shift_from_power_of_2(unsigned int p_pixel) { // return a GL_TEXTURE_SIZE_ENUM + for (unsigned int i = 0; i < 32; i++) { - for (unsigned int i=0;i<32;i++) { - - if (p_pixel==(unsigned int)(1<<i)) + if (p_pixel == (unsigned int)(1 << i)) return i; } @@ -236,18 +235,18 @@ static inline int get_shift_from_power_of_2( unsigned int p_pixel ) { /** Swap 16 bits value for endianness */ static inline uint16_t BSWAP16(uint16_t x) { - return (x>>8)|(x<<8); + return (x >> 8) | (x << 8); } /** Swap 32 bits value for endianness */ static inline uint32_t BSWAP32(uint32_t x) { - return((x<<24)|((x<<8)&0x00FF0000)|((x>>8)&0x0000FF00)|(x>>24)); + return ((x << 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x >> 24)); } /** Swap 64 bits value for endianness */ static inline uint64_t BSWAP64(uint64_t x) { x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32; x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16; - x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8; + x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8; return x; } @@ -256,14 +255,12 @@ static inline uint64_t BSWAP64(uint64_t x) { * is used besides casting by enum. */ -template<class T> +template <class T> struct Comparator { - inline bool operator()(const T& p_a, const T& p_b) const { return (p_a<p_b); } - + inline bool operator()(const T &p_a, const T &p_b) const { return (p_a < p_b); } }; - void _global_lock(); void _global_unlock(); @@ -286,4 +283,4 @@ struct _GlobalLock { #define __STRX(m_index) #m_index #define __STR(m_index) __STRX(m_index) -#endif /* typedefs.h */ +#endif /* typedefs.h */ diff --git a/core/ucaps.h b/core/ucaps.h index 55b6509269..0e4b5709e6 100644 --- a/core/ucaps.h +++ b/core/ucaps.h @@ -32,1358 +32,1356 @@ //satan invented unicode? #define CAPS_LEN 666 -static const int caps_table[CAPS_LEN][2]={ -{0x0061,0x0041}, -{0x0062,0x0042}, -{0x0063,0x0043}, -{0x0064,0x0044}, -{0x0065,0x0045}, -{0x0066,0x0046}, -{0x0067,0x0047}, -{0x0068,0x0048}, -{0x0069,0x0049}, -{0x006A,0x004A}, -{0x006B,0x004B}, -{0x006C,0x004C}, -{0x006D,0x004D}, -{0x006E,0x004E}, -{0x006F,0x004F}, -{0x0070,0x0050}, -{0x0071,0x0051}, -{0x0072,0x0052}, -{0x0073,0x0053}, -{0x0074,0x0054}, -{0x0075,0x0055}, -{0x0076,0x0056}, -{0x0077,0x0057}, -{0x0078,0x0058}, -{0x0079,0x0059}, -{0x007A,0x005A}, -{0x00E0,0x00C0}, -{0x00E1,0x00C1}, -{0x00E2,0x00C2}, -{0x00E3,0x00C3}, -{0x00E4,0x00C4}, -{0x00E5,0x00C5}, -{0x00E6,0x00C6}, -{0x00E7,0x00C7}, -{0x00E8,0x00C8}, -{0x00E9,0x00C9}, -{0x00EA,0x00CA}, -{0x00EB,0x00CB}, -{0x00EC,0x00CC}, -{0x00ED,0x00CD}, -{0x00EE,0x00CE}, -{0x00EF,0x00CF}, -{0x00F0,0x00D0}, -{0x00F1,0x00D1}, -{0x00F2,0x00D2}, -{0x00F3,0x00D3}, -{0x00F4,0x00D4}, -{0x00F5,0x00D5}, -{0x00F6,0x00D6}, -{0x00F8,0x00D8}, -{0x00F9,0x00D9}, -{0x00FA,0x00DA}, -{0x00FB,0x00DB}, -{0x00FC,0x00DC}, -{0x00FD,0x00DD}, -{0x00FE,0x00DE}, -{0x00FF,0x0178}, -{0x0101,0x0100}, -{0x0103,0x0102}, -{0x0105,0x0104}, -{0x0107,0x0106}, -{0x0109,0x0108}, -{0x010B,0x010A}, -{0x010D,0x010C}, -{0x010F,0x010E}, -{0x0111,0x0110}, -{0x0113,0x0112}, -{0x0115,0x0114}, -{0x0117,0x0116}, -{0x0119,0x0118}, -{0x011B,0x011A}, -{0x011D,0x011C}, -{0x011F,0x011E}, -{0x0121,0x0120}, -{0x0123,0x0122}, -{0x0125,0x0124}, -{0x0127,0x0126}, -{0x0129,0x0128}, -{0x012B,0x012A}, -{0x012D,0x012C}, -{0x012F,0x012E}, -{0x0131,0x0049}, -{0x0133,0x0132}, -{0x0135,0x0134}, -{0x0137,0x0136}, -{0x013A,0x0139}, -{0x013C,0x013B}, -{0x013E,0x013D}, -{0x0140,0x013F}, -{0x0142,0x0141}, -{0x0144,0x0143}, -{0x0146,0x0145}, -{0x0148,0x0147}, -{0x014B,0x014A}, -{0x014D,0x014C}, -{0x014F,0x014E}, -{0x0151,0x0150}, -{0x0153,0x0152}, -{0x0155,0x0154}, -{0x0157,0x0156}, -{0x0159,0x0158}, -{0x015B,0x015A}, -{0x015D,0x015C}, -{0x015F,0x015E}, -{0x0161,0x0160}, -{0x0163,0x0162}, -{0x0165,0x0164}, -{0x0167,0x0166}, -{0x0169,0x0168}, -{0x016B,0x016A}, -{0x016D,0x016C}, -{0x016F,0x016E}, -{0x0171,0x0170}, -{0x0173,0x0172}, -{0x0175,0x0174}, -{0x0177,0x0176}, -{0x017A,0x0179}, -{0x017C,0x017B}, -{0x017E,0x017D}, -{0x0183,0x0182}, -{0x0185,0x0184}, -{0x0188,0x0187}, -{0x018C,0x018B}, -{0x0192,0x0191}, -{0x0199,0x0198}, -{0x01A1,0x01A0}, -{0x01A3,0x01A2}, -{0x01A5,0x01A4}, -{0x01A8,0x01A7}, -{0x01AD,0x01AC}, -{0x01B0,0x01AF}, -{0x01B4,0x01B3}, -{0x01B6,0x01B5}, -{0x01B9,0x01B8}, -{0x01BD,0x01BC}, -{0x01C6,0x01C4}, -{0x01C9,0x01C7}, -{0x01CC,0x01CA}, -{0x01CE,0x01CD}, -{0x01D0,0x01CF}, -{0x01D2,0x01D1}, -{0x01D4,0x01D3}, -{0x01D6,0x01D5}, -{0x01D8,0x01D7}, -{0x01DA,0x01D9}, -{0x01DC,0x01DB}, -{0x01DF,0x01DE}, -{0x01E1,0x01E0}, -{0x01E3,0x01E2}, -{0x01E5,0x01E4}, -{0x01E7,0x01E6}, -{0x01E9,0x01E8}, -{0x01EB,0x01EA}, -{0x01ED,0x01EC}, -{0x01EF,0x01EE}, -{0x01F3,0x01F1}, -{0x01F5,0x01F4}, -{0x01FB,0x01FA}, -{0x01FD,0x01FC}, -{0x01FF,0x01FE}, -{0x0201,0x0200}, -{0x0203,0x0202}, -{0x0205,0x0204}, -{0x0207,0x0206}, -{0x0209,0x0208}, -{0x020B,0x020A}, -{0x020D,0x020C}, -{0x020F,0x020E}, -{0x0211,0x0210}, -{0x0213,0x0212}, -{0x0215,0x0214}, -{0x0217,0x0216}, -{0x0253,0x0181}, -{0x0254,0x0186}, -{0x0257,0x018A}, -{0x0258,0x018E}, -{0x0259,0x018F}, -{0x025B,0x0190}, -{0x0260,0x0193}, -{0x0263,0x0194}, -{0x0268,0x0197}, -{0x0269,0x0196}, -{0x026F,0x019C}, -{0x0272,0x019D}, -{0x0275,0x019F}, -{0x0283,0x01A9}, -{0x0288,0x01AE}, -{0x028A,0x01B1}, -{0x028B,0x01B2}, -{0x0292,0x01B7}, -{0x03AC,0x0386}, -{0x03AD,0x0388}, -{0x03AE,0x0389}, -{0x03AF,0x038A}, -{0x03B1,0x0391}, -{0x03B2,0x0392}, -{0x03B3,0x0393}, -{0x03B4,0x0394}, -{0x03B5,0x0395}, -{0x03B6,0x0396}, -{0x03B7,0x0397}, -{0x03B8,0x0398}, -{0x03B9,0x0399}, -{0x03BA,0x039A}, -{0x03BB,0x039B}, -{0x03BC,0x039C}, -{0x03BD,0x039D}, -{0x03BE,0x039E}, -{0x03BF,0x039F}, -{0x03C0,0x03A0}, -{0x03C1,0x03A1}, -{0x03C3,0x03A3}, -{0x03C4,0x03A4}, -{0x03C5,0x03A5}, -{0x03C6,0x03A6}, -{0x03C7,0x03A7}, -{0x03C8,0x03A8}, -{0x03C9,0x03A9}, -{0x03CA,0x03AA}, -{0x03CB,0x03AB}, -{0x03CC,0x038C}, -{0x03CD,0x038E}, -{0x03CE,0x038F}, -{0x03E3,0x03E2}, -{0x03E5,0x03E4}, -{0x03E7,0x03E6}, -{0x03E9,0x03E8}, -{0x03EB,0x03EA}, -{0x03ED,0x03EC}, -{0x03EF,0x03EE}, -{0x0430,0x0410}, -{0x0431,0x0411}, -{0x0432,0x0412}, -{0x0433,0x0413}, -{0x0434,0x0414}, -{0x0435,0x0415}, -{0x0436,0x0416}, -{0x0437,0x0417}, -{0x0438,0x0418}, -{0x0439,0x0419}, -{0x043A,0x041A}, -{0x043B,0x041B}, -{0x043C,0x041C}, -{0x043D,0x041D}, -{0x043E,0x041E}, -{0x043F,0x041F}, -{0x0440,0x0420}, -{0x0441,0x0421}, -{0x0442,0x0422}, -{0x0443,0x0423}, -{0x0444,0x0424}, -{0x0445,0x0425}, -{0x0446,0x0426}, -{0x0447,0x0427}, -{0x0448,0x0428}, -{0x0449,0x0429}, -{0x044A,0x042A}, -{0x044B,0x042B}, -{0x044C,0x042C}, -{0x044D,0x042D}, -{0x044E,0x042E}, -{0x044F,0x042F}, -{0x0451,0x0401}, -{0x0452,0x0402}, -{0x0453,0x0403}, -{0x0454,0x0404}, -{0x0455,0x0405}, -{0x0456,0x0406}, -{0x0457,0x0407}, -{0x0458,0x0408}, -{0x0459,0x0409}, -{0x045A,0x040A}, -{0x045B,0x040B}, -{0x045C,0x040C}, -{0x045E,0x040E}, -{0x045F,0x040F}, -{0x0461,0x0460}, -{0x0463,0x0462}, -{0x0465,0x0464}, -{0x0467,0x0466}, -{0x0469,0x0468}, -{0x046B,0x046A}, -{0x046D,0x046C}, -{0x046F,0x046E}, -{0x0471,0x0470}, -{0x0473,0x0472}, -{0x0475,0x0474}, -{0x0477,0x0476}, -{0x0479,0x0478}, -{0x047B,0x047A}, -{0x047D,0x047C}, -{0x047F,0x047E}, -{0x0481,0x0480}, -{0x0491,0x0490}, -{0x0493,0x0492}, -{0x0495,0x0494}, -{0x0497,0x0496}, -{0x0499,0x0498}, -{0x049B,0x049A}, -{0x049D,0x049C}, -{0x049F,0x049E}, -{0x04A1,0x04A0}, -{0x04A3,0x04A2}, -{0x04A5,0x04A4}, -{0x04A7,0x04A6}, -{0x04A9,0x04A8}, -{0x04AB,0x04AA}, -{0x04AD,0x04AC}, -{0x04AF,0x04AE}, -{0x04B1,0x04B0}, -{0x04B3,0x04B2}, -{0x04B5,0x04B4}, -{0x04B7,0x04B6}, -{0x04B9,0x04B8}, -{0x04BB,0x04BA}, -{0x04BD,0x04BC}, -{0x04BF,0x04BE}, -{0x04C2,0x04C1}, -{0x04C4,0x04C3}, -{0x04C8,0x04C7}, -{0x04CC,0x04CB}, -{0x04D1,0x04D0}, -{0x04D3,0x04D2}, -{0x04D5,0x04D4}, -{0x04D7,0x04D6}, -{0x04D9,0x04D8}, -{0x04DB,0x04DA}, -{0x04DD,0x04DC}, -{0x04DF,0x04DE}, -{0x04E1,0x04E0}, -{0x04E3,0x04E2}, -{0x04E5,0x04E4}, -{0x04E7,0x04E6}, -{0x04E9,0x04E8}, -{0x04EB,0x04EA}, -{0x04EF,0x04EE}, -{0x04F1,0x04F0}, -{0x04F3,0x04F2}, -{0x04F5,0x04F4}, -{0x04F9,0x04F8}, -{0x0561,0x0531}, -{0x0562,0x0532}, -{0x0563,0x0533}, -{0x0564,0x0534}, -{0x0565,0x0535}, -{0x0566,0x0536}, -{0x0567,0x0537}, -{0x0568,0x0538}, -{0x0569,0x0539}, -{0x056A,0x053A}, -{0x056B,0x053B}, -{0x056C,0x053C}, -{0x056D,0x053D}, -{0x056E,0x053E}, -{0x056F,0x053F}, -{0x0570,0x0540}, -{0x0571,0x0541}, -{0x0572,0x0542}, -{0x0573,0x0543}, -{0x0574,0x0544}, -{0x0575,0x0545}, -{0x0576,0x0546}, -{0x0577,0x0547}, -{0x0578,0x0548}, -{0x0579,0x0549}, -{0x057A,0x054A}, -{0x057B,0x054B}, -{0x057C,0x054C}, -{0x057D,0x054D}, -{0x057E,0x054E}, -{0x057F,0x054F}, -{0x0580,0x0550}, -{0x0581,0x0551}, -{0x0582,0x0552}, -{0x0583,0x0553}, -{0x0584,0x0554}, -{0x0585,0x0555}, -{0x0586,0x0556}, -{0x10D0,0x10A0}, -{0x10D1,0x10A1}, -{0x10D2,0x10A2}, -{0x10D3,0x10A3}, -{0x10D4,0x10A4}, -{0x10D5,0x10A5}, -{0x10D6,0x10A6}, -{0x10D7,0x10A7}, -{0x10D8,0x10A8}, -{0x10D9,0x10A9}, -{0x10DA,0x10AA}, -{0x10DB,0x10AB}, -{0x10DC,0x10AC}, -{0x10DD,0x10AD}, -{0x10DE,0x10AE}, -{0x10DF,0x10AF}, -{0x10E0,0x10B0}, -{0x10E1,0x10B1}, -{0x10E2,0x10B2}, -{0x10E3,0x10B3}, -{0x10E4,0x10B4}, -{0x10E5,0x10B5}, -{0x10E6,0x10B6}, -{0x10E7,0x10B7}, -{0x10E8,0x10B8}, -{0x10E9,0x10B9}, -{0x10EA,0x10BA}, -{0x10EB,0x10BB}, -{0x10EC,0x10BC}, -{0x10ED,0x10BD}, -{0x10EE,0x10BE}, -{0x10EF,0x10BF}, -{0x10F0,0x10C0}, -{0x10F1,0x10C1}, -{0x10F2,0x10C2}, -{0x10F3,0x10C3}, -{0x10F4,0x10C4}, -{0x10F5,0x10C5}, -{0x1E01,0x1E00}, -{0x1E03,0x1E02}, -{0x1E05,0x1E04}, -{0x1E07,0x1E06}, -{0x1E09,0x1E08}, -{0x1E0B,0x1E0A}, -{0x1E0D,0x1E0C}, -{0x1E0F,0x1E0E}, -{0x1E11,0x1E10}, -{0x1E13,0x1E12}, -{0x1E15,0x1E14}, -{0x1E17,0x1E16}, -{0x1E19,0x1E18}, -{0x1E1B,0x1E1A}, -{0x1E1D,0x1E1C}, -{0x1E1F,0x1E1E}, -{0x1E21,0x1E20}, -{0x1E23,0x1E22}, -{0x1E25,0x1E24}, -{0x1E27,0x1E26}, -{0x1E29,0x1E28}, -{0x1E2B,0x1E2A}, -{0x1E2D,0x1E2C}, -{0x1E2F,0x1E2E}, -{0x1E31,0x1E30}, -{0x1E33,0x1E32}, -{0x1E35,0x1E34}, -{0x1E37,0x1E36}, -{0x1E39,0x1E38}, -{0x1E3B,0x1E3A}, -{0x1E3D,0x1E3C}, -{0x1E3F,0x1E3E}, -{0x1E41,0x1E40}, -{0x1E43,0x1E42}, -{0x1E45,0x1E44}, -{0x1E47,0x1E46}, -{0x1E49,0x1E48}, -{0x1E4B,0x1E4A}, -{0x1E4D,0x1E4C}, -{0x1E4F,0x1E4E}, -{0x1E51,0x1E50}, -{0x1E53,0x1E52}, -{0x1E55,0x1E54}, -{0x1E57,0x1E56}, -{0x1E59,0x1E58}, -{0x1E5B,0x1E5A}, -{0x1E5D,0x1E5C}, -{0x1E5F,0x1E5E}, -{0x1E61,0x1E60}, -{0x1E63,0x1E62}, -{0x1E65,0x1E64}, -{0x1E67,0x1E66}, -{0x1E69,0x1E68}, -{0x1E6B,0x1E6A}, -{0x1E6D,0x1E6C}, -{0x1E6F,0x1E6E}, -{0x1E71,0x1E70}, -{0x1E73,0x1E72}, -{0x1E75,0x1E74}, -{0x1E77,0x1E76}, -{0x1E79,0x1E78}, -{0x1E7B,0x1E7A}, -{0x1E7D,0x1E7C}, -{0x1E7F,0x1E7E}, -{0x1E81,0x1E80}, -{0x1E83,0x1E82}, -{0x1E85,0x1E84}, -{0x1E87,0x1E86}, -{0x1E89,0x1E88}, -{0x1E8B,0x1E8A}, -{0x1E8D,0x1E8C}, -{0x1E8F,0x1E8E}, -{0x1E91,0x1E90}, -{0x1E93,0x1E92}, -{0x1E95,0x1E94}, -{0x1EA1,0x1EA0}, -{0x1EA3,0x1EA2}, -{0x1EA5,0x1EA4}, -{0x1EA7,0x1EA6}, -{0x1EA9,0x1EA8}, -{0x1EAB,0x1EAA}, -{0x1EAD,0x1EAC}, -{0x1EAF,0x1EAE}, -{0x1EB1,0x1EB0}, -{0x1EB3,0x1EB2}, -{0x1EB5,0x1EB4}, -{0x1EB7,0x1EB6}, -{0x1EB9,0x1EB8}, -{0x1EBB,0x1EBA}, -{0x1EBD,0x1EBC}, -{0x1EBF,0x1EBE}, -{0x1EC1,0x1EC0}, -{0x1EC3,0x1EC2}, -{0x1EC5,0x1EC4}, -{0x1EC7,0x1EC6}, -{0x1EC9,0x1EC8}, -{0x1ECB,0x1ECA}, -{0x1ECD,0x1ECC}, -{0x1ECF,0x1ECE}, -{0x1ED1,0x1ED0}, -{0x1ED3,0x1ED2}, -{0x1ED5,0x1ED4}, -{0x1ED7,0x1ED6}, -{0x1ED9,0x1ED8}, -{0x1EDB,0x1EDA}, -{0x1EDD,0x1EDC}, -{0x1EDF,0x1EDE}, -{0x1EE1,0x1EE0}, -{0x1EE3,0x1EE2}, -{0x1EE5,0x1EE4}, -{0x1EE7,0x1EE6}, -{0x1EE9,0x1EE8}, -{0x1EEB,0x1EEA}, -{0x1EED,0x1EEC}, -{0x1EEF,0x1EEE}, -{0x1EF1,0x1EF0}, -{0x1EF3,0x1EF2}, -{0x1EF5,0x1EF4}, -{0x1EF7,0x1EF6}, -{0x1EF9,0x1EF8}, -{0x1F00,0x1F08}, -{0x1F01,0x1F09}, -{0x1F02,0x1F0A}, -{0x1F03,0x1F0B}, -{0x1F04,0x1F0C}, -{0x1F05,0x1F0D}, -{0x1F06,0x1F0E}, -{0x1F07,0x1F0F}, -{0x1F10,0x1F18}, -{0x1F11,0x1F19}, -{0x1F12,0x1F1A}, -{0x1F13,0x1F1B}, -{0x1F14,0x1F1C}, -{0x1F15,0x1F1D}, -{0x1F20,0x1F28}, -{0x1F21,0x1F29}, -{0x1F22,0x1F2A}, -{0x1F23,0x1F2B}, -{0x1F24,0x1F2C}, -{0x1F25,0x1F2D}, -{0x1F26,0x1F2E}, -{0x1F27,0x1F2F}, -{0x1F30,0x1F38}, -{0x1F31,0x1F39}, -{0x1F32,0x1F3A}, -{0x1F33,0x1F3B}, -{0x1F34,0x1F3C}, -{0x1F35,0x1F3D}, -{0x1F36,0x1F3E}, -{0x1F37,0x1F3F}, -{0x1F40,0x1F48}, -{0x1F41,0x1F49}, -{0x1F42,0x1F4A}, -{0x1F43,0x1F4B}, -{0x1F44,0x1F4C}, -{0x1F45,0x1F4D}, -{0x1F51,0x1F59}, -{0x1F53,0x1F5B}, -{0x1F55,0x1F5D}, -{0x1F57,0x1F5F}, -{0x1F60,0x1F68}, -{0x1F61,0x1F69}, -{0x1F62,0x1F6A}, -{0x1F63,0x1F6B}, -{0x1F64,0x1F6C}, -{0x1F65,0x1F6D}, -{0x1F66,0x1F6E}, -{0x1F67,0x1F6F}, -{0x1F80,0x1F88}, -{0x1F81,0x1F89}, -{0x1F82,0x1F8A}, -{0x1F83,0x1F8B}, -{0x1F84,0x1F8C}, -{0x1F85,0x1F8D}, -{0x1F86,0x1F8E}, -{0x1F87,0x1F8F}, -{0x1F90,0x1F98}, -{0x1F91,0x1F99}, -{0x1F92,0x1F9A}, -{0x1F93,0x1F9B}, -{0x1F94,0x1F9C}, -{0x1F95,0x1F9D}, -{0x1F96,0x1F9E}, -{0x1F97,0x1F9F}, -{0x1FA0,0x1FA8}, -{0x1FA1,0x1FA9}, -{0x1FA2,0x1FAA}, -{0x1FA3,0x1FAB}, -{0x1FA4,0x1FAC}, -{0x1FA5,0x1FAD}, -{0x1FA6,0x1FAE}, -{0x1FA7,0x1FAF}, -{0x1FB0,0x1FB8}, -{0x1FB1,0x1FB9}, -{0x1FD0,0x1FD8}, -{0x1FD1,0x1FD9}, -{0x1FE0,0x1FE8}, -{0x1FE1,0x1FE9}, -{0x24D0,0x24B6}, -{0x24D1,0x24B7}, -{0x24D2,0x24B8}, -{0x24D3,0x24B9}, -{0x24D4,0x24BA}, -{0x24D5,0x24BB}, -{0x24D6,0x24BC}, -{0x24D7,0x24BD}, -{0x24D8,0x24BE}, -{0x24D9,0x24BF}, -{0x24DA,0x24C0}, -{0x24DB,0x24C1}, -{0x24DC,0x24C2}, -{0x24DD,0x24C3}, -{0x24DE,0x24C4}, -{0x24DF,0x24C5}, -{0x24E0,0x24C6}, -{0x24E1,0x24C7}, -{0x24E2,0x24C8}, -{0x24E3,0x24C9}, -{0x24E4,0x24CA}, -{0x24E5,0x24CB}, -{0x24E6,0x24CC}, -{0x24E7,0x24CD}, -{0x24E8,0x24CE}, -{0x24E9,0x24CF}, -{0xFF41,0xFF21}, -{0xFF42,0xFF22}, -{0xFF43,0xFF23}, -{0xFF44,0xFF24}, -{0xFF45,0xFF25}, -{0xFF46,0xFF26}, -{0xFF47,0xFF27}, -{0xFF48,0xFF28}, -{0xFF49,0xFF29}, -{0xFF4A,0xFF2A}, -{0xFF4B,0xFF2B}, -{0xFF4C,0xFF2C}, -{0xFF4D,0xFF2D}, -{0xFF4E,0xFF2E}, -{0xFF4F,0xFF2F}, -{0xFF50,0xFF30}, -{0xFF51,0xFF31}, -{0xFF52,0xFF32}, -{0xFF53,0xFF33}, -{0xFF54,0xFF34}, -{0xFF55,0xFF35}, -{0xFF56,0xFF36}, -{0xFF57,0xFF37}, -{0xFF58,0xFF38}, -{0xFF59,0xFF39}, -{0xFF5A,0xFF3A}, +static const int caps_table[CAPS_LEN][2] = { + { 0x0061, 0x0041 }, + { 0x0062, 0x0042 }, + { 0x0063, 0x0043 }, + { 0x0064, 0x0044 }, + { 0x0065, 0x0045 }, + { 0x0066, 0x0046 }, + { 0x0067, 0x0047 }, + { 0x0068, 0x0048 }, + { 0x0069, 0x0049 }, + { 0x006A, 0x004A }, + { 0x006B, 0x004B }, + { 0x006C, 0x004C }, + { 0x006D, 0x004D }, + { 0x006E, 0x004E }, + { 0x006F, 0x004F }, + { 0x0070, 0x0050 }, + { 0x0071, 0x0051 }, + { 0x0072, 0x0052 }, + { 0x0073, 0x0053 }, + { 0x0074, 0x0054 }, + { 0x0075, 0x0055 }, + { 0x0076, 0x0056 }, + { 0x0077, 0x0057 }, + { 0x0078, 0x0058 }, + { 0x0079, 0x0059 }, + { 0x007A, 0x005A }, + { 0x00E0, 0x00C0 }, + { 0x00E1, 0x00C1 }, + { 0x00E2, 0x00C2 }, + { 0x00E3, 0x00C3 }, + { 0x00E4, 0x00C4 }, + { 0x00E5, 0x00C5 }, + { 0x00E6, 0x00C6 }, + { 0x00E7, 0x00C7 }, + { 0x00E8, 0x00C8 }, + { 0x00E9, 0x00C9 }, + { 0x00EA, 0x00CA }, + { 0x00EB, 0x00CB }, + { 0x00EC, 0x00CC }, + { 0x00ED, 0x00CD }, + { 0x00EE, 0x00CE }, + { 0x00EF, 0x00CF }, + { 0x00F0, 0x00D0 }, + { 0x00F1, 0x00D1 }, + { 0x00F2, 0x00D2 }, + { 0x00F3, 0x00D3 }, + { 0x00F4, 0x00D4 }, + { 0x00F5, 0x00D5 }, + { 0x00F6, 0x00D6 }, + { 0x00F8, 0x00D8 }, + { 0x00F9, 0x00D9 }, + { 0x00FA, 0x00DA }, + { 0x00FB, 0x00DB }, + { 0x00FC, 0x00DC }, + { 0x00FD, 0x00DD }, + { 0x00FE, 0x00DE }, + { 0x00FF, 0x0178 }, + { 0x0101, 0x0100 }, + { 0x0103, 0x0102 }, + { 0x0105, 0x0104 }, + { 0x0107, 0x0106 }, + { 0x0109, 0x0108 }, + { 0x010B, 0x010A }, + { 0x010D, 0x010C }, + { 0x010F, 0x010E }, + { 0x0111, 0x0110 }, + { 0x0113, 0x0112 }, + { 0x0115, 0x0114 }, + { 0x0117, 0x0116 }, + { 0x0119, 0x0118 }, + { 0x011B, 0x011A }, + { 0x011D, 0x011C }, + { 0x011F, 0x011E }, + { 0x0121, 0x0120 }, + { 0x0123, 0x0122 }, + { 0x0125, 0x0124 }, + { 0x0127, 0x0126 }, + { 0x0129, 0x0128 }, + { 0x012B, 0x012A }, + { 0x012D, 0x012C }, + { 0x012F, 0x012E }, + { 0x0131, 0x0049 }, + { 0x0133, 0x0132 }, + { 0x0135, 0x0134 }, + { 0x0137, 0x0136 }, + { 0x013A, 0x0139 }, + { 0x013C, 0x013B }, + { 0x013E, 0x013D }, + { 0x0140, 0x013F }, + { 0x0142, 0x0141 }, + { 0x0144, 0x0143 }, + { 0x0146, 0x0145 }, + { 0x0148, 0x0147 }, + { 0x014B, 0x014A }, + { 0x014D, 0x014C }, + { 0x014F, 0x014E }, + { 0x0151, 0x0150 }, + { 0x0153, 0x0152 }, + { 0x0155, 0x0154 }, + { 0x0157, 0x0156 }, + { 0x0159, 0x0158 }, + { 0x015B, 0x015A }, + { 0x015D, 0x015C }, + { 0x015F, 0x015E }, + { 0x0161, 0x0160 }, + { 0x0163, 0x0162 }, + { 0x0165, 0x0164 }, + { 0x0167, 0x0166 }, + { 0x0169, 0x0168 }, + { 0x016B, 0x016A }, + { 0x016D, 0x016C }, + { 0x016F, 0x016E }, + { 0x0171, 0x0170 }, + { 0x0173, 0x0172 }, + { 0x0175, 0x0174 }, + { 0x0177, 0x0176 }, + { 0x017A, 0x0179 }, + { 0x017C, 0x017B }, + { 0x017E, 0x017D }, + { 0x0183, 0x0182 }, + { 0x0185, 0x0184 }, + { 0x0188, 0x0187 }, + { 0x018C, 0x018B }, + { 0x0192, 0x0191 }, + { 0x0199, 0x0198 }, + { 0x01A1, 0x01A0 }, + { 0x01A3, 0x01A2 }, + { 0x01A5, 0x01A4 }, + { 0x01A8, 0x01A7 }, + { 0x01AD, 0x01AC }, + { 0x01B0, 0x01AF }, + { 0x01B4, 0x01B3 }, + { 0x01B6, 0x01B5 }, + { 0x01B9, 0x01B8 }, + { 0x01BD, 0x01BC }, + { 0x01C6, 0x01C4 }, + { 0x01C9, 0x01C7 }, + { 0x01CC, 0x01CA }, + { 0x01CE, 0x01CD }, + { 0x01D0, 0x01CF }, + { 0x01D2, 0x01D1 }, + { 0x01D4, 0x01D3 }, + { 0x01D6, 0x01D5 }, + { 0x01D8, 0x01D7 }, + { 0x01DA, 0x01D9 }, + { 0x01DC, 0x01DB }, + { 0x01DF, 0x01DE }, + { 0x01E1, 0x01E0 }, + { 0x01E3, 0x01E2 }, + { 0x01E5, 0x01E4 }, + { 0x01E7, 0x01E6 }, + { 0x01E9, 0x01E8 }, + { 0x01EB, 0x01EA }, + { 0x01ED, 0x01EC }, + { 0x01EF, 0x01EE }, + { 0x01F3, 0x01F1 }, + { 0x01F5, 0x01F4 }, + { 0x01FB, 0x01FA }, + { 0x01FD, 0x01FC }, + { 0x01FF, 0x01FE }, + { 0x0201, 0x0200 }, + { 0x0203, 0x0202 }, + { 0x0205, 0x0204 }, + { 0x0207, 0x0206 }, + { 0x0209, 0x0208 }, + { 0x020B, 0x020A }, + { 0x020D, 0x020C }, + { 0x020F, 0x020E }, + { 0x0211, 0x0210 }, + { 0x0213, 0x0212 }, + { 0x0215, 0x0214 }, + { 0x0217, 0x0216 }, + { 0x0253, 0x0181 }, + { 0x0254, 0x0186 }, + { 0x0257, 0x018A }, + { 0x0258, 0x018E }, + { 0x0259, 0x018F }, + { 0x025B, 0x0190 }, + { 0x0260, 0x0193 }, + { 0x0263, 0x0194 }, + { 0x0268, 0x0197 }, + { 0x0269, 0x0196 }, + { 0x026F, 0x019C }, + { 0x0272, 0x019D }, + { 0x0275, 0x019F }, + { 0x0283, 0x01A9 }, + { 0x0288, 0x01AE }, + { 0x028A, 0x01B1 }, + { 0x028B, 0x01B2 }, + { 0x0292, 0x01B7 }, + { 0x03AC, 0x0386 }, + { 0x03AD, 0x0388 }, + { 0x03AE, 0x0389 }, + { 0x03AF, 0x038A }, + { 0x03B1, 0x0391 }, + { 0x03B2, 0x0392 }, + { 0x03B3, 0x0393 }, + { 0x03B4, 0x0394 }, + { 0x03B5, 0x0395 }, + { 0x03B6, 0x0396 }, + { 0x03B7, 0x0397 }, + { 0x03B8, 0x0398 }, + { 0x03B9, 0x0399 }, + { 0x03BA, 0x039A }, + { 0x03BB, 0x039B }, + { 0x03BC, 0x039C }, + { 0x03BD, 0x039D }, + { 0x03BE, 0x039E }, + { 0x03BF, 0x039F }, + { 0x03C0, 0x03A0 }, + { 0x03C1, 0x03A1 }, + { 0x03C3, 0x03A3 }, + { 0x03C4, 0x03A4 }, + { 0x03C5, 0x03A5 }, + { 0x03C6, 0x03A6 }, + { 0x03C7, 0x03A7 }, + { 0x03C8, 0x03A8 }, + { 0x03C9, 0x03A9 }, + { 0x03CA, 0x03AA }, + { 0x03CB, 0x03AB }, + { 0x03CC, 0x038C }, + { 0x03CD, 0x038E }, + { 0x03CE, 0x038F }, + { 0x03E3, 0x03E2 }, + { 0x03E5, 0x03E4 }, + { 0x03E7, 0x03E6 }, + { 0x03E9, 0x03E8 }, + { 0x03EB, 0x03EA }, + { 0x03ED, 0x03EC }, + { 0x03EF, 0x03EE }, + { 0x0430, 0x0410 }, + { 0x0431, 0x0411 }, + { 0x0432, 0x0412 }, + { 0x0433, 0x0413 }, + { 0x0434, 0x0414 }, + { 0x0435, 0x0415 }, + { 0x0436, 0x0416 }, + { 0x0437, 0x0417 }, + { 0x0438, 0x0418 }, + { 0x0439, 0x0419 }, + { 0x043A, 0x041A }, + { 0x043B, 0x041B }, + { 0x043C, 0x041C }, + { 0x043D, 0x041D }, + { 0x043E, 0x041E }, + { 0x043F, 0x041F }, + { 0x0440, 0x0420 }, + { 0x0441, 0x0421 }, + { 0x0442, 0x0422 }, + { 0x0443, 0x0423 }, + { 0x0444, 0x0424 }, + { 0x0445, 0x0425 }, + { 0x0446, 0x0426 }, + { 0x0447, 0x0427 }, + { 0x0448, 0x0428 }, + { 0x0449, 0x0429 }, + { 0x044A, 0x042A }, + { 0x044B, 0x042B }, + { 0x044C, 0x042C }, + { 0x044D, 0x042D }, + { 0x044E, 0x042E }, + { 0x044F, 0x042F }, + { 0x0451, 0x0401 }, + { 0x0452, 0x0402 }, + { 0x0453, 0x0403 }, + { 0x0454, 0x0404 }, + { 0x0455, 0x0405 }, + { 0x0456, 0x0406 }, + { 0x0457, 0x0407 }, + { 0x0458, 0x0408 }, + { 0x0459, 0x0409 }, + { 0x045A, 0x040A }, + { 0x045B, 0x040B }, + { 0x045C, 0x040C }, + { 0x045E, 0x040E }, + { 0x045F, 0x040F }, + { 0x0461, 0x0460 }, + { 0x0463, 0x0462 }, + { 0x0465, 0x0464 }, + { 0x0467, 0x0466 }, + { 0x0469, 0x0468 }, + { 0x046B, 0x046A }, + { 0x046D, 0x046C }, + { 0x046F, 0x046E }, + { 0x0471, 0x0470 }, + { 0x0473, 0x0472 }, + { 0x0475, 0x0474 }, + { 0x0477, 0x0476 }, + { 0x0479, 0x0478 }, + { 0x047B, 0x047A }, + { 0x047D, 0x047C }, + { 0x047F, 0x047E }, + { 0x0481, 0x0480 }, + { 0x0491, 0x0490 }, + { 0x0493, 0x0492 }, + { 0x0495, 0x0494 }, + { 0x0497, 0x0496 }, + { 0x0499, 0x0498 }, + { 0x049B, 0x049A }, + { 0x049D, 0x049C }, + { 0x049F, 0x049E }, + { 0x04A1, 0x04A0 }, + { 0x04A3, 0x04A2 }, + { 0x04A5, 0x04A4 }, + { 0x04A7, 0x04A6 }, + { 0x04A9, 0x04A8 }, + { 0x04AB, 0x04AA }, + { 0x04AD, 0x04AC }, + { 0x04AF, 0x04AE }, + { 0x04B1, 0x04B0 }, + { 0x04B3, 0x04B2 }, + { 0x04B5, 0x04B4 }, + { 0x04B7, 0x04B6 }, + { 0x04B9, 0x04B8 }, + { 0x04BB, 0x04BA }, + { 0x04BD, 0x04BC }, + { 0x04BF, 0x04BE }, + { 0x04C2, 0x04C1 }, + { 0x04C4, 0x04C3 }, + { 0x04C8, 0x04C7 }, + { 0x04CC, 0x04CB }, + { 0x04D1, 0x04D0 }, + { 0x04D3, 0x04D2 }, + { 0x04D5, 0x04D4 }, + { 0x04D7, 0x04D6 }, + { 0x04D9, 0x04D8 }, + { 0x04DB, 0x04DA }, + { 0x04DD, 0x04DC }, + { 0x04DF, 0x04DE }, + { 0x04E1, 0x04E0 }, + { 0x04E3, 0x04E2 }, + { 0x04E5, 0x04E4 }, + { 0x04E7, 0x04E6 }, + { 0x04E9, 0x04E8 }, + { 0x04EB, 0x04EA }, + { 0x04EF, 0x04EE }, + { 0x04F1, 0x04F0 }, + { 0x04F3, 0x04F2 }, + { 0x04F5, 0x04F4 }, + { 0x04F9, 0x04F8 }, + { 0x0561, 0x0531 }, + { 0x0562, 0x0532 }, + { 0x0563, 0x0533 }, + { 0x0564, 0x0534 }, + { 0x0565, 0x0535 }, + { 0x0566, 0x0536 }, + { 0x0567, 0x0537 }, + { 0x0568, 0x0538 }, + { 0x0569, 0x0539 }, + { 0x056A, 0x053A }, + { 0x056B, 0x053B }, + { 0x056C, 0x053C }, + { 0x056D, 0x053D }, + { 0x056E, 0x053E }, + { 0x056F, 0x053F }, + { 0x0570, 0x0540 }, + { 0x0571, 0x0541 }, + { 0x0572, 0x0542 }, + { 0x0573, 0x0543 }, + { 0x0574, 0x0544 }, + { 0x0575, 0x0545 }, + { 0x0576, 0x0546 }, + { 0x0577, 0x0547 }, + { 0x0578, 0x0548 }, + { 0x0579, 0x0549 }, + { 0x057A, 0x054A }, + { 0x057B, 0x054B }, + { 0x057C, 0x054C }, + { 0x057D, 0x054D }, + { 0x057E, 0x054E }, + { 0x057F, 0x054F }, + { 0x0580, 0x0550 }, + { 0x0581, 0x0551 }, + { 0x0582, 0x0552 }, + { 0x0583, 0x0553 }, + { 0x0584, 0x0554 }, + { 0x0585, 0x0555 }, + { 0x0586, 0x0556 }, + { 0x10D0, 0x10A0 }, + { 0x10D1, 0x10A1 }, + { 0x10D2, 0x10A2 }, + { 0x10D3, 0x10A3 }, + { 0x10D4, 0x10A4 }, + { 0x10D5, 0x10A5 }, + { 0x10D6, 0x10A6 }, + { 0x10D7, 0x10A7 }, + { 0x10D8, 0x10A8 }, + { 0x10D9, 0x10A9 }, + { 0x10DA, 0x10AA }, + { 0x10DB, 0x10AB }, + { 0x10DC, 0x10AC }, + { 0x10DD, 0x10AD }, + { 0x10DE, 0x10AE }, + { 0x10DF, 0x10AF }, + { 0x10E0, 0x10B0 }, + { 0x10E1, 0x10B1 }, + { 0x10E2, 0x10B2 }, + { 0x10E3, 0x10B3 }, + { 0x10E4, 0x10B4 }, + { 0x10E5, 0x10B5 }, + { 0x10E6, 0x10B6 }, + { 0x10E7, 0x10B7 }, + { 0x10E8, 0x10B8 }, + { 0x10E9, 0x10B9 }, + { 0x10EA, 0x10BA }, + { 0x10EB, 0x10BB }, + { 0x10EC, 0x10BC }, + { 0x10ED, 0x10BD }, + { 0x10EE, 0x10BE }, + { 0x10EF, 0x10BF }, + { 0x10F0, 0x10C0 }, + { 0x10F1, 0x10C1 }, + { 0x10F2, 0x10C2 }, + { 0x10F3, 0x10C3 }, + { 0x10F4, 0x10C4 }, + { 0x10F5, 0x10C5 }, + { 0x1E01, 0x1E00 }, + { 0x1E03, 0x1E02 }, + { 0x1E05, 0x1E04 }, + { 0x1E07, 0x1E06 }, + { 0x1E09, 0x1E08 }, + { 0x1E0B, 0x1E0A }, + { 0x1E0D, 0x1E0C }, + { 0x1E0F, 0x1E0E }, + { 0x1E11, 0x1E10 }, + { 0x1E13, 0x1E12 }, + { 0x1E15, 0x1E14 }, + { 0x1E17, 0x1E16 }, + { 0x1E19, 0x1E18 }, + { 0x1E1B, 0x1E1A }, + { 0x1E1D, 0x1E1C }, + { 0x1E1F, 0x1E1E }, + { 0x1E21, 0x1E20 }, + { 0x1E23, 0x1E22 }, + { 0x1E25, 0x1E24 }, + { 0x1E27, 0x1E26 }, + { 0x1E29, 0x1E28 }, + { 0x1E2B, 0x1E2A }, + { 0x1E2D, 0x1E2C }, + { 0x1E2F, 0x1E2E }, + { 0x1E31, 0x1E30 }, + { 0x1E33, 0x1E32 }, + { 0x1E35, 0x1E34 }, + { 0x1E37, 0x1E36 }, + { 0x1E39, 0x1E38 }, + { 0x1E3B, 0x1E3A }, + { 0x1E3D, 0x1E3C }, + { 0x1E3F, 0x1E3E }, + { 0x1E41, 0x1E40 }, + { 0x1E43, 0x1E42 }, + { 0x1E45, 0x1E44 }, + { 0x1E47, 0x1E46 }, + { 0x1E49, 0x1E48 }, + { 0x1E4B, 0x1E4A }, + { 0x1E4D, 0x1E4C }, + { 0x1E4F, 0x1E4E }, + { 0x1E51, 0x1E50 }, + { 0x1E53, 0x1E52 }, + { 0x1E55, 0x1E54 }, + { 0x1E57, 0x1E56 }, + { 0x1E59, 0x1E58 }, + { 0x1E5B, 0x1E5A }, + { 0x1E5D, 0x1E5C }, + { 0x1E5F, 0x1E5E }, + { 0x1E61, 0x1E60 }, + { 0x1E63, 0x1E62 }, + { 0x1E65, 0x1E64 }, + { 0x1E67, 0x1E66 }, + { 0x1E69, 0x1E68 }, + { 0x1E6B, 0x1E6A }, + { 0x1E6D, 0x1E6C }, + { 0x1E6F, 0x1E6E }, + { 0x1E71, 0x1E70 }, + { 0x1E73, 0x1E72 }, + { 0x1E75, 0x1E74 }, + { 0x1E77, 0x1E76 }, + { 0x1E79, 0x1E78 }, + { 0x1E7B, 0x1E7A }, + { 0x1E7D, 0x1E7C }, + { 0x1E7F, 0x1E7E }, + { 0x1E81, 0x1E80 }, + { 0x1E83, 0x1E82 }, + { 0x1E85, 0x1E84 }, + { 0x1E87, 0x1E86 }, + { 0x1E89, 0x1E88 }, + { 0x1E8B, 0x1E8A }, + { 0x1E8D, 0x1E8C }, + { 0x1E8F, 0x1E8E }, + { 0x1E91, 0x1E90 }, + { 0x1E93, 0x1E92 }, + { 0x1E95, 0x1E94 }, + { 0x1EA1, 0x1EA0 }, + { 0x1EA3, 0x1EA2 }, + { 0x1EA5, 0x1EA4 }, + { 0x1EA7, 0x1EA6 }, + { 0x1EA9, 0x1EA8 }, + { 0x1EAB, 0x1EAA }, + { 0x1EAD, 0x1EAC }, + { 0x1EAF, 0x1EAE }, + { 0x1EB1, 0x1EB0 }, + { 0x1EB3, 0x1EB2 }, + { 0x1EB5, 0x1EB4 }, + { 0x1EB7, 0x1EB6 }, + { 0x1EB9, 0x1EB8 }, + { 0x1EBB, 0x1EBA }, + { 0x1EBD, 0x1EBC }, + { 0x1EBF, 0x1EBE }, + { 0x1EC1, 0x1EC0 }, + { 0x1EC3, 0x1EC2 }, + { 0x1EC5, 0x1EC4 }, + { 0x1EC7, 0x1EC6 }, + { 0x1EC9, 0x1EC8 }, + { 0x1ECB, 0x1ECA }, + { 0x1ECD, 0x1ECC }, + { 0x1ECF, 0x1ECE }, + { 0x1ED1, 0x1ED0 }, + { 0x1ED3, 0x1ED2 }, + { 0x1ED5, 0x1ED4 }, + { 0x1ED7, 0x1ED6 }, + { 0x1ED9, 0x1ED8 }, + { 0x1EDB, 0x1EDA }, + { 0x1EDD, 0x1EDC }, + { 0x1EDF, 0x1EDE }, + { 0x1EE1, 0x1EE0 }, + { 0x1EE3, 0x1EE2 }, + { 0x1EE5, 0x1EE4 }, + { 0x1EE7, 0x1EE6 }, + { 0x1EE9, 0x1EE8 }, + { 0x1EEB, 0x1EEA }, + { 0x1EED, 0x1EEC }, + { 0x1EEF, 0x1EEE }, + { 0x1EF1, 0x1EF0 }, + { 0x1EF3, 0x1EF2 }, + { 0x1EF5, 0x1EF4 }, + { 0x1EF7, 0x1EF6 }, + { 0x1EF9, 0x1EF8 }, + { 0x1F00, 0x1F08 }, + { 0x1F01, 0x1F09 }, + { 0x1F02, 0x1F0A }, + { 0x1F03, 0x1F0B }, + { 0x1F04, 0x1F0C }, + { 0x1F05, 0x1F0D }, + { 0x1F06, 0x1F0E }, + { 0x1F07, 0x1F0F }, + { 0x1F10, 0x1F18 }, + { 0x1F11, 0x1F19 }, + { 0x1F12, 0x1F1A }, + { 0x1F13, 0x1F1B }, + { 0x1F14, 0x1F1C }, + { 0x1F15, 0x1F1D }, + { 0x1F20, 0x1F28 }, + { 0x1F21, 0x1F29 }, + { 0x1F22, 0x1F2A }, + { 0x1F23, 0x1F2B }, + { 0x1F24, 0x1F2C }, + { 0x1F25, 0x1F2D }, + { 0x1F26, 0x1F2E }, + { 0x1F27, 0x1F2F }, + { 0x1F30, 0x1F38 }, + { 0x1F31, 0x1F39 }, + { 0x1F32, 0x1F3A }, + { 0x1F33, 0x1F3B }, + { 0x1F34, 0x1F3C }, + { 0x1F35, 0x1F3D }, + { 0x1F36, 0x1F3E }, + { 0x1F37, 0x1F3F }, + { 0x1F40, 0x1F48 }, + { 0x1F41, 0x1F49 }, + { 0x1F42, 0x1F4A }, + { 0x1F43, 0x1F4B }, + { 0x1F44, 0x1F4C }, + { 0x1F45, 0x1F4D }, + { 0x1F51, 0x1F59 }, + { 0x1F53, 0x1F5B }, + { 0x1F55, 0x1F5D }, + { 0x1F57, 0x1F5F }, + { 0x1F60, 0x1F68 }, + { 0x1F61, 0x1F69 }, + { 0x1F62, 0x1F6A }, + { 0x1F63, 0x1F6B }, + { 0x1F64, 0x1F6C }, + { 0x1F65, 0x1F6D }, + { 0x1F66, 0x1F6E }, + { 0x1F67, 0x1F6F }, + { 0x1F80, 0x1F88 }, + { 0x1F81, 0x1F89 }, + { 0x1F82, 0x1F8A }, + { 0x1F83, 0x1F8B }, + { 0x1F84, 0x1F8C }, + { 0x1F85, 0x1F8D }, + { 0x1F86, 0x1F8E }, + { 0x1F87, 0x1F8F }, + { 0x1F90, 0x1F98 }, + { 0x1F91, 0x1F99 }, + { 0x1F92, 0x1F9A }, + { 0x1F93, 0x1F9B }, + { 0x1F94, 0x1F9C }, + { 0x1F95, 0x1F9D }, + { 0x1F96, 0x1F9E }, + { 0x1F97, 0x1F9F }, + { 0x1FA0, 0x1FA8 }, + { 0x1FA1, 0x1FA9 }, + { 0x1FA2, 0x1FAA }, + { 0x1FA3, 0x1FAB }, + { 0x1FA4, 0x1FAC }, + { 0x1FA5, 0x1FAD }, + { 0x1FA6, 0x1FAE }, + { 0x1FA7, 0x1FAF }, + { 0x1FB0, 0x1FB8 }, + { 0x1FB1, 0x1FB9 }, + { 0x1FD0, 0x1FD8 }, + { 0x1FD1, 0x1FD9 }, + { 0x1FE0, 0x1FE8 }, + { 0x1FE1, 0x1FE9 }, + { 0x24D0, 0x24B6 }, + { 0x24D1, 0x24B7 }, + { 0x24D2, 0x24B8 }, + { 0x24D3, 0x24B9 }, + { 0x24D4, 0x24BA }, + { 0x24D5, 0x24BB }, + { 0x24D6, 0x24BC }, + { 0x24D7, 0x24BD }, + { 0x24D8, 0x24BE }, + { 0x24D9, 0x24BF }, + { 0x24DA, 0x24C0 }, + { 0x24DB, 0x24C1 }, + { 0x24DC, 0x24C2 }, + { 0x24DD, 0x24C3 }, + { 0x24DE, 0x24C4 }, + { 0x24DF, 0x24C5 }, + { 0x24E0, 0x24C6 }, + { 0x24E1, 0x24C7 }, + { 0x24E2, 0x24C8 }, + { 0x24E3, 0x24C9 }, + { 0x24E4, 0x24CA }, + { 0x24E5, 0x24CB }, + { 0x24E6, 0x24CC }, + { 0x24E7, 0x24CD }, + { 0x24E8, 0x24CE }, + { 0x24E9, 0x24CF }, + { 0xFF41, 0xFF21 }, + { 0xFF42, 0xFF22 }, + { 0xFF43, 0xFF23 }, + { 0xFF44, 0xFF24 }, + { 0xFF45, 0xFF25 }, + { 0xFF46, 0xFF26 }, + { 0xFF47, 0xFF27 }, + { 0xFF48, 0xFF28 }, + { 0xFF49, 0xFF29 }, + { 0xFF4A, 0xFF2A }, + { 0xFF4B, 0xFF2B }, + { 0xFF4C, 0xFF2C }, + { 0xFF4D, 0xFF2D }, + { 0xFF4E, 0xFF2E }, + { 0xFF4F, 0xFF2F }, + { 0xFF50, 0xFF30 }, + { 0xFF51, 0xFF31 }, + { 0xFF52, 0xFF32 }, + { 0xFF53, 0xFF33 }, + { 0xFF54, 0xFF34 }, + { 0xFF55, 0xFF35 }, + { 0xFF56, 0xFF36 }, + { 0xFF57, 0xFF37 }, + { 0xFF58, 0xFF38 }, + { 0xFF59, 0xFF39 }, + { 0xFF5A, 0xFF3A }, }; -static const int reverse_caps_table[CAPS_LEN-1][2]={ -{0x41,0x61}, -{0x42,0x62}, -{0x43,0x63}, -{0x44,0x64}, -{0x45,0x65}, -{0x46,0x66}, -{0x47,0x67}, -{0x48,0x68}, -{0x49,0x69}, -{0x4a,0x6a}, -{0x4b,0x6b}, -{0x4c,0x6c}, -{0x4d,0x6d}, -{0x4e,0x6e}, -{0x4f,0x6f}, -{0x50,0x70}, -{0x51,0x71}, -{0x52,0x72}, -{0x53,0x73}, -{0x54,0x74}, -{0x55,0x75}, -{0x56,0x76}, -{0x57,0x77}, -{0x58,0x78}, -{0x59,0x79}, -{0x5a,0x7a}, -{0xc0,0xe0}, -{0xc1,0xe1}, -{0xc2,0xe2}, -{0xc3,0xe3}, -{0xc4,0xe4}, -{0xc5,0xe5}, -{0xc6,0xe6}, -{0xc7,0xe7}, -{0xc8,0xe8}, -{0xc9,0xe9}, -{0xca,0xea}, -{0xcb,0xeb}, -{0xcc,0xec}, -{0xcd,0xed}, -{0xce,0xee}, -{0xcf,0xef}, -{0xd0,0xf0}, -{0xd1,0xf1}, -{0xd2,0xf2}, -{0xd3,0xf3}, -{0xd4,0xf4}, -{0xd5,0xf5}, -{0xd6,0xf6}, -{0xd8,0xf8}, -{0xd9,0xf9}, -{0xda,0xfa}, -{0xdb,0xfb}, -{0xdc,0xfc}, -{0xdd,0xfd}, -{0xde,0xfe}, -{0x178,0xff}, -{0x100,0x101}, -{0x102,0x103}, -{0x104,0x105}, -{0x106,0x107}, -{0x108,0x109}, -{0x10a,0x10b}, -{0x10c,0x10d}, -{0x10e,0x10f}, -{0x110,0x111}, -{0x112,0x113}, -{0x114,0x115}, -{0x116,0x117}, -{0x118,0x119}, -{0x11a,0x11b}, -{0x11c,0x11d}, -{0x11e,0x11f}, -{0x120,0x121}, -{0x122,0x123}, -{0x124,0x125}, -{0x126,0x127}, -{0x128,0x129}, -{0x12a,0x12b}, -{0x12c,0x12d}, -{0x12e,0x12f}, -//{0x49,0x131}, -{0x132,0x133}, -{0x134,0x135}, -{0x136,0x137}, -{0x139,0x13a}, -{0x13b,0x13c}, -{0x13d,0x13e}, -{0x13f,0x140}, -{0x141,0x142}, -{0x143,0x144}, -{0x145,0x146}, -{0x147,0x148}, -{0x14a,0x14b}, -{0x14c,0x14d}, -{0x14e,0x14f}, -{0x150,0x151}, -{0x152,0x153}, -{0x154,0x155}, -{0x156,0x157}, -{0x158,0x159}, -{0x15a,0x15b}, -{0x15c,0x15d}, -{0x15e,0x15f}, -{0x160,0x161}, -{0x162,0x163}, -{0x164,0x165}, -{0x166,0x167}, -{0x168,0x169}, -{0x16a,0x16b}, -{0x16c,0x16d}, -{0x16e,0x16f}, -{0x170,0x171}, -{0x172,0x173}, -{0x174,0x175}, -{0x176,0x177}, -{0x179,0x17a}, -{0x17b,0x17c}, -{0x17d,0x17e}, -{0x182,0x183}, -{0x184,0x185}, -{0x187,0x188}, -{0x18b,0x18c}, -{0x191,0x192}, -{0x198,0x199}, -{0x1a0,0x1a1}, -{0x1a2,0x1a3}, -{0x1a4,0x1a5}, -{0x1a7,0x1a8}, -{0x1ac,0x1ad}, -{0x1af,0x1b0}, -{0x1b3,0x1b4}, -{0x1b5,0x1b6}, -{0x1b8,0x1b9}, -{0x1bc,0x1bd}, -{0x1c4,0x1c6}, -{0x1c7,0x1c9}, -{0x1ca,0x1cc}, -{0x1cd,0x1ce}, -{0x1cf,0x1d0}, -{0x1d1,0x1d2}, -{0x1d3,0x1d4}, -{0x1d5,0x1d6}, -{0x1d7,0x1d8}, -{0x1d9,0x1da}, -{0x1db,0x1dc}, -{0x1de,0x1df}, -{0x1e0,0x1e1}, -{0x1e2,0x1e3}, -{0x1e4,0x1e5}, -{0x1e6,0x1e7}, -{0x1e8,0x1e9}, -{0x1ea,0x1eb}, -{0x1ec,0x1ed}, -{0x1ee,0x1ef}, -{0x1f1,0x1f3}, -{0x1f4,0x1f5}, -{0x1fa,0x1fb}, -{0x1fc,0x1fd}, -{0x1fe,0x1ff}, -{0x200,0x201}, -{0x202,0x203}, -{0x204,0x205}, -{0x206,0x207}, -{0x208,0x209}, -{0x20a,0x20b}, -{0x20c,0x20d}, -{0x20e,0x20f}, -{0x210,0x211}, -{0x212,0x213}, -{0x214,0x215}, -{0x216,0x217}, -{0x181,0x253}, -{0x186,0x254}, -{0x18a,0x257}, -{0x18e,0x258}, -{0x18f,0x259}, -{0x190,0x25b}, -{0x193,0x260}, -{0x194,0x263}, -{0x197,0x268}, -{0x196,0x269}, -{0x19c,0x26f}, -{0x19d,0x272}, -{0x19f,0x275}, -{0x1a9,0x283}, -{0x1ae,0x288}, -{0x1b1,0x28a}, -{0x1b2,0x28b}, -{0x1b7,0x292}, -{0x386,0x3ac}, -{0x388,0x3ad}, -{0x389,0x3ae}, -{0x38a,0x3af}, -{0x391,0x3b1}, -{0x392,0x3b2}, -{0x393,0x3b3}, -{0x394,0x3b4}, -{0x395,0x3b5}, -{0x396,0x3b6}, -{0x397,0x3b7}, -{0x398,0x3b8}, -{0x399,0x3b9}, -{0x39a,0x3ba}, -{0x39b,0x3bb}, -{0x39c,0x3bc}, -{0x39d,0x3bd}, -{0x39e,0x3be}, -{0x39f,0x3bf}, -{0x3a0,0x3c0}, -{0x3a1,0x3c1}, -{0x3a3,0x3c3}, -{0x3a4,0x3c4}, -{0x3a5,0x3c5}, -{0x3a6,0x3c6}, -{0x3a7,0x3c7}, -{0x3a8,0x3c8}, -{0x3a9,0x3c9}, -{0x3aa,0x3ca}, -{0x3ab,0x3cb}, -{0x38c,0x3cc}, -{0x38e,0x3cd}, -{0x38f,0x3ce}, -{0x3e2,0x3e3}, -{0x3e4,0x3e5}, -{0x3e6,0x3e7}, -{0x3e8,0x3e9}, -{0x3ea,0x3eb}, -{0x3ec,0x3ed}, -{0x3ee,0x3ef}, -{0x410,0x430}, -{0x411,0x431}, -{0x412,0x432}, -{0x413,0x433}, -{0x414,0x434}, -{0x415,0x435}, -{0x416,0x436}, -{0x417,0x437}, -{0x418,0x438}, -{0x419,0x439}, -{0x41a,0x43a}, -{0x41b,0x43b}, -{0x41c,0x43c}, -{0x41d,0x43d}, -{0x41e,0x43e}, -{0x41f,0x43f}, -{0x420,0x440}, -{0x421,0x441}, -{0x422,0x442}, -{0x423,0x443}, -{0x424,0x444}, -{0x425,0x445}, -{0x426,0x446}, -{0x427,0x447}, -{0x428,0x448}, -{0x429,0x449}, -{0x42a,0x44a}, -{0x42b,0x44b}, -{0x42c,0x44c}, -{0x42d,0x44d}, -{0x42e,0x44e}, -{0x42f,0x44f}, -{0x401,0x451}, -{0x402,0x452}, -{0x403,0x453}, -{0x404,0x454}, -{0x405,0x455}, -{0x406,0x456}, -{0x407,0x457}, -{0x408,0x458}, -{0x409,0x459}, -{0x40a,0x45a}, -{0x40b,0x45b}, -{0x40c,0x45c}, -{0x40e,0x45e}, -{0x40f,0x45f}, -{0x460,0x461}, -{0x462,0x463}, -{0x464,0x465}, -{0x466,0x467}, -{0x468,0x469}, -{0x46a,0x46b}, -{0x46c,0x46d}, -{0x46e,0x46f}, -{0x470,0x471}, -{0x472,0x473}, -{0x474,0x475}, -{0x476,0x477}, -{0x478,0x479}, -{0x47a,0x47b}, -{0x47c,0x47d}, -{0x47e,0x47f}, -{0x480,0x481}, -{0x490,0x491}, -{0x492,0x493}, -{0x494,0x495}, -{0x496,0x497}, -{0x498,0x499}, -{0x49a,0x49b}, -{0x49c,0x49d}, -{0x49e,0x49f}, -{0x4a0,0x4a1}, -{0x4a2,0x4a3}, -{0x4a4,0x4a5}, -{0x4a6,0x4a7}, -{0x4a8,0x4a9}, -{0x4aa,0x4ab}, -{0x4ac,0x4ad}, -{0x4ae,0x4af}, -{0x4b0,0x4b1}, -{0x4b2,0x4b3}, -{0x4b4,0x4b5}, -{0x4b6,0x4b7}, -{0x4b8,0x4b9}, -{0x4ba,0x4bb}, -{0x4bc,0x4bd}, -{0x4be,0x4bf}, -{0x4c1,0x4c2}, -{0x4c3,0x4c4}, -{0x4c7,0x4c8}, -{0x4cb,0x4cc}, -{0x4d0,0x4d1}, -{0x4d2,0x4d3}, -{0x4d4,0x4d5}, -{0x4d6,0x4d7}, -{0x4d8,0x4d9}, -{0x4da,0x4db}, -{0x4dc,0x4dd}, -{0x4de,0x4df}, -{0x4e0,0x4e1}, -{0x4e2,0x4e3}, -{0x4e4,0x4e5}, -{0x4e6,0x4e7}, -{0x4e8,0x4e9}, -{0x4ea,0x4eb}, -{0x4ee,0x4ef}, -{0x4f0,0x4f1}, -{0x4f2,0x4f3}, -{0x4f4,0x4f5}, -{0x4f8,0x4f9}, -{0x531,0x561}, -{0x532,0x562}, -{0x533,0x563}, -{0x534,0x564}, -{0x535,0x565}, -{0x536,0x566}, -{0x537,0x567}, -{0x538,0x568}, -{0x539,0x569}, -{0x53a,0x56a}, -{0x53b,0x56b}, -{0x53c,0x56c}, -{0x53d,0x56d}, -{0x53e,0x56e}, -{0x53f,0x56f}, -{0x540,0x570}, -{0x541,0x571}, -{0x542,0x572}, -{0x543,0x573}, -{0x544,0x574}, -{0x545,0x575}, -{0x546,0x576}, -{0x547,0x577}, -{0x548,0x578}, -{0x549,0x579}, -{0x54a,0x57a}, -{0x54b,0x57b}, -{0x54c,0x57c}, -{0x54d,0x57d}, -{0x54e,0x57e}, -{0x54f,0x57f}, -{0x550,0x580}, -{0x551,0x581}, -{0x552,0x582}, -{0x553,0x583}, -{0x554,0x584}, -{0x555,0x585}, -{0x556,0x586}, -{0x10a0,0x10d0}, -{0x10a1,0x10d1}, -{0x10a2,0x10d2}, -{0x10a3,0x10d3}, -{0x10a4,0x10d4}, -{0x10a5,0x10d5}, -{0x10a6,0x10d6}, -{0x10a7,0x10d7}, -{0x10a8,0x10d8}, -{0x10a9,0x10d9}, -{0x10aa,0x10da}, -{0x10ab,0x10db}, -{0x10ac,0x10dc}, -{0x10ad,0x10dd}, -{0x10ae,0x10de}, -{0x10af,0x10df}, -{0x10b0,0x10e0}, -{0x10b1,0x10e1}, -{0x10b2,0x10e2}, -{0x10b3,0x10e3}, -{0x10b4,0x10e4}, -{0x10b5,0x10e5}, -{0x10b6,0x10e6}, -{0x10b7,0x10e7}, -{0x10b8,0x10e8}, -{0x10b9,0x10e9}, -{0x10ba,0x10ea}, -{0x10bb,0x10eb}, -{0x10bc,0x10ec}, -{0x10bd,0x10ed}, -{0x10be,0x10ee}, -{0x10bf,0x10ef}, -{0x10c0,0x10f0}, -{0x10c1,0x10f1}, -{0x10c2,0x10f2}, -{0x10c3,0x10f3}, -{0x10c4,0x10f4}, -{0x10c5,0x10f5}, -{0x1e00,0x1e01}, -{0x1e02,0x1e03}, -{0x1e04,0x1e05}, -{0x1e06,0x1e07}, -{0x1e08,0x1e09}, -{0x1e0a,0x1e0b}, -{0x1e0c,0x1e0d}, -{0x1e0e,0x1e0f}, -{0x1e10,0x1e11}, -{0x1e12,0x1e13}, -{0x1e14,0x1e15}, -{0x1e16,0x1e17}, -{0x1e18,0x1e19}, -{0x1e1a,0x1e1b}, -{0x1e1c,0x1e1d}, -{0x1e1e,0x1e1f}, -{0x1e20,0x1e21}, -{0x1e22,0x1e23}, -{0x1e24,0x1e25}, -{0x1e26,0x1e27}, -{0x1e28,0x1e29}, -{0x1e2a,0x1e2b}, -{0x1e2c,0x1e2d}, -{0x1e2e,0x1e2f}, -{0x1e30,0x1e31}, -{0x1e32,0x1e33}, -{0x1e34,0x1e35}, -{0x1e36,0x1e37}, -{0x1e38,0x1e39}, -{0x1e3a,0x1e3b}, -{0x1e3c,0x1e3d}, -{0x1e3e,0x1e3f}, -{0x1e40,0x1e41}, -{0x1e42,0x1e43}, -{0x1e44,0x1e45}, -{0x1e46,0x1e47}, -{0x1e48,0x1e49}, -{0x1e4a,0x1e4b}, -{0x1e4c,0x1e4d}, -{0x1e4e,0x1e4f}, -{0x1e50,0x1e51}, -{0x1e52,0x1e53}, -{0x1e54,0x1e55}, -{0x1e56,0x1e57}, -{0x1e58,0x1e59}, -{0x1e5a,0x1e5b}, -{0x1e5c,0x1e5d}, -{0x1e5e,0x1e5f}, -{0x1e60,0x1e61}, -{0x1e62,0x1e63}, -{0x1e64,0x1e65}, -{0x1e66,0x1e67}, -{0x1e68,0x1e69}, -{0x1e6a,0x1e6b}, -{0x1e6c,0x1e6d}, -{0x1e6e,0x1e6f}, -{0x1e70,0x1e71}, -{0x1e72,0x1e73}, -{0x1e74,0x1e75}, -{0x1e76,0x1e77}, -{0x1e78,0x1e79}, -{0x1e7a,0x1e7b}, -{0x1e7c,0x1e7d}, -{0x1e7e,0x1e7f}, -{0x1e80,0x1e81}, -{0x1e82,0x1e83}, -{0x1e84,0x1e85}, -{0x1e86,0x1e87}, -{0x1e88,0x1e89}, -{0x1e8a,0x1e8b}, -{0x1e8c,0x1e8d}, -{0x1e8e,0x1e8f}, -{0x1e90,0x1e91}, -{0x1e92,0x1e93}, -{0x1e94,0x1e95}, -{0x1ea0,0x1ea1}, -{0x1ea2,0x1ea3}, -{0x1ea4,0x1ea5}, -{0x1ea6,0x1ea7}, -{0x1ea8,0x1ea9}, -{0x1eaa,0x1eab}, -{0x1eac,0x1ead}, -{0x1eae,0x1eaf}, -{0x1eb0,0x1eb1}, -{0x1eb2,0x1eb3}, -{0x1eb4,0x1eb5}, -{0x1eb6,0x1eb7}, -{0x1eb8,0x1eb9}, -{0x1eba,0x1ebb}, -{0x1ebc,0x1ebd}, -{0x1ebe,0x1ebf}, -{0x1ec0,0x1ec1}, -{0x1ec2,0x1ec3}, -{0x1ec4,0x1ec5}, -{0x1ec6,0x1ec7}, -{0x1ec8,0x1ec9}, -{0x1eca,0x1ecb}, -{0x1ecc,0x1ecd}, -{0x1ece,0x1ecf}, -{0x1ed0,0x1ed1}, -{0x1ed2,0x1ed3}, -{0x1ed4,0x1ed5}, -{0x1ed6,0x1ed7}, -{0x1ed8,0x1ed9}, -{0x1eda,0x1edb}, -{0x1edc,0x1edd}, -{0x1ede,0x1edf}, -{0x1ee0,0x1ee1}, -{0x1ee2,0x1ee3}, -{0x1ee4,0x1ee5}, -{0x1ee6,0x1ee7}, -{0x1ee8,0x1ee9}, -{0x1eea,0x1eeb}, -{0x1eec,0x1eed}, -{0x1eee,0x1eef}, -{0x1ef0,0x1ef1}, -{0x1ef2,0x1ef3}, -{0x1ef4,0x1ef5}, -{0x1ef6,0x1ef7}, -{0x1ef8,0x1ef9}, -{0x1f08,0x1f00}, -{0x1f09,0x1f01}, -{0x1f0a,0x1f02}, -{0x1f0b,0x1f03}, -{0x1f0c,0x1f04}, -{0x1f0d,0x1f05}, -{0x1f0e,0x1f06}, -{0x1f0f,0x1f07}, -{0x1f18,0x1f10}, -{0x1f19,0x1f11}, -{0x1f1a,0x1f12}, -{0x1f1b,0x1f13}, -{0x1f1c,0x1f14}, -{0x1f1d,0x1f15}, -{0x1f28,0x1f20}, -{0x1f29,0x1f21}, -{0x1f2a,0x1f22}, -{0x1f2b,0x1f23}, -{0x1f2c,0x1f24}, -{0x1f2d,0x1f25}, -{0x1f2e,0x1f26}, -{0x1f2f,0x1f27}, -{0x1f38,0x1f30}, -{0x1f39,0x1f31}, -{0x1f3a,0x1f32}, -{0x1f3b,0x1f33}, -{0x1f3c,0x1f34}, -{0x1f3d,0x1f35}, -{0x1f3e,0x1f36}, -{0x1f3f,0x1f37}, -{0x1f48,0x1f40}, -{0x1f49,0x1f41}, -{0x1f4a,0x1f42}, -{0x1f4b,0x1f43}, -{0x1f4c,0x1f44}, -{0x1f4d,0x1f45}, -{0x1f59,0x1f51}, -{0x1f5b,0x1f53}, -{0x1f5d,0x1f55}, -{0x1f5f,0x1f57}, -{0x1f68,0x1f60}, -{0x1f69,0x1f61}, -{0x1f6a,0x1f62}, -{0x1f6b,0x1f63}, -{0x1f6c,0x1f64}, -{0x1f6d,0x1f65}, -{0x1f6e,0x1f66}, -{0x1f6f,0x1f67}, -{0x1f88,0x1f80}, -{0x1f89,0x1f81}, -{0x1f8a,0x1f82}, -{0x1f8b,0x1f83}, -{0x1f8c,0x1f84}, -{0x1f8d,0x1f85}, -{0x1f8e,0x1f86}, -{0x1f8f,0x1f87}, -{0x1f98,0x1f90}, -{0x1f99,0x1f91}, -{0x1f9a,0x1f92}, -{0x1f9b,0x1f93}, -{0x1f9c,0x1f94}, -{0x1f9d,0x1f95}, -{0x1f9e,0x1f96}, -{0x1f9f,0x1f97}, -{0x1fa8,0x1fa0}, -{0x1fa9,0x1fa1}, -{0x1faa,0x1fa2}, -{0x1fab,0x1fa3}, -{0x1fac,0x1fa4}, -{0x1fad,0x1fa5}, -{0x1fae,0x1fa6}, -{0x1faf,0x1fa7}, -{0x1fb8,0x1fb0}, -{0x1fb9,0x1fb1}, -{0x1fd8,0x1fd0}, -{0x1fd9,0x1fd1}, -{0x1fe8,0x1fe0}, -{0x1fe9,0x1fe1}, -{0x24b6,0x24d0}, -{0x24b7,0x24d1}, -{0x24b8,0x24d2}, -{0x24b9,0x24d3}, -{0x24ba,0x24d4}, -{0x24bb,0x24d5}, -{0x24bc,0x24d6}, -{0x24bd,0x24d7}, -{0x24be,0x24d8}, -{0x24bf,0x24d9}, -{0x24c0,0x24da}, -{0x24c1,0x24db}, -{0x24c2,0x24dc}, -{0x24c3,0x24dd}, -{0x24c4,0x24de}, -{0x24c5,0x24df}, -{0x24c6,0x24e0}, -{0x24c7,0x24e1}, -{0x24c8,0x24e2}, -{0x24c9,0x24e3}, -{0x24ca,0x24e4}, -{0x24cb,0x24e5}, -{0x24cc,0x24e6}, -{0x24cd,0x24e7}, -{0x24ce,0x24e8}, -{0x24cf,0x24e9}, -{0xff21,0xff41}, -{0xff22,0xff42}, -{0xff23,0xff43}, -{0xff24,0xff44}, -{0xff25,0xff45}, -{0xff26,0xff46}, -{0xff27,0xff47}, -{0xff28,0xff48}, -{0xff29,0xff49}, -{0xff2a,0xff4a}, -{0xff2b,0xff4b}, -{0xff2c,0xff4c}, -{0xff2d,0xff4d}, -{0xff2e,0xff4e}, -{0xff2f,0xff4f}, -{0xff30,0xff50}, -{0xff31,0xff51}, -{0xff32,0xff52}, -{0xff33,0xff53}, -{0xff34,0xff54}, -{0xff35,0xff55}, -{0xff36,0xff56}, -{0xff37,0xff57}, -{0xff38,0xff58}, -{0xff39,0xff59}, -{0xff3a,0xff5a} +static const int reverse_caps_table[CAPS_LEN - 1][2] = { + { 0x41, 0x61 }, + { 0x42, 0x62 }, + { 0x43, 0x63 }, + { 0x44, 0x64 }, + { 0x45, 0x65 }, + { 0x46, 0x66 }, + { 0x47, 0x67 }, + { 0x48, 0x68 }, + { 0x49, 0x69 }, + { 0x4a, 0x6a }, + { 0x4b, 0x6b }, + { 0x4c, 0x6c }, + { 0x4d, 0x6d }, + { 0x4e, 0x6e }, + { 0x4f, 0x6f }, + { 0x50, 0x70 }, + { 0x51, 0x71 }, + { 0x52, 0x72 }, + { 0x53, 0x73 }, + { 0x54, 0x74 }, + { 0x55, 0x75 }, + { 0x56, 0x76 }, + { 0x57, 0x77 }, + { 0x58, 0x78 }, + { 0x59, 0x79 }, + { 0x5a, 0x7a }, + { 0xc0, 0xe0 }, + { 0xc1, 0xe1 }, + { 0xc2, 0xe2 }, + { 0xc3, 0xe3 }, + { 0xc4, 0xe4 }, + { 0xc5, 0xe5 }, + { 0xc6, 0xe6 }, + { 0xc7, 0xe7 }, + { 0xc8, 0xe8 }, + { 0xc9, 0xe9 }, + { 0xca, 0xea }, + { 0xcb, 0xeb }, + { 0xcc, 0xec }, + { 0xcd, 0xed }, + { 0xce, 0xee }, + { 0xcf, 0xef }, + { 0xd0, 0xf0 }, + { 0xd1, 0xf1 }, + { 0xd2, 0xf2 }, + { 0xd3, 0xf3 }, + { 0xd4, 0xf4 }, + { 0xd5, 0xf5 }, + { 0xd6, 0xf6 }, + { 0xd8, 0xf8 }, + { 0xd9, 0xf9 }, + { 0xda, 0xfa }, + { 0xdb, 0xfb }, + { 0xdc, 0xfc }, + { 0xdd, 0xfd }, + { 0xde, 0xfe }, + { 0x178, 0xff }, + { 0x100, 0x101 }, + { 0x102, 0x103 }, + { 0x104, 0x105 }, + { 0x106, 0x107 }, + { 0x108, 0x109 }, + { 0x10a, 0x10b }, + { 0x10c, 0x10d }, + { 0x10e, 0x10f }, + { 0x110, 0x111 }, + { 0x112, 0x113 }, + { 0x114, 0x115 }, + { 0x116, 0x117 }, + { 0x118, 0x119 }, + { 0x11a, 0x11b }, + { 0x11c, 0x11d }, + { 0x11e, 0x11f }, + { 0x120, 0x121 }, + { 0x122, 0x123 }, + { 0x124, 0x125 }, + { 0x126, 0x127 }, + { 0x128, 0x129 }, + { 0x12a, 0x12b }, + { 0x12c, 0x12d }, + { 0x12e, 0x12f }, + //{0x49,0x131}, + { 0x132, 0x133 }, + { 0x134, 0x135 }, + { 0x136, 0x137 }, + { 0x139, 0x13a }, + { 0x13b, 0x13c }, + { 0x13d, 0x13e }, + { 0x13f, 0x140 }, + { 0x141, 0x142 }, + { 0x143, 0x144 }, + { 0x145, 0x146 }, + { 0x147, 0x148 }, + { 0x14a, 0x14b }, + { 0x14c, 0x14d }, + { 0x14e, 0x14f }, + { 0x150, 0x151 }, + { 0x152, 0x153 }, + { 0x154, 0x155 }, + { 0x156, 0x157 }, + { 0x158, 0x159 }, + { 0x15a, 0x15b }, + { 0x15c, 0x15d }, + { 0x15e, 0x15f }, + { 0x160, 0x161 }, + { 0x162, 0x163 }, + { 0x164, 0x165 }, + { 0x166, 0x167 }, + { 0x168, 0x169 }, + { 0x16a, 0x16b }, + { 0x16c, 0x16d }, + { 0x16e, 0x16f }, + { 0x170, 0x171 }, + { 0x172, 0x173 }, + { 0x174, 0x175 }, + { 0x176, 0x177 }, + { 0x179, 0x17a }, + { 0x17b, 0x17c }, + { 0x17d, 0x17e }, + { 0x182, 0x183 }, + { 0x184, 0x185 }, + { 0x187, 0x188 }, + { 0x18b, 0x18c }, + { 0x191, 0x192 }, + { 0x198, 0x199 }, + { 0x1a0, 0x1a1 }, + { 0x1a2, 0x1a3 }, + { 0x1a4, 0x1a5 }, + { 0x1a7, 0x1a8 }, + { 0x1ac, 0x1ad }, + { 0x1af, 0x1b0 }, + { 0x1b3, 0x1b4 }, + { 0x1b5, 0x1b6 }, + { 0x1b8, 0x1b9 }, + { 0x1bc, 0x1bd }, + { 0x1c4, 0x1c6 }, + { 0x1c7, 0x1c9 }, + { 0x1ca, 0x1cc }, + { 0x1cd, 0x1ce }, + { 0x1cf, 0x1d0 }, + { 0x1d1, 0x1d2 }, + { 0x1d3, 0x1d4 }, + { 0x1d5, 0x1d6 }, + { 0x1d7, 0x1d8 }, + { 0x1d9, 0x1da }, + { 0x1db, 0x1dc }, + { 0x1de, 0x1df }, + { 0x1e0, 0x1e1 }, + { 0x1e2, 0x1e3 }, + { 0x1e4, 0x1e5 }, + { 0x1e6, 0x1e7 }, + { 0x1e8, 0x1e9 }, + { 0x1ea, 0x1eb }, + { 0x1ec, 0x1ed }, + { 0x1ee, 0x1ef }, + { 0x1f1, 0x1f3 }, + { 0x1f4, 0x1f5 }, + { 0x1fa, 0x1fb }, + { 0x1fc, 0x1fd }, + { 0x1fe, 0x1ff }, + { 0x200, 0x201 }, + { 0x202, 0x203 }, + { 0x204, 0x205 }, + { 0x206, 0x207 }, + { 0x208, 0x209 }, + { 0x20a, 0x20b }, + { 0x20c, 0x20d }, + { 0x20e, 0x20f }, + { 0x210, 0x211 }, + { 0x212, 0x213 }, + { 0x214, 0x215 }, + { 0x216, 0x217 }, + { 0x181, 0x253 }, + { 0x186, 0x254 }, + { 0x18a, 0x257 }, + { 0x18e, 0x258 }, + { 0x18f, 0x259 }, + { 0x190, 0x25b }, + { 0x193, 0x260 }, + { 0x194, 0x263 }, + { 0x197, 0x268 }, + { 0x196, 0x269 }, + { 0x19c, 0x26f }, + { 0x19d, 0x272 }, + { 0x19f, 0x275 }, + { 0x1a9, 0x283 }, + { 0x1ae, 0x288 }, + { 0x1b1, 0x28a }, + { 0x1b2, 0x28b }, + { 0x1b7, 0x292 }, + { 0x386, 0x3ac }, + { 0x388, 0x3ad }, + { 0x389, 0x3ae }, + { 0x38a, 0x3af }, + { 0x391, 0x3b1 }, + { 0x392, 0x3b2 }, + { 0x393, 0x3b3 }, + { 0x394, 0x3b4 }, + { 0x395, 0x3b5 }, + { 0x396, 0x3b6 }, + { 0x397, 0x3b7 }, + { 0x398, 0x3b8 }, + { 0x399, 0x3b9 }, + { 0x39a, 0x3ba }, + { 0x39b, 0x3bb }, + { 0x39c, 0x3bc }, + { 0x39d, 0x3bd }, + { 0x39e, 0x3be }, + { 0x39f, 0x3bf }, + { 0x3a0, 0x3c0 }, + { 0x3a1, 0x3c1 }, + { 0x3a3, 0x3c3 }, + { 0x3a4, 0x3c4 }, + { 0x3a5, 0x3c5 }, + { 0x3a6, 0x3c6 }, + { 0x3a7, 0x3c7 }, + { 0x3a8, 0x3c8 }, + { 0x3a9, 0x3c9 }, + { 0x3aa, 0x3ca }, + { 0x3ab, 0x3cb }, + { 0x38c, 0x3cc }, + { 0x38e, 0x3cd }, + { 0x38f, 0x3ce }, + { 0x3e2, 0x3e3 }, + { 0x3e4, 0x3e5 }, + { 0x3e6, 0x3e7 }, + { 0x3e8, 0x3e9 }, + { 0x3ea, 0x3eb }, + { 0x3ec, 0x3ed }, + { 0x3ee, 0x3ef }, + { 0x410, 0x430 }, + { 0x411, 0x431 }, + { 0x412, 0x432 }, + { 0x413, 0x433 }, + { 0x414, 0x434 }, + { 0x415, 0x435 }, + { 0x416, 0x436 }, + { 0x417, 0x437 }, + { 0x418, 0x438 }, + { 0x419, 0x439 }, + { 0x41a, 0x43a }, + { 0x41b, 0x43b }, + { 0x41c, 0x43c }, + { 0x41d, 0x43d }, + { 0x41e, 0x43e }, + { 0x41f, 0x43f }, + { 0x420, 0x440 }, + { 0x421, 0x441 }, + { 0x422, 0x442 }, + { 0x423, 0x443 }, + { 0x424, 0x444 }, + { 0x425, 0x445 }, + { 0x426, 0x446 }, + { 0x427, 0x447 }, + { 0x428, 0x448 }, + { 0x429, 0x449 }, + { 0x42a, 0x44a }, + { 0x42b, 0x44b }, + { 0x42c, 0x44c }, + { 0x42d, 0x44d }, + { 0x42e, 0x44e }, + { 0x42f, 0x44f }, + { 0x401, 0x451 }, + { 0x402, 0x452 }, + { 0x403, 0x453 }, + { 0x404, 0x454 }, + { 0x405, 0x455 }, + { 0x406, 0x456 }, + { 0x407, 0x457 }, + { 0x408, 0x458 }, + { 0x409, 0x459 }, + { 0x40a, 0x45a }, + { 0x40b, 0x45b }, + { 0x40c, 0x45c }, + { 0x40e, 0x45e }, + { 0x40f, 0x45f }, + { 0x460, 0x461 }, + { 0x462, 0x463 }, + { 0x464, 0x465 }, + { 0x466, 0x467 }, + { 0x468, 0x469 }, + { 0x46a, 0x46b }, + { 0x46c, 0x46d }, + { 0x46e, 0x46f }, + { 0x470, 0x471 }, + { 0x472, 0x473 }, + { 0x474, 0x475 }, + { 0x476, 0x477 }, + { 0x478, 0x479 }, + { 0x47a, 0x47b }, + { 0x47c, 0x47d }, + { 0x47e, 0x47f }, + { 0x480, 0x481 }, + { 0x490, 0x491 }, + { 0x492, 0x493 }, + { 0x494, 0x495 }, + { 0x496, 0x497 }, + { 0x498, 0x499 }, + { 0x49a, 0x49b }, + { 0x49c, 0x49d }, + { 0x49e, 0x49f }, + { 0x4a0, 0x4a1 }, + { 0x4a2, 0x4a3 }, + { 0x4a4, 0x4a5 }, + { 0x4a6, 0x4a7 }, + { 0x4a8, 0x4a9 }, + { 0x4aa, 0x4ab }, + { 0x4ac, 0x4ad }, + { 0x4ae, 0x4af }, + { 0x4b0, 0x4b1 }, + { 0x4b2, 0x4b3 }, + { 0x4b4, 0x4b5 }, + { 0x4b6, 0x4b7 }, + { 0x4b8, 0x4b9 }, + { 0x4ba, 0x4bb }, + { 0x4bc, 0x4bd }, + { 0x4be, 0x4bf }, + { 0x4c1, 0x4c2 }, + { 0x4c3, 0x4c4 }, + { 0x4c7, 0x4c8 }, + { 0x4cb, 0x4cc }, + { 0x4d0, 0x4d1 }, + { 0x4d2, 0x4d3 }, + { 0x4d4, 0x4d5 }, + { 0x4d6, 0x4d7 }, + { 0x4d8, 0x4d9 }, + { 0x4da, 0x4db }, + { 0x4dc, 0x4dd }, + { 0x4de, 0x4df }, + { 0x4e0, 0x4e1 }, + { 0x4e2, 0x4e3 }, + { 0x4e4, 0x4e5 }, + { 0x4e6, 0x4e7 }, + { 0x4e8, 0x4e9 }, + { 0x4ea, 0x4eb }, + { 0x4ee, 0x4ef }, + { 0x4f0, 0x4f1 }, + { 0x4f2, 0x4f3 }, + { 0x4f4, 0x4f5 }, + { 0x4f8, 0x4f9 }, + { 0x531, 0x561 }, + { 0x532, 0x562 }, + { 0x533, 0x563 }, + { 0x534, 0x564 }, + { 0x535, 0x565 }, + { 0x536, 0x566 }, + { 0x537, 0x567 }, + { 0x538, 0x568 }, + { 0x539, 0x569 }, + { 0x53a, 0x56a }, + { 0x53b, 0x56b }, + { 0x53c, 0x56c }, + { 0x53d, 0x56d }, + { 0x53e, 0x56e }, + { 0x53f, 0x56f }, + { 0x540, 0x570 }, + { 0x541, 0x571 }, + { 0x542, 0x572 }, + { 0x543, 0x573 }, + { 0x544, 0x574 }, + { 0x545, 0x575 }, + { 0x546, 0x576 }, + { 0x547, 0x577 }, + { 0x548, 0x578 }, + { 0x549, 0x579 }, + { 0x54a, 0x57a }, + { 0x54b, 0x57b }, + { 0x54c, 0x57c }, + { 0x54d, 0x57d }, + { 0x54e, 0x57e }, + { 0x54f, 0x57f }, + { 0x550, 0x580 }, + { 0x551, 0x581 }, + { 0x552, 0x582 }, + { 0x553, 0x583 }, + { 0x554, 0x584 }, + { 0x555, 0x585 }, + { 0x556, 0x586 }, + { 0x10a0, 0x10d0 }, + { 0x10a1, 0x10d1 }, + { 0x10a2, 0x10d2 }, + { 0x10a3, 0x10d3 }, + { 0x10a4, 0x10d4 }, + { 0x10a5, 0x10d5 }, + { 0x10a6, 0x10d6 }, + { 0x10a7, 0x10d7 }, + { 0x10a8, 0x10d8 }, + { 0x10a9, 0x10d9 }, + { 0x10aa, 0x10da }, + { 0x10ab, 0x10db }, + { 0x10ac, 0x10dc }, + { 0x10ad, 0x10dd }, + { 0x10ae, 0x10de }, + { 0x10af, 0x10df }, + { 0x10b0, 0x10e0 }, + { 0x10b1, 0x10e1 }, + { 0x10b2, 0x10e2 }, + { 0x10b3, 0x10e3 }, + { 0x10b4, 0x10e4 }, + { 0x10b5, 0x10e5 }, + { 0x10b6, 0x10e6 }, + { 0x10b7, 0x10e7 }, + { 0x10b8, 0x10e8 }, + { 0x10b9, 0x10e9 }, + { 0x10ba, 0x10ea }, + { 0x10bb, 0x10eb }, + { 0x10bc, 0x10ec }, + { 0x10bd, 0x10ed }, + { 0x10be, 0x10ee }, + { 0x10bf, 0x10ef }, + { 0x10c0, 0x10f0 }, + { 0x10c1, 0x10f1 }, + { 0x10c2, 0x10f2 }, + { 0x10c3, 0x10f3 }, + { 0x10c4, 0x10f4 }, + { 0x10c5, 0x10f5 }, + { 0x1e00, 0x1e01 }, + { 0x1e02, 0x1e03 }, + { 0x1e04, 0x1e05 }, + { 0x1e06, 0x1e07 }, + { 0x1e08, 0x1e09 }, + { 0x1e0a, 0x1e0b }, + { 0x1e0c, 0x1e0d }, + { 0x1e0e, 0x1e0f }, + { 0x1e10, 0x1e11 }, + { 0x1e12, 0x1e13 }, + { 0x1e14, 0x1e15 }, + { 0x1e16, 0x1e17 }, + { 0x1e18, 0x1e19 }, + { 0x1e1a, 0x1e1b }, + { 0x1e1c, 0x1e1d }, + { 0x1e1e, 0x1e1f }, + { 0x1e20, 0x1e21 }, + { 0x1e22, 0x1e23 }, + { 0x1e24, 0x1e25 }, + { 0x1e26, 0x1e27 }, + { 0x1e28, 0x1e29 }, + { 0x1e2a, 0x1e2b }, + { 0x1e2c, 0x1e2d }, + { 0x1e2e, 0x1e2f }, + { 0x1e30, 0x1e31 }, + { 0x1e32, 0x1e33 }, + { 0x1e34, 0x1e35 }, + { 0x1e36, 0x1e37 }, + { 0x1e38, 0x1e39 }, + { 0x1e3a, 0x1e3b }, + { 0x1e3c, 0x1e3d }, + { 0x1e3e, 0x1e3f }, + { 0x1e40, 0x1e41 }, + { 0x1e42, 0x1e43 }, + { 0x1e44, 0x1e45 }, + { 0x1e46, 0x1e47 }, + { 0x1e48, 0x1e49 }, + { 0x1e4a, 0x1e4b }, + { 0x1e4c, 0x1e4d }, + { 0x1e4e, 0x1e4f }, + { 0x1e50, 0x1e51 }, + { 0x1e52, 0x1e53 }, + { 0x1e54, 0x1e55 }, + { 0x1e56, 0x1e57 }, + { 0x1e58, 0x1e59 }, + { 0x1e5a, 0x1e5b }, + { 0x1e5c, 0x1e5d }, + { 0x1e5e, 0x1e5f }, + { 0x1e60, 0x1e61 }, + { 0x1e62, 0x1e63 }, + { 0x1e64, 0x1e65 }, + { 0x1e66, 0x1e67 }, + { 0x1e68, 0x1e69 }, + { 0x1e6a, 0x1e6b }, + { 0x1e6c, 0x1e6d }, + { 0x1e6e, 0x1e6f }, + { 0x1e70, 0x1e71 }, + { 0x1e72, 0x1e73 }, + { 0x1e74, 0x1e75 }, + { 0x1e76, 0x1e77 }, + { 0x1e78, 0x1e79 }, + { 0x1e7a, 0x1e7b }, + { 0x1e7c, 0x1e7d }, + { 0x1e7e, 0x1e7f }, + { 0x1e80, 0x1e81 }, + { 0x1e82, 0x1e83 }, + { 0x1e84, 0x1e85 }, + { 0x1e86, 0x1e87 }, + { 0x1e88, 0x1e89 }, + { 0x1e8a, 0x1e8b }, + { 0x1e8c, 0x1e8d }, + { 0x1e8e, 0x1e8f }, + { 0x1e90, 0x1e91 }, + { 0x1e92, 0x1e93 }, + { 0x1e94, 0x1e95 }, + { 0x1ea0, 0x1ea1 }, + { 0x1ea2, 0x1ea3 }, + { 0x1ea4, 0x1ea5 }, + { 0x1ea6, 0x1ea7 }, + { 0x1ea8, 0x1ea9 }, + { 0x1eaa, 0x1eab }, + { 0x1eac, 0x1ead }, + { 0x1eae, 0x1eaf }, + { 0x1eb0, 0x1eb1 }, + { 0x1eb2, 0x1eb3 }, + { 0x1eb4, 0x1eb5 }, + { 0x1eb6, 0x1eb7 }, + { 0x1eb8, 0x1eb9 }, + { 0x1eba, 0x1ebb }, + { 0x1ebc, 0x1ebd }, + { 0x1ebe, 0x1ebf }, + { 0x1ec0, 0x1ec1 }, + { 0x1ec2, 0x1ec3 }, + { 0x1ec4, 0x1ec5 }, + { 0x1ec6, 0x1ec7 }, + { 0x1ec8, 0x1ec9 }, + { 0x1eca, 0x1ecb }, + { 0x1ecc, 0x1ecd }, + { 0x1ece, 0x1ecf }, + { 0x1ed0, 0x1ed1 }, + { 0x1ed2, 0x1ed3 }, + { 0x1ed4, 0x1ed5 }, + { 0x1ed6, 0x1ed7 }, + { 0x1ed8, 0x1ed9 }, + { 0x1eda, 0x1edb }, + { 0x1edc, 0x1edd }, + { 0x1ede, 0x1edf }, + { 0x1ee0, 0x1ee1 }, + { 0x1ee2, 0x1ee3 }, + { 0x1ee4, 0x1ee5 }, + { 0x1ee6, 0x1ee7 }, + { 0x1ee8, 0x1ee9 }, + { 0x1eea, 0x1eeb }, + { 0x1eec, 0x1eed }, + { 0x1eee, 0x1eef }, + { 0x1ef0, 0x1ef1 }, + { 0x1ef2, 0x1ef3 }, + { 0x1ef4, 0x1ef5 }, + { 0x1ef6, 0x1ef7 }, + { 0x1ef8, 0x1ef9 }, + { 0x1f08, 0x1f00 }, + { 0x1f09, 0x1f01 }, + { 0x1f0a, 0x1f02 }, + { 0x1f0b, 0x1f03 }, + { 0x1f0c, 0x1f04 }, + { 0x1f0d, 0x1f05 }, + { 0x1f0e, 0x1f06 }, + { 0x1f0f, 0x1f07 }, + { 0x1f18, 0x1f10 }, + { 0x1f19, 0x1f11 }, + { 0x1f1a, 0x1f12 }, + { 0x1f1b, 0x1f13 }, + { 0x1f1c, 0x1f14 }, + { 0x1f1d, 0x1f15 }, + { 0x1f28, 0x1f20 }, + { 0x1f29, 0x1f21 }, + { 0x1f2a, 0x1f22 }, + { 0x1f2b, 0x1f23 }, + { 0x1f2c, 0x1f24 }, + { 0x1f2d, 0x1f25 }, + { 0x1f2e, 0x1f26 }, + { 0x1f2f, 0x1f27 }, + { 0x1f38, 0x1f30 }, + { 0x1f39, 0x1f31 }, + { 0x1f3a, 0x1f32 }, + { 0x1f3b, 0x1f33 }, + { 0x1f3c, 0x1f34 }, + { 0x1f3d, 0x1f35 }, + { 0x1f3e, 0x1f36 }, + { 0x1f3f, 0x1f37 }, + { 0x1f48, 0x1f40 }, + { 0x1f49, 0x1f41 }, + { 0x1f4a, 0x1f42 }, + { 0x1f4b, 0x1f43 }, + { 0x1f4c, 0x1f44 }, + { 0x1f4d, 0x1f45 }, + { 0x1f59, 0x1f51 }, + { 0x1f5b, 0x1f53 }, + { 0x1f5d, 0x1f55 }, + { 0x1f5f, 0x1f57 }, + { 0x1f68, 0x1f60 }, + { 0x1f69, 0x1f61 }, + { 0x1f6a, 0x1f62 }, + { 0x1f6b, 0x1f63 }, + { 0x1f6c, 0x1f64 }, + { 0x1f6d, 0x1f65 }, + { 0x1f6e, 0x1f66 }, + { 0x1f6f, 0x1f67 }, + { 0x1f88, 0x1f80 }, + { 0x1f89, 0x1f81 }, + { 0x1f8a, 0x1f82 }, + { 0x1f8b, 0x1f83 }, + { 0x1f8c, 0x1f84 }, + { 0x1f8d, 0x1f85 }, + { 0x1f8e, 0x1f86 }, + { 0x1f8f, 0x1f87 }, + { 0x1f98, 0x1f90 }, + { 0x1f99, 0x1f91 }, + { 0x1f9a, 0x1f92 }, + { 0x1f9b, 0x1f93 }, + { 0x1f9c, 0x1f94 }, + { 0x1f9d, 0x1f95 }, + { 0x1f9e, 0x1f96 }, + { 0x1f9f, 0x1f97 }, + { 0x1fa8, 0x1fa0 }, + { 0x1fa9, 0x1fa1 }, + { 0x1faa, 0x1fa2 }, + { 0x1fab, 0x1fa3 }, + { 0x1fac, 0x1fa4 }, + { 0x1fad, 0x1fa5 }, + { 0x1fae, 0x1fa6 }, + { 0x1faf, 0x1fa7 }, + { 0x1fb8, 0x1fb0 }, + { 0x1fb9, 0x1fb1 }, + { 0x1fd8, 0x1fd0 }, + { 0x1fd9, 0x1fd1 }, + { 0x1fe8, 0x1fe0 }, + { 0x1fe9, 0x1fe1 }, + { 0x24b6, 0x24d0 }, + { 0x24b7, 0x24d1 }, + { 0x24b8, 0x24d2 }, + { 0x24b9, 0x24d3 }, + { 0x24ba, 0x24d4 }, + { 0x24bb, 0x24d5 }, + { 0x24bc, 0x24d6 }, + { 0x24bd, 0x24d7 }, + { 0x24be, 0x24d8 }, + { 0x24bf, 0x24d9 }, + { 0x24c0, 0x24da }, + { 0x24c1, 0x24db }, + { 0x24c2, 0x24dc }, + { 0x24c3, 0x24dd }, + { 0x24c4, 0x24de }, + { 0x24c5, 0x24df }, + { 0x24c6, 0x24e0 }, + { 0x24c7, 0x24e1 }, + { 0x24c8, 0x24e2 }, + { 0x24c9, 0x24e3 }, + { 0x24ca, 0x24e4 }, + { 0x24cb, 0x24e5 }, + { 0x24cc, 0x24e6 }, + { 0x24cd, 0x24e7 }, + { 0x24ce, 0x24e8 }, + { 0x24cf, 0x24e9 }, + { 0xff21, 0xff41 }, + { 0xff22, 0xff42 }, + { 0xff23, 0xff43 }, + { 0xff24, 0xff44 }, + { 0xff25, 0xff45 }, + { 0xff26, 0xff46 }, + { 0xff27, 0xff47 }, + { 0xff28, 0xff48 }, + { 0xff29, 0xff49 }, + { 0xff2a, 0xff4a }, + { 0xff2b, 0xff4b }, + { 0xff2c, 0xff4c }, + { 0xff2d, 0xff4d }, + { 0xff2e, 0xff4e }, + { 0xff2f, 0xff4f }, + { 0xff30, 0xff50 }, + { 0xff31, 0xff51 }, + { 0xff32, 0xff52 }, + { 0xff33, 0xff53 }, + { 0xff34, 0xff54 }, + { 0xff35, 0xff55 }, + { 0xff36, 0xff56 }, + { 0xff37, 0xff57 }, + { 0xff38, 0xff58 }, + { 0xff39, 0xff59 }, + { 0xff3a, 0xff5a } }; -static int _find_upper(int ch) { - +static int _find_upper(int ch) { int low = 0; - int high = CAPS_LEN -1; + int high = CAPS_LEN - 1; int middle; - while( low <= high ) - { - middle = ( low + high ) / 2; + while (low <= high) { + middle = (low + high) / 2; - if( ch < caps_table[ middle][0] ) { + if (ch < caps_table[middle][0]) { high = middle - 1; //search low end of array - } else if ( caps_table[middle][0] < ch) { + } else if (caps_table[middle][0] < ch) { low = middle + 1; //search high end of array } else { return caps_table[middle][1]; @@ -1393,21 +1391,18 @@ static int _find_upper(int ch) { return ch; } - -static int _find_lower(int ch) { - +static int _find_lower(int ch) { int low = 0; - int high = CAPS_LEN -2; + int high = CAPS_LEN - 2; int middle; - while( low <= high ) - { - middle = ( low + high ) / 2; + while (low <= high) { + middle = (low + high) / 2; - if( ch < reverse_caps_table[ middle][0] ) { + if (ch < reverse_caps_table[middle][0]) { high = middle - 1; //search low end of array - } else if ( reverse_caps_table[middle][0] < ch) { + } else if (reverse_caps_table[middle][0] < ch) { low = middle + 1; //search high end of array } else { return reverse_caps_table[middle][1]; diff --git a/core/undo_redo.cpp b/core/undo_redo.cpp index f91f1aa14b..76eee40b9c 100644 --- a/core/undo_redo.cpp +++ b/core/undo_redo.cpp @@ -32,14 +32,14 @@ void UndoRedo::_discard_redo() { - if (current_action==actions.size()-1) + if (current_action == actions.size() - 1) return; - for(int i=current_action+1;i<actions.size();i++) { + for (int i = current_action + 1; i < actions.size(); i++) { - for (List<Operation>::Element *E=actions[i].do_ops.front();E;E=E->next()) { + for (List<Operation>::Element *E = actions[i].do_ops.front(); E; E = E->next()) { - if (E->get().type==Operation::TYPE_REFERENCE) { + if (E->get().type == Operation::TYPE_REFERENCE) { Object *obj = ObjectDB::get_instance(E->get().object); if (obj) @@ -49,169 +49,163 @@ void UndoRedo::_discard_redo() { //ERASE do data } - actions.resize(current_action+1); - + actions.resize(current_action + 1); } -void UndoRedo::create_action(const String& p_name,MergeMode p_mode) { +void UndoRedo::create_action(const String &p_name, MergeMode p_mode) { uint32_t ticks = OS::get_singleton()->get_ticks_msec(); - if (action_level==0) { + if (action_level == 0) { _discard_redo(); // Check if the merge operation is valid - if (p_mode!=MERGE_DISABLE && actions.size() && actions[actions.size()-1].name==p_name && actions[actions.size()-1].last_tick+800 > ticks) { + if (p_mode != MERGE_DISABLE && actions.size() && actions[actions.size() - 1].name == p_name && actions[actions.size() - 1].last_tick + 800 > ticks) { - current_action=actions.size()-2; + current_action = actions.size() - 2; - if (p_mode==MERGE_ENDS) { + if (p_mode == MERGE_ENDS) { // Clear all do ops from last action, and delete all object references - List<Operation>::Element *E=actions[current_action+1].do_ops.front(); + List<Operation>::Element *E = actions[current_action + 1].do_ops.front(); while (E) { - if (E->get().type==Operation::TYPE_REFERENCE) { + if (E->get().type == Operation::TYPE_REFERENCE) { - Object *obj=ObjectDB::get_instance(E->get().object); + Object *obj = ObjectDB::get_instance(E->get().object); if (obj) memdelete(obj); } - E=E->next(); - actions[current_action+1].do_ops.pop_front(); + E = E->next(); + actions[current_action + 1].do_ops.pop_front(); } } - actions[actions.size()-1].last_tick=ticks; + actions[actions.size() - 1].last_tick = ticks; - merge_mode=p_mode; + merge_mode = p_mode; } else { Action new_action; - new_action.name=p_name; - new_action.last_tick=ticks; + new_action.name = p_name; + new_action.last_tick = ticks; actions.push_back(new_action); - merge_mode=MERGE_DISABLE; + merge_mode = MERGE_DISABLE; } } action_level++; } -void UndoRedo::add_do_method(Object *p_object,const String& p_method,VARIANT_ARG_DECLARE) { +void UndoRedo::add_do_method(Object *p_object, const String &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS - ERR_FAIL_COND(action_level<=0); - ERR_FAIL_COND((current_action+1)>=actions.size()); + ERR_FAIL_COND(action_level <= 0); + ERR_FAIL_COND((current_action + 1) >= actions.size()); Operation do_op; - do_op.object=p_object->get_instance_ID(); + do_op.object = p_object->get_instance_ID(); if (p_object->cast_to<Resource>()) - do_op.resref=Ref<Resource>(p_object->cast_to<Resource>()); + do_op.resref = Ref<Resource>(p_object->cast_to<Resource>()); - do_op.type=Operation::TYPE_METHOD; - do_op.name=p_method; + do_op.type = Operation::TYPE_METHOD; + do_op.name = p_method; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - do_op.args[i]=*argptr[i]; + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + do_op.args[i] = *argptr[i]; } - actions[current_action+1].do_ops.push_back(do_op); + actions[current_action + 1].do_ops.push_back(do_op); } -void UndoRedo::add_undo_method(Object *p_object,const String& p_method,VARIANT_ARG_DECLARE) { +void UndoRedo::add_undo_method(Object *p_object, const String &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS - ERR_FAIL_COND(action_level<=0); - ERR_FAIL_COND((current_action+1)>=actions.size()); + ERR_FAIL_COND(action_level <= 0); + ERR_FAIL_COND((current_action + 1) >= actions.size()); // No undo if the merge mode is MERGE_ENDS - if (merge_mode==MERGE_ENDS) + if (merge_mode == MERGE_ENDS) return; Operation undo_op; - undo_op.object=p_object->get_instance_ID(); + undo_op.object = p_object->get_instance_ID(); if (p_object->cast_to<Resource>()) - undo_op.resref=Ref<Resource>(p_object->cast_to<Resource>()); + undo_op.resref = Ref<Resource>(p_object->cast_to<Resource>()); - undo_op.type=Operation::TYPE_METHOD; - undo_op.name=p_method; + undo_op.type = Operation::TYPE_METHOD; + undo_op.name = p_method; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - undo_op.args[i]=*argptr[i]; + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + undo_op.args[i] = *argptr[i]; } - actions[current_action+1].undo_ops.push_back(undo_op); - + actions[current_action + 1].undo_ops.push_back(undo_op); } -void UndoRedo::add_do_property(Object *p_object,const String& p_property,const Variant& p_value) { +void UndoRedo::add_do_property(Object *p_object, const String &p_property, const Variant &p_value) { - ERR_FAIL_COND(action_level<=0); - ERR_FAIL_COND((current_action+1)>=actions.size()); + ERR_FAIL_COND(action_level <= 0); + ERR_FAIL_COND((current_action + 1) >= actions.size()); Operation do_op; - do_op.object=p_object->get_instance_ID(); + do_op.object = p_object->get_instance_ID(); if (p_object->cast_to<Resource>()) - do_op.resref=Ref<Resource>(p_object->cast_to<Resource>()); - - do_op.type=Operation::TYPE_PROPERTY; - do_op.name=p_property; - do_op.args[0]=p_value; - actions[current_action+1].do_ops.push_back(do_op); + do_op.resref = Ref<Resource>(p_object->cast_to<Resource>()); + do_op.type = Operation::TYPE_PROPERTY; + do_op.name = p_property; + do_op.args[0] = p_value; + actions[current_action + 1].do_ops.push_back(do_op); } -void UndoRedo::add_undo_property(Object *p_object,const String& p_property,const Variant& p_value) { +void UndoRedo::add_undo_property(Object *p_object, const String &p_property, const Variant &p_value) { - ERR_FAIL_COND(action_level<=0); - ERR_FAIL_COND((current_action+1)>=actions.size()); + ERR_FAIL_COND(action_level <= 0); + ERR_FAIL_COND((current_action + 1) >= actions.size()); // No undo if the merge mode is MERGE_ENDS - if (merge_mode==MERGE_ENDS) + if (merge_mode == MERGE_ENDS) return; Operation undo_op; - undo_op.object=p_object->get_instance_ID(); + undo_op.object = p_object->get_instance_ID(); if (p_object->cast_to<Resource>()) - undo_op.resref=Ref<Resource>(p_object->cast_to<Resource>()); - - undo_op.type=Operation::TYPE_PROPERTY; - undo_op.name=p_property; - undo_op.args[0]=p_value; - actions[current_action+1].undo_ops.push_back(undo_op); + undo_op.resref = Ref<Resource>(p_object->cast_to<Resource>()); + undo_op.type = Operation::TYPE_PROPERTY; + undo_op.name = p_property; + undo_op.args[0] = p_value; + actions[current_action + 1].undo_ops.push_back(undo_op); } void UndoRedo::add_do_reference(Object *p_object) { - ERR_FAIL_COND(action_level<=0); - ERR_FAIL_COND((current_action+1)>=actions.size()); + ERR_FAIL_COND(action_level <= 0); + ERR_FAIL_COND((current_action + 1) >= actions.size()); Operation do_op; - do_op.object=p_object->get_instance_ID(); + do_op.object = p_object->get_instance_ID(); if (p_object->cast_to<Resource>()) - do_op.resref=Ref<Resource>(p_object->cast_to<Resource>()); - - do_op.type=Operation::TYPE_REFERENCE; - actions[current_action+1].do_ops.push_back(do_op); + do_op.resref = Ref<Resource>(p_object->cast_to<Resource>()); + do_op.type = Operation::TYPE_REFERENCE; + actions[current_action + 1].do_ops.push_back(do_op); } void UndoRedo::add_undo_reference(Object *p_object) { - ERR_FAIL_COND(action_level<=0); - ERR_FAIL_COND((current_action+1)>=actions.size()); + ERR_FAIL_COND(action_level <= 0); + ERR_FAIL_COND((current_action + 1) >= actions.size()); // No undo if the merge mode is MERGE_ENDS - if (merge_mode==MERGE_ENDS) + if (merge_mode == MERGE_ENDS) return; Operation undo_op; - undo_op.object=p_object->get_instance_ID(); + undo_op.object = p_object->get_instance_ID(); if (p_object->cast_to<Resource>()) - undo_op.resref=Ref<Resource>(p_object->cast_to<Resource>()); - - undo_op.type=Operation::TYPE_REFERENCE; - actions[current_action+1].undo_ops.push_back(undo_op); + undo_op.resref = Ref<Resource>(p_object->cast_to<Resource>()); + undo_op.type = Operation::TYPE_REFERENCE; + actions[current_action + 1].undo_ops.push_back(undo_op); } void UndoRedo::_pop_history_tail() { @@ -221,9 +215,9 @@ void UndoRedo::_pop_history_tail() { if (!actions.size()) return; - for (List<Operation>::Element *E=actions[0].undo_ops.front();E;E=E->next()) { + for (List<Operation>::Element *E = actions[0].undo_ops.front(); E; E = E->next()) { - if (E->get().type==Operation::TYPE_REFERENCE) { + if (E->get().type == Operation::TYPE_REFERENCE) { Object *obj = ObjectDB::get_instance(E->get().object); if (obj) @@ -237,82 +231,78 @@ void UndoRedo::_pop_history_tail() { void UndoRedo::commit_action() { - ERR_FAIL_COND(action_level<=0); + ERR_FAIL_COND(action_level <= 0); action_level--; - if (action_level>0) + if (action_level > 0) return; //still nested redo(); // perform action - if (max_steps>0 && actions.size()>max_steps) { + if (max_steps > 0 && actions.size() > max_steps) { //clear early steps - while(actions.size() > max_steps) + while (actions.size() > max_steps) _pop_history_tail(); - } - if (callback && actions.size()>0) { - callback(callback_ud,actions[actions.size()-1].name); + if (callback && actions.size() > 0) { + callback(callback_ud, actions[actions.size() - 1].name); } } - void UndoRedo::_process_operation_list(List<Operation>::Element *E) { - for (;E;E=E->next()) { + for (; E; E = E->next()) { - Operation &op=E->get(); + Operation &op = E->get(); Object *obj = ObjectDB::get_instance(op.object); if (!obj) { //corruption clear_history(); ERR_FAIL_COND(!obj); - } - switch(op.type) { + switch (op.type) { case Operation::TYPE_METHOD: { - obj->call(op.name,VARIANT_ARGS_FROM_ARRAY(op.args)); + obj->call(op.name, VARIANT_ARGS_FROM_ARRAY(op.args)); #ifdef TOOLS_ENABLED - Resource* res = obj->cast_to<Resource>(); + Resource *res = obj->cast_to<Resource>(); if (res) res->set_edited(true); #endif if (method_callback) { - method_callback(method_callbck_ud,obj,op.name,VARIANT_ARGS_FROM_ARRAY(op.args)); + method_callback(method_callbck_ud, obj, op.name, VARIANT_ARGS_FROM_ARRAY(op.args)); } } break; case Operation::TYPE_PROPERTY: { - obj->set(op.name,op.args[0]); + obj->set(op.name, op.args[0]); #ifdef TOOLS_ENABLED - Resource* res = obj->cast_to<Resource>(); + Resource *res = obj->cast_to<Resource>(); if (res) res->set_edited(true); #endif if (property_callback) { - property_callback(prop_callback_ud,obj,op.name,op.args[0]); + property_callback(prop_callback_ud, obj, op.name, op.args[0]); } } break; case Operation::TYPE_REFERENCE: { //do nothing } break; - } } } void UndoRedo::redo() { - ERR_FAIL_COND(action_level>0); + ERR_FAIL_COND(action_level > 0); - if ((current_action+1)>=actions.size()) + if ((current_action + 1) >= actions.size()) return; //nothing to redo current_action++; @@ -322,8 +312,8 @@ void UndoRedo::redo() { void UndoRedo::undo() { - ERR_FAIL_COND(action_level>0); - if (current_action<0) + ERR_FAIL_COND(action_level > 0); + if (current_action < 0) return; //nothing to redo _process_operation_list(actions[current_action].undo_ops.front()); current_action--; @@ -332,10 +322,10 @@ void UndoRedo::undo() { void UndoRedo::clear_history() { - ERR_FAIL_COND(action_level>0); + ERR_FAIL_COND(action_level > 0); _discard_redo(); - while(actions.size()) + while (actions.size()) _pop_history_tail(); //version++; @@ -343,15 +333,15 @@ void UndoRedo::clear_history() { String UndoRedo::get_current_action_name() const { - ERR_FAIL_COND_V(action_level>0,""); - if (current_action<0) + ERR_FAIL_COND_V(action_level > 0, ""); + if (current_action < 0) return ""; //nothing to redo return actions[current_action].name; } void UndoRedo::set_max_steps(int p_max_steps) { - max_steps=p_max_steps; + max_steps = p_max_steps; } int UndoRedo::get_max_steps() const { @@ -364,40 +354,38 @@ uint64_t UndoRedo::get_version() const { return version; } -void UndoRedo::set_commit_notify_callback(CommitNotifyCallback p_callback,void* p_ud) { +void UndoRedo::set_commit_notify_callback(CommitNotifyCallback p_callback, void *p_ud) { - callback=p_callback; - callback_ud=p_ud; + callback = p_callback; + callback_ud = p_ud; } -void UndoRedo::set_method_notify_callback(MethodNotifyCallback p_method_callback,void* p_ud) { +void UndoRedo::set_method_notify_callback(MethodNotifyCallback p_method_callback, void *p_ud) { - method_callback=p_method_callback; - method_callbck_ud=p_ud; + method_callback = p_method_callback; + method_callbck_ud = p_ud; } -void UndoRedo::set_property_notify_callback(PropertyNotifyCallback p_property_callback,void* p_ud){ +void UndoRedo::set_property_notify_callback(PropertyNotifyCallback p_property_callback, void *p_ud) { - property_callback=p_property_callback; - prop_callback_ud=p_ud; + property_callback = p_property_callback; + prop_callback_ud = p_ud; } - UndoRedo::UndoRedo() { - version=1; - action_level=0; - current_action=-1; - max_steps=-1; - merge_mode=MERGE_DISABLE; - callback=NULL; - callback_ud=NULL; - - method_callbck_ud=NULL; - prop_callback_ud=NULL; - method_callback=NULL; - property_callback=NULL; - + version = 1; + action_level = 0; + current_action = -1; + max_steps = -1; + merge_mode = MERGE_DISABLE; + callback = NULL; + callback_ud = NULL; + + method_callbck_ud = NULL; + prop_callback_ud = NULL; + method_callback = NULL; + property_callback = NULL; } UndoRedo::~UndoRedo() { @@ -405,119 +393,115 @@ UndoRedo::~UndoRedo() { clear_history(); } -Variant UndoRedo::_add_do_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { +Variant UndoRedo::_add_do_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - if (p_argcount<2) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=0; + if (p_argcount < 2) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 0; return Variant(); } - if (p_args[0]->get_type()!=Variant::OBJECT) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; + if (p_args[0]->get_type() != Variant::OBJECT) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; return Variant(); } - if (p_args[1]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=1; - r_error.expected=Variant::STRING; + if (p_args[1]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 1; + r_error.expected = Variant::STRING; return Variant(); } - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; - Object* object = *p_args[0]; + Object *object = *p_args[0]; String method = *p_args[1]; Variant v[VARIANT_ARG_MAX]; + for (int i = 0; i < MIN(VARIANT_ARG_MAX, p_argcount - 2); ++i) { - for(int i=0;i<MIN(VARIANT_ARG_MAX,p_argcount-2);++i) { - - v[i]=*p_args[i+2]; + v[i] = *p_args[i + 2]; } - add_do_method(object,method,v[0],v[1],v[2],v[3],v[4]); + add_do_method(object, method, v[0], v[1], v[2], v[3], v[4]); return Variant(); } -Variant UndoRedo::_add_undo_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { +Variant UndoRedo::_add_undo_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - if (p_argcount<2) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=0; + if (p_argcount < 2) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 0; return Variant(); } - if (p_args[0]->get_type()!=Variant::OBJECT) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; + if (p_args[0]->get_type() != Variant::OBJECT) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; return Variant(); } - if (p_args[1]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=1; - r_error.expected=Variant::STRING; + if (p_args[1]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 1; + r_error.expected = Variant::STRING; return Variant(); } - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; - Object* object = *p_args[0]; + Object *object = *p_args[0]; String method = *p_args[1]; Variant v[VARIANT_ARG_MAX]; + for (int i = 0; i < MIN(VARIANT_ARG_MAX, p_argcount - 2); ++i) { - for(int i=0;i<MIN(VARIANT_ARG_MAX,p_argcount-2);++i) { - - v[i]=*p_args[i+2]; + v[i] = *p_args[i + 2]; } - add_undo_method(object,method,v[0],v[1],v[2],v[3],v[4]); + add_undo_method(object, method, v[0], v[1], v[2], v[3], v[4]); return Variant(); } void UndoRedo::_bind_methods() { - ClassDB::bind_method(D_METHOD("create_action","name","merge_mode"),&UndoRedo::create_action, DEFVAL(MERGE_DISABLE) ); - ClassDB::bind_method(D_METHOD("commit_action"),&UndoRedo::commit_action); + ClassDB::bind_method(D_METHOD("create_action", "name", "merge_mode"), &UndoRedo::create_action, DEFVAL(MERGE_DISABLE)); + ClassDB::bind_method(D_METHOD("commit_action"), &UndoRedo::commit_action); //ClassDB::bind_method(D_METHOD("add_do_method","p_object", "p_method", "VARIANT_ARG_LIST"),&UndoRedo::add_do_method); //ClassDB::bind_method(D_METHOD("add_undo_method","p_object", "p_method", "VARIANT_ARG_LIST"),&UndoRedo::add_undo_method); { MethodInfo mi; - mi.name="add_do_method"; - mi.arguments.push_back( PropertyInfo( Variant::OBJECT, "object")); - mi.arguments.push_back( PropertyInfo( Variant::STRING, "method")); + mi.name = "add_do_method"; + mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object")); + mi.arguments.push_back(PropertyInfo(Variant::STRING, "method")); - - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"add_do_method",&UndoRedo::_add_do_method,mi); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "add_do_method", &UndoRedo::_add_do_method, mi); } { MethodInfo mi; - mi.name="add_undo_method"; - mi.arguments.push_back( PropertyInfo( Variant::OBJECT, "object")); - mi.arguments.push_back( PropertyInfo( Variant::STRING, "method")); - + mi.name = "add_undo_method"; + mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object")); + mi.arguments.push_back(PropertyInfo(Variant::STRING, "method")); - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"add_undo_method",&UndoRedo::_add_undo_method,mi); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "add_undo_method", &UndoRedo::_add_undo_method, mi); } - ClassDB::bind_method(D_METHOD("add_do_property","object", "property", "value:Variant"),&UndoRedo::add_do_property); - ClassDB::bind_method(D_METHOD("add_undo_property","object", "property", "value:Variant"),&UndoRedo::add_undo_property); - ClassDB::bind_method(D_METHOD("add_do_reference","object"),&UndoRedo::add_do_reference); - ClassDB::bind_method(D_METHOD("add_undo_reference","object"),&UndoRedo::add_undo_reference); - ClassDB::bind_method(D_METHOD("clear_history"),&UndoRedo::clear_history); - ClassDB::bind_method(D_METHOD("get_current_action_name"),&UndoRedo::get_current_action_name); - ClassDB::bind_method(D_METHOD("get_version"),&UndoRedo::get_version); + ClassDB::bind_method(D_METHOD("add_do_property", "object", "property", "value:Variant"), &UndoRedo::add_do_property); + ClassDB::bind_method(D_METHOD("add_undo_property", "object", "property", "value:Variant"), &UndoRedo::add_undo_property); + ClassDB::bind_method(D_METHOD("add_do_reference", "object"), &UndoRedo::add_do_reference); + ClassDB::bind_method(D_METHOD("add_undo_reference", "object"), &UndoRedo::add_undo_reference); + ClassDB::bind_method(D_METHOD("clear_history"), &UndoRedo::clear_history); + ClassDB::bind_method(D_METHOD("get_current_action_name"), &UndoRedo::get_current_action_name); + ClassDB::bind_method(D_METHOD("get_version"), &UndoRedo::get_version); BIND_CONSTANT(MERGE_DISABLE); BIND_CONSTANT(MERGE_ENDS); diff --git a/core/undo_redo.h b/core/undo_redo.h index 7664cf7cb5..30601fa321 100644 --- a/core/undo_redo.h +++ b/core/undo_redo.h @@ -32,27 +32,24 @@ #include "object.h" #include "resource.h" - - - class UndoRedo : public Object { - GDCLASS(UndoRedo,Object); - OBJ_SAVE_TYPE( UndoRedo ); -public: + GDCLASS(UndoRedo, Object); + OBJ_SAVE_TYPE(UndoRedo); +public: enum MergeMode { MERGE_DISABLE, MERGE_ENDS, MERGE_ALL }; - typedef void (*CommitNotifyCallback)(void *p_ud,const String& p_name); - Variant _add_do_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error); - Variant _add_undo_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error); + typedef void (*CommitNotifyCallback)(void *p_ud, const String &p_name); + Variant _add_do_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error); + Variant _add_undo_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error); - typedef void (*MethodNotifyCallback)(void *p_ud,Object*p_base,const StringName& p_name,VARIANT_ARG_DECLARE); - typedef void (*PropertyNotifyCallback)(void *p_ud,Object*p_base,const StringName& p_property,const Variant& p_value); + typedef void (*MethodNotifyCallback)(void *p_ud, Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE); + typedef void (*PropertyNotifyCallback)(void *p_ud, Object *p_base, const StringName &p_property, const Variant &p_value); private: struct Operation { @@ -68,10 +65,8 @@ private: ObjectID object; String name; Variant args[VARIANT_ARG_MAX]; - }; - struct Action { String name; List<Operation> do_ops; @@ -90,27 +85,24 @@ private: void _process_operation_list(List<Operation>::Element *E); void _discard_redo(); - CommitNotifyCallback callback; - void* callback_ud; - void* method_callbck_ud; - void* prop_callback_ud; + void *callback_ud; + void *method_callbck_ud; + void *prop_callback_ud; MethodNotifyCallback method_callback; PropertyNotifyCallback property_callback; - protected: static void _bind_methods(); public: + void create_action(const String &p_name = "", MergeMode p_mode = MERGE_DISABLE); - void create_action(const String& p_name="",MergeMode p_mode=MERGE_DISABLE); - - void add_do_method(Object *p_object,const String& p_method,VARIANT_ARG_LIST); - void add_undo_method(Object *p_object,const String& p_method,VARIANT_ARG_LIST); - void add_do_property(Object *p_object,const String& p_property,const Variant& p_value); - void add_undo_property(Object *p_object,const String& p_property,const Variant& p_value); + void add_do_method(Object *p_object, const String &p_method, VARIANT_ARG_LIST); + void add_undo_method(Object *p_object, const String &p_method, VARIANT_ARG_LIST); + void add_do_property(Object *p_object, const String &p_property, const Variant &p_value); + void add_undo_property(Object *p_object, const String &p_property, const Variant &p_value); void add_do_reference(Object *p_object); void add_undo_reference(Object *p_object); @@ -126,15 +118,15 @@ public: uint64_t get_version() const; - void set_commit_notify_callback(CommitNotifyCallback p_callback,void* p_ud); + void set_commit_notify_callback(CommitNotifyCallback p_callback, void *p_ud); - void set_method_notify_callback(MethodNotifyCallback p_method_callback,void* p_ud); - void set_property_notify_callback(PropertyNotifyCallback p_property_callback,void* p_ud); + void set_method_notify_callback(MethodNotifyCallback p_method_callback, void *p_ud); + void set_property_notify_callback(PropertyNotifyCallback p_property_callback, void *p_ud); UndoRedo(); ~UndoRedo(); }; -VARIANT_ENUM_CAST( UndoRedo::MergeMode ); +VARIANT_ENUM_CAST(UndoRedo::MergeMode); #endif // UNDO_REDO_H diff --git a/core/ustring.cpp b/core/ustring.cpp index 7d88989d04..db85db28ef 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -28,20 +28,20 @@ /*************************************************************************/ #include "ustring.h" -#include "os/memory.h" -#include "print_string.h" -#include "math_funcs.h" +#include "color.h" #include "io/md5.h" #include "io/sha256.h" +#include "math_funcs.h" +#include "os/memory.h" +#include "print_string.h" #include "ucaps.h" -#include "color.h" #include "variant.h" #include <wchar.h> #ifndef NO_USE_STDLIB -#include <stdlib.h> #include <stdio.h> +#include <stdlib.h> #endif #if defined(MINGW_ENABLED) || defined(_MSC_VER) @@ -49,34 +49,30 @@ #endif #define MAX_DIGITS 6 -#define UPPERCASE(m_c) (((m_c)>='a' && (m_c)<='z')?((m_c)-('a'-'A')):(m_c)) -#define LOWERCASE(m_c) (((m_c)>='A' && (m_c)<='Z')?((m_c)+('a'-'A')):(m_c)) - - - +#define UPPERCASE(m_c) (((m_c) >= 'a' && (m_c) <= 'z') ? ((m_c) - ('a' - 'A')) : (m_c)) +#define LOWERCASE(m_c) (((m_c) >= 'A' && (m_c) <= 'Z') ? ((m_c) + ('a' - 'A')) : (m_c)) /** STRING **/ -bool CharString::operator<(const CharString& p_right) const { +bool CharString::operator<(const CharString &p_right) const { - if (length()==0) { - return p_right.length()!=0; + if (length() == 0) { + return p_right.length() != 0; } - - const char *this_str=get_data(); - const char *that_str=get_data(); + const char *this_str = get_data(); + const char *that_str = get_data(); while (true) { - if (*that_str==0 && *this_str==0) + if (*that_str == 0 && *this_str == 0) return false; //this can't be equal, sadly - else if (*this_str==0) + else if (*this_str == 0) return true; //if this is empty, and the other one is not, then we're less.. I think? - else if (*that_str==0) + else if (*that_str == 0) return false; //otherwise the other one is smaller.. - else if (*this_str < *that_str ) //more than + else if (*this_str < *that_str) //more than return true; - else if (*this_str > *that_str ) //less than + else if (*this_str > *that_str) //less than return false; this_str++; @@ -96,98 +92,92 @@ const char *CharString::get_data() const { void String::copy_from(const char *p_cstr) { - int len=0; - const char *ptr=p_cstr; - while (*(ptr++)!=0) + int len = 0; + const char *ptr = p_cstr; + while (*(ptr++) != 0) len++; - if (len==0) { + if (len == 0) { resize(0); return; } - - resize(len+1); // include 0 + resize(len + 1); // include 0 CharType *dst = this->ptr(); - for (int i=0;i<len+1;i++) { + for (int i = 0; i < len + 1; i++) { - dst[i]=p_cstr[i]; + dst[i] = p_cstr[i]; } - } -void String::copy_from(const CharType* p_cstr, int p_clip_to) { +void String::copy_from(const CharType *p_cstr, int p_clip_to) { - int len=0; - const CharType *ptr=p_cstr; - while (*(ptr++)!=0) + int len = 0; + const CharType *ptr = p_cstr; + while (*(ptr++) != 0) len++; - if (p_clip_to>=0 && len>p_clip_to) - len=p_clip_to; + if (p_clip_to >= 0 && len > p_clip_to) + len = p_clip_to; - if (len==0) { + if (len == 0) { resize(0); return; } - resize(len+1); - set(len,0); + resize(len + 1); + set(len, 0); CharType *dst = &operator[](0); + for (int i = 0; i < len; i++) { - for (int i=0;i<len;i++) { - - dst[i]=p_cstr[i]; + dst[i] = p_cstr[i]; } } -void String::copy_from(const CharType& p_char) { +void String::copy_from(const CharType &p_char) { resize(2); - set(0,p_char); - set(1,0); + set(0, p_char); + set(1, 0); } +bool String::operator==(const String &p_str) const { -bool String::operator==(const String& p_str) const { - - if (length()!=p_str.length()) + if (length() != p_str.length()) return false; if (empty()) return true; - int l=length(); + int l = length(); const CharType *src = c_str(); const CharType *dst = p_str.c_str(); /* Compare char by char */ - for (int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - if (src[i]!=dst[i]) + if (src[i] != dst[i]) return false; } return true; } -bool String::operator!=(const String& p_str) const { +bool String::operator!=(const String &p_str) const { - return !(*this==p_str); + return !(*this == p_str); } +String String::operator+(const String &p_str) const { - -String String::operator+(const String& p_str) const { - - String res=*this; - res+=p_str; + String res = *this; + res += p_str; return res; } @@ -199,104 +189,96 @@ String String::operator+(CharType p_chr) const { return res; } */ -String& String::operator+=(const String &p_str) { +String &String::operator+=(const String &p_str) { if (empty()) { - *this=p_str; + *this = p_str; return *this; } if (p_str.empty()) return *this; - int from=length(); + int from = length(); - resize( length() + p_str.size() ); + resize(length() + p_str.size()); const CharType *src = p_str.c_str(); CharType *dst = &operator[](0); - set( length(), 0 ); + set(length(), 0); - for (int i=0;i<p_str.length();i++) - dst[from+i]=src[i]; + for (int i = 0; i < p_str.length(); i++) + dst[from + i] = src[i]; return *this; - } -String& String::operator+=(const CharType *p_str) { - +String &String::operator+=(const CharType *p_str) { - *this+=String(p_str); + *this += String(p_str); return *this; } +String &String::operator+=(CharType p_char) { -String& String::operator+=(CharType p_char) { - - - resize( size() ? size() + 1 : 2); - set( length(), 0 ); - set( length() -1, p_char ); + resize(size() ? size() + 1 : 2); + set(length(), 0); + set(length() - 1, p_char); return *this; - } -String& String::operator+=(const char * p_str) { +String &String::operator+=(const char *p_str) { - if (!p_str || p_str[0]==0) + if (!p_str || p_str[0] == 0) return *this; - int src_len=0; - const char *ptr=p_str; - while (*(ptr++)!=0) + int src_len = 0; + const char *ptr = p_str; + while (*(ptr++) != 0) src_len++; - int from=length(); + int from = length(); - resize( from + src_len + 1 ); + resize(from + src_len + 1); CharType *dst = &operator[](0); - set( length(), 0 ); + set(length(), 0); - for (int i=0;i<src_len;i++) - dst[from+i]=p_str[i]; + for (int i = 0; i < src_len; i++) + dst[from + i] = p_str[i]; return *this; - } void String::operator=(const char *p_str) { copy_from(p_str); - } void String::operator=(const CharType *p_str) { copy_from(p_str); - } bool String::operator==(const StrRange &p_range) const { - int len=p_range.len; + int len = p_range.len; - if (length()!=len) + if (length() != len) return false; if (empty()) return true; - const CharType *c_str=p_range.c_str; + const CharType *c_str = p_range.c_str; const CharType *dst = &operator[](0); /* Compare char by char */ - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (c_str[i]!=dst[i]) + if (c_str[i] != dst[i]) return false; } @@ -305,94 +287,87 @@ bool String::operator==(const StrRange &p_range) const { bool String::operator==(const char *p_str) const { - int len=0; - const char *aux=p_str; + int len = 0; + const char *aux = p_str; - while (*(aux++)!=0) + while (*(aux++) != 0) len++; - if (length()!=len) + if (length() != len) return false; if (empty()) return true; - int l=length(); + int l = length(); const CharType *dst = c_str(); /* Compare char by char */ - for (int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - if (p_str[i]!=dst[i]) + if (p_str[i] != dst[i]) return false; } return true; - - } bool String::operator==(const CharType *p_str) const { - int len=0; - const CharType *aux=p_str; + int len = 0; + const CharType *aux = p_str; - while (*(aux++)!=0) + while (*(aux++) != 0) len++; - if (length()!=len) + if (length() != len) return false; if (empty()) return true; - int l=length(); + int l = length(); const CharType *dst = c_str(); /* Compare char by char */ - for (int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - if (p_str[i]!=dst[i]) + if (p_str[i] != dst[i]) return false; } return true; - } bool String::operator!=(const char *p_str) const { - return (! ( *this==p_str ) ); + return (!(*this == p_str)); } - bool String::operator!=(const CharType *p_str) const { - return (! ( *this==p_str ) ); - + return (!(*this == p_str)); } bool String::operator<(const CharType *p_str) const { - - if (empty() && p_str[0]==0) + if (empty() && p_str[0] == 0) return false; if (empty()) return true; - - const CharType *this_str=c_str(); + const CharType *this_str = c_str(); while (true) { - if (*p_str==0 && *this_str==0) + if (*p_str == 0 && *this_str == 0) return false; //this can't be equal, sadly - else if (*this_str==0) + else if (*this_str == 0) return true; //if this is empty, and the other one is not, then we're less.. I think? - else if (*p_str==0) + else if (*p_str == 0) return false; //otherwise the other one is smaller.. - else if (*this_str < *p_str ) //more than + else if (*this_str < *p_str) //more than return true; - else if (*this_str > *p_str ) //less than + else if (*this_str > *p_str) //less than return false; this_str++; @@ -400,33 +375,32 @@ bool String::operator<(const CharType *p_str) const { } return false; //should never reach here anyway - } bool String::operator<=(String p_str) const { - return (*this<p_str) || (*this==p_str); + return (*this < p_str) || (*this == p_str); } bool String::operator<(const char *p_str) const { - if (empty() && p_str[0]==0) + if (empty() && p_str[0] == 0) return false; if (empty()) return true; - const CharType *this_str=c_str(); + const CharType *this_str = c_str(); while (true) { - if (*p_str==0 && *this_str==0) + if (*p_str == 0 && *this_str == 0) return false; //this can't be equal, sadly - else if (*this_str==0) + else if (*this_str == 0) return true; //if this is empty, and the other one is not, then we're less.. I think? - else if (*p_str==0) + else if (*p_str == 0) return false; //otherwise the other one is smaller.. - else if (*this_str < *p_str ) //more than + else if (*this_str < *p_str) //more than return true; - else if (*this_str > *p_str ) //less than + else if (*this_str > *p_str) //less than return false; this_str++; @@ -434,11 +408,8 @@ bool String::operator<(const char *p_str) const { } return false; //should never reach here anyway - } - - bool String::operator<(String p_str) const { return operator<(p_str.c_str()); @@ -453,20 +424,20 @@ signed char String::nocasecmp_to(const String &p_str) const { if (p_str.empty()) return 1; - const CharType *that_str=p_str.c_str(); - const CharType *this_str=c_str(); + const CharType *that_str = p_str.c_str(); + const CharType *this_str = c_str(); while (true) { - if (*that_str==0 && *this_str==0) + if (*that_str == 0 && *this_str == 0) return 0; //we're equal - else if (*this_str==0) + else if (*this_str == 0) return -1; //if this is empty, and the other one is not, then we're less.. I think? - else if (*that_str==0) + else if (*that_str == 0) return 1; //otherwise the other one is smaller.. - else if (_find_upper(*this_str) < _find_upper(*that_str) ) //more than + else if (_find_upper(*this_str) < _find_upper(*that_str)) //more than return -1; - else if (_find_upper(*this_str) > _find_upper(*that_str) ) //less than + else if (_find_upper(*this_str) > _find_upper(*that_str)) //less than return 1; this_str++; @@ -474,7 +445,6 @@ signed char String::nocasecmp_to(const String &p_str) const { } return 0; //should never reach anyway - } signed char String::casecmp_to(const String &p_str) const { @@ -486,20 +456,20 @@ signed char String::casecmp_to(const String &p_str) const { if (p_str.empty()) return 1; - const CharType *that_str=p_str.c_str(); - const CharType *this_str=c_str(); + const CharType *that_str = p_str.c_str(); + const CharType *this_str = c_str(); while (true) { - if (*that_str==0 && *this_str==0) + if (*that_str == 0 && *this_str == 0) return 0; //we're equal - else if (*this_str==0) + else if (*this_str == 0) return -1; //if this is empty, and the other one is not, then we're less.. I think? - else if (*that_str==0) + else if (*that_str == 0) return 1; //otherwise the other one is smaller.. - else if (*this_str < *that_str ) //more than + else if (*this_str < *that_str) //more than return -1; - else if (*this_str > *that_str ) //less than + else if (*this_str > *that_str) //less than return 1; this_str++; @@ -507,32 +477,26 @@ signed char String::casecmp_to(const String &p_str) const { } return 0; //should never reach anyway - } void String::erase(int p_pos, int p_chars) { - - *this=left(p_pos)+substr( p_pos + p_chars , length() - ( (p_pos+p_chars) ) ); - - + *this = left(p_pos) + substr(p_pos + p_chars, length() - ((p_pos + p_chars))); } - - String String::capitalize() const { - String aux=this->replace("_"," ").to_lower(); + String aux = this->replace("_", " ").to_lower(); String cap; - for (int i=0;i<aux.get_slice_count(" ");i++) { + for (int i = 0; i < aux.get_slice_count(" "); i++) { - String slice=aux.get_slicec(' ',i); - if (slice.length()>0) { + String slice = aux.get_slicec(' ', i); + if (slice.length() > 0) { - slice[0]=_find_upper(slice[0]); - if (i>0) - cap+=" "; - cap+=slice; + slice[0] = _find_upper(slice[0]); + if (i > 0) + cap += " "; + cap += slice; } } @@ -540,19 +504,19 @@ String String::capitalize() const { } String String::camelcase_to_underscore(bool lowercase) const { - const CharType * cstr = c_str(); + const CharType *cstr = c_str(); String new_string; const char A = 'A', Z = 'Z'; const char a = 'a', z = 'z'; int start_index = 0; - for ( size_t i = 1; i < this->size(); i++ ) { + for (size_t i = 1; i < this->size(); i++) { bool is_upper = cstr[i] >= A && cstr[i] <= Z; bool are_next_2_lower = false; - bool was_precedent_upper = cstr[i-1] >= A && cstr[i-1] <= Z; + bool was_precedent_upper = cstr[i - 1] >= A && cstr[i - 1] <= Z; - if (i+2 < this->size()) { - are_next_2_lower = cstr[i+1] >= a && cstr[i+1] <= z && cstr[i+2] >= a && cstr[i+2] <= z; + if (i + 2 < this->size()) { + are_next_2_lower = cstr[i + 1] >= a && cstr[i + 1] <= z && cstr[i + 2] >= a && cstr[i + 2] <= z; } bool should_split = ((is_upper && !was_precedent_upper) || (was_precedent_upper && is_upper && are_next_2_lower)); @@ -566,22 +530,20 @@ String String::camelcase_to_underscore(bool lowercase) const { return lowercase ? new_string.to_lower() : new_string; } - - -int String::get_slice_count(String p_splitter) const{ +int String::get_slice_count(String p_splitter) const { if (empty()) return 0; if (p_splitter.empty()) return 0; - int pos=0; - int slices=1; + int pos = 0; + int slices = 1; - while ( (pos=find(p_splitter,pos))>=0) { + while ((pos = find(p_splitter, pos)) >= 0) { slices++; - pos+=p_splitter.length(); + pos += p_splitter.length(); } return slices; @@ -592,38 +554,37 @@ String String::get_slice(String p_splitter, int p_slice) const { if (empty() || p_splitter.empty()) return ""; - int pos=0; - int prev_pos=0; + int pos = 0; + int prev_pos = 0; //int slices=1; - if (p_slice<0) + if (p_slice < 0) return ""; - if (find(p_splitter)==-1) + if (find(p_splitter) == -1) return *this; - int i=0; - while(true) { + int i = 0; + while (true) { - pos=find(p_splitter,pos); - if (pos==-1) - pos=length(); //reached end + pos = find(p_splitter, pos); + if (pos == -1) + pos = length(); //reached end - int from=prev_pos; + int from = prev_pos; //int to=pos; - if (p_slice==i) { + if (p_slice == i) { - return substr( from, pos-from ); + return substr(from, pos - from); } - if (pos==length()) //reached end and no find + if (pos == length()) //reached end and no find break; - pos+=p_splitter.length(); - prev_pos=pos; + pos += p_splitter.length(); + prev_pos = pos; i++; } return ""; //no find! - } String String::get_slicec(CharType p_splitter, int p_slice) const { @@ -631,226 +592,213 @@ String String::get_slicec(CharType p_splitter, int p_slice) const { if (empty()) return String(); - if (p_slice<0) + if (p_slice < 0) return String(); - const CharType *c=this->ptr(); - int i=0; - int prev=0; - int count=0; - while(true) { - + const CharType *c = this->ptr(); + int i = 0; + int prev = 0; + int count = 0; + while (true) { - if (c[i]==0 || c[i]==p_splitter) { + if (c[i] == 0 || c[i] == p_splitter) { - if (p_slice==count) { + if (p_slice == count) { - return substr(prev,i-prev); - } else if (c[i]==0) { + return substr(prev, i - prev); + } else if (c[i] == 0) { return String(); } else { count++; - prev=i+1; + prev = i + 1; } - } i++; - } return String(); //no find! - } - Vector<String> String::split_spaces() const { Vector<String> ret; - int from=0; - int i=0; + int from = 0; + int i = 0; int len = length(); - bool inside=false; + bool inside = false; - while(true) { + while (true) { - bool empty=operator[](i)<33; + bool empty = operator[](i) < 33; - if (i==0) - inside=!empty; + if (i == 0) + inside = !empty; if (!empty && !inside) { - inside=true; - from=i; + inside = true; + from = i; } if (empty && inside) { - ret.push_back(substr(from,i-from)); - inside=false; + ret.push_back(substr(from, i - from)); + inside = false; } - if (i==len) + if (i == len) break; i++; } return ret; - } -Vector<String> String::split(const String &p_splitter,bool p_allow_empty) const { +Vector<String> String::split(const String &p_splitter, bool p_allow_empty) const { Vector<String> ret; - int from=0; + int from = 0; int len = length(); - while(true) { + while (true) { - int end=find(p_splitter,from); - if (end<0) - end=len; - if (p_allow_empty || (end>from)) - ret.push_back(substr(from,end-from)); + int end = find(p_splitter, from); + if (end < 0) + end = len; + if (p_allow_empty || (end > from)) + ret.push_back(substr(from, end - from)); - if (end==len) + if (end == len) break; - from = end+p_splitter.length(); + from = end + p_splitter.length(); } return ret; } -Vector<float> String::split_floats(const String &p_splitter,bool p_allow_empty) const { +Vector<float> String::split_floats(const String &p_splitter, bool p_allow_empty) const { Vector<float> ret; - int from=0; + int from = 0; int len = length(); - while(true) { + while (true) { - int end=find(p_splitter,from); - if (end<0) - end=len; - if (p_allow_empty || (end>from)) + int end = find(p_splitter, from); + if (end < 0) + end = len; + if (p_allow_empty || (end > from)) ret.push_back(String::to_double(&c_str()[from])); - if (end==len) + if (end == len) break; - from = end+p_splitter.length(); + from = end + p_splitter.length(); } return ret; } -Vector<float> String::split_floats_mk(const Vector<String> &p_splitters,bool p_allow_empty) const { +Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const { Vector<float> ret; - int from=0; + int from = 0; int len = length(); - while(true) { + while (true) { int idx; - int end=findmk(p_splitters,from,&idx); - int spl_len=1; - if (end<0) { - end=len; + int end = findmk(p_splitters, from, &idx); + int spl_len = 1; + if (end < 0) { + end = len; } else { - spl_len=p_splitters[idx].length(); + spl_len = p_splitters[idx].length(); } - if (p_allow_empty || (end>from)) { + if (p_allow_empty || (end > from)) { ret.push_back(String::to_double(&c_str()[from])); } - if (end==len) + if (end == len) break; - from = end+spl_len; + from = end + spl_len; } return ret; - - } - -Vector<int> String::split_ints(const String &p_splitter,bool p_allow_empty) const { +Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const { Vector<int> ret; - int from=0; + int from = 0; int len = length(); - while(true) { + while (true) { - int end=find(p_splitter,from); - if (end<0) - end=len; - if (p_allow_empty || (end>from)) - ret.push_back(String::to_int(&c_str()[from],end-from)); + int end = find(p_splitter, from); + if (end < 0) + end = len; + if (p_allow_empty || (end > from)) + ret.push_back(String::to_int(&c_str()[from], end - from)); - if (end==len) + if (end == len) break; - from = end+p_splitter.length(); + from = end + p_splitter.length(); } return ret; } -Vector<int> String::split_ints_mk(const Vector<String> &p_splitters,bool p_allow_empty) const { +Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const { Vector<int> ret; - int from=0; + int from = 0; int len = length(); - while(true) { + while (true) { int idx; - int end=findmk(p_splitters,from,&idx); - int spl_len=1; - if (end<0) { - end=len; + int end = findmk(p_splitters, from, &idx); + int spl_len = 1; + if (end < 0) { + end = len; } else { - spl_len=p_splitters[idx].length(); + spl_len = p_splitters[idx].length(); } - if (p_allow_empty || (end>from)) - ret.push_back(String::to_int(&c_str()[from],end-from)); + if (p_allow_empty || (end > from)) + ret.push_back(String::to_int(&c_str()[from], end - from)); - if (end==len) + if (end == len) break; - from = end+spl_len; + from = end + spl_len; } return ret; - - } - CharType String::char_uppercase(CharType p_char) { return _find_upper(p_char); } -CharType String::char_lowercase(CharType p_char){ +CharType String::char_lowercase(CharType p_char) { return _find_lower(p_char); } - String String::to_upper() const { - String upper=*this; + String upper = *this; - for(int i=0;i<upper.size();i++) { + for (int i = 0; i < upper.size(); i++) { - upper[i]=_find_upper(upper[i]); + upper[i] = _find_upper(upper[i]); } return upper; @@ -858,11 +806,11 @@ String String::to_upper() const { String String::to_lower() const { - String upper=*this; + String upper = *this; - for(int i=0;i<upper.size();i++) { + for (int i = 0; i < upper.size(); i++) { - upper[i]=_find_lower(upper[i]); + upper[i] = _find_lower(upper[i]); } return upper; @@ -870,16 +818,15 @@ String String::to_lower() const { int String::length() const { - int s=size(); - return s?(s-1):0; // length does not include zero + int s = size(); + return s ? (s - 1) : 0; // length does not include zero } +const CharType *String::c_str() const { -const CharType * String::c_str() const { + static const CharType zero = 0; - static const CharType zero=0; - - return size()?&operator[](0):&zero; + return size() ? &operator[](0) : &zero; } String String::md5(const uint8_t *p_md5) { @@ -887,16 +834,16 @@ String String::md5(const uint8_t *p_md5) { } String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) { - static const char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; + static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String ret; - char v[2]={0,0}; + char v[2] = { 0, 0 }; - for(int i=0;i<p_len;i++) { - v[0]=hex[p_buffer[i]>>4]; - ret+=v; - v[0]=hex[p_buffer[i]&0xF]; - ret+=v; + for (int i = 0; i < p_len; i++) { + v[0] = hex[p_buffer[i] >> 4]; + ret += v; + v[0] = hex[p_buffer[i] & 0xF]; + ret += v; } return ret; @@ -904,73 +851,68 @@ String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) { String String::chr(CharType p_char) { - CharType c[2]={p_char,0}; + CharType c[2] = { p_char, 0 }; return String(c); - } -String String::num(double p_num,int p_decimals) { - +String String::num(double p_num, int p_decimals) { #ifndef NO_USE_STDLIB - if (p_decimals>12) - p_decimals=12; - + if (p_decimals > 12) + p_decimals = 12; char fmt[7]; - fmt[0]='%'; - fmt[1]='.'; + fmt[0] = '%'; + fmt[1] = '.'; - if (p_decimals<0) { + if (p_decimals < 0) { - fmt[1]='l'; - fmt[2]='f'; - fmt[3]=0; + fmt[1] = 'l'; + fmt[2] = 'f'; + fmt[3] = 0; - } else if(p_decimals<10) { - fmt[2]='0'+p_decimals; - fmt[3]='l'; - fmt[4]='f'; - fmt[5]=0; + } else if (p_decimals < 10) { + fmt[2] = '0' + p_decimals; + fmt[3] = 'l'; + fmt[4] = 'f'; + fmt[5] = 0; } else { - fmt[2]='0'+(p_decimals/10); - fmt[3]='0'+(p_decimals%10); - fmt[4]='l'; - fmt[5]='f'; - fmt[6]=0; - + fmt[2] = '0' + (p_decimals / 10); + fmt[3] = '0' + (p_decimals % 10); + fmt[4] = 'l'; + fmt[5] = 'f'; + fmt[6] = 0; } char buf[256]; #if defined(__GNUC__) || defined(_MSC_VER) - snprintf(buf,256,fmt,p_num); + snprintf(buf, 256, fmt, p_num); #else - sprintf(buf,fmt,p_num); + sprintf(buf, fmt, p_num); #endif - buf[255]=0; + buf[255] = 0; //destroy trailing zeroes { - bool period=false; - int z=0; - while(buf[z]) { - if (buf[z]=='.') - period=true; + bool period = false; + int z = 0; + while (buf[z]) { + if (buf[z] == '.') + period = true; z++; } if (period) { z--; - while(z>0) { - + while (z > 0) { - if (buf[z]=='0') { + if (buf[z] == '0') { - buf[z]=0; - } else if (buf[z]=='.') { + buf[z] = 0; + } else if (buf[z] == '.') { - buf[z]=0; + buf[z] = 0; break; } else { @@ -978,13 +920,10 @@ String String::num(double p_num,int p_decimals) { } z--; - } } } - - return buf; #else @@ -992,55 +931,49 @@ String String::num(double p_num,int p_decimals) { String sd; /* integer part */ - bool neg=p_num<0; - p_num=ABS(p_num); - int intn=(int)p_num; - + bool neg = p_num < 0; + p_num = ABS(p_num); + int intn = (int)p_num; /* decimal part */ + if (p_decimals > 0 || (p_decimals == -1 && (int)p_num != p_num)) { - if (p_decimals>0 || (p_decimals==-1 && (int)p_num!=p_num)) { - - double dec=p_num-(float)((int)p_num); + double dec = p_num - (float)((int)p_num); - int digit=0; - if (p_decimals>MAX_DIGITS) - p_decimals=MAX_DIGITS; + int digit = 0; + if (p_decimals > MAX_DIGITS) + p_decimals = MAX_DIGITS; - int dec_int=0; - int dec_max=0; + int dec_int = 0; + int dec_max = 0; while (true) { - dec*=10.0; - dec_int=dec_int*10+(int)dec%10; - dec_max=dec_max*10+9; + dec *= 10.0; + dec_int = dec_int * 10 + (int)dec % 10; + dec_max = dec_max * 10 + 9; digit++; + if (p_decimals == -1) { - - if (p_decimals==-1) { - - if (digit==MAX_DIGITS) //no point in going to infinite + if (digit == MAX_DIGITS) //no point in going to infinite break; - if ((dec-(float)((int)dec))<1e-6) + if ((dec - (float)((int)dec)) < 1e-6) break; } - if (digit==p_decimals) + if (digit == p_decimals) break; - - } - dec*=10; - int last=(int)dec%10; + dec *= 10; + int last = (int)dec % 10; - if (last>5) { - if (dec_int==dec_max) { + if (last > 5) { + if (dec_int == dec_max) { - dec_int=0; + dec_int = 0; intn++; } else { @@ -1049,73 +982,69 @@ String String::num(double p_num,int p_decimals) { } String decimal; - for (int i=0;i<digit;i++) { - - char num[2]={0,0}; - num[0]='0'+dec_int%10; - decimal=num+decimal; - dec_int/=10; + for (int i = 0; i < digit; i++) { + char num[2] = { 0, 0 }; + num[0] = '0' + dec_int % 10; + decimal = num + decimal; + dec_int /= 10; } - sd='.'+decimal; - + sd = '.' + decimal; } - if (intn==0) + if (intn == 0) - s="0"; + s = "0"; else { - while(intn) { - - CharType num='0'+(intn%10); - intn/=10; - s=num+s; + while (intn) { + CharType num = '0' + (intn % 10); + intn /= 10; + s = num + s; } } - s=s+sd; + s = s + sd; if (neg) - s="-"+s; + s = "-" + s; return s; #endif - } String String::num_int64(int64_t p_num, int base, bool capitalize_hex) { - bool sign=p_num<0; - int64_t num=ABS(p_num); + bool sign = p_num < 0; + int64_t num = ABS(p_num); - int64_t n=num; + int64_t n = num; - int chars=0; + int chars = 0; do { - n/=base; + n /= base; chars++; - } while(n); + } while (n); if (sign) chars++; String s; - s.resize(chars+1); - CharType *c=s.ptr(); - c[chars]=0; - n=num; + s.resize(chars + 1); + CharType *c = s.ptr(); + c[chars] = 0; + n = num; do { - int mod = n%base; + int mod = n % base; if (mod >= 10) { char a = (capitalize_hex ? 'A' : 'a'); - c[--chars]=a+(mod - 10); + c[--chars] = a + (mod - 10); } else { - c[--chars]='0'+mod; + c[--chars] = '0' + mod; } - n/=base; - } while(n); + n /= base; + } while (n); if (sign) - c[0]='-'; + c[0] = '-'; return s; } @@ -1126,45 +1055,43 @@ String String::num_real(double p_num) { String sd; /* integer part */ - bool neg=p_num<0; - p_num=ABS(p_num); - int intn=(int)p_num; + bool neg = p_num < 0; + p_num = ABS(p_num); + int intn = (int)p_num; /* decimal part */ + if ((int)p_num != p_num) { - if ((int)p_num!=p_num) { - - double dec=p_num-(float)((int)p_num); + double dec = p_num - (float)((int)p_num); - int digit=0; - int decimals=MAX_DIGITS; + int digit = 0; + int decimals = MAX_DIGITS; - int dec_int=0; - int dec_max=0; + int dec_int = 0; + int dec_max = 0; while (true) { - dec*=10.0; - dec_int=dec_int*10+(int)dec%10; - dec_max=dec_max*10+9; + dec *= 10.0; + dec_int = dec_int * 10 + (int)dec % 10; + dec_max = dec_max * 10 + 9; digit++; - if ((dec-(float)((int)dec))<1e-6) + if ((dec - (float)((int)dec)) < 1e-6) break; - if (digit==decimals) + if (digit == decimals) break; - } - dec*=10; - int last=(int)dec%10; + dec *= 10; + int last = (int)dec % 10; - if (last>5) { - if (dec_int==dec_max) { + if (last > 5) { + if (dec_int == dec_max) { - dec_int=0; + dec_int = 0; intn++; } else { @@ -1173,54 +1100,49 @@ String String::num_real(double p_num) { } String decimal; - for (int i=0;i<digit;i++) { - - char num[2]={0,0}; - num[0]='0'+dec_int%10; - decimal=num+decimal; - dec_int/=10; + for (int i = 0; i < digit; i++) { + char num[2] = { 0, 0 }; + num[0] = '0' + dec_int % 10; + decimal = num + decimal; + dec_int /= 10; } - sd='.'+decimal; + sd = '.' + decimal; } else { - sd=".0"; + sd = ".0"; } - if (intn==0) + if (intn == 0) - s="0"; + s = "0"; else { - while(intn) { - - CharType num='0'+(intn%10); - intn/=10; - s=num+s; + while (intn) { + CharType num = '0' + (intn % 10); + intn /= 10; + s = num + s; } } - s=s+sd; + s = s + sd; if (neg) - s="-"+s; + s = "-" + s; return s; - } - String String::num_scientific(double p_num) { #ifndef NO_USE_STDLIB - char buf[256]; #if defined(__GNUC__) || defined(_MSC_VER) - snprintf(buf,256,"%lg",p_num); + snprintf(buf, 256, "%lg", p_num); #else - sprintf(buf,"%.16lg",p_num); + sprintf(buf, "%.16lg", p_num); #endif - buf[255]=0; + buf[255] = 0; return buf; #else @@ -1237,17 +1159,16 @@ CharString String::ascii(bool p_allow_extended) const { CharString cs; cs.resize(size()); - for (int i=0;i<size();i++) - cs[i]=operator[](i); + for (int i = 0; i < size(); i++) + cs[i] = operator[](i); return cs; - } -String String::utf8(const char* p_utf8,int p_len) { +String String::utf8(const char *p_utf8, int p_len) { String ret; - ret.parse_utf8(p_utf8,p_len); + ret.parse_utf8(p_utf8, p_len); return ret; }; @@ -1311,57 +1232,57 @@ _FORCE_INLINE static int parse_utf8_char(const char *p_utf8,unsigned int *p_ucs4 } #endif -bool String::parse_utf8(const char* p_utf8,int p_len) { +bool String::parse_utf8(const char *p_utf8, int p_len) { -#define _UNICERROR(m_err) print_line("unicode error: "+String(m_err)); +#define _UNICERROR(m_err) print_line("unicode error: " + String(m_err)); String aux; - int cstr_size=0; - int str_size=0; + int cstr_size = 0; + int str_size = 0; /* HANDLE BOM (Byte Order Mark) */ - if (p_len<0 || p_len>=3) { + if (p_len < 0 || p_len >= 3) { - bool has_bom = uint8_t(p_utf8[0])==0xEF && uint8_t(p_utf8[1])==0xBB && uint8_t(p_utf8[2])==0xBF; + bool has_bom = uint8_t(p_utf8[0]) == 0xEF && uint8_t(p_utf8[1]) == 0xBB && uint8_t(p_utf8[2]) == 0xBF; if (has_bom) { //just skip it - if (p_len>=0) - p_len-=3; - p_utf8+=3; + if (p_len >= 0) + p_len -= 3; + p_utf8 += 3; } } { - const char *ptrtmp=p_utf8; - const char *ptrtmp_limit=&p_utf8[p_len]; - int skip=0; - while (ptrtmp!=ptrtmp_limit && *ptrtmp) { + const char *ptrtmp = p_utf8; + const char *ptrtmp_limit = &p_utf8[p_len]; + int skip = 0; + while (ptrtmp != ptrtmp_limit && *ptrtmp) { - if (skip==0) { + if (skip == 0) { uint8_t c = *ptrtmp; /* Determine the number of characters in sequence */ - if ((c & 0x80)==0) - skip=0; - else if ((c & 0xE0)==0xC0) - skip=1; - else if ((c & 0xF0)==0xE0) - skip=2; - else if ((c & 0xF8)==0xF0) - skip=3; - else if ((c & 0xFC)==0xF8) - skip=4; - else if ((c & 0xFE)==0xFC) - skip=5; + if ((c & 0x80) == 0) + skip = 0; + else if ((c & 0xE0) == 0xC0) + skip = 1; + else if ((c & 0xF0) == 0xE0) + skip = 2; + else if ((c & 0xF8) == 0xF0) + skip = 3; + else if ((c & 0xFC) == 0xF8) + skip = 4; + else if ((c & 0xFE) == 0xFC) + skip = 5; else { _UNICERROR("invalid skip"); return true; //invalid utf8 } - if (skip==1 && (c&0x1E)==0) { + if (skip == 1 && (c & 0x1E) == 0) { //printf("overlong rejected\n"); _UNICERROR("overlong rejected"); return true; //reject overlong @@ -1369,7 +1290,6 @@ bool String::parse_utf8(const char* p_utf8,int p_len) { str_size++; - } else { --skip; @@ -1383,48 +1303,46 @@ bool String::parse_utf8(const char* p_utf8,int p_len) { _UNICERROR("no space left"); return true; //not enough spac } - } - if (str_size==0) { + if (str_size == 0) { clear(); return false; } - resize(str_size+1); + resize(str_size + 1); CharType *dst = &operator[](0); - dst[str_size]=0; + dst[str_size] = 0; while (cstr_size) { - - int len=0; - - /* Determine the number of characters in sequence */ - if ((*p_utf8 & 0x80)==0) - len=1; - else if ((*p_utf8 & 0xE0)==0xC0) - len=2; - else if ((*p_utf8 & 0xF0)==0xE0) - len=3; - else if ((*p_utf8 & 0xF8)==0xF0) - len=4; - else if ((*p_utf8 & 0xFC)==0xF8) - len=5; - else if ((*p_utf8 & 0xFE)==0xFC) - len=6; + int len = 0; + + /* Determine the number of characters in sequence */ + if ((*p_utf8 & 0x80) == 0) + len = 1; + else if ((*p_utf8 & 0xE0) == 0xC0) + len = 2; + else if ((*p_utf8 & 0xF0) == 0xE0) + len = 3; + else if ((*p_utf8 & 0xF8) == 0xF0) + len = 4; + else if ((*p_utf8 & 0xFC) == 0xF8) + len = 5; + else if ((*p_utf8 & 0xFE) == 0xFC) + len = 6; else { _UNICERROR("invalid len"); return true; //invalid UTF8 } - if (len>cstr_size) { + if (len > cstr_size) { _UNICERROR("no space left"); return true; //not enough space } - if (len==2 && (*p_utf8&0x1E)==0) { + if (len == 2 && (*p_utf8 & 0x1E) == 0) { //printf("overlong rejected\n"); _UNICERROR("no space left"); return true; //reject overlong @@ -1432,21 +1350,21 @@ bool String::parse_utf8(const char* p_utf8,int p_len) { /* Convert the first character */ - uint32_t unichar=0; + uint32_t unichar = 0; if (len == 1) - unichar=*p_utf8; + unichar = *p_utf8; else { - unichar=(0xFF >> (len +1)) & *p_utf8; + unichar = (0xFF >> (len + 1)) & *p_utf8; - for (int i=1;i<len;i++) { + for (int i = 1; i < len; i++) { if ((p_utf8[i] & 0xC0) != 0x80) { _UNICERROR("invalid utf8"); return true; //invalid utf8 } - if (unichar==0 && i==2 && ((p_utf8[i] & 0x7F) >> (7 - len)) == 0) { + if (unichar == 0 && i == 2 && ((p_utf8[i] & 0x7F) >> (7 - len)) == 0) { _UNICERROR("invalid utf8 overlong"); return true; //no overlong } @@ -1455,104 +1373,99 @@ bool String::parse_utf8(const char* p_utf8,int p_len) { } //printf("char %i, len %i\n",unichar,len); - if (sizeof(wchar_t)==2 && unichar>0xFFFF) { - unichar=' '; //too long for windows - + if (sizeof(wchar_t) == 2 && unichar > 0xFFFF) { + unichar = ' '; //too long for windows } *(dst++) = unichar; - cstr_size-=len; + cstr_size -= len; p_utf8 += len; } return false; } - - CharString String::utf8() const { int l = length(); if (!l) return CharString(); - const CharType *d=&operator[](0); - int fl=0; - for (int i=0;i<l;i++) { + const CharType *d = &operator[](0); + int fl = 0; + for (int i = 0; i < l; i++) { - uint32_t c=d[i]; + uint32_t c = d[i]; if (c <= 0x7f) // 7 bits. - fl+=1; - else if (c <= 0x7ff) { // 11 bits - fl+=2; + fl += 1; + else if (c <= 0x7ff) { // 11 bits + fl += 2; } else if (c <= 0xffff) { // 16 bits - fl+=3; + fl += 3; } else if (c <= 0x001fffff) { // 21 bits - fl+=4; + fl += 4; } else if (c <= 0x03ffffff) { // 26 bits - fl+=5; - } else if (c <= 0x7fffffff) { // 31 bits - fl+=6; + fl += 5; + } else if (c <= 0x7fffffff) { // 31 bits + fl += 6; } } - CharString utf8s; - if (fl==0) { + if (fl == 0) { return utf8s; } - utf8s.resize(fl+1); - uint8_t *cdst=(uint8_t*)utf8s.get_data(); + utf8s.resize(fl + 1); + uint8_t *cdst = (uint8_t *)utf8s.get_data(); -#define APPEND_CHAR( m_c ) *(cdst++) = m_c +#define APPEND_CHAR(m_c) *(cdst++) = m_c - for (int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - uint32_t c=d[i]; + uint32_t c = d[i]; if (c <= 0x7f) // 7 bits. - APPEND_CHAR( c ); - else if (c <= 0x7ff) { // 11 bits + APPEND_CHAR(c); + else if (c <= 0x7ff) { // 11 bits - APPEND_CHAR( uint32_t(0xc0 | ((c >> 6) & 0x1f)) ); // Top 5 bits. - APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits. + APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits. + APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits. } else if (c <= 0xffff) { // 16 bits - APPEND_CHAR( uint32_t(0xe0 | ((c >> 12) & 0x0f)) ); // Top 4 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits. + APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits. } else if (c <= 0x001fffff) { // 21 bits - APPEND_CHAR( uint32_t(0xf0 | ((c >> 18) & 0x07)) ); // Top 3 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 12) & 0x3f)) ); // Upper middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Lower middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits. + APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits. } else if (c <= 0x03ffffff) { // 26 bits - APPEND_CHAR( uint32_t(0xf8 | ((c >> 24) & 0x03)) ); // Top 2 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 18) & 0x3f)) ); // Upper middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 12) & 0x3f)) ); // middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Lower middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits. - } else if (c <= 0x7fffffff) { // 31 bits - - APPEND_CHAR( uint32_t(0xfc | ((c >> 30) & 0x01)) ); // Top 1 bit. - APPEND_CHAR( uint32_t(0x80 | ((c >> 24) & 0x3f)) ); // Upper upper middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 18) & 0x3f)) ); // Lower upper middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 12) & 0x3f)) ); // Upper lower middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Lower lower middle 6 bits. - APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits. + APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits. + } else if (c <= 0x7fffffff) { // 31 bits + + APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit. + APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits. + APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits. } } #undef APPEND_CHAR - *cdst=0; //trailing zero + *cdst = 0; //trailing zero return utf8s; } - /* String::String(CharType p_char) { @@ -1565,203 +1478,194 @@ String::String(const char *p_str) { copy_from(p_str); } -String::String(const CharType *p_str,int p_clip_to_len) { +String::String(const CharType *p_str, int p_clip_to_len) { - copy_from(p_str,p_clip_to_len); + copy_from(p_str, p_clip_to_len); } - -String::String(const StrRange& p_range) { +String::String(const StrRange &p_range) { if (!p_range.c_str) return; - copy_from(p_range.c_str,p_range.len); + copy_from(p_range.c_str, p_range.len); } int String::hex_to_int(bool p_with_prefix) const { int l = length(); - if (p_with_prefix && l<3) + if (p_with_prefix && l < 3) return 0; - const CharType *s=ptr(); + const CharType *s = ptr(); - int sign = s[0]=='-' ? -1 : 1; + int sign = s[0] == '-' ? -1 : 1; - if (sign<0) { + if (sign < 0) { s++; l--; - if (p_with_prefix && l<2) + if (p_with_prefix && l < 2) return 0; } if (p_with_prefix) { - if (s[0]!='0' || s[1]!='x') + if (s[0] != '0' || s[1] != 'x') return 0; - s+=2; - l-=2; + s += 2; + l -= 2; }; - int hex=0; + int hex = 0; - while(*s) { + while (*s) { CharType c = LOWERCASE(*s); int n; - if (c>='0' && c<='9') { - n=c-'0'; - } else if (c>='a' && c<='f') { - n=(c-'a')+10; + if (c >= '0' && c <= '9') { + n = c - '0'; + } else if (c >= 'a' && c <= 'f') { + n = (c - 'a') + 10; } else { return 0; } - hex*=16; - hex+=n; + hex *= 16; + hex += n; s++; } - return hex*sign; - + return hex * sign; } - int64_t String::hex_to_int64(bool p_with_prefix) const { int l = length(); - if (p_with_prefix && l<3) + if (p_with_prefix && l < 3) return 0; - const CharType *s=ptr(); + const CharType *s = ptr(); - int64_t sign = s[0]=='-' ? -1 : 1; + int64_t sign = s[0] == '-' ? -1 : 1; - if (sign<0) { + if (sign < 0) { s++; l--; - if (p_with_prefix && l<2) + if (p_with_prefix && l < 2) return 0; } if (p_with_prefix) { - if (s[0]!='0' || s[1]!='x') + if (s[0] != '0' || s[1] != 'x') return 0; - s+=2; - l-=2; + s += 2; + l -= 2; }; - int64_t hex=0; + int64_t hex = 0; - while(*s) { + while (*s) { CharType c = LOWERCASE(*s); int64_t n; - if (c>='0' && c<='9') { - n=c-'0'; - } else if (c>='a' && c<='f') { - n=(c-'a')+10; + if (c >= '0' && c <= '9') { + n = c - '0'; + } else if (c >= 'a' && c <= 'f') { + n = (c - 'a') + 10; } else { return 0; } - hex*=16; - hex+=n; + hex *= 16; + hex += n; s++; } - return hex*sign; - + return hex * sign; } int String::to_int() const { - if (length()==0) + if (length() == 0) return 0; - int to=(find(".")>=0) ? find(".") : length() ; + int to = (find(".") >= 0) ? find(".") : length(); - int integer=0; - int sign=1; + int integer = 0; + int sign = 1; - for (int i=0;i<to;i++) { + for (int i = 0; i < to; i++) { - CharType c=operator[](i); - if (c>='0' && c<='9') { + CharType c = operator[](i); + if (c >= '0' && c <= '9') { - integer*=10; - integer+=c-'0'; + integer *= 10; + integer += c - '0'; - } else if (integer==0 && c=='-') { + } else if (integer == 0 && c == '-') { - sign=-sign; + sign = -sign; } - } - return integer*sign; + return integer * sign; } int64_t String::to_int64() const { - if (length()==0) + if (length() == 0) return 0; - int to=(find(".")>=0) ? find(".") : length() ; + int to = (find(".") >= 0) ? find(".") : length(); - int64_t integer=0; - int64_t sign=1; + int64_t integer = 0; + int64_t sign = 1; - for (int i=0;i<to;i++) { + for (int i = 0; i < to; i++) { - CharType c=operator[](i); - if (c>='0' && c<='9') { + CharType c = operator[](i); + if (c >= '0' && c <= '9') { - integer*=10; - integer+=c-'0'; + integer *= 10; + integer += c - '0'; - } else if (integer==0 && c=='-') { + } else if (integer == 0 && c == '-') { - sign=-sign; + sign = -sign; } - } - return integer*sign; + return integer * sign; } -int String::to_int(const char* p_str,int p_len) { - +int String::to_int(const char *p_str, int p_len) { - int to=0; - if (p_len>=0) - to=p_len; + int to = 0; + if (p_len >= 0) + to = p_len; else { - while(p_str[to]!=0 && p_str[to]!='.') + while (p_str[to] != 0 && p_str[to] != '.') to++; } + int integer = 0; + int sign = 1; - int integer=0; - int sign=1; + for (int i = 0; i < to; i++) { - for (int i=0;i<to;i++) { + char c = p_str[i]; + if (c >= '0' && c <= '9') { - char c=p_str[i]; - if (c>='0' && c<='9') { + integer *= 10; + integer += c - '0'; - integer*=10; - integer+=c-'0'; + } else if (c == '-' && integer == 0) { - } else if (c=='-' && integer==0) { - - sign=-sign; - } else if (c!=' ') + sign = -sign; + } else if (c != ' ') break; - } - return integer*sign; + return integer * sign; } bool String::is_numeric() const { @@ -1773,7 +1677,7 @@ bool String::is_numeric() const { int s = 0; if (operator[](0) == '-') ++s; bool dot = false; - for (int i=s; i<length(); i++) { + for (int i = s; i < length(); i++) { CharType c = operator[](i); if (c == '.') { @@ -1790,11 +1694,11 @@ bool String::is_numeric() const { return true; // TODO: Use the parser below for this instead }; -#define IS_DIGIT(m_d) ( (m_d)>='0' && (m_d)<='9' ) -#define IS_HEX_DIGIT(m_d) ( ( (m_d)>='0' && (m_d)<='9' ) || ( (m_d)>='a' && (m_d)<='f' ) || ( (m_d)>='A' && (m_d)<='F' ) ) +#define IS_DIGIT(m_d) ((m_d) >= '0' && (m_d) <= '9') +#define IS_HEX_DIGIT(m_d) (((m_d) >= '0' && (m_d) <= '9') || ((m_d) >= 'a' && (m_d) <= 'f') || ((m_d) >= 'A' && (m_d) <= 'F')) -template<class C> -static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number, +template <class C> +static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number, * optionally preceded by white space. Must * have form "-I.FE-X", where I is the integer * part of the mantissa, F is the fractional @@ -1805,36 +1709,34 @@ static double built_in_strtod(const C *string, /* A decimal ASCII floati * necessary unless F is present. The "E" may * actually be an "e". E and X may both be * omitted (but not just one). */ - C **endPtr=NULL) /* If non-NULL, store terminating Cacter's + C **endPtr = NULL) /* If non-NULL, store terminating Cacter's * address here. */ { - - static const int maxExponent = 511; /* Largest possible base 10 exponent. Any + static const int maxExponent = 511; /* Largest possible base 10 exponent. Any * exponent larger than this will already * produce underflow or overflow, so there's * no need to worry about additional digits. */ - static const double powersOf10[] = { /* Table giving binary powers of 10. Entry */ - 10., /* is 10^2^i. Used to convert decimal */ - 100., /* exponents into floating-point numbers. */ - 1.0e4, - 1.0e8, - 1.0e16, - 1.0e32, - 1.0e64, - 1.0e128, - 1.0e256 + static const double powersOf10[] = { /* Table giving binary powers of 10. Entry */ + 10., /* is 10^2^i. Used to convert decimal */ + 100., /* exponents into floating-point numbers. */ + 1.0e4, + 1.0e8, + 1.0e16, + 1.0e32, + 1.0e64, + 1.0e128, + 1.0e256 }; - - int sign, expSign = false; - double fraction, dblExp; - const double *d; - register const C *p; - register int c; - int exp = 0; /* Exponent read from "EX" field. */ - int fracExp = 0; /* Exponent that derives from the fractional + int sign, expSign = false; + double fraction, dblExp; + const double *d; + register const C *p; + register int c; + int exp = 0; /* Exponent read from "EX" field. */ + int fracExp = 0; /* Exponent that derives from the fractional * part. Under normal circumstatnces, it is * the negative of the number of digits in F. * However, if I is very long, the last digits @@ -1843,182 +1745,179 @@ static double built_in_strtod(const C *string, /* A decimal ASCII floati * unnecessary overflow on I alone). In this * case, fracExp is incremented one for each * dropped digit. */ - int mantSize; /* Number of digits in mantissa. */ - int decPt; /* Number of mantissa digits BEFORE decimal + int mantSize; /* Number of digits in mantissa. */ + int decPt; /* Number of mantissa digits BEFORE decimal * point. */ - const C *pExp; /* Temporarily holds location of exponent in + const C *pExp; /* Temporarily holds location of exponent in * string. */ - /* + /* * Strip off leading blanks and check for a sign. */ - p = string; - while (*p == ' ' || *p=='\t' || *p=='\n') { - p += 1; - } - if (*p == '-') { - sign = true; - p += 1; - } else { - if (*p == '+') { - p += 1; - } - sign = false; - } - - /* + p = string; + while (*p == ' ' || *p == '\t' || *p == '\n') { + p += 1; + } + if (*p == '-') { + sign = true; + p += 1; + } else { + if (*p == '+') { + p += 1; + } + sign = false; + } + + /* * Count the number of digits in the mantissa (including the decimal * point), and also locate the decimal point. */ - decPt = -1; - for (mantSize = 0; ; mantSize += 1) - { - c = *p; - if (!IS_DIGIT(c)) { - if ((c != '.') || (decPt >= 0)) { - break; - } - decPt = mantSize; + decPt = -1; + for (mantSize = 0;; mantSize += 1) { + c = *p; + if (!IS_DIGIT(c)) { + if ((c != '.') || (decPt >= 0)) { + break; + } + decPt = mantSize; + } + p += 1; } - p += 1; - } - /* + /* * Now suck up the digits in the mantissa. Use two integers to collect 9 * digits each (this is faster than using floating-point). If the mantissa * has more than 18 digits, ignore the extras, since they can't affect the * value anyway. */ - pExp = p; - p -= mantSize; - if (decPt < 0) { - decPt = mantSize; - } else { - mantSize -= 1; /* One of the digits was the point. */ - } - if (mantSize > 18) { - fracExp = decPt - 18; - mantSize = 18; - } else { - fracExp = decPt - mantSize; - } - if (mantSize == 0) { - fraction = 0.0; - p = string; - goto done; - } else { - int frac1, frac2; - - frac1 = 0; - for ( ; mantSize > 9; mantSize -= 1) { - c = *p; - p += 1; - if (c == '.') { - c = *p; - p += 1; - } - frac1 = 10*frac1 + (c - '0'); - } - frac2 = 0; - for (; mantSize > 0; mantSize -= 1) { - c = *p; - p += 1; - if (c == '.') { - c = *p; - p += 1; - } - frac2 = 10*frac2 + (c - '0'); + pExp = p; + p -= mantSize; + if (decPt < 0) { + decPt = mantSize; + } else { + mantSize -= 1; /* One of the digits was the point. */ + } + if (mantSize > 18) { + fracExp = decPt - 18; + mantSize = 18; + } else { + fracExp = decPt - mantSize; + } + if (mantSize == 0) { + fraction = 0.0; + p = string; + goto done; + } else { + int frac1, frac2; + + frac1 = 0; + for (; mantSize > 9; mantSize -= 1) { + c = *p; + p += 1; + if (c == '.') { + c = *p; + p += 1; + } + frac1 = 10 * frac1 + (c - '0'); + } + frac2 = 0; + for (; mantSize > 0; mantSize -= 1) { + c = *p; + p += 1; + if (c == '.') { + c = *p; + p += 1; + } + frac2 = 10 * frac2 + (c - '0'); + } + fraction = (1.0e9 * frac1) + frac2; } - fraction = (1.0e9 * frac1) + frac2; - } - /* + /* * Skim off the exponent. */ - p = pExp; - if ((*p == 'E') || (*p == 'e')) { - p += 1; - if (*p == '-') { - expSign = true; - p += 1; - } else { - if (*p == '+') { + p = pExp; + if ((*p == 'E') || (*p == 'e')) { p += 1; - } - expSign = false; - } - if (!IS_DIGIT(CharType(*p))) { - p = pExp; - goto done; + if (*p == '-') { + expSign = true; + p += 1; + } else { + if (*p == '+') { + p += 1; + } + expSign = false; + } + if (!IS_DIGIT(CharType(*p))) { + p = pExp; + goto done; + } + while (IS_DIGIT(CharType(*p))) { + exp = exp * 10 + (*p - '0'); + p += 1; + } } - while (IS_DIGIT(CharType(*p))) { - exp = exp * 10 + (*p - '0'); - p += 1; + if (expSign) { + exp = fracExp - exp; + } else { + exp = fracExp + exp; } - } - if (expSign) { - exp = fracExp - exp; - } else { - exp = fracExp + exp; - } - /* + /* * Generate a floating-point number that represents the exponent. Do this * by processing the exponent one bit at a time to combine many powers of * 2 of 10. Then combine the exponent with the fraction. */ - if (exp < 0) { - expSign = true; - exp = -exp; - } else { - expSign = false; - } + if (exp < 0) { + expSign = true; + exp = -exp; + } else { + expSign = false; + } - if (exp > maxExponent) { - exp = maxExponent; - WARN_PRINT("Exponent too high"); - } - dblExp = 1.0; - for (d = powersOf10; exp != 0; exp >>= 1, ++d) { - if (exp & 01) { - dblExp *= *d; + if (exp > maxExponent) { + exp = maxExponent; + WARN_PRINT("Exponent too high"); + } + dblExp = 1.0; + for (d = powersOf10; exp != 0; exp >>= 1, ++d) { + if (exp & 01) { + dblExp *= *d; + } + } + if (expSign) { + fraction /= dblExp; + } else { + fraction *= dblExp; } - } - if (expSign) { - fraction /= dblExp; - } else { - fraction *= dblExp; - } - done: - if (endPtr != NULL) { - *endPtr = (C *) p; - } +done: + if (endPtr != NULL) { + *endPtr = (C *)p; + } - if (sign) { - return -fraction; - } - return fraction; + if (sign) { + return -fraction; + } + return fraction; } - - #define READING_SIGN 0 #define READING_INT 1 #define READING_DEC 2 #define READING_EXP 3 #define READING_DONE 4 -double String::to_double(const char* p_str) { +double String::to_double(const char *p_str) { #ifndef NO_USE_STDLIB return built_in_strtod<char>(p_str); - //return atof(p_str); DOES NOT WORK ON ANDROID(??) +//return atof(p_str); DOES NOT WORK ON ANDROID(??) #else return built_in_strtod<char>(p_str); #endif @@ -2112,15 +2011,14 @@ double String::to_double(const char* p_str) { #endif } - float String::to_float() const { return to_double(); } -double String::to_double(const CharType* p_str, const CharType **r_end) { +double String::to_double(const CharType *p_str, const CharType **r_end) { - return built_in_strtod<CharType>(p_str,(CharType**)r_end); + return built_in_strtod<CharType>(p_str, (CharType **)r_end); #if 0 #if 0 //ndef NO_USE_STDLIB @@ -2217,34 +2115,34 @@ double String::to_double(const CharType* p_str, const CharType **r_end) { #endif } -int64_t String::to_int(const CharType* p_str,int p_len) { +int64_t String::to_int(const CharType *p_str, int p_len) { - if (p_len==0 || !p_str[0]) + if (p_len == 0 || !p_str[0]) return 0; -///@todo make more exact so saving and loading does not lose precision + ///@todo make more exact so saving and loading does not lose precision - int64_t integer=0; - int64_t sign=1; - int reading=READING_SIGN; + int64_t integer = 0; + int64_t sign = 1; + int reading = READING_SIGN; - const CharType *str=p_str; - const CharType *limit=&p_str[p_len]; + const CharType *str = p_str; + const CharType *limit = &p_str[p_len]; - while(*str && reading!=READING_DONE && str!=limit) { + while (*str && reading != READING_DONE && str != limit) { - CharType c=*(str++); - switch(reading) { + CharType c = *(str++); + switch (reading) { case READING_SIGN: { - if (c>='0' && c<='9') { - reading=READING_INT; + if (c >= '0' && c <= '9') { + reading = READING_INT; // let it fallthrough - } else if (c=='-') { - sign=-1; - reading=READING_INT; + } else if (c == '-') { + sign = -1; + reading = READING_INT; break; - } else if (c=='+') { - sign=1; - reading=READING_INT; + } else if (c == '+') { + sign = 1; + reading = READING_INT; break; } else { break; @@ -2252,30 +2150,28 @@ int64_t String::to_int(const CharType* p_str,int p_len) { } case READING_INT: { - if (c>='0' && c<='9') { + if (c >= '0' && c <= '9') { - integer*=10; - integer+=c-'0'; + integer *= 10; + integer += c - '0'; } else { - reading=READING_DONE; + reading = READING_DONE; } - } break; + } break; } } - return sign*integer; - + return sign * integer; } - double String::to_double() const { if (empty()) return 0; #ifndef NO_USE_STDLIB return built_in_strtod<CharType>(c_str()); - //return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :( +//return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :( #else return built_in_strtod<CharType>(c_str()); #endif @@ -2373,26 +2269,23 @@ double String::to_double() const { #endif } +bool operator==(const char *p_chr, const String &p_str) { -bool operator==(const char*p_chr, const String& p_str) { - - return p_str==p_chr; + return p_str == p_chr; } -String operator+(const char*p_chr, const String& p_str) { +String operator+(const char *p_chr, const String &p_str) { - String tmp=p_chr; - tmp+=p_str; + String tmp = p_chr; + tmp += p_str; return tmp; - } -String operator+(CharType p_chr, const String& p_str) { - - return (String::chr(p_chr)+p_str); +String operator+(CharType p_chr, const String &p_str) { + return (String::chr(p_chr) + p_str); } -uint32_t String::hash(const char* p_cstr) { +uint32_t String::hash(const char *p_cstr) { uint32_t hashv = 5381; uint32_t c; @@ -2403,25 +2296,25 @@ uint32_t String::hash(const char* p_cstr) { return hashv; } -uint32_t String::hash(const char* p_cstr,int p_len) { +uint32_t String::hash(const char *p_cstr, int p_len) { uint32_t hashv = 5381; - for(int i=0;i<p_len;i++) + for (int i = 0; i < p_len; i++) hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */ return hashv; } -uint32_t String::hash(const CharType* p_cstr,int p_len) { +uint32_t String::hash(const CharType *p_cstr, int p_len) { uint32_t hashv = 5381; - for(int i=0;i<p_len;i++) + for (int i = 0; i < p_len; i++) hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */ return hashv; } -uint32_t String::hash(const CharType* p_cstr) { +uint32_t String::hash(const CharType *p_cstr) { uint32_t hashv = 5381; uint32_t c; @@ -2436,7 +2329,7 @@ uint32_t String::hash() const { /* simple djb2 hashing */ - const CharType * chr = c_str(); + const CharType *chr = c_str(); uint32_t hashv = 5381; uint32_t c; @@ -2444,15 +2337,13 @@ uint32_t String::hash() const { hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */ return hashv; - - } uint64_t String::hash64() const { /* simple djb2 hashing */ - const CharType * chr = c_str(); + const CharType *chr = c_str(); uint64_t hashv = 5381; uint64_t c; @@ -2460,41 +2351,39 @@ uint64_t String::hash64() const { hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */ return hashv; - - } String String::md5_text() const { - CharString cs=utf8(); + CharString cs = utf8(); MD5_CTX ctx; MD5Init(&ctx); - MD5Update(&ctx,(unsigned char*)cs.ptr(),cs.length()); + MD5Update(&ctx, (unsigned char *)cs.ptr(), cs.length()); MD5Final(&ctx); return String::md5(ctx.digest); } String String::sha256_text() const { - CharString cs=utf8(); + CharString cs = utf8(); unsigned char hash[32]; sha256_context ctx; sha256_init(&ctx); - sha256_hash(&ctx,(unsigned char*)cs.ptr(),cs.length()); + sha256_hash(&ctx, (unsigned char *)cs.ptr(), cs.length()); sha256_done(&ctx, hash); return String::hex_encode_buffer(hash, 32); } Vector<uint8_t> String::md5_buffer() const { - CharString cs=utf8(); + CharString cs = utf8(); MD5_CTX ctx; MD5Init(&ctx); - MD5Update(&ctx,(unsigned char*)cs.ptr(),cs.length()); + MD5Update(&ctx, (unsigned char *)cs.ptr(), cs.length()); MD5Final(&ctx); Vector<uint8_t> ret; ret.resize(16); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { ret[i] = ctx.digest[i]; }; @@ -2506,7 +2395,7 @@ Vector<uint8_t> String::sha256_buffer() const { unsigned char hash[32]; sha256_context ctx; sha256_init(&ctx); - sha256_hash(&ctx, (unsigned char*)cs.ptr(), cs.length()); + sha256_hash(&ctx, (unsigned char *)cs.ptr(), cs.length()); sha256_done(&ctx, hash); Vector<uint8_t> ret; @@ -2518,85 +2407,79 @@ Vector<uint8_t> String::sha256_buffer() const { return ret; } +String String::insert(int p_at_pos, String p_string) const { -String String::insert(int p_at_pos,String p_string) const { - - if (p_at_pos<0) + if (p_at_pos < 0) return *this; - if (p_at_pos>length()) - p_at_pos=length(); - + if (p_at_pos > length()) + p_at_pos = length(); String pre; - if (p_at_pos>0) - pre=substr( 0, p_at_pos ); + if (p_at_pos > 0) + pre = substr(0, p_at_pos); String post; - if (p_at_pos<length()) - post=substr( p_at_pos, length()-p_at_pos); - - return pre+p_string+post; + if (p_at_pos < length()) + post = substr(p_at_pos, length() - p_at_pos); + return pre + p_string + post; } -String String::substr(int p_from,int p_chars) const{ +String String::substr(int p_from, int p_chars) const { - if (empty() || p_from<0 || p_from>=length() || p_chars<=0) + if (empty() || p_from < 0 || p_from >= length() || p_chars <= 0) return ""; - if ( (p_from+p_chars)>length()) { + if ((p_from + p_chars) > length()) { - p_chars=length()-p_from; + p_chars = length() - p_from; } - return String(&c_str()[p_from],p_chars); - + return String(&c_str()[p_from], p_chars); } int String::find_last(String p_str) const { - int pos=-1; - int findfrom=0; - int findres=-1; - while((findres=find(p_str,findfrom))!=-1) { + int pos = -1; + int findfrom = 0; + int findres = -1; + while ((findres = find(p_str, findfrom)) != -1) { - pos=findres; - findfrom=pos+1; + pos = findres; + findfrom = pos + 1; } return pos; } -int String::find(String p_str,int p_from) const { +int String::find(String p_str, int p_from) const { - if (p_from<0) + if (p_from < 0) return -1; - int src_len=p_str.length(); + int src_len = p_str.length(); - int len=length(); + int len = length(); - if(src_len==0 || len==0) + if (src_len == 0 || len == 0) return -1; //wont find anything! - const CharType *src = c_str(); - for (int i=p_from;i<=(len-src_len);i++) { + for (int i = p_from; i <= (len - src_len); i++) { - bool found=true; - for (int j=0;j<src_len;j++) { + bool found = true; + for (int j = 0; j < src_len; j++) { - int read_pos=i+j; + int read_pos = i + j; - if (read_pos>=len) { + if (read_pos >= len) { ERR_PRINT("read_pos>=len"); return -1; }; - - if (src[read_pos]!=p_str[j]) { - found=false; + if (src[read_pos] != p_str[j]) { + found = false; break; } } @@ -2608,48 +2491,46 @@ int String::find(String p_str,int p_from) const { return -1; } -int String::findmk(const Vector<String>& p_keys,int p_from,int *r_key) const { +int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const { - if (p_from<0) + if (p_from < 0) return -1; - if (p_keys.size()==0) + if (p_keys.size() == 0) return -1; //int src_len=p_str.length(); - const String *keys=&p_keys[0]; - int key_count=p_keys.size(); + const String *keys = &p_keys[0]; + int key_count = p_keys.size(); int len = length(); - if(len==0) + if (len == 0) return -1; //wont find anything! const CharType *src = c_str(); + for (int i = p_from; i < len; i++) { - for (int i=p_from;i<len;i++) { - - bool found=true; - for(int k=0;k<key_count;k++) { + bool found = true; + for (int k = 0; k < key_count; k++) { - found=true; + found = true; if (r_key) - *r_key=k; - const CharType *cmp=keys[k].c_str(); - int l=keys[k].length(); + *r_key = k; + const CharType *cmp = keys[k].c_str(); + int l = keys[k].length(); - for (int j=0;j<l;j++) { + for (int j = 0; j < l; j++) { - int read_pos=i+j; + int read_pos = i + j; - if (read_pos>=len) { + if (read_pos >= len) { - found=false; + found = false; break; }; - - if (src[read_pos]!=cmp[j]) { - found=false; + if (src[read_pos] != cmp[j]) { + found = false; break; } } @@ -2662,41 +2543,38 @@ int String::findmk(const Vector<String>& p_keys,int p_from,int *r_key) const { } return -1; - } +int String::findn(String p_str, int p_from) const { -int String::findn(String p_str,int p_from) const { - - if (p_from<0) + if (p_from < 0) return -1; - int src_len=p_str.length(); + int src_len = p_str.length(); - if(src_len==0 || length()==0) + if (src_len == 0 || length() == 0) return -1; //wont find anything! const CharType *srcd = c_str(); - for (int i=p_from;i<=(length()-src_len);i++) { + for (int i = p_from; i <= (length() - src_len); i++) { - bool found=true; - for (int j=0;j<src_len;j++) { + bool found = true; + for (int j = 0; j < src_len; j++) { - int read_pos=i+j; + int read_pos = i + j; - if (read_pos>=length()) { + if (read_pos >= length()) { ERR_PRINT("read_pos>=length()"); return -1; }; + CharType src = _find_lower(srcd[read_pos]); + CharType dst = _find_lower(p_str[j]); - CharType src=_find_lower(srcd[read_pos]); - CharType dst=_find_lower(p_str[j]); - - if (src!=dst) { - found=false; + if (src != dst) { + found = false; break; } } @@ -2708,44 +2586,42 @@ int String::findn(String p_str,int p_from) const { return -1; } -int String::rfind(String p_str,int p_from) const { +int String::rfind(String p_str, int p_from) const { //stabilish a limit - int limit = length()-p_str.length(); - if (limit<0) + int limit = length() - p_str.length(); + if (limit < 0) return -1; //stabilish a starting point - if (p_from<0) - p_from=limit; - else if (p_from>limit) - p_from=limit; + if (p_from < 0) + p_from = limit; + else if (p_from > limit) + p_from = limit; - int src_len=p_str.length(); - int len=length(); + int src_len = p_str.length(); + int len = length(); - if(src_len==0 || len==0) + if (src_len == 0 || len == 0) return -1; //wont find anything! - const CharType *src = c_str(); - for (int i=p_from;i>=0;i--) { + for (int i = p_from; i >= 0; i--) { - bool found=true; - for (int j=0;j<src_len;j++) { + bool found = true; + for (int j = 0; j < src_len; j++) { - int read_pos=i+j; + int read_pos = i + j; - if (read_pos>=len) { + if (read_pos >= len) { ERR_PRINT("read_pos>=len"); return -1; }; - - if (src[read_pos]!=p_str[j]) { - found=false; + if (src[read_pos] != p_str[j]) { + found = false; break; } } @@ -2756,47 +2632,45 @@ int String::rfind(String p_str,int p_from) const { return -1; } -int String::rfindn(String p_str,int p_from) const { +int String::rfindn(String p_str, int p_from) const { //stabilish a limit - int limit = length()-p_str.length(); - if (limit<0) + int limit = length() - p_str.length(); + if (limit < 0) return -1; //stabilish a starting point - if (p_from<0) - p_from=limit; - else if (p_from>limit) - p_from=limit; + if (p_from < 0) + p_from = limit; + else if (p_from > limit) + p_from = limit; - int src_len=p_str.length(); - int len=length(); + int src_len = p_str.length(); + int len = length(); - if(src_len==0 || len==0) + if (src_len == 0 || len == 0) return -1; //wont find anything! - const CharType *src = c_str(); - for (int i=p_from;i>=0;i--) { + for (int i = p_from; i >= 0; i--) { - bool found=true; - for (int j=0;j<src_len;j++) { + bool found = true; + for (int j = 0; j < src_len; j++) { - int read_pos=i+j; + int read_pos = i + j; - if (read_pos>=len) { + if (read_pos >= len) { ERR_PRINT("read_pos>=len"); return -1; }; - CharType srcc=_find_lower(src[read_pos]); - CharType dstc=_find_lower(p_str[j]); - + CharType srcc = _find_lower(src[read_pos]); + CharType dstc = _find_lower(p_str[j]); - if (srcc!=dstc) { - found=false; + if (srcc != dstc) { + found = false; break; } } @@ -2808,75 +2682,69 @@ int String::rfindn(String p_str,int p_from) const { return -1; } - -bool String::ends_with(const String& p_string) const { - +bool String::ends_with(const String &p_string) const { int pos = find_last(p_string); - if (pos==-1) + if (pos == -1) return false; - return pos+p_string.length()==length(); - + return pos + p_string.length() == length(); } -bool String::begins_with(const String& p_string) const { +bool String::begins_with(const String &p_string) const { if (p_string.length() > length()) return false; - int l=p_string.length(); - if (l==0) + int l = p_string.length(); + if (l == 0) return true; - const CharType *src=&p_string[0]; - const CharType *str=&operator[](0); + const CharType *src = &p_string[0]; + const CharType *str = &operator[](0); int i = 0; - for (;i<l;i++) { + for (; i < l; i++) { - if (src[i]!=str[i]) + if (src[i] != str[i]) return false; } // only if i == l the p_string matches the beginning return i == l; - } -bool String::begins_with(const char* p_string) const { +bool String::begins_with(const char *p_string) const { - int l=length(); - if (l==0||!p_string) + int l = length(); + if (l == 0 || !p_string) return false; - const CharType *str=&operator[](0); - int i=0; + const CharType *str = &operator[](0); + int i = 0; - while (*p_string && i<l) { + while (*p_string && i < l) { if (*p_string != str[i]) return false; i++; p_string++; - } return *p_string == 0; - } -bool String::is_subsequence_of(const String& p_string) const { +bool String::is_subsequence_of(const String &p_string) const { return _base_is_subsequence_of(p_string, false); } -bool String::is_subsequence_ofi(const String& p_string) const { +bool String::is_subsequence_ofi(const String &p_string) const { return _base_is_subsequence_of(p_string, true); } -bool String::_base_is_subsequence_of(const String& p_string, bool case_insensitive) const { +bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const { - int len=length(); + int len = length(); if (len == 0) { // Technically an empty string is subsequence of any string return true; @@ -2889,7 +2757,7 @@ bool String::_base_is_subsequence_of(const String& p_string, bool case_insensiti const CharType *src = &operator[](0); const CharType *tgt = &p_string[0]; - for (;*src && *tgt;tgt++) { + for (; *src && *tgt; tgt++) { bool match = false; if (case_insensitive) { CharType srcc = _find_lower(*src); @@ -2900,7 +2768,7 @@ bool String::_base_is_subsequence_of(const String& p_string, bool case_insensiti } if (match) { src++; - if(!*src) { + if (!*src) { return true; } } @@ -2912,19 +2780,19 @@ bool String::_base_is_subsequence_of(const String& p_string, bool case_insensiti Vector<String> String::bigrams() const { int n_pairs = length() - 1; Vector<String> b; - if(n_pairs <= 0) { + if (n_pairs <= 0) { return b; } b.resize(n_pairs); - for(int i = 0; i < n_pairs; i++) { - b[i] = substr(i,2); + for (int i = 0; i < n_pairs; i++) { + b[i] = substr(i, 2); } return b; } // Similarity according to Sorensen-Dice coefficient -float String::similarity(const String& p_string) const { - if(operator==(p_string)) { +float String::similarity(const String &p_string) const { + if (operator==(p_string)) { // Equal strings are totally similar return 1.0f; } @@ -2950,187 +2818,183 @@ float String::similarity(const String& p_string) const { } } - return (2.0f * inter)/sum; + return (2.0f * inter) / sum; } -static bool _wildcard_match(const CharType* p_pattern, const CharType* p_string,bool p_case_sensitive) { +static bool _wildcard_match(const CharType *p_pattern, const CharType *p_string, bool p_case_sensitive) { switch (*p_pattern) { - case '\0': - return !*p_string; - case '*' : - return _wildcard_match(p_pattern+1, p_string,p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string+1,p_case_sensitive)); - case '?' : - return *p_string && (*p_string != '.') && _wildcard_match(p_pattern+1, p_string+1,p_case_sensitive); - default : - - return (p_case_sensitive?(*p_string==*p_pattern):(_find_upper(*p_string)==_find_upper(*p_pattern))) && _wildcard_match(p_pattern+1, p_string+1,p_case_sensitive); + case '\0': + return !*p_string; + case '*': + return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive)); + case '?': + return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive); + default: + + return (p_case_sensitive ? (*p_string == *p_pattern) : (_find_upper(*p_string) == _find_upper(*p_pattern))) && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive); } } - -bool String::match(const String& p_wildcard) const { +bool String::match(const String &p_wildcard) const { if (!p_wildcard.length() || !length()) return false; - return _wildcard_match(p_wildcard.c_str(),c_str(),true); - + return _wildcard_match(p_wildcard.c_str(), c_str(), true); } -bool String::matchn(const String& p_wildcard) const { +bool String::matchn(const String &p_wildcard) const { if (!p_wildcard.length() || !length()) return false; - return _wildcard_match(p_wildcard.c_str(),c_str(),false); - + return _wildcard_match(p_wildcard.c_str(), c_str(), false); } -String String::format(const Variant& values,String placeholder) const { +String String::format(const Variant &values, String placeholder) const { - String new_string = String( this->ptr() ); + String new_string = String(this->ptr()); - if( values.get_type() == Variant::ARRAY ) { + if (values.get_type() == Variant::ARRAY) { Array values_arr = values; - for(int i=0;i<values_arr.size();i++) { - String i_as_str = String::num_int64( i ); + for (int i = 0; i < values_arr.size(); i++) { + String i_as_str = String::num_int64(i); - if( values_arr[i].get_type() == Variant::ARRAY ) {//Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]] + if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]] Array value_arr = values_arr[i]; - if( value_arr.size()==2 ) { + if (value_arr.size() == 2) { Variant v_key = value_arr[0]; String key; key = v_key.get_construct_string(); - if( key.left(1)=="\"" && key.right(key.length()-1)=="\"" ) { - key = key.substr(1,key.length()-2); + if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") { + key = key.substr(1, key.length() - 2); } Variant v_val = value_arr[1]; String val; val = v_val.get_construct_string(); - if( val.left(1)=="\"" && val.right(val.length()-1)=="\"" ) { - val = val.substr(1,val.length()-2); + if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") { + val = val.substr(1, val.length() - 2); } - new_string = new_string.replacen( placeholder.replace("_", key ), val ); - }else { + new_string = new_string.replacen(placeholder.replace("_", key), val); + } else { ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data()); } - } else {//Array structure ["RobotGuy","Logis","rookie"] + } else { //Array structure ["RobotGuy","Logis","rookie"] Variant v_val = values_arr[i]; String val; val = v_val.get_construct_string(); - if( val.left(1)=="\"" && val.right(val.length()-1)=="\"" ) { - val = val.substr(1,val.length()-2); + if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") { + val = val.substr(1, val.length() - 2); } - new_string = new_string.replacen( placeholder.replace("_", i_as_str ), val ); + new_string = new_string.replacen(placeholder.replace("_", i_as_str), val); } } - }else if( values.get_type() == Variant::DICTIONARY ) { + } else if (values.get_type() == Variant::DICTIONARY) { Dictionary d = values; List<Variant> keys; d.get_key_list(&keys); - for (List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { String key = E->get().get_construct_string(); String val = d[E->get()].get_construct_string(); - if( key.left(1)=="\"" && key.right(key.length()-1)=="\"" ) { - key = key.substr(1,key.length()-2); + if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") { + key = key.substr(1, key.length() - 2); } - if( val.left(1)=="\"" && val.right(val.length()-1)=="\"" ) { - val = val.substr(1,val.length()-2); + if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") { + val = val.substr(1, val.length() - 2); } - new_string = new_string.replacen( placeholder.replace("_", key ), val ); + new_string = new_string.replacen(placeholder.replace("_", key), val); } - }else{ + } else { ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data()); } return new_string; } -String String::replace(String p_key,String p_with) const { +String String::replace(String p_key, String p_with) const { String new_string; - int search_from=0; - int result=0; + int search_from = 0; + int result = 0; - while( (result=find(p_key,search_from))>=0 ) { + while ((result = find(p_key, search_from)) >= 0) { - new_string+=substr(search_from,result-search_from); - new_string+=p_with; - search_from=result+p_key.length(); + new_string += substr(search_from, result - search_from); + new_string += p_with; + search_from = result + p_key.length(); } - new_string+=substr(search_from,length()-search_from); + new_string += substr(search_from, length() - search_from); return new_string; } -String String::replace_first(String p_key,String p_with) const { +String String::replace_first(String p_key, String p_with) const { String new_string; - int search_from=0; - int result=0; + int search_from = 0; + int result = 0; - while( (result=find(p_key,search_from))>=0 ) { + while ((result = find(p_key, search_from)) >= 0) { - new_string+=substr(search_from,result-search_from); - new_string+=p_with; - search_from=result+p_key.length(); + new_string += substr(search_from, result - search_from); + new_string += p_with; + search_from = result + p_key.length(); break; } - new_string+=substr(search_from,length()-search_from); + new_string += substr(search_from, length() - search_from); return new_string; } -String String::replacen(String p_key,String p_with) const { +String String::replacen(String p_key, String p_with) const { String new_string; - int search_from=0; - int result=0; + int search_from = 0; + int result = 0; - while( (result=findn(p_key,search_from))>=0 ) { + while ((result = findn(p_key, search_from)) >= 0) { - new_string+=substr(search_from,result-search_from); - new_string+=p_with; - search_from=result+p_key.length(); + new_string += substr(search_from, result - search_from); + new_string += p_with; + search_from = result + p_key.length(); } - new_string+=substr(search_from,length()-search_from); + new_string += substr(search_from, length() - search_from); return new_string; } - String String::left(int p_pos) const { - if (p_pos<=0) + if (p_pos <= 0) return ""; - if (p_pos>=length()) + if (p_pos >= length()) return *this; - return substr(0,p_pos); + return substr(0, p_pos); } String String::right(int p_pos) const { - if (p_pos>=size()) + if (p_pos >= size()) return *this; - if (p_pos<0) + if (p_pos < 0) return ""; - return substr(p_pos,(length()-p_pos)); + return substr(p_pos, (length() - p_pos)); } CharType String::ord_at(int p_idx) const { @@ -3141,140 +3005,141 @@ CharType String::ord_at(int p_idx) const { String String::strip_edges(bool left, bool right) const { - int len=length(); - int beg=0,end=len; + int len = length(); + int beg = 0, end = len; - if(left) { - for (int i=0;i<len;i++) { + if (left) { + for (int i = 0; i < len; i++) { - if (operator[](i)<=32) + if (operator[](i) <= 32) beg++; else break; } } - if(right) { - for (int i=(int)(len-1);i>=0;i--) { + if (right) { + for (int i = (int)(len - 1); i >= 0; i--) { - if (operator[](i)<=32) + if (operator[](i) <= 32) end--; else break; } } - if (beg==0 && end==len) + if (beg == 0 && end == len) return *this; - return substr(beg,end-beg); + return substr(beg, end - beg); } String String::strip_escapes() const { - int len=length(); - int beg=0,end=len; + int len = length(); + int beg = 0, end = len; - for (int i=0;i<length();i++) { + for (int i = 0; i < length(); i++) { - if (operator[](i)<=31) + if (operator[](i) <= 31) beg++; else break; } - for (int i=(int)(length()-1);i>=0;i--) { + for (int i = (int)(length() - 1); i >= 0; i--) { - if (operator[](i)<=31) + if (operator[](i) <= 31) end--; else break; } - if (beg==0 && end==len) + if (beg == 0 && end == len) return *this; - return substr(beg,end-beg); + return substr(beg, end - beg); } String String::simplify_path() const { - String s = *this; String drive; if (s.begins_with("local://")) { - drive="local://"; - s=s.substr(8,s.length()); + drive = "local://"; + s = s.substr(8, s.length()); } else if (s.begins_with("res://")) { - drive="res://"; - s=s.substr(6,s.length()); + drive = "res://"; + s = s.substr(6, s.length()); } else if (s.begins_with("user://")) { - drive="user://"; - s=s.substr(6,s.length()); + drive = "user://"; + s = s.substr(6, s.length()); } else if (s.begins_with("/") || s.begins_with("\\")) { - drive=s.substr(0,1); - s=s.substr(1,s.length()-1); + drive = s.substr(0, 1); + s = s.substr(1, s.length() - 1); } else { int p = s.find(":/"); - if (p==-1) - p=s.find(":\\"); - if (p!=-1 && p < s.find("/")) { + if (p == -1) + p = s.find(":\\"); + if (p != -1 && p < s.find("/")) { - drive=s.substr(0,p+2); - s=s.substr(p+2,s.length()); + drive = s.substr(0, p + 2); + s = s.substr(p + 2, s.length()); } } - s =s.replace("\\","/"); - while(true){ // in case of using 2 or more slash - String compare = s.replace("//","/"); - if (s==compare) break; - else s=compare; + s = s.replace("\\", "/"); + while (true) { // in case of using 2 or more slash + String compare = s.replace("//", "/"); + if (s == compare) + break; + else + s = compare; } - Vector<String> dirs = s.split("/",false); + Vector<String> dirs = s.split("/", false); - for(int i=0;i<dirs.size();i++) { + for (int i = 0; i < dirs.size(); i++) { String d = dirs[i]; - if (d==".") { + if (d == ".") { dirs.remove(i); i--; - } else if (d=="..") { + } else if (d == "..") { - if (i==0) { + if (i == 0) { dirs.remove(i); i--; } else { dirs.remove(i); - dirs.remove(i-1); - i-=2; + dirs.remove(i - 1); + i -= 2; } } } - s=""; + s = ""; - for(int i=0;i<dirs.size();i++) { + for (int i = 0; i < dirs.size(); i++) { - if (i>0) - s+="/"; - s+=dirs[i]; + if (i > 0) + s += "/"; + s += dirs[i]; } - return drive+s; + return drive + s; } static int _humanize_digits(int p_num) { - if (p_num<10) + if (p_num < 10) return 2; - else if (p_num<100) + else if (p_num < 100) return 2; - else if (p_num<1024) + else if (p_num < 1024) return 1; else return 0; @@ -3282,26 +3147,26 @@ static int _humanize_digits(int p_num) { String String::humanize_size(size_t p_size) { - uint64_t _div=1; - static const char* prefix[]={" Bytes"," KB"," MB"," GB","TB"," PB","HB",""}; - int prefix_idx=0; + uint64_t _div = 1; + static const char *prefix[] = { " Bytes", " KB", " MB", " GB", "TB", " PB", "HB", "" }; + int prefix_idx = 0; - while(p_size>(_div*1024) && prefix[prefix_idx][0]) { - _div*=1024; + while (p_size > (_div * 1024) && prefix[prefix_idx][0]) { + _div *= 1024; prefix_idx++; } - int digits=prefix_idx>0?_humanize_digits(p_size/_div):0; - double divisor = prefix_idx>0?_div:1; + int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0; + double divisor = prefix_idx > 0 ? _div : 1; - return String::num(p_size/divisor,digits)+prefix[prefix_idx]; + return String::num(p_size / divisor, digits) + prefix[prefix_idx]; } bool String::is_abs_path() const { - if (length()>1) - return (operator[](0)=='/' || operator[](0)=='\\' || find(":/")!=-1 || find(":\\")!=-1); - else if ((length())==1) - return (operator[](0)=='/' || operator[](0)=='\\'); + if (length() > 1) + return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1); + else if ((length()) == 1) + return (operator[](0) == '/' || operator[](0) == '\\'); else return false; } @@ -3310,24 +3175,22 @@ bool String::is_valid_identifier() const { int len = length(); - if (len==0) + if (len == 0) return false; - const wchar_t * str = &operator[](0); - + const wchar_t *str = &operator[](0); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i==0) { - if (str[0]>='0' && str[0]<='9') + if (i == 0) { + if (str[0] >= '0' && str[0] <= '9') return false; // no start with number plz } - bool valid_char = (str[i]>='0' && str[i]<='9') || (str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z') || str[i]=='_'; + bool valid_char = (str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '_'; if (!valid_char) return false; - } return true; @@ -3337,150 +3200,150 @@ bool String::is_valid_identifier() const { String String::word_wrap(int p_chars_per_line) const { - int from=0; - int last_space=0; + int from = 0; + int last_space = 0; String ret; - for(int i=0;i<length();i++) { - if (i-from>=p_chars_per_line) { - if (last_space==-1) { - ret+=substr(from,i-from+1)+"\n"; + for (int i = 0; i < length(); i++) { + if (i - from >= p_chars_per_line) { + if (last_space == -1) { + ret += substr(from, i - from + 1) + "\n"; } else { - ret+=substr(from,last_space-from)+"\n"; - i=last_space; //rewind + ret += substr(from, last_space - from) + "\n"; + i = last_space; //rewind } - from=i+1; - last_space=-1; - } else if (operator[](i)==' ' || operator[](i)=='\t') { - last_space=i; - } else if (operator[](i)=='\n') { - ret+=substr(from,i-from)+"\n"; - from=i+1; - last_space=-1; + from = i + 1; + last_space = -1; + } else if (operator[](i) == ' ' || operator[](i) == '\t') { + last_space = i; + } else if (operator[](i) == '\n') { + ret += substr(from, i - from) + "\n"; + from = i + 1; + last_space = -1; } } - if (from<length()) { - ret+=substr(from,length()); + if (from < length()) { + ret += substr(from, length()); } return ret; } String String::http_escape() const { - const CharString temp = utf8(); - String res; - for (int i = 0; i < length(); ++i) { - CharType ord = temp[i]; - if (ord == '.' || ord == '-' || ord == '_' || ord == '~' || - (ord >= 'a' && ord <= 'z') || - (ord >= 'A' && ord <= 'Z') || - (ord >= '0' && ord <= '9')) { - res += ord; - } else { - char h_Val[3]; + const CharString temp = utf8(); + String res; + for (int i = 0; i < length(); ++i) { + CharType ord = temp[i]; + if (ord == '.' || ord == '-' || ord == '_' || ord == '~' || + (ord >= 'a' && ord <= 'z') || + (ord >= 'A' && ord <= 'Z') || + (ord >= '0' && ord <= '9')) { + res += ord; + } else { + char h_Val[3]; #if defined(__GNUC__) || defined(_MSC_VER) - snprintf(h_Val, 3, "%.2X", ord); + snprintf(h_Val, 3, "%.2X", ord); #else - sprintf(h_Val, "%.2X", ord); + sprintf(h_Val, "%.2X", ord); #endif - res += "%"; - res += h_Val; - } - } - return res; + res += "%"; + res += h_Val; + } + } + return res; } String String::http_unescape() const { - String res; - for (int i = 0; i < length(); ++i) { - if (ord_at(i) == '%' && i+2 < length()) { - CharType ord1 = ord_at(i+1); - if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) { - CharType ord2 = ord_at(i+2); - if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) { - char bytes[2] = {ord1, ord2}; - res += (char)strtol(bytes, NULL, 16); - i+=2; - } - } else { - res += ord_at(i); - } - } else { - res += ord_at(i); - } - } - return String::utf8(res.ascii()); + String res; + for (int i = 0; i < length(); ++i) { + if (ord_at(i) == '%' && i + 2 < length()) { + CharType ord1 = ord_at(i + 1); + if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) { + CharType ord2 = ord_at(i + 2); + if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) { + char bytes[2] = { ord1, ord2 }; + res += (char)strtol(bytes, NULL, 16); + i += 2; + } + } else { + res += ord_at(i); + } + } else { + res += ord_at(i); + } + } + return String::utf8(res.ascii()); } String String::c_unescape() const { - String escaped=*this; - escaped=escaped.replace("\\a","\a"); - escaped=escaped.replace("\\b","\b"); - escaped=escaped.replace("\\f","\f"); - escaped=escaped.replace("\\n","\n"); - escaped=escaped.replace("\\r","\r"); - escaped=escaped.replace("\\t","\t"); - escaped=escaped.replace("\\v","\v"); - escaped=escaped.replace("\\'","\'"); - escaped=escaped.replace("\\\"","\""); - escaped=escaped.replace("\\?","\?"); - escaped=escaped.replace("\\\\","\\"); + String escaped = *this; + escaped = escaped.replace("\\a", "\a"); + escaped = escaped.replace("\\b", "\b"); + escaped = escaped.replace("\\f", "\f"); + escaped = escaped.replace("\\n", "\n"); + escaped = escaped.replace("\\r", "\r"); + escaped = escaped.replace("\\t", "\t"); + escaped = escaped.replace("\\v", "\v"); + escaped = escaped.replace("\\'", "\'"); + escaped = escaped.replace("\\\"", "\""); + escaped = escaped.replace("\\?", "\?"); + escaped = escaped.replace("\\\\", "\\"); return escaped; } String String::c_escape() const { - String escaped=*this; - escaped=escaped.replace("\\","\\\\"); - escaped=escaped.replace("\a","\\a"); - escaped=escaped.replace("\b","\\b"); - escaped=escaped.replace("\f","\\f"); - escaped=escaped.replace("\n","\\n"); - escaped=escaped.replace("\r","\\r"); - escaped=escaped.replace("\t","\\t"); - escaped=escaped.replace("\v","\\v"); - escaped=escaped.replace("\'","\\'"); - escaped=escaped.replace("\?","\\?"); - escaped=escaped.replace("\"","\\\""); + String escaped = *this; + escaped = escaped.replace("\\", "\\\\"); + escaped = escaped.replace("\a", "\\a"); + escaped = escaped.replace("\b", "\\b"); + escaped = escaped.replace("\f", "\\f"); + escaped = escaped.replace("\n", "\\n"); + escaped = escaped.replace("\r", "\\r"); + escaped = escaped.replace("\t", "\\t"); + escaped = escaped.replace("\v", "\\v"); + escaped = escaped.replace("\'", "\\'"); + escaped = escaped.replace("\?", "\\?"); + escaped = escaped.replace("\"", "\\\""); return escaped; } String String::c_escape_multiline() const { - String escaped=*this; - escaped=escaped.replace("\\","\\\\"); - escaped=escaped.replace("\"","\\\""); + String escaped = *this; + escaped = escaped.replace("\\", "\\\\"); + escaped = escaped.replace("\"", "\\\""); return escaped; } String String::json_escape() const { - String escaped=*this; - escaped=escaped.replace("\\","\\\\"); - escaped=escaped.replace("\b","\\b"); - escaped=escaped.replace("\f","\\f"); - escaped=escaped.replace("\n","\\n"); - escaped=escaped.replace("\r","\\r"); - escaped=escaped.replace("\t","\\t"); - escaped=escaped.replace("\v","\\v"); - escaped=escaped.replace("\"","\\\""); + String escaped = *this; + escaped = escaped.replace("\\", "\\\\"); + escaped = escaped.replace("\b", "\\b"); + escaped = escaped.replace("\f", "\\f"); + escaped = escaped.replace("\n", "\\n"); + escaped = escaped.replace("\r", "\\r"); + escaped = escaped.replace("\t", "\\t"); + escaped = escaped.replace("\v", "\\v"); + escaped = escaped.replace("\"", "\\\""); return escaped; } String String::xml_escape(bool p_escape_quotes) const { - String str=*this; - str=str.replace("&","&"); - str=str.replace("<","<"); - str=str.replace(">",">"); + String str = *this; + str = str.replace("&", "&"); + str = str.replace("<", "<"); + str = str.replace(">", ">"); if (p_escape_quotes) { - str=str.replace("'","'"); - str=str.replace("\"","""); + str = str.replace("'", "'"); + str = str.replace("\"", """); } /* for (int i=1;i<32;i++) { @@ -3491,84 +3354,83 @@ String String::xml_escape(bool p_escape_quotes) const { return str; } -static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src,int p_src_len,CharType *p_dst) { +static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src, int p_src_len, CharType *p_dst) { - int len=0; - while(p_src_len) { + int len = 0; + while (p_src_len) { - if (*p_src=='&') { + if (*p_src == '&') { - int eat=0; + int eat = 0; - if (p_src_len>=4 && p_src[1]=='#') { + if (p_src_len >= 4 && p_src[1] == '#') { - CharType c=0; + CharType c = 0; - for(int i=2;i<p_src_len;i++) { + for (int i = 2; i < p_src_len; i++) { - eat=i+1; - CharType ct=p_src[i]; - if (ct==';') { + eat = i + 1; + CharType ct = p_src[i]; + if (ct == ';') { break; - } else if (ct>='0' && ct<='9') { - ct=ct-'0'; - } else if (ct>='a' && ct<='f') { - ct=(ct-'a')+10; - } else if (ct>='A' && ct<='F') { - ct=(ct-'A')+10; + } else if (ct >= '0' && ct <= '9') { + ct = ct - '0'; + } else if (ct >= 'a' && ct <= 'f') { + ct = (ct - 'a') + 10; + } else if (ct >= 'A' && ct <= 'F') { + ct = (ct - 'A') + 10; } else { continue; } - c<<=4; - c|=ct; + c <<= 4; + c |= ct; } if (p_dst) - *p_dst=c; + *p_dst = c; - } else if (p_src_len>=4 && p_src[1]=='g' && p_src[2]=='t' && p_src[3]==';') { + } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') { if (p_dst) - *p_dst='>'; - eat=4; - } else if (p_src_len>=4 && p_src[1]=='l' && p_src[2]=='t' && p_src[3]==';') { + *p_dst = '>'; + eat = 4; + } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') { if (p_dst) - *p_dst='<'; - eat=4; - } else if (p_src_len>=5 && p_src[1]=='a' && p_src[2]=='m' && p_src[3]=='p' && p_src[4]==';') { + *p_dst = '<'; + eat = 4; + } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') { if (p_dst) - *p_dst='&'; - eat=5; - } else if (p_src_len>=6 && p_src[1]=='q' && p_src[2]=='u' && p_src[3]=='o' && p_src[4]=='t' && p_src[5]==';') { + *p_dst = '&'; + eat = 5; + } else if (p_src_len >= 6 && p_src[1] == 'q' && p_src[2] == 'u' && p_src[3] == 'o' && p_src[4] == 't' && p_src[5] == ';') { if (p_dst) - *p_dst='"'; - eat=6; - } else if (p_src_len>=6 && p_src[1]=='a' && p_src[2]=='p' && p_src[3]=='o' && p_src[4]=='s' && p_src[5]==';') { + *p_dst = '"'; + eat = 6; + } else if (p_src_len >= 6 && p_src[1] == 'a' && p_src[2] == 'p' && p_src[3] == 'o' && p_src[4] == 's' && p_src[5] == ';') { if (p_dst) - *p_dst='\''; - eat=6; + *p_dst = '\''; + eat = 6; } else { if (p_dst) - *p_dst=*p_src; - eat=1; - + *p_dst = *p_src; + eat = 1; } if (p_dst) p_dst++; len++; - p_src+=eat; - p_src_len-=eat; + p_src += eat; + p_src_len -= eat; } else { if (p_dst) { - *p_dst=*p_src; + *p_dst = *p_src; p_dst++; } len++; @@ -3578,45 +3440,43 @@ static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src,int p_src_len,Char } return len; - } String String::xml_unescape() const { - String str; int l = length(); - int len = _xml_unescape(c_str(),l,NULL); - if (len==0) + int len = _xml_unescape(c_str(), l, NULL); + if (len == 0) return String(); - str.resize(len+1); - _xml_unescape(c_str(),l,&str[0]); - str[len]=0; + str.resize(len + 1); + _xml_unescape(c_str(), l, &str[0]); + str[len] = 0; return str; } String String::pad_decimals(int p_digits) const { - String s=*this; + String s = *this; int c = s.find("."); - if (c==-1) { - if (p_digits<=0) { + if (c == -1) { + if (p_digits <= 0) { return s; } - s+="."; - c=s.length()-1; + s += "."; + c = s.length() - 1; } else { - if (p_digits<=0) { - return s.substr(0,c); + if (p_digits <= 0) { + return s.substr(0, c); } } - if (s.length()-(c+1) > p_digits) { - s=s.substr(0,c+p_digits+1); + if (s.length() - (c + 1) > p_digits) { + s = s.substr(0, c + p_digits + 1); } else { - while(s.length()-(c+1) < p_digits) { - s+="0"; + while (s.length() - (c + 1) < p_digits) { + s += "0"; } } return s; @@ -3624,30 +3484,28 @@ String String::pad_decimals(int p_digits) const { String String::pad_zeros(int p_digits) const { - String s=*this; + String s = *this; int end = s.find("."); - if (end==-1) { - end=s.length(); + if (end == -1) { + end = s.length(); } - - if (end==0) + if (end == 0) return s; - int begin=0; + int begin = 0; - while (begin<end && (s[begin]<'0' || s[begin]>'9')) { + while (begin < end && (s[begin] < '0' || s[begin] > '9')) { begin++; } - if (begin>=end) + if (begin >= end) return s; + while (end - begin < p_digits) { - while(end-begin < p_digits) { - - s=s.insert(begin,"0"); + s = s.insert(begin, "0"); end++; } @@ -3658,22 +3516,20 @@ bool String::is_valid_integer() const { int len = length(); - if (len==0) + if (len == 0) return false; - int from=0; - if (len!=1 && (operator[](0)=='+' || operator[](0)=='-')) + int from = 0; + if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) from++; - for(int i=from;i<len;i++) { + for (int i = from; i < len; i++) { - if (operator[](i)<'0' || operator[](i)>'9') + if (operator[](i) < '0' || operator[](i) > '9') return false; // no start with number plz - } return true; - } bool String::is_valid_hex_number(bool p_with_prefix) const { @@ -3681,20 +3537,20 @@ bool String::is_valid_hex_number(bool p_with_prefix) const { int from = 0; int len = length(); - if (len!=1 && (operator[](0)=='+' || operator[](0)=='-')) + if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) from++; if (p_with_prefix) { if (len < 2) return false; - if (operator[](from) != '0' || operator[](from+1) != 'x') { + if (operator[](from) != '0' || operator[](from + 1) != 'x') { return false; }; from += 2; }; - for (int i=from; i<len; i++) { + for (int i = from; i < len; i++) { CharType c = operator[](i); if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) @@ -3705,114 +3561,110 @@ bool String::is_valid_hex_number(bool p_with_prefix) const { return true; }; - bool String::is_valid_float() const { int len = length(); - if (len==0) + if (len == 0) return false; - int from=0; - if (operator[](0)=='+' || operator[](0)=='-') { + int from = 0; + if (operator[](0) == '+' || operator[](0) == '-') { from++; } //this was pulled out of my ass, i wonder if it's correct... - bool exponent_found=false; - bool period_found=false; - bool sign_found=false; - bool exponent_values_found=false; - bool numbers_found=false; + bool exponent_found = false; + bool period_found = false; + bool sign_found = false; + bool exponent_values_found = false; + bool numbers_found = false; - for(int i=from;i<len;i++) { + for (int i = from; i < len; i++) { - if (operator[](i)>='0' && operator[](i)<='9') { + if (operator[](i) >= '0' && operator[](i) <= '9') { if (exponent_found) - exponent_values_found=true; + exponent_values_found = true; else - numbers_found=true; - } else if (numbers_found && !exponent_found && operator[](i)=='e') { - exponent_found=true; - } else if (!period_found && !exponent_found && operator[](i)=='.') { - period_found=true; - } else if ((operator[](i)=='-' || operator[](i)=='+') && exponent_found && !exponent_values_found && !sign_found) { - sign_found=true; + numbers_found = true; + } else if (numbers_found && !exponent_found && operator[](i) == 'e') { + exponent_found = true; + } else if (!period_found && !exponent_found && operator[](i) == '.') { + period_found = true; + } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) { + sign_found = true; } else return false; // no start with number plz - } return numbers_found; - } -String String::path_to_file(const String& p_path) const { +String String::path_to_file(const String &p_path) const { - String src=this->replace("\\","/").get_base_dir(); - String dst=p_path.replace("\\","/").get_base_dir(); + String src = this->replace("\\", "/").get_base_dir(); + String dst = p_path.replace("\\", "/").get_base_dir(); String rel = src.path_to(dst); - if (rel==dst) // failed + if (rel == dst) // failed return p_path; else - return rel+p_path.get_file(); + return rel + p_path.get_file(); } -String String::path_to(const String& p_path) const { +String String::path_to(const String &p_path) const { - String src=this->replace("\\","/"); - String dst=p_path.replace("\\","/"); + String src = this->replace("\\", "/"); + String dst = p_path.replace("\\", "/"); if (!src.ends_with("/")) - src+="/"; + src += "/"; if (!dst.ends_with("/")) - dst+="/"; - + dst += "/"; String base; if (src.begins_with("res://") && dst.begins_with("res://")) { - base="res:/"; - src=src.replace("res://","/"); - dst=dst.replace("res://","/"); + base = "res:/"; + src = src.replace("res://", "/"); + dst = dst.replace("res://", "/"); } else if (src.begins_with("user://") && dst.begins_with("user://")) { - base="user:/"; - src=src.replace("user://","/"); - dst=dst.replace("user://","/"); + base = "user:/"; + src = src.replace("user://", "/"); + dst = dst.replace("user://", "/"); } else if (src.begins_with("/") && dst.begins_with("/")) { //nothing } else { //dos style - String src_begin=src.get_slicec('/',0); - String dst_begin=dst.get_slicec('/',0); + String src_begin = src.get_slicec('/', 0); + String dst_begin = dst.get_slicec('/', 0); - if (src_begin!=dst_begin) + if (src_begin != dst_begin) return p_path; //impossible to do this - base=src_begin; - src=src.substr(src_begin.length(),src.length()); - dst=dst.substr(dst_begin.length(),dst.length()); + base = src_begin; + src = src.substr(src_begin.length(), src.length()); + dst = dst.substr(dst_begin.length(), dst.length()); } //remove leading and trailing slash and split - Vector<String> src_dirs=src.substr(1,src.length()-2).split("/"); - Vector<String> dst_dirs=dst.substr(1,dst.length()-2).split("/"); + Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/"); + Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/"); //find common parent - int common_parent=0; + int common_parent = 0; - while(true) { - if (src_dirs.size()==common_parent) + while (true) { + if (src_dirs.size() == common_parent) break; - if (dst_dirs.size()==common_parent) + if (dst_dirs.size() == common_parent) break; - if (src_dirs[common_parent]!=dst_dirs[common_parent]) + if (src_dirs[common_parent] != dst_dirs[common_parent]) break; common_parent++; } @@ -3821,34 +3673,32 @@ String String::path_to(const String& p_path) const { String dir; - for(int i=src_dirs.size()-1;i>common_parent;i--) { + for (int i = src_dirs.size() - 1; i > common_parent; i--) { - dir+="../"; + dir += "../"; } - for(int i=common_parent+1;i<dst_dirs.size();i++) { + for (int i = common_parent + 1; i < dst_dirs.size(); i++) { - dir+=dst_dirs[i]+"/"; + dir += dst_dirs[i] + "/"; } - if (dir.length()==0) - dir="./"; + if (dir.length() == 0) + dir = "./"; return dir; } bool String::is_valid_html_color() const { return Color::html_is_valid(*this); - } - bool String::is_valid_ip_address() const { if (find(":") >= 0) { Vector<String> ip = split(":"); - for (int i=0; i<ip.size(); i++) { + for (int i = 0; i < ip.size(); i++) { String n = ip[i]; if (n.empty()) @@ -3865,15 +3715,15 @@ bool String::is_valid_ip_address() const { } else { Vector<String> ip = split("."); - if (ip.size()!=4) + if (ip.size() != 4) return false; - for(int i=0;i<ip.size();i++) { + for (int i = 0; i < ip.size(); i++) { String n = ip[i]; if (!n.is_valid_integer()) return false; int val = n.to_int(); - if (val<0 || val>255) + if (val < 0 || val > 255) return false; } }; @@ -3883,7 +3733,7 @@ bool String::is_valid_ip_address() const { bool String::is_resource_file() const { - return begins_with("res://") && find("::")==-1; + return begins_with("res://") && find("::") == -1; } bool String::is_rel_path() const { @@ -3896,71 +3746,70 @@ String String::get_base_dir() const { int basepos = find("://"); String rs; String base; - if (basepos!=-1) { - int end = basepos+3; - rs = substr(end,length()); - base = substr(0,end); + if (basepos != -1) { + int end = basepos + 3; + rs = substr(end, length()); + base = substr(0, end); } else { if (begins_with("/")) { - rs=substr(1,length()); - base="/"; + rs = substr(1, length()); + base = "/"; } else { - rs=*this; + rs = *this; } } - int sep = MAX( rs.find_last("/"), rs.find_last("\\") ); - if (sep==-1) + int sep = MAX(rs.find_last("/"), rs.find_last("\\")); + if (sep == -1) return base; - return base+rs.substr(0,sep); - + return base + rs.substr(0, sep); } String String::get_file() const { - int sep = MAX( find_last("/"), find_last("\\") ); - if (sep==-1) + int sep = MAX(find_last("/"), find_last("\\")); + if (sep == -1) return *this; - return substr(sep+1,length()); + return substr(sep + 1, length()); } String String::get_extension() const { int pos = find_last("."); - if (pos<0) + if (pos < 0) return *this; - return substr( pos+1, length() ); + return substr(pos + 1, length()); } -String String::plus_file(const String& p_file) const { +String String::plus_file(const String &p_file) const { if (empty()) return p_file; - if (operator [](length()-1)=='/' || (p_file.size()>0 && p_file.operator [](0)=='/')) - return *this+p_file; - return *this+"/"+p_file; + if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) + return *this + p_file; + return *this + "/" + p_file; } String String::percent_encode() const { CharString cs = utf8(); String encoded; - for(int i=0;i<cs.length();i++) { + for (int i = 0; i < cs.length(); i++) { uint8_t c = cs[i]; - if ( (c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9') || c=='-' || c=='_' || c=='~' || c=='.') { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '~' || c == '.') { - char p[2]={(char)c,0}; - encoded+=p; + char p[2] = { (char)c, 0 }; + encoded += p; } else { - char p[4]={'%',0,0,0}; - static const char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; + char p[4] = { '%', 0, 0, 0 }; + static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - p[1]=hex[c>>4]; - p[2]=hex[c&0xF]; - encoded+=p; + p[1] = hex[c >> 4]; + p[2] = hex[c & 0xF]; + encoded += p; } } @@ -3971,32 +3820,32 @@ String String::percent_decode() const { CharString pe; CharString cs = utf8(); - for(int i=0;i<cs.length();i++) { + for (int i = 0; i < cs.length(); i++) { uint8_t c = cs[i]; - if (c=='%' && i<length()-2) { + if (c == '%' && i < length() - 2) { - uint8_t a = LOWERCASE(cs[i+1]); - uint8_t b = LOWERCASE(cs[i+2]); + uint8_t a = LOWERCASE(cs[i + 1]); + uint8_t b = LOWERCASE(cs[i + 2]); - c=0; - if (a>='0' && a<='9') - c=(a-'0')<<4; - else if (a>='a' && a<='f') - c=(a-'a'+10)<<4; + c = 0; + if (a >= '0' && a <= '9') + c = (a - '0') << 4; + else if (a >= 'a' && a <= 'f') + c = (a - 'a' + 10) << 4; else continue; - uint8_t d=0; + uint8_t d = 0; - if (b>='0' && b<='9') - d=(b-'0'); - else if (b>='a' && b<='f') - d=(b-'a'+10); + if (b >= '0' && b <= '9') + d = (b - '0'); + else if (b >= 'a' && b <= 'f') + d = (b - 'a' + 10); else continue; - c+=d; - i+=2; + c += d; + i += 2; } pe.push_back(c); } @@ -4009,10 +3858,10 @@ String String::percent_decode() const { String String::get_basename() const { int pos = find_last("."); - if (pos<0) + if (pos < 0) return *this; - return substr( 0, pos ); + return substr(0, pos); } String itos(int64_t p_val) { @@ -4031,21 +3880,23 @@ String rtoss(double p_val) { } // Right-pad with a character. -String String::rpad(int min_length, const String& character) const { +String String::rpad(int min_length, const String &character) const { String s = *this; int padding = min_length - s.length(); if (padding > 0) { - for (int i = 0; i < padding; i++) s = s + character; + for (int i = 0; i < padding; i++) + s = s + character; } return s; } // Left-pad with a character. -String String::lpad(int min_length, const String& character) const { +String String::lpad(int min_length, const String &character) const { String s = *this; int padding = min_length - s.length(); if (padding > 0) { - for (int i = 0; i < padding; i++) s = character + s; + for (int i = 0; i < padding; i++) + s = character + s; } return s; @@ -4055,9 +3906,9 @@ String String::lpad(int min_length, const String& character) const { // "fish %s pie" % "frog" // "fish %s %d pie" % ["frog", 12] // In case of an error, the string returned is the error description and "error" is true. -String String::sprintf(const Array& values, bool* error) const { +String String::sprintf(const Array &values, bool *error) const { String formatted; - CharType* self = (CharType*)c_str(); + CharType *self = (CharType *)c_str(); bool in_format = false; int value_index = 0; int min_chars; @@ -4098,7 +3949,10 @@ String String::sprintf(const Array& values, bool* error) const { case 'd': base = 10; break; case 'o': base = 8; break; case 'x': base = 16; break; - case 'X': base = 16; capitalize = true; break; + case 'X': + base = 16; + capitalize = true; + break; } // Get basic number. String str = String::num_int64(ABS(value), base, capitalize); @@ -4114,9 +3968,9 @@ String String::sprintf(const Array& values, bool* error) const { // Sign. if (show_sign && value >= 0) { - str = str.insert(pad_with_zeroes?0:str.length()-number_len, "+"); + str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "+"); } else if (value < 0) { - str = str.insert(pad_with_zeroes?0:str.length()-number_len, "-"); + str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "-"); } formatted += str; @@ -4220,8 +4074,16 @@ String String::sprintf(const Array& values, bool* error) const { show_sign = true; break; } - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { int n = c - '0'; if (in_decimals) { min_decimals *= 10; @@ -4268,7 +4130,7 @@ String String::sprintf(const Array& values, bool* error) const { default: { return "unsupported format character"; - } + } } } else { // Not in format string. switch (c) { @@ -4303,7 +4165,7 @@ String String::sprintf(const Array& values, bool* error) const { #include "translation.h" #ifdef TOOLS_ENABLED -String TTR(const String& p_text) { +String TTR(const String &p_text) { if (TranslationServer::get_singleton()) { return TranslationServer::get_singleton()->tool_translate(p_text); @@ -4314,13 +4176,11 @@ String TTR(const String& p_text) { #endif -String RTR(const String& p_text) { - - +String RTR(const String &p_text) { if (TranslationServer::get_singleton()) { String rtr = TranslationServer::get_singleton()->tool_translate(p_text); - if (rtr==String() || rtr==p_text) { + if (rtr == String() || rtr == p_text) { return TranslationServer::get_singleton()->translate(p_text); } else { return rtr; diff --git a/core/ustring.h b/core/ustring.h index 87289f9e16..6a69d8b147 100644 --- a/core/ustring.h +++ b/core/ustring.h @@ -29,67 +29,60 @@ #ifndef RSTRING_H #define RSTRING_H +#include "array.h" #include "typedefs.h" #include "vector.h" -#include "array.h" /** @author red <red@killy> */ - - class CharString : public Vector<char> { public: - - bool operator<(const CharString& p_right) const; - int length() const { return size() ? size()-1 : 0; } + bool operator<(const CharString &p_right) const; + int length() const { return size() ? size() - 1 : 0; } const char *get_data() const; - operator const char*() {return get_data();}; + operator const char *() { return get_data(); }; }; - typedef wchar_t CharType; - struct StrRange { const CharType *c_str; int len; - StrRange(const CharType *p_c_str=NULL,int p_len=0) { c_str=p_c_str; len=p_len; } - + StrRange(const CharType *p_c_str = NULL, int p_len = 0) { + c_str = p_c_str; + len = p_len; + } }; class String : public Vector<CharType> { void copy_from(const char *p_cstr); - void copy_from(const CharType* p_cstr, int p_clip_to=-1); - void copy_from(const CharType& p_char); - bool _base_is_subsequence_of(const String& p_string, bool case_insensitive) const; - + void copy_from(const CharType *p_cstr, int p_clip_to = -1); + void copy_from(const CharType &p_char); + bool _base_is_subsequence_of(const String &p_string, bool case_insensitive) const; public: - enum { - npos=-1 ///<for "some" compatibility with std::string (npos is a huge value in std::string) + npos = -1 ///<for "some" compatibility with std::string (npos is a huge value in std::string) }; - - bool operator==(const String& p_str) const; - bool operator!=(const String& p_str) const; - String operator+(const String & p_str) const; + bool operator==(const String &p_str) const; + bool operator!=(const String &p_str) const; + String operator+(const String &p_str) const; //String operator+(CharType p_char) const; - String& operator+=(const String &); - String& operator+=(CharType p_str); - String& operator+=(const char * p_str); - String& operator+=(const CharType * p_str); + String &operator+=(const String &); + String &operator+=(CharType p_str); + String &operator+=(const char *p_str); + String &operator+=(const CharType *p_str); /* Compatibility Operators */ - void operator=(const char *p_str); void operator=(const CharType *p_str); bool operator==(const char *p_str) const; @@ -102,45 +95,45 @@ public: bool operator<(String p_str) const; bool operator<=(String p_str) const; - signed char casecmp_to(const String& p_str) const; - signed char nocasecmp_to(const String& p_str) const; + signed char casecmp_to(const String &p_str) const; + signed char nocasecmp_to(const String &p_str) const; - const CharType * c_str() const; + const CharType *c_str() const; /* standard size stuff */ int length() const; /* complex helpers */ - String substr(int p_from,int p_chars) const; - int find(String p_str,int p_from=0) const; ///< return <0 if failed + String substr(int p_from, int p_chars) const; + int find(String p_str, int p_from = 0) const; ///< return <0 if failed int find_last(String p_str) const; ///< return <0 if failed - int findn(String p_str,int p_from=0) const; ///< return <0 if failed, case insensitive - int rfind(String p_str,int p_from=-1) const; ///< return <0 if failed - int rfindn(String p_str,int p_from=-1) const; ///< return <0 if failed, case insensitive - int findmk(const Vector<String>& p_keys,int p_from=0,int *r_key=NULL) const; ///< return <0 if failed - bool match(const String& p_wildcard) const; - bool matchn(const String& p_wildcard) const; - bool begins_with(const String& p_string) const; - bool begins_with(const char* p_string) const; - bool ends_with(const String& p_string) const; - bool is_subsequence_of(const String& p_string) const; - bool is_subsequence_ofi(const String& p_string) const; + int findn(String p_str, int p_from = 0) const; ///< return <0 if failed, case insensitive + int rfind(String p_str, int p_from = -1) const; ///< return <0 if failed + int rfindn(String p_str, int p_from = -1) const; ///< return <0 if failed, case insensitive + int findmk(const Vector<String> &p_keys, int p_from = 0, int *r_key = NULL) const; ///< return <0 if failed + bool match(const String &p_wildcard) const; + bool matchn(const String &p_wildcard) const; + bool begins_with(const String &p_string) const; + bool begins_with(const char *p_string) const; + bool ends_with(const String &p_string) const; + bool is_subsequence_of(const String &p_string) const; + bool is_subsequence_ofi(const String &p_string) const; Vector<String> bigrams() const; - float similarity(const String& p_string) const; - String format(const Variant& values,String placeholder="{_}") const; - String replace_first(String p_key,String p_with) const; - String replace(String p_key,String p_with) const; - String replacen(String p_key,String p_with) const; - String insert(int p_at_pos,String p_string) const; + float similarity(const String &p_string) const; + String format(const Variant &values, String placeholder = "{_}") const; + String replace_first(String p_key, String p_with) const; + String replace(String p_key, String p_with) const; + String replacen(String p_key, String p_with) const; + String insert(int p_at_pos, String p_string) const; String pad_decimals(int p_digits) const; String pad_zeros(int p_digits) const; - String lpad(int min_length,const String& character=" ") const; - String rpad(int min_length,const String& character=" ") const; - String sprintf(const Array& values, bool* error) const; - static String num(double p_num,int p_decimals=-1); + String lpad(int min_length, const String &character = " ") const; + String rpad(int min_length, const String &character = " ") const; + String sprintf(const Array &values, bool *error) const; + static String num(double p_num, int p_decimals = -1); static String num_scientific(double p_num); static String num_real(double p_num); - static String num_int64(int64_t p_num,int base=10,bool capitalize_hex=false); + static String num_int64(int64_t p_num, int base = 10, bool capitalize_hex = false); static String chr(CharType p_char); static String md5(const uint8_t *p_md5); static String hex_encode_buffer(const uint8_t *p_buffer, int p_len); @@ -152,23 +145,23 @@ public: int64_t hex_to_int64(bool p_with_prefix = true) const; int64_t to_int64() const; - static int to_int(const char* p_str, int p_len=-1); - static double to_double(const char* p_str); - static double to_double(const CharType* p_str, const CharType **r_end=NULL); - static int64_t to_int(const CharType* p_str,int p_len=-1); + static int to_int(const char *p_str, int p_len = -1); + static double to_double(const char *p_str); + static double to_double(const CharType *p_str, const CharType **r_end = NULL); + static int64_t to_int(const CharType *p_str, int p_len = -1); String capitalize() const; - String camelcase_to_underscore(bool lowercase=true) const; + String camelcase_to_underscore(bool lowercase = true) const; int get_slice_count(String p_splitter) const; - String get_slice(String p_splitter,int p_slice) const; - String get_slicec(CharType splitter,int p_slice) const; + String get_slice(String p_splitter, int p_slice) const; + String get_slicec(CharType splitter, int p_slice) const; - Vector<String> split(const String &p_splitter,bool p_allow_empty=true) const; + Vector<String> split(const String &p_splitter, bool p_allow_empty = true) const; Vector<String> split_spaces() const; - Vector<float> split_floats(const String &p_splitter,bool p_allow_empty=true) const; - Vector<float> split_floats_mk(const Vector<String> &p_splitters,bool p_allow_empty=true) const; - Vector<int> split_ints(const String &p_splitter,bool p_allow_empty=true) const; - Vector<int> split_ints_mk(const Vector<String> &p_splitters,bool p_allow_empty=true) const; + Vector<float> split_floats(const String &p_splitter, bool p_allow_empty = true) const; + Vector<float> split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty = true) const; + Vector<int> split_ints(const String &p_splitter, bool p_allow_empty = true) const; + Vector<int> split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty = true) const; static CharType char_uppercase(CharType p_char); static CharType char_lowercase(CharType p_char); @@ -181,20 +174,20 @@ public: String strip_escapes() const; String get_extension() const; String get_basename() const; - String plus_file(const String& p_file) const; + String plus_file(const String &p_file) const; CharType ord_at(int p_idx) const; void erase(int p_pos, int p_chars); - CharString ascii(bool p_allow_extended=false) const; + CharString ascii(bool p_allow_extended = false) const; CharString utf8() const; - bool parse_utf8(const char* p_utf8,int p_len=-1); //return true on error - static String utf8(const char* p_utf8,int p_len=-1); + bool parse_utf8(const char *p_utf8, int p_len = -1); //return true on error + static String utf8(const char *p_utf8, int p_len = -1); - static uint32_t hash(const CharType* p_str,int p_len); /* hash the string */ - static uint32_t hash(const CharType* p_str); /* hash the string */ - static uint32_t hash(const char* p_cstr,int p_len); /* hash the string */ - static uint32_t hash(const char* p_cstr); /* hash the string */ + static uint32_t hash(const CharType *p_str, int p_len); /* hash the string */ + static uint32_t hash(const CharType *p_str); /* hash the string */ + static uint32_t hash(const char *p_cstr, int p_len); /* hash the string */ + static uint32_t hash(const char *p_cstr); /* hash the string */ uint32_t hash() const; /* hash the string */ uint64_t hash64() const; /* hash the string */ String md5_text() const; @@ -208,17 +201,17 @@ public: bool is_abs_path() const; bool is_rel_path() const; bool is_resource_file() const; - String path_to(const String& p_path) const; - String path_to_file(const String& p_path) const; + String path_to(const String &p_path) const; + String path_to_file(const String &p_path) const; String get_base_dir() const; String get_file() const; static String humanize_size(size_t p_size); String simplify_path() const; - String xml_escape(bool p_escape_quotes=false) const; + String xml_escape(bool p_escape_quotes = false) const; String xml_unescape() const; - String http_escape() const; - String http_unescape() const; + String http_escape() const; + String http_unescape() const; String c_escape() const; String c_escape_multiline() const; String c_unescape() const; @@ -238,40 +231,36 @@ public: /** * The constructors must not depend on other overloads */ -/* String(CharType p_char);*/ + /* String(CharType p_char);*/ inline String() {} String(const char *p_str); - String(const CharType *p_str,int p_clip_to_len=-1); - String(const StrRange& p_range); - - + String(const CharType *p_str, int p_clip_to_len = -1); + String(const StrRange &p_range); }; +bool operator==(const char *p_chr, const String &p_str); -bool operator==(const char*p_chr, const String& p_str); - -String operator+(const char*p_chr, const String& p_str); -String operator+(CharType p_chr, const String& p_str); +String operator+(const char *p_chr, const String &p_str); +String operator+(CharType p_chr, const String &p_str); String itos(int64_t p_val); String rtos(double p_val); String rtoss(double p_val); //scientific version - struct NoCaseComparator { - bool operator()(const String& p_a, const String& p_b) const { + bool operator()(const String &p_a, const String &p_b) const { - return p_a.nocasecmp_to(p_b)<0; + return p_a.nocasecmp_to(p_b) < 0; } }; - /* end of namespace */ +/* end of namespace */ //tool translate #ifdef TOOLS_ENABLED -String TTR(const String&); +String TTR(const String &); #else @@ -280,6 +269,6 @@ String TTR(const String&); #endif //tool or regular translate -String RTR(const String&); +String RTR(const String &); #endif diff --git a/core/variant.cpp b/core/variant.cpp index 6fd0618250..771d97a4eb 100644 --- a/core/variant.cpp +++ b/core/variant.cpp @@ -28,25 +28,24 @@ /*************************************************************************/ #include "variant.h" +#include "core_string_names.h" +#include "io/marshalls.h" #include "math_funcs.h" -#include "resource.h" #include "print_string.h" -#include "scene/main/node.h" +#include "resource.h" #include "scene/gui/control.h" -#include "io/marshalls.h" -#include "core_string_names.h" +#include "scene/main/node.h" #include "variant_parser.h" - String Variant::get_type_name(Variant::Type p_type) { - switch( p_type ) { + switch (p_type) { case NIL: { return "Nil"; } break; - // atomic types + // atomic types case BOOL: { return "bool"; @@ -66,7 +65,7 @@ String Variant::get_type_name(Variant::Type p_type) { return "String"; } break; - // math types + // math types case VECTOR2: { @@ -89,7 +88,7 @@ String Variant::get_type_name(Variant::Type p_type) { return "Plane"; } break; - /* + /* case QUAT: { @@ -114,7 +113,7 @@ String Variant::get_type_name(Variant::Type p_type) { } break; - // misc types + // misc types case COLOR: { return "Color"; @@ -154,7 +153,7 @@ String Variant::get_type_name(Variant::Type p_type) { } break; - // arrays + // arrays case POOL_BYTE_ARRAY: { return "PoolByteArray"; @@ -190,114 +189,110 @@ String Variant::get_type_name(Variant::Type p_type) { } break; default: {} - } + } return ""; } +bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) { -bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) { - - if (p_type_from==p_type_to) + if (p_type_from == p_type_to) return true; - if (p_type_to==NIL && p_type_from!=NIL) //nil can convert to anything + if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything return true; if (p_type_from == NIL) { return (p_type_to == OBJECT); }; - const Type *valid_types=NULL; - const Type *invalid_types=NULL; + const Type *valid_types = NULL; + const Type *invalid_types = NULL; - switch(p_type_to) { + switch (p_type_to) { case BOOL: { - static const Type valid[]={ + static const Type valid[] = { INT, REAL, STRING, NIL, }; - valid_types=valid; + valid_types = valid; } break; case INT: { - static const Type valid[]={ + static const Type valid[] = { BOOL, REAL, STRING, NIL, }; - valid_types=valid; + valid_types = valid; } break; case REAL: { - static const Type valid[]={ + static const Type valid[] = { BOOL, INT, STRING, NIL, }; - valid_types=valid; + valid_types = valid; } break; case STRING: { - - static const Type invalid[]={ + static const Type invalid[] = { OBJECT, IMAGE, NIL }; - invalid_types=invalid; + invalid_types = invalid; } break; case TRANSFORM2D: { - - static const Type valid[]={ + static const Type valid[] = { TRANSFORM, NIL }; - valid_types=valid; + valid_types = valid; } break; case QUAT: { - static const Type valid[]={ + static const Type valid[] = { BASIS, NIL }; - valid_types=valid; + valid_types = valid; } break; case BASIS: { - static const Type valid[]={ + static const Type valid[] = { QUAT, NIL }; - valid_types=valid; - + valid_types = valid; } break; case TRANSFORM: { - static const Type valid[]={ + static const Type valid[] = { TRANSFORM2D, QUAT, BASIS, NIL }; - valid_types=valid; + valid_types = valid; } break; @@ -315,34 +310,33 @@ bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) { case _RID: { - static const Type valid[]={ + static const Type valid[] = { OBJECT, NIL }; - valid_types=valid; + valid_types = valid; } break; case OBJECT: { - static const Type valid[]={ + static const Type valid[] = { NIL }; - valid_types=valid; + valid_types = valid; } break; case NODE_PATH: { - static const Type valid[]={ + static const Type valid[] = { STRING, NIL }; - valid_types=valid; + valid_types = valid; } break; case ARRAY: { - - static const Type valid[]={ + static const Type valid[] = { POOL_BYTE_ARRAY, POOL_INT_ARRAY, POOL_STRING_ARRAY, @@ -353,92 +347,90 @@ bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) { NIL }; - valid_types=valid; + valid_types = valid; } break; - // arrays + // arrays case POOL_BYTE_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_INT_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_REAL_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_STRING_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_VECTOR2_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_VECTOR3_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_COLOR_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; default: {} } - if (valid_types) { - int i=0; - while(valid_types[i]!=NIL) { + int i = 0; + while (valid_types[i] != NIL) { - if (p_type_from==valid_types[i]) + if (p_type_from == valid_types[i]) return true; i++; } } else if (invalid_types) { + int i = 0; + while (invalid_types[i] != NIL) { - int i=0; - while(invalid_types[i]!=NIL) { - - if (p_type_from==invalid_types[i]) + if (p_type_from == invalid_types[i]) return false; i++; } @@ -447,109 +439,105 @@ bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) { } return false; - } -bool Variant::can_convert_strict(Variant::Type p_type_from,Variant::Type p_type_to) { +bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type_to) { - if (p_type_from==p_type_to) + if (p_type_from == p_type_to) return true; - if (p_type_to==NIL && p_type_from!=NIL) //nil can convert to anything + if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything return true; if (p_type_from == NIL) { return (p_type_to == OBJECT); }; - const Type *valid_types=NULL; + const Type *valid_types = NULL; - switch(p_type_to) { + switch (p_type_to) { case BOOL: { - static const Type valid[]={ + static const Type valid[] = { INT, REAL, //STRING, NIL, }; - valid_types=valid; + valid_types = valid; } break; case INT: { - static const Type valid[]={ + static const Type valid[] = { BOOL, REAL, //STRING, NIL, }; - valid_types=valid; + valid_types = valid; } break; case REAL: { - static const Type valid[]={ + static const Type valid[] = { BOOL, INT, //STRING, NIL, }; - valid_types=valid; + valid_types = valid; } break; case STRING: { - - static const Type valid[]={ + static const Type valid[] = { NODE_PATH, NIL }; - valid_types=valid; + valid_types = valid; } break; case TRANSFORM2D: { - - static const Type valid[]={ + static const Type valid[] = { TRANSFORM, NIL }; - valid_types=valid; + valid_types = valid; } break; case QUAT: { - static const Type valid[]={ + static const Type valid[] = { BASIS, NIL }; - valid_types=valid; + valid_types = valid; } break; case BASIS: { - static const Type valid[]={ + static const Type valid[] = { QUAT, NIL }; - valid_types=valid; - + valid_types = valid; } break; case TRANSFORM: { - static const Type valid[]={ + static const Type valid[] = { TRANSFORM2D, QUAT, BASIS, NIL }; - valid_types=valid; + valid_types = valid; } break; @@ -567,34 +555,33 @@ bool Variant::can_convert_strict(Variant::Type p_type_from,Variant::Type p_type_ case _RID: { - static const Type valid[]={ + static const Type valid[] = { OBJECT, NIL }; - valid_types=valid; + valid_types = valid; } break; case OBJECT: { - static const Type valid[]={ + static const Type valid[] = { NIL }; - valid_types=valid; + valid_types = valid; } break; case NODE_PATH: { - static const Type valid[]={ + static const Type valid[] = { STRING, NIL }; - valid_types=valid; + valid_types = valid; } break; case ARRAY: { - - static const Type valid[]={ + static const Type valid[] = { POOL_BYTE_ARRAY, POOL_INT_ARRAY, POOL_STRING_ARRAY, @@ -605,124 +592,120 @@ bool Variant::can_convert_strict(Variant::Type p_type_from,Variant::Type p_type_ NIL }; - valid_types=valid; + valid_types = valid; } break; - // arrays + // arrays case POOL_BYTE_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_INT_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_REAL_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_STRING_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_VECTOR2_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_VECTOR3_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; case POOL_COLOR_ARRAY: { - static const Type valid[]={ + static const Type valid[] = { ARRAY, NIL }; - valid_types=valid; + valid_types = valid; } break; default: {} } - if (valid_types) { - int i=0; - while(valid_types[i]!=NIL) { + int i = 0; + while (valid_types[i] != NIL) { - if (p_type_from==valid_types[i]) + if (p_type_from == valid_types[i]) return true; i++; } } return false; - } -bool Variant::operator==(const Variant& p_variant) const { +bool Variant::operator==(const Variant &p_variant) const { - if (type!=p_variant.type) //evaluation of operator== needs to be more strict + if (type != p_variant.type) //evaluation of operator== needs to be more strict return false; bool v; Variant r; - evaluate(OP_EQUAL,*this,p_variant,r,v); + evaluate(OP_EQUAL, *this, p_variant, r, v); return r; - } -bool Variant::operator!=(const Variant& p_variant) const { +bool Variant::operator!=(const Variant &p_variant) const { - if (type!=p_variant.type) //evaluation of operator== needs to be more strict + if (type != p_variant.type) //evaluation of operator== needs to be more strict return true; bool v; Variant r; - evaluate(OP_NOT_EQUAL,*this,p_variant,r,v); + evaluate(OP_NOT_EQUAL, *this, p_variant, r, v); return r; - } -bool Variant::operator<(const Variant& p_variant) const { - if (type!=p_variant.type) //if types differ, then order by type first - return type<p_variant.type; +bool Variant::operator<(const Variant &p_variant) const { + if (type != p_variant.type) //if types differ, then order by type first + return type < p_variant.type; bool v; Variant r; - evaluate(OP_LESS,*this,p_variant,r,v); + evaluate(OP_LESS, *this, p_variant, r, v); return r; } bool Variant::is_zero() const { - switch( type ) { + switch (type) { case NIL: { return true; @@ -731,21 +714,21 @@ bool Variant::is_zero() const { // atomic types case BOOL: { - return _data._bool==false; + return _data._bool == false; } break; case INT: { - return _data._int==0; + return _data._int == 0; } break; case REAL: { - return _data._real==0; + return _data._real == 0; } break; case STRING: { - return *reinterpret_cast<const String*>(_data._mem)==String(); + return *reinterpret_cast<const String *>(_data._mem) == String(); } break; @@ -753,46 +736,46 @@ bool Variant::is_zero() const { case VECTOR2: { - return *reinterpret_cast<const Vector2*>(_data._mem)==Vector2(); + return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(); } break; case RECT2: { - return *reinterpret_cast<const Rect2*>(_data._mem)==Rect2(); + return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(); } break; case TRANSFORM2D: { - return *_data._transform2d==Transform2D(); + return *_data._transform2d == Transform2D(); } break; case VECTOR3: { - return *reinterpret_cast<const Vector3*>(_data._mem)==Vector3(); + return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(); } break; case PLANE: { - return *reinterpret_cast<const Plane*>(_data._mem)==Plane(); + return *reinterpret_cast<const Plane *>(_data._mem) == Plane(); } break; -/* + /* case QUAT: { } break;*/ case RECT3: { - return *_data._rect3==Rect3(); + return *_data._rect3 == Rect3(); } break; case QUAT: { - return *reinterpret_cast<const Quat*>(_data._mem)==Quat(); + return *reinterpret_cast<const Quat *>(_data._mem) == Quat(); } break; case BASIS: { - return *_data._basis==Basis(); + return *_data._basis == Basis(); } break; case TRANSFORM: { @@ -804,7 +787,7 @@ bool Variant::is_zero() const { // misc types case COLOR: { - return *reinterpret_cast<const Color*>(_data._mem)==Color(); + return *reinterpret_cast<const Color *>(_data._mem) == Color(); } break; case IMAGE: { @@ -814,67 +797,67 @@ bool Variant::is_zero() const { } break; case _RID: { - return *reinterpret_cast<const RID*>(_data._mem)==RID(); + return *reinterpret_cast<const RID *>(_data._mem) == RID(); } break; case OBJECT: { - return _get_obj().obj==NULL; + return _get_obj().obj == NULL; } break; case NODE_PATH: { - return reinterpret_cast<const NodePath*>(_data._mem)->is_empty(); + return reinterpret_cast<const NodePath *>(_data._mem)->is_empty(); } break; case INPUT_EVENT: { - return _data._input_event->type==InputEvent::NONE; + return _data._input_event->type == InputEvent::NONE; } break; case DICTIONARY: { - return reinterpret_cast<const Dictionary*>(_data._mem)->empty(); + return reinterpret_cast<const Dictionary *>(_data._mem)->empty(); } break; case ARRAY: { - return reinterpret_cast<const Array*>(_data._mem)->empty(); + return reinterpret_cast<const Array *>(_data._mem)->empty(); } break; // arrays case POOL_BYTE_ARRAY: { - return reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem)->size() == 0; } break; case POOL_INT_ARRAY: { - return reinterpret_cast<const PoolVector<int>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<int> *>(_data._mem)->size() == 0; } break; case POOL_REAL_ARRAY: { - return reinterpret_cast<const PoolVector<real_t>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<real_t> *>(_data._mem)->size() == 0; } break; case POOL_STRING_ARRAY: { - return reinterpret_cast<const PoolVector<String>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<String> *>(_data._mem)->size() == 0; } break; case POOL_VECTOR2_ARRAY: { - return reinterpret_cast<const PoolVector<Vector2>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<Vector2> *>(_data._mem)->size() == 0; } break; case POOL_VECTOR3_ARRAY: { - return reinterpret_cast<const PoolVector<Vector3>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<Vector3> *>(_data._mem)->size() == 0; } break; case POOL_COLOR_ARRAY: { - return reinterpret_cast<const PoolVector<Color>*>(_data._mem)->size()==0; + return reinterpret_cast<const PoolVector<Color> *>(_data._mem)->size() == 0; } break; default: {} @@ -883,10 +866,9 @@ bool Variant::is_zero() const { return false; } - bool Variant::is_one() const { - switch( type ) { + switch (type) { case NIL: { return true; @@ -895,41 +877,41 @@ bool Variant::is_one() const { // atomic types case BOOL: { - return _data._bool==true; + return _data._bool == true; } break; case INT: { - return _data._int==1; + return _data._int == 1; } break; case REAL: { - return _data._real==1; + return _data._real == 1; } break; case VECTOR2: { - return *reinterpret_cast<const Vector2*>(_data._mem)==Vector2(1,1); + return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(1, 1); } break; case RECT2: { - return *reinterpret_cast<const Rect2*>(_data._mem)==Rect2(1,1,1,1); + return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(1, 1, 1, 1); } break; case VECTOR3: { - return *reinterpret_cast<const Vector3*>(_data._mem)==Vector3(1,1,1); + return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(1, 1, 1); } break; case PLANE: { - return *reinterpret_cast<const Plane*>(_data._mem)==Plane(1,1,1,1); + return *reinterpret_cast<const Plane *>(_data._mem) == Plane(1, 1, 1, 1); } break; case COLOR: { - return *reinterpret_cast<const Color*>(_data._mem)==Color(1,1,1,1); + return *reinterpret_cast<const Color *>(_data._mem) == Color(1, 1, 1, 1); } break; @@ -939,18 +921,16 @@ bool Variant::is_one() const { return false; } - -void Variant::reference(const Variant& p_variant) { - +void Variant::reference(const Variant &p_variant) { if (this == &p_variant) return; clear(); - type=p_variant.type; + type = p_variant.type; - switch( p_variant.type ) { + switch (p_variant.type) { case NIL: { // none @@ -959,21 +939,21 @@ void Variant::reference(const Variant& p_variant) { // atomic types case BOOL: { - _data._bool=p_variant._data._bool; + _data._bool = p_variant._data._bool; } break; case INT: { - _data._int=p_variant._data._int; + _data._int = p_variant._data._int; } break; case REAL: { - _data._real=p_variant._data._real; + _data._real = p_variant._data._real; } break; case STRING: { - memnew_placement( _data._mem, String( *reinterpret_cast<const String*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, String(*reinterpret_cast<const String *>(p_variant._data._mem))); } break; @@ -981,158 +961,156 @@ void Variant::reference(const Variant& p_variant) { case VECTOR2: { - memnew_placement( _data._mem, Vector2( *reinterpret_cast<const Vector2*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Vector2(*reinterpret_cast<const Vector2 *>(p_variant._data._mem))); } break; case RECT2: { - memnew_placement( _data._mem, Rect2( *reinterpret_cast<const Rect2*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Rect2(*reinterpret_cast<const Rect2 *>(p_variant._data._mem))); } break; case TRANSFORM2D: { - _data._transform2d = memnew( Transform2D( *p_variant._data._transform2d ) ); + _data._transform2d = memnew(Transform2D(*p_variant._data._transform2d)); } break; case VECTOR3: { - memnew_placement( _data._mem, Vector3( *reinterpret_cast<const Vector3*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Vector3(*reinterpret_cast<const Vector3 *>(p_variant._data._mem))); } break; case PLANE: { - memnew_placement( _data._mem, Plane( *reinterpret_cast<const Plane*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Plane(*reinterpret_cast<const Plane *>(p_variant._data._mem))); } break; -/* + /* case QUAT: { } break;*/ case RECT3: { - _data._rect3 = memnew( Rect3( *p_variant._data._rect3 ) ); + _data._rect3 = memnew(Rect3(*p_variant._data._rect3)); } break; case QUAT: { - memnew_placement( _data._mem, Quat( *reinterpret_cast<const Quat*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Quat(*reinterpret_cast<const Quat *>(p_variant._data._mem))); } break; case BASIS: { - _data._basis = memnew( Basis( *p_variant._data._basis ) ); + _data._basis = memnew(Basis(*p_variant._data._basis)); } break; case TRANSFORM: { - _data._transform = memnew( Transform( *p_variant._data._transform ) ); + _data._transform = memnew(Transform(*p_variant._data._transform)); } break; // misc types case COLOR: { - memnew_placement( _data._mem, Color( *reinterpret_cast<const Color*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Color(*reinterpret_cast<const Color *>(p_variant._data._mem))); } break; case IMAGE: { - _data._image = memnew( Image( *p_variant._data._image ) ); + _data._image = memnew(Image(*p_variant._data._image)); } break; case _RID: { - memnew_placement( _data._mem, RID( *reinterpret_cast<const RID*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, RID(*reinterpret_cast<const RID *>(p_variant._data._mem))); } break; case OBJECT: { - memnew_placement( _data._mem, ObjData( p_variant._get_obj() ) ); + memnew_placement(_data._mem, ObjData(p_variant._get_obj())); } break; case NODE_PATH: { - memnew_placement( _data._mem, NodePath( *reinterpret_cast<const NodePath*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, NodePath(*reinterpret_cast<const NodePath *>(p_variant._data._mem))); } break; case INPUT_EVENT: { - _data._input_event= memnew( InputEvent( *p_variant._data._input_event ) ); + _data._input_event = memnew(InputEvent(*p_variant._data._input_event)); } break; case DICTIONARY: { - memnew_placement( _data._mem, Dictionary( *reinterpret_cast<const Dictionary*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Dictionary(*reinterpret_cast<const Dictionary *>(p_variant._data._mem))); } break; case ARRAY: { - memnew_placement( _data._mem, Array ( *reinterpret_cast<const Array*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, Array(*reinterpret_cast<const Array *>(p_variant._data._mem))); } break; // arrays case POOL_BYTE_ARRAY: { - memnew_placement( _data._mem, PoolVector<uint8_t> ( *reinterpret_cast<const PoolVector<uint8_t>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<uint8_t>(*reinterpret_cast<const PoolVector<uint8_t> *>(p_variant._data._mem))); } break; case POOL_INT_ARRAY: { - memnew_placement( _data._mem, PoolVector<int> ( *reinterpret_cast<const PoolVector<int>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<int>(*reinterpret_cast<const PoolVector<int> *>(p_variant._data._mem))); } break; case POOL_REAL_ARRAY: { - memnew_placement( _data._mem, PoolVector<real_t> ( *reinterpret_cast<const PoolVector<real_t>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<real_t>(*reinterpret_cast<const PoolVector<real_t> *>(p_variant._data._mem))); } break; case POOL_STRING_ARRAY: { - memnew_placement( _data._mem, PoolVector<String> ( *reinterpret_cast<const PoolVector<String>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<String>(*reinterpret_cast<const PoolVector<String> *>(p_variant._data._mem))); } break; case POOL_VECTOR2_ARRAY: { - memnew_placement( _data._mem, PoolVector<Vector2> ( *reinterpret_cast<const PoolVector<Vector2>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<Vector2>(*reinterpret_cast<const PoolVector<Vector2> *>(p_variant._data._mem))); } break; case POOL_VECTOR3_ARRAY: { - memnew_placement( _data._mem, PoolVector<Vector3> ( *reinterpret_cast<const PoolVector<Vector3>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<Vector3>(*reinterpret_cast<const PoolVector<Vector3> *>(p_variant._data._mem))); } break; case POOL_COLOR_ARRAY: { - memnew_placement( _data._mem, PoolVector<Color> ( *reinterpret_cast<const PoolVector<Color>*>(p_variant._data._mem) ) ); + memnew_placement(_data._mem, PoolVector<Color>(*reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem))); } break; default: {} } - - } void Variant::zero() { - switch(type) { + switch (type) { case NIL: break; case BOOL: this->_data._bool = false; break; case INT: this->_data._int = 0; break; case REAL: this->_data._real = 0; break; - case VECTOR2: *reinterpret_cast<Vector2*>(this->_data._mem) = Vector2(); break; - case RECT2: *reinterpret_cast<Rect2*>(this->_data._mem) = Rect2(); break; - case VECTOR3: *reinterpret_cast<Vector3*>(this->_data._mem) = Vector3(); break; - case PLANE: *reinterpret_cast<Plane*>(this->_data._mem) = Plane(); break; - case QUAT: *reinterpret_cast<Quat*>(this->_data._mem) = Quat(); break; - case COLOR: *reinterpret_cast<Color*>(this->_data._mem) = Color(); break; + case VECTOR2: *reinterpret_cast<Vector2 *>(this->_data._mem) = Vector2(); break; + case RECT2: *reinterpret_cast<Rect2 *>(this->_data._mem) = Rect2(); break; + case VECTOR3: *reinterpret_cast<Vector3 *>(this->_data._mem) = Vector3(); break; + case PLANE: *reinterpret_cast<Plane *>(this->_data._mem) = Plane(); break; + case QUAT: *reinterpret_cast<Quat *>(this->_data._mem) = Quat(); break; + case COLOR: *reinterpret_cast<Color *>(this->_data._mem) = Color(); break; default: this->clear(); break; } } void Variant::clear() { - switch(type) { + switch (type) { case STRING: { - reinterpret_cast<String*>(_data._mem)->~String(); + reinterpret_cast<String *>(_data._mem)->~String(); } break; - /* + /* // no point, they don't allocate memory VECTOR3, PLANE, @@ -1143,107 +1121,105 @@ void Variant::clear() { */ case TRANSFORM2D: { - memdelete( _data._transform2d ); + memdelete(_data._transform2d); } break; case RECT3: { - memdelete( _data._rect3 ); + memdelete(_data._rect3); } break; case BASIS: { - memdelete( _data._basis ); + memdelete(_data._basis); } break; case TRANSFORM: { - memdelete( _data._transform ); + memdelete(_data._transform); } break; // misc types case IMAGE: { - memdelete( _data._image ); + memdelete(_data._image); } break; case NODE_PATH: { - reinterpret_cast<NodePath*>(_data._mem)->~NodePath(); + reinterpret_cast<NodePath *>(_data._mem)->~NodePath(); } break; case OBJECT: { - _get_obj().obj=NULL; + _get_obj().obj = NULL; _get_obj().ref.unref(); } break; case _RID: { // not much need probably - reinterpret_cast<RID*>(_data._mem)->~RID(); + reinterpret_cast<RID *>(_data._mem)->~RID(); } break; case DICTIONARY: { - reinterpret_cast<Dictionary*>(_data._mem)->~Dictionary(); + reinterpret_cast<Dictionary *>(_data._mem)->~Dictionary(); } break; case ARRAY: { - reinterpret_cast<Array*>(_data._mem)->~Array(); + reinterpret_cast<Array *>(_data._mem)->~Array(); } break; case INPUT_EVENT: { - memdelete( _data._input_event ); + memdelete(_data._input_event); } break; // arrays case POOL_BYTE_ARRAY: { - reinterpret_cast< PoolVector<uint8_t>* >(_data._mem)->~PoolVector<uint8_t>(); + reinterpret_cast<PoolVector<uint8_t> *>(_data._mem)->~PoolVector<uint8_t>(); } break; case POOL_INT_ARRAY: { - reinterpret_cast< PoolVector<int>* >(_data._mem)->~PoolVector<int>(); + reinterpret_cast<PoolVector<int> *>(_data._mem)->~PoolVector<int>(); } break; case POOL_REAL_ARRAY: { - reinterpret_cast< PoolVector<real_t>* >(_data._mem)->~PoolVector<real_t>(); + reinterpret_cast<PoolVector<real_t> *>(_data._mem)->~PoolVector<real_t>(); } break; case POOL_STRING_ARRAY: { - reinterpret_cast< PoolVector<String>* >(_data._mem)->~PoolVector<String>(); + reinterpret_cast<PoolVector<String> *>(_data._mem)->~PoolVector<String>(); } break; case POOL_VECTOR2_ARRAY: { - reinterpret_cast< PoolVector<Vector2>* >(_data._mem)->~PoolVector<Vector2>(); + reinterpret_cast<PoolVector<Vector2> *>(_data._mem)->~PoolVector<Vector2>(); } break; case POOL_VECTOR3_ARRAY: { - reinterpret_cast< PoolVector<Vector3>* >(_data._mem)->~PoolVector<Vector3>(); + reinterpret_cast<PoolVector<Vector3> *>(_data._mem)->~PoolVector<Vector3>(); } break; case POOL_COLOR_ARRAY: { - reinterpret_cast< PoolVector<Color>* >(_data._mem)->~PoolVector<Color>(); + reinterpret_cast<PoolVector<Color> *>(_data._mem)->~PoolVector<Color>(); } break; default: {} /* not needed */ } - type=NIL; - + type = NIL; } - Variant::operator signed int() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1260,7 +1236,7 @@ Variant::operator signed int() const { } Variant::operator unsigned int() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1278,7 +1254,7 @@ Variant::operator unsigned int() const { Variant::operator int64_t() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1316,7 +1292,7 @@ Variant::operator long unsigned int() const { Variant::operator uint64_t() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1335,7 +1311,7 @@ Variant::operator uint64_t() const { #ifdef NEED_LONG_INT Variant::operator signed long() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1353,7 +1329,7 @@ Variant::operator signed long() const { Variant::operator unsigned long() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1370,10 +1346,9 @@ Variant::operator unsigned long() const { }; #endif - Variant::operator signed short() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1390,7 +1365,7 @@ Variant::operator signed short() const { } Variant::operator unsigned short() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1407,7 +1382,7 @@ Variant::operator unsigned short() const { } Variant::operator signed char() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1424,7 +1399,7 @@ Variant::operator signed char() const { } Variant::operator unsigned char() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; @@ -1445,10 +1420,9 @@ Variant::operator CharType() const { return operator unsigned int(); } - Variant::operator float() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1.0 : 0.0; @@ -1465,7 +1439,7 @@ Variant::operator float() const { } Variant::operator double() const { - switch( type ) { + switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1.0 : 0.0; @@ -1483,8 +1457,8 @@ Variant::operator double() const { Variant::operator StringName() const { - if (type==NODE_PATH) { - return reinterpret_cast<const NodePath*>(_data._mem)->get_sname(); + if (type == NODE_PATH) { + return reinterpret_cast<const NodePath *>(_data._mem)->get_sname(); } return StringName(operator String()); } @@ -1494,7 +1468,7 @@ struct _VariantStrPair { String key; String value; - bool operator<(const _VariantStrPair& p) const { + bool operator<(const _VariantStrPair &p) const { return key < p.key; } @@ -1502,57 +1476,58 @@ struct _VariantStrPair { Variant::operator String() const { - switch( type ) { + switch (type) { case NIL: return "Null"; case BOOL: return _data._bool ? "True" : "False"; case INT: return itos(_data._int); case REAL: return rtos(_data._real); - case STRING: return *reinterpret_cast<const String*>(_data._mem); - case VECTOR2: return "("+operator Vector2()+")"; - case RECT2: return "("+operator Rect2()+")"; + case STRING: return *reinterpret_cast<const String *>(_data._mem); + case VECTOR2: return "(" + operator Vector2() + ")"; + case RECT2: return "(" + operator Rect2() + ")"; case TRANSFORM2D: { Transform2D mat32 = operator Transform2D(); - return "("+Variant(mat32.elements[0]).operator String()+", "+Variant(mat32.elements[1]).operator String()+", "+Variant(mat32.elements[2]).operator String()+")"; + return "(" + Variant(mat32.elements[0]).operator String() + ", " + Variant(mat32.elements[1]).operator String() + ", " + Variant(mat32.elements[2]).operator String() + ")"; } break; - case VECTOR3: return "("+operator Vector3()+")"; - case PLANE: return operator Plane(); + case VECTOR3: return "(" + operator Vector3() + ")"; + case PLANE: + return operator Plane(); //case QUAT: case RECT3: return operator Rect3(); - case QUAT: return "("+operator Quat()+")"; + case QUAT: return "(" + operator Quat() + ")"; case BASIS: { Basis mat3 = operator Basis(); String mtx("("); - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - if (i!=0) - mtx+=", "; + if (i != 0) + mtx += ", "; - mtx+="("; + mtx += "("; - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - if (j!=0) - mtx+=", "; + if (j != 0) + mtx += ", "; - mtx+=Variant( mat3.elements[i][j] ).operator String(); + mtx += Variant(mat3.elements[i][j]).operator String(); } - mtx+=")"; + mtx += ")"; } - return mtx+")"; + return mtx + ")"; } break; case TRANSFORM: return operator Transform(); case NODE_PATH: return operator NodePath(); case INPUT_EVENT: return operator InputEvent(); - case COLOR: return String::num( operator Color().r)+","+String::num( operator Color().g)+","+String::num( operator Color().b)+","+String::num( operator Color().a) ; + case COLOR: return String::num(operator Color().r) + "," + String::num(operator Color().g) + "," + String::num(operator Color().b) + "," + String::num(operator Color().a); case DICTIONARY: { - const Dictionary &d =*reinterpret_cast<const Dictionary*>(_data._mem); + const Dictionary &d = *reinterpret_cast<const Dictionary *>(_data._mem); //const String *K=NULL; String str; List<Variant> keys; @@ -1560,20 +1535,20 @@ Variant::operator String() const { Vector<_VariantStrPair> pairs; - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _VariantStrPair sp; - sp.key=String(E->get()); - sp.value=d[E->get()]; + sp.key = String(E->get()); + sp.value = d[E->get()]; pairs.push_back(sp); } pairs.sort(); - for(int i=0;i<pairs.size();i++) { - if (i>0) - str+=", "; - str+="("+pairs[i].key+":"+pairs[i].value+")"; + for (int i = 0; i < pairs.size(); i++) { + if (i > 0) + str += ", "; + str += "(" + pairs[i].key + ":" + pairs[i].value + ")"; } return str; @@ -1582,11 +1557,11 @@ Variant::operator String() const { PoolVector<Vector2> vec = operator PoolVector<Vector2>(); String str("["); - for(int i=0;i<vec.size();i++) { + for (int i = 0; i < vec.size(); i++) { - if (i>0) - str+=", "; - str=str+Variant( vec[i] ); + if (i > 0) + str += ", "; + str = str + Variant(vec[i]); } str += "]"; return str; @@ -1595,11 +1570,11 @@ Variant::operator String() const { PoolVector<Vector3> vec = operator PoolVector<Vector3>(); String str("["); - for(int i=0;i<vec.size();i++) { + for (int i = 0; i < vec.size(); i++) { - if (i>0) - str+=", "; - str=str+Variant( vec[i] ); + if (i > 0) + str += ", "; + str = str + Variant(vec[i]); } str += "]"; return str; @@ -1608,11 +1583,11 @@ Variant::operator String() const { PoolVector<String> vec = operator PoolVector<String>(); String str("["); - for(int i=0;i<vec.size();i++) { + for (int i = 0; i < vec.size(); i++) { - if (i>0) - str+=", "; - str=str+vec[i]; + if (i > 0) + str += ", "; + str = str + vec[i]; } str += "]"; return str; @@ -1621,11 +1596,11 @@ Variant::operator String() const { PoolVector<int> vec = operator PoolVector<int>(); String str("["); - for(int i=0;i<vec.size();i++) { + for (int i = 0; i < vec.size(); i++) { - if (i>0) - str+=", "; - str=str+itos(vec[i]); + if (i > 0) + str += ", "; + str = str + itos(vec[i]); } str += "]"; return str; @@ -1634,11 +1609,11 @@ Variant::operator String() const { PoolVector<real_t> vec = operator PoolVector<real_t>(); String str("["); - for(int i=0;i<vec.size();i++) { + for (int i = 0; i < vec.size(); i++) { - if (i>0) - str+=", "; - str=str+rtos(vec[i]); + if (i > 0) + str += ", "; + str = str + rtos(vec[i]); } str += "]"; return str; @@ -1647,9 +1622,9 @@ Variant::operator String() const { Array arr = operator Array(); String str("["); - for (int i=0; i<arr.size(); i++) { + for (int i = 0; i < arr.size(); i++) { if (i) - str+=", "; + str += ", "; str += String(arr[i]); }; str += "]"; @@ -1659,21 +1634,21 @@ Variant::operator String() const { case OBJECT: { if (_get_obj().obj) { - #ifdef DEBUG_ENABLED - if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { - //only if debugging! - if (!ObjectDB::instance_validate(_get_obj().obj)) { - return "[Deleted Object]"; - }; +#ifdef DEBUG_ENABLED + if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { + //only if debugging! + if (!ObjectDB::instance_validate(_get_obj().obj)) { + return "[Deleted Object]"; }; - #endif - return "["+_get_obj().obj->get_class()+":"+itos(_get_obj().obj->get_instance_ID())+"]"; + }; +#endif + return "[" + _get_obj().obj->get_class() + ":" + itos(_get_obj().obj->get_instance_ID()) + "]"; } else return "[Object:null]"; } break; default: { - return "["+get_type_name(type)+"]"; + return "[" + get_type_name(type) + "]"; } } @@ -1682,42 +1657,38 @@ Variant::operator String() const { Variant::operator Vector2() const { - if (type==VECTOR2) - return *reinterpret_cast<const Vector2*>(_data._mem); - else if (type==VECTOR3) - return Vector2(reinterpret_cast<const Vector3*>(_data._mem)->x,reinterpret_cast<const Vector3*>(_data._mem)->y); + if (type == VECTOR2) + return *reinterpret_cast<const Vector2 *>(_data._mem); + else if (type == VECTOR3) + return Vector2(reinterpret_cast<const Vector3 *>(_data._mem)->x, reinterpret_cast<const Vector3 *>(_data._mem)->y); else return Vector2(); - } Variant::operator Rect2() const { - if (type==RECT2) - return *reinterpret_cast<const Rect2*>(_data._mem); + if (type == RECT2) + return *reinterpret_cast<const Rect2 *>(_data._mem); else return Rect2(); - } Variant::operator Vector3() const { - if (type==VECTOR3) - return *reinterpret_cast<const Vector3*>(_data._mem); + if (type == VECTOR3) + return *reinterpret_cast<const Vector3 *>(_data._mem); else return Vector3(); - } Variant::operator Plane() const { - if (type==PLANE) - return *reinterpret_cast<const Plane*>(_data._mem); + if (type == PLANE) + return *reinterpret_cast<const Plane *>(_data._mem); else return Plane(); - } Variant::operator Rect3() const { - if (type==RECT3) + if (type == RECT3) return *_data._rect3; else return Rect3(); @@ -1725,11 +1696,11 @@ Variant::operator Rect3() const { Variant::operator Basis() const { - if (type==BASIS) + if (type == BASIS) return *_data._basis; - else if (type==QUAT) - return *reinterpret_cast<const Quat*>(_data._mem); - else if (type==TRANSFORM) + else if (type == QUAT) + return *reinterpret_cast<const Quat *>(_data._mem); + else if (type == TRANSFORM) return _data._transform->basis; else return Basis(); @@ -1737,63 +1708,60 @@ Variant::operator Basis() const { Variant::operator Quat() const { - if (type==QUAT) - return *reinterpret_cast<const Quat*>(_data._mem); - else if (type==BASIS) - return *_data._basis; - else if (type==TRANSFORM) - return _data._transform->basis; + if (type == QUAT) + return *reinterpret_cast<const Quat *>(_data._mem); + else if (type == BASIS) + return *_data._basis; + else if (type == TRANSFORM) + return _data._transform->basis; else return Quat(); } - - Variant::operator Transform() const { - if (type==TRANSFORM) + if (type == TRANSFORM) return *_data._transform; - else if (type==BASIS) - return Transform(*_data._basis,Vector3()); - else if (type==QUAT) - return Transform(Basis(*reinterpret_cast<const Quat*>(_data._mem)),Vector3()); + else if (type == BASIS) + return Transform(*_data._basis, Vector3()); + else if (type == QUAT) + return Transform(Basis(*reinterpret_cast<const Quat *>(_data._mem)), Vector3()); else return Transform(); } - Variant::operator Transform2D() const { +Variant::operator Transform2D() const { - if (type==TRANSFORM2D) { - return *_data._transform2d; - } else if (type==TRANSFORM) { - const Transform& t = *_data._transform; - Transform2D m; - m.elements[0][0]=t.basis.elements[0][0]; - m.elements[0][1]=t.basis.elements[1][0]; - m.elements[1][0]=t.basis.elements[0][1]; - m.elements[1][1]=t.basis.elements[1][1]; - m.elements[2][0]=t.origin[0]; - m.elements[2][1]=t.origin[1]; - return m; - } else - return Transform2D(); + if (type == TRANSFORM2D) { + return *_data._transform2d; + } else if (type == TRANSFORM) { + const Transform &t = *_data._transform; + Transform2D m; + m.elements[0][0] = t.basis.elements[0][0]; + m.elements[0][1] = t.basis.elements[1][0]; + m.elements[1][0] = t.basis.elements[0][1]; + m.elements[1][1] = t.basis.elements[1][1]; + m.elements[2][0] = t.origin[0]; + m.elements[2][1] = t.origin[1]; + return m; + } else + return Transform2D(); } - Variant::operator Color() const { - if (type==COLOR) - return *reinterpret_cast<const Color*>(_data._mem); - else if (type==STRING) - return Color::html( operator String() ); - else if (type==INT) - return Color::hex( operator int() ); + if (type == COLOR) + return *reinterpret_cast<const Color *>(_data._mem); + else if (type == STRING) + return Color::html(operator String()); + else if (type == INT) + return Color::hex(operator int()); else return Color(); } Variant::operator Image() const { - if (type==IMAGE) + if (type == IMAGE) return *_data._image; else return Image(); @@ -1801,18 +1769,17 @@ Variant::operator Image() const { Variant::operator NodePath() const { - if (type==NODE_PATH) - return *reinterpret_cast<const NodePath*>(_data._mem); - else if (type==STRING) + if (type == NODE_PATH) + return *reinterpret_cast<const NodePath *>(_data._mem); + else if (type == STRING) return NodePath(operator String()); else return NodePath(); } - Variant::operator RefPtr() const { - if (type==OBJECT) + if (type == OBJECT) return _get_obj().ref; else return RefPtr(); @@ -1820,14 +1787,14 @@ Variant::operator RefPtr() const { Variant::operator RID() const { - if (type==_RID) - return *reinterpret_cast<const RID*>(_data._mem); - else if (type==OBJECT && !_get_obj().ref.is_null()) { + if (type == _RID) + return *reinterpret_cast<const RID *>(_data._mem); + else if (type == OBJECT && !_get_obj().ref.is_null()) { return _get_obj().ref.get_rid(); - } else if (type==OBJECT && _get_obj().obj) { + } else if (type == OBJECT && _get_obj().obj) { Variant::CallError ce; - Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid,NULL,0,ce); - if (ce.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::_RID) { + Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid, NULL, 0, ce); + if (ce.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::_RID) { return ret; } return RID(); @@ -1836,72 +1803,87 @@ Variant::operator RID() const { } } -Variant::operator Object*() const { +Variant::operator Object *() const { - if (type==OBJECT) + if (type == OBJECT) return _get_obj().obj; else return NULL; } -Variant::operator Node*() const { +Variant::operator Node *() const { - if (type==OBJECT) - return _get_obj().obj?_get_obj().obj->cast_to<Node>():NULL; + if (type == OBJECT) + return _get_obj().obj ? _get_obj().obj->cast_to<Node>() : NULL; else return NULL; } -Variant::operator Control*() const { +Variant::operator Control *() const { - if (type==OBJECT) - return _get_obj().obj?_get_obj().obj->cast_to<Control>():NULL; + if (type == OBJECT) + return _get_obj().obj ? _get_obj().obj->cast_to<Control>() : NULL; else return NULL; } Variant::operator InputEvent() const { - if (type==INPUT_EVENT) - return *reinterpret_cast<const InputEvent*>(_data._input_event); + if (type == INPUT_EVENT) + return *reinterpret_cast<const InputEvent *>(_data._input_event); else return InputEvent(); } Variant::operator Dictionary() const { - if (type==DICTIONARY) - return *reinterpret_cast<const Dictionary*>(_data._mem); + if (type == DICTIONARY) + return *reinterpret_cast<const Dictionary *>(_data._mem); else return Dictionary(); } -template<class DA,class SA> -inline DA _convert_array(const SA& p_array) { +template <class DA, class SA> +inline DA _convert_array(const SA &p_array) { DA da; da.resize(p_array.size()); - for(int i=0;i<p_array.size();i++) { + for (int i = 0; i < p_array.size(); i++) { - da.set( i, Variant(p_array.get(i)) ); + da.set(i, Variant(p_array.get(i))); } return da; } -template<class DA> -inline DA _convert_array_from_variant(const Variant& p_variant) { - - switch(p_variant.get_type()) { +template <class DA> +inline DA _convert_array_from_variant(const Variant &p_variant) { + switch (p_variant.get_type()) { - case Variant::ARRAY: { return _convert_array<DA,Array >( p_variant.operator Array () ); } - case Variant::POOL_BYTE_ARRAY: { return _convert_array<DA,PoolVector<uint8_t> >( p_variant.operator PoolVector<uint8_t> () ); } - case Variant::POOL_INT_ARRAY: { return _convert_array<DA,PoolVector<int> >( p_variant.operator PoolVector<int> () ); } - case Variant::POOL_REAL_ARRAY: { return _convert_array<DA,PoolVector<real_t> >( p_variant.operator PoolVector<real_t> () ); } - case Variant::POOL_STRING_ARRAY: { return _convert_array<DA,PoolVector<String> >( p_variant.operator PoolVector<String> () ); } - case Variant::POOL_VECTOR2_ARRAY: { return _convert_array<DA,PoolVector<Vector2> >( p_variant.operator PoolVector<Vector2> () ); } - case Variant::POOL_VECTOR3_ARRAY: { return _convert_array<DA,PoolVector<Vector3> >( p_variant.operator PoolVector<Vector3> () ); } - case Variant::POOL_COLOR_ARRAY: { return _convert_array<DA,PoolVector<Color> >( p_variant.operator PoolVector<Color>() ); } + case Variant::ARRAY: { + return _convert_array<DA, Array>(p_variant.operator Array()); + } + case Variant::POOL_BYTE_ARRAY: { + return _convert_array<DA, PoolVector<uint8_t> >(p_variant.operator PoolVector<uint8_t>()); + } + case Variant::POOL_INT_ARRAY: { + return _convert_array<DA, PoolVector<int> >(p_variant.operator PoolVector<int>()); + } + case Variant::POOL_REAL_ARRAY: { + return _convert_array<DA, PoolVector<real_t> >(p_variant.operator PoolVector<real_t>()); + } + case Variant::POOL_STRING_ARRAY: { + return _convert_array<DA, PoolVector<String> >(p_variant.operator PoolVector<String>()); + } + case Variant::POOL_VECTOR2_ARRAY: { + return _convert_array<DA, PoolVector<Vector2> >(p_variant.operator PoolVector<Vector2>()); + } + case Variant::POOL_VECTOR3_ARRAY: { + return _convert_array<DA, PoolVector<Vector3> >(p_variant.operator PoolVector<Vector3>()); + } + case Variant::POOL_COLOR_ARRAY: { + return _convert_array<DA, PoolVector<Color> >(p_variant.operator PoolVector<Color>()); + } default: { return DA(); } } @@ -1910,278 +1892,265 @@ inline DA _convert_array_from_variant(const Variant& p_variant) { Variant::operator Array() const { - if (type==ARRAY) - return *reinterpret_cast<const Array*>(_data._mem); + if (type == ARRAY) + return *reinterpret_cast<const Array *>(_data._mem); else - return _convert_array_from_variant<Array >(*this); + return _convert_array_from_variant<Array>(*this); } Variant::operator PoolVector<uint8_t>() const { - if (type==POOL_BYTE_ARRAY) - return *reinterpret_cast<const PoolVector<uint8_t>* >(_data._mem); + if (type == POOL_BYTE_ARRAY) + return *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); else return _convert_array_from_variant<PoolVector<uint8_t> >(*this); } Variant::operator PoolVector<int>() const { - if (type==POOL_INT_ARRAY) - return *reinterpret_cast<const PoolVector<int>* >(_data._mem); + if (type == POOL_INT_ARRAY) + return *reinterpret_cast<const PoolVector<int> *>(_data._mem); else return _convert_array_from_variant<PoolVector<int> >(*this); - } Variant::operator PoolVector<real_t>() const { - if (type==POOL_REAL_ARRAY) - return *reinterpret_cast<const PoolVector<real_t>* >(_data._mem); + if (type == POOL_REAL_ARRAY) + return *reinterpret_cast<const PoolVector<real_t> *>(_data._mem); else return _convert_array_from_variant<PoolVector<real_t> >(*this); - } Variant::operator PoolVector<String>() const { - if (type==POOL_STRING_ARRAY) - return *reinterpret_cast<const PoolVector<String>* >(_data._mem); + if (type == POOL_STRING_ARRAY) + return *reinterpret_cast<const PoolVector<String> *>(_data._mem); else return _convert_array_from_variant<PoolVector<String> >(*this); - - } Variant::operator PoolVector<Vector3>() const { - if (type==POOL_VECTOR3_ARRAY) - return *reinterpret_cast<const PoolVector<Vector3>* >(_data._mem); + if (type == POOL_VECTOR3_ARRAY) + return *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); else return _convert_array_from_variant<PoolVector<Vector3> >(*this); - - } Variant::operator PoolVector<Vector2>() const { - if (type==POOL_VECTOR2_ARRAY) - return *reinterpret_cast<const PoolVector<Vector2>* >(_data._mem); + if (type == POOL_VECTOR2_ARRAY) + return *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); else return _convert_array_from_variant<PoolVector<Vector2> >(*this); - - } Variant::operator PoolVector<Color>() const { - if (type==POOL_COLOR_ARRAY) - return *reinterpret_cast<const PoolVector<Color>* >(_data._mem); + if (type == POOL_COLOR_ARRAY) + return *reinterpret_cast<const PoolVector<Color> *>(_data._mem); else return _convert_array_from_variant<PoolVector<Color> >(*this); - } /* helpers */ - Variant::operator Vector<RID>() const { - Array va= operator Array(); + Array va = operator Array(); Vector<RID> rids; rids.resize(va.size()); - for(int i=0;i<rids.size();i++) - rids[i]=va[i]; + for (int i = 0; i < rids.size(); i++) + rids[i] = va[i]; return rids; } Variant::operator Vector<Vector2>() const { - PoolVector<Vector2> from=operator PoolVector<Vector2>(); + PoolVector<Vector2> from = operator PoolVector<Vector2>(); Vector<Vector2> to; - int len=from.size(); - if (len==0) + int len = from.size(); + if (len == 0) return Vector<Vector2>(); to.resize(len); PoolVector<Vector2>::Read r = from.read(); Vector2 *w = &to[0]; - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - w[i]=r[i]; + w[i] = r[i]; } return to; } Variant::operator PoolVector<Plane>() const { - Array va= operator Array(); + Array va = operator Array(); PoolVector<Plane> planes; - int va_size=va.size(); - if (va_size==0) + int va_size = va.size(); + if (va_size == 0) return planes; planes.resize(va_size); PoolVector<Plane>::Write w = planes.write(); - for(int i=0;i<va_size;i++) - w[i]=va[i]; + for (int i = 0; i < va_size; i++) + w[i] = va[i]; return planes; } Variant::operator PoolVector<Face3>() const { - PoolVector<Vector3> va= operator PoolVector<Vector3>(); + PoolVector<Vector3> va = operator PoolVector<Vector3>(); PoolVector<Face3> faces; - int va_size=va.size(); - if (va_size==0) + int va_size = va.size(); + if (va_size == 0) return faces; - faces.resize(va_size/3); + faces.resize(va_size / 3); PoolVector<Face3>::Write w = faces.write(); PoolVector<Vector3>::Read r = va.read(); - for(int i=0;i<va_size;i++) - w[i/3].vertex[i%3]=r[i]; + for (int i = 0; i < va_size; i++) + w[i / 3].vertex[i % 3] = r[i]; return faces; } Variant::operator Vector<Plane>() const { - Array va= operator Array(); + Array va = operator Array(); Vector<Plane> planes; - int va_size=va.size(); - if (va_size==0) + int va_size = va.size(); + if (va_size == 0) return planes; planes.resize(va_size); - for(int i=0;i<va_size;i++) - planes[i]=va[i]; + for (int i = 0; i < va_size; i++) + planes[i] = va[i]; return planes; } Variant::operator Vector<Variant>() const { - Array from=operator Array(); + Array from = operator Array(); Vector<Variant> to; - int len=from.size(); + int len = from.size(); to.resize(len); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - to[i]=from[i]; + to[i] = from[i]; } return to; - } Variant::operator Vector<uint8_t>() const { - PoolVector<uint8_t> from=operator PoolVector<uint8_t>(); + PoolVector<uint8_t> from = operator PoolVector<uint8_t>(); Vector<uint8_t> to; - int len=from.size(); + int len = from.size(); to.resize(len); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - to[i]=from[i]; + to[i] = from[i]; } return to; } Variant::operator Vector<int>() const { - PoolVector<int> from=operator PoolVector<int>(); + PoolVector<int> from = operator PoolVector<int>(); Vector<int> to; - int len=from.size(); + int len = from.size(); to.resize(len); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - to[i]=from[i]; + to[i] = from[i]; } return to; } Variant::operator Vector<real_t>() const { - PoolVector<real_t> from=operator PoolVector<real_t>(); + PoolVector<real_t> from = operator PoolVector<real_t>(); Vector<real_t> to; - int len=from.size(); + int len = from.size(); to.resize(len); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - to[i]=from[i]; + to[i] = from[i]; } return to; } Variant::operator Vector<String>() const { - PoolVector<String> from=operator PoolVector<String>(); + PoolVector<String> from = operator PoolVector<String>(); Vector<String> to; - int len=from.size(); + int len = from.size(); to.resize(len); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - to[i]=from[i]; + to[i] = from[i]; } return to; - } Variant::operator Vector<Vector3>() const { - PoolVector<Vector3> from=operator PoolVector<Vector3>(); + PoolVector<Vector3> from = operator PoolVector<Vector3>(); Vector<Vector3> to; - int len=from.size(); - if (len==0) + int len = from.size(); + if (len == 0) return Vector<Vector3>(); to.resize(len); PoolVector<Vector3>::Read r = from.read(); Vector3 *w = &to[0]; - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - w[i]=r[i]; + w[i] = r[i]; } return to; - } Variant::operator Vector<Color>() const { - PoolVector<Color> from=operator PoolVector<Color>(); + PoolVector<Color> from = operator PoolVector<Color>(); Vector<Color> to; - int len=from.size(); - if (len==0) + int len = from.size(); + if (len == 0) return Vector<Color>(); to.resize(len); PoolVector<Color>::Read r = from.read(); Color *w = &to[0]; - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - w[i]=r[i]; + w[i] = r[i]; } return to; } Variant::operator Margin() const { - return (Margin)operator int(); + return (Margin) operator int(); } Variant::operator Orientation() const { - return (Orientation)operator int(); + return (Orientation) operator int(); } Variant::operator IP_Address() const { - if (type==POOL_REAL_ARRAY || type==POOL_INT_ARRAY || type==POOL_BYTE_ARRAY) { + if (type == POOL_REAL_ARRAY || type == POOL_INT_ARRAY || type == POOL_BYTE_ARRAY) { - PoolVector<int> addr=operator PoolVector<int>(); - if (addr.size()==4) { - return IP_Address(addr.get(0),addr.get(1),addr.get(2),addr.get(3)); + PoolVector<int> addr = operator PoolVector<int>(); + if (addr.size() == 4) { + return IP_Address(addr.get(0), addr.get(1), addr.get(2), addr.get(3)); } } - return IP_Address( operator String() ); + return IP_Address(operator String()); } Variant::Variant(bool p_bool) { - type=BOOL; - _data._bool=p_bool; + type = BOOL; + _data._bool = p_bool; } /* @@ -2194,358 +2163,314 @@ Variant::Variant(long unsigned int p_long) { Variant::Variant(signed int p_int) { - type=INT; - _data._int=p_int; - + type = INT; + _data._int = p_int; } Variant::Variant(unsigned int p_int) { - type=INT; - _data._int=p_int; - + type = INT; + _data._int = p_int; } #ifdef NEED_LONG_INT Variant::Variant(signed long p_int) { - type=INT; - _data._int=p_int; - + type = INT; + _data._int = p_int; } Variant::Variant(unsigned long p_int) { - type=INT; - _data._int=p_int; - + type = INT; + _data._int = p_int; } #endif Variant::Variant(int64_t p_int) { - type=INT; - _data._int=p_int; - + type = INT; + _data._int = p_int; } Variant::Variant(uint64_t p_int) { - type=INT; - _data._int=p_int; - + type = INT; + _data._int = p_int; } Variant::Variant(signed short p_short) { - type=INT; - _data._int=p_short; - + type = INT; + _data._int = p_short; } Variant::Variant(unsigned short p_short) { - type=INT; - _data._int=p_short; - + type = INT; + _data._int = p_short; } Variant::Variant(signed char p_char) { - type=INT; - _data._int=p_char; - + type = INT; + _data._int = p_char; } Variant::Variant(unsigned char p_char) { - type=INT; - _data._int=p_char; - + type = INT; + _data._int = p_char; } Variant::Variant(float p_float) { - type=REAL; - _data._real=p_float; - + type = REAL; + _data._real = p_float; } Variant::Variant(double p_double) { - type=REAL; - _data._real=p_double; + type = REAL; + _data._real = p_double; } -Variant::Variant(const StringName& p_string) { - - type=STRING; - memnew_placement( _data._mem, String( p_string.operator String() ) ); +Variant::Variant(const StringName &p_string) { + type = STRING; + memnew_placement(_data._mem, String(p_string.operator String())); } -Variant::Variant(const String& p_string) { - - type=STRING; - memnew_placement( _data._mem, String( p_string ) ); +Variant::Variant(const String &p_string) { + type = STRING; + memnew_placement(_data._mem, String(p_string)); } -Variant::Variant(const char * const p_cstring) { - - type=STRING; - memnew_placement( _data._mem, String( (const char*)p_cstring ) ); +Variant::Variant(const char *const p_cstring) { + type = STRING; + memnew_placement(_data._mem, String((const char *)p_cstring)); } -Variant::Variant(const CharType * p_wstring) { - - type=STRING; - memnew_placement( _data._mem, String( p_wstring ) ); +Variant::Variant(const CharType *p_wstring) { + type = STRING; + memnew_placement(_data._mem, String(p_wstring)); } -Variant::Variant(const Vector3& p_vector3) { - - type=VECTOR3; - memnew_placement( _data._mem, Vector3( p_vector3 ) ); +Variant::Variant(const Vector3 &p_vector3) { + type = VECTOR3; + memnew_placement(_data._mem, Vector3(p_vector3)); } -Variant::Variant(const Vector2& p_vector2) { - - type=VECTOR2; - memnew_placement( _data._mem, Vector2( p_vector2 ) ); +Variant::Variant(const Vector2 &p_vector2) { + type = VECTOR2; + memnew_placement(_data._mem, Vector2(p_vector2)); } -Variant::Variant(const Rect2& p_rect2) { - - type=RECT2; - memnew_placement( _data._mem, Rect2( p_rect2 ) ); +Variant::Variant(const Rect2 &p_rect2) { + type = RECT2; + memnew_placement(_data._mem, Rect2(p_rect2)); } -Variant::Variant(const Plane& p_plane) { - - type=PLANE; - memnew_placement( _data._mem, Plane( p_plane ) ); +Variant::Variant(const Plane &p_plane) { + type = PLANE; + memnew_placement(_data._mem, Plane(p_plane)); } -Variant::Variant(const Rect3& p_aabb) { +Variant::Variant(const Rect3 &p_aabb) { - type=RECT3; - _data._rect3 = memnew( Rect3( p_aabb ) ); + type = RECT3; + _data._rect3 = memnew(Rect3(p_aabb)); } -Variant::Variant(const Basis& p_matrix) { - - type=BASIS; - _data._basis= memnew( Basis( p_matrix ) ); +Variant::Variant(const Basis &p_matrix) { + type = BASIS; + _data._basis = memnew(Basis(p_matrix)); } -Variant::Variant(const Quat& p_quat) { - - type=QUAT; - memnew_placement( _data._mem, Quat( p_quat ) ); +Variant::Variant(const Quat &p_quat) { + type = QUAT; + memnew_placement(_data._mem, Quat(p_quat)); } -Variant::Variant(const Transform& p_transform) { - - type=TRANSFORM; - _data._transform = memnew( Transform( p_transform ) ); +Variant::Variant(const Transform &p_transform) { + type = TRANSFORM; + _data._transform = memnew(Transform(p_transform)); } -Variant::Variant(const Transform2D& p_transform) { - - type=TRANSFORM2D; - _data._transform2d = memnew( Transform2D( p_transform ) ); +Variant::Variant(const Transform2D &p_transform) { + type = TRANSFORM2D; + _data._transform2d = memnew(Transform2D(p_transform)); } -Variant::Variant(const Color& p_color) { - - type=COLOR; - memnew_placement( _data._mem, Color(p_color) ); +Variant::Variant(const Color &p_color) { + type = COLOR; + memnew_placement(_data._mem, Color(p_color)); } -Variant::Variant(const Image& p_image) { - - type=IMAGE; - _data._image=memnew( Image(p_image) ); +Variant::Variant(const Image &p_image) { + type = IMAGE; + _data._image = memnew(Image(p_image)); } -Variant::Variant(const NodePath& p_node_path) { - - type=NODE_PATH; - memnew_placement( _data._mem, NodePath(p_node_path) ); +Variant::Variant(const NodePath &p_node_path) { + type = NODE_PATH; + memnew_placement(_data._mem, NodePath(p_node_path)); } -Variant::Variant(const InputEvent& p_input_event) { - - type=INPUT_EVENT; - _data._input_event = memnew( InputEvent(p_input_event) ); +Variant::Variant(const InputEvent &p_input_event) { + type = INPUT_EVENT; + _data._input_event = memnew(InputEvent(p_input_event)); } -Variant::Variant(const RefPtr& p_resource) { +Variant::Variant(const RefPtr &p_resource) { - type=OBJECT; - memnew_placement( _data._mem, ObjData ); + type = OBJECT; + memnew_placement(_data._mem, ObjData); REF ref = p_resource; - _get_obj().obj=ref.ptr(); - _get_obj().ref=p_resource; - + _get_obj().obj = ref.ptr(); + _get_obj().ref = p_resource; } -Variant::Variant(const RID& p_rid) { - - type=_RID; - memnew_placement( _data._mem, RID(p_rid) ); +Variant::Variant(const RID &p_rid) { + type = _RID; + memnew_placement(_data._mem, RID(p_rid)); } -Variant::Variant(const Object* p_object) { +Variant::Variant(const Object *p_object) { - type=OBJECT; + type = OBJECT; - memnew_placement( _data._mem, ObjData ); - _get_obj().obj=const_cast<Object*>(p_object); + memnew_placement(_data._mem, ObjData); + _get_obj().obj = const_cast<Object *>(p_object); } -Variant::Variant(const Dictionary& p_dictionary) { - - type=DICTIONARY; - memnew_placement( _data._mem, (Dictionary)( p_dictionary) ); +Variant::Variant(const Dictionary &p_dictionary) { + type = DICTIONARY; + memnew_placement(_data._mem, (Dictionary)(p_dictionary)); } -Variant::Variant(const Array& p_array) { - - type=ARRAY; - memnew_placement( _data._mem, Array(p_array) ); +Variant::Variant(const Array &p_array) { + type = ARRAY; + memnew_placement(_data._mem, Array(p_array)); } -Variant::Variant(const PoolVector<Plane>& p_array) { +Variant::Variant(const PoolVector<Plane> &p_array) { + type = ARRAY; - type=ARRAY; + Array *plane_array = memnew_placement(_data._mem, Array); - Array *plane_array=memnew_placement( _data._mem, Array ); + plane_array->resize(p_array.size()); - plane_array->resize( p_array.size() ); + for (int i = 0; i < p_array.size(); i++) { - for (int i=0;i<p_array.size();i++) { - - plane_array->operator [](i)=Variant(p_array[i]); + plane_array->operator[](i) = Variant(p_array[i]); } } -Variant::Variant(const Vector<Plane>& p_array) { - +Variant::Variant(const Vector<Plane> &p_array) { - type=ARRAY; + type = ARRAY; - Array *plane_array=memnew_placement( _data._mem, Array ); + Array *plane_array = memnew_placement(_data._mem, Array); - plane_array->resize( p_array.size() ); + plane_array->resize(p_array.size()); - for (int i=0;i<p_array.size();i++) { + for (int i = 0; i < p_array.size(); i++) { - plane_array->operator [](i)=Variant(p_array[i]); + plane_array->operator[](i) = Variant(p_array[i]); } } -Variant::Variant(const Vector<RID>& p_array) { +Variant::Variant(const Vector<RID> &p_array) { + type = ARRAY; - type=ARRAY; + Array *rid_array = memnew_placement(_data._mem, Array); - Array *rid_array=memnew_placement( _data._mem, Array ); + rid_array->resize(p_array.size()); - rid_array->resize( p_array.size() ); + for (int i = 0; i < p_array.size(); i++) { - for (int i=0;i<p_array.size();i++) { - - rid_array->set(i,Variant(p_array[i])); + rid_array->set(i, Variant(p_array[i])); } } -Variant::Variant(const Vector<Vector2>& p_array) { - +Variant::Variant(const Vector<Vector2> &p_array) { - type=NIL; + type = NIL; PoolVector<Vector2> v; - int len=p_array.size(); - if (len>0) { + int len = p_array.size(); + if (len > 0) { v.resize(len); PoolVector<Vector2>::Write w = v.write(); const Vector2 *r = p_array.ptr(); - for (int i=0;i<len;i++) - w[i]=r[i]; + for (int i = 0; i < len; i++) + w[i] = r[i]; } - *this=v; + *this = v; } +Variant::Variant(const PoolVector<uint8_t> &p_raw_array) { -Variant::Variant(const PoolVector<uint8_t>& p_raw_array) { - - type=POOL_BYTE_ARRAY; - memnew_placement( _data._mem, PoolVector<uint8_t>(p_raw_array) ); - + type = POOL_BYTE_ARRAY; + memnew_placement(_data._mem, PoolVector<uint8_t>(p_raw_array)); } -Variant::Variant(const PoolVector<int>& p_int_array) { - - type=POOL_INT_ARRAY; - memnew_placement( _data._mem, PoolVector<int>(p_int_array) ); +Variant::Variant(const PoolVector<int> &p_int_array) { + type = POOL_INT_ARRAY; + memnew_placement(_data._mem, PoolVector<int>(p_int_array)); } -Variant::Variant(const PoolVector<real_t>& p_real_array) { - - type=POOL_REAL_ARRAY; - memnew_placement( _data._mem, PoolVector<real_t>(p_real_array) ); +Variant::Variant(const PoolVector<real_t> &p_real_array) { + type = POOL_REAL_ARRAY; + memnew_placement(_data._mem, PoolVector<real_t>(p_real_array)); } -Variant::Variant(const PoolVector<String>& p_string_array) { - - type=POOL_STRING_ARRAY; - memnew_placement( _data._mem, PoolVector<String>(p_string_array) ); +Variant::Variant(const PoolVector<String> &p_string_array) { + type = POOL_STRING_ARRAY; + memnew_placement(_data._mem, PoolVector<String>(p_string_array)); } -Variant::Variant(const PoolVector<Vector3>& p_vector3_array) { - - type=POOL_VECTOR3_ARRAY; - memnew_placement( _data._mem, PoolVector<Vector3>(p_vector3_array) ); +Variant::Variant(const PoolVector<Vector3> &p_vector3_array) { + type = POOL_VECTOR3_ARRAY; + memnew_placement(_data._mem, PoolVector<Vector3>(p_vector3_array)); } -Variant::Variant(const PoolVector<Vector2>& p_vector2_array) { - - type=POOL_VECTOR2_ARRAY; - memnew_placement( _data._mem, PoolVector<Vector2>(p_vector2_array) ); +Variant::Variant(const PoolVector<Vector2> &p_vector2_array) { + type = POOL_VECTOR2_ARRAY; + memnew_placement(_data._mem, PoolVector<Vector2>(p_vector2_array)); } -Variant::Variant(const PoolVector<Color>& p_color_array) { +Variant::Variant(const PoolVector<Color> &p_color_array) { - type=POOL_COLOR_ARRAY; - memnew_placement( _data._mem, PoolVector<Color>(p_color_array) ); + type = POOL_COLOR_ARRAY; + memnew_placement(_data._mem, PoolVector<Color>(p_color_array)); } -Variant::Variant(const PoolVector<Face3>& p_face_array) { - +Variant::Variant(const PoolVector<Face3> &p_face_array) { PoolVector<Vector3> vertices; - int face_count=p_face_array.size(); - vertices.resize(face_count*3); + int face_count = p_face_array.size(); + vertices.resize(face_count * 3); if (face_count) { PoolVector<Face3>::Read r = p_face_array.read(); PoolVector<Vector3>::Write w = vertices.write(); - for(int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - for(int j=0;j<3;j++) - w[i*3+j]=r[i].vertex[j]; + for (int j = 0; j < 3; j++) + w[i * 3 + j] = r[i].vertex[j]; } - r=PoolVector<Face3>::Read(); - w=PoolVector<Vector3>::Write(); - + r = PoolVector<Face3>::Read(); + w = PoolVector<Vector3>::Write(); } type = NIL; @@ -2555,107 +2480,105 @@ Variant::Variant(const PoolVector<Face3>& p_face_array) { /* helpers */ -Variant::Variant(const Vector<Variant>& p_array) { +Variant::Variant(const Vector<Variant> &p_array) { - type=NIL; + type = NIL; Array v; - int len=p_array.size(); + int len = p_array.size(); v.resize(len); - for (int i=0;i<len;i++) - v.set(i,p_array[i]); - *this=v; + for (int i = 0; i < len; i++) + v.set(i, p_array[i]); + *this = v; } -Variant::Variant(const Vector<uint8_t>& p_array) { +Variant::Variant(const Vector<uint8_t> &p_array) { - type=NIL; + type = NIL; PoolVector<uint8_t> v; - int len=p_array.size(); + int len = p_array.size(); v.resize(len); - for (int i=0;i<len;i++) - v.set(i,p_array[i]); - *this=v; + for (int i = 0; i < len; i++) + v.set(i, p_array[i]); + *this = v; } -Variant::Variant(const Vector<int>& p_array) { +Variant::Variant(const Vector<int> &p_array) { - type=NIL; + type = NIL; PoolVector<int> v; - int len=p_array.size(); + int len = p_array.size(); v.resize(len); - for (int i=0;i<len;i++) - v.set(i,p_array[i]); - *this=v; + for (int i = 0; i < len; i++) + v.set(i, p_array[i]); + *this = v; } -Variant::Variant(const Vector<real_t>& p_array) { +Variant::Variant(const Vector<real_t> &p_array) { - type=NIL; + type = NIL; PoolVector<real_t> v; - int len=p_array.size(); + int len = p_array.size(); v.resize(len); - for (int i=0;i<len;i++) - v.set(i,p_array[i]); - *this=v; + for (int i = 0; i < len; i++) + v.set(i, p_array[i]); + *this = v; } -Variant::Variant(const Vector<String>& p_array) { +Variant::Variant(const Vector<String> &p_array) { - type=NIL; + type = NIL; PoolVector<String> v; - int len=p_array.size(); + int len = p_array.size(); v.resize(len); - for (int i=0;i<len;i++) - v.set(i,p_array[i]); - *this=v; + for (int i = 0; i < len; i++) + v.set(i, p_array[i]); + *this = v; } -Variant::Variant(const Vector<Vector3>& p_array) { +Variant::Variant(const Vector<Vector3> &p_array) { - type=NIL; + type = NIL; PoolVector<Vector3> v; - int len=p_array.size(); - if (len>0) { + int len = p_array.size(); + if (len > 0) { v.resize(len); PoolVector<Vector3>::Write w = v.write(); const Vector3 *r = p_array.ptr(); - for (int i=0;i<len;i++) - w[i]=r[i]; + for (int i = 0; i < len; i++) + w[i] = r[i]; } - *this=v; + *this = v; } -Variant::Variant(const Vector<Color>& p_array) { +Variant::Variant(const Vector<Color> &p_array) { - type=NIL; + type = NIL; PoolVector<Color> v; - int len=p_array.size(); + int len = p_array.size(); v.resize(len); - for (int i=0;i<len;i++) - v.set(i,p_array[i]); - *this=v; + for (int i = 0; i < len; i++) + v.set(i, p_array[i]); + *this = v; } -void Variant::operator=(const Variant& p_variant) { +void Variant::operator=(const Variant &p_variant) { reference(p_variant); } -Variant::Variant(const IP_Address& p_address) { +Variant::Variant(const IP_Address &p_address) { - type=STRING; - memnew_placement( _data._mem, String( p_address ) ); + type = STRING; + memnew_placement(_data._mem, String(p_address)); } +Variant::Variant(const Variant &p_variant) { -Variant::Variant(const Variant& p_variant) { - - type=NIL; + type = NIL; reference(p_variant); } - /* Variant::~Variant() { @@ -2664,14 +2587,14 @@ Variant::~Variant() { uint32_t Variant::hash() const { - switch( type ) { + switch (type) { case NIL: { return 0; } break; case BOOL: { - return _data._bool?1:0; + return _data._bool ? 1 : 0; } break; case INT: { @@ -2683,29 +2606,29 @@ uint32_t Variant::hash() const { } break; case STRING: { - return reinterpret_cast<const String*>(_data._mem)->hash(); + return reinterpret_cast<const String *>(_data._mem)->hash(); } break; - // math types + // math types case VECTOR2: { - uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector2*>(_data._mem)->x); - return hash_djb2_one_float(reinterpret_cast<const Vector2*>(_data._mem)->y,hash); + uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->x); + return hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->y, hash); } break; case RECT2: { - uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->pos.x); - hash = hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->pos.y,hash); - hash = hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->size.x,hash); - return hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->size.y,hash); + uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->pos.x); + hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->pos.y, hash); + hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.x, hash); + return hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.y, hash); } break; case TRANSFORM2D: { uint32_t hash = 5831; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - for(int j=0;j<2;j++) { - hash = hash_djb2_one_float(_data._transform2d->elements[i][j],hash); + for (int j = 0; j < 2; j++) { + hash = hash_djb2_one_float(_data._transform2d->elements[i][j], hash); } } @@ -2713,19 +2636,19 @@ uint32_t Variant::hash() const { } break; case VECTOR3: { - uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector3*>(_data._mem)->x); - hash = hash_djb2_one_float(reinterpret_cast<const Vector3*>(_data._mem)->y,hash); - return hash_djb2_one_float(reinterpret_cast<const Vector3*>(_data._mem)->z,hash); + uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->x); + hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->y, hash); + return hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->z, hash); } break; case PLANE: { - uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->normal.x); - hash = hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->normal.y,hash); - hash = hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->normal.z,hash); - return hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->d,hash); + uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.x); + hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.y, hash); + hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.z, hash); + return hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->d, hash); } break; - /* + /* case QUAT: { @@ -2733,31 +2656,30 @@ uint32_t Variant::hash() const { case RECT3: { uint32_t hash = 5831; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - hash = hash_djb2_one_float(_data._rect3->pos[i],hash); - hash = hash_djb2_one_float(_data._rect3->size[i],hash); + hash = hash_djb2_one_float(_data._rect3->pos[i], hash); + hash = hash_djb2_one_float(_data._rect3->size[i], hash); } - return hash; } break; case QUAT: { - uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->x); - hash = hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->y,hash); - hash = hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->z,hash); - return hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->w,hash); + uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->x); + hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->y, hash); + hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->z, hash); + return hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->w, hash); } break; case BASIS: { uint32_t hash = 5831; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - for(int j=0;j<3;j++) { - hash = hash_djb2_one_float(_data._basis->elements[i][j],hash); + for (int j = 0; j < 3; j++) { + hash = hash_djb2_one_float(_data._basis->elements[i][j], hash); } } @@ -2767,26 +2689,25 @@ uint32_t Variant::hash() const { case TRANSFORM: { uint32_t hash = 5831; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - for(int j=0;j<3;j++) { - hash = hash_djb2_one_float(_data._transform->basis.elements[i][j],hash); + for (int j = 0; j < 3; j++) { + hash = hash_djb2_one_float(_data._transform->basis.elements[i][j], hash); } - hash = hash_djb2_one_float(_data._transform->origin[i],hash); + hash = hash_djb2_one_float(_data._transform->origin[i], hash); } - return hash; } break; - // misc types + // misc types case COLOR: { - uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->r); - hash = hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->g,hash); - hash = hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->b,hash); - return hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->a,hash); + uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->r); + hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->g, hash); + hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->b, hash); + return hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->a, hash); } break; case IMAGE: { @@ -2796,7 +2717,7 @@ uint32_t Variant::hash() const { } break; case _RID: { - return hash_djb2_one_64(reinterpret_cast<const RID*>(_data._mem)->get_id()); + return hash_djb2_one_64(reinterpret_cast<const RID *>(_data._mem)->get_id()); } break; case OBJECT: { @@ -2804,75 +2725,74 @@ uint32_t Variant::hash() const { } break; case NODE_PATH: { - return reinterpret_cast<const NodePath*>(_data._mem)->hash(); + return reinterpret_cast<const NodePath *>(_data._mem)->hash(); } break; case INPUT_EVENT: { - return hash_djb2_buffer((uint8_t*)_data._input_event,sizeof(InputEvent)); + return hash_djb2_buffer((uint8_t *)_data._input_event, sizeof(InputEvent)); } break; case DICTIONARY: { - return reinterpret_cast<const Dictionary*>(_data._mem)->hash(); - + return reinterpret_cast<const Dictionary *>(_data._mem)->hash(); } break; case ARRAY: { - const Array& arr = *reinterpret_cast<const Array* >(_data._mem); + const Array &arr = *reinterpret_cast<const Array *>(_data._mem); return arr.hash(); } break; case POOL_BYTE_ARRAY: { - const PoolVector<uint8_t>& arr = *reinterpret_cast<const PoolVector<uint8_t>* >(_data._mem); + const PoolVector<uint8_t> &arr = *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); int len = arr.size(); PoolVector<uint8_t>::Read r = arr.read(); - return hash_djb2_buffer((uint8_t*)&r[0],len); + return hash_djb2_buffer((uint8_t *)&r[0], len); } break; case POOL_INT_ARRAY: { - const PoolVector<int>& arr = *reinterpret_cast<const PoolVector<int>* >(_data._mem); + const PoolVector<int> &arr = *reinterpret_cast<const PoolVector<int> *>(_data._mem); int len = arr.size(); PoolVector<int>::Read r = arr.read(); - return hash_djb2_buffer((uint8_t*)&r[0],len*sizeof(int)); + return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(int)); } break; case POOL_REAL_ARRAY: { - const PoolVector<real_t>& arr = *reinterpret_cast<const PoolVector<real_t>* >(_data._mem); + const PoolVector<real_t> &arr = *reinterpret_cast<const PoolVector<real_t> *>(_data._mem); int len = arr.size(); PoolVector<real_t>::Read r = arr.read(); - return hash_djb2_buffer((uint8_t*)&r[0],len*sizeof(real_t)); + return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(real_t)); } break; case POOL_STRING_ARRAY: { - uint32_t hash=5831; - const PoolVector<String>& arr = *reinterpret_cast<const PoolVector<String>* >(_data._mem); + uint32_t hash = 5831; + const PoolVector<String> &arr = *reinterpret_cast<const PoolVector<String> *>(_data._mem); int len = arr.size(); PoolVector<String>::Read r = arr.read(); - for(int i=0;i<len;i++) { - hash = hash_djb2_one_32(r[i].hash(),hash); + for (int i = 0; i < len; i++) { + hash = hash_djb2_one_32(r[i].hash(), hash); } return hash; } break; case POOL_VECTOR2_ARRAY: { - uint32_t hash=5831; - const PoolVector<Vector2>& arr = *reinterpret_cast<const PoolVector<Vector2>* >(_data._mem); + uint32_t hash = 5831; + const PoolVector<Vector2> &arr = *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); int len = arr.size(); PoolVector<Vector2>::Read r = arr.read(); - for(int i=0;i<len;i++) { - hash = hash_djb2_one_float(r[i].x,hash); - hash = hash_djb2_one_float(r[i].y,hash); + for (int i = 0; i < len; i++) { + hash = hash_djb2_one_float(r[i].x, hash); + hash = hash_djb2_one_float(r[i].y, hash); } return hash; @@ -2880,15 +2800,15 @@ uint32_t Variant::hash() const { } break; case POOL_VECTOR3_ARRAY: { - uint32_t hash=5831; - const PoolVector<Vector3>& arr = *reinterpret_cast<const PoolVector<Vector3>* >(_data._mem); + uint32_t hash = 5831; + const PoolVector<Vector3> &arr = *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); int len = arr.size(); PoolVector<Vector3>::Read r = arr.read(); - for(int i=0;i<len;i++) { - hash = hash_djb2_one_float(r[i].x,hash); - hash = hash_djb2_one_float(r[i].y,hash); - hash = hash_djb2_one_float(r[i].z,hash); + for (int i = 0; i < len; i++) { + hash = hash_djb2_one_float(r[i].x, hash); + hash = hash_djb2_one_float(r[i].y, hash); + hash = hash_djb2_one_float(r[i].z, hash); } return hash; @@ -2896,100 +2816,98 @@ uint32_t Variant::hash() const { } break; case POOL_COLOR_ARRAY: { - uint32_t hash=5831; - const PoolVector<Color>& arr = *reinterpret_cast<const PoolVector<Color>* >(_data._mem); + uint32_t hash = 5831; + const PoolVector<Color> &arr = *reinterpret_cast<const PoolVector<Color> *>(_data._mem); int len = arr.size(); PoolVector<Color>::Read r = arr.read(); - for(int i=0;i<len;i++) { - hash = hash_djb2_one_float(r[i].r,hash); - hash = hash_djb2_one_float(r[i].g,hash); - hash = hash_djb2_one_float(r[i].b,hash); - hash = hash_djb2_one_float(r[i].a,hash); + for (int i = 0; i < len; i++) { + hash = hash_djb2_one_float(r[i].r, hash); + hash = hash_djb2_one_float(r[i].g, hash); + hash = hash_djb2_one_float(r[i].b, hash); + hash = hash_djb2_one_float(r[i].a, hash); } return hash; } break; default: {} - - } + } return 0; - } -#define hash_compare_scalar(p_lhs, p_rhs)\ +#define hash_compare_scalar(p_lhs, p_rhs) \ ((p_lhs) == (p_rhs)) || (Math::is_nan(p_lhs) == Math::is_nan(p_rhs)) -#define hash_compare_vector2(p_lhs, p_rhs)\ - (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ - (hash_compare_scalar((p_lhs).y, (p_rhs).y)) - -#define hash_compare_vector3(p_lhs, p_rhs)\ +#define hash_compare_vector2(p_lhs, p_rhs) \ (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ - (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \ - (hash_compare_scalar((p_lhs).z, (p_rhs).z)) - -#define hash_compare_quat(p_lhs, p_rhs)\ - (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ - (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \ - (hash_compare_scalar((p_lhs).z, (p_rhs).z)) && \ - (hash_compare_scalar((p_lhs).w, (p_rhs).w)) - -#define hash_compare_color(p_lhs, p_rhs)\ - (hash_compare_scalar((p_lhs).r, (p_rhs).r)) && \ - (hash_compare_scalar((p_lhs).g, (p_rhs).g)) && \ - (hash_compare_scalar((p_lhs).b, (p_rhs).b)) && \ - (hash_compare_scalar((p_lhs).a, (p_rhs).a)) - -#define hash_compare_pool_array(p_lhs, p_rhs, p_type, p_compare_func)\ - const PoolVector<p_type>& l = *reinterpret_cast<const PoolVector<p_type>*>(p_lhs);\ - const PoolVector<p_type>& r = *reinterpret_cast<const PoolVector<p_type>*>(p_rhs);\ - \ - if(l.size() != r.size()) \ - return false; \ - \ - PoolVector<p_type>::Read lr = l.read(); \ - PoolVector<p_type>::Read rr = r.read(); \ - \ - for(int i = 0; i < l.size(); ++i) { \ - if(! p_compare_func((lr[i]), (rr[i]))) \ - return false; \ - }\ - \ - return true - -bool Variant::hash_compare(const Variant& p_variant) const { + (hash_compare_scalar((p_lhs).y, (p_rhs).y)) + +#define hash_compare_vector3(p_lhs, p_rhs) \ + (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ + (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \ + (hash_compare_scalar((p_lhs).z, (p_rhs).z)) + +#define hash_compare_quat(p_lhs, p_rhs) \ + (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ + (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \ + (hash_compare_scalar((p_lhs).z, (p_rhs).z)) && \ + (hash_compare_scalar((p_lhs).w, (p_rhs).w)) + +#define hash_compare_color(p_lhs, p_rhs) \ + (hash_compare_scalar((p_lhs).r, (p_rhs).r)) && \ + (hash_compare_scalar((p_lhs).g, (p_rhs).g)) && \ + (hash_compare_scalar((p_lhs).b, (p_rhs).b)) && \ + (hash_compare_scalar((p_lhs).a, (p_rhs).a)) + +#define hash_compare_pool_array(p_lhs, p_rhs, p_type, p_compare_func) \ + const PoolVector<p_type> &l = *reinterpret_cast<const PoolVector<p_type> *>(p_lhs); \ + const PoolVector<p_type> &r = *reinterpret_cast<const PoolVector<p_type> *>(p_rhs); \ + \ + if (l.size() != r.size()) \ + return false; \ + \ + PoolVector<p_type>::Read lr = l.read(); \ + PoolVector<p_type>::Read rr = r.read(); \ + \ + for (int i = 0; i < l.size(); ++i) { \ + if (!p_compare_func((lr[i]), (rr[i]))) \ + return false; \ + } \ + \ + return true + +bool Variant::hash_compare(const Variant &p_variant) const { if (type != p_variant.type) return false; - switch( type ) { + switch (type) { case REAL: { return hash_compare_scalar(_data._real, p_variant._data._real); } break; case VECTOR2: { - const Vector2* l = reinterpret_cast<const Vector2*>(_data._mem); - const Vector2* r = reinterpret_cast<const Vector2*>(p_variant._data._mem); + const Vector2 *l = reinterpret_cast<const Vector2 *>(_data._mem); + const Vector2 *r = reinterpret_cast<const Vector2 *>(p_variant._data._mem); return hash_compare_vector2(*l, *r); } break; case RECT2: { - const Rect2* l = reinterpret_cast<const Rect2*>(_data._mem); - const Rect2* r = reinterpret_cast<const Rect2*>(p_variant._data._mem); + const Rect2 *l = reinterpret_cast<const Rect2 *>(_data._mem); + const Rect2 *r = reinterpret_cast<const Rect2 *>(p_variant._data._mem); return (hash_compare_vector2(l->pos, r->pos)) && - (hash_compare_vector2(l->size, r->size)); + (hash_compare_vector2(l->size, r->size)); } break; case TRANSFORM2D: { - Transform2D* l = _data._transform2d; - Transform2D* r = p_variant._data._transform2d; + Transform2D *l = _data._transform2d; + Transform2D *r = p_variant._data._transform2d; - for(int i=0;i<3;i++) { - if (! (hash_compare_vector2(l->elements[i], r->elements[i]))) + for (int i = 0; i < 3; i++) { + if (!(hash_compare_vector2(l->elements[i], r->elements[i]))) return false; } @@ -2997,23 +2915,23 @@ bool Variant::hash_compare(const Variant& p_variant) const { } break; case VECTOR3: { - const Vector3* l = reinterpret_cast<const Vector3*>(_data._mem); - const Vector3* r = reinterpret_cast<const Vector3*>(p_variant._data._mem); + const Vector3 *l = reinterpret_cast<const Vector3 *>(_data._mem); + const Vector3 *r = reinterpret_cast<const Vector3 *>(p_variant._data._mem); return hash_compare_vector3(*l, *r); } break; case PLANE: { - const Plane* l = reinterpret_cast<const Plane*>(_data._mem); - const Plane* r = reinterpret_cast<const Plane*>(p_variant._data._mem); + const Plane *l = reinterpret_cast<const Plane *>(_data._mem); + const Plane *r = reinterpret_cast<const Plane *>(p_variant._data._mem); return (hash_compare_vector3(l->normal, r->normal)) && - (hash_compare_scalar(l->d, r->d)); + (hash_compare_scalar(l->d, r->d)); } break; case RECT3: { - const Rect3* l = _data._rect3; - const Rect3* r = p_variant._data._rect3; + const Rect3 *l = _data._rect3; + const Rect3 *r = p_variant._data._rect3; return (hash_compare_vector3(l->pos, r->pos) && (hash_compare_vector3(l->size, r->size))); @@ -3021,18 +2939,18 @@ bool Variant::hash_compare(const Variant& p_variant) const { } break; case QUAT: { - const Quat* l = reinterpret_cast<const Quat*>(_data._mem); - const Quat* r = reinterpret_cast<const Quat*>(p_variant._data._mem); + const Quat *l = reinterpret_cast<const Quat *>(_data._mem); + const Quat *r = reinterpret_cast<const Quat *>(p_variant._data._mem); return hash_compare_quat(*l, *r); } break; case BASIS: { - const Basis* l = _data._basis; - const Basis* r = p_variant._data._basis; + const Basis *l = _data._basis; + const Basis *r = p_variant._data._basis; - for(int i=0;i<3;i++) { - if (! (hash_compare_vector3(l->elements[i], r->elements[i]))) + for (int i = 0; i < 3; i++) { + if (!(hash_compare_vector3(l->elements[i], r->elements[i]))) return false; } @@ -3040,11 +2958,11 @@ bool Variant::hash_compare(const Variant& p_variant) const { } break; case TRANSFORM: { - const Transform* l = _data._transform; - const Transform* r = p_variant._data._transform; + const Transform *l = _data._transform; + const Transform *r = p_variant._data._transform; - for(int i=0;i<3;i++) { - if (! (hash_compare_vector3(l->basis.elements[i], r->basis.elements[i]))) + for (int i = 0; i < 3; i++) { + if (!(hash_compare_vector3(l->basis.elements[i], r->basis.elements[i]))) return false; } @@ -3052,21 +2970,21 @@ bool Variant::hash_compare(const Variant& p_variant) const { } break; case COLOR: { - const Color* l = reinterpret_cast<const Color*>(_data._mem); - const Color* r = reinterpret_cast<const Color*>(p_variant._data._mem); + const Color *l = reinterpret_cast<const Color *>(_data._mem); + const Color *r = reinterpret_cast<const Color *>(p_variant._data._mem); return hash_compare_color(*l, *r); } break; case ARRAY: { - const Array& l = *(reinterpret_cast<const Array*>(_data._mem)); - const Array& r = *(reinterpret_cast<const Array*>(p_variant._data._mem)); + const Array &l = *(reinterpret_cast<const Array *>(_data._mem)); + const Array &r = *(reinterpret_cast<const Array *>(p_variant._data._mem)); - if(l.size() != r.size()) + if (l.size() != r.size()) return false; - for(int i = 0; i < l.size(); ++i) { - if(! l[i].hash_compare(r[i])) + for (int i = 0; i < l.size(); ++i) { + if (!l[i].hash_compare(r[i])) return false; } @@ -3092,39 +3010,37 @@ bool Variant::hash_compare(const Variant& p_variant) const { default: bool v; Variant r; - evaluate(OP_EQUAL,*this,p_variant,r,v); + evaluate(OP_EQUAL, *this, p_variant, r, v); return r; - } + } return false; } - bool Variant::is_ref() const { - return type==OBJECT && !_get_obj().ref.is_null(); + return type == OBJECT && !_get_obj().ref.is_null(); } - Vector<Variant> varray() { return Vector<Variant>(); } -Vector<Variant> varray(const Variant& p_arg1) { +Vector<Variant> varray(const Variant &p_arg1) { Vector<Variant> v; v.push_back(p_arg1); return v; } -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2) { +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2) { Vector<Variant> v; v.push_back(p_arg1); v.push_back(p_arg2); return v; } -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3) { +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3) { Vector<Variant> v; v.push_back(p_arg1); @@ -3132,7 +3048,7 @@ Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant v.push_back(p_arg3); return v; } -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4) { +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4) { Vector<Variant> v; v.push_back(p_arg1); @@ -3142,7 +3058,7 @@ Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant return v; } -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4,const Variant& p_arg5) { +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5) { Vector<Variant> v; v.push_back(p_arg1); @@ -3151,57 +3067,53 @@ Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant v.push_back(p_arg4); v.push_back(p_arg5); return v; - } -void Variant::static_assign(const Variant& p_variant) { - - +void Variant::static_assign(const Variant &p_variant) { } bool Variant::is_shared() const { - switch(type) { - - case OBJECT: return true; - case ARRAY: return true; - case DICTIONARY: return true; - default: {} + switch (type) { - } + case OBJECT: return true; + case ARRAY: return true; + case DICTIONARY: return true; + default: {} + } - return false; + return false; } -Variant Variant::call(const StringName& p_method,VARIANT_ARG_DECLARE) { +Variant Variant::call(const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;i<VARIANT_ARG_MAX;i++) { - if (argptr[i]->get_type()==Variant::NIL) + int argc = 0; + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + if (argptr[i]->get_type() == Variant::NIL) break; argc++; } CallError error; - Variant ret = call(p_method,argptr,argc,error); + Variant ret = call(p_method, argptr, argc, error); - switch(error.error) { + switch (error.error) { case CallError::CALL_ERROR_INVALID_ARGUMENT: { - String err = "Invalid type for argument #"+itos(error.argument)+", expected '"+Variant::get_type_name(error.expected)+"'."; + String err = "Invalid type for argument #" + itos(error.argument) + ", expected '" + Variant::get_type_name(error.expected) + "'."; ERR_PRINT(err.utf8().get_data()); } break; case CallError::CALL_ERROR_INVALID_METHOD: { - String err = "Invalid method '"+p_method+"' for type '"+Variant::get_type_name(type)+"'."; + String err = "Invalid method '" + p_method + "' for type '" + Variant::get_type_name(type) + "'."; ERR_PRINT(err.utf8().get_data()); } break; case CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { - String err = "Too many arguments for method '"+p_method+"'"; + String err = "Too many arguments for method '" + p_method + "'"; ERR_PRINT(err.utf8().get_data()); } break; default: {} @@ -3210,38 +3122,35 @@ Variant Variant::call(const StringName& p_method,VARIANT_ARG_DECLARE) { return ret; } -void Variant::construct_from_string(const String& p_string,Variant& r_value,ObjectConstruct p_obj_construct,void *p_construct_ud) { +void Variant::construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct, void *p_construct_ud) { - r_value=Variant(); + r_value = Variant(); } - String Variant::get_construct_string() const { String vars; - VariantWriter::write_to_string(*this,vars); + VariantWriter::write_to_string(*this, vars); return vars; - } -String Variant::get_call_error_text(Object* p_base, const StringName& p_method,const Variant** p_argptrs,int p_argcount,const Variant::CallError &ce) { - +String Variant::get_call_error_text(Object *p_base, const StringName &p_method, const Variant **p_argptrs, int p_argcount, const Variant::CallError &ce) { String err_text; - if (ce.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { - int errorarg=ce.argument; - err_text="Cannot convert argument "+itos(errorarg+1)+" from "+Variant::get_type_name(p_argptrs[errorarg]->get_type())+" to "+Variant::get_type_name(ce.expected)+"."; - } else if (ce.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { - err_text="Method expected "+itos(ce.argument)+" arguments, but called with "+itos(p_argcount)+"."; - } else if (ce.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { - err_text="Method expected "+itos(ce.argument)+" arguments, but called with "+itos(p_argcount)+"."; - } else if (ce.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) { - err_text="Method not found."; - } else if (ce.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { - err_text="Instance is null"; - } else if (ce.error==Variant::CallError::CALL_OK){ + if (ce.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { + int errorarg = ce.argument; + err_text = "Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(p_argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(ce.expected) + "."; + } else if (ce.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { + err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + "."; + } else if (ce.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { + err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + "."; + } else if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { + err_text = "Method not found."; + } else if (ce.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { + err_text = "Instance is null"; + } else if (ce.error == Variant::CallError::CALL_OK) { return "Call OK"; } @@ -3249,51 +3158,43 @@ String Variant::get_call_error_text(Object* p_base, const StringName& p_method,c Ref<Script> script = p_base->get_script(); if (script.is_valid() && script->get_path().is_resource_file()) { - class_name+="("+script->get_path().get_file()+")"; + class_name += "(" + script->get_path().get_file() + ")"; } - return "'"+class_name+"::"+String(p_method)+"': "+err_text; + return "'" + class_name + "::" + String(p_method) + "': " + err_text; } - -String vformat(const String& p_text, const Variant& p1,const Variant& p2,const Variant& p3,const Variant& p4,const Variant& p5) { +String vformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) { Array args; - if (p1.get_type()!=Variant::NIL) { + if (p1.get_type() != Variant::NIL) { args.push_back(p1); - if (p2.get_type()!=Variant::NIL) { + if (p2.get_type() != Variant::NIL) { args.push_back(p2); - if (p3.get_type()!=Variant::NIL) { + if (p3.get_type() != Variant::NIL) { args.push_back(p3); - if (p4.get_type()!=Variant::NIL) { + if (p4.get_type() != Variant::NIL) { args.push_back(p4); - if (p5.get_type()!=Variant::NIL) { + if (p5.get_type() != Variant::NIL) { args.push_back(p5); - } - } - - } - } - } - bool error=false; - String fmt = p_text.sprintf(args,&error); + bool error = false; + String fmt = p_text.sprintf(args, &error); - ERR_FAIL_COND_V(error,String()); + ERR_FAIL_COND_V(error, String()); return fmt; - } diff --git a/core/variant.h b/core/variant.h index f0c0d65852..c9f7ada3ac 100644 --- a/core/variant.h +++ b/core/variant.h @@ -33,27 +33,27 @@ @author Juan Linietsky <reduzio@gmail.com> */ -#include "rect3.h" -#include "ustring.h" -#include "vector3.h" -#include "plane.h" -#include "quat.h" -#include "matrix3.h" -#include "transform.h" -#include "image.h" +#include "array.h" +#include "color.h" +#include "dictionary.h" #include "dvector.h" -#include "path_db.h" -#include "simple_type.h" +#include "face3.h" +#include "image.h" +#include "io/ip_address.h" +#include "math_2d.h" +#include "matrix3.h" #include "os/input_event.h" #include "os/power.h" -#include "color.h" -#include "face3.h" +#include "path_db.h" +#include "plane.h" +#include "quat.h" +#include "rect3.h" #include "ref_ptr.h" -#include "math_2d.h" #include "rid.h" -#include "io/ip_address.h" -#include "dictionary.h" -#include "array.h" +#include "simple_type.h" +#include "transform.h" +#include "ustring.h" +#include "vector3.h" class RefPtr; class Object; @@ -63,7 +63,6 @@ class Control; // helper struct PropertyInfo; struct MethodInfo; - typedef PoolVector<uint8_t> PoolByteArray; typedef PoolVector<int> PoolIntArray; typedef PoolVector<real_t> PoolRealArray; @@ -74,7 +73,6 @@ typedef PoolVector<Color> PoolColorArray; class Variant { public: - enum Type { NIL, @@ -87,31 +85,31 @@ public: // math types - VECTOR2, // 5 + VECTOR2, // 5 RECT2, VECTOR3, TRANSFORM2D, PLANE, - QUAT, // 10 + QUAT, // 10 RECT3, //sorry naming convention fail :( not like it's used often BASIS, TRANSFORM, // misc types COLOR, - IMAGE, // 15 + IMAGE, // 15 NODE_PATH, _RID, OBJECT, INPUT_EVENT, - DICTIONARY, // 20 + DICTIONARY, // 20 ARRAY, // arrays POOL_BYTE_ARRAY, POOL_INT_ARRAY, POOL_REAL_ARRAY, - POOL_STRING_ARRAY, // 25 + POOL_STRING_ARRAY, // 25 POOL_VECTOR2_ARRAY, POOL_VECTOR3_ARRAY, POOL_COLOR_ARRAY, @@ -121,8 +119,6 @@ public: }; private: - - friend class _VariantCall; // Variant takes 20 bytes when real_t is float, and 36 if double // it only allocates extra memory for aabb/matrix. @@ -135,9 +131,8 @@ private: RefPtr ref; }; - - _FORCE_INLINE_ ObjData& _get_obj(); - _FORCE_INLINE_ const ObjData& _get_obj() const; + _FORCE_INLINE_ ObjData &_get_obj(); + _FORCE_INLINE_ const ObjData &_get_obj() const; union { @@ -145,29 +140,26 @@ private: int64_t _int; double _real; Transform2D *_transform2d; - Rect3* _rect3; + Rect3 *_rect3; Basis *_basis; Transform *_transform; RefPtr *_resource; InputEvent *_input_event; Image *_image; void *_ptr; //generic pointer - uint8_t _mem[sizeof(ObjData) > (sizeof(real_t)*4) ? sizeof(ObjData) : (sizeof(real_t)*4)]; + uint8_t _mem[sizeof(ObjData) > (sizeof(real_t) * 4) ? sizeof(ObjData) : (sizeof(real_t) * 4)]; } _data; - - void reference(const Variant& p_variant); + void reference(const Variant &p_variant); void clear(); -public: +public: _FORCE_INLINE_ Type get_type() const { return type; } static String get_type_name(Variant::Type p_type); static bool can_convert(Type p_type_from, Type p_type_to); static bool can_convert_strict(Type p_type_from, Type p_type_to); - - - template<class T> + template <class T> static Type get_type_for() { GetSimpleType<T> t; @@ -176,10 +168,9 @@ public: return r; } - bool is_ref() const; - _FORCE_INLINE_ bool is_num() const { return type==INT || type==REAL; }; - _FORCE_INLINE_ bool is_array() const { return type>=ARRAY; }; + _FORCE_INLINE_ bool is_num() const { return type == INT || type == REAL; }; + _FORCE_INLINE_ bool is_array() const { return type >= ARRAY; }; bool is_shared() const; bool is_zero() const; bool is_one() const; @@ -199,7 +190,6 @@ public: operator unsigned long() const; #endif - operator CharType() const; operator float() const; operator double() const; @@ -221,9 +211,9 @@ public: operator RefPtr() const; operator RID() const; operator InputEvent() const; - operator Object*() const; - operator Node*() const; - operator Control*() const; + operator Object *() const; + operator Node *() const; + operator Control *() const; operator Dictionary() const; operator Array() const; @@ -237,7 +227,6 @@ public: operator PoolVector<Plane>() const; operator PoolVector<Face3>() const; - operator Vector<Variant>() const; operator Vector<uint8_t>() const; operator Vector<int>() const; @@ -256,14 +245,13 @@ public: operator IP_Address() const; - Variant(bool p_bool); Variant(signed int p_int); // real one Variant(unsigned int p_int); #ifdef NEED_LONG_INT Variant(signed long p_long); // real one Variant(unsigned long p_long); - //Variant(long unsigned int p_long); +//Variant(long unsigned int p_long); #endif Variant(signed short p_short); // real one Variant(unsigned short p_short); @@ -273,54 +261,51 @@ public: Variant(uint64_t p_char); Variant(float p_float); Variant(double p_double); - Variant(const String& p_string); - Variant(const StringName& p_string); - Variant(const char * const p_cstring); - Variant(const CharType * p_wstring); - Variant(const Vector2& p_vector2); - Variant(const Rect2& p_rect2); - Variant(const Vector3& p_vector3); - Variant(const Plane& p_plane); - Variant(const Rect3& p_aabb); - Variant(const Quat& p_quat); - Variant(const Basis& p_transform); - Variant(const Transform2D& p_transform); - Variant(const Transform& p_transform); - Variant(const Color& p_color); - Variant(const Image& p_image); - Variant(const NodePath& p_path); - Variant(const RefPtr& p_resource); - Variant(const RID& p_rid); - Variant(const Object* p_object); - Variant(const InputEvent& p_input_event); - Variant(const Dictionary& p_dictionary); - - Variant(const Array& p_array); - Variant(const PoolVector<Plane>& p_array); // helper - Variant(const PoolVector<uint8_t>& p_raw_array); - Variant(const PoolVector<int>& p_int_array); - Variant(const PoolVector<real_t>& p_real_array); - Variant(const PoolVector<String>& p_string_array); - Variant(const PoolVector<Vector3>& p_vector3_array); - Variant(const PoolVector<Color>& p_color_array); - Variant(const PoolVector<Face3>& p_face_array); - - - Variant(const Vector<Variant>& p_array); - Variant(const Vector<uint8_t>& p_raw_array); - Variant(const Vector<int>& p_int_array); - Variant(const Vector<real_t>& p_real_array); - Variant(const Vector<String>& p_string_array); - Variant(const Vector<Vector3>& p_vector3_array); - Variant(const Vector<Color>& p_color_array); - Variant(const Vector<Plane>& p_array); // helper - Variant(const Vector<RID>& p_array); // helper - Variant(const Vector<Vector2>& p_array); // helper - Variant(const PoolVector<Vector2>& p_array); // helper - - Variant(const IP_Address& p_address); - - + Variant(const String &p_string); + Variant(const StringName &p_string); + Variant(const char *const p_cstring); + Variant(const CharType *p_wstring); + Variant(const Vector2 &p_vector2); + Variant(const Rect2 &p_rect2); + Variant(const Vector3 &p_vector3); + Variant(const Plane &p_plane); + Variant(const Rect3 &p_aabb); + Variant(const Quat &p_quat); + Variant(const Basis &p_transform); + Variant(const Transform2D &p_transform); + Variant(const Transform &p_transform); + Variant(const Color &p_color); + Variant(const Image &p_image); + Variant(const NodePath &p_path); + Variant(const RefPtr &p_resource); + Variant(const RID &p_rid); + Variant(const Object *p_object); + Variant(const InputEvent &p_input_event); + Variant(const Dictionary &p_dictionary); + + Variant(const Array &p_array); + Variant(const PoolVector<Plane> &p_array); // helper + Variant(const PoolVector<uint8_t> &p_raw_array); + Variant(const PoolVector<int> &p_int_array); + Variant(const PoolVector<real_t> &p_real_array); + Variant(const PoolVector<String> &p_string_array); + Variant(const PoolVector<Vector3> &p_vector3_array); + Variant(const PoolVector<Color> &p_color_array); + Variant(const PoolVector<Face3> &p_face_array); + + Variant(const Vector<Variant> &p_array); + Variant(const Vector<uint8_t> &p_raw_array); + Variant(const Vector<int> &p_int_array); + Variant(const Vector<real_t> &p_real_array); + Variant(const Vector<String> &p_string_array); + Variant(const Vector<Vector3> &p_vector3_array); + Variant(const Vector<Color> &p_color_array); + Variant(const Vector<Plane> &p_array); // helper + Variant(const Vector<RID> &p_array); // helper + Variant(const Vector<Vector2> &p_array); // helper + Variant(const PoolVector<Vector2> &p_array); // helper + + Variant(const IP_Address &p_address); enum Operator { @@ -358,20 +343,19 @@ public: }; - static String get_operator_name(Operator p_op); - static void evaluate(const Operator& p_op,const Variant& p_a, const Variant& p_b,Variant &r_ret,bool &r_valid); - static _FORCE_INLINE_ Variant evaluate(const Operator& p_op,const Variant& p_a, const Variant& p_b) { + static void evaluate(const Operator &p_op, const Variant &p_a, const Variant &p_b, Variant &r_ret, bool &r_valid); + static _FORCE_INLINE_ Variant evaluate(const Operator &p_op, const Variant &p_a, const Variant &p_b) { - bool valid=true; + bool valid = true; Variant res; - evaluate(p_op,p_a,p_b,res,valid); + evaluate(p_op, p_a, p_b, res, valid); return res; } void zero(); - static void blend(const Variant& a, const Variant& b, float c,Variant &r_dst); - static void interpolate(const Variant& a, const Variant& b, float c,Variant &r_dst); + static void blend(const Variant &a, const Variant &b, float c, Variant &r_dst); + static void interpolate(const Variant &a, const Variant &b, float c, Variant &r_dst); struct CallError { enum Error { @@ -387,95 +371,93 @@ public: Type expected; }; - void call_ptr(const StringName& p_method,const Variant** p_args,int p_argcount,Variant* r_ret,CallError &r_error); - Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,CallError &r_error); - Variant call(const StringName& p_method,const Variant& p_arg1=Variant(),const Variant& p_arg2=Variant(),const Variant& p_arg3=Variant(),const Variant& p_arg4=Variant(),const Variant& p_arg5=Variant()); + void call_ptr(const StringName &p_method, const Variant **p_args, int p_argcount, Variant *r_ret, CallError &r_error); + Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, CallError &r_error); + Variant call(const StringName &p_method, const Variant &p_arg1 = Variant(), const Variant &p_arg2 = Variant(), const Variant &p_arg3 = Variant(), const Variant &p_arg4 = Variant(), const Variant &p_arg5 = Variant()); - static String get_call_error_text(Object* p_base, const StringName& p_method,const Variant** p_argptrs,int p_argcount,const Variant::CallError &ce); + static String get_call_error_text(Object *p_base, const StringName &p_method, const Variant **p_argptrs, int p_argcount, const Variant::CallError &ce); - static Variant construct(const Variant::Type,const Variant** p_args,int p_argcount,CallError &r_error,bool p_strict=true); + static Variant construct(const Variant::Type, const Variant **p_args, int p_argcount, CallError &r_error, bool p_strict = true); void get_method_list(List<MethodInfo> *p_list) const; - bool has_method(const StringName& p_method) const; - static Vector<Variant::Type> get_method_argument_types(Variant::Type p_type,const StringName& p_method); - static Vector<Variant> get_method_default_arguments(Variant::Type p_type,const StringName& p_method); - static Variant::Type get_method_return_type(Variant::Type p_type,const StringName& p_method,bool* r_has_return=NULL); - static Vector<StringName> get_method_argument_names(Variant::Type p_type,const StringName& p_method); + bool has_method(const StringName &p_method) const; + static Vector<Variant::Type> get_method_argument_types(Variant::Type p_type, const StringName &p_method); + static Vector<Variant> get_method_default_arguments(Variant::Type p_type, const StringName &p_method); + static Variant::Type get_method_return_type(Variant::Type p_type, const StringName &p_method, bool *r_has_return = NULL); + static Vector<StringName> get_method_argument_names(Variant::Type p_type, const StringName &p_method); - void set_named(const StringName& p_index, const Variant& p_value, bool *r_valid=NULL); - Variant get_named(const StringName& p_index, bool *r_valid=NULL) const; + void set_named(const StringName &p_index, const Variant &p_value, bool *r_valid = NULL); + Variant get_named(const StringName &p_index, bool *r_valid = NULL) const; - void set(const Variant& p_index, const Variant& p_value, bool *r_valid=NULL); - Variant get(const Variant& p_index, bool *r_valid=NULL) const; - bool in(const Variant& p_index, bool *r_valid=NULL) const; + void set(const Variant &p_index, const Variant &p_value, bool *r_valid = NULL); + Variant get(const Variant &p_index, bool *r_valid = NULL) const; + bool in(const Variant &p_index, bool *r_valid = NULL) const; - bool iter_init(Variant& r_iter,bool &r_valid) const; - bool iter_next(Variant& r_iter,bool &r_valid) const; - Variant iter_get(const Variant& r_iter,bool &r_valid) const; + bool iter_init(Variant &r_iter, bool &r_valid) const; + bool iter_next(Variant &r_iter, bool &r_valid) const; + Variant iter_get(const Variant &r_iter, bool &r_valid) const; void get_property_list(List<PropertyInfo> *p_list) const; //argsVariant call() - bool operator==(const Variant& p_variant) const; - bool operator!=(const Variant& p_variant) const; - bool operator<(const Variant& p_variant) const; + bool operator==(const Variant &p_variant) const; + bool operator!=(const Variant &p_variant) const; + bool operator<(const Variant &p_variant) const; uint32_t hash() const; - bool hash_compare(const Variant& p_variant) const; + bool hash_compare(const Variant &p_variant) const; bool booleanize(bool &valid) const; - void static_assign(const Variant& p_variant); + void static_assign(const Variant &p_variant); static void get_constructor_list(Variant::Type p_type, List<MethodInfo> *p_list); static void get_numeric_constants_for_type(Variant::Type p_type, List<StringName> *p_constants); - static bool has_numeric_constant(Variant::Type p_type, const StringName& p_value); - static int get_numeric_constant_value(Variant::Type p_type, const StringName& p_value,bool *r_valid=NULL); + static bool has_numeric_constant(Variant::Type p_type, const StringName &p_value); + static int get_numeric_constant_value(Variant::Type p_type, const StringName &p_value, bool *r_valid = NULL); - typedef String (*ObjectDeConstruct)(const Variant& p_object,void *ud); - typedef void (*ObjectConstruct)(const String& p_text,void *ud,Variant& r_value); + typedef String (*ObjectDeConstruct)(const Variant &p_object, void *ud); + typedef void (*ObjectConstruct)(const String &p_text, void *ud, Variant &r_value); String get_construct_string() const; - static void construct_from_string(const String& p_string,Variant& r_value,ObjectConstruct p_obj_construct=NULL,void *p_construct_ud=NULL); - - void operator=(const Variant& p_variant); // only this is enough for all the other types - Variant(const Variant& p_variant); - _FORCE_INLINE_ Variant() { type=NIL; } - _FORCE_INLINE_ ~Variant() { if (type!=Variant::NIL) clear(); } + static void construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct = NULL, void *p_construct_ud = NULL); + void operator=(const Variant &p_variant); // only this is enough for all the other types + Variant(const Variant &p_variant); + _FORCE_INLINE_ Variant() { type = NIL; } + _FORCE_INLINE_ ~Variant() { + if (type != Variant::NIL) clear(); + } }; //typedef Dictionary Dictionary; no //typedef Array Array; - - Vector<Variant> varray(); -Vector<Variant> varray(const Variant& p_arg1); -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2); -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3); -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4); -Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4,const Variant& p_arg5); +Vector<Variant> varray(const Variant &p_arg1); +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2); +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3); +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4); +Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5); struct VariantHasher { - 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 VariantComparator { - static _FORCE_INLINE_ bool compare(const Variant &p_lhs, const Variant &p_rhs) { return p_lhs.hash_compare(p_rhs); } + static _FORCE_INLINE_ bool compare(const Variant &p_lhs, const Variant &p_rhs) { return p_lhs.hash_compare(p_rhs); } }; -Variant::ObjData& Variant::_get_obj() { +Variant::ObjData &Variant::_get_obj() { - return *reinterpret_cast<ObjData*>(&_data._mem[0]); + return *reinterpret_cast<ObjData *>(&_data._mem[0]); } -const Variant::ObjData& Variant::_get_obj() const { +const Variant::ObjData &Variant::_get_obj() const { - return *reinterpret_cast<const ObjData*>(&_data._mem[0]); + return *reinterpret_cast<const ObjData *>(&_data._mem[0]); } - -String vformat(const String& p_text, const Variant& p1=Variant(),const Variant& p2=Variant(),const Variant& p3=Variant(),const Variant& p4=Variant(),const Variant& p5=Variant()); +String vformat(const String &p_text, const Variant &p1 = Variant(), const Variant &p2 = Variant(), const Variant &p3 = Variant(), const Variant &p4 = Variant(), const Variant &p5 = Variant()); #endif diff --git a/core/variant_call.cpp b/core/variant_call.cpp index 376e646fc2..758500a873 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -28,27 +28,22 @@ /*************************************************************************/ #include "variant.h" +#include "core_string_names.h" #include "object.h" #include "os/os.h" -#include "core_string_names.h" #include "script_language.h" - -typedef void (*VariantFunc)(Variant& r_ret,Variant& p_self,const Variant** p_args); -typedef void (*VariantConstructFunc)(Variant& r_ret,const Variant** p_args); +typedef void (*VariantFunc)(Variant &r_ret, Variant &p_self, const Variant **p_args); +typedef void (*VariantConstructFunc)(Variant &r_ret, const Variant **p_args); VARIANT_ENUM_CAST(Image::CompressMode); //VARIANT_ENUM_CAST(Image::Format); - struct _VariantCall { + static void Vector3_dot(Variant &r_ret, Variant &p_self, const Variant **p_args) { - - - static void Vector3_dot(Variant& r_ret,Variant& p_self,const Variant** p_args) { - - r_ret=reinterpret_cast<Vector3*>(p_self._data._mem)->dot(*reinterpret_cast<const Vector3*>(p_args[0]->_data._mem)); + r_ret = reinterpret_cast<Vector3 *>(p_self._data._mem)->dot(*reinterpret_cast<const Vector3 *>(p_args[0]->_data._mem)); } struct FuncData { @@ -64,107 +59,101 @@ struct _VariantCall { #endif VariantFunc func; - _FORCE_INLINE_ bool verify_arguments(const Variant **p_args,Variant::CallError &r_error) { + _FORCE_INLINE_ bool verify_arguments(const Variant **p_args, Variant::CallError &r_error) { - if (arg_count==0) + if (arg_count == 0) return true; Variant::Type *tptr = &arg_types[0]; - for(int i=0;i<arg_count;i++) { + for (int i = 0; i < arg_count; i++) { - if (!tptr[i] || tptr[i]==p_args[i]->type) + if (!tptr[i] || tptr[i] == p_args[i]->type) continue; // all good - if (!Variant::can_convert(p_args[i]->type,tptr[i])) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=i; - r_error.expected=tptr[i]; + if (!Variant::can_convert(p_args[i]->type, tptr[i])) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = i; + r_error.expected = tptr[i]; return false; - } } return true; } - _FORCE_INLINE_ void call(Variant& r_ret,Variant& p_self,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { + _FORCE_INLINE_ void call(Variant &r_ret, Variant &p_self, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { #ifdef DEBUG_ENABLED - if(p_argcount>arg_count) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=arg_count; + if (p_argcount > arg_count) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = arg_count; return; } else #endif - if (p_argcount<arg_count) { + if (p_argcount < arg_count) { int def_argcount = default_args.size(); #ifdef DEBUG_ENABLED - if (p_argcount<(arg_count-def_argcount)) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=arg_count-def_argcount; + if (p_argcount < (arg_count - def_argcount)) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = arg_count - def_argcount; return; } #endif - ERR_FAIL_COND(p_argcount>VARIANT_ARG_MAX); + ERR_FAIL_COND(p_argcount > VARIANT_ARG_MAX); const Variant *newargs[VARIANT_ARG_MAX]; - for(int i=0;i<p_argcount;i++) - newargs[i]=p_args[i]; - int defargcount=def_argcount; - for(int i=p_argcount;i<arg_count;i++) - newargs[i]=&default_args[defargcount-(i-p_argcount)-1]; //default arguments + for (int i = 0; i < p_argcount; i++) + newargs[i] = p_args[i]; + int defargcount = def_argcount; + for (int i = p_argcount; i < arg_count; i++) + newargs[i] = &default_args[defargcount - (i - p_argcount) - 1]; //default arguments #ifdef DEBUG_ENABLED - if (!verify_arguments(newargs,r_error)) + if (!verify_arguments(newargs, r_error)) return; #endif - func(r_ret,p_self,newargs); + func(r_ret, p_self, newargs); } else { #ifdef DEBUG_ENABLED - if (!verify_arguments(p_args,r_error)) + if (!verify_arguments(p_args, r_error)) return; #endif - func(r_ret,p_self,p_args); + func(r_ret, p_self, p_args); } - } - }; - struct TypeFunc { - Map<StringName,FuncData> functions; + Map<StringName, FuncData> functions; }; - static TypeFunc* type_funcs; - - - - + static TypeFunc *type_funcs; struct Arg { StringName name; Variant::Type type; - Arg() { type=Variant::NIL;} - Arg(Variant::Type p_type,const StringName &p_name) { name=p_name; type=p_type; } + Arg() { type = Variant::NIL; } + Arg(Variant::Type p_type, const StringName &p_name) { + name = p_name; + type = p_type; + } }; //void addfunc(Variant::Type p_type, const StringName& p_name,VariantFunc p_func); - static void make_func_return_variant(Variant::Type p_type,const StringName& p_name) { + static void make_func_return_variant(Variant::Type p_type, const StringName &p_name) { #ifdef DEBUG_ENABLED - type_funcs[p_type].functions[p_name].returns=true; + type_funcs[p_type].functions[p_name].returns = true; #endif } - - static void addfunc(Variant::Type p_type, Variant::Type p_return,const StringName& p_name,VariantFunc p_func, const Vector<Variant>& p_defaultarg,const Arg& p_argtype1=Arg(),const Arg& p_argtype2=Arg(),const Arg& p_argtype3=Arg(),const Arg& p_argtype4=Arg(),const Arg& p_argtype5=Arg()) { + static void addfunc(Variant::Type p_type, Variant::Type p_return, const StringName &p_name, VariantFunc p_func, const Vector<Variant> &p_defaultarg, const Arg &p_argtype1 = Arg(), const Arg &p_argtype2 = Arg(), const Arg &p_argtype3 = Arg(), const Arg &p_argtype4 = Arg(), const Arg &p_argtype5 = Arg()) { FuncData funcdata; - funcdata.func=p_func; - funcdata.default_args=p_defaultarg; + funcdata.func = p_func; + funcdata.default_args = p_defaultarg; #ifdef DEBUG_ENABLED - funcdata.return_type=p_return; - funcdata.returns=p_return!=Variant::NIL; + funcdata.return_type = p_return; + funcdata.returns = p_return != Variant::NIL; #endif if (p_argtype1.name) { @@ -210,106 +199,104 @@ struct _VariantCall { } else goto end; - end: - - funcdata.arg_count=funcdata.arg_types.size(); - type_funcs[p_type].functions[p_name]=funcdata; + end: + funcdata.arg_count = funcdata.arg_types.size(); + type_funcs[p_type].functions[p_name] = funcdata; } -#define VCALL_LOCALMEM0(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(); } -#define VCALL_LOCALMEM0R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(); } -#define VCALL_LOCALMEM1(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0]); } -#define VCALL_LOCALMEM1R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0]); } -#define VCALL_LOCALMEM2(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1]); } -#define VCALL_LOCALMEM2R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1]); } -#define VCALL_LOCALMEM3(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2]); } -#define VCALL_LOCALMEM3R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2]); } -#define VCALL_LOCALMEM4(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); } -#define VCALL_LOCALMEM4R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); } -#define VCALL_LOCALMEM5(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); } -#define VCALL_LOCALMEM5R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); } - +#define VCALL_LOCALMEM0(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(); } +#define VCALL_LOCALMEM0R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(); } +#define VCALL_LOCALMEM1(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0]); } +#define VCALL_LOCALMEM1R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0]); } +#define VCALL_LOCALMEM2(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1]); } +#define VCALL_LOCALMEM2R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1]); } +#define VCALL_LOCALMEM3(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2]); } +#define VCALL_LOCALMEM3R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2]); } +#define VCALL_LOCALMEM4(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } +#define VCALL_LOCALMEM4R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } +#define VCALL_LOCALMEM5(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); } +#define VCALL_LOCALMEM5R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); } // built-in functions of localmem based types - VCALL_LOCALMEM1R(String,casecmp_to); - VCALL_LOCALMEM1R(String,nocasecmp_to); - VCALL_LOCALMEM0R(String,length); - VCALL_LOCALMEM2R(String,substr); - VCALL_LOCALMEM2R(String,find); - VCALL_LOCALMEM1R(String,find_last); - VCALL_LOCALMEM2R(String,findn); - VCALL_LOCALMEM2R(String,rfind); - VCALL_LOCALMEM2R(String,rfindn); - VCALL_LOCALMEM1R(String,match); - VCALL_LOCALMEM1R(String,matchn); - VCALL_LOCALMEM1R(String,begins_with); - VCALL_LOCALMEM1R(String,ends_with); - VCALL_LOCALMEM1R(String,is_subsequence_of); - VCALL_LOCALMEM1R(String,is_subsequence_ofi); - VCALL_LOCALMEM0R(String,bigrams); - VCALL_LOCALMEM1R(String,similarity); - VCALL_LOCALMEM2R(String,format); - VCALL_LOCALMEM2R(String,replace); - VCALL_LOCALMEM2R(String,replacen); - VCALL_LOCALMEM2R(String,insert); - VCALL_LOCALMEM0R(String,capitalize); - VCALL_LOCALMEM2R(String,split); - VCALL_LOCALMEM2R(String,split_floats); - VCALL_LOCALMEM0R(String,to_upper); - VCALL_LOCALMEM0R(String,to_lower); - VCALL_LOCALMEM1R(String,left); - VCALL_LOCALMEM1R(String,right); - VCALL_LOCALMEM2R(String,strip_edges); - VCALL_LOCALMEM0R(String,get_extension); - VCALL_LOCALMEM0R(String,get_basename); - VCALL_LOCALMEM1R(String,plus_file); - VCALL_LOCALMEM1R(String,ord_at); - VCALL_LOCALMEM2(String,erase); - VCALL_LOCALMEM0R(String,hash); - VCALL_LOCALMEM0R(String,md5_text); - VCALL_LOCALMEM0R(String,sha256_text); - VCALL_LOCALMEM0R(String,md5_buffer); - VCALL_LOCALMEM0R(String,sha256_buffer); - VCALL_LOCALMEM0R(String,empty); - VCALL_LOCALMEM0R(String,is_abs_path); - VCALL_LOCALMEM0R(String,is_rel_path); - VCALL_LOCALMEM0R(String,get_base_dir); - VCALL_LOCALMEM0R(String,get_file); - VCALL_LOCALMEM0R(String,xml_escape); - VCALL_LOCALMEM0R(String,xml_unescape); - VCALL_LOCALMEM0R(String,c_escape); - VCALL_LOCALMEM0R(String,c_unescape); - VCALL_LOCALMEM0R(String,json_escape); - VCALL_LOCALMEM0R(String,percent_encode); - VCALL_LOCALMEM0R(String,percent_decode); - VCALL_LOCALMEM0R(String,is_valid_identifier); - VCALL_LOCALMEM0R(String,is_valid_integer); - VCALL_LOCALMEM0R(String,is_valid_float); - VCALL_LOCALMEM0R(String,is_valid_html_color); - VCALL_LOCALMEM0R(String,is_valid_ip_address); - VCALL_LOCALMEM0R(String,to_int); - VCALL_LOCALMEM0R(String,to_float); - VCALL_LOCALMEM0R(String,hex_to_int); - VCALL_LOCALMEM1R(String,pad_decimals); - VCALL_LOCALMEM1R(String,pad_zeros); - - static void _call_String_to_ascii(Variant& r_ret,Variant& p_self,const Variant** p_args) { - - String *s = reinterpret_cast<String*>(p_self._data._mem); + VCALL_LOCALMEM1R(String, casecmp_to); + VCALL_LOCALMEM1R(String, nocasecmp_to); + VCALL_LOCALMEM0R(String, length); + VCALL_LOCALMEM2R(String, substr); + VCALL_LOCALMEM2R(String, find); + VCALL_LOCALMEM1R(String, find_last); + VCALL_LOCALMEM2R(String, findn); + VCALL_LOCALMEM2R(String, rfind); + VCALL_LOCALMEM2R(String, rfindn); + VCALL_LOCALMEM1R(String, match); + VCALL_LOCALMEM1R(String, matchn); + VCALL_LOCALMEM1R(String, begins_with); + VCALL_LOCALMEM1R(String, ends_with); + VCALL_LOCALMEM1R(String, is_subsequence_of); + VCALL_LOCALMEM1R(String, is_subsequence_ofi); + VCALL_LOCALMEM0R(String, bigrams); + VCALL_LOCALMEM1R(String, similarity); + VCALL_LOCALMEM2R(String, format); + VCALL_LOCALMEM2R(String, replace); + VCALL_LOCALMEM2R(String, replacen); + VCALL_LOCALMEM2R(String, insert); + VCALL_LOCALMEM0R(String, capitalize); + VCALL_LOCALMEM2R(String, split); + VCALL_LOCALMEM2R(String, split_floats); + VCALL_LOCALMEM0R(String, to_upper); + VCALL_LOCALMEM0R(String, to_lower); + VCALL_LOCALMEM1R(String, left); + VCALL_LOCALMEM1R(String, right); + VCALL_LOCALMEM2R(String, strip_edges); + VCALL_LOCALMEM0R(String, get_extension); + VCALL_LOCALMEM0R(String, get_basename); + VCALL_LOCALMEM1R(String, plus_file); + VCALL_LOCALMEM1R(String, ord_at); + VCALL_LOCALMEM2(String, erase); + VCALL_LOCALMEM0R(String, hash); + VCALL_LOCALMEM0R(String, md5_text); + VCALL_LOCALMEM0R(String, sha256_text); + VCALL_LOCALMEM0R(String, md5_buffer); + VCALL_LOCALMEM0R(String, sha256_buffer); + VCALL_LOCALMEM0R(String, empty); + VCALL_LOCALMEM0R(String, is_abs_path); + VCALL_LOCALMEM0R(String, is_rel_path); + VCALL_LOCALMEM0R(String, get_base_dir); + VCALL_LOCALMEM0R(String, get_file); + VCALL_LOCALMEM0R(String, xml_escape); + VCALL_LOCALMEM0R(String, xml_unescape); + VCALL_LOCALMEM0R(String, c_escape); + VCALL_LOCALMEM0R(String, c_unescape); + VCALL_LOCALMEM0R(String, json_escape); + VCALL_LOCALMEM0R(String, percent_encode); + VCALL_LOCALMEM0R(String, percent_decode); + VCALL_LOCALMEM0R(String, is_valid_identifier); + VCALL_LOCALMEM0R(String, is_valid_integer); + VCALL_LOCALMEM0R(String, is_valid_float); + VCALL_LOCALMEM0R(String, is_valid_html_color); + VCALL_LOCALMEM0R(String, is_valid_ip_address); + VCALL_LOCALMEM0R(String, to_int); + VCALL_LOCALMEM0R(String, to_float); + VCALL_LOCALMEM0R(String, hex_to_int); + VCALL_LOCALMEM1R(String, pad_decimals); + VCALL_LOCALMEM1R(String, pad_zeros); + + static void _call_String_to_ascii(Variant &r_ret, Variant &p_self, const Variant **p_args) { + + String *s = reinterpret_cast<String *>(p_self._data._mem); CharString charstr = s->ascii(); PoolByteArray retval; @@ -322,9 +309,9 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var r_ret = retval; } - static void _call_String_to_utf8(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_String_to_utf8(Variant &r_ret, Variant &p_self, const Variant **p_args) { - String *s = reinterpret_cast<String*>(p_self._data._mem); + String *s = reinterpret_cast<String *>(p_self._data._mem); CharString charstr = s->utf8(); PoolByteArray retval; @@ -337,38 +324,37 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var r_ret = retval; } - - VCALL_LOCALMEM0R(Vector2,normalized); - VCALL_LOCALMEM0R(Vector2,length); - VCALL_LOCALMEM0R(Vector2,length_squared); - VCALL_LOCALMEM1R(Vector2,distance_to); - VCALL_LOCALMEM1R(Vector2,distance_squared_to); - VCALL_LOCALMEM1R(Vector2,angle_to); - VCALL_LOCALMEM1R(Vector2,angle_to_point); - VCALL_LOCALMEM2R(Vector2,linear_interpolate); - VCALL_LOCALMEM4R(Vector2,cubic_interpolate); - VCALL_LOCALMEM1R(Vector2,rotated); - VCALL_LOCALMEM0R(Vector2,tangent); - VCALL_LOCALMEM0R(Vector2,floor); - VCALL_LOCALMEM1R(Vector2,snapped); - VCALL_LOCALMEM0R(Vector2,aspect); - VCALL_LOCALMEM1R(Vector2,dot); - VCALL_LOCALMEM1R(Vector2,slide); - VCALL_LOCALMEM1R(Vector2,reflect); - VCALL_LOCALMEM0R(Vector2,angle); + VCALL_LOCALMEM0R(Vector2, normalized); + VCALL_LOCALMEM0R(Vector2, length); + VCALL_LOCALMEM0R(Vector2, length_squared); + VCALL_LOCALMEM1R(Vector2, distance_to); + VCALL_LOCALMEM1R(Vector2, distance_squared_to); + VCALL_LOCALMEM1R(Vector2, angle_to); + VCALL_LOCALMEM1R(Vector2, angle_to_point); + VCALL_LOCALMEM2R(Vector2, linear_interpolate); + VCALL_LOCALMEM4R(Vector2, cubic_interpolate); + VCALL_LOCALMEM1R(Vector2, rotated); + VCALL_LOCALMEM0R(Vector2, tangent); + VCALL_LOCALMEM0R(Vector2, floor); + VCALL_LOCALMEM1R(Vector2, snapped); + VCALL_LOCALMEM0R(Vector2, aspect); + VCALL_LOCALMEM1R(Vector2, dot); + VCALL_LOCALMEM1R(Vector2, slide); + VCALL_LOCALMEM1R(Vector2, reflect); + VCALL_LOCALMEM0R(Vector2, angle); //VCALL_LOCALMEM1R(Vector2,cross); - VCALL_LOCALMEM0R(Vector2,abs); - VCALL_LOCALMEM1R(Vector2,clamped); - - VCALL_LOCALMEM0R(Rect2,get_area); - VCALL_LOCALMEM1R(Rect2,intersects); - VCALL_LOCALMEM1R(Rect2,encloses); - VCALL_LOCALMEM0R(Rect2,has_no_area); - VCALL_LOCALMEM1R(Rect2,clip); - VCALL_LOCALMEM1R(Rect2,merge); - VCALL_LOCALMEM1R(Rect2,has_point); - VCALL_LOCALMEM1R(Rect2,grow); - VCALL_LOCALMEM1R(Rect2,expand); + VCALL_LOCALMEM0R(Vector2, abs); + VCALL_LOCALMEM1R(Vector2, clamped); + + VCALL_LOCALMEM0R(Rect2, get_area); + VCALL_LOCALMEM1R(Rect2, intersects); + VCALL_LOCALMEM1R(Rect2, encloses); + VCALL_LOCALMEM0R(Rect2, has_no_area); + VCALL_LOCALMEM1R(Rect2, clip); + VCALL_LOCALMEM1R(Rect2, merge); + VCALL_LOCALMEM1R(Rect2, has_point); + VCALL_LOCALMEM1R(Rect2, grow); + VCALL_LOCALMEM1R(Rect2, expand); VCALL_LOCALMEM0R(Vector3, min_axis); VCALL_LOCALMEM0R(Vector3, max_axis); @@ -393,374 +379,367 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var VCALL_LOCALMEM1R(Vector3, slide); VCALL_LOCALMEM1R(Vector3, reflect); - - VCALL_LOCALMEM0R(Plane,normalized); - VCALL_LOCALMEM0R(Plane,center); - VCALL_LOCALMEM0R(Plane,get_any_point); - VCALL_LOCALMEM1R(Plane,is_point_over); - VCALL_LOCALMEM1R(Plane,distance_to); - VCALL_LOCALMEM2R(Plane,has_point); - VCALL_LOCALMEM1R(Plane,project); + VCALL_LOCALMEM0R(Plane, normalized); + VCALL_LOCALMEM0R(Plane, center); + VCALL_LOCALMEM0R(Plane, get_any_point); + VCALL_LOCALMEM1R(Plane, is_point_over); + VCALL_LOCALMEM1R(Plane, distance_to); + VCALL_LOCALMEM2R(Plane, has_point); + VCALL_LOCALMEM1R(Plane, project); //return vector3 if intersected, nil if not - static void _call_Plane_intersect_3(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Plane_intersect_3(Variant &r_ret, Variant &p_self, const Variant **p_args) { Vector3 result; - if (reinterpret_cast<Plane*>(p_self._data._mem)->intersect_3(*p_args[0],*p_args[1],&result)) - r_ret=result; + if (reinterpret_cast<Plane *>(p_self._data._mem)->intersect_3(*p_args[0], *p_args[1], &result)) + r_ret = result; else - r_ret=Variant(); + r_ret = Variant(); } - static void _call_Plane_intersects_ray(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Plane_intersects_ray(Variant &r_ret, Variant &p_self, const Variant **p_args) { Vector3 result; - if (reinterpret_cast<Plane*>(p_self._data._mem)->intersects_ray(*p_args[0],*p_args[1],&result)) - r_ret=result; + if (reinterpret_cast<Plane *>(p_self._data._mem)->intersects_ray(*p_args[0], *p_args[1], &result)) + r_ret = result; else - r_ret=Variant(); + r_ret = Variant(); } - static void _call_Plane_intersects_segment(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Plane_intersects_segment(Variant &r_ret, Variant &p_self, const Variant **p_args) { Vector3 result; - if (reinterpret_cast<Plane*>(p_self._data._mem)->intersects_segment(*p_args[0],*p_args[1],&result)) - r_ret=result; + if (reinterpret_cast<Plane *>(p_self._data._mem)->intersects_segment(*p_args[0], *p_args[1], &result)) + r_ret = result; else - r_ret=Variant(); + r_ret = Variant(); } - VCALL_LOCALMEM0R(Quat,length); - VCALL_LOCALMEM0R(Quat,length_squared); - VCALL_LOCALMEM0R(Quat,normalized); - VCALL_LOCALMEM0R(Quat,inverse); - VCALL_LOCALMEM1R(Quat,dot); - VCALL_LOCALMEM1R(Quat,xform); - VCALL_LOCALMEM2R(Quat,slerp); - VCALL_LOCALMEM2R(Quat,slerpni); - VCALL_LOCALMEM4R(Quat,cubic_slerp); - - VCALL_LOCALMEM0R(Color,to_32); - VCALL_LOCALMEM0R(Color,to_ARGB32); - VCALL_LOCALMEM0R(Color,gray); - VCALL_LOCALMEM0R(Color,inverted); - VCALL_LOCALMEM0R(Color,contrasted); - VCALL_LOCALMEM2R(Color,linear_interpolate); - VCALL_LOCALMEM1R(Color,blend); - VCALL_LOCALMEM1R(Color,to_html); - - VCALL_LOCALMEM0R(RID,get_id); - - VCALL_LOCALMEM0R(NodePath,is_absolute); - VCALL_LOCALMEM0R(NodePath,get_name_count); - VCALL_LOCALMEM1R(NodePath,get_name); - VCALL_LOCALMEM0R(NodePath,get_subname_count); - VCALL_LOCALMEM1R(NodePath,get_subname); - VCALL_LOCALMEM0R(NodePath,get_property); - VCALL_LOCALMEM0R(NodePath,is_empty); - - VCALL_LOCALMEM0R(Dictionary,size); - VCALL_LOCALMEM0R(Dictionary,empty); - VCALL_LOCALMEM0(Dictionary,clear); - VCALL_LOCALMEM1R(Dictionary,has); - VCALL_LOCALMEM1R(Dictionary,has_all); - VCALL_LOCALMEM1(Dictionary,erase); - VCALL_LOCALMEM0R(Dictionary,hash); - VCALL_LOCALMEM0R(Dictionary,keys); - VCALL_LOCALMEM0R(Dictionary,values); - - VCALL_LOCALMEM2(Array,set); - VCALL_LOCALMEM1R(Array,get); - VCALL_LOCALMEM0R(Array,size); - VCALL_LOCALMEM0R(Array,empty); - VCALL_LOCALMEM0(Array,clear); - VCALL_LOCALMEM0R(Array,hash); - VCALL_LOCALMEM1(Array,push_back); - VCALL_LOCALMEM1(Array,push_front); - VCALL_LOCALMEM0R(Array,pop_back); - VCALL_LOCALMEM0R(Array,pop_front); - VCALL_LOCALMEM1(Array,append); - VCALL_LOCALMEM1(Array,resize); - VCALL_LOCALMEM2(Array,insert); - VCALL_LOCALMEM1(Array,remove); - VCALL_LOCALMEM0R(Array,front); - VCALL_LOCALMEM0R(Array,back); - VCALL_LOCALMEM2R(Array,find); - VCALL_LOCALMEM2R(Array,rfind); - VCALL_LOCALMEM1R(Array,find_last); - VCALL_LOCALMEM1R(Array,count); - VCALL_LOCALMEM1R(Array,has); - VCALL_LOCALMEM1(Array,erase); - VCALL_LOCALMEM0(Array,sort); - VCALL_LOCALMEM2(Array,sort_custom); - VCALL_LOCALMEM0(Array,invert); - - - static void _call_PoolByteArray_get_string_from_ascii(Variant& r_ret,Variant& p_self,const Variant** p_args) { - - PoolByteArray* ba = reinterpret_cast<PoolByteArray*>(p_self._data._mem); + VCALL_LOCALMEM0R(Quat, length); + VCALL_LOCALMEM0R(Quat, length_squared); + VCALL_LOCALMEM0R(Quat, normalized); + VCALL_LOCALMEM0R(Quat, inverse); + VCALL_LOCALMEM1R(Quat, dot); + VCALL_LOCALMEM1R(Quat, xform); + VCALL_LOCALMEM2R(Quat, slerp); + VCALL_LOCALMEM2R(Quat, slerpni); + VCALL_LOCALMEM4R(Quat, cubic_slerp); + + VCALL_LOCALMEM0R(Color, to_32); + VCALL_LOCALMEM0R(Color, to_ARGB32); + VCALL_LOCALMEM0R(Color, gray); + VCALL_LOCALMEM0R(Color, inverted); + VCALL_LOCALMEM0R(Color, contrasted); + VCALL_LOCALMEM2R(Color, linear_interpolate); + VCALL_LOCALMEM1R(Color, blend); + VCALL_LOCALMEM1R(Color, to_html); + + VCALL_LOCALMEM0R(RID, get_id); + + VCALL_LOCALMEM0R(NodePath, is_absolute); + VCALL_LOCALMEM0R(NodePath, get_name_count); + VCALL_LOCALMEM1R(NodePath, get_name); + VCALL_LOCALMEM0R(NodePath, get_subname_count); + VCALL_LOCALMEM1R(NodePath, get_subname); + VCALL_LOCALMEM0R(NodePath, get_property); + VCALL_LOCALMEM0R(NodePath, is_empty); + + VCALL_LOCALMEM0R(Dictionary, size); + VCALL_LOCALMEM0R(Dictionary, empty); + VCALL_LOCALMEM0(Dictionary, clear); + VCALL_LOCALMEM1R(Dictionary, has); + VCALL_LOCALMEM1R(Dictionary, has_all); + VCALL_LOCALMEM1(Dictionary, erase); + VCALL_LOCALMEM0R(Dictionary, hash); + VCALL_LOCALMEM0R(Dictionary, keys); + VCALL_LOCALMEM0R(Dictionary, values); + + VCALL_LOCALMEM2(Array, set); + VCALL_LOCALMEM1R(Array, get); + VCALL_LOCALMEM0R(Array, size); + VCALL_LOCALMEM0R(Array, empty); + VCALL_LOCALMEM0(Array, clear); + VCALL_LOCALMEM0R(Array, hash); + VCALL_LOCALMEM1(Array, push_back); + VCALL_LOCALMEM1(Array, push_front); + VCALL_LOCALMEM0R(Array, pop_back); + VCALL_LOCALMEM0R(Array, pop_front); + VCALL_LOCALMEM1(Array, append); + VCALL_LOCALMEM1(Array, resize); + VCALL_LOCALMEM2(Array, insert); + VCALL_LOCALMEM1(Array, remove); + VCALL_LOCALMEM0R(Array, front); + VCALL_LOCALMEM0R(Array, back); + VCALL_LOCALMEM2R(Array, find); + VCALL_LOCALMEM2R(Array, rfind); + VCALL_LOCALMEM1R(Array, find_last); + VCALL_LOCALMEM1R(Array, count); + VCALL_LOCALMEM1R(Array, has); + VCALL_LOCALMEM1(Array, erase); + VCALL_LOCALMEM0(Array, sort); + VCALL_LOCALMEM2(Array, sort_custom); + VCALL_LOCALMEM0(Array, invert); + + static void _call_PoolByteArray_get_string_from_ascii(Variant &r_ret, Variant &p_self, const Variant **p_args) { + + PoolByteArray *ba = reinterpret_cast<PoolByteArray *>(p_self._data._mem); String s; - if (ba->size()>=0) { + if (ba->size() >= 0) { PoolByteArray::Read r = ba->read(); CharString cs; - cs.resize(ba->size()+1); - copymem(cs.ptr(),r.ptr(),ba->size()); - cs[ba->size()]=0; + cs.resize(ba->size() + 1); + copymem(cs.ptr(), r.ptr(), ba->size()); + cs[ba->size()] = 0; s = cs.get_data(); } - r_ret=s; + r_ret = s; } - static void _call_PoolByteArray_get_string_from_utf8(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_PoolByteArray_get_string_from_utf8(Variant &r_ret, Variant &p_self, const Variant **p_args) { - PoolByteArray* ba = reinterpret_cast<PoolByteArray*>(p_self._data._mem); + PoolByteArray *ba = reinterpret_cast<PoolByteArray *>(p_self._data._mem); String s; - if (ba->size()>=0) { + if (ba->size() >= 0) { PoolByteArray::Read r = ba->read(); - s.parse_utf8((const char*)r.ptr(),ba->size()); + s.parse_utf8((const char *)r.ptr(), ba->size()); } - r_ret=s; + r_ret = s; } - VCALL_LOCALMEM0R(PoolByteArray,size); - VCALL_LOCALMEM2(PoolByteArray,set); - VCALL_LOCALMEM1R(PoolByteArray,get); - VCALL_LOCALMEM1(PoolByteArray,push_back); - VCALL_LOCALMEM1(PoolByteArray,resize); - VCALL_LOCALMEM2R(PoolByteArray,insert); - VCALL_LOCALMEM1(PoolByteArray,remove); - VCALL_LOCALMEM1(PoolByteArray,append); - VCALL_LOCALMEM1(PoolByteArray,append_array); - VCALL_LOCALMEM0(PoolByteArray,invert); - VCALL_LOCALMEM2R(PoolByteArray,subarray); - - VCALL_LOCALMEM0R(PoolIntArray,size); - VCALL_LOCALMEM2(PoolIntArray,set); - VCALL_LOCALMEM1R(PoolIntArray,get); - VCALL_LOCALMEM1(PoolIntArray,push_back); - VCALL_LOCALMEM1(PoolIntArray,resize); - VCALL_LOCALMEM2R(PoolIntArray,insert); - VCALL_LOCALMEM1(PoolIntArray,remove); - VCALL_LOCALMEM1(PoolIntArray,append); - VCALL_LOCALMEM1(PoolIntArray,append_array); - VCALL_LOCALMEM0(PoolIntArray,invert); - - VCALL_LOCALMEM0R(PoolRealArray,size); - VCALL_LOCALMEM2(PoolRealArray,set); - VCALL_LOCALMEM1R(PoolRealArray,get); - VCALL_LOCALMEM1(PoolRealArray,push_back); - VCALL_LOCALMEM1(PoolRealArray,resize); - VCALL_LOCALMEM2R(PoolRealArray,insert); - VCALL_LOCALMEM1(PoolRealArray,remove); - VCALL_LOCALMEM1(PoolRealArray,append); - VCALL_LOCALMEM1(PoolRealArray,append_array); - VCALL_LOCALMEM0(PoolRealArray,invert); - - VCALL_LOCALMEM0R(PoolStringArray,size); - VCALL_LOCALMEM2(PoolStringArray,set); - VCALL_LOCALMEM1R(PoolStringArray,get); - VCALL_LOCALMEM1(PoolStringArray,push_back); - VCALL_LOCALMEM1(PoolStringArray,resize); - VCALL_LOCALMEM2R(PoolStringArray,insert); - VCALL_LOCALMEM1(PoolStringArray,remove); - VCALL_LOCALMEM1(PoolStringArray,append); - VCALL_LOCALMEM1(PoolStringArray,append_array); - VCALL_LOCALMEM0(PoolStringArray,invert); - VCALL_LOCALMEM1R(PoolStringArray,join); - - VCALL_LOCALMEM0R(PoolVector2Array,size); - VCALL_LOCALMEM2(PoolVector2Array,set); - VCALL_LOCALMEM1R(PoolVector2Array,get); - VCALL_LOCALMEM1(PoolVector2Array,push_back); - VCALL_LOCALMEM1(PoolVector2Array,resize); - VCALL_LOCALMEM2R(PoolVector2Array,insert); - VCALL_LOCALMEM1(PoolVector2Array,remove); - VCALL_LOCALMEM1(PoolVector2Array,append); - VCALL_LOCALMEM1(PoolVector2Array,append_array); - VCALL_LOCALMEM0(PoolVector2Array,invert); - - VCALL_LOCALMEM0R(PoolVector3Array,size); - VCALL_LOCALMEM2(PoolVector3Array,set); - VCALL_LOCALMEM1R(PoolVector3Array,get); - VCALL_LOCALMEM1(PoolVector3Array,push_back); - VCALL_LOCALMEM1(PoolVector3Array,resize); - VCALL_LOCALMEM2R(PoolVector3Array,insert); - VCALL_LOCALMEM1(PoolVector3Array,remove); - VCALL_LOCALMEM1(PoolVector3Array,append); - VCALL_LOCALMEM1(PoolVector3Array,append_array); - VCALL_LOCALMEM0(PoolVector3Array,invert); - - VCALL_LOCALMEM0R(PoolColorArray,size); - VCALL_LOCALMEM2(PoolColorArray,set); - VCALL_LOCALMEM1R(PoolColorArray,get); - VCALL_LOCALMEM1(PoolColorArray,push_back); - VCALL_LOCALMEM1(PoolColorArray,resize); - VCALL_LOCALMEM2R(PoolColorArray,insert); - VCALL_LOCALMEM1(PoolColorArray,remove); - VCALL_LOCALMEM1(PoolColorArray,append); - VCALL_LOCALMEM1(PoolColorArray,append_array); - VCALL_LOCALMEM0(PoolColorArray,invert); - -#define VCALL_PTR0(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(); } -#define VCALL_PTR0R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(); } -#define VCALL_PTR1(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0]); } -#define VCALL_PTR1R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0]); } -#define VCALL_PTR2(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1]); } -#define VCALL_PTR2R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1]); } -#define VCALL_PTR3(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2]); } -#define VCALL_PTR3R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2]); } -#define VCALL_PTR4(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); } -#define VCALL_PTR4R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); } -#define VCALL_PTR5(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); } -#define VCALL_PTR5R(m_type,m_method)\ -static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); } - - VCALL_PTR0R(Image,get_format); - VCALL_PTR0R(Image,get_width); - VCALL_PTR0R(Image,get_height); - VCALL_PTR0R(Image,empty); - VCALL_PTR0R(Image,get_used_rect); - VCALL_PTR1R(Image,load); - VCALL_PTR1R(Image,save_png); - VCALL_PTR1R(Image,get_rect); - VCALL_PTR1R(Image,compressed); - VCALL_PTR0R(Image,decompressed); + VCALL_LOCALMEM0R(PoolByteArray, size); + VCALL_LOCALMEM2(PoolByteArray, set); + VCALL_LOCALMEM1R(PoolByteArray, get); + VCALL_LOCALMEM1(PoolByteArray, push_back); + VCALL_LOCALMEM1(PoolByteArray, resize); + VCALL_LOCALMEM2R(PoolByteArray, insert); + VCALL_LOCALMEM1(PoolByteArray, remove); + VCALL_LOCALMEM1(PoolByteArray, append); + VCALL_LOCALMEM1(PoolByteArray, append_array); + VCALL_LOCALMEM0(PoolByteArray, invert); + VCALL_LOCALMEM2R(PoolByteArray, subarray); + + VCALL_LOCALMEM0R(PoolIntArray, size); + VCALL_LOCALMEM2(PoolIntArray, set); + VCALL_LOCALMEM1R(PoolIntArray, get); + VCALL_LOCALMEM1(PoolIntArray, push_back); + VCALL_LOCALMEM1(PoolIntArray, resize); + VCALL_LOCALMEM2R(PoolIntArray, insert); + VCALL_LOCALMEM1(PoolIntArray, remove); + VCALL_LOCALMEM1(PoolIntArray, append); + VCALL_LOCALMEM1(PoolIntArray, append_array); + VCALL_LOCALMEM0(PoolIntArray, invert); + + VCALL_LOCALMEM0R(PoolRealArray, size); + VCALL_LOCALMEM2(PoolRealArray, set); + VCALL_LOCALMEM1R(PoolRealArray, get); + VCALL_LOCALMEM1(PoolRealArray, push_back); + VCALL_LOCALMEM1(PoolRealArray, resize); + VCALL_LOCALMEM2R(PoolRealArray, insert); + VCALL_LOCALMEM1(PoolRealArray, remove); + VCALL_LOCALMEM1(PoolRealArray, append); + VCALL_LOCALMEM1(PoolRealArray, append_array); + VCALL_LOCALMEM0(PoolRealArray, invert); + + VCALL_LOCALMEM0R(PoolStringArray, size); + VCALL_LOCALMEM2(PoolStringArray, set); + VCALL_LOCALMEM1R(PoolStringArray, get); + VCALL_LOCALMEM1(PoolStringArray, push_back); + VCALL_LOCALMEM1(PoolStringArray, resize); + VCALL_LOCALMEM2R(PoolStringArray, insert); + VCALL_LOCALMEM1(PoolStringArray, remove); + VCALL_LOCALMEM1(PoolStringArray, append); + VCALL_LOCALMEM1(PoolStringArray, append_array); + VCALL_LOCALMEM0(PoolStringArray, invert); + VCALL_LOCALMEM1R(PoolStringArray, join); + + VCALL_LOCALMEM0R(PoolVector2Array, size); + VCALL_LOCALMEM2(PoolVector2Array, set); + VCALL_LOCALMEM1R(PoolVector2Array, get); + VCALL_LOCALMEM1(PoolVector2Array, push_back); + VCALL_LOCALMEM1(PoolVector2Array, resize); + VCALL_LOCALMEM2R(PoolVector2Array, insert); + VCALL_LOCALMEM1(PoolVector2Array, remove); + VCALL_LOCALMEM1(PoolVector2Array, append); + VCALL_LOCALMEM1(PoolVector2Array, append_array); + VCALL_LOCALMEM0(PoolVector2Array, invert); + + VCALL_LOCALMEM0R(PoolVector3Array, size); + VCALL_LOCALMEM2(PoolVector3Array, set); + VCALL_LOCALMEM1R(PoolVector3Array, get); + VCALL_LOCALMEM1(PoolVector3Array, push_back); + VCALL_LOCALMEM1(PoolVector3Array, resize); + VCALL_LOCALMEM2R(PoolVector3Array, insert); + VCALL_LOCALMEM1(PoolVector3Array, remove); + VCALL_LOCALMEM1(PoolVector3Array, append); + VCALL_LOCALMEM1(PoolVector3Array, append_array); + VCALL_LOCALMEM0(PoolVector3Array, invert); + + VCALL_LOCALMEM0R(PoolColorArray, size); + VCALL_LOCALMEM2(PoolColorArray, set); + VCALL_LOCALMEM1R(PoolColorArray, get); + VCALL_LOCALMEM1(PoolColorArray, push_back); + VCALL_LOCALMEM1(PoolColorArray, resize); + VCALL_LOCALMEM2R(PoolColorArray, insert); + VCALL_LOCALMEM1(PoolColorArray, remove); + VCALL_LOCALMEM1(PoolColorArray, append); + VCALL_LOCALMEM1(PoolColorArray, append_array); + VCALL_LOCALMEM0(PoolColorArray, invert); + +#define VCALL_PTR0(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(); } +#define VCALL_PTR0R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(); } +#define VCALL_PTR1(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0]); } +#define VCALL_PTR1R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0]); } +#define VCALL_PTR2(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1]); } +#define VCALL_PTR2R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1]); } +#define VCALL_PTR3(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2]); } +#define VCALL_PTR3R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2]); } +#define VCALL_PTR4(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } +#define VCALL_PTR4R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } +#define VCALL_PTR5(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); } +#define VCALL_PTR5R(m_type, m_method) \ + static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); } + + VCALL_PTR0R(Image, get_format); + VCALL_PTR0R(Image, get_width); + VCALL_PTR0R(Image, get_height); + VCALL_PTR0R(Image, empty); + VCALL_PTR0R(Image, get_used_rect); + VCALL_PTR1R(Image, load); + VCALL_PTR1R(Image, save_png); + VCALL_PTR1R(Image, get_rect); + VCALL_PTR1R(Image, compressed); + VCALL_PTR0R(Image, decompressed); VCALL_PTR3R(Image, resized); VCALL_PTR0R(Image, get_data); VCALL_PTR3(Image, blit_rect); VCALL_PTR1R(Image, converted); VCALL_PTR0(Image, fix_alpha_edges); - VCALL_PTR0R( Rect3, get_area ); - VCALL_PTR0R( Rect3, has_no_area ); - VCALL_PTR0R( Rect3, has_no_surface ); - VCALL_PTR1R( Rect3, intersects ); - VCALL_PTR1R( Rect3, encloses ); - VCALL_PTR1R( Rect3, merge ); - VCALL_PTR1R( Rect3, intersection ); - VCALL_PTR1R( Rect3, intersects_plane ); - VCALL_PTR2R( Rect3, intersects_segment ); - VCALL_PTR1R( Rect3, has_point ); - VCALL_PTR1R( Rect3, get_support ); - VCALL_PTR0R( Rect3, get_longest_axis ); - VCALL_PTR0R( Rect3, get_longest_axis_index ); - VCALL_PTR0R( Rect3, get_longest_axis_size ); - VCALL_PTR0R( Rect3, get_shortest_axis ); - VCALL_PTR0R( Rect3, get_shortest_axis_index ); - VCALL_PTR0R( Rect3, get_shortest_axis_size ); - VCALL_PTR1R( Rect3, expand ); - VCALL_PTR1R( Rect3, grow ); - VCALL_PTR1R( Rect3, get_endpoint ); - - VCALL_PTR0R( Transform2D, inverse ); - VCALL_PTR0R( Transform2D, affine_inverse ); - VCALL_PTR0R( Transform2D, get_rotation ); - VCALL_PTR0R( Transform2D, get_origin ); - VCALL_PTR0R( Transform2D, get_scale ); - VCALL_PTR0R( Transform2D, orthonormalized ); - VCALL_PTR1R( Transform2D, rotated ); - VCALL_PTR1R( Transform2D, scaled ); - VCALL_PTR1R( Transform2D, translated ); - VCALL_PTR2R( Transform2D, interpolate_with ); - - static void _call_Transform2D_xform(Variant& r_ret,Variant& p_self,const Variant** p_args) { - - switch(p_args[0]->type) { - - case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform( p_args[0]->operator Vector2()); return; - case Variant::RECT2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform( p_args[0]->operator Rect2()); return; - default: r_ret=Variant(); + VCALL_PTR0R(Rect3, get_area); + VCALL_PTR0R(Rect3, has_no_area); + VCALL_PTR0R(Rect3, has_no_surface); + VCALL_PTR1R(Rect3, intersects); + VCALL_PTR1R(Rect3, encloses); + VCALL_PTR1R(Rect3, merge); + VCALL_PTR1R(Rect3, intersection); + VCALL_PTR1R(Rect3, intersects_plane); + VCALL_PTR2R(Rect3, intersects_segment); + VCALL_PTR1R(Rect3, has_point); + VCALL_PTR1R(Rect3, get_support); + VCALL_PTR0R(Rect3, get_longest_axis); + VCALL_PTR0R(Rect3, get_longest_axis_index); + VCALL_PTR0R(Rect3, get_longest_axis_size); + VCALL_PTR0R(Rect3, get_shortest_axis); + VCALL_PTR0R(Rect3, get_shortest_axis_index); + VCALL_PTR0R(Rect3, get_shortest_axis_size); + VCALL_PTR1R(Rect3, expand); + VCALL_PTR1R(Rect3, grow); + VCALL_PTR1R(Rect3, get_endpoint); + + VCALL_PTR0R(Transform2D, inverse); + VCALL_PTR0R(Transform2D, affine_inverse); + VCALL_PTR0R(Transform2D, get_rotation); + VCALL_PTR0R(Transform2D, get_origin); + VCALL_PTR0R(Transform2D, get_scale); + VCALL_PTR0R(Transform2D, orthonormalized); + VCALL_PTR1R(Transform2D, rotated); + VCALL_PTR1R(Transform2D, scaled); + VCALL_PTR1R(Transform2D, translated); + VCALL_PTR2R(Transform2D, interpolate_with); + + static void _call_Transform2D_xform(Variant &r_ret, Variant &p_self, const Variant **p_args) { + + switch (p_args[0]->type) { + + case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform(p_args[0]->operator Vector2()); return; + case Variant::RECT2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform(p_args[0]->operator Rect2()); return; + default: r_ret = Variant(); } - } - static void _call_Transform2D_xform_inv(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Transform2D_xform_inv(Variant &r_ret, Variant &p_self, const Variant **p_args) { - switch(p_args[0]->type) { + switch (p_args[0]->type) { - case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Vector2()); return; - case Variant::RECT2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Rect2()); return; - default: r_ret=Variant(); + case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Vector2()); return; + case Variant::RECT2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Rect2()); return; + default: r_ret = Variant(); } } - static void _call_Transform2D_basis_xform(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Transform2D_basis_xform(Variant &r_ret, Variant &p_self, const Variant **p_args) { - switch(p_args[0]->type) { + switch (p_args[0]->type) { - case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->basis_xform( p_args[0]->operator Vector2()); return; - default: r_ret=Variant(); + case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->basis_xform(p_args[0]->operator Vector2()); return; + default: r_ret = Variant(); } - } - static void _call_Transform2D_basis_xform_inv(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Transform2D_basis_xform_inv(Variant &r_ret, Variant &p_self, const Variant **p_args) { - switch(p_args[0]->type) { + switch (p_args[0]->type) { - case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->basis_xform_inv( p_args[0]->operator Vector2()); return; - default: r_ret=Variant(); + case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->basis_xform_inv(p_args[0]->operator Vector2()); return; + default: r_ret = Variant(); } } - - VCALL_PTR0R( Basis, inverse ); - VCALL_PTR0R( Basis, transposed ); - VCALL_PTR0R( Basis, determinant ); - VCALL_PTR2R( Basis, rotated ); - VCALL_PTR1R( Basis, scaled ); - VCALL_PTR0R( Basis, get_scale ); - VCALL_PTR0R( Basis, get_euler ); - VCALL_PTR1R( Basis, tdotx ); - VCALL_PTR1R( Basis, tdoty ); - VCALL_PTR1R( Basis, tdotz ); - VCALL_PTR1R( Basis, xform ); - VCALL_PTR1R( Basis, xform_inv ); - VCALL_PTR0R( Basis, get_orthogonal_index ); - VCALL_PTR0R( Basis, orthonormalized ); - - - VCALL_PTR0R( Transform, inverse ); - VCALL_PTR0R( Transform, affine_inverse ); - VCALL_PTR2R( Transform, rotated ); - VCALL_PTR1R( Transform, scaled ); - VCALL_PTR1R( Transform, translated ); - VCALL_PTR0R( Transform, orthonormalized ); - VCALL_PTR2R( Transform, looking_at ); - - static void _call_Transform_xform(Variant& r_ret,Variant& p_self,const Variant** p_args) { - - switch(p_args[0]->type) { - - case Variant::VECTOR3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform( p_args[0]->operator Vector3()); return; - case Variant::PLANE: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform( p_args[0]->operator Plane()); return; - case Variant::RECT3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform( p_args[0]->operator Rect3()); return; - default: r_ret=Variant(); + VCALL_PTR0R(Basis, inverse); + VCALL_PTR0R(Basis, transposed); + VCALL_PTR0R(Basis, determinant); + VCALL_PTR2R(Basis, rotated); + VCALL_PTR1R(Basis, scaled); + VCALL_PTR0R(Basis, get_scale); + VCALL_PTR0R(Basis, get_euler); + VCALL_PTR1R(Basis, tdotx); + VCALL_PTR1R(Basis, tdoty); + VCALL_PTR1R(Basis, tdotz); + VCALL_PTR1R(Basis, xform); + VCALL_PTR1R(Basis, xform_inv); + VCALL_PTR0R(Basis, get_orthogonal_index); + VCALL_PTR0R(Basis, orthonormalized); + + VCALL_PTR0R(Transform, inverse); + VCALL_PTR0R(Transform, affine_inverse); + VCALL_PTR2R(Transform, rotated); + VCALL_PTR1R(Transform, scaled); + VCALL_PTR1R(Transform, translated); + VCALL_PTR0R(Transform, orthonormalized); + VCALL_PTR2R(Transform, looking_at); + + static void _call_Transform_xform(Variant &r_ret, Variant &p_self, const Variant **p_args) { + + switch (p_args[0]->type) { + + case Variant::VECTOR3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform(p_args[0]->operator Vector3()); return; + case Variant::PLANE: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform(p_args[0]->operator Plane()); return; + case Variant::RECT3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform(p_args[0]->operator Rect3()); return; + default: r_ret = Variant(); } - } - static void _call_Transform_xform_inv(Variant& r_ret,Variant& p_self,const Variant** p_args) { + static void _call_Transform_xform_inv(Variant &r_ret, Variant &p_self, const Variant **p_args) { - switch(p_args[0]->type) { + switch (p_args[0]->type) { - case Variant::VECTOR3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Vector3()); return; - case Variant::PLANE: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Plane()); return; - case Variant::RECT3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Rect3()); return; - default: r_ret=Variant(); + case Variant::VECTOR3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Vector3()); return; + case Variant::PLANE: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Plane()); return; + case Variant::RECT3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Rect3()); return; + default: r_ret = Variant(); } } -/* + /* VCALL_PTR0( Transform, invert ); VCALL_PTR0( Transform, affine_invert ); VCALL_PTR2( Transform, rotate ); @@ -768,21 +747,19 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var VCALL_PTR1( Transform, translate ); VCALL_PTR0( Transform, orthonormalize ); */ - VCALL_PTR0R( InputEvent, is_pressed ); - VCALL_PTR1R( InputEvent, is_action ); - VCALL_PTR1R( InputEvent, is_action_pressed ); - VCALL_PTR1R( InputEvent, is_action_released ); - VCALL_PTR0R( InputEvent, is_echo ); - VCALL_PTR2( InputEvent, set_as_action ); + VCALL_PTR0R(InputEvent, is_pressed); + VCALL_PTR1R(InputEvent, is_action); + VCALL_PTR1R(InputEvent, is_action_pressed); + VCALL_PTR1R(InputEvent, is_action_released); + VCALL_PTR0R(InputEvent, is_echo); + VCALL_PTR2(InputEvent, set_as_action); struct ConstructData { - int arg_count; Vector<Variant::Type> arg_types; Vector<String> arg_names; VariantConstructFunc func; - }; struct ConstructFunc { @@ -790,180 +767,179 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var List<ConstructData> constructors; }; - static ConstructFunc* construct_funcs; + static ConstructFunc *construct_funcs; - static void Vector2_init1(Variant& r_ret,const Variant** p_args) { + static void Vector2_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Vector2(*p_args[0],*p_args[1]); + r_ret = Vector2(*p_args[0], *p_args[1]); } - static void Rect2_init1(Variant& r_ret,const Variant** p_args) { + static void Rect2_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Rect2(*p_args[0],*p_args[1]); + r_ret = Rect2(*p_args[0], *p_args[1]); } - static void Rect2_init2(Variant& r_ret,const Variant** p_args) { + static void Rect2_init2(Variant &r_ret, const Variant **p_args) { - r_ret=Rect2(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); + r_ret = Rect2(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } - static void Transform2D_init2(Variant& r_ret,const Variant** p_args) { + static void Transform2D_init2(Variant &r_ret, const Variant **p_args) { Transform2D m(*p_args[0], *p_args[1]); - r_ret=m; + r_ret = m; } - static void Transform2D_init3(Variant& r_ret,const Variant** p_args) { + static void Transform2D_init3(Variant &r_ret, const Variant **p_args) { Transform2D m; - m[0]=*p_args[0]; - m[1]=*p_args[1]; - m[2]=*p_args[2]; - r_ret=m; + m[0] = *p_args[0]; + m[1] = *p_args[1]; + m[2] = *p_args[2]; + r_ret = m; } - static void Vector3_init1(Variant& r_ret,const Variant** p_args) { + static void Vector3_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Vector3(*p_args[0],*p_args[1],*p_args[2]); + r_ret = Vector3(*p_args[0], *p_args[1], *p_args[2]); } - static void Plane_init1(Variant& r_ret,const Variant** p_args) { + static void Plane_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Plane(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); + r_ret = Plane(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } - static void Plane_init2(Variant& r_ret,const Variant** p_args) { + static void Plane_init2(Variant &r_ret, const Variant **p_args) { - r_ret=Plane(*p_args[0],*p_args[1],*p_args[2]); + r_ret = Plane(*p_args[0], *p_args[1], *p_args[2]); } - static void Plane_init3(Variant& r_ret,const Variant** p_args) { + static void Plane_init3(Variant &r_ret, const Variant **p_args) { - r_ret=Plane(p_args[0]->operator Vector3(),p_args[1]->operator real_t()); + r_ret = Plane(p_args[0]->operator Vector3(), p_args[1]->operator real_t()); } - static void Plane_init4(Variant& r_ret,const Variant** p_args) { + static void Plane_init4(Variant &r_ret, const Variant **p_args) { - r_ret=Plane(p_args[0]->operator Vector3(),p_args[1]->operator Vector3()); + r_ret = Plane(p_args[0]->operator Vector3(), p_args[1]->operator Vector3()); } - static void Quat_init1(Variant& r_ret,const Variant** p_args) { + static void Quat_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Quat(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); + r_ret = Quat(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } - static void Quat_init2(Variant& r_ret,const Variant** p_args) { + static void Quat_init2(Variant &r_ret, const Variant **p_args) { - r_ret=Quat(((Vector3)(*p_args[0])),((float)(*p_args[1]))); - } + r_ret = Quat(((Vector3)(*p_args[0])), ((float)(*p_args[1]))); + } - static void Color_init1(Variant& r_ret,const Variant** p_args) { + static void Color_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Color(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); + r_ret = Color(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); } - static void Color_init2(Variant& r_ret,const Variant** p_args) { + static void Color_init2(Variant &r_ret, const Variant **p_args) { - r_ret=Color(*p_args[0],*p_args[1],*p_args[2]); + r_ret = Color(*p_args[0], *p_args[1], *p_args[2]); } - static void Color_init3(Variant& r_ret,const Variant** p_args) { + static void Color_init3(Variant &r_ret, const Variant **p_args) { - r_ret=Color::html(*p_args[0]); + r_ret = Color::html(*p_args[0]); } - static void Color_init4(Variant& r_ret,const Variant** p_args) { + static void Color_init4(Variant &r_ret, const Variant **p_args) { - r_ret=Color::hex(*p_args[0]); + r_ret = Color::hex(*p_args[0]); } - static void Rect3_init1(Variant& r_ret,const Variant** p_args) { + static void Rect3_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Rect3(*p_args[0],*p_args[1]); + r_ret = Rect3(*p_args[0], *p_args[1]); } - static void Basis_init1(Variant& r_ret,const Variant** p_args) { + static void Basis_init1(Variant &r_ret, const Variant **p_args) { Basis m; - m.set_axis(0,*p_args[0]); - m.set_axis(1,*p_args[1]); - m.set_axis(2,*p_args[2]); - r_ret=m; + m.set_axis(0, *p_args[0]); + m.set_axis(1, *p_args[1]); + m.set_axis(2, *p_args[2]); + r_ret = m; } - static void Basis_init2(Variant& r_ret,const Variant** p_args) { + static void Basis_init2(Variant &r_ret, const Variant **p_args) { - r_ret=Basis(p_args[0]->operator Vector3(),p_args[1]->operator real_t()); + r_ret = Basis(p_args[0]->operator Vector3(), p_args[1]->operator real_t()); } - static void Transform_init1(Variant& r_ret,const Variant** p_args) { + static void Transform_init1(Variant &r_ret, const Variant **p_args) { Transform t; - t.basis.set_axis(0,*p_args[0]); - t.basis.set_axis(1,*p_args[1]); - t.basis.set_axis(2,*p_args[2]); - t.origin=*p_args[3]; - r_ret=t; + t.basis.set_axis(0, *p_args[0]); + t.basis.set_axis(1, *p_args[1]); + t.basis.set_axis(2, *p_args[2]); + t.origin = *p_args[3]; + r_ret = t; } - static void Transform_init2(Variant& r_ret,const Variant** p_args) { + static void Transform_init2(Variant &r_ret, const Variant **p_args) { - r_ret=Transform(p_args[0]->operator Basis(),p_args[1]->operator Vector3()); + r_ret = Transform(p_args[0]->operator Basis(), p_args[1]->operator Vector3()); } - static void Image_init1(Variant& r_ret, const Variant** p_args) { + static void Image_init1(Variant &r_ret, const Variant **p_args) { - r_ret=Image(*p_args[0],*p_args[1],*p_args[2],Image::Format(p_args[3]->operator int())); + r_ret = Image(*p_args[0], *p_args[1], *p_args[2], Image::Format(p_args[3]->operator int())); } - static void add_constructor(VariantConstructFunc p_func,const Variant::Type p_type, - const String& p_name1="", const Variant::Type p_type1=Variant::NIL, - const String& p_name2="", const Variant::Type p_type2=Variant::NIL, - const String& p_name3="", const Variant::Type p_type3=Variant::NIL, - const String& p_name4="", const Variant::Type p_type4=Variant::NIL ) { + static void add_constructor(VariantConstructFunc p_func, const Variant::Type p_type, + const String &p_name1 = "", const Variant::Type p_type1 = Variant::NIL, + const String &p_name2 = "", const Variant::Type p_type2 = Variant::NIL, + const String &p_name3 = "", const Variant::Type p_type3 = Variant::NIL, + const String &p_name4 = "", const Variant::Type p_type4 = Variant::NIL) { ConstructData cd; - cd.func=p_func; - cd.arg_count=0; + cd.func = p_func; + cd.arg_count = 0; - if (p_name1=="") + if (p_name1 == "") goto end; cd.arg_count++; cd.arg_names.push_back(p_name1); cd.arg_types.push_back(p_type1); - if (p_name2=="") + if (p_name2 == "") goto end; cd.arg_count++; cd.arg_names.push_back(p_name2); cd.arg_types.push_back(p_type2); - if (p_name3=="") + if (p_name3 == "") goto end; cd.arg_count++; cd.arg_names.push_back(p_name3); cd.arg_types.push_back(p_type3); - if (p_name4=="") + if (p_name4 == "") goto end; cd.arg_count++; cd.arg_names.push_back(p_name4); cd.arg_types.push_back(p_type4); - end: + end: construct_funcs[p_type].constructors.push_back(cd); } - struct ConstantData { - Map<StringName,int> value; + Map<StringName, int> value; #ifdef DEBUG_ENABLED List<StringName> value_ordered; #endif }; - static ConstantData* constant_data; + static ConstantData *constant_data; static void add_constant(int p_type, StringName p_constant_name, int p_constant_value) { @@ -971,198 +947,213 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var #ifdef DEBUG_ENABLED constant_data[p_type].value_ordered.push_back(p_constant_name); #endif - } - }; -_VariantCall::TypeFunc* _VariantCall::type_funcs=NULL; -_VariantCall::ConstructFunc* _VariantCall::construct_funcs=NULL; -_VariantCall::ConstantData* _VariantCall::constant_data=NULL; +_VariantCall::TypeFunc *_VariantCall::type_funcs = NULL; +_VariantCall::ConstructFunc *_VariantCall::construct_funcs = NULL; +_VariantCall::ConstantData *_VariantCall::constant_data = NULL; - -Variant Variant::call(const StringName& p_method,const Variant** p_args,int p_argcount,CallError &r_error) { +Variant Variant::call(const StringName &p_method, const Variant **p_args, int p_argcount, CallError &r_error) { Variant ret; - call_ptr(p_method,p_args,p_argcount,&ret,r_error); + call_ptr(p_method, p_args, p_argcount, &ret, r_error); return ret; } -void Variant::call_ptr(const StringName& p_method,const Variant** p_args,int p_argcount,Variant* r_ret,CallError &r_error) { +void Variant::call_ptr(const StringName &p_method, const Variant **p_args, int p_argcount, Variant *r_ret, CallError &r_error) { Variant ret; - if (type==Variant::OBJECT) { + if (type == Variant::OBJECT) { //call object Object *obj = _get_obj().obj; if (!obj) { - r_error.error=CallError::CALL_ERROR_INSTANCE_IS_NULL; + r_error.error = CallError::CALL_ERROR_INSTANCE_IS_NULL; return; } #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { //only if debugging! if (!ObjectDB::instance_validate(obj)) { - r_error.error=CallError::CALL_ERROR_INSTANCE_IS_NULL; + r_error.error = CallError::CALL_ERROR_INSTANCE_IS_NULL; return; } } - #endif - ret=_get_obj().obj->call(p_method,p_args,p_argcount,r_error); + ret = _get_obj().obj->call(p_method, p_args, p_argcount, r_error); - //else if (type==Variant::METHOD) { + //else if (type==Variant::METHOD) { } else { - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; - Map<StringName,_VariantCall::FuncData>::Element *E=_VariantCall::type_funcs[type].functions.find(p_method); + Map<StringName, _VariantCall::FuncData>::Element *E = _VariantCall::type_funcs[type].functions.find(p_method); #ifdef DEBUG_ENABLED if (!E) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return; } #endif - _VariantCall::FuncData& funcdata = E->get(); - funcdata.call(ret,*this,p_args,p_argcount,r_error); + _VariantCall::FuncData &funcdata = E->get(); + funcdata.call(ret, *this, p_args, p_argcount, r_error); } - if (r_error.error==Variant::CallError::CALL_OK && r_ret) - *r_ret=ret; + if (r_error.error == Variant::CallError::CALL_OK && r_ret) + *r_ret = ret; } -#define VCALL(m_type,m_method) _VariantCall::_call_##m_type##_##m_method +#define VCALL(m_type, m_method) _VariantCall::_call_##m_type##_##m_method +Variant Variant::construct(const Variant::Type p_type, const Variant **p_args, int p_argcount, CallError &r_error, bool p_strict) { -Variant Variant::construct(const Variant::Type p_type, const Variant** p_args, int p_argcount, CallError &r_error, bool p_strict) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + ERR_FAIL_INDEX_V(p_type, VARIANT_MAX, Variant()); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - ERR_FAIL_INDEX_V(p_type,VARIANT_MAX,Variant()); + r_error.error = Variant::CallError::CALL_OK; + if (p_argcount == 0) { //generic construct - r_error.error=Variant::CallError::CALL_OK; - if (p_argcount==0) { //generic construct - - switch(p_type) { - case NIL: return Variant(); + switch (p_type) { + case NIL: + return Variant(); // atomic types - case BOOL: return Variant( false ); + case BOOL: return Variant(false); case INT: return 0; case REAL: return 0.0f; - case STRING: return String(); + case STRING: + return String(); // math types - case VECTOR2: return Vector2(); // 5 + case VECTOR2: + return Vector2(); // 5 case RECT2: return Rect2(); case VECTOR3: return Vector3(); case TRANSFORM2D: return Transform2D(); case PLANE: return Plane(); case QUAT: return Quat(); - case RECT3: return Rect3(); // 10 + case RECT3: + return Rect3(); // 10 case BASIS: return Basis(); - case TRANSFORM: return Transform(); + case TRANSFORM: + return Transform(); // misc types case COLOR: return Color(); case IMAGE: return Image(); - case NODE_PATH: return NodePath(); // 15 + case NODE_PATH: + return NodePath(); // 15 case _RID: return RID(); - case OBJECT: return (Object*)NULL; + case OBJECT: return (Object *)NULL; case INPUT_EVENT: return InputEvent(); case DICTIONARY: return Dictionary(); - case ARRAY: return Array(); // 20 + case ARRAY: + return Array(); // 20 case POOL_BYTE_ARRAY: return PoolByteArray(); case POOL_INT_ARRAY: return PoolIntArray(); case POOL_REAL_ARRAY: return PoolRealArray(); case POOL_STRING_ARRAY: return PoolStringArray(); - case POOL_VECTOR2_ARRAY: return PoolVector2Array(); // 25 + case POOL_VECTOR2_ARRAY: + return PoolVector2Array(); // 25 case POOL_VECTOR3_ARRAY: return PoolVector3Array(); case POOL_COLOR_ARRAY: return PoolColorArray(); default: return Variant(); } - } else if (p_argcount>1) { + } else if (p_argcount > 1) { - _VariantCall::ConstructFunc & c = _VariantCall::construct_funcs[p_type]; + _VariantCall::ConstructFunc &c = _VariantCall::construct_funcs[p_type]; - for(List<_VariantCall::ConstructData>::Element *E=c.constructors.front();E;E=E->next()) { + for (List<_VariantCall::ConstructData>::Element *E = c.constructors.front(); E; E = E->next()) { const _VariantCall::ConstructData &cd = E->get(); - if (cd.arg_count!=p_argcount) + if (cd.arg_count != p_argcount) continue; //validate parameters - for(int i=0;i<cd.arg_count;i++) { - if (!Variant::can_convert(p_args[i]->type,cd.arg_types[i])) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; //no such constructor - r_error.argument=i; - r_error.expected=cd.arg_types[i]; + for (int i = 0; i < cd.arg_count; i++) { + if (!Variant::can_convert(p_args[i]->type, cd.arg_types[i])) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; //no such constructor + r_error.argument = i; + r_error.expected = cd.arg_types[i]; return Variant(); } } Variant v; - cd.func(v,p_args); + cd.func(v, p_args); return v; } - - } else if (p_argcount==1 && p_args[0]->type==p_type) { + } else if (p_argcount == 1 && p_args[0]->type == p_type) { return *p_args[0]; //copy construct - } else if (p_argcount==1 && (!p_strict || Variant::can_convert(p_args[0]->type,p_type))) { + } else if (p_argcount == 1 && (!p_strict || Variant::can_convert(p_args[0]->type, p_type))) { //near match construct - switch(p_type) { + switch (p_type) { case NIL: { return Variant(); } break; - case BOOL: { return Variant(bool(*p_args[0])); } - case INT: { return (int(*p_args[0])); } - case REAL: { return real_t(*p_args[0]); } - case STRING: { return String(*p_args[0]); } - case VECTOR2: { return Vector2(*p_args[0]); } + case BOOL: { + return Variant(bool(*p_args[0])); + } + case INT: { + return (int(*p_args[0])); + } + case REAL: { + return real_t(*p_args[0]); + } + case STRING: { + return String(*p_args[0]); + } + case VECTOR2: { + return Vector2(*p_args[0]); + } case RECT2: return (Rect2(*p_args[0])); case VECTOR3: return (Vector3(*p_args[0])); case PLANE: return (Plane(*p_args[0])); case QUAT: return (Quat(*p_args[0])); - case RECT3: return (Rect3(*p_args[0])); // 10 + case RECT3: + return (Rect3(*p_args[0])); // 10 case BASIS: return (Basis(p_args[0]->operator Basis())); - case TRANSFORM: return (Transform(p_args[0]->operator Transform())); + case TRANSFORM: + return (Transform(p_args[0]->operator Transform())); // misc types case COLOR: return p_args[0]->type == Variant::STRING ? Color::html(*p_args[0]) : Color::hex(*p_args[0]); case IMAGE: return (Image(*p_args[0])); - case NODE_PATH: return (NodePath(p_args[0]->operator NodePath())); // 15 + case NODE_PATH: + return (NodePath(p_args[0]->operator NodePath())); // 15 case _RID: return (RID(*p_args[0])); - case OBJECT: return ((Object*)(p_args[0]->operator Object *())); + case OBJECT: return ((Object *)(p_args[0]->operator Object *())); case INPUT_EVENT: return (InputEvent(*p_args[0])); case DICTIONARY: return p_args[0]->operator Dictionary(); - case ARRAY: return p_args[0]->operator Array(); // 20 + case ARRAY: + return p_args[0]->operator Array(); // 20 // arrays case POOL_BYTE_ARRAY: return (PoolByteArray(*p_args[0])); case POOL_INT_ARRAY: return (PoolIntArray(*p_args[0])); case POOL_REAL_ARRAY: return (PoolRealArray(*p_args[0])); case POOL_STRING_ARRAY: return (PoolStringArray(*p_args[0])); - case POOL_VECTOR2_ARRAY: return (PoolVector2Array(*p_args[0])); // 25 + case POOL_VECTOR2_ARRAY: + return (PoolVector2Array(*p_args[0])); // 25 case POOL_VECTOR3_ARRAY: return (PoolVector3Array(*p_args[0])); case POOL_COLOR_ARRAY: return (PoolColorArray(*p_args[0])); default: return Variant(); } } - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; //no such constructor + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; //no such constructor return Variant(); } +bool Variant::has_method(const StringName &p_method) const { -bool Variant::has_method(const StringName& p_method) const { - - - if (type==OBJECT) { - Object *obj = operator Object*(); + if (type == OBJECT) { + Object *obj = operator Object *(); if (!obj) return false; #ifdef DEBUG_ENABLED @@ -1171,367 +1162,351 @@ bool Variant::has_method(const StringName& p_method) const { #endif return obj->has_method(p_method); #ifdef DEBUG_ENABLED - } } #endif } - const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[type]; return fd.functions.has(p_method); - } -Vector<Variant::Type> Variant::get_method_argument_types(Variant::Type p_type,const StringName& p_method) { +Vector<Variant::Type> Variant::get_method_argument_types(Variant::Type p_type, const StringName &p_method) { const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type]; - const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method); + const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method); if (!E) return Vector<Variant::Type>(); return E->get().arg_types; } -Vector<StringName> Variant::get_method_argument_names(Variant::Type p_type,const StringName& p_method) { - +Vector<StringName> Variant::get_method_argument_names(Variant::Type p_type, const StringName &p_method) { const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type]; - const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method); + const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method); if (!E) return Vector<StringName>(); return E->get().arg_names; - } -Variant::Type Variant::get_method_return_type(Variant::Type p_type,const StringName& p_method,bool* r_has_return) { +Variant::Type Variant::get_method_return_type(Variant::Type p_type, const StringName &p_method, bool *r_has_return) { const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type]; - const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method); + const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method); if (!E) return Variant::NIL; if (r_has_return) - *r_has_return=E->get().return_type; + *r_has_return = E->get().return_type; return E->get().return_type; } -Vector<Variant> Variant::get_method_default_arguments(Variant::Type p_type,const StringName& p_method) { +Vector<Variant> Variant::get_method_default_arguments(Variant::Type p_type, const StringName &p_method) { const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type]; - const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method); + const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method); if (!E) return Vector<Variant>(); return E->get().default_args; - } void Variant::get_method_list(List<MethodInfo> *p_list) const { - const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[type]; - for (const Map<StringName,_VariantCall::FuncData>::Element *E=fd.functions.front();E;E=E->next()) { + for (const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.front(); E; E = E->next()) { const _VariantCall::FuncData &fd = E->get(); MethodInfo mi; - mi.name=E->key(); + mi.name = E->key(); - for(int i=0;i<fd.arg_types.size();i++) { + for (int i = 0; i < fd.arg_types.size(); i++) { PropertyInfo pi; - pi.type=fd.arg_types[i]; + pi.type = fd.arg_types[i]; #ifdef DEBUG_ENABLED - pi.name=fd.arg_names[i]; + pi.name = fd.arg_names[i]; #endif mi.arguments.push_back(pi); } - mi.default_arguments=fd.default_args; + mi.default_arguments = fd.default_args; PropertyInfo ret; #ifdef DEBUG_ENABLED - ret.type=fd.return_type; + ret.type = fd.return_type; if (fd.returns) - ret.name="ret"; - mi.return_val=ret; + ret.name = "ret"; + mi.return_val = ret; #endif p_list->push_back(mi); } - } void Variant::get_constructor_list(Variant::Type p_type, List<MethodInfo> *p_list) { - ERR_FAIL_INDEX(p_type,VARIANT_MAX); + ERR_FAIL_INDEX(p_type, VARIANT_MAX); //custom constructors - for(const List<_VariantCall::ConstructData>::Element *E=_VariantCall::construct_funcs[p_type].constructors.front();E;E=E->next()) { + for (const List<_VariantCall::ConstructData>::Element *E = _VariantCall::construct_funcs[p_type].constructors.front(); E; E = E->next()) { const _VariantCall::ConstructData &cd = E->get(); MethodInfo mi; - mi.name=Variant::get_type_name(p_type); - mi.return_val.type=p_type; - for(int i=0;i<cd.arg_count;i++) { + mi.name = Variant::get_type_name(p_type); + mi.return_val.type = p_type; + for (int i = 0; i < cd.arg_count; i++) { PropertyInfo pi; - pi.name=cd.arg_names[i]; - pi.type=cd.arg_types[i]; + pi.name = cd.arg_names[i]; + pi.type = cd.arg_types[i]; mi.arguments.push_back(pi); } p_list->push_back(mi); } //default constructors - for(int i=0;i<VARIANT_MAX;i++) { - if (i==p_type) + for (int i = 0; i < VARIANT_MAX; i++) { + if (i == p_type) continue; - if (!Variant::can_convert(Variant::Type(i),p_type)) + if (!Variant::can_convert(Variant::Type(i), p_type)) continue; MethodInfo mi; - mi.name=Variant::get_type_name(p_type); + mi.name = Variant::get_type_name(p_type); PropertyInfo pi; - pi.name="from"; - pi.type=Variant::Type(i); + pi.name = "from"; + pi.type = Variant::Type(i); mi.arguments.push_back(pi); - mi.return_val.type=p_type; + mi.return_val.type = p_type; p_list->push_back(mi); } } - void Variant::get_numeric_constants_for_type(Variant::Type p_type, List<StringName> *p_constants) { - ERR_FAIL_INDEX(p_type,Variant::VARIANT_MAX); + ERR_FAIL_INDEX(p_type, Variant::VARIANT_MAX); - _VariantCall::ConstantData& cd = _VariantCall::constant_data[p_type]; + _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type]; #ifdef DEBUG_ENABLED - for(List<StringName>::Element *E=cd.value_ordered.front();E;E=E->next()) { + for (List<StringName>::Element *E = cd.value_ordered.front(); E; E = E->next()) { p_constants->push_back(E->get()); #else - for(Map<StringName,int>::Element *E=cd.value.front();E;E=E->next()) { + for (Map<StringName, int>::Element *E = cd.value.front(); E; E = E->next()) { p_constants->push_back(E->key()); #endif } } +bool Variant::has_numeric_constant(Variant::Type p_type, const StringName &p_value) { -bool Variant::has_numeric_constant(Variant::Type p_type, const StringName& p_value) { - - ERR_FAIL_INDEX_V(p_type,Variant::VARIANT_MAX,false); - _VariantCall::ConstantData& cd = _VariantCall::constant_data[p_type]; + ERR_FAIL_INDEX_V(p_type, Variant::VARIANT_MAX, false); + _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type]; return cd.value.has(p_value); } -int Variant::get_numeric_constant_value(Variant::Type p_type, const StringName& p_value, bool *r_valid) { +int Variant::get_numeric_constant_value(Variant::Type p_type, const StringName &p_value, bool *r_valid) { if (r_valid) - *r_valid=false; - - ERR_FAIL_INDEX_V(p_type,Variant::VARIANT_MAX,0); - _VariantCall::ConstantData& cd = _VariantCall::constant_data[p_type]; + *r_valid = false; + ERR_FAIL_INDEX_V(p_type, Variant::VARIANT_MAX, 0); + _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type]; - Map<StringName,int>::Element *E = cd.value.find(p_value); + Map<StringName, int>::Element *E = cd.value.find(p_value); if (!E) { return -1; } if (r_valid) - *r_valid=true; + *r_valid = true; return E->get(); } - - void register_variant_methods() { - _VariantCall::type_funcs = memnew_arr(_VariantCall::TypeFunc,Variant::VARIANT_MAX ); + _VariantCall::type_funcs = memnew_arr(_VariantCall::TypeFunc, Variant::VARIANT_MAX); - _VariantCall::construct_funcs = memnew_arr(_VariantCall::ConstructFunc,Variant::VARIANT_MAX ); + _VariantCall::construct_funcs = memnew_arr(_VariantCall::ConstructFunc, Variant::VARIANT_MAX); _VariantCall::constant_data = memnew_arr(_VariantCall::ConstantData, Variant::VARIANT_MAX); -#define ADDFUNC0(m_vtype,m_ret,m_class,m_method,m_defarg)\ -_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg); -#define ADDFUNC1(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_defarg)\ -_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)) ); -#define ADDFUNC2(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_arg2,m_argname2,m_defarg)\ -_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)),_VariantCall::Arg(Variant::m_arg2,_scs_create(m_argname2))); -#define ADDFUNC3(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_arg2,m_argname2,m_arg3,m_argname3,m_defarg)\ -_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)),_VariantCall::Arg(Variant::m_arg2,_scs_create(m_argname2)),_VariantCall::Arg(Variant::m_arg3,_scs_create(m_argname3))); -#define ADDFUNC4(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_arg2,m_argname2,m_arg3,m_argname3,m_arg4,m_argname4,m_defarg)\ -_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)),_VariantCall::Arg(Variant::m_arg2,_scs_create(m_argname2)),_VariantCall::Arg(Variant::m_arg3,_scs_create(m_argname3)),_VariantCall::Arg(Variant::m_arg4,_scs_create(m_argname4))); - +#define ADDFUNC0(m_vtype, m_ret, m_class, m_method, m_defarg) \ + _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg); +#define ADDFUNC1(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_defarg) \ + _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1))); +#define ADDFUNC2(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_arg2, m_argname2, m_defarg) \ + _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)), _VariantCall::Arg(Variant::m_arg2, _scs_create(m_argname2))); +#define ADDFUNC3(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_arg2, m_argname2, m_arg3, m_argname3, m_defarg) \ + _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)), _VariantCall::Arg(Variant::m_arg2, _scs_create(m_argname2)), _VariantCall::Arg(Variant::m_arg3, _scs_create(m_argname3))); +#define ADDFUNC4(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_arg2, m_argname2, m_arg3, m_argname3, m_arg4, m_argname4, m_defarg) \ + _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)), _VariantCall::Arg(Variant::m_arg2, _scs_create(m_argname2)), _VariantCall::Arg(Variant::m_arg3, _scs_create(m_argname3)), _VariantCall::Arg(Variant::m_arg4, _scs_create(m_argname4))); /* STRING */ - ADDFUNC1(STRING,INT,String,casecmp_to,STRING,"to",varray()); - ADDFUNC1(STRING,INT,String,nocasecmp_to,STRING,"to",varray()); - ADDFUNC0(STRING,INT,String,length,varray()); - ADDFUNC2(STRING,STRING,String,substr,INT,"from",INT,"len",varray()); - - ADDFUNC2(STRING,INT,String,find,STRING,"what",INT,"from",varray(0)); - - ADDFUNC1(STRING,INT,String,find_last,STRING,"what",varray()); - ADDFUNC2(STRING,INT,String,findn,STRING,"what",INT,"from",varray(0)); - ADDFUNC2(STRING,INT,String,rfind,STRING,"what",INT,"from",varray(-1)); - ADDFUNC2(STRING,INT,String,rfindn,STRING,"what",INT,"from",varray(-1)); - ADDFUNC1(STRING,BOOL,String,match,STRING,"expr",varray()); - ADDFUNC1(STRING,BOOL,String,matchn,STRING,"expr",varray()); - ADDFUNC1(STRING,BOOL,String,begins_with,STRING,"text",varray()); - ADDFUNC1(STRING,BOOL,String,ends_with,STRING,"text",varray()); - ADDFUNC1(STRING,BOOL,String,is_subsequence_of,STRING,"text",varray()); - ADDFUNC1(STRING,BOOL,String,is_subsequence_ofi,STRING,"text",varray()); - ADDFUNC0(STRING,POOL_STRING_ARRAY,String,bigrams,varray()); - ADDFUNC1(STRING,REAL,String,similarity,STRING,"text",varray()); - - ADDFUNC2(STRING,STRING,String,format,NIL,"values",STRING,"placeholder",varray("{_}")); - ADDFUNC2(STRING,STRING,String,replace,STRING,"what",STRING,"forwhat",varray()); - ADDFUNC2(STRING,STRING,String,replacen,STRING,"what",STRING,"forwhat",varray()); - ADDFUNC2(STRING,STRING,String,insert,INT,"pos",STRING,"what",varray()); - ADDFUNC0(STRING,STRING,String,capitalize,varray()); - ADDFUNC2(STRING,POOL_STRING_ARRAY,String,split,STRING,"divisor",BOOL,"allow_empty",varray(true)); - ADDFUNC2(STRING,POOL_REAL_ARRAY,String,split_floats,STRING,"divisor",BOOL,"allow_empty",varray(true)); - - ADDFUNC0(STRING,STRING,String,to_upper,varray()); - ADDFUNC0(STRING,STRING,String,to_lower,varray()); - - ADDFUNC1(STRING,STRING,String,left,INT,"pos",varray()); - ADDFUNC1(STRING,STRING,String,right,INT,"pos",varray()); - ADDFUNC2(STRING,STRING,String,strip_edges,BOOL,"left",BOOL,"right",varray(true,true)); - ADDFUNC0(STRING,STRING,String,get_extension,varray()); - ADDFUNC0(STRING,STRING,String,get_basename,varray()); - ADDFUNC1(STRING,STRING,String,plus_file,STRING,"file",varray()); - ADDFUNC1(STRING,INT,String,ord_at,INT,"at",varray()); - ADDFUNC2(STRING,NIL,String,erase,INT,"pos",INT,"chars", varray()); - ADDFUNC0(STRING,INT,String,hash,varray()); - ADDFUNC0(STRING,STRING,String,md5_text,varray()); - ADDFUNC0(STRING,STRING,String,sha256_text,varray()); - ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,md5_buffer,varray()); - ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,sha256_buffer,varray()); - ADDFUNC0(STRING,BOOL,String,empty,varray()); - ADDFUNC0(STRING,BOOL,String,is_abs_path,varray()); - ADDFUNC0(STRING,BOOL,String,is_rel_path,varray()); - ADDFUNC0(STRING,STRING,String,get_base_dir,varray()); - ADDFUNC0(STRING,STRING,String,get_file,varray()); - ADDFUNC0(STRING,STRING,String,xml_escape,varray()); - ADDFUNC0(STRING,STRING,String,xml_unescape,varray()); - ADDFUNC0(STRING,STRING,String,c_escape,varray()); - ADDFUNC0(STRING,STRING,String,c_unescape,varray()); - ADDFUNC0(STRING,STRING,String,json_escape,varray()); - ADDFUNC0(STRING,STRING,String,percent_encode,varray()); - ADDFUNC0(STRING,STRING,String,percent_decode,varray()); - ADDFUNC0(STRING,BOOL,String,is_valid_identifier,varray()); - ADDFUNC0(STRING,BOOL,String,is_valid_integer,varray()); - ADDFUNC0(STRING,BOOL,String,is_valid_float,varray()); - ADDFUNC0(STRING,BOOL,String,is_valid_html_color,varray()); - ADDFUNC0(STRING,BOOL,String,is_valid_ip_address,varray()); - ADDFUNC0(STRING,INT,String,to_int,varray()); - ADDFUNC0(STRING,REAL,String,to_float,varray()); - ADDFUNC0(STRING,INT,String,hex_to_int,varray()); - ADDFUNC1(STRING,STRING,String,pad_decimals,INT,"digits",varray()); - ADDFUNC1(STRING,STRING,String,pad_zeros,INT,"digits",varray()); - - ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,to_ascii,varray()); - ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,to_utf8,varray()); - - - - ADDFUNC0(VECTOR2,VECTOR2,Vector2,normalized,varray()); - ADDFUNC0(VECTOR2,REAL,Vector2,length,varray()); - ADDFUNC0(VECTOR2,REAL,Vector2,angle,varray()); - ADDFUNC0(VECTOR2,REAL,Vector2,length_squared,varray()); - ADDFUNC1(VECTOR2,REAL,Vector2,distance_to,VECTOR2,"to",varray()); - ADDFUNC1(VECTOR2,REAL,Vector2,distance_squared_to,VECTOR2,"to",varray()); - ADDFUNC1(VECTOR2,REAL,Vector2,angle_to,VECTOR2,"to",varray()); - ADDFUNC1(VECTOR2,REAL,Vector2,angle_to_point,VECTOR2,"to",varray()); - ADDFUNC2(VECTOR2,VECTOR2,Vector2,linear_interpolate,VECTOR2,"b",REAL,"t",varray()); - ADDFUNC4(VECTOR2,VECTOR2,Vector2,cubic_interpolate,VECTOR2,"b",VECTOR2,"pre_a",VECTOR2,"post_b",REAL,"t",varray()); - ADDFUNC1(VECTOR2,VECTOR2,Vector2,rotated,REAL,"phi",varray()); - ADDFUNC0(VECTOR2,VECTOR2,Vector2,tangent,varray()); - ADDFUNC0(VECTOR2,VECTOR2,Vector2,floor,varray()); - ADDFUNC1(VECTOR2,VECTOR2,Vector2,snapped,VECTOR2,"by",varray()); - ADDFUNC0(VECTOR2,REAL,Vector2,aspect,varray()); - ADDFUNC1(VECTOR2,REAL,Vector2,dot,VECTOR2,"with",varray()); - ADDFUNC1(VECTOR2,VECTOR2,Vector2,slide,VECTOR2,"vec",varray()); - ADDFUNC1(VECTOR2,VECTOR2,Vector2,reflect,VECTOR2,"vec",varray()); + ADDFUNC1(STRING, INT, String, casecmp_to, STRING, "to", varray()); + ADDFUNC1(STRING, INT, String, nocasecmp_to, STRING, "to", varray()); + ADDFUNC0(STRING, INT, String, length, varray()); + ADDFUNC2(STRING, STRING, String, substr, INT, "from", INT, "len", varray()); + + ADDFUNC2(STRING, INT, String, find, STRING, "what", INT, "from", varray(0)); + + ADDFUNC1(STRING, INT, String, find_last, STRING, "what", varray()); + ADDFUNC2(STRING, INT, String, findn, STRING, "what", INT, "from", varray(0)); + ADDFUNC2(STRING, INT, String, rfind, STRING, "what", INT, "from", varray(-1)); + ADDFUNC2(STRING, INT, String, rfindn, STRING, "what", INT, "from", varray(-1)); + ADDFUNC1(STRING, BOOL, String, match, STRING, "expr", varray()); + ADDFUNC1(STRING, BOOL, String, matchn, STRING, "expr", varray()); + ADDFUNC1(STRING, BOOL, String, begins_with, STRING, "text", varray()); + ADDFUNC1(STRING, BOOL, String, ends_with, STRING, "text", varray()); + ADDFUNC1(STRING, BOOL, String, is_subsequence_of, STRING, "text", varray()); + ADDFUNC1(STRING, BOOL, String, is_subsequence_ofi, STRING, "text", varray()); + ADDFUNC0(STRING, POOL_STRING_ARRAY, String, bigrams, varray()); + ADDFUNC1(STRING, REAL, String, similarity, STRING, "text", varray()); + + ADDFUNC2(STRING, STRING, String, format, NIL, "values", STRING, "placeholder", varray("{_}")); + ADDFUNC2(STRING, STRING, String, replace, STRING, "what", STRING, "forwhat", varray()); + ADDFUNC2(STRING, STRING, String, replacen, STRING, "what", STRING, "forwhat", varray()); + ADDFUNC2(STRING, STRING, String, insert, INT, "pos", STRING, "what", varray()); + ADDFUNC0(STRING, STRING, String, capitalize, varray()); + ADDFUNC2(STRING, POOL_STRING_ARRAY, String, split, STRING, "divisor", BOOL, "allow_empty", varray(true)); + ADDFUNC2(STRING, POOL_REAL_ARRAY, String, split_floats, STRING, "divisor", BOOL, "allow_empty", varray(true)); + + ADDFUNC0(STRING, STRING, String, to_upper, varray()); + ADDFUNC0(STRING, STRING, String, to_lower, varray()); + + ADDFUNC1(STRING, STRING, String, left, INT, "pos", varray()); + ADDFUNC1(STRING, STRING, String, right, INT, "pos", varray()); + ADDFUNC2(STRING, STRING, String, strip_edges, BOOL, "left", BOOL, "right", varray(true, true)); + ADDFUNC0(STRING, STRING, String, get_extension, varray()); + ADDFUNC0(STRING, STRING, String, get_basename, varray()); + ADDFUNC1(STRING, STRING, String, plus_file, STRING, "file", varray()); + ADDFUNC1(STRING, INT, String, ord_at, INT, "at", varray()); + ADDFUNC2(STRING, NIL, String, erase, INT, "pos", INT, "chars", varray()); + ADDFUNC0(STRING, INT, String, hash, varray()); + ADDFUNC0(STRING, STRING, String, md5_text, varray()); + ADDFUNC0(STRING, STRING, String, sha256_text, varray()); + ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, md5_buffer, varray()); + ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, sha256_buffer, varray()); + ADDFUNC0(STRING, BOOL, String, empty, varray()); + ADDFUNC0(STRING, BOOL, String, is_abs_path, varray()); + ADDFUNC0(STRING, BOOL, String, is_rel_path, varray()); + ADDFUNC0(STRING, STRING, String, get_base_dir, varray()); + ADDFUNC0(STRING, STRING, String, get_file, varray()); + ADDFUNC0(STRING, STRING, String, xml_escape, varray()); + ADDFUNC0(STRING, STRING, String, xml_unescape, varray()); + ADDFUNC0(STRING, STRING, String, c_escape, varray()); + ADDFUNC0(STRING, STRING, String, c_unescape, varray()); + ADDFUNC0(STRING, STRING, String, json_escape, varray()); + ADDFUNC0(STRING, STRING, String, percent_encode, varray()); + ADDFUNC0(STRING, STRING, String, percent_decode, varray()); + ADDFUNC0(STRING, BOOL, String, is_valid_identifier, varray()); + ADDFUNC0(STRING, BOOL, String, is_valid_integer, varray()); + ADDFUNC0(STRING, BOOL, String, is_valid_float, varray()); + ADDFUNC0(STRING, BOOL, String, is_valid_html_color, varray()); + ADDFUNC0(STRING, BOOL, String, is_valid_ip_address, varray()); + ADDFUNC0(STRING, INT, String, to_int, varray()); + ADDFUNC0(STRING, REAL, String, to_float, varray()); + ADDFUNC0(STRING, INT, String, hex_to_int, varray()); + ADDFUNC1(STRING, STRING, String, pad_decimals, INT, "digits", varray()); + ADDFUNC1(STRING, STRING, String, pad_zeros, INT, "digits", varray()); + + ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, to_ascii, varray()); + ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, to_utf8, varray()); + + ADDFUNC0(VECTOR2, VECTOR2, Vector2, normalized, varray()); + ADDFUNC0(VECTOR2, REAL, Vector2, length, varray()); + ADDFUNC0(VECTOR2, REAL, Vector2, angle, varray()); + ADDFUNC0(VECTOR2, REAL, Vector2, length_squared, varray()); + ADDFUNC1(VECTOR2, REAL, Vector2, distance_to, VECTOR2, "to", varray()); + ADDFUNC1(VECTOR2, REAL, Vector2, distance_squared_to, VECTOR2, "to", varray()); + ADDFUNC1(VECTOR2, REAL, Vector2, angle_to, VECTOR2, "to", varray()); + ADDFUNC1(VECTOR2, REAL, Vector2, angle_to_point, VECTOR2, "to", varray()); + ADDFUNC2(VECTOR2, VECTOR2, Vector2, linear_interpolate, VECTOR2, "b", REAL, "t", varray()); + ADDFUNC4(VECTOR2, VECTOR2, Vector2, cubic_interpolate, VECTOR2, "b", VECTOR2, "pre_a", VECTOR2, "post_b", REAL, "t", varray()); + ADDFUNC1(VECTOR2, VECTOR2, Vector2, rotated, REAL, "phi", varray()); + ADDFUNC0(VECTOR2, VECTOR2, Vector2, tangent, varray()); + ADDFUNC0(VECTOR2, VECTOR2, Vector2, floor, varray()); + ADDFUNC1(VECTOR2, VECTOR2, Vector2, snapped, VECTOR2, "by", varray()); + ADDFUNC0(VECTOR2, REAL, Vector2, aspect, varray()); + ADDFUNC1(VECTOR2, REAL, Vector2, dot, VECTOR2, "with", varray()); + ADDFUNC1(VECTOR2, VECTOR2, Vector2, slide, VECTOR2, "vec", varray()); + ADDFUNC1(VECTOR2, VECTOR2, Vector2, reflect, VECTOR2, "vec", varray()); //ADDFUNC1(VECTOR2,REAL,Vector2,cross,VECTOR2,"with",varray()); - ADDFUNC0(VECTOR2,VECTOR2,Vector2,abs,varray()); - ADDFUNC1(VECTOR2,VECTOR2,Vector2,clamped,REAL,"length",varray()); - - ADDFUNC0(RECT2,REAL,Rect2,get_area,varray()); - ADDFUNC1(RECT2,BOOL,Rect2,intersects,RECT2,"b",varray()); - ADDFUNC1(RECT2,BOOL,Rect2,encloses,RECT2,"b",varray()); - ADDFUNC0(RECT2,BOOL,Rect2,has_no_area,varray()); - ADDFUNC1(RECT2,RECT2,Rect2,clip,RECT2,"b",varray()); - ADDFUNC1(RECT2,RECT2,Rect2,merge,RECT2,"b",varray()); - ADDFUNC1(RECT2,BOOL,Rect2,has_point,VECTOR2,"point",varray()); - ADDFUNC1(RECT2,RECT2,Rect2,grow,REAL,"by",varray()); - ADDFUNC1(RECT2,RECT2,Rect2,expand,VECTOR2,"to",varray()); - - ADDFUNC0(VECTOR3,INT,Vector3,min_axis,varray()); - ADDFUNC0(VECTOR3,INT,Vector3,max_axis,varray()); - ADDFUNC0(VECTOR3,REAL,Vector3,length,varray()); - ADDFUNC0(VECTOR3,REAL,Vector3,length_squared,varray()); - ADDFUNC0(VECTOR3,VECTOR3,Vector3,normalized,varray()); - ADDFUNC0(VECTOR3,VECTOR3,Vector3,inverse,varray()); - ADDFUNC1(VECTOR3,VECTOR3,Vector3,snapped,REAL,"by",varray()); - ADDFUNC2(VECTOR3,VECTOR3,Vector3,rotated,VECTOR3,"axis",REAL,"phi",varray()); - ADDFUNC2(VECTOR3,VECTOR3,Vector3,linear_interpolate,VECTOR3,"b",REAL,"t",varray()); - ADDFUNC4(VECTOR3,VECTOR3,Vector3,cubic_interpolate,VECTOR3,"b",VECTOR3,"pre_a",VECTOR3,"post_b",REAL,"t",varray()); - ADDFUNC1(VECTOR3,REAL,Vector3,dot,VECTOR3,"b",varray()); - ADDFUNC1(VECTOR3,VECTOR3,Vector3,cross,VECTOR3,"b",varray()); - ADDFUNC1(VECTOR3,BASIS,Vector3,outer,VECTOR3,"b",varray()); - ADDFUNC0(VECTOR3,BASIS,Vector3,to_diagonal_matrix,varray()); - ADDFUNC0(VECTOR3,VECTOR3,Vector3,abs,varray()); - ADDFUNC0(VECTOR3,VECTOR3,Vector3,abs,varray()); - ADDFUNC0(VECTOR3,VECTOR3,Vector3,floor,varray()); - ADDFUNC0(VECTOR3,VECTOR3,Vector3,ceil,varray()); - ADDFUNC1(VECTOR3,REAL,Vector3,distance_to,VECTOR3,"b",varray()); - ADDFUNC1(VECTOR3,REAL,Vector3,distance_squared_to,VECTOR3,"b",varray()); - ADDFUNC1(VECTOR3,REAL,Vector3,angle_to,VECTOR3,"to",varray()); - ADDFUNC1(VECTOR3,VECTOR3,Vector3,slide,VECTOR3,"by",varray()); - ADDFUNC1(VECTOR3,VECTOR3,Vector3,reflect,VECTOR3,"by",varray()); - - ADDFUNC0(PLANE,PLANE,Plane,normalized,varray()); - ADDFUNC0(PLANE,VECTOR3,Plane,center,varray()); - ADDFUNC0(PLANE,VECTOR3,Plane,get_any_point,varray()); - ADDFUNC1(PLANE,BOOL,Plane,is_point_over,VECTOR3,"point",varray()); - ADDFUNC1(PLANE,REAL,Plane,distance_to,VECTOR3,"point",varray()); - ADDFUNC2(PLANE,BOOL,Plane,has_point,VECTOR3,"point",REAL,"epsilon",varray(CMP_EPSILON)); - ADDFUNC1(PLANE,VECTOR3,Plane,project,VECTOR3,"point",varray()); - ADDFUNC2(PLANE,VECTOR3,Plane,intersect_3,PLANE,"b",PLANE,"c",varray()); - ADDFUNC2(PLANE,VECTOR3,Plane,intersects_ray,VECTOR3,"from",VECTOR3,"dir",varray()); - ADDFUNC2(PLANE,VECTOR3,Plane,intersects_segment,VECTOR3,"begin",VECTOR3,"end",varray()); - - ADDFUNC0(QUAT,REAL,Quat,length,varray()); - ADDFUNC0(QUAT,REAL,Quat,length_squared,varray()); - ADDFUNC0(QUAT,QUAT,Quat,normalized,varray()); - ADDFUNC0(QUAT,QUAT,Quat,inverse,varray()); - ADDFUNC1(QUAT,REAL,Quat,dot,QUAT,"b",varray()); - ADDFUNC1(QUAT,VECTOR3,Quat,xform,VECTOR3,"v",varray()); - ADDFUNC2(QUAT,QUAT,Quat,slerp,QUAT,"b",REAL,"t",varray()); - ADDFUNC2(QUAT,QUAT,Quat,slerpni,QUAT,"b",REAL,"t",varray()); - ADDFUNC4(QUAT,QUAT,Quat,cubic_slerp,QUAT,"b",QUAT,"pre_a",QUAT,"post_b",REAL,"t",varray()); - - ADDFUNC0(COLOR,INT,Color,to_32,varray()); - ADDFUNC0(COLOR,INT,Color,to_ARGB32,varray()); - ADDFUNC0(COLOR,REAL,Color,gray,varray()); - ADDFUNC0(COLOR,COLOR,Color,inverted,varray()); - ADDFUNC0(COLOR,COLOR,Color,contrasted,varray()); - ADDFUNC2(COLOR,COLOR,Color,linear_interpolate,COLOR,"b",REAL,"t",varray()); - ADDFUNC1(COLOR,COLOR,Color,blend,COLOR,"over",varray()); - ADDFUNC1(COLOR,STRING,Color,to_html,BOOL,"with_alpha",varray(true)); + ADDFUNC0(VECTOR2, VECTOR2, Vector2, abs, varray()); + ADDFUNC1(VECTOR2, VECTOR2, Vector2, clamped, REAL, "length", varray()); + + ADDFUNC0(RECT2, REAL, Rect2, get_area, varray()); + ADDFUNC1(RECT2, BOOL, Rect2, intersects, RECT2, "b", varray()); + ADDFUNC1(RECT2, BOOL, Rect2, encloses, RECT2, "b", varray()); + ADDFUNC0(RECT2, BOOL, Rect2, has_no_area, varray()); + ADDFUNC1(RECT2, RECT2, Rect2, clip, RECT2, "b", varray()); + ADDFUNC1(RECT2, RECT2, Rect2, merge, RECT2, "b", varray()); + ADDFUNC1(RECT2, BOOL, Rect2, has_point, VECTOR2, "point", varray()); + ADDFUNC1(RECT2, RECT2, Rect2, grow, REAL, "by", varray()); + ADDFUNC1(RECT2, RECT2, Rect2, expand, VECTOR2, "to", varray()); + + ADDFUNC0(VECTOR3, INT, Vector3, min_axis, varray()); + ADDFUNC0(VECTOR3, INT, Vector3, max_axis, varray()); + ADDFUNC0(VECTOR3, REAL, Vector3, length, varray()); + ADDFUNC0(VECTOR3, REAL, Vector3, length_squared, varray()); + ADDFUNC0(VECTOR3, VECTOR3, Vector3, normalized, varray()); + ADDFUNC0(VECTOR3, VECTOR3, Vector3, inverse, varray()); + ADDFUNC1(VECTOR3, VECTOR3, Vector3, snapped, REAL, "by", varray()); + ADDFUNC2(VECTOR3, VECTOR3, Vector3, rotated, VECTOR3, "axis", REAL, "phi", varray()); + ADDFUNC2(VECTOR3, VECTOR3, Vector3, linear_interpolate, VECTOR3, "b", REAL, "t", varray()); + ADDFUNC4(VECTOR3, VECTOR3, Vector3, cubic_interpolate, VECTOR3, "b", VECTOR3, "pre_a", VECTOR3, "post_b", REAL, "t", varray()); + ADDFUNC1(VECTOR3, REAL, Vector3, dot, VECTOR3, "b", varray()); + ADDFUNC1(VECTOR3, VECTOR3, Vector3, cross, VECTOR3, "b", varray()); + ADDFUNC1(VECTOR3, BASIS, Vector3, outer, VECTOR3, "b", varray()); + ADDFUNC0(VECTOR3, BASIS, Vector3, to_diagonal_matrix, varray()); + ADDFUNC0(VECTOR3, VECTOR3, Vector3, abs, varray()); + ADDFUNC0(VECTOR3, VECTOR3, Vector3, abs, varray()); + ADDFUNC0(VECTOR3, VECTOR3, Vector3, floor, varray()); + ADDFUNC0(VECTOR3, VECTOR3, Vector3, ceil, varray()); + ADDFUNC1(VECTOR3, REAL, Vector3, distance_to, VECTOR3, "b", varray()); + ADDFUNC1(VECTOR3, REAL, Vector3, distance_squared_to, VECTOR3, "b", varray()); + ADDFUNC1(VECTOR3, REAL, Vector3, angle_to, VECTOR3, "to", varray()); + ADDFUNC1(VECTOR3, VECTOR3, Vector3, slide, VECTOR3, "by", varray()); + ADDFUNC1(VECTOR3, VECTOR3, Vector3, reflect, VECTOR3, "by", varray()); + + ADDFUNC0(PLANE, PLANE, Plane, normalized, varray()); + ADDFUNC0(PLANE, VECTOR3, Plane, center, varray()); + ADDFUNC0(PLANE, VECTOR3, Plane, get_any_point, varray()); + ADDFUNC1(PLANE, BOOL, Plane, is_point_over, VECTOR3, "point", varray()); + ADDFUNC1(PLANE, REAL, Plane, distance_to, VECTOR3, "point", varray()); + ADDFUNC2(PLANE, BOOL, Plane, has_point, VECTOR3, "point", REAL, "epsilon", varray(CMP_EPSILON)); + ADDFUNC1(PLANE, VECTOR3, Plane, project, VECTOR3, "point", varray()); + ADDFUNC2(PLANE, VECTOR3, Plane, intersect_3, PLANE, "b", PLANE, "c", varray()); + ADDFUNC2(PLANE, VECTOR3, Plane, intersects_ray, VECTOR3, "from", VECTOR3, "dir", varray()); + ADDFUNC2(PLANE, VECTOR3, Plane, intersects_segment, VECTOR3, "begin", VECTOR3, "end", varray()); + + ADDFUNC0(QUAT, REAL, Quat, length, varray()); + ADDFUNC0(QUAT, REAL, Quat, length_squared, varray()); + ADDFUNC0(QUAT, QUAT, Quat, normalized, varray()); + ADDFUNC0(QUAT, QUAT, Quat, inverse, varray()); + ADDFUNC1(QUAT, REAL, Quat, dot, QUAT, "b", varray()); + ADDFUNC1(QUAT, VECTOR3, Quat, xform, VECTOR3, "v", varray()); + ADDFUNC2(QUAT, QUAT, Quat, slerp, QUAT, "b", REAL, "t", varray()); + ADDFUNC2(QUAT, QUAT, Quat, slerpni, QUAT, "b", REAL, "t", varray()); + ADDFUNC4(QUAT, QUAT, Quat, cubic_slerp, QUAT, "b", QUAT, "pre_a", QUAT, "post_b", REAL, "t", varray()); + + ADDFUNC0(COLOR, INT, Color, to_32, varray()); + ADDFUNC0(COLOR, INT, Color, to_ARGB32, varray()); + ADDFUNC0(COLOR, REAL, Color, gray, varray()); + ADDFUNC0(COLOR, COLOR, Color, inverted, varray()); + ADDFUNC0(COLOR, COLOR, Color, contrasted, varray()); + ADDFUNC2(COLOR, COLOR, Color, linear_interpolate, COLOR, "b", REAL, "t", varray()); + ADDFUNC1(COLOR, COLOR, Color, blend, COLOR, "over", varray()); + ADDFUNC1(COLOR, STRING, Color, to_html, BOOL, "with_alpha", varray(true)); ADDFUNC0(IMAGE, INT, Image, get_format, varray()); ADDFUNC0(IMAGE, INT, Image, get_width, varray()); @@ -1549,312 +1524,302 @@ _VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCA ADDFUNC1(IMAGE, IMAGE, Image, converted, INT, "format", varray(0)); ADDFUNC0(IMAGE, NIL, Image, fix_alpha_edges, varray()); - ADDFUNC0(_RID,INT,RID,get_id,varray()); - - ADDFUNC0(NODE_PATH,BOOL,NodePath,is_absolute,varray()); - ADDFUNC0(NODE_PATH,INT,NodePath,get_name_count,varray()); - ADDFUNC1(NODE_PATH,STRING,NodePath,get_name,INT,"idx",varray()); - ADDFUNC0(NODE_PATH,INT,NodePath,get_subname_count,varray()); - ADDFUNC1(NODE_PATH,STRING,NodePath,get_subname,INT,"idx",varray()); - ADDFUNC0(NODE_PATH,STRING,NodePath,get_property,varray()); - ADDFUNC0(NODE_PATH,BOOL,NodePath,is_empty,varray()); - - ADDFUNC0(DICTIONARY,INT,Dictionary,size,varray()); - ADDFUNC0(DICTIONARY,BOOL,Dictionary,empty,varray()); - ADDFUNC0(DICTIONARY,NIL,Dictionary,clear,varray()); - ADDFUNC1(DICTIONARY,BOOL,Dictionary,has,NIL,"key",varray()); - ADDFUNC1(DICTIONARY,BOOL,Dictionary,has_all,ARRAY,"keys",varray()); - ADDFUNC1(DICTIONARY,NIL,Dictionary,erase,NIL,"key",varray()); - ADDFUNC0(DICTIONARY,INT,Dictionary,hash,varray()); - ADDFUNC0(DICTIONARY,ARRAY,Dictionary,keys,varray()); - ADDFUNC0(DICTIONARY,ARRAY,Dictionary,values,varray()); - - ADDFUNC0(ARRAY,INT,Array,size,varray()); - ADDFUNC0(ARRAY,BOOL,Array,empty,varray()); - ADDFUNC0(ARRAY,NIL,Array,clear,varray()); - ADDFUNC0(ARRAY,INT,Array,hash,varray()); - ADDFUNC1(ARRAY,NIL,Array,push_back,NIL,"value",varray()); - ADDFUNC1(ARRAY,NIL,Array,push_front,NIL,"value",varray()); - ADDFUNC1(ARRAY,NIL,Array,append,NIL,"value",varray()); - ADDFUNC1(ARRAY,NIL,Array,resize,INT,"pos",varray()); - ADDFUNC2(ARRAY,NIL,Array,insert,INT,"pos",NIL,"value",varray()); - ADDFUNC1(ARRAY,NIL,Array,remove,INT,"pos",varray()); - ADDFUNC1(ARRAY,NIL,Array,erase,NIL,"value",varray()); - ADDFUNC0(ARRAY,NIL,Array,front,varray()); - ADDFUNC0(ARRAY,NIL,Array,back,varray()); - ADDFUNC2(ARRAY,INT,Array,find,NIL,"what",INT,"from",varray(0)); - ADDFUNC2(ARRAY,INT,Array,rfind,NIL,"what",INT,"from",varray(-1)); - ADDFUNC1(ARRAY,INT,Array,find_last,NIL,"value",varray()); - ADDFUNC1(ARRAY,INT,Array,count,NIL,"value",varray()); - ADDFUNC1(ARRAY,BOOL,Array,has,NIL,"value",varray()); - ADDFUNC0(ARRAY,NIL,Array,pop_back,varray()); - ADDFUNC0(ARRAY,NIL,Array,pop_front,varray()); - ADDFUNC0(ARRAY,NIL,Array,sort,varray()); - ADDFUNC2(ARRAY,NIL,Array,sort_custom,OBJECT,"obj",STRING,"func",varray()); - ADDFUNC0(ARRAY,NIL,Array,invert,varray()); - - - ADDFUNC0(POOL_BYTE_ARRAY,INT,PoolByteArray,size,varray()); - ADDFUNC2(POOL_BYTE_ARRAY,NIL,PoolByteArray,set,INT,"idx",INT,"byte",varray()); - ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,push_back,INT,"byte",varray()); - ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,append,INT,"byte",varray()); - ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,append_array,POOL_BYTE_ARRAY,"array",varray()); - ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,remove,INT,"idx",varray()); - ADDFUNC2(POOL_BYTE_ARRAY,INT,PoolByteArray,insert,INT,"idx",INT,"byte",varray()); - ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,resize,INT,"idx",varray()); - ADDFUNC0(POOL_BYTE_ARRAY,NIL,PoolByteArray,invert,varray()); - ADDFUNC2(POOL_BYTE_ARRAY,POOL_BYTE_ARRAY,PoolByteArray,subarray,INT,"from",INT,"to",varray()); - - ADDFUNC0(POOL_BYTE_ARRAY,STRING,PoolByteArray,get_string_from_ascii,varray()); - ADDFUNC0(POOL_BYTE_ARRAY,STRING,PoolByteArray,get_string_from_utf8,varray()); - - - ADDFUNC0(POOL_INT_ARRAY,INT,PoolIntArray,size,varray()); - ADDFUNC2(POOL_INT_ARRAY,NIL,PoolIntArray,set,INT,"idx",INT,"integer",varray()); - ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,push_back,INT,"integer",varray()); - ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,append,INT,"integer",varray()); - ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,append_array,POOL_INT_ARRAY,"array",varray()); - ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,remove,INT,"idx",varray()); - ADDFUNC2(POOL_INT_ARRAY,INT,PoolIntArray,insert,INT,"idx",INT,"integer",varray()); - ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,resize,INT,"idx",varray()); - ADDFUNC0(POOL_INT_ARRAY,NIL,PoolIntArray,invert,varray()); - - ADDFUNC0(POOL_REAL_ARRAY,INT,PoolRealArray,size,varray()); - ADDFUNC2(POOL_REAL_ARRAY,NIL,PoolRealArray,set,INT,"idx",REAL,"value",varray()); - ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,push_back,REAL,"value",varray()); - ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,append,REAL,"value",varray()); - ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,append_array,POOL_REAL_ARRAY,"array",varray()); - ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,remove,INT,"idx",varray()); - ADDFUNC2(POOL_REAL_ARRAY,INT,PoolRealArray,insert,INT,"idx",REAL,"value",varray()); - ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,resize,INT,"idx",varray()); - ADDFUNC0(POOL_REAL_ARRAY,NIL,PoolRealArray,invert,varray()); - - ADDFUNC0(POOL_STRING_ARRAY,INT,PoolStringArray,size,varray()); - ADDFUNC2(POOL_STRING_ARRAY,NIL,PoolStringArray,set,INT,"idx",STRING,"string",varray()); - ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,push_back,STRING,"string",varray()); - ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,append,STRING,"string",varray()); - ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,append_array,POOL_STRING_ARRAY,"array",varray()); - ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,remove,INT,"idx",varray()); - ADDFUNC2(POOL_STRING_ARRAY,INT,PoolStringArray,insert,INT,"idx",STRING,"string",varray()); - ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,resize,INT,"idx",varray()); - ADDFUNC0(POOL_STRING_ARRAY,NIL,PoolStringArray,invert,varray()); - ADDFUNC1(POOL_STRING_ARRAY,STRING,PoolStringArray,join,STRING,"string",varray()); - - ADDFUNC0(POOL_VECTOR2_ARRAY,INT,PoolVector2Array,size,varray()); - ADDFUNC2(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,set,INT,"idx",VECTOR2,"vector2",varray()); - ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,push_back,VECTOR2,"vector2",varray()); - ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,append,VECTOR2,"vector2",varray()); - ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,append_array,POOL_VECTOR2_ARRAY,"array",varray()); - ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,remove,INT,"idx",varray()); - ADDFUNC2(POOL_VECTOR2_ARRAY,INT,PoolVector2Array,insert,INT,"idx",VECTOR2,"vector2",varray()); - ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,resize,INT,"idx",varray()); - ADDFUNC0(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,invert,varray()); - - ADDFUNC0(POOL_VECTOR3_ARRAY,INT,PoolVector3Array,size,varray()); - ADDFUNC2(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,set,INT,"idx",VECTOR3,"vector3",varray()); - ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,push_back,VECTOR3,"vector3",varray()); - ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,append,VECTOR3,"vector3",varray()); - ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,append_array,POOL_VECTOR3_ARRAY,"array",varray()); - ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,remove,INT,"idx",varray()); - ADDFUNC2(POOL_VECTOR3_ARRAY,INT,PoolVector3Array,insert,INT,"idx",VECTOR3,"vector3",varray()); - ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,resize,INT,"idx",varray()); - ADDFUNC0(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,invert,varray()); - - ADDFUNC0(POOL_COLOR_ARRAY,INT,PoolColorArray,size,varray()); - ADDFUNC2(POOL_COLOR_ARRAY,NIL,PoolColorArray,set,INT,"idx",COLOR,"color",varray()); - ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,push_back,COLOR,"color",varray()); - ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,append,COLOR,"color",varray()); - ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,append_array,POOL_COLOR_ARRAY,"array",varray()); - ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,remove,INT,"idx",varray()); - ADDFUNC2(POOL_COLOR_ARRAY,INT,PoolColorArray,insert,INT,"idx",COLOR,"color",varray()); - ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,resize,INT,"idx",varray()); - ADDFUNC0(POOL_COLOR_ARRAY,NIL,PoolColorArray,invert,varray()); + ADDFUNC0(_RID, INT, RID, get_id, varray()); + + ADDFUNC0(NODE_PATH, BOOL, NodePath, is_absolute, varray()); + ADDFUNC0(NODE_PATH, INT, NodePath, get_name_count, varray()); + ADDFUNC1(NODE_PATH, STRING, NodePath, get_name, INT, "idx", varray()); + ADDFUNC0(NODE_PATH, INT, NodePath, get_subname_count, varray()); + ADDFUNC1(NODE_PATH, STRING, NodePath, get_subname, INT, "idx", varray()); + ADDFUNC0(NODE_PATH, STRING, NodePath, get_property, varray()); + ADDFUNC0(NODE_PATH, BOOL, NodePath, is_empty, varray()); + + ADDFUNC0(DICTIONARY, INT, Dictionary, size, varray()); + ADDFUNC0(DICTIONARY, BOOL, Dictionary, empty, varray()); + ADDFUNC0(DICTIONARY, NIL, Dictionary, clear, varray()); + ADDFUNC1(DICTIONARY, BOOL, Dictionary, has, NIL, "key", varray()); + ADDFUNC1(DICTIONARY, BOOL, Dictionary, has_all, ARRAY, "keys", varray()); + ADDFUNC1(DICTIONARY, NIL, Dictionary, erase, NIL, "key", varray()); + ADDFUNC0(DICTIONARY, INT, Dictionary, hash, varray()); + ADDFUNC0(DICTIONARY, ARRAY, Dictionary, keys, varray()); + ADDFUNC0(DICTIONARY, ARRAY, Dictionary, values, varray()); + + ADDFUNC0(ARRAY, INT, Array, size, varray()); + ADDFUNC0(ARRAY, BOOL, Array, empty, varray()); + ADDFUNC0(ARRAY, NIL, Array, clear, varray()); + ADDFUNC0(ARRAY, INT, Array, hash, varray()); + ADDFUNC1(ARRAY, NIL, Array, push_back, NIL, "value", varray()); + ADDFUNC1(ARRAY, NIL, Array, push_front, NIL, "value", varray()); + ADDFUNC1(ARRAY, NIL, Array, append, NIL, "value", varray()); + ADDFUNC1(ARRAY, NIL, Array, resize, INT, "pos", varray()); + ADDFUNC2(ARRAY, NIL, Array, insert, INT, "pos", NIL, "value", varray()); + ADDFUNC1(ARRAY, NIL, Array, remove, INT, "pos", varray()); + ADDFUNC1(ARRAY, NIL, Array, erase, NIL, "value", varray()); + ADDFUNC0(ARRAY, NIL, Array, front, varray()); + ADDFUNC0(ARRAY, NIL, Array, back, varray()); + ADDFUNC2(ARRAY, INT, Array, find, NIL, "what", INT, "from", varray(0)); + ADDFUNC2(ARRAY, INT, Array, rfind, NIL, "what", INT, "from", varray(-1)); + ADDFUNC1(ARRAY, INT, Array, find_last, NIL, "value", varray()); + ADDFUNC1(ARRAY, INT, Array, count, NIL, "value", varray()); + ADDFUNC1(ARRAY, BOOL, Array, has, NIL, "value", varray()); + ADDFUNC0(ARRAY, NIL, Array, pop_back, varray()); + ADDFUNC0(ARRAY, NIL, Array, pop_front, varray()); + ADDFUNC0(ARRAY, NIL, Array, sort, varray()); + ADDFUNC2(ARRAY, NIL, Array, sort_custom, OBJECT, "obj", STRING, "func", varray()); + ADDFUNC0(ARRAY, NIL, Array, invert, varray()); + + ADDFUNC0(POOL_BYTE_ARRAY, INT, PoolByteArray, size, varray()); + ADDFUNC2(POOL_BYTE_ARRAY, NIL, PoolByteArray, set, INT, "idx", INT, "byte", varray()); + ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, push_back, INT, "byte", varray()); + ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, append, INT, "byte", varray()); + ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, append_array, POOL_BYTE_ARRAY, "array", varray()); + ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, remove, INT, "idx", varray()); + ADDFUNC2(POOL_BYTE_ARRAY, INT, PoolByteArray, insert, INT, "idx", INT, "byte", varray()); + ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, resize, INT, "idx", varray()); + ADDFUNC0(POOL_BYTE_ARRAY, NIL, PoolByteArray, invert, varray()); + ADDFUNC2(POOL_BYTE_ARRAY, POOL_BYTE_ARRAY, PoolByteArray, subarray, INT, "from", INT, "to", varray()); + + ADDFUNC0(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_ascii, varray()); + ADDFUNC0(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_utf8, varray()); + + ADDFUNC0(POOL_INT_ARRAY, INT, PoolIntArray, size, varray()); + ADDFUNC2(POOL_INT_ARRAY, NIL, PoolIntArray, set, INT, "idx", INT, "integer", varray()); + ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, push_back, INT, "integer", varray()); + ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, append, INT, "integer", varray()); + ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, append_array, POOL_INT_ARRAY, "array", varray()); + ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, remove, INT, "idx", varray()); + ADDFUNC2(POOL_INT_ARRAY, INT, PoolIntArray, insert, INT, "idx", INT, "integer", varray()); + ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, resize, INT, "idx", varray()); + ADDFUNC0(POOL_INT_ARRAY, NIL, PoolIntArray, invert, varray()); + + ADDFUNC0(POOL_REAL_ARRAY, INT, PoolRealArray, size, varray()); + ADDFUNC2(POOL_REAL_ARRAY, NIL, PoolRealArray, set, INT, "idx", REAL, "value", varray()); + ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, push_back, REAL, "value", varray()); + ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, append, REAL, "value", varray()); + ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, append_array, POOL_REAL_ARRAY, "array", varray()); + ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, remove, INT, "idx", varray()); + ADDFUNC2(POOL_REAL_ARRAY, INT, PoolRealArray, insert, INT, "idx", REAL, "value", varray()); + ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, resize, INT, "idx", varray()); + ADDFUNC0(POOL_REAL_ARRAY, NIL, PoolRealArray, invert, varray()); + + ADDFUNC0(POOL_STRING_ARRAY, INT, PoolStringArray, size, varray()); + ADDFUNC2(POOL_STRING_ARRAY, NIL, PoolStringArray, set, INT, "idx", STRING, "string", varray()); + ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, push_back, STRING, "string", varray()); + ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, append, STRING, "string", varray()); + ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, append_array, POOL_STRING_ARRAY, "array", varray()); + ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, remove, INT, "idx", varray()); + ADDFUNC2(POOL_STRING_ARRAY, INT, PoolStringArray, insert, INT, "idx", STRING, "string", varray()); + ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, resize, INT, "idx", varray()); + ADDFUNC0(POOL_STRING_ARRAY, NIL, PoolStringArray, invert, varray()); + ADDFUNC1(POOL_STRING_ARRAY, STRING, PoolStringArray, join, STRING, "string", varray()); + + ADDFUNC0(POOL_VECTOR2_ARRAY, INT, PoolVector2Array, size, varray()); + ADDFUNC2(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, set, INT, "idx", VECTOR2, "vector2", varray()); + ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, push_back, VECTOR2, "vector2", varray()); + ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, append, VECTOR2, "vector2", varray()); + ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, append_array, POOL_VECTOR2_ARRAY, "array", varray()); + ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, remove, INT, "idx", varray()); + ADDFUNC2(POOL_VECTOR2_ARRAY, INT, PoolVector2Array, insert, INT, "idx", VECTOR2, "vector2", varray()); + ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, resize, INT, "idx", varray()); + ADDFUNC0(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, invert, varray()); + + ADDFUNC0(POOL_VECTOR3_ARRAY, INT, PoolVector3Array, size, varray()); + ADDFUNC2(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, set, INT, "idx", VECTOR3, "vector3", varray()); + ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, push_back, VECTOR3, "vector3", varray()); + ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, append, VECTOR3, "vector3", varray()); + ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, append_array, POOL_VECTOR3_ARRAY, "array", varray()); + ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, remove, INT, "idx", varray()); + ADDFUNC2(POOL_VECTOR3_ARRAY, INT, PoolVector3Array, insert, INT, "idx", VECTOR3, "vector3", varray()); + ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, resize, INT, "idx", varray()); + ADDFUNC0(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, invert, varray()); + + ADDFUNC0(POOL_COLOR_ARRAY, INT, PoolColorArray, size, varray()); + ADDFUNC2(POOL_COLOR_ARRAY, NIL, PoolColorArray, set, INT, "idx", COLOR, "color", varray()); + ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, push_back, COLOR, "color", varray()); + ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, append, COLOR, "color", varray()); + ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, append_array, POOL_COLOR_ARRAY, "array", varray()); + ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, remove, INT, "idx", varray()); + ADDFUNC2(POOL_COLOR_ARRAY, INT, PoolColorArray, insert, INT, "idx", COLOR, "color", varray()); + ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, resize, INT, "idx", varray()); + ADDFUNC0(POOL_COLOR_ARRAY, NIL, PoolColorArray, invert, varray()); //pointerbased - ADDFUNC0(RECT3,REAL,Rect3,get_area,varray()); - ADDFUNC0(RECT3,BOOL,Rect3,has_no_area,varray()); - ADDFUNC0(RECT3,BOOL,Rect3,has_no_surface,varray()); - ADDFUNC1(RECT3,BOOL,Rect3,intersects,RECT3,"with",varray()); - ADDFUNC1(RECT3,BOOL,Rect3,encloses,RECT3,"with",varray()); - ADDFUNC1(RECT3,RECT3,Rect3,merge,RECT3,"with",varray()); - ADDFUNC1(RECT3,RECT3,Rect3,intersection,RECT3,"with",varray()); - ADDFUNC1(RECT3,BOOL,Rect3,intersects_plane,PLANE,"plane",varray()); - ADDFUNC2(RECT3,BOOL,Rect3,intersects_segment,VECTOR3,"from",VECTOR3,"to",varray()); - ADDFUNC1(RECT3,BOOL,Rect3,has_point,VECTOR3,"point",varray()); - ADDFUNC1(RECT3,VECTOR3,Rect3,get_support,VECTOR3,"dir",varray()); - ADDFUNC0(RECT3,VECTOR3,Rect3,get_longest_axis,varray()); - ADDFUNC0(RECT3,INT,Rect3,get_longest_axis_index,varray()); - ADDFUNC0(RECT3,REAL,Rect3,get_longest_axis_size,varray()); - ADDFUNC0(RECT3,VECTOR3,Rect3,get_shortest_axis,varray()); - ADDFUNC0(RECT3,INT,Rect3,get_shortest_axis_index,varray()); - ADDFUNC0(RECT3,REAL,Rect3,get_shortest_axis_size,varray()); - ADDFUNC1(RECT3,RECT3,Rect3,expand,VECTOR3,"to_point",varray()); - ADDFUNC1(RECT3,RECT3,Rect3,grow,REAL,"by",varray()); - ADDFUNC1(RECT3,VECTOR3,Rect3,get_endpoint,INT,"idx",varray()); - - ADDFUNC0(TRANSFORM2D,TRANSFORM2D,Transform2D,inverse,varray()); - ADDFUNC0(TRANSFORM2D,TRANSFORM2D,Transform2D,affine_inverse,varray()); - ADDFUNC0(TRANSFORM2D,REAL,Transform2D,get_rotation,varray()); - ADDFUNC0(TRANSFORM2D,VECTOR2,Transform2D,get_origin,varray()); - ADDFUNC0(TRANSFORM2D,VECTOR2,Transform2D,get_scale,varray()); - ADDFUNC0(TRANSFORM2D,TRANSFORM2D,Transform2D,orthonormalized,varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,rotated,REAL,"phi",varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,scaled,VECTOR2,"scale",varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,translated,VECTOR2,"offset",varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,xform,NIL,"v",varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,xform_inv,NIL,"v",varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,basis_xform,NIL,"v",varray()); - ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,basis_xform_inv,NIL,"v",varray()); - ADDFUNC2(TRANSFORM2D,TRANSFORM2D,Transform2D,interpolate_with,TRANSFORM2D,"m",REAL,"c",varray()); - - ADDFUNC0(BASIS,BASIS,Basis,inverse,varray()); - ADDFUNC0(BASIS,BASIS,Basis,transposed,varray()); - ADDFUNC0(BASIS,BASIS,Basis,orthonormalized,varray()); - ADDFUNC0(BASIS,REAL,Basis,determinant,varray()); - ADDFUNC2(BASIS,BASIS,Basis,rotated,VECTOR3,"axis",REAL,"phi",varray()); - ADDFUNC1(BASIS,BASIS,Basis,scaled,VECTOR3,"scale",varray()); - ADDFUNC0(BASIS,VECTOR3,Basis,get_scale,varray()); - ADDFUNC0(BASIS,VECTOR3,Basis,get_euler,varray()); - ADDFUNC1(BASIS,REAL,Basis,tdotx,VECTOR3,"with",varray()); - ADDFUNC1(BASIS,REAL,Basis,tdoty,VECTOR3,"with",varray()); - ADDFUNC1(BASIS,REAL,Basis,tdotz,VECTOR3,"with",varray()); - ADDFUNC1(BASIS,VECTOR3,Basis,xform,VECTOR3,"v",varray()); - ADDFUNC1(BASIS,VECTOR3,Basis,xform_inv,VECTOR3,"v",varray()); - ADDFUNC0(BASIS,INT,Basis,get_orthogonal_index,varray()); - - ADDFUNC0(TRANSFORM,TRANSFORM,Transform,inverse,varray()); - ADDFUNC0(TRANSFORM,TRANSFORM,Transform,affine_inverse,varray()); - ADDFUNC0(TRANSFORM,TRANSFORM,Transform,orthonormalized,varray()); - ADDFUNC2(TRANSFORM,TRANSFORM,Transform,rotated,VECTOR3,"axis",REAL,"phi",varray()); - ADDFUNC1(TRANSFORM,TRANSFORM,Transform,scaled,VECTOR3,"scale",varray()); - ADDFUNC1(TRANSFORM,TRANSFORM,Transform,translated,VECTOR3,"ofs",varray()); - ADDFUNC2(TRANSFORM,TRANSFORM,Transform,looking_at,VECTOR3,"target",VECTOR3,"up",varray()); - ADDFUNC1(TRANSFORM,NIL,Transform,xform,NIL,"v",varray()); - ADDFUNC1(TRANSFORM,NIL,Transform,xform_inv,NIL,"v",varray()); + ADDFUNC0(RECT3, REAL, Rect3, get_area, varray()); + ADDFUNC0(RECT3, BOOL, Rect3, has_no_area, varray()); + ADDFUNC0(RECT3, BOOL, Rect3, has_no_surface, varray()); + ADDFUNC1(RECT3, BOOL, Rect3, intersects, RECT3, "with", varray()); + ADDFUNC1(RECT3, BOOL, Rect3, encloses, RECT3, "with", varray()); + ADDFUNC1(RECT3, RECT3, Rect3, merge, RECT3, "with", varray()); + ADDFUNC1(RECT3, RECT3, Rect3, intersection, RECT3, "with", varray()); + ADDFUNC1(RECT3, BOOL, Rect3, intersects_plane, PLANE, "plane", varray()); + ADDFUNC2(RECT3, BOOL, Rect3, intersects_segment, VECTOR3, "from", VECTOR3, "to", varray()); + ADDFUNC1(RECT3, BOOL, Rect3, has_point, VECTOR3, "point", varray()); + ADDFUNC1(RECT3, VECTOR3, Rect3, get_support, VECTOR3, "dir", varray()); + ADDFUNC0(RECT3, VECTOR3, Rect3, get_longest_axis, varray()); + ADDFUNC0(RECT3, INT, Rect3, get_longest_axis_index, varray()); + ADDFUNC0(RECT3, REAL, Rect3, get_longest_axis_size, varray()); + ADDFUNC0(RECT3, VECTOR3, Rect3, get_shortest_axis, varray()); + ADDFUNC0(RECT3, INT, Rect3, get_shortest_axis_index, varray()); + ADDFUNC0(RECT3, REAL, Rect3, get_shortest_axis_size, varray()); + ADDFUNC1(RECT3, RECT3, Rect3, expand, VECTOR3, "to_point", varray()); + ADDFUNC1(RECT3, RECT3, Rect3, grow, REAL, "by", varray()); + ADDFUNC1(RECT3, VECTOR3, Rect3, get_endpoint, INT, "idx", varray()); + + ADDFUNC0(TRANSFORM2D, TRANSFORM2D, Transform2D, inverse, varray()); + ADDFUNC0(TRANSFORM2D, TRANSFORM2D, Transform2D, affine_inverse, varray()); + ADDFUNC0(TRANSFORM2D, REAL, Transform2D, get_rotation, varray()); + ADDFUNC0(TRANSFORM2D, VECTOR2, Transform2D, get_origin, varray()); + ADDFUNC0(TRANSFORM2D, VECTOR2, Transform2D, get_scale, varray()); + ADDFUNC0(TRANSFORM2D, TRANSFORM2D, Transform2D, orthonormalized, varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, rotated, REAL, "phi", varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, scaled, VECTOR2, "scale", varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, translated, VECTOR2, "offset", varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, xform, NIL, "v", varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, xform_inv, NIL, "v", varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, basis_xform, NIL, "v", varray()); + ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, basis_xform_inv, NIL, "v", varray()); + ADDFUNC2(TRANSFORM2D, TRANSFORM2D, Transform2D, interpolate_with, TRANSFORM2D, "m", REAL, "c", varray()); + + ADDFUNC0(BASIS, BASIS, Basis, inverse, varray()); + ADDFUNC0(BASIS, BASIS, Basis, transposed, varray()); + ADDFUNC0(BASIS, BASIS, Basis, orthonormalized, varray()); + ADDFUNC0(BASIS, REAL, Basis, determinant, varray()); + ADDFUNC2(BASIS, BASIS, Basis, rotated, VECTOR3, "axis", REAL, "phi", varray()); + ADDFUNC1(BASIS, BASIS, Basis, scaled, VECTOR3, "scale", varray()); + ADDFUNC0(BASIS, VECTOR3, Basis, get_scale, varray()); + ADDFUNC0(BASIS, VECTOR3, Basis, get_euler, varray()); + ADDFUNC1(BASIS, REAL, Basis, tdotx, VECTOR3, "with", varray()); + ADDFUNC1(BASIS, REAL, Basis, tdoty, VECTOR3, "with", varray()); + ADDFUNC1(BASIS, REAL, Basis, tdotz, VECTOR3, "with", varray()); + ADDFUNC1(BASIS, VECTOR3, Basis, xform, VECTOR3, "v", varray()); + ADDFUNC1(BASIS, VECTOR3, Basis, xform_inv, VECTOR3, "v", varray()); + ADDFUNC0(BASIS, INT, Basis, get_orthogonal_index, varray()); + + ADDFUNC0(TRANSFORM, TRANSFORM, Transform, inverse, varray()); + ADDFUNC0(TRANSFORM, TRANSFORM, Transform, affine_inverse, varray()); + ADDFUNC0(TRANSFORM, TRANSFORM, Transform, orthonormalized, varray()); + ADDFUNC2(TRANSFORM, TRANSFORM, Transform, rotated, VECTOR3, "axis", REAL, "phi", varray()); + ADDFUNC1(TRANSFORM, TRANSFORM, Transform, scaled, VECTOR3, "scale", varray()); + ADDFUNC1(TRANSFORM, TRANSFORM, Transform, translated, VECTOR3, "ofs", varray()); + ADDFUNC2(TRANSFORM, TRANSFORM, Transform, looking_at, VECTOR3, "target", VECTOR3, "up", varray()); + ADDFUNC1(TRANSFORM, NIL, Transform, xform, NIL, "v", varray()); + ADDFUNC1(TRANSFORM, NIL, Transform, xform_inv, NIL, "v", varray()); #ifdef DEBUG_ENABLED - _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform"].returns=true; - _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform_inv"].returns=true; + _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform"].returns = true; + _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform_inv"].returns = true; #endif - ADDFUNC0(INPUT_EVENT,BOOL,InputEvent,is_pressed,varray()); - ADDFUNC1(INPUT_EVENT,BOOL,InputEvent,is_action,STRING,"action",varray()); - ADDFUNC1(INPUT_EVENT,BOOL,InputEvent,is_action_pressed,STRING,"action",varray()); - ADDFUNC1(INPUT_EVENT,BOOL,InputEvent,is_action_released,STRING,"action",varray()); - ADDFUNC0(INPUT_EVENT,BOOL,InputEvent,is_echo,varray()); - ADDFUNC2(INPUT_EVENT,NIL,InputEvent,set_as_action,STRING,"action",BOOL,"pressed",varray()); + ADDFUNC0(INPUT_EVENT, BOOL, InputEvent, is_pressed, varray()); + ADDFUNC1(INPUT_EVENT, BOOL, InputEvent, is_action, STRING, "action", varray()); + ADDFUNC1(INPUT_EVENT, BOOL, InputEvent, is_action_pressed, STRING, "action", varray()); + ADDFUNC1(INPUT_EVENT, BOOL, InputEvent, is_action_released, STRING, "action", varray()); + ADDFUNC0(INPUT_EVENT, BOOL, InputEvent, is_echo, varray()); + ADDFUNC2(INPUT_EVENT, NIL, InputEvent, set_as_action, STRING, "action", BOOL, "pressed", varray()); /* REGISTER CONSTRUCTORS */ - _VariantCall::add_constructor(_VariantCall::Vector2_init1,Variant::VECTOR2,"x",Variant::REAL,"y",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Vector2_init1, Variant::VECTOR2, "x", Variant::REAL, "y", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Rect2_init1,Variant::RECT2,"pos",Variant::VECTOR2,"size",Variant::VECTOR2); - _VariantCall::add_constructor(_VariantCall::Rect2_init2,Variant::RECT2,"x",Variant::REAL,"y",Variant::REAL,"width",Variant::REAL,"height",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Rect2_init1, Variant::RECT2, "pos", Variant::VECTOR2, "size", Variant::VECTOR2); + _VariantCall::add_constructor(_VariantCall::Rect2_init2, Variant::RECT2, "x", Variant::REAL, "y", Variant::REAL, "width", Variant::REAL, "height", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Transform2D_init2,Variant::TRANSFORM2D,"rot",Variant::REAL,"pos",Variant::VECTOR2); - _VariantCall::add_constructor(_VariantCall::Transform2D_init3,Variant::TRANSFORM2D,"x_axis",Variant::VECTOR2,"y_axis",Variant::VECTOR2,"origin",Variant::VECTOR2); + _VariantCall::add_constructor(_VariantCall::Transform2D_init2, Variant::TRANSFORM2D, "rot", Variant::REAL, "pos", Variant::VECTOR2); + _VariantCall::add_constructor(_VariantCall::Transform2D_init3, Variant::TRANSFORM2D, "x_axis", Variant::VECTOR2, "y_axis", Variant::VECTOR2, "origin", Variant::VECTOR2); - _VariantCall::add_constructor(_VariantCall::Vector3_init1,Variant::VECTOR3,"x",Variant::REAL,"y",Variant::REAL,"z",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Vector3_init1, Variant::VECTOR3, "x", Variant::REAL, "y", Variant::REAL, "z", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Plane_init1,Variant::PLANE,"a",Variant::REAL,"b",Variant::REAL,"c",Variant::REAL,"d",Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Plane_init2,Variant::PLANE,"v1",Variant::VECTOR3,"v2",Variant::VECTOR3,"v3",Variant::VECTOR3); - _VariantCall::add_constructor(_VariantCall::Plane_init3,Variant::PLANE,"normal",Variant::VECTOR3,"d",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Plane_init1, Variant::PLANE, "a", Variant::REAL, "b", Variant::REAL, "c", Variant::REAL, "d", Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Plane_init2, Variant::PLANE, "v1", Variant::VECTOR3, "v2", Variant::VECTOR3, "v3", Variant::VECTOR3); + _VariantCall::add_constructor(_VariantCall::Plane_init3, Variant::PLANE, "normal", Variant::VECTOR3, "d", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Quat_init1,Variant::QUAT,"x",Variant::REAL,"y",Variant::REAL,"z",Variant::REAL,"w",Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Quat_init2,Variant::QUAT,"axis",Variant::VECTOR3,"angle",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Quat_init1, Variant::QUAT, "x", Variant::REAL, "y", Variant::REAL, "z", Variant::REAL, "w", Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Quat_init2, Variant::QUAT, "axis", Variant::VECTOR3, "angle", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Color_init1,Variant::COLOR,"r",Variant::REAL,"g",Variant::REAL,"b",Variant::REAL,"a",Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Color_init2,Variant::COLOR,"r",Variant::REAL,"g",Variant::REAL,"b",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Color_init1, Variant::COLOR, "r", Variant::REAL, "g", Variant::REAL, "b", Variant::REAL, "a", Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Color_init2, Variant::COLOR, "r", Variant::REAL, "g", Variant::REAL, "b", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Rect3_init1,Variant::RECT3,"pos",Variant::VECTOR3,"size",Variant::VECTOR3); + _VariantCall::add_constructor(_VariantCall::Rect3_init1, Variant::RECT3, "pos", Variant::VECTOR3, "size", Variant::VECTOR3); - _VariantCall::add_constructor(_VariantCall::Basis_init1,Variant::BASIS,"x_axis",Variant::VECTOR3,"y_axis",Variant::VECTOR3,"z_axis",Variant::VECTOR3); - _VariantCall::add_constructor(_VariantCall::Basis_init2,Variant::BASIS,"axis",Variant::VECTOR3,"phi",Variant::REAL); + _VariantCall::add_constructor(_VariantCall::Basis_init1, Variant::BASIS, "x_axis", Variant::VECTOR3, "y_axis", Variant::VECTOR3, "z_axis", Variant::VECTOR3); + _VariantCall::add_constructor(_VariantCall::Basis_init2, Variant::BASIS, "axis", Variant::VECTOR3, "phi", Variant::REAL); - _VariantCall::add_constructor(_VariantCall::Transform_init1,Variant::TRANSFORM,"x_axis",Variant::VECTOR3,"y_axis",Variant::VECTOR3,"z_axis",Variant::VECTOR3,"origin",Variant::VECTOR3); - _VariantCall::add_constructor(_VariantCall::Transform_init2,Variant::TRANSFORM,"basis",Variant::BASIS,"origin",Variant::VECTOR3); + _VariantCall::add_constructor(_VariantCall::Transform_init1, Variant::TRANSFORM, "x_axis", Variant::VECTOR3, "y_axis", Variant::VECTOR3, "z_axis", Variant::VECTOR3, "origin", Variant::VECTOR3); + _VariantCall::add_constructor(_VariantCall::Transform_init2, Variant::TRANSFORM, "basis", Variant::BASIS, "origin", Variant::VECTOR3); - _VariantCall::add_constructor(_VariantCall::Image_init1,Variant::IMAGE,"width",Variant::INT,"height",Variant::INT,"mipmaps",Variant::BOOL,"format",Variant::INT); + _VariantCall::add_constructor(_VariantCall::Image_init1, Variant::IMAGE, "width", Variant::INT, "height", Variant::INT, "mipmaps", Variant::BOOL, "format", Variant::INT); /* REGISTER CONSTANTS */ - _VariantCall::add_constant(Variant::VECTOR3,"AXIS_X",Vector3::AXIS_X); - _VariantCall::add_constant(Variant::VECTOR3,"AXIS_Y",Vector3::AXIS_Y); - _VariantCall::add_constant(Variant::VECTOR3,"AXIS_Z",Vector3::AXIS_Z); - - - _VariantCall::add_constant(Variant::INPUT_EVENT,"NONE",InputEvent::NONE); - _VariantCall::add_constant(Variant::INPUT_EVENT,"KEY",InputEvent::KEY); - _VariantCall::add_constant(Variant::INPUT_EVENT,"MOUSE_MOTION",InputEvent::MOUSE_MOTION); - _VariantCall::add_constant(Variant::INPUT_EVENT,"MOUSE_BUTTON",InputEvent::MOUSE_BUTTON); - _VariantCall::add_constant(Variant::INPUT_EVENT,"JOYPAD_MOTION",InputEvent::JOYPAD_MOTION); - _VariantCall::add_constant(Variant::INPUT_EVENT,"JOYPAD_BUTTON",InputEvent::JOYPAD_BUTTON); - _VariantCall::add_constant(Variant::INPUT_EVENT,"SCREEN_TOUCH",InputEvent::SCREEN_TOUCH); - _VariantCall::add_constant(Variant::INPUT_EVENT,"SCREEN_DRAG",InputEvent::SCREEN_DRAG); - _VariantCall::add_constant(Variant::INPUT_EVENT,"ACTION",InputEvent::ACTION); - - - _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_16BIT",Image::COMPRESS_16BIT); - _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_S3TC",Image::COMPRESS_S3TC); - _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_PVRTC2",Image::COMPRESS_PVRTC2); - _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_PVRTC4",Image::COMPRESS_PVRTC4); - _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_ETC",Image::COMPRESS_ETC); - _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_ETC2",Image::COMPRESS_ETC2); - - - - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_L8",Image::FORMAT_L8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_LA8",Image::FORMAT_LA8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_R8",Image::FORMAT_R8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RG8",Image::FORMAT_RG8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGB8",Image::FORMAT_RGB8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBA8",Image::FORMAT_RGBA8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGB565",Image::FORMAT_RGB565); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBA4444",Image::FORMAT_RGBA4444); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBA5551",Image::FORMAT_DXT1); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RF",Image::FORMAT_RF); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGF",Image::FORMAT_RGF); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBF",Image::FORMAT_RGBF); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBAF",Image::FORMAT_RGBAF); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RH",Image::FORMAT_RH); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGH",Image::FORMAT_RGH); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBH",Image::FORMAT_RGBH); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBAH",Image::FORMAT_RGBAH); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_DXT1",Image::FORMAT_DXT1); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_DXT3",Image::FORMAT_DXT3); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_DXT5",Image::FORMAT_DXT5); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ATI1",Image::FORMAT_ATI1); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ATI2",Image::FORMAT_ATI2); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_BPTC_RGBA",Image::FORMAT_BPTC_RGBA); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_BPTC_RGBF",Image::FORMAT_BPTC_RGBF); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_BPTC_RGBFU",Image::FORMAT_BPTC_RGBFU); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC2",Image::FORMAT_PVRTC2); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC2A",Image::FORMAT_PVRTC2A); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC4",Image::FORMAT_PVRTC4); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC4A",Image::FORMAT_PVRTC4A); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC",Image::FORMAT_ETC); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_R11",Image::FORMAT_ETC2_R11); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_R11S",Image::FORMAT_ETC2_R11S); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RG11",Image::FORMAT_ETC2_RG11); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RG11S",Image::FORMAT_ETC2_RG11S); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RGB8",Image::FORMAT_ETC2_RGB8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RGBA8",Image::FORMAT_ETC2_RGBA8); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RGB8A1",Image::FORMAT_ETC2_RGB8A1); - _VariantCall::add_constant(Variant::IMAGE,"FORMAT_MAX",Image::FORMAT_MAX); - - _VariantCall::add_constant(Variant::IMAGE,"INTERPOLATE_NEAREST",Image::INTERPOLATE_NEAREST); - _VariantCall::add_constant(Variant::IMAGE,"INTERPOLATE_BILINEAR",Image::INTERPOLATE_BILINEAR); - _VariantCall::add_constant(Variant::IMAGE,"INTERPOLATE_CUBIC",Image::INTERPOLATE_CUBIC); - + _VariantCall::add_constant(Variant::VECTOR3, "AXIS_X", Vector3::AXIS_X); + _VariantCall::add_constant(Variant::VECTOR3, "AXIS_Y", Vector3::AXIS_Y); + _VariantCall::add_constant(Variant::VECTOR3, "AXIS_Z", Vector3::AXIS_Z); + + _VariantCall::add_constant(Variant::INPUT_EVENT, "NONE", InputEvent::NONE); + _VariantCall::add_constant(Variant::INPUT_EVENT, "KEY", InputEvent::KEY); + _VariantCall::add_constant(Variant::INPUT_EVENT, "MOUSE_MOTION", InputEvent::MOUSE_MOTION); + _VariantCall::add_constant(Variant::INPUT_EVENT, "MOUSE_BUTTON", InputEvent::MOUSE_BUTTON); + _VariantCall::add_constant(Variant::INPUT_EVENT, "JOYPAD_MOTION", InputEvent::JOYPAD_MOTION); + _VariantCall::add_constant(Variant::INPUT_EVENT, "JOYPAD_BUTTON", InputEvent::JOYPAD_BUTTON); + _VariantCall::add_constant(Variant::INPUT_EVENT, "SCREEN_TOUCH", InputEvent::SCREEN_TOUCH); + _VariantCall::add_constant(Variant::INPUT_EVENT, "SCREEN_DRAG", InputEvent::SCREEN_DRAG); + _VariantCall::add_constant(Variant::INPUT_EVENT, "ACTION", InputEvent::ACTION); + + _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_16BIT", Image::COMPRESS_16BIT); + _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_S3TC", Image::COMPRESS_S3TC); + _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_PVRTC2", Image::COMPRESS_PVRTC2); + _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_PVRTC4", Image::COMPRESS_PVRTC4); + _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_ETC", Image::COMPRESS_ETC); + _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_ETC2", Image::COMPRESS_ETC2); + + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_L8", Image::FORMAT_L8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_LA8", Image::FORMAT_LA8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_R8", Image::FORMAT_R8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RG8", Image::FORMAT_RG8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGB8", Image::FORMAT_RGB8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBA8", Image::FORMAT_RGBA8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGB565", Image::FORMAT_RGB565); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBA4444", Image::FORMAT_RGBA4444); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBA5551", Image::FORMAT_DXT1); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RF", Image::FORMAT_RF); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGF", Image::FORMAT_RGF); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBF", Image::FORMAT_RGBF); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBAF", Image::FORMAT_RGBAF); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RH", Image::FORMAT_RH); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGH", Image::FORMAT_RGH); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBH", Image::FORMAT_RGBH); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBAH", Image::FORMAT_RGBAH); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_DXT1", Image::FORMAT_DXT1); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_DXT3", Image::FORMAT_DXT3); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_DXT5", Image::FORMAT_DXT5); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ATI1", Image::FORMAT_ATI1); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ATI2", Image::FORMAT_ATI2); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_BPTC_RGBA", Image::FORMAT_BPTC_RGBA); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_BPTC_RGBF", Image::FORMAT_BPTC_RGBF); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_BPTC_RGBFU", Image::FORMAT_BPTC_RGBFU); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC2", Image::FORMAT_PVRTC2); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC2A", Image::FORMAT_PVRTC2A); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC4", Image::FORMAT_PVRTC4); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC4A", Image::FORMAT_PVRTC4A); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC", Image::FORMAT_ETC); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_R11", Image::FORMAT_ETC2_R11); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_R11S", Image::FORMAT_ETC2_R11S); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RG11", Image::FORMAT_ETC2_RG11); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RG11S", Image::FORMAT_ETC2_RG11S); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RGB8", Image::FORMAT_ETC2_RGB8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RGBA8", Image::FORMAT_ETC2_RGBA8); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RGB8A1", Image::FORMAT_ETC2_RGB8A1); + _VariantCall::add_constant(Variant::IMAGE, "FORMAT_MAX", Image::FORMAT_MAX); + + _VariantCall::add_constant(Variant::IMAGE, "INTERPOLATE_NEAREST", Image::INTERPOLATE_NEAREST); + _VariantCall::add_constant(Variant::IMAGE, "INTERPOLATE_BILINEAR", Image::INTERPOLATE_BILINEAR); + _VariantCall::add_constant(Variant::IMAGE, "INTERPOLATE_CUBIC", Image::INTERPOLATE_CUBIC); } void unregister_variant_methods() { - memdelete_arr(_VariantCall::type_funcs); memdelete_arr(_VariantCall::construct_funcs); - memdelete_arr( _VariantCall::constant_data ); - - + memdelete_arr(_VariantCall::constant_data); } diff --git a/core/variant_construct_string.cpp b/core/variant_construct_string.cpp index 56aa9891fb..7f176749d3 100644 --- a/core/variant_construct_string.cpp +++ b/core/variant_construct_string.cpp @@ -58,22 +58,20 @@ class VariantConstruct { Variant value; }; - static const char * tk_name[TK_MAX]; + static const char *tk_name[TK_MAX]; - static String _print_var(const Variant& p_var); + static String _print_var(const Variant &p_var); - static Error _get_token(const CharType *p_str,int &index, int p_len,Token& r_token,int &line,String &r_err_str); - static Error _parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud); - static Error _parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud); - static Error _parse_dict(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud); + static Error _get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str); + static Error _parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud); + static Error _parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud); + static Error _parse_dict(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud); public: - - static Error parse(const String& p_string,Variant& r_ret,String &r_err_str,int &r_err_line,Variant::ObjectConstruct* p_construct,void* p_ud); + static Error parse(const String &p_string, Variant &r_ret, String &r_err_str, int &r_err_line, Variant::ObjectConstruct *p_construct, void *p_ud); }; - -const char * VariantConstruct::tk_name[TK_MAX] = { +const char *VariantConstruct::tk_name[TK_MAX] = { "'{'", "'}'", "'['", @@ -86,12 +84,10 @@ const char * VariantConstruct::tk_name[TK_MAX] = { "EOF", }; - - -Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_token,int &line,String &r_err_str) { +Error VariantConstruct::_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': { @@ -100,42 +96,42 @@ Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, T 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; }; @@ -143,318 +139,298 @@ Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, T 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; - - 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 '\"': res='\"'; break; - case '\\': res='\\'; break; - case '/': res='/'; break; + CharType res = 0; + + 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 '\"': res = '\"'; break; + case '\\': res = '\\'; break; + case '/': res = '/'; 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; default: { - r_err_str="Invalid escape sequence"; + r_err_str = "Invalid escape sequence"; return ERR_PARSE_ERROR; } 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 VariantConstruct::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud) { - -Error VariantConstruct::_parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud) { - - - if (token.type==TK_CURLY_BRACKET_OPEN) { + if (token.type == TK_CURLY_BRACKET_OPEN) { Dictionary d; - Error err = _parse_dict(d,p_str,index,p_len,line,r_err_str,p_construct,p_ud); + Error err = _parse_dict(d, p_str, index, p_len, line, r_err_str, p_construct, p_ud); if (err) return err; - value=d; + value = d; return OK; - } else if (token.type==TK_BRACKET_OPEN) { + } else if (token.type == TK_BRACKET_OPEN) { Array a; - Error err = _parse_array(a,p_str,index,p_len,line,r_err_str,p_construct,p_ud); + Error err = _parse_array(a, p_str, index, p_len, line, r_err_str, p_construct, p_ud); 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 VariantConstruct::_parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud) { +Error VariantConstruct::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud) { Token token; - bool need_comma=false; - + bool need_comma = false; - while(index<p_len) { + while (index < p_len) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_BRACKET_CLOSE) { + if (token.type == TK_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected ','"; + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str,p_construct,p_ud); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str, p_construct, p_ud); if (err) return err; array.push_back(v); - need_comma=true; - + need_comma = true; } return OK; - } -Error VariantConstruct::_parse_dict(Dictionary &dict,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud) { +Error VariantConstruct::_parse_dict(Dictionary &dict, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud) { - bool at_key=true; + bool at_key = true; Variant key; Token token; - bool need_comma=false; - - - while(index<p_len) { + bool need_comma = false; + while (index < p_len) { if (at_key) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_CURLY_BRACKET_CLOSE) { + if (token.type == TK_CURLY_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected '}' or ','"; + r_err_str = "Expected '}' or ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } - err = _parse_value(key,token,p_str,index,p_len,line,r_err_str,p_construct,p_ud); + err = _parse_value(key, token, p_str, index, p_len, line, r_err_str, p_construct, p_ud); - - if (err!=OK) + if (err != OK) return err; - err = _get_token(p_str,index,p_len,token,line,r_err_str); + err = _get_token(p_str, index, p_len, token, line, r_err_str); - if (err!=OK) + if (err != OK) return err; - if (token.type!=TK_COLON) { + if (token.type != TK_COLON) { - r_err_str="Expected ':'"; + r_err_str = "Expected ':'"; return ERR_PARSE_ERROR; } - at_key=false; + at_key = false; } else { - - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str,p_construct,p_ud); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str, p_construct, p_ud); if (err) return err; - dict[key]=v; - need_comma=true; - at_key=true; + dict[key] = v; + need_comma = true; + at_key = true; } } return OK; } - -Error VariantConstruct::parse(const String& p_string,Variant& r_ret,String &r_err_str,int &r_err_line,Variant::ObjectConstruct* p_construct,void* p_ud) { - +Error VariantConstruct::parse(const String &p_string, Variant &r_ret, String &r_err_str, int &r_err_line, Variant::ObjectConstruct *p_construct, void *p_ud) { const CharType *str = p_string.ptr(); int idx = 0; int len = p_string.length(); Token token; - r_err_line=0; + r_err_line = 0; String aux_key; - Error err = _get_token(str,idx,len,token,r_err_line,r_err_str); + Error err = _get_token(str, idx, len, token, r_err_line, r_err_str); if (err) return err; - return _parse_value(r_ret,token,str,idx,len,r_err_line,r_err_str,p_construct,p_ud); + return _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str, p_construct, p_ud); } - - diff --git a/core/variant_op.cpp b/core/variant_op.cpp index 28e804b5bf..71d03b159e 100644 --- a/core/variant_op.cpp +++ b/core/variant_op.cpp @@ -28,9 +28,9 @@ /*************************************************************************/ #include "variant.h" +#include "core_string_names.h" #include "object.h" #include "script_language.h" -#include "core_string_names.h" Variant::operator bool() const { @@ -40,13 +40,13 @@ Variant::operator bool() const { bool Variant::booleanize(bool &r_valid) const { - r_valid=true; - switch(type) { + r_valid = true; + switch (type) { case NIL: return false; case BOOL: return _data._bool; case INT: return _data._int; case REAL: return _data._real; - case STRING: return (*reinterpret_cast<const String*>(_data._mem))!=""; + case STRING: return (*reinterpret_cast<const String *>(_data._mem)) != ""; case VECTOR2: case RECT2: case TRANSFORM2D: @@ -57,10 +57,10 @@ bool Variant::booleanize(bool &r_valid) const { case BASIS: case TRANSFORM: case COLOR: - case IMAGE: r_valid=false; return false; - case _RID: return (*reinterpret_cast<const RID*>(_data._mem)).is_valid(); - case OBJECT: return _get_obj().obj; - case NODE_PATH: return (*reinterpret_cast<const NodePath*>(_data._mem))!=NodePath(); + case IMAGE: r_valid = false; return false; + case _RID: return (*reinterpret_cast<const RID *>(_data._mem)).is_valid(); + case OBJECT: return _get_obj().obj; + case NODE_PATH: return (*reinterpret_cast<const NodePath *>(_data._mem)) != NodePath(); case INPUT_EVENT: case DICTIONARY: case ARRAY: @@ -71,293 +71,299 @@ bool Variant::booleanize(bool &r_valid) const { case POOL_VECTOR2_ARRAY: case POOL_VECTOR3_ARRAY: case POOL_COLOR_ARRAY: - r_valid=false; + r_valid = false; return false; - default: {} + default: {} } return false; } -#define _RETURN(m_what) { r_ret=m_what; return; } - -#define DEFAULT_OP_NUM(m_op,m_name,m_type)\ -case m_name: {\ - switch(p_b.type) {\ - case BOOL: _RETURN(p_a._data.m_type m_op p_b._data._bool);\ - case INT: _RETURN(p_a._data.m_type m_op p_b._data._int);\ - case REAL: _RETURN(p_a._data.m_type m_op p_b._data._real);\ - default: {}\ - }\ - r_valid=false;\ - return;\ -}; - -#define DEFAULT_OP_NUM_NEG(m_name,m_type)\ -case m_name: {\ -\ - _RETURN( -p_a._data.m_type);\ -}; - -#define DEFAULT_OP_NUM_POS(m_name,m_type)\ -case m_name: {\ -\ - _RETURN( p_a._data.m_type);\ -}; - -#define DEFAULT_OP_NUM_VEC(m_op,m_name,m_type)\ -case m_name: {\ - switch(p_b.type) {\ - case BOOL: _RETURN( p_a._data.m_type m_op p_b._data._bool);\ - case INT: _RETURN( p_a._data.m_type m_op p_b._data._int);\ - case REAL: _RETURN( p_a._data.m_type m_op p_b._data._real);\ - case VECTOR2: _RETURN( p_a._data.m_type m_op *reinterpret_cast<const Vector2*>(p_b._data._mem));\ - case VECTOR3: _RETURN( p_a._data.m_type m_op *reinterpret_cast<const Vector3*>(p_b._data._mem));\ - default: {}\ - }\ - r_valid=false;\ - return;\ -}; - -#define DEFAULT_OP_STR(m_op,m_name,m_type)\ -case m_name: {\ - switch(p_b.type) {\ - case STRING: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const String*>(p_b._data._mem));\ - case NODE_PATH: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const NodePath*>(p_b._data._mem));\ - default: {}\ - }\ - r_valid=false;\ - return;\ -}; - -#define DEFAULT_OP_LOCALMEM(m_op,m_name,m_type)\ -case m_name: {switch(p_b.type) {\ - case m_name: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const m_type*>(p_b._data._mem));\ - default: {}\ -}\ -r_valid=false;\ -return;} - +#define _RETURN(m_what) \ + { \ + r_ret = m_what; \ + return; \ + } -#define DEFAULT_OP_LOCALMEM_NEG(m_name,m_type)\ -case m_name: {\ - _RETURN( -*reinterpret_cast<const m_type*>(p_a._data._mem));\ -} +#define DEFAULT_OP_NUM(m_op, m_name, m_type) \ + case m_name: { \ + switch (p_b.type) { \ + case BOOL: _RETURN(p_a._data.m_type m_op p_b._data._bool); \ + case INT: _RETURN(p_a._data.m_type m_op p_b._data._int); \ + case REAL: _RETURN(p_a._data.m_type m_op p_b._data._real); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + }; + +#define DEFAULT_OP_NUM_NEG(m_name, m_type) \ + case m_name: { \ + \ + _RETURN(-p_a._data.m_type); \ + }; + +#define DEFAULT_OP_NUM_POS(m_name, m_type) \ + case m_name: { \ + \ + _RETURN(p_a._data.m_type); \ + }; + +#define DEFAULT_OP_NUM_VEC(m_op, m_name, m_type) \ + case m_name: { \ + switch (p_b.type) { \ + case BOOL: _RETURN(p_a._data.m_type m_op p_b._data._bool); \ + case INT: _RETURN(p_a._data.m_type m_op p_b._data._int); \ + case REAL: _RETURN(p_a._data.m_type m_op p_b._data._real); \ + case VECTOR2: _RETURN(p_a._data.m_type m_op *reinterpret_cast<const Vector2 *>(p_b._data._mem)); \ + case VECTOR3: _RETURN(p_a._data.m_type m_op *reinterpret_cast<const Vector3 *>(p_b._data._mem)); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + }; + +#define DEFAULT_OP_STR(m_op, m_name, m_type) \ + case m_name: { \ + switch (p_b.type) { \ + case STRING: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const String *>(p_b._data._mem)); \ + case NODE_PATH: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const NodePath *>(p_b._data._mem)); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + }; + +#define DEFAULT_OP_LOCALMEM(m_op, m_name, m_type) \ + case m_name: { \ + switch (p_b.type) { \ + case m_name: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const m_type *>(p_b._data._mem)); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + } -#define DEFAULT_OP_LOCALMEM_POS(m_name,m_type)\ -case m_name: {\ - _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem));\ -} +#define DEFAULT_OP_LOCALMEM_NEG(m_name, m_type) \ + case m_name: { \ + _RETURN(-*reinterpret_cast<const m_type *>(p_a._data._mem)); \ + } -#define DEFAULT_OP_LOCALMEM_NUM(m_op,m_name,m_type)\ -case m_name: {switch(p_b.type) {\ - case m_name: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const m_type*>(p_b._data._mem));\ - case BOOL: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op p_b._data._bool);\ - case INT: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op p_b._data._int);\ - case REAL: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op p_b._data._real);\ - default: {}\ -}\ -r_valid=false;\ -return;} - -#define DEFAULT_OP_PTR(m_op,m_name,m_sub)\ -case m_name: {switch(p_b.type) {\ - case m_name: _RETURN( p_a._data.m_sub m_op p_b._data.m_sub);\ - default: {}\ -}\ -r_valid=false;\ -return;} - -#define DEFAULT_OP_PTRREF(m_op,m_name,m_sub)\ -case m_name: {switch(p_b.type) {\ - case m_name: _RETURN( *p_a._data.m_sub m_op *p_b._data.m_sub);\ - default: {}\ -}\ -r_valid=false;\ -return;} - -#define DEFAULT_OP_ARRAY_EQ(m_name,m_type)\ -DEFAULT_OP_ARRAY_OP(m_name,m_type,!=,!=,true,false,false) - -#define DEFAULT_OP_ARRAY_LT(m_name,m_type)\ -DEFAULT_OP_ARRAY_OP(m_name,m_type,<,!=,false,a_len<array_b.size(),true) - -#define DEFAULT_OP_ARRAY_OP(m_name,m_type,m_opa,m_opb,m_ret_def,m_ret_s,m_ret_f)\ -case m_name: { \ - if (p_a.type!=p_b.type) {\ - r_valid=false;\ - return;\ - }\ - const PoolVector<m_type> &array_a=*reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem);\ - const PoolVector<m_type> &array_b=*reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem);\ -\ - int a_len = array_a.size();\ - if (a_len m_opa array_b.size()){\ - _RETURN( m_ret_s);\ - }else {\ -\ - PoolVector<m_type>::Read ra = array_a.read();\ - PoolVector<m_type>::Read rb = array_b.read();\ -\ - for(int i=0;i<a_len;i++) {\ - if (ra[i] m_opb rb[i])\ - _RETURN( m_ret_f);\ - }\ -\ - _RETURN( m_ret_def);\ - }\ -} +#define DEFAULT_OP_LOCALMEM_POS(m_name, m_type) \ + case m_name: { \ + _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem)); \ + } -#define DEFAULT_OP_ARRAY_ADD(m_name,m_type)\ -case m_name: { \ - if (p_a.type!=p_b.type) {\ - r_valid=false;\ - _RETURN( NIL);\ - }\ - const PoolVector<m_type> &array_a=*reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem);\ - const PoolVector<m_type> &array_b=*reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem);\ - PoolVector<m_type> sum = array_a;\ - sum.append_array(array_b);\ - _RETURN( sum );\ -} +#define DEFAULT_OP_LOCALMEM_NUM(m_op, m_name, m_type) \ + case m_name: { \ + switch (p_b.type) { \ + case m_name: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const m_type *>(p_b._data._mem)); \ + case BOOL: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op p_b._data._bool); \ + case INT: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op p_b._data._int); \ + case REAL: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op p_b._data._real); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + } +#define DEFAULT_OP_PTR(m_op, m_name, m_sub) \ + case m_name: { \ + switch (p_b.type) { \ + case m_name: _RETURN(p_a._data.m_sub m_op p_b._data.m_sub); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + } +#define DEFAULT_OP_PTRREF(m_op, m_name, m_sub) \ + case m_name: { \ + switch (p_b.type) { \ + case m_name: _RETURN(*p_a._data.m_sub m_op *p_b._data.m_sub); \ + default: {} \ + } \ + r_valid = false; \ + return; \ + } -#define DEFAULT_OP_FAIL(m_name)\ -case m_name: {r_valid=false;\ -return;} +#define DEFAULT_OP_ARRAY_EQ(m_name, m_type) \ + DEFAULT_OP_ARRAY_OP(m_name, m_type, !=, !=, true, false, false) + +#define DEFAULT_OP_ARRAY_LT(m_name, m_type) \ + DEFAULT_OP_ARRAY_OP(m_name, m_type, <, !=, false, a_len < array_b.size(), true) + +#define DEFAULT_OP_ARRAY_OP(m_name, m_type, m_opa, m_opb, m_ret_def, m_ret_s, m_ret_f) \ + case m_name: { \ + if (p_a.type != p_b.type) { \ + r_valid = false; \ + return; \ + } \ + const PoolVector<m_type> &array_a = *reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem); \ + const PoolVector<m_type> &array_b = *reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem); \ + \ + int a_len = array_a.size(); \ + if (a_len m_opa array_b.size()) { \ + _RETURN(m_ret_s); \ + } else { \ + \ + PoolVector<m_type>::Read ra = array_a.read(); \ + PoolVector<m_type>::Read rb = array_b.read(); \ + \ + for (int i = 0; i < a_len; i++) { \ + if (ra[i] m_opb rb[i]) \ + _RETURN(m_ret_f); \ + } \ + \ + _RETURN(m_ret_def); \ + } \ + } +#define DEFAULT_OP_ARRAY_ADD(m_name, m_type) \ + case m_name: { \ + if (p_a.type != p_b.type) { \ + r_valid = false; \ + _RETURN(NIL); \ + } \ + const PoolVector<m_type> &array_a = *reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem); \ + const PoolVector<m_type> &array_b = *reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem); \ + PoolVector<m_type> sum = array_a; \ + sum.append_array(array_b); \ + _RETURN(sum); \ + } -void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& p_b, Variant &r_ret, bool &r_valid) { +#define DEFAULT_OP_FAIL(m_name) \ + case m_name: { \ + r_valid = false; \ + return; \ + } +void Variant::evaluate(const Operator &p_op, const Variant &p_a, const Variant &p_b, Variant &r_ret, bool &r_valid) { - r_valid=true; + r_valid = true; - switch(p_op) { + switch (p_op) { case OP_EQUAL: { - if ((int(p_a.type)*int(p_b.type))==0) { + if ((int(p_a.type) * int(p_b.type)) == 0) { //null case is an exception, one of both is null - if (p_a.type==p_b.type) //null against null is true + if (p_a.type == p_b.type) //null against null is true _RETURN(true); //only against object is allowed - if (p_a.type==Variant::OBJECT) { - _RETURN(p_a._get_obj().obj==NULL); - } else if (p_b.type==Variant::OBJECT) { - _RETURN(p_b._get_obj().obj==NULL); + if (p_a.type == Variant::OBJECT) { + _RETURN(p_a._get_obj().obj == NULL); + } else if (p_b.type == Variant::OBJECT) { + _RETURN(p_b._get_obj().obj == NULL); } //otherwise, always false _RETURN(false); } - switch(p_a.type) { + switch (p_a.type) { case NIL: { - _RETURN(p_b.type==NIL || (p_b.type==Variant::OBJECT && !p_b._get_obj().obj)); + _RETURN(p_b.type == NIL || (p_b.type == Variant::OBJECT && !p_b._get_obj().obj)); } break; - DEFAULT_OP_NUM(==,BOOL,_bool); - DEFAULT_OP_NUM(==,INT,_int); - DEFAULT_OP_NUM(==,REAL,_real); - DEFAULT_OP_STR(==,STRING,String); - DEFAULT_OP_LOCALMEM(==,VECTOR2,Vector2); - DEFAULT_OP_LOCALMEM(==,RECT2,Rect2); - DEFAULT_OP_PTRREF(==,TRANSFORM2D,_transform2d); - DEFAULT_OP_LOCALMEM(==,VECTOR3,Vector3); - DEFAULT_OP_LOCALMEM(==,PLANE,Plane); - DEFAULT_OP_LOCALMEM(==,QUAT,Quat); - DEFAULT_OP_PTRREF(==,RECT3,_rect3); - DEFAULT_OP_PTRREF(==,BASIS,_basis); - DEFAULT_OP_PTRREF(==,TRANSFORM,_transform); - - DEFAULT_OP_LOCALMEM(==,COLOR,Color); - DEFAULT_OP_PTRREF(==,IMAGE,_image); - DEFAULT_OP_STR(==,NODE_PATH,NodePath); - DEFAULT_OP_LOCALMEM(==,_RID,RID); + DEFAULT_OP_NUM(==, BOOL, _bool); + DEFAULT_OP_NUM(==, INT, _int); + DEFAULT_OP_NUM(==, REAL, _real); + DEFAULT_OP_STR(==, STRING, String); + DEFAULT_OP_LOCALMEM(==, VECTOR2, Vector2); + DEFAULT_OP_LOCALMEM(==, RECT2, Rect2); + DEFAULT_OP_PTRREF(==, TRANSFORM2D, _transform2d); + DEFAULT_OP_LOCALMEM(==, VECTOR3, Vector3); + DEFAULT_OP_LOCALMEM(==, PLANE, Plane); + DEFAULT_OP_LOCALMEM(==, QUAT, Quat); + DEFAULT_OP_PTRREF(==, RECT3, _rect3); + DEFAULT_OP_PTRREF(==, BASIS, _basis); + DEFAULT_OP_PTRREF(==, TRANSFORM, _transform); + + DEFAULT_OP_LOCALMEM(==, COLOR, Color); + DEFAULT_OP_PTRREF(==, IMAGE, _image); + DEFAULT_OP_STR(==, NODE_PATH, NodePath); + DEFAULT_OP_LOCALMEM(==, _RID, RID); case OBJECT: { - if (p_b.type==OBJECT) - _RETURN( (p_a._get_obj().obj == p_b._get_obj().obj) ); - if (p_b.type==NIL) - _RETURN( !p_a._get_obj().obj ); + if (p_b.type == OBJECT) + _RETURN((p_a._get_obj().obj == p_b._get_obj().obj)); + if (p_b.type == NIL) + _RETURN(!p_a._get_obj().obj); } break; - DEFAULT_OP_PTRREF(==,INPUT_EVENT,_input_event); + DEFAULT_OP_PTRREF(==, INPUT_EVENT, _input_event); case DICTIONARY: { - if (p_b.type!=DICTIONARY) - _RETURN( false ); + if (p_b.type != DICTIONARY) + _RETURN(false); - const Dictionary *arr_a=reinterpret_cast<const Dictionary*>(p_a._data._mem); - const Dictionary *arr_b=reinterpret_cast<const Dictionary*>(p_b._data._mem); + const Dictionary *arr_a = reinterpret_cast<const Dictionary *>(p_a._data._mem); + const Dictionary *arr_b = reinterpret_cast<const Dictionary *>(p_b._data._mem); - _RETURN( *arr_a == *arr_b ); + _RETURN(*arr_a == *arr_b); } break; case ARRAY: { - if (p_b.type!=ARRAY) - _RETURN( false ); + if (p_b.type != ARRAY) + _RETURN(false); - const Array *arr_a=reinterpret_cast<const Array*>(p_a._data._mem); - const Array *arr_b=reinterpret_cast<const Array*>(p_b._data._mem); + const Array *arr_a = reinterpret_cast<const Array *>(p_a._data._mem); + const Array *arr_b = reinterpret_cast<const Array *>(p_b._data._mem); int l = arr_a->size(); - if (arr_b->size()!=l) - _RETURN( false ); - for(int i=0;i<l;i++) { - if (!((*arr_a)[i]==(*arr_b)[i])) { - _RETURN( false ); + if (arr_b->size() != l) + _RETURN(false); + for (int i = 0; i < l; i++) { + if (!((*arr_a)[i] == (*arr_b)[i])) { + _RETURN(false); } } - _RETURN( true ); + _RETURN(true); } break; - - DEFAULT_OP_ARRAY_EQ(POOL_BYTE_ARRAY,uint8_t); - DEFAULT_OP_ARRAY_EQ(POOL_INT_ARRAY,int); - DEFAULT_OP_ARRAY_EQ(POOL_REAL_ARRAY,real_t); - DEFAULT_OP_ARRAY_EQ(POOL_STRING_ARRAY,String); - DEFAULT_OP_ARRAY_EQ(POOL_VECTOR2_ARRAY,Vector3); - DEFAULT_OP_ARRAY_EQ(POOL_VECTOR3_ARRAY,Vector3); - DEFAULT_OP_ARRAY_EQ(POOL_COLOR_ARRAY,Color); + DEFAULT_OP_ARRAY_EQ(POOL_BYTE_ARRAY, uint8_t); + DEFAULT_OP_ARRAY_EQ(POOL_INT_ARRAY, int); + DEFAULT_OP_ARRAY_EQ(POOL_REAL_ARRAY, real_t); + DEFAULT_OP_ARRAY_EQ(POOL_STRING_ARRAY, String); + DEFAULT_OP_ARRAY_EQ(POOL_VECTOR2_ARRAY, Vector3); + DEFAULT_OP_ARRAY_EQ(POOL_VECTOR3_ARRAY, Vector3); + DEFAULT_OP_ARRAY_EQ(POOL_COLOR_ARRAY, Color); case VARIANT_MAX: { - r_valid=false; + r_valid = false; return; } break; - - } } break; case OP_NOT_EQUAL: { Variant res; - evaluate(OP_EQUAL,p_a,p_b,res,r_valid); + evaluate(OP_EQUAL, p_a, p_b, res, r_valid); if (!r_valid) return; - if (res.type==BOOL) - res._data._bool=!res._data._bool; - _RETURN( res ); + if (res.type == BOOL) + res._data._bool = !res._data._bool; + _RETURN(res); } break; case OP_LESS: { - switch(p_a.type) { + switch (p_a.type) { DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM(<,BOOL,_bool); - DEFAULT_OP_NUM(<,INT,_int); - DEFAULT_OP_NUM(<,REAL,_real); - DEFAULT_OP_STR(<,STRING,String); - DEFAULT_OP_LOCALMEM(<,VECTOR2,Vector2); + DEFAULT_OP_NUM(<, BOOL, _bool); + DEFAULT_OP_NUM(<, INT, _int); + DEFAULT_OP_NUM(<, REAL, _real); + DEFAULT_OP_STR(<, STRING, String); + DEFAULT_OP_LOCALMEM(<, VECTOR2, Vector2); DEFAULT_OP_FAIL(RECT2); DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_LOCALMEM(<,VECTOR3,Vector3); + DEFAULT_OP_LOCALMEM(<, VECTOR3, Vector3); DEFAULT_OP_FAIL(PLANE); DEFAULT_OP_FAIL(QUAT); DEFAULT_OP_FAIL(RECT3); @@ -367,63 +373,62 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& DEFAULT_OP_FAIL(COLOR); DEFAULT_OP_FAIL(IMAGE); DEFAULT_OP_FAIL(NODE_PATH); - DEFAULT_OP_LOCALMEM(<,_RID,RID); + DEFAULT_OP_LOCALMEM(<, _RID, RID); case OBJECT: { - if (p_b.type==OBJECT) - _RETURN( (p_a._get_obj().obj < p_b._get_obj().obj) ); + if (p_b.type == OBJECT) + _RETURN((p_a._get_obj().obj < p_b._get_obj().obj)); } break; - DEFAULT_OP_FAIL(INPUT_EVENT); - DEFAULT_OP_FAIL(DICTIONARY); + DEFAULT_OP_FAIL(INPUT_EVENT); + DEFAULT_OP_FAIL(DICTIONARY); case ARRAY: { - if (p_b.type!=ARRAY) - _RETURN( false ); + if (p_b.type != ARRAY) + _RETURN(false); - const Array *arr_a=reinterpret_cast<const Array*>(p_a._data._mem); - const Array *arr_b=reinterpret_cast<const Array*>(p_b._data._mem); + const Array *arr_a = reinterpret_cast<const Array *>(p_a._data._mem); + const Array *arr_b = reinterpret_cast<const Array *>(p_b._data._mem); int l = arr_a->size(); - if (arr_b->size()<l) - _RETURN( false ); - for(int i=0;i<l;i++) { - if (!((*arr_a)[i]<(*arr_b)[i])) { - _RETURN( true ); + if (arr_b->size() < l) + _RETURN(false); + for (int i = 0; i < l; i++) { + if (!((*arr_a)[i] < (*arr_b)[i])) { + _RETURN(true); } } - _RETURN( false ); + _RETURN(false); } break; - DEFAULT_OP_ARRAY_LT(POOL_BYTE_ARRAY,uint8_t); - DEFAULT_OP_ARRAY_LT(POOL_INT_ARRAY,int); - DEFAULT_OP_ARRAY_LT(POOL_REAL_ARRAY,real_t); - DEFAULT_OP_ARRAY_LT(POOL_STRING_ARRAY,String); - DEFAULT_OP_ARRAY_LT(POOL_VECTOR2_ARRAY,Vector3); - DEFAULT_OP_ARRAY_LT(POOL_VECTOR3_ARRAY,Vector3); - DEFAULT_OP_ARRAY_LT(POOL_COLOR_ARRAY,Color); + DEFAULT_OP_ARRAY_LT(POOL_BYTE_ARRAY, uint8_t); + DEFAULT_OP_ARRAY_LT(POOL_INT_ARRAY, int); + DEFAULT_OP_ARRAY_LT(POOL_REAL_ARRAY, real_t); + DEFAULT_OP_ARRAY_LT(POOL_STRING_ARRAY, String); + DEFAULT_OP_ARRAY_LT(POOL_VECTOR2_ARRAY, Vector3); + DEFAULT_OP_ARRAY_LT(POOL_VECTOR3_ARRAY, Vector3); + DEFAULT_OP_ARRAY_LT(POOL_COLOR_ARRAY, Color); case VARIANT_MAX: { - r_valid=false; + r_valid = false; return; } break; - } } break; case OP_LESS_EQUAL: { - switch(p_a.type) { + switch (p_a.type) { DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM(<=,BOOL,_bool); - DEFAULT_OP_NUM(<=,INT,_int); - DEFAULT_OP_NUM(<=,REAL,_real); - DEFAULT_OP_STR(<=,STRING,String); - DEFAULT_OP_LOCALMEM(<=,VECTOR2,Vector2); + DEFAULT_OP_NUM(<=, BOOL, _bool); + DEFAULT_OP_NUM(<=, INT, _int); + DEFAULT_OP_NUM(<=, REAL, _real); + DEFAULT_OP_STR(<=, STRING, String); + DEFAULT_OP_LOCALMEM(<=, VECTOR2, Vector2); DEFAULT_OP_FAIL(RECT2); DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_LOCALMEM(<=,VECTOR3,Vector3); + DEFAULT_OP_LOCALMEM(<=, VECTOR3, Vector3); DEFAULT_OP_FAIL(PLANE); DEFAULT_OP_FAIL(QUAT); DEFAULT_OP_FAIL(RECT3); @@ -433,35 +438,34 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& DEFAULT_OP_FAIL(COLOR); DEFAULT_OP_FAIL(IMAGE); DEFAULT_OP_FAIL(NODE_PATH); - DEFAULT_OP_LOCALMEM(<=,_RID,RID); + DEFAULT_OP_LOCALMEM(<=, _RID, RID); case OBJECT: { - if (p_b.type==OBJECT) - _RETURN( (p_a._get_obj().obj <= p_b._get_obj().obj) ); + if (p_b.type == OBJECT) + _RETURN((p_a._get_obj().obj <= p_b._get_obj().obj)); } break; - DEFAULT_OP_FAIL(INPUT_EVENT); - DEFAULT_OP_FAIL(DICTIONARY); - DEFAULT_OP_FAIL(ARRAY); - DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); - DEFAULT_OP_FAIL(POOL_INT_ARRAY); - DEFAULT_OP_FAIL(POOL_REAL_ARRAY); - DEFAULT_OP_FAIL(POOL_STRING_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); - DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); + DEFAULT_OP_FAIL(INPUT_EVENT); + DEFAULT_OP_FAIL(DICTIONARY); + DEFAULT_OP_FAIL(ARRAY); + DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); + DEFAULT_OP_FAIL(POOL_INT_ARRAY); + DEFAULT_OP_FAIL(POOL_REAL_ARRAY); + DEFAULT_OP_FAIL(POOL_STRING_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); + DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); case VARIANT_MAX: { - r_valid=false; + r_valid = false; return; } break; - } } break; case OP_GREATER: { Variant res; - evaluate(OP_LESS,p_b,p_a,res,r_valid); + evaluate(OP_LESS, p_b, p_a, res, r_valid); if (!r_valid) return; _RETURN(res); @@ -470,82 +474,81 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& case OP_GREATER_EQUAL: { Variant res; - evaluate(OP_LESS_EQUAL,p_b,p_a,res,r_valid); + evaluate(OP_LESS_EQUAL, p_b, p_a, res, r_valid); if (!r_valid) return; - _RETURN( res ); + _RETURN(res); } break; //mathematic case OP_ADD: { - switch(p_a.type) { - - DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM(+,BOOL,_bool); - DEFAULT_OP_NUM(+,INT,_int); - DEFAULT_OP_NUM(+,REAL,_real); - DEFAULT_OP_STR(+,STRING,String); - DEFAULT_OP_LOCALMEM(+,VECTOR2,Vector2); - DEFAULT_OP_FAIL(RECT2); - DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_LOCALMEM(+,VECTOR3,Vector3); - DEFAULT_OP_FAIL(PLANE); - DEFAULT_OP_LOCALMEM(+, QUAT, Quat); - DEFAULT_OP_FAIL(RECT3); - DEFAULT_OP_FAIL(BASIS); - DEFAULT_OP_FAIL(TRANSFORM); + switch (p_a.type) { - DEFAULT_OP_FAIL(COLOR); - DEFAULT_OP_FAIL(IMAGE); - DEFAULT_OP_FAIL(NODE_PATH); - DEFAULT_OP_FAIL(_RID); - DEFAULT_OP_FAIL(OBJECT); - DEFAULT_OP_FAIL(INPUT_EVENT); - DEFAULT_OP_FAIL(DICTIONARY); + DEFAULT_OP_FAIL(NIL); + DEFAULT_OP_NUM(+, BOOL, _bool); + DEFAULT_OP_NUM(+, INT, _int); + DEFAULT_OP_NUM(+, REAL, _real); + DEFAULT_OP_STR(+, STRING, String); + DEFAULT_OP_LOCALMEM(+, VECTOR2, Vector2); + DEFAULT_OP_FAIL(RECT2); + DEFAULT_OP_FAIL(TRANSFORM2D); + DEFAULT_OP_LOCALMEM(+, VECTOR3, Vector3); + DEFAULT_OP_FAIL(PLANE); + DEFAULT_OP_LOCALMEM(+, QUAT, Quat); + DEFAULT_OP_FAIL(RECT3); + DEFAULT_OP_FAIL(BASIS); + DEFAULT_OP_FAIL(TRANSFORM); - case ARRAY: { - if (p_a.type!=p_b.type) { - r_valid=false; - return; - } - const Array &array_a=*reinterpret_cast<const Array *>(p_a._data._mem); - const Array &array_b=*reinterpret_cast<const Array *>(p_b._data._mem); - Array sum; - int asize=array_a.size(); - int bsize=array_b.size(); - sum.resize(asize+bsize); - for(int i=0;i<asize;i++) - sum[i]=array_a[i]; - for(int i=0;i<bsize;i++) - sum[i+asize]=array_b[i]; - _RETURN( sum ); - } - DEFAULT_OP_ARRAY_ADD(POOL_BYTE_ARRAY,uint8_t); - DEFAULT_OP_ARRAY_ADD(POOL_INT_ARRAY,int); - DEFAULT_OP_ARRAY_ADD(POOL_REAL_ARRAY,real_t); - DEFAULT_OP_ARRAY_ADD(POOL_STRING_ARRAY,String); - DEFAULT_OP_ARRAY_ADD(POOL_VECTOR2_ARRAY,Vector2); - DEFAULT_OP_ARRAY_ADD(POOL_VECTOR3_ARRAY,Vector3); - DEFAULT_OP_ARRAY_ADD(POOL_COLOR_ARRAY,Color); - case VARIANT_MAX: { - r_valid=false; - return; + DEFAULT_OP_FAIL(COLOR); + DEFAULT_OP_FAIL(IMAGE); + DEFAULT_OP_FAIL(NODE_PATH); + DEFAULT_OP_FAIL(_RID); + DEFAULT_OP_FAIL(OBJECT); + DEFAULT_OP_FAIL(INPUT_EVENT); + DEFAULT_OP_FAIL(DICTIONARY); - } break; + case ARRAY: { + if (p_a.type != p_b.type) { + r_valid = false; + return; + } + const Array &array_a = *reinterpret_cast<const Array *>(p_a._data._mem); + const Array &array_b = *reinterpret_cast<const Array *>(p_b._data._mem); + Array sum; + int asize = array_a.size(); + int bsize = array_b.size(); + sum.resize(asize + bsize); + for (int i = 0; i < asize; i++) + sum[i] = array_a[i]; + for (int i = 0; i < bsize; i++) + sum[i + asize] = array_b[i]; + _RETURN(sum); + } + DEFAULT_OP_ARRAY_ADD(POOL_BYTE_ARRAY, uint8_t); + DEFAULT_OP_ARRAY_ADD(POOL_INT_ARRAY, int); + DEFAULT_OP_ARRAY_ADD(POOL_REAL_ARRAY, real_t); + DEFAULT_OP_ARRAY_ADD(POOL_STRING_ARRAY, String); + DEFAULT_OP_ARRAY_ADD(POOL_VECTOR2_ARRAY, Vector2); + DEFAULT_OP_ARRAY_ADD(POOL_VECTOR3_ARRAY, Vector3); + DEFAULT_OP_ARRAY_ADD(POOL_COLOR_ARRAY, Color); + case VARIANT_MAX: { + r_valid = false; + return; - } + } break; + } } break; case OP_SUBSTRACT: { - switch(p_a.type) { + switch (p_a.type) { DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM(-,BOOL,_bool); - DEFAULT_OP_NUM(-,INT,_int); - DEFAULT_OP_NUM(-,REAL,_real); + DEFAULT_OP_NUM(-, BOOL, _bool); + DEFAULT_OP_NUM(-, INT, _int); + DEFAULT_OP_NUM(-, REAL, _real); DEFAULT_OP_FAIL(STRING); - DEFAULT_OP_LOCALMEM(-,VECTOR2,Vector2); + DEFAULT_OP_LOCALMEM(-, VECTOR2, Vector2); DEFAULT_OP_FAIL(RECT2); DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_LOCALMEM(-,VECTOR3,Vector3); + DEFAULT_OP_LOCALMEM(-, VECTOR3, Vector3); DEFAULT_OP_FAIL(PLANE); DEFAULT_OP_LOCALMEM(-, QUAT, Quat); DEFAULT_OP_FAIL(RECT3); @@ -568,165 +571,201 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); case VARIANT_MAX: { - r_valid=false; + r_valid = false; return; } break; - } } break; case OP_MULTIPLY: { - switch(p_a.type) { + switch (p_a.type) { DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM(*,BOOL,_bool); - DEFAULT_OP_NUM_VEC(*,INT,_int); - DEFAULT_OP_NUM_VEC(*,REAL,_real); + DEFAULT_OP_NUM(*, BOOL, _bool); + DEFAULT_OP_NUM_VEC(*, INT, _int); + DEFAULT_OP_NUM_VEC(*, REAL, _real); DEFAULT_OP_FAIL(STRING); - DEFAULT_OP_LOCALMEM_NUM(*,VECTOR2,Vector2); + DEFAULT_OP_LOCALMEM_NUM(*, VECTOR2, Vector2); DEFAULT_OP_FAIL(RECT2); case TRANSFORM2D: { - if (p_b.type==TRANSFORM2D) { - _RETURN( *p_a._data._transform2d * *p_b._data._transform2d ); + if (p_b.type == TRANSFORM2D) { + _RETURN(*p_a._data._transform2d * *p_b._data._transform2d); }; - if (p_b.type==VECTOR2) { - _RETURN( p_a._data._transform2d->xform( *(const Vector2*)p_b._data._mem) ); + if (p_b.type == VECTOR2) { + _RETURN(p_a._data._transform2d->xform(*(const Vector2 *)p_b._data._mem)); }; - r_valid=false; + r_valid = false; return; } break; - DEFAULT_OP_LOCALMEM_NUM(*,VECTOR3,Vector3); - DEFAULT_OP_FAIL(PLANE); + DEFAULT_OP_LOCALMEM_NUM(*, VECTOR3, Vector3); + DEFAULT_OP_FAIL(PLANE); case QUAT: { - switch(p_b.type) { + switch (p_b.type) { case VECTOR3: { - _RETURN( reinterpret_cast<const Quat*>(p_a._data._mem)->xform( *(const Vector3*)p_b._data._mem) ); + _RETURN(reinterpret_cast<const Quat *>(p_a._data._mem)->xform(*(const Vector3 *)p_b._data._mem)); } break; case QUAT: { - _RETURN( *reinterpret_cast<const Quat*>(p_a._data._mem) * *reinterpret_cast<const Quat*>(p_b._data._mem) ); + _RETURN(*reinterpret_cast<const Quat *>(p_a._data._mem) * *reinterpret_cast<const Quat *>(p_b._data._mem)); } break; case REAL: { - _RETURN( *reinterpret_cast<const Quat*>(p_a._data._mem) * p_b._data._real); + _RETURN(*reinterpret_cast<const Quat *>(p_a._data._mem) * p_b._data._real); } break; default: {} }; - r_valid=false; + r_valid = false; return; } break; - DEFAULT_OP_FAIL(RECT3); + DEFAULT_OP_FAIL(RECT3); case BASIS: { - switch(p_b.type) { + switch (p_b.type) { case VECTOR3: { - _RETURN( p_a._data._basis->xform( *(const Vector3*)p_b._data._mem) ); - - } ; + _RETURN(p_a._data._basis->xform(*(const Vector3 *)p_b._data._mem)); + }; case BASIS: { - _RETURN( *p_a._data._basis * *p_b._data._basis ); - + _RETURN(*p_a._data._basis * *p_b._data._basis); }; default: {} - } ; - r_valid=false; + }; + r_valid = false; return; } break; case TRANSFORM: { - switch(p_b.type) { + switch (p_b.type) { case VECTOR3: { - _RETURN( p_a._data._transform->xform( *(const Vector3*)p_b._data._mem) ); - - } ; + _RETURN(p_a._data._transform->xform(*(const Vector3 *)p_b._data._mem)); + }; case TRANSFORM: { - _RETURN( *p_a._data._transform * *p_b._data._transform ); - + _RETURN(*p_a._data._transform * *p_b._data._transform); }; default: {} - } ; - r_valid=false; + }; + r_valid = false; return; } break; - DEFAULT_OP_FAIL(COLOR); - DEFAULT_OP_FAIL(IMAGE); - DEFAULT_OP_FAIL(NODE_PATH); - DEFAULT_OP_FAIL(_RID); - DEFAULT_OP_FAIL(OBJECT); - DEFAULT_OP_FAIL(INPUT_EVENT); - DEFAULT_OP_FAIL(DICTIONARY); - DEFAULT_OP_FAIL(ARRAY); - DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); - DEFAULT_OP_FAIL(POOL_INT_ARRAY); - DEFAULT_OP_FAIL(POOL_REAL_ARRAY); - DEFAULT_OP_FAIL(POOL_STRING_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); - DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); + DEFAULT_OP_FAIL(COLOR); + DEFAULT_OP_FAIL(IMAGE); + DEFAULT_OP_FAIL(NODE_PATH); + DEFAULT_OP_FAIL(_RID); + DEFAULT_OP_FAIL(OBJECT); + DEFAULT_OP_FAIL(INPUT_EVENT); + DEFAULT_OP_FAIL(DICTIONARY); + DEFAULT_OP_FAIL(ARRAY); + DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); + DEFAULT_OP_FAIL(POOL_INT_ARRAY); + DEFAULT_OP_FAIL(POOL_REAL_ARRAY); + DEFAULT_OP_FAIL(POOL_STRING_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); + DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); case VARIANT_MAX: { - r_valid=false; + r_valid = false; return; } break; - } } break; case OP_DIVIDE: { - switch(p_a.type) { + switch (p_a.type) { DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM(/,BOOL,_bool); + DEFAULT_OP_NUM(/, BOOL, _bool); case INT: { - switch(p_b.type) { + switch (p_b.type) { case BOOL: { int64_t b = p_b._data._bool; - if (b==0) { + if (b == 0) { - r_valid=false; - _RETURN( "Division By False" ); + r_valid = false; + _RETURN("Division By False"); } - _RETURN( p_a._data._int / b ); + _RETURN(p_a._data._int / b); } break; case INT: { int64_t b = p_b._data._int; - if (b==0) { + if (b == 0) { - r_valid=false; - _RETURN( "Division By Zero" ); + r_valid = false; + _RETURN("Division By Zero"); } - _RETURN( p_a._data._int / b ); + _RETURN(p_a._data._int / b); } break; - case REAL: _RETURN( p_a._data._int / p_b._data._real ); + case REAL: _RETURN(p_a._data._int / p_b._data._real); default: {} } - r_valid=false; + r_valid = false; return; }; - DEFAULT_OP_NUM(/,REAL,_real); - DEFAULT_OP_FAIL(STRING); - DEFAULT_OP_LOCALMEM_NUM(/,VECTOR2,Vector2); - DEFAULT_OP_FAIL(RECT2); - DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_LOCALMEM_NUM(/,VECTOR3,Vector3); - DEFAULT_OP_FAIL(PLANE); + DEFAULT_OP_NUM(/, REAL, _real); + DEFAULT_OP_FAIL(STRING); + DEFAULT_OP_LOCALMEM_NUM(/, VECTOR2, Vector2); + DEFAULT_OP_FAIL(RECT2); + DEFAULT_OP_FAIL(TRANSFORM2D); + DEFAULT_OP_LOCALMEM_NUM(/, VECTOR3, Vector3); + DEFAULT_OP_FAIL(PLANE); case QUAT: { if (p_b.type != REAL) { r_valid = false; return; } - _RETURN( *reinterpret_cast<const Quat*>(p_a._data._mem) / p_b._data._real); + _RETURN(*reinterpret_cast<const Quat *>(p_a._data._mem) / p_b._data._real); } break; + DEFAULT_OP_FAIL(RECT3); + DEFAULT_OP_FAIL(BASIS); + DEFAULT_OP_FAIL(TRANSFORM); + + DEFAULT_OP_FAIL(COLOR); + DEFAULT_OP_FAIL(IMAGE); + DEFAULT_OP_FAIL(NODE_PATH); + DEFAULT_OP_FAIL(_RID); + DEFAULT_OP_FAIL(OBJECT); + DEFAULT_OP_FAIL(INPUT_EVENT); + DEFAULT_OP_FAIL(DICTIONARY); + DEFAULT_OP_FAIL(ARRAY); + DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); + DEFAULT_OP_FAIL(POOL_INT_ARRAY); + DEFAULT_OP_FAIL(POOL_REAL_ARRAY); + DEFAULT_OP_FAIL(POOL_STRING_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); + DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); + case VARIANT_MAX: { + r_valid = false; + return; + + } break; + } + + } break; + case OP_POSITIVE: { + // Simple case when user defines variable as +value. + switch (p_a.type) { + + DEFAULT_OP_FAIL(NIL); + DEFAULT_OP_FAIL(STRING); + DEFAULT_OP_FAIL(RECT2); + DEFAULT_OP_FAIL(TRANSFORM2D); DEFAULT_OP_FAIL(RECT3); DEFAULT_OP_FAIL(BASIS); DEFAULT_OP_FAIL(TRANSFORM); + DEFAULT_OP_NUM_POS(BOOL, _bool); + DEFAULT_OP_NUM_POS(INT, _int); + DEFAULT_OP_NUM_POS(REAL, _real); + DEFAULT_OP_LOCALMEM_POS(VECTOR3, Vector3); + DEFAULT_OP_LOCALMEM_POS(PLANE, Plane); + DEFAULT_OP_LOCALMEM_POS(QUAT, Quat); + DEFAULT_OP_LOCALMEM_POS(VECTOR2, Vector2); DEFAULT_OP_FAIL(COLOR); DEFAULT_OP_FAIL(IMAGE); @@ -744,182 +783,138 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); case VARIANT_MAX: { - r_valid=false; + r_valid = false; return; } break; - } - - } break; - case OP_POSITIVE: { - // Simple case when user defines variable as +value. - switch(p_a.type) { - - DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_FAIL(STRING); - DEFAULT_OP_FAIL(RECT2); - DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_FAIL(RECT3); - DEFAULT_OP_FAIL(BASIS); - DEFAULT_OP_FAIL(TRANSFORM); - DEFAULT_OP_NUM_POS(BOOL,_bool); - DEFAULT_OP_NUM_POS(INT,_int); - DEFAULT_OP_NUM_POS(REAL,_real); - DEFAULT_OP_LOCALMEM_POS(VECTOR3,Vector3); - DEFAULT_OP_LOCALMEM_POS(PLANE,Plane); - DEFAULT_OP_LOCALMEM_POS(QUAT,Quat); - DEFAULT_OP_LOCALMEM_POS(VECTOR2,Vector2); - - DEFAULT_OP_FAIL(COLOR); - DEFAULT_OP_FAIL(IMAGE); - DEFAULT_OP_FAIL(NODE_PATH); - DEFAULT_OP_FAIL(_RID); - DEFAULT_OP_FAIL(OBJECT); - DEFAULT_OP_FAIL(INPUT_EVENT); - DEFAULT_OP_FAIL(DICTIONARY); - DEFAULT_OP_FAIL(ARRAY); - DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); - DEFAULT_OP_FAIL(POOL_INT_ARRAY); - DEFAULT_OP_FAIL(POOL_REAL_ARRAY); - DEFAULT_OP_FAIL(POOL_STRING_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); - DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); - case VARIANT_MAX: { - r_valid=false; - return; - - } break; - - } } break; case OP_NEGATE: { - switch(p_a.type) { + switch (p_a.type) { - DEFAULT_OP_FAIL(NIL); - DEFAULT_OP_NUM_NEG(BOOL,_bool); - DEFAULT_OP_NUM_NEG(INT,_int); - DEFAULT_OP_NUM_NEG(REAL,_real); - DEFAULT_OP_FAIL(STRING); - DEFAULT_OP_LOCALMEM_NEG(VECTOR2,Vector2); - DEFAULT_OP_FAIL(RECT2); - DEFAULT_OP_FAIL(TRANSFORM2D); - DEFAULT_OP_LOCALMEM_NEG(VECTOR3,Vector3); - DEFAULT_OP_LOCALMEM_NEG(PLANE,Plane); - DEFAULT_OP_LOCALMEM_NEG(QUAT,Quat); - DEFAULT_OP_FAIL(RECT3); - DEFAULT_OP_FAIL(BASIS); - DEFAULT_OP_FAIL(TRANSFORM); + DEFAULT_OP_FAIL(NIL); + DEFAULT_OP_NUM_NEG(BOOL, _bool); + DEFAULT_OP_NUM_NEG(INT, _int); + DEFAULT_OP_NUM_NEG(REAL, _real); + DEFAULT_OP_FAIL(STRING); + DEFAULT_OP_LOCALMEM_NEG(VECTOR2, Vector2); + DEFAULT_OP_FAIL(RECT2); + DEFAULT_OP_FAIL(TRANSFORM2D); + DEFAULT_OP_LOCALMEM_NEG(VECTOR3, Vector3); + DEFAULT_OP_LOCALMEM_NEG(PLANE, Plane); + DEFAULT_OP_LOCALMEM_NEG(QUAT, Quat); + DEFAULT_OP_FAIL(RECT3); + DEFAULT_OP_FAIL(BASIS); + DEFAULT_OP_FAIL(TRANSFORM); - DEFAULT_OP_FAIL(COLOR); - DEFAULT_OP_FAIL(IMAGE); - DEFAULT_OP_FAIL(NODE_PATH); - DEFAULT_OP_FAIL(_RID); - DEFAULT_OP_FAIL(OBJECT); - DEFAULT_OP_FAIL(INPUT_EVENT); - DEFAULT_OP_FAIL(DICTIONARY); - DEFAULT_OP_FAIL(ARRAY); - DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); - DEFAULT_OP_FAIL(POOL_INT_ARRAY); - DEFAULT_OP_FAIL(POOL_REAL_ARRAY); - DEFAULT_OP_FAIL(POOL_STRING_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); - DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); - DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); - case VARIANT_MAX: { - r_valid=false; - return; + DEFAULT_OP_FAIL(COLOR); + DEFAULT_OP_FAIL(IMAGE); + DEFAULT_OP_FAIL(NODE_PATH); + DEFAULT_OP_FAIL(_RID); + DEFAULT_OP_FAIL(OBJECT); + DEFAULT_OP_FAIL(INPUT_EVENT); + DEFAULT_OP_FAIL(DICTIONARY); + DEFAULT_OP_FAIL(ARRAY); + DEFAULT_OP_FAIL(POOL_BYTE_ARRAY); + DEFAULT_OP_FAIL(POOL_INT_ARRAY); + DEFAULT_OP_FAIL(POOL_REAL_ARRAY); + DEFAULT_OP_FAIL(POOL_STRING_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY); + DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY); + DEFAULT_OP_FAIL(POOL_COLOR_ARRAY); + case VARIANT_MAX: { + r_valid = false; + return; - } break; - } + } break; + } } break; case OP_MODULE: { - if (p_a.type==INT && p_b.type==INT) { + if (p_a.type == INT && p_b.type == INT) { #ifdef DEBUG_ENABLED - if (p_b._data._int==0) { - r_valid=false; - _RETURN( "Division By Zero" ); + if (p_b._data._int == 0) { + r_valid = false; + _RETURN("Division By Zero"); } #endif - _RETURN( p_a._data._int % p_b._data._int ); + _RETURN(p_a._data._int % p_b._data._int); - } else if (p_a.type==STRING) { - const String* format=reinterpret_cast<const String*>(p_a._data._mem); + } else if (p_a.type == STRING) { + const String *format = reinterpret_cast<const String *>(p_a._data._mem); String result; bool error; - if (p_b.type==ARRAY) { + if (p_b.type == ARRAY) { // e.g. "frog %s %d" % ["fish", 12] - const Array* args=reinterpret_cast<const Array*>(p_b._data._mem); - result=format->sprintf(*args, &error); + const Array *args = reinterpret_cast<const Array *>(p_b._data._mem); + result = format->sprintf(*args, &error); } else { // e.g. "frog %d" % 12 Array args; args.push_back(p_b); - result=format->sprintf(args, &error); + result = format->sprintf(args, &error); } r_valid = !error; _RETURN(result); } - r_valid=false; + r_valid = false; return; } break; case OP_STRING_CONCAT: { - _RETURN( p_a.operator String() + p_b.operator String() ); + _RETURN(p_a.operator String() + p_b.operator String()); } break; //bitwise case OP_SHIFT_LEFT: { - if (p_a.type==INT && p_b.type==INT) - _RETURN( p_a._data._int << p_b._data._int ); + if (p_a.type == INT && p_b.type == INT) + _RETURN(p_a._data._int << p_b._data._int); - r_valid=false; + r_valid = false; return; } break; case OP_SHIFT_RIGHT: { - if (p_a.type==INT && p_b.type==INT) - _RETURN( p_a._data._int >> p_b._data._int ); + if (p_a.type == INT && p_b.type == INT) + _RETURN(p_a._data._int >> p_b._data._int); - r_valid=false; + r_valid = false; return; } break; case OP_BIT_AND: { - if (p_a.type==INT && p_b.type==INT) - _RETURN( p_a._data._int & p_b._data._int ); + if (p_a.type == INT && p_b.type == INT) + _RETURN(p_a._data._int & p_b._data._int); - r_valid=false; + r_valid = false; return; } break; case OP_BIT_OR: { - if (p_a.type==INT && p_b.type==INT) - _RETURN( p_a._data._int | p_b._data._int ); + if (p_a.type == INT && p_b.type == INT) + _RETURN(p_a._data._int | p_b._data._int); - r_valid=false; + r_valid = false; return; } break; case OP_BIT_XOR: { - if (p_a.type==INT && p_b.type==INT) - _RETURN( p_a._data._int ^ p_b._data._int ); + if (p_a.type == INT && p_b.type == INT) + _RETURN(p_a._data._int ^ p_b._data._int); - r_valid=false; + r_valid = false; return; } break; case OP_BIT_NEGATE: { - if (p_a.type==INT) - _RETURN( ~p_a._data._int ); + if (p_a.type == INT) + _RETURN(~p_a._data._int); - r_valid=false; + r_valid = false; return; } break; @@ -932,7 +927,7 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& if (!r_valid) return; - _RETURN( l && r ); + _RETURN(l && r); } break; case OP_OR: { bool l = p_a.booleanize(r_valid); @@ -942,7 +937,7 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& if (!r_valid) return; - _RETURN( l || r ); + _RETURN(l || r); } break; case OP_XOR: { @@ -953,246 +948,249 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& if (!r_valid) return; - _RETURN( (l || r) && !(l && r) ); + _RETURN((l || r) && !(l && r)); } break; case OP_NOT: { bool l = p_a.booleanize(r_valid); if (!r_valid) return; - _RETURN( !l ); + _RETURN(!l); } break; case OP_IN: { - _RETURN( p_b.in(p_a,&r_valid) ); + _RETURN(p_b.in(p_a, &r_valid)); } break; case OP_MAX: { - r_valid=false; + r_valid = false; ERR_FAIL(); } - } - r_valid=false; + r_valid = false; } -void Variant::set_named(const StringName& p_index, const Variant& p_value, bool *r_valid) { +void Variant::set_named(const StringName &p_index, const Variant &p_value, bool *r_valid) { - if (type==OBJECT) { + if (type == OBJECT) { #ifdef DEBUG_ENABLED if (!_get_obj().obj) { if (r_valid) - *r_valid=false; + *r_valid = false; return; } else { if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) { if (r_valid) - *r_valid=false; + *r_valid = false; return; } - } #endif - _get_obj().obj->set(p_index,p_value,r_valid); + _get_obj().obj->set(p_index, p_value, r_valid); return; } - set(p_index.operator String(),p_value,r_valid); + set(p_index.operator String(), p_value, r_valid); } -Variant Variant::get_named(const StringName& p_index, bool *r_valid) const { +Variant Variant::get_named(const StringName &p_index, bool *r_valid) const { - if (type==OBJECT) { + if (type == OBJECT) { #ifdef DEBUG_ENABLED if (!_get_obj().obj) { if (r_valid) - *r_valid=false; + *r_valid = false; return "Instance base is null."; } else { if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) { if (r_valid) - *r_valid=false; + *r_valid = false; return "Attempted use of stray pointer object."; } } #endif - return _get_obj().obj->get(p_index,r_valid); + return _get_obj().obj->get(p_index, r_valid); } - return get(p_index.operator String(),r_valid); + return get(p_index.operator String(), r_valid); } - -#define DEFAULT_OP_ARRAY_CMD(m_name, m_type, skip_test, cmd)\ - case m_name: {\ - skip_test;\ -\ - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {\ - int index = p_index;\ - m_type *arr=reinterpret_cast<m_type* >(_data._mem);\ -\ - if (index<0)\ - index += arr->size();\ - if (index>=0 && index<arr->size()) {\ - valid=true;\ - cmd;\ - }\ - }\ +#define DEFAULT_OP_ARRAY_CMD(m_name, m_type, skip_test, cmd) \ + case m_name: { \ + skip_test; \ + \ + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { \ + int index = p_index; \ + m_type *arr = reinterpret_cast<m_type *>(_data._mem); \ + \ + if (index < 0) \ + index += arr->size(); \ + if (index >= 0 && index < arr->size()) { \ + valid = true; \ + cmd; \ + } \ + } \ } break; -#define DEFAULT_OP_DVECTOR_SET(m_name, dv_type, skip_cond)\ - DEFAULT_OP_ARRAY_CMD(m_name, PoolVector<dv_type>, if(skip_cond) return;, arr->set(index, p_value);return) +#define DEFAULT_OP_DVECTOR_SET(m_name, dv_type, skip_cond) \ + DEFAULT_OP_ARRAY_CMD(m_name, PoolVector<dv_type>, if (skip_cond) return;, arr->set(index, p_value); return ) -#define DEFAULT_OP_DVECTOR_GET(m_name, dv_type)\ +#define DEFAULT_OP_DVECTOR_GET(m_name, dv_type) \ DEFAULT_OP_ARRAY_CMD(m_name, const PoolVector<dv_type>, ;, return arr->get(index)) -void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) { +void Variant::set(const Variant &p_index, const Variant &p_value, bool *r_valid) { - static bool _dummy=false; + static bool _dummy = false; bool &valid = r_valid ? *r_valid : _dummy; - valid=false; + valid = false; - switch(type) { - case NIL: { return; } break; - case BOOL: { return; } break; - case INT: { return; } break; - case REAL: { return; } break; + switch (type) { + case NIL: { + return; + } break; + case BOOL: { + return; + } break; + case INT: { + return; + } break; + case REAL: { + return; + } break; case STRING: { - - if (p_index.type!=Variant::INT && p_index.type!=Variant::REAL) + if (p_index.type != Variant::INT && p_index.type != Variant::REAL) return; - int idx=p_index; - String *str=reinterpret_cast<String*>(_data._mem); + int idx = p_index; + String *str = reinterpret_cast<String *>(_data._mem); int len = str->length(); - if (idx<0) + if (idx < 0) idx += len; - if (idx<0 || idx>=len) + if (idx < 0 || idx >= len) return; String chr; - if (p_value.type==Variant::INT || p_value.type==Variant::REAL) { + if (p_value.type == Variant::INT || p_value.type == Variant::REAL) { chr = String::chr(p_value); - } else if (p_value.type==Variant::STRING) { + } else if (p_value.type == Variant::STRING) { chr = p_value; } else { return; } - *str = str->substr(0,idx)+chr+str->substr(idx+1, len); - valid=true; + *str = str->substr(0, idx) + chr + str->substr(idx + 1, len); + valid = true; return; - } break; case VECTOR2: { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { // scalar index - int idx=p_index; + int idx = p_index; - if (idx<0) + if (idx < 0) idx += 2; - if (idx>=0 && idx<2) { + if (idx >= 0 && idx < 2) { - Vector2 *v=reinterpret_cast<Vector2*>(_data._mem); - valid=true; - (*v)[idx]=p_value; + Vector2 *v = reinterpret_cast<Vector2 *>(_data._mem); + valid = true; + (*v)[idx] = p_value; return; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Vector2 *v=reinterpret_cast<Vector2*>(_data._mem); - if (*str=="x" || *str=="width") { - valid=true; - v->x=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Vector2 *v = reinterpret_cast<Vector2 *>(_data._mem); + if (*str == "x" || *str == "width") { + valid = true; + v->x = p_value; return; - } else if (*str=="y" || *str=="height") { - valid=true; - v->y=p_value; + } else if (*str == "y" || *str == "height") { + valid = true; + v->y = p_value; return; } } - } break; // 5 + } break; // 5 case RECT2: { - if (p_value.type!=Variant::VECTOR2) + if (p_value.type != Variant::VECTOR2) return; - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Rect2 *v=reinterpret_cast<Rect2*>(_data._mem); - if (*str=="pos") { - valid=true; - v->pos=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Rect2 *v = reinterpret_cast<Rect2 *>(_data._mem); + if (*str == "pos") { + valid = true; + v->pos = p_value; return; - } else if (*str=="size") { - valid=true; - v->size=p_value; + } else if (*str == "size") { + valid = true; + v->size = p_value; return; - } else if (*str=="end") { - valid=true; - v->size=Vector2(p_value) - v->pos; + } else if (*str == "end") { + valid = true; + v->size = Vector2(p_value) - v->pos; return; } } } break; case TRANSFORM2D: { - if (p_value.type!=Variant::VECTOR2) + if (p_value.type != Variant::VECTOR2) return; - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - if (index<0) + if (index < 0) index += 3; - if (index>=0 && index<3) { - Transform2D *v=_data._transform2d; + if (index >= 0 && index < 3) { + Transform2D *v = _data._transform2d; - valid=true; - v->elements[index]=p_value; + valid = true; + v->elements[index] = p_value; return; } - } else if (p_index.get_type()==Variant::STRING && p_value.get_type()==Variant::VECTOR2) { + } else if (p_index.get_type() == Variant::STRING && p_value.get_type() == Variant::VECTOR2) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Transform2D *v=_data._transform2d; - if (*str=="x") { - valid=true; - v->elements[0]=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Transform2D *v = _data._transform2d; + if (*str == "x") { + valid = true; + v->elements[0] = p_value; return; - } else if (*str=="y" ) { - valid=true; - v->elements[1]=p_value; + } else if (*str == "y") { + valid = true; + v->elements[1] = p_value; return; - } else if (*str=="o" ) { - valid=true; - v->elements[2]=p_value; + } else if (*str == "o") { + valid = true; + v->elements[2] = p_value; return; } } @@ -1200,37 +1198,37 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case VECTOR3: { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { //scalar index - int idx=p_index; - if (idx<0) + int idx = p_index; + if (idx < 0) idx += 3; - if (idx>=0 && idx<3) { + if (idx >= 0 && idx < 3) { - Vector3 *v=reinterpret_cast<Vector3*>(_data._mem); - valid=true; - (*v)[idx]=p_value; + Vector3 *v = reinterpret_cast<Vector3 *>(_data._mem); + valid = true; + (*v)[idx] = p_value; return; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Vector3 *v=reinterpret_cast<Vector3*>(_data._mem); - if (*str=="x") { - valid=true; - v->x=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Vector3 *v = reinterpret_cast<Vector3 *>(_data._mem); + if (*str == "x") { + valid = true; + v->x = p_value; return; - } else if (*str=="y" ) { - valid=true; - v->y=p_value; + } else if (*str == "y") { + valid = true; + v->y = p_value; return; - } else if (*str=="z" ) { - valid=true; - v->z=p_value; + } else if (*str == "z") { + valid = true; + v->z = p_value; return; } } @@ -1238,41 +1236,41 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case PLANE: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Plane *v=reinterpret_cast<Plane*>(_data._mem); - if (*str=="x") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Plane *v = reinterpret_cast<Plane *>(_data._mem); + if (*str == "x") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - v->normal.x=p_value; + valid = true; + v->normal.x = p_value; return; - } else if (*str=="y" ) { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (*str == "y") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - v->normal.y=p_value; + valid = true; + v->normal.y = p_value; return; - } else if (*str=="z" ) { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (*str == "z") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - v->normal.z=p_value; + valid = true; + v->normal.z = p_value; return; - } else if (*str=="normal" ) { - if (p_value.type!=Variant::VECTOR3) + } else if (*str == "normal") { + if (p_value.type != Variant::VECTOR3) return; - valid=true; - v->normal=p_value; + valid = true; + v->normal = p_value; return; - } else if (*str=="d" ) { - valid=true; - v->d=p_value; + } else if (*str == "d") { + valid = true; + v->d = p_value; return; } } @@ -1280,28 +1278,28 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case QUAT: { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Quat *v=reinterpret_cast<Quat*>(_data._mem); - if (*str=="x") { - valid=true; - v->x=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Quat *v = reinterpret_cast<Quat *>(_data._mem); + if (*str == "x") { + valid = true; + v->x = p_value; return; - } else if (*str=="y" ) { - valid=true; - v->y=p_value; + } else if (*str == "y") { + valid = true; + v->y = p_value; return; - } else if (*str=="z" ) { - valid=true; - v->z=p_value; + } else if (*str == "z") { + valid = true; + v->z = p_value; return; - } else if (*str=="w" ) { - valid=true; - v->w=p_value; + } else if (*str == "w") { + valid = true; + v->w = p_value; return; } } @@ -1309,64 +1307,63 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case RECT3: { - if (p_value.type!=Variant::VECTOR3) + if (p_value.type != Variant::VECTOR3) return; - - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Rect3 *v=_data._rect3; - if (*str=="pos") { - valid=true; - v->pos=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Rect3 *v = _data._rect3; + if (*str == "pos") { + valid = true; + v->pos = p_value; return; - } else if (*str=="size") { - valid=true; - v->size=p_value; + } else if (*str == "size") { + valid = true; + v->size = p_value; return; - } else if (*str=="end") { - valid=true; - v->size=Vector3(p_value) - v->pos; + } else if (*str == "end") { + valid = true; + v->size = Vector3(p_value) - v->pos; return; } } } break; //sorry naming convention fail :( not like it's used often // 10 case BASIS: { - if (p_value.type!=Variant::VECTOR3) + if (p_value.type != Variant::VECTOR3) return; - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - if (index<0) + if (index < 0) index += 3; - if (index>=0 && index<3) { - Basis *v=_data._basis; + if (index >= 0 && index < 3) { + Basis *v = _data._basis; - valid=true; - v->set_axis(index,p_value); + valid = true; + v->set_axis(index, p_value); return; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Basis *v=_data._basis; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Basis *v = _data._basis; - if (*str=="x") { - valid=true; - v->set_axis(0,p_value); + if (*str == "x") { + valid = true; + v->set_axis(0, p_value); return; - } else if (*str=="y" ) { - valid=true; - v->set_axis(1,p_value); + } else if (*str == "y") { + valid = true; + v->set_axis(1, p_value); return; - } else if (*str=="z" ) { - valid=true; - v->set_axis(2,p_value); + } else if (*str == "z") { + valid = true; + v->set_axis(2, p_value); return; } } @@ -1374,42 +1371,42 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case TRANSFORM: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { - - if (p_value.type!=Variant::VECTOR3) + if (p_value.type != Variant::VECTOR3) return; int index = p_index; - if (index<0) + if (index < 0) index += 4; - if (index>=0 && index<4) { - Transform *v=_data._transform; - valid=true; - if (index==3) - v->origin=p_value; + if (index >= 0 && index < 4) { + Transform *v = _data._transform; + valid = true; + if (index == 3) + v->origin = p_value; else - v->basis.set_axis(index,p_value); + v->basis.set_axis(index, p_value); return; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { - Transform *v=_data._transform; - const String *str=reinterpret_cast<const String*>(p_index._data._mem); + Transform *v = _data._transform; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); - if (*str=="basis") { + if (*str == "basis") { - if (p_value.type!=Variant::BASIS) + if (p_value.type != Variant::BASIS) return; - valid=true; - v->basis=p_value; + valid = true; + v->basis = p_value; return; - } if (*str=="origin") { - if (p_value.type!=Variant::VECTOR3) + } + if (*str == "origin") { + if (p_value.type != Variant::VECTOR3) return; - valid=true; - v->origin=p_value; + valid = true; + v->origin = p_value; return; } } @@ -1417,80 +1414,81 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case COLOR: { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - Color *v=reinterpret_cast<Color*>(_data._mem); - if (*str=="r") { - valid=true; - v->r=p_value; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + Color *v = reinterpret_cast<Color *>(_data._mem); + if (*str == "r") { + valid = true; + v->r = p_value; return; - } else if (*str=="g" ) { - valid=true; - v->g=p_value; + } else if (*str == "g") { + valid = true; + v->g = p_value; return; - } else if (*str=="b" ) { - valid=true; - v->b=p_value; + } else if (*str == "b") { + valid = true; + v->b = p_value; return; - } else if (*str=="a" ) { - valid=true; - v->a=p_value; + } else if (*str == "a") { + valid = true; + v->a = p_value; return; - } else if (*str=="h") { - valid=true; - v->set_hsv(p_value,v->get_s(),v->get_v()); + } else if (*str == "h") { + valid = true; + v->set_hsv(p_value, v->get_s(), v->get_v()); return; - } else if (*str=="s" ) { - valid=true; - v->set_hsv(v->get_h(),p_value,v->get_v()); + } else if (*str == "s") { + valid = true; + v->set_hsv(v->get_h(), p_value, v->get_v()); return; - } else if (*str=="v" ) { - valid=true; - v->set_hsv(v->get_h(),v->get_s(),p_value); + } else if (*str == "v") { + valid = true; + v->set_hsv(v->get_h(), v->get_s(), p_value); return; - } else if (*str=="r8" ) { - valid=true; - v->r=float(p_value)/255.0; + } else if (*str == "r8") { + valid = true; + v->r = float(p_value) / 255.0; return; - } else if (*str=="g8" ) { - valid=true; - v->g=float(p_value)/255.0; + } else if (*str == "g8") { + valid = true; + v->g = float(p_value) / 255.0; return; - } else if (*str=="b8" ) { - valid=true; - v->b=float(p_value)/255.0; + } else if (*str == "b8") { + valid = true; + v->b = float(p_value) / 255.0; return; - } else if (*str=="a8" ) {\ - valid=true; - v->a=float(p_value)/255.0; + } else if (*str == "a8") { + valid = true; + v->a = float(p_value) / 255.0; return; } - } else if (p_index.get_type()==Variant::INT) { + } else if (p_index.get_type() == Variant::INT) { int idx = p_index; - if (idx<0) + if (idx < 0) idx += 4; - if (idx>=0 || idx<4) { - Color *v=reinterpret_cast<Color*>(_data._mem); - (*v)[idx]=p_value; - valid=true; + if (idx >= 0 || idx < 4) { + Color *v = reinterpret_cast<Color *>(_data._mem); + (*v)[idx] = p_value; + valid = true; } } - - } break; - case IMAGE: { } break; - case NODE_PATH: { } break; // 15 - case _RID: { } break; + case IMAGE: { + } break; + case NODE_PATH: { + } break; // 15 + case _RID: { + } break; case OBJECT: { - Object *obj=_get_obj().obj; - //only if debugging! + Object *obj = _get_obj().obj; + //only if debugging! if (obj) { #ifdef DEBUG_ENABLED @@ -1498,384 +1496,398 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) if (!ObjectDB::instance_validate(obj)) { WARN_PRINT("Attempted use of stray pointer object."); - valid=false; + valid = false; return; } } #endif - if (p_index.get_type()!=Variant::STRING) { - obj->setvar(p_index,p_value,r_valid); + if (p_index.get_type() != Variant::STRING) { + obj->setvar(p_index, p_value, r_valid); return; } - return obj->set(p_index,p_value,r_valid); + return obj->set(p_index, p_value, r_valid); } } break; case INPUT_EVENT: { InputEvent &ie = *_data._input_event; - if (p_index.get_type()!=Variant::STRING) + if (p_index.get_type() != Variant::STRING) return; - const String &str=*reinterpret_cast<const String*>(p_index._data._mem); + const String &str = *reinterpret_cast<const String *>(p_index._data._mem); - if (str=="type") { + if (str == "type") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - int type=p_value; - if (type<0 || type>=InputEvent::TYPE_MAX) + int type = p_value; + if (type < 0 || type >= InputEvent::TYPE_MAX) return; //fail - valid=true; - ie.type=InputEvent::Type(type); + valid = true; + ie.type = InputEvent::Type(type); return; - } else if (str=="device") { + } else if (str == "device") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.device=p_value; + valid = true; + ie.device = p_value; return; - } else if (str=="ID") { + } else if (str == "ID") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.ID=p_value; + valid = true; + ie.ID = p_value; return; } - if (ie.type==InputEvent::KEY || ie.type==InputEvent::MOUSE_BUTTON || ie.type==InputEvent::MOUSE_MOTION) { + if (ie.type == InputEvent::KEY || ie.type == InputEvent::MOUSE_BUTTON || ie.type == InputEvent::MOUSE_MOTION) { - if (str=="shift") { + if (str == "shift") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.key.mod.shift=p_value; + valid = true; + ie.key.mod.shift = p_value; return; - } if (str=="alt") { + } + if (str == "alt") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.key.mod.alt=p_value; + valid = true; + ie.key.mod.alt = p_value; return; - } if (str=="control") { + } + if (str == "control") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.key.mod.control=p_value; + valid = true; + ie.key.mod.control = p_value; return; - } if (str=="meta") { + } + if (str == "meta") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.key.mod.meta=p_value; + valid = true; + ie.key.mod.meta = p_value; return; } } - if (ie.type==InputEvent::KEY) { + if (ie.type == InputEvent::KEY) { - if (str=="pressed") { - - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) - return; + if (str == "pressed") { - valid=true; - ie.key.pressed=p_value; + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - } else if (str=="scancode") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) - return; + valid = true; + ie.key.pressed = p_value; + return; + } else if (str == "scancode") { - valid=true; - ie.key.scancode=p_value; - return; - } else if (str=="unicode") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) - return; - valid=true; - ie.key.unicode=p_value; + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - } else if (str=="echo") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) - return; - valid=true; - ie.key.echo=p_value; + valid = true; + ie.key.scancode = p_value; + return; + } else if (str == "unicode") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - } + valid = true; + ie.key.unicode = p_value; + return; + } else if (str == "echo") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) + return; + + valid = true; + ie.key.echo = p_value; + return; + } } - if (ie.type==InputEvent::MOUSE_MOTION || ie.type==InputEvent::MOUSE_BUTTON) { + if (ie.type == InputEvent::MOUSE_MOTION || ie.type == InputEvent::MOUSE_BUTTON) { - if (str=="button_mask") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (str == "button_mask") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_button.button_mask=p_value; + valid = true; + ie.mouse_button.button_mask = p_value; return; - } else if (str=="x") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (str == "x") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_button.x=p_value; + valid = true; + ie.mouse_button.x = p_value; return; - } else if (str=="y") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (str == "y") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_button.y=p_value; + valid = true; + ie.mouse_button.y = p_value; return; - } else if (str=="pos") { - if (p_value.type!=Variant::VECTOR2) + } else if (str == "pos") { + if (p_value.type != Variant::VECTOR2) return; - valid=true; - Point2 value=p_value; - ie.mouse_button.x=value.x; - ie.mouse_button.y=value.y; + valid = true; + Point2 value = p_value; + ie.mouse_button.x = value.x; + ie.mouse_button.y = value.y; return; - } else if (str=="global_x") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (str == "global_x") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_button.global_x=p_value; + valid = true; + ie.mouse_button.global_x = p_value; return; - } else if (str=="global_y") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (str == "global_y") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_button.global_y=p_value; + valid = true; + ie.mouse_button.global_y = p_value; return; - } else if (str=="global_pos") { - if (p_value.type!=Variant::VECTOR2) + } else if (str == "global_pos") { + if (p_value.type != Variant::VECTOR2) return; - valid=true; - Point2 value=p_value; - ie.mouse_button.global_x=value.x; - ie.mouse_button.global_y=value.y; + valid = true; + Point2 value = p_value; + ie.mouse_button.global_x = value.x; + ie.mouse_button.global_y = value.y; return; } /*else if (str=="pointer_index") { valid=true; return ie.mouse_button.pointer_index; }*/ + if (ie.type == InputEvent::MOUSE_MOTION) { - if (ie.type==InputEvent::MOUSE_MOTION) { - - if (str=="relative_x") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (str == "relative_x") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_motion.relative_x=p_value; + valid = true; + ie.mouse_motion.relative_x = p_value; return; - } else if (str=="relative_y") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (str == "relative_y") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_motion.relative_y=p_value; + valid = true; + ie.mouse_motion.relative_y = p_value; return; - } else if (str=="relative_pos") { - if (p_value.type!=Variant::VECTOR2) + } else if (str == "relative_pos") { + if (p_value.type != Variant::VECTOR2) return; - valid=true; - Point2 value=p_value; - ie.mouse_motion.relative_x=value.x; - ie.mouse_motion.relative_y=value.y; + valid = true; + Point2 value = p_value; + ie.mouse_motion.relative_x = value.x; + ie.mouse_motion.relative_y = value.y; return; } - if (str=="speed_x") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (str == "speed_x") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_motion.speed_x=p_value; + valid = true; + ie.mouse_motion.speed_x = p_value; return; - } else if (str=="speed_y") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + } else if (str == "speed_y") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_motion.speed_y=p_value; + valid = true; + ie.mouse_motion.speed_y = p_value; return; - } else if (str=="speed") { - if (p_value.type!=Variant::VECTOR2) + } else if (str == "speed") { + if (p_value.type != Variant::VECTOR2) return; - valid=true; - Point2 value=p_value; - ie.mouse_motion.speed_x=value.x; - ie.mouse_motion.speed_y=value.y; + valid = true; + Point2 value = p_value; + ie.mouse_motion.speed_x = value.x; + ie.mouse_motion.speed_y = value.y; return; } - } else if (ie.type==InputEvent::MOUSE_BUTTON) { + } else if (ie.type == InputEvent::MOUSE_BUTTON) { - if (str=="button_index") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL) + if (str == "button_index") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL) return; - valid=true; - ie.mouse_button.button_index=p_value; + valid = true; + ie.mouse_button.button_index = p_value; return; - } else if (str=="pressed") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + } else if (str == "pressed") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.mouse_button.pressed=p_value; + valid = true; + ie.mouse_button.pressed = p_value; return; - } else if (str=="doubleclick") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + } else if (str == "doubleclick") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.mouse_button.doubleclick=p_value; + valid = true; + ie.mouse_button.doubleclick = p_value; return; } } - } - if (ie.type==InputEvent::JOYPAD_BUTTON) { + if (ie.type == InputEvent::JOYPAD_BUTTON) { - if (str=="button_index") { - if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT) + if (str == "button_index") { + if (p_value.type != Variant::REAL && p_value.type != Variant::INT) return; - valid=true; - ie.joy_button.button_index=p_value; + valid = true; + ie.joy_button.button_index = p_value; return; - } if (str=="pressed") { - if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL) + } + if (str == "pressed") { + if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL) return; - valid=true; - ie.joy_button.pressed=p_value; + valid = true; + ie.joy_button.pressed = p_value; return; - } if (str=="pressure") { - if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT) + } + if (str == "pressure") { + if (p_value.type != Variant::REAL && p_value.type != Variant::INT) return; - valid=true; - ie.joy_button.pressure=p_value; + valid = true; + ie.joy_button.pressure = p_value; return; } - } - if (ie.type==InputEvent::JOYPAD_MOTION) { + if (ie.type == InputEvent::JOYPAD_MOTION) { - if (str=="axis") { - if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT) + if (str == "axis") { + if (p_value.type != Variant::REAL && p_value.type != Variant::INT) return; - valid=true; - ie.joy_motion.axis=p_value; + valid = true; + ie.joy_motion.axis = p_value; return; - } if (str=="value") { - if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT) + } + if (str == "value") { + if (p_value.type != Variant::REAL && p_value.type != Variant::INT) return; - valid=true; - ie.joy_motion.axis_value=p_value; + valid = true; + ie.joy_motion.axis_value = p_value; return; } } - if (ie.type==InputEvent::SCREEN_TOUCH) { + if (ie.type == InputEvent::SCREEN_TOUCH) { - if (str=="index") { - valid=true; - ie.screen_touch.index=p_value; + if (str == "index") { + valid = true; + ie.screen_touch.index = p_value; return; - } if (str=="x") { - valid=true; - ie.screen_touch.x=p_value; + } + if (str == "x") { + valid = true; + ie.screen_touch.x = p_value; return; - } if (str=="y") { - valid=true; - ie.screen_touch.y=p_value; + } + if (str == "y") { + valid = true; + ie.screen_touch.y = p_value; return; - } if (str=="pos") { - valid=true; + } + if (str == "pos") { + valid = true; Vector2 v = p_value; - ie.screen_touch.x=v.x; - ie.screen_touch.y=v.y; + ie.screen_touch.x = v.x; + ie.screen_touch.y = v.y; return; - } if (str=="pressed") { - valid=true; - ie.screen_touch.pressed=p_value; + } + if (str == "pressed") { + valid = true; + ie.screen_touch.pressed = p_value; return; } - } - if (ie.type==InputEvent::SCREEN_DRAG) { + if (ie.type == InputEvent::SCREEN_DRAG) { - if (str=="index") { - valid=true; - ie.screen_drag.index=p_value; + if (str == "index") { + valid = true; + ie.screen_drag.index = p_value; return; - } if (str=="x") { - valid=true; - ie.screen_drag.x=p_value; + } + if (str == "x") { + valid = true; + ie.screen_drag.x = p_value; return; - } if (str=="y") { - valid=true; - ie.screen_drag.y=p_value; + } + if (str == "y") { + valid = true; + ie.screen_drag.y = p_value; return; - } if (str=="pos") { - valid=true; + } + if (str == "pos") { + valid = true; Vector2 v = p_value; - ie.screen_drag.x=v.x; - ie.screen_drag.y=v.y; + ie.screen_drag.x = v.x; + ie.screen_drag.y = v.y; return; - } if (str=="relative_x") { - valid=true; - ie.screen_drag.relative_x=p_value; + } + if (str == "relative_x") { + valid = true; + ie.screen_drag.relative_x = p_value; return; - } if (str=="relative_y") { - valid=true; - ie.screen_drag.relative_y=p_value; + } + if (str == "relative_y") { + valid = true; + ie.screen_drag.relative_y = p_value; return; - } if (str=="relative_pos") { - valid=true; - Vector2 v=p_value; - ie.screen_drag.relative_x=v.x; - ie.screen_drag.relative_y=v.y; + } + if (str == "relative_pos") { + valid = true; + Vector2 v = p_value; + ie.screen_drag.relative_x = v.x; + ie.screen_drag.relative_y = v.y; return; - } if (str=="speed_x") { - valid=true; - ie.screen_drag.speed_x=p_value; + } + if (str == "speed_x") { + valid = true; + ie.screen_drag.speed_x = p_value; return; - } if (str=="speed_y") { - valid=true; - ie.screen_drag.speed_y=p_value; + } + if (str == "speed_y") { + valid = true; + ie.screen_drag.speed_y = p_value; return; - } if (str=="speed") { - valid=true; - Vector2 v=p_value; - ie.screen_drag.speed_x=v.x; - ie.screen_drag.speed_y=v.y; + } + if (str == "speed") { + valid = true; + Vector2 v = p_value; + ie.screen_drag.speed_x = v.x; + ie.screen_drag.speed_y = v.y; return; } } if (ie.type == InputEvent::ACTION) { - if (str =="action") { - valid=true; - ie.action.action=p_value; + if (str == "action") { + valid = true; + ie.action.action = p_value; return; - } - else if (str == "pressed") { - valid=true; - ie.action.pressed=p_value; + } else if (str == "pressed") { + valid = true; + ie.action.pressed = p_value; return; } } @@ -1883,127 +1895,134 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) } break; case DICTIONARY: { - Dictionary *dic=reinterpret_cast<Dictionary*>(_data._mem); - dic->operator [](p_index)=p_value; - valid=true; //always valid, i guess? should this really be ok? + Dictionary *dic = reinterpret_cast<Dictionary *>(_data._mem); + dic->operator[](p_index) = p_value; + valid = true; //always valid, i guess? should this really be ok? return; - } break; // 20 - DEFAULT_OP_ARRAY_CMD(ARRAY, Array, ;, (*arr)[index]=p_value;return) - DEFAULT_OP_DVECTOR_SET(POOL_BYTE_ARRAY, uint8_t, p_value.type != Variant::REAL && p_value.type != Variant::INT) - DEFAULT_OP_DVECTOR_SET(POOL_INT_ARRAY, int, p_value.type != Variant::REAL && p_value.type != Variant::INT) - DEFAULT_OP_DVECTOR_SET(POOL_REAL_ARRAY, real_t, p_value.type != Variant::REAL && p_value.type != Variant::INT) - DEFAULT_OP_DVECTOR_SET(POOL_STRING_ARRAY, String, p_value.type != Variant::STRING) // 25 - DEFAULT_OP_DVECTOR_SET(POOL_VECTOR2_ARRAY, Vector2, p_value.type != Variant::VECTOR2) - DEFAULT_OP_DVECTOR_SET(POOL_VECTOR3_ARRAY, Vector3, p_value.type != Variant::VECTOR3) - DEFAULT_OP_DVECTOR_SET(POOL_COLOR_ARRAY, Color, p_value.type != Variant::COLOR) + } break; // 20 + DEFAULT_OP_ARRAY_CMD(ARRAY, Array, ;, (*arr)[index] = p_value; return ) + DEFAULT_OP_DVECTOR_SET(POOL_BYTE_ARRAY, uint8_t, p_value.type != Variant::REAL && p_value.type != Variant::INT) + DEFAULT_OP_DVECTOR_SET(POOL_INT_ARRAY, int, p_value.type != Variant::REAL && p_value.type != Variant::INT) + DEFAULT_OP_DVECTOR_SET(POOL_REAL_ARRAY, real_t, p_value.type != Variant::REAL && p_value.type != Variant::INT) + DEFAULT_OP_DVECTOR_SET(POOL_STRING_ARRAY, String, p_value.type != Variant::STRING) // 25 + DEFAULT_OP_DVECTOR_SET(POOL_VECTOR2_ARRAY, Vector2, p_value.type != Variant::VECTOR2) + DEFAULT_OP_DVECTOR_SET(POOL_VECTOR3_ARRAY, Vector3, p_value.type != Variant::VECTOR3) + DEFAULT_OP_DVECTOR_SET(POOL_COLOR_ARRAY, Color, p_value.type != Variant::COLOR) default: return; } - } -Variant Variant::get(const Variant& p_index, bool *r_valid) const { +Variant Variant::get(const Variant &p_index, bool *r_valid) const { - static bool _dummy=false; + static bool _dummy = false; bool &valid = r_valid ? *r_valid : _dummy; - valid=false; + valid = false; - switch(type) { - case NIL: { return Variant(); } break; - case BOOL: { return Variant(); } break; - case INT: { return Variant(); } break; - case REAL: { return Variant(); } break; + switch (type) { + case NIL: { + return Variant(); + } break; + case BOOL: { + return Variant(); + } break; + case INT: { + return Variant(); + } break; + case REAL: { + return Variant(); + } break; case STRING: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { //string index - int idx=p_index; - const String *str=reinterpret_cast<const String*>(_data._mem); - if (idx<0) + int idx = p_index; + const String *str = reinterpret_cast<const String *>(_data._mem); + if (idx < 0) idx += str->length(); - if (idx >=0 && idx<str->length()) { + if (idx >= 0 && idx < str->length()) { - valid=true; - return str->substr(idx,1); + valid = true; + return str->substr(idx, 1); } } } break; case VECTOR2: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { // scalar index - int idx=p_index; - if (idx<0) + int idx = p_index; + if (idx < 0) idx += 2; - if (idx>=0 && idx<2) { + if (idx >= 0 && idx < 2) { - const Vector2 *v=reinterpret_cast<const Vector2*>(_data._mem); - valid=true; + const Vector2 *v = reinterpret_cast<const Vector2 *>(_data._mem); + valid = true; return (*v)[idx]; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Vector2 *v=reinterpret_cast<const Vector2*>(_data._mem); - if (*str=="x" || *str=="width") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Vector2 *v = reinterpret_cast<const Vector2 *>(_data._mem); + if (*str == "x" || *str == "width") { + valid = true; return v->x; - } else if (*str=="y" || *str=="height") { - valid=true; + } else if (*str == "y" || *str == "height") { + valid = true; return v->y; } } - } break; // 5 + } break; // 5 case RECT2: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Rect2 *v=reinterpret_cast<const Rect2*>(_data._mem); - if (*str=="pos") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Rect2 *v = reinterpret_cast<const Rect2 *>(_data._mem); + if (*str == "pos") { + valid = true; return v->pos; - } else if (*str=="size") { - valid=true; + } else if (*str == "size") { + valid = true; return v->size; - } else if (*str=="end") { - valid=true; - return v->size+v->pos; + } else if (*str == "end") { + valid = true; + return v->size + v->pos; } } } break; case VECTOR3: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { //scalar index - int idx=p_index; - if (idx<0) + int idx = p_index; + if (idx < 0) idx += 3; - if (idx>=0 && idx<3) { + if (idx >= 0 && idx < 3) { - const Vector3 *v=reinterpret_cast<const Vector3*>(_data._mem); - valid=true; + const Vector3 *v = reinterpret_cast<const Vector3 *>(_data._mem); + valid = true; return (*v)[idx]; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Vector3 *v=reinterpret_cast<const Vector3*>(_data._mem); - if (*str=="x") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Vector3 *v = reinterpret_cast<const Vector3 *>(_data._mem); + if (*str == "x") { + valid = true; return v->x; - } else if (*str=="y" ) { - valid=true; + } else if (*str == "y") { + valid = true; return v->y; - } else if (*str=="z" ) { - valid=true; + } else if (*str == "z") { + valid = true; return v->z; } } @@ -2011,31 +2030,31 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case TRANSFORM2D: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - if (index<0) + if (index < 0) index += 3; - if (index>=0 && index<3) { - const Transform2D *v=_data._transform2d; + if (index >= 0 && index < 3) { + const Transform2D *v = _data._transform2d; - valid=true; + valid = true; return v->elements[index]; } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Transform2D *v=_data._transform2d; - if (*str=="x") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Transform2D *v = _data._transform2d; + if (*str == "x") { + valid = true; return v->elements[0]; - } else if (*str=="y" ) { - valid=true; + } else if (*str == "y") { + valid = true; return v->elements[1]; - } else if (*str=="o" ) { - valid=true; + } else if (*str == "o") { + valid = true; return v->elements[2]; } } @@ -2043,24 +2062,24 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case PLANE: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Plane *v=reinterpret_cast<const Plane*>(_data._mem); - if (*str=="x") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Plane *v = reinterpret_cast<const Plane *>(_data._mem); + if (*str == "x") { + valid = true; return v->normal.x; - } else if (*str=="y" ) { - valid=true; + } else if (*str == "y") { + valid = true; return v->normal.y; - } else if (*str=="z" ) { - valid=true; + } else if (*str == "z") { + valid = true; return v->normal.z; - } else if (*str=="normal" ) { - valid=true; + } else if (*str == "normal") { + valid = true; return v->normal; - } else if (*str=="d" ) { - valid=true; + } else if (*str == "d") { + valid = true; return v->d; } } @@ -2068,21 +2087,21 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case QUAT: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Quat *v=reinterpret_cast<const Quat*>(_data._mem); - if (*str=="x") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Quat *v = reinterpret_cast<const Quat *>(_data._mem); + if (*str == "x") { + valid = true; return v->x; - } else if (*str=="y" ) { - valid=true; + } else if (*str == "y") { + valid = true; return v->y; - } else if (*str=="z" ) { - valid=true; + } else if (*str == "z") { + valid = true; return v->z; - } else if (*str=="w" ) { - valid=true; + } else if (*str == "w") { + valid = true; return v->w; } } @@ -2090,49 +2109,49 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case RECT3: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //scalar name - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Rect3 *v=_data._rect3; - if (*str=="pos") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Rect3 *v = _data._rect3; + if (*str == "pos") { + valid = true; return v->pos; - } else if (*str=="size") { - valid=true; + } else if (*str == "size") { + valid = true; return v->size; - } else if (*str=="end") { - valid=true; - return v->size+v->pos; + } else if (*str == "end") { + valid = true; + return v->size + v->pos; } } } break; //sorry naming convention fail :( not like it's used often // 10 case BASIS: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - if (index<0) + if (index < 0) index += 3; - if (index>=0 && index<3) { - const Basis *v=_data._basis; + if (index >= 0 && index < 3) { + const Basis *v = _data._basis; - valid=true; + valid = true; return v->get_axis(index); } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Basis *v=_data._basis; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Basis *v = _data._basis; - if (*str=="x") { - valid=true; + if (*str == "x") { + valid = true; return v->get_axis(0); - } else if (*str=="y" ) { - valid=true; + } else if (*str == "y") { + valid = true; return v->get_axis(1); - } else if (*str=="z" ) { - valid=true; + } else if (*str == "z") { + valid = true; return v->get_axis(2); } } @@ -2140,26 +2159,27 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case TRANSFORM: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - if (index<0) + if (index < 0) index += 4; - if (index>=0 && index<4) { - const Transform *v=_data._transform; - valid=true; - return index==3?v->origin:v->basis.get_axis(index); + if (index >= 0 && index < 4) { + const Transform *v = _data._transform; + valid = true; + return index == 3 ? v->origin : v->basis.get_axis(index); } - } else if (p_index.get_type()==Variant::STRING) { + } else if (p_index.get_type() == Variant::STRING) { - const Transform *v=_data._transform; - const String *str=reinterpret_cast<const String*>(p_index._data._mem); + const Transform *v = _data._transform; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); - if (*str=="basis") { - valid=true; + if (*str == "basis") { + valid = true; return v->basis; - } if (*str=="origin") { - valid=true; + } + if (*str == "origin") { + valid = true; return v->origin; } } @@ -2167,297 +2187,309 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case COLOR: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { - const String *str=reinterpret_cast<const String*>(p_index._data._mem); - const Color *v=reinterpret_cast<const Color*>(_data._mem); - if (*str=="r") { - valid=true; + const String *str = reinterpret_cast<const String *>(p_index._data._mem); + const Color *v = reinterpret_cast<const Color *>(_data._mem); + if (*str == "r") { + valid = true; return v->r; - } else if (*str=="g" ) { - valid=true; + } else if (*str == "g") { + valid = true; return v->g; - } else if (*str=="b" ) { - valid=true; + } else if (*str == "b") { + valid = true; return v->b; - } else if (*str=="a" ) { - valid=true; + } else if (*str == "a") { + valid = true; return v->a; - } else if (*str=="h") { - valid=true; + } else if (*str == "h") { + valid = true; return v->get_h(); - } else if (*str=="s" ) { - valid=true; + } else if (*str == "s") { + valid = true; return v->get_s(); - } else if (*str=="v" ) { - valid=true; + } else if (*str == "v") { + valid = true; return v->get_v(); - } else if (*str=="r8") { - valid=true; - return (int)Math::round(v->r*255.0); - } else if (*str=="g8" ) { - valid=true; - return (int)Math::round(v->g*255.0); - } else if (*str=="b8" ) { - valid=true; - return (int)Math::round(v->b*255.0); - } else if (*str=="a8" ) { - valid=true; - return (int)Math::round(v->a*255.0); - } - } else if (p_index.get_type()==Variant::INT) { + } else if (*str == "r8") { + valid = true; + return (int)Math::round(v->r * 255.0); + } else if (*str == "g8") { + valid = true; + return (int)Math::round(v->g * 255.0); + } else if (*str == "b8") { + valid = true; + return (int)Math::round(v->b * 255.0); + } else if (*str == "a8") { + valid = true; + return (int)Math::round(v->a * 255.0); + } + } else if (p_index.get_type() == Variant::INT) { int idx = p_index; - if (idx<0) + if (idx < 0) idx += 4; - if (idx>=0 || idx<4) { - const Color *v=reinterpret_cast<const Color*>(_data._mem); - valid=true; + if (idx >= 0 || idx < 4) { + const Color *v = reinterpret_cast<const Color *>(_data._mem); + valid = true; return (*v)[idx]; } } - } break; - case IMAGE: { } break; - case NODE_PATH: { } break; // 15 - case _RID: { } break; + case IMAGE: { + } break; + case NODE_PATH: { + } break; // 15 + case _RID: { + } break; case OBJECT: { Object *obj = _get_obj().obj; if (obj) { - #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { //only if debugging! if (!ObjectDB::instance_validate(obj)) { - valid=false; + valid = false; return "Attempted get on stray pointer."; } } #endif - if (p_index.get_type()!=Variant::STRING) { - return obj->getvar(p_index,r_valid); + if (p_index.get_type() != Variant::STRING) { + return obj->getvar(p_index, r_valid); } - return obj->get(p_index,r_valid); + return obj->get(p_index, r_valid); } - } break; case INPUT_EVENT: { InputEvent ie = operator InputEvent(); - if (p_index.get_type()!=Variant::STRING) + if (p_index.get_type() != Variant::STRING) break; + const String &str = *reinterpret_cast<const String *>(p_index._data._mem); - const String &str=*reinterpret_cast<const String*>(p_index._data._mem); - - if (str=="type") { - valid=true; + if (str == "type") { + valid = true; return ie.type; - } else if (str=="device") { - valid=true; + } else if (str == "device") { + valid = true; return ie.device; - } else if (str=="ID") { - valid=true; + } else if (str == "ID") { + valid = true; return ie.ID; } - if (ie.type==InputEvent::KEY || ie.type==InputEvent::MOUSE_BUTTON || ie.type==InputEvent::MOUSE_MOTION) { + if (ie.type == InputEvent::KEY || ie.type == InputEvent::MOUSE_BUTTON || ie.type == InputEvent::MOUSE_MOTION) { - if (str=="shift") { - valid=true; + if (str == "shift") { + valid = true; return ie.key.mod.shift; - } if (str=="alt") { - valid=true; + } + if (str == "alt") { + valid = true; return ie.key.mod.alt; - } if (str=="control") { - valid=true; + } + if (str == "control") { + valid = true; return ie.key.mod.control; - } if (str=="meta") { - valid=true; + } + if (str == "meta") { + valid = true; return ie.key.mod.meta; } } - if (ie.type==InputEvent::KEY) { + if (ie.type == InputEvent::KEY) { - if (str=="pressed") { - valid=true; - return ie.key.pressed; - } else if (str=="scancode") { - valid=true; - return ie.key.scancode; - } else if (str=="unicode") { - valid=true; - return ie.key.unicode; - } else if (str=="echo") { - valid=true; - return ie.key.echo; - } + if (str == "pressed") { + valid = true; + return ie.key.pressed; + } else if (str == "scancode") { + valid = true; + return ie.key.scancode; + } else if (str == "unicode") { + valid = true; + return ie.key.unicode; + } else if (str == "echo") { + valid = true; + return ie.key.echo; + } } - if (ie.type==InputEvent::MOUSE_MOTION || ie.type==InputEvent::MOUSE_BUTTON) { + if (ie.type == InputEvent::MOUSE_MOTION || ie.type == InputEvent::MOUSE_BUTTON) { - if (str=="button_mask") { - valid=true; + if (str == "button_mask") { + valid = true; return ie.mouse_button.button_mask; - } else if (str=="x") { - valid=true; + } else if (str == "x") { + valid = true; return ie.mouse_button.x; - } else if (str=="y") { - valid=true; + } else if (str == "y") { + valid = true; return ie.mouse_button.y; - } else if (str=="pos") { - valid=true; - return Point2(ie.mouse_button.x,ie.mouse_button.y); - } else if (str=="global_x") { - valid=true; + } else if (str == "pos") { + valid = true; + return Point2(ie.mouse_button.x, ie.mouse_button.y); + } else if (str == "global_x") { + valid = true; return ie.mouse_button.global_x; - } else if (str=="global_y") { - valid=true; + } else if (str == "global_y") { + valid = true; return ie.mouse_button.global_y; - } else if (str=="global_pos") { - valid=true; - return Point2(ie.mouse_button.global_x,ie.mouse_button.global_y); + } else if (str == "global_pos") { + valid = true; + return Point2(ie.mouse_button.global_x, ie.mouse_button.global_y); } /*else if (str=="pointer_index") { valid=true; return ie.mouse_button.pointer_index; }*/ + if (ie.type == InputEvent::MOUSE_MOTION) { - if (ie.type==InputEvent::MOUSE_MOTION) { - - if (str=="relative_x") { - valid=true; + if (str == "relative_x") { + valid = true; return ie.mouse_motion.relative_x; - } else if (str=="relative_y") { - valid=true; + } else if (str == "relative_y") { + valid = true; return ie.mouse_motion.relative_y; - } else if (str=="relative_pos") { - valid=true; - return Point2(ie.mouse_motion.relative_x,ie.mouse_motion.relative_y); - } else if (str=="speed_x") { - valid=true; + } else if (str == "relative_pos") { + valid = true; + return Point2(ie.mouse_motion.relative_x, ie.mouse_motion.relative_y); + } else if (str == "speed_x") { + valid = true; return ie.mouse_motion.speed_x; - } else if (str=="speed_y") { - valid=true; + } else if (str == "speed_y") { + valid = true; return ie.mouse_motion.speed_y; - } else if (str=="speed") { - valid=true; - return Point2(ie.mouse_motion.speed_x,ie.mouse_motion.speed_y); + } else if (str == "speed") { + valid = true; + return Point2(ie.mouse_motion.speed_x, ie.mouse_motion.speed_y); } + } else if (ie.type == InputEvent::MOUSE_BUTTON) { - } else if (ie.type==InputEvent::MOUSE_BUTTON) { - - if (str=="button_index") { - valid=true; + if (str == "button_index") { + valid = true; return ie.mouse_button.button_index; - } else if (str=="pressed") { - valid=true; + } else if (str == "pressed") { + valid = true; return ie.mouse_button.pressed; - } else if (str=="doubleclick") { - valid=true; + } else if (str == "doubleclick") { + valid = true; return ie.mouse_button.doubleclick; } } - } - if (ie.type==InputEvent::JOYPAD_BUTTON) { + if (ie.type == InputEvent::JOYPAD_BUTTON) { - if (str=="button_index") { - valid=true; + if (str == "button_index") { + valid = true; return ie.joy_button.button_index; - } if (str=="pressed") { - valid=true; + } + if (str == "pressed") { + valid = true; return ie.joy_button.pressed; - } if (str=="pressure") { - valid=true; + } + if (str == "pressure") { + valid = true; return ie.joy_button.pressure; } - } - if (ie.type==InputEvent::JOYPAD_MOTION) { + if (ie.type == InputEvent::JOYPAD_MOTION) { - if (str=="axis") { - valid=true; + if (str == "axis") { + valid = true; return ie.joy_motion.axis; - } if (str=="value") { - valid=true; + } + if (str == "value") { + valid = true; return ie.joy_motion.axis_value; } } - if (ie.type==InputEvent::SCREEN_TOUCH) { + if (ie.type == InputEvent::SCREEN_TOUCH) { - if (str=="index") { - valid=true; + if (str == "index") { + valid = true; return ie.screen_touch.index; - } if (str=="x") { - valid=true; + } + if (str == "x") { + valid = true; return ie.screen_touch.x; - } if (str=="y") { - valid=true; + } + if (str == "y") { + valid = true; return ie.screen_touch.y; - } if (str=="pos") { - valid=true; - return Vector2(ie.screen_touch.x,ie.screen_touch.y); - } if (str=="pressed") { - valid=true; + } + if (str == "pos") { + valid = true; + return Vector2(ie.screen_touch.x, ie.screen_touch.y); + } + if (str == "pressed") { + valid = true; return ie.screen_touch.pressed; } - } - if (ie.type==InputEvent::SCREEN_DRAG) { + if (ie.type == InputEvent::SCREEN_DRAG) { - if (str=="index") { - valid=true; + if (str == "index") { + valid = true; return ie.screen_drag.index; - } if (str=="x") { - valid=true; + } + if (str == "x") { + valid = true; return ie.screen_drag.x; - } if (str=="y") { - valid=true; + } + if (str == "y") { + valid = true; return ie.screen_drag.y; - } if (str=="pos") { - valid=true; - return Vector2(ie.screen_drag.x,ie.screen_drag.y); - } if (str=="relative_x") { - valid=true; + } + if (str == "pos") { + valid = true; + return Vector2(ie.screen_drag.x, ie.screen_drag.y); + } + if (str == "relative_x") { + valid = true; return ie.screen_drag.relative_x; - } if (str=="relative_y") { - valid=true; + } + if (str == "relative_y") { + valid = true; return ie.screen_drag.relative_y; - } if (str=="relative_pos") { - valid=true; - return Vector2(ie.screen_drag.relative_x,ie.screen_drag.relative_y); - } if (str=="speed_x") { - valid=true; + } + if (str == "relative_pos") { + valid = true; + return Vector2(ie.screen_drag.relative_x, ie.screen_drag.relative_y); + } + if (str == "speed_x") { + valid = true; return ie.screen_drag.speed_x; - } if (str=="speed_y") { - valid=true; + } + if (str == "speed_y") { + valid = true; return ie.screen_drag.speed_y; - } if (str=="speed") { - valid=true; - return Vector2(ie.screen_drag.speed_x,ie.screen_drag.speed_y); + } + if (str == "speed") { + valid = true; + return Vector2(ie.screen_drag.speed_x, ie.screen_drag.speed_y); } } if (ie.type == InputEvent::ACTION) { - if (str =="action") { - valid=true; + if (str == "action") { + valid = true; return ie.action.action; - } - else if (str == "pressed") { - valid=true; + } else if (str == "pressed") { + valid = true; return ie.action.pressed; } } @@ -2465,44 +2497,42 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const { } break; case DICTIONARY: { - const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem); - const Variant * res = dic->getptr(p_index); + const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem); + const Variant *res = dic->getptr(p_index); if (res) { - valid=true; + valid = true; return *res; } - } break; // 20 - DEFAULT_OP_ARRAY_CMD(ARRAY, const Array, ;, return (*arr)[index]) - DEFAULT_OP_DVECTOR_GET(POOL_BYTE_ARRAY, uint8_t) - DEFAULT_OP_DVECTOR_GET(POOL_INT_ARRAY, int) - DEFAULT_OP_DVECTOR_GET(POOL_REAL_ARRAY, real_t) - DEFAULT_OP_DVECTOR_GET(POOL_STRING_ARRAY, String) - DEFAULT_OP_DVECTOR_GET(POOL_VECTOR2_ARRAY, Vector2) - DEFAULT_OP_DVECTOR_GET(POOL_VECTOR3_ARRAY, Vector3) - DEFAULT_OP_DVECTOR_GET(POOL_COLOR_ARRAY, Color) + } break; // 20 + DEFAULT_OP_ARRAY_CMD(ARRAY, const Array, ;, return (*arr)[index]) + DEFAULT_OP_DVECTOR_GET(POOL_BYTE_ARRAY, uint8_t) + DEFAULT_OP_DVECTOR_GET(POOL_INT_ARRAY, int) + DEFAULT_OP_DVECTOR_GET(POOL_REAL_ARRAY, real_t) + DEFAULT_OP_DVECTOR_GET(POOL_STRING_ARRAY, String) + DEFAULT_OP_DVECTOR_GET(POOL_VECTOR2_ARRAY, Vector2) + DEFAULT_OP_DVECTOR_GET(POOL_VECTOR3_ARRAY, Vector3) + DEFAULT_OP_DVECTOR_GET(POOL_COLOR_ARRAY, Color) default: return Variant(); } return Variant(); - } - -bool Variant::in(const Variant& p_index, bool *r_valid) const { +bool Variant::in(const Variant &p_index, bool *r_valid) const { if (r_valid) - *r_valid=true; + *r_valid = true; - switch(type) { + switch (type) { case STRING: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { //string index - String idx=p_index; - const String *str=reinterpret_cast<const String*>(_data._mem); + String idx = p_index; + const String *str = reinterpret_cast<const String *>(_data._mem); - return str->find(idx)!=-1; + return str->find(idx) != -1; } } break; @@ -2510,68 +2540,65 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { Object *obj = _get_obj().obj; if (obj) { - - bool valid=false; + bool valid = false; #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { //only if debugging! if (!ObjectDB::instance_validate(obj)) { if (r_valid) { - *r_valid=false; + *r_valid = false; } return "Attempted get on stray pointer."; } } #endif - if (p_index.get_type()!=Variant::STRING) { - obj->getvar(p_index,&valid); + if (p_index.get_type() != Variant::STRING) { + obj->getvar(p_index, &valid); } else { - obj->get(p_index,&valid); + obj->get(p_index, &valid); } return valid; } else { if (r_valid) - *r_valid=false; + *r_valid = false; } return false; } break; case DICTIONARY: { - const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem); + const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem); return dic->has(p_index); - } break; // 20 + } break; // 20 case ARRAY: { - const Array *arr=reinterpret_cast<const Array* >(_data._mem); + const Array *arr = reinterpret_cast<const Array *>(_data._mem); int l = arr->size(); if (l) { - for(int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - if (evaluate(OP_EQUAL,(*arr)[i],p_index)) + if (evaluate(OP_EQUAL, (*arr)[i], p_index)) return true; } - } return false; } break; case POOL_BYTE_ARRAY: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>* >(_data._mem); - int l=arr->size(); + const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); + int l = arr->size(); if (l) { PoolVector<uint8_t>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; @@ -2579,18 +2606,17 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { } break; case POOL_INT_ARRAY: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { int index = p_index; - const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>* >(_data._mem); - int l=arr->size(); + const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem); + int l = arr->size(); if (l) { PoolVector<int>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; @@ -2598,18 +2624,17 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { } break; case POOL_REAL_ARRAY: { - if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) { + if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { real_t index = p_index; - const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>* >(_data._mem); - int l=arr->size(); + const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem); + int l = arr->size(); if (l) { PoolVector<real_t>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; @@ -2617,39 +2642,37 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { } break; case POOL_STRING_ARRAY: { - if (p_index.get_type()==Variant::STRING) { + if (p_index.get_type() == Variant::STRING) { String index = p_index; - const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>* >(_data._mem); + const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem); - int l=arr->size(); + int l = arr->size(); if (l) { PoolVector<String>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; } - } break; //25 + } break; //25 case POOL_VECTOR2_ARRAY: { - if (p_index.get_type()==Variant::VECTOR2) { + if (p_index.get_type() == Variant::VECTOR2) { Vector2 index = p_index; - const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>* >(_data._mem); + const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); - int l=arr->size(); + int l = arr->size(); if (l) { PoolVector<Vector2>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; @@ -2657,19 +2680,18 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { } break; case POOL_VECTOR3_ARRAY: { - if (p_index.get_type()==Variant::VECTOR3) { + if (p_index.get_type() == Variant::VECTOR3) { Vector3 index = p_index; - const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>* >(_data._mem); + const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); - int l=arr->size(); + int l = arr->size(); if (l) { PoolVector<Vector3>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; @@ -2678,20 +2700,18 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { } break; case POOL_COLOR_ARRAY: { - if (p_index.get_type()==Variant::COLOR) { + if (p_index.get_type() == Variant::COLOR) { Color index = p_index; - const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>* >(_data._mem); - + const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem); - int l=arr->size(); + int l = arr->size(); if (l) { PoolVector<Color>::Read r = arr->read(); - for(int i=0;i<l;i++) { - if (r[i]==index) + for (int i = 0; i < l; i++) { + if (r[i] == index) return true; } - } return false; @@ -2701,98 +2721,100 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const { } if (r_valid) - *r_valid=false; + *r_valid = false; return false; } void Variant::get_property_list(List<PropertyInfo> *p_list) const { - - switch(type) { + switch (type) { case VECTOR2: { - p_list->push_back( PropertyInfo(Variant::REAL,"x")); - p_list->push_back( PropertyInfo(Variant::REAL,"y")); - p_list->push_back( PropertyInfo(Variant::REAL,"width")); - p_list->push_back( PropertyInfo(Variant::REAL,"height")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::REAL, "width")); + p_list->push_back(PropertyInfo(Variant::REAL, "height")); - } break; // 5 + } break; // 5 case RECT2: { - p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos")); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"size")); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"end")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "size")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "end")); } break; case VECTOR3: { - p_list->push_back( PropertyInfo(Variant::REAL,"x")); - p_list->push_back( PropertyInfo(Variant::REAL,"y")); - p_list->push_back( PropertyInfo(Variant::REAL,"z")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::REAL, "z")); } break; case TRANSFORM2D: { - p_list->push_back( PropertyInfo(Variant::VECTOR2,"x")); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"y")); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"o")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "x")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "o")); } break; case PLANE: { - p_list->push_back( PropertyInfo(Variant::VECTOR3,"normal")); - p_list->push_back( PropertyInfo(Variant::REAL,"x")); - p_list->push_back( PropertyInfo(Variant::REAL,"y")); - p_list->push_back( PropertyInfo(Variant::REAL,"z")); - p_list->push_back( PropertyInfo(Variant::REAL,"d")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "normal")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::REAL, "z")); + p_list->push_back(PropertyInfo(Variant::REAL, "d")); } break; case QUAT: { - p_list->push_back( PropertyInfo(Variant::REAL,"x")); - p_list->push_back( PropertyInfo(Variant::REAL,"y")); - p_list->push_back( PropertyInfo(Variant::REAL,"z")); - p_list->push_back( PropertyInfo(Variant::REAL,"w")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::REAL, "z")); + p_list->push_back(PropertyInfo(Variant::REAL, "w")); } break; case RECT3: { - p_list->push_back( PropertyInfo(Variant::VECTOR3,"pos")); - p_list->push_back( PropertyInfo(Variant::VECTOR3,"size")); - p_list->push_back( PropertyInfo(Variant::VECTOR3,"end")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "pos")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "size")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "end")); } break; //sorry naming convention fail :( not like it's used often // 10 case BASIS: { - p_list->push_back( PropertyInfo(Variant::VECTOR3,"x")); - p_list->push_back( PropertyInfo(Variant::VECTOR3,"y")); - p_list->push_back( PropertyInfo(Variant::VECTOR3,"z")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "x")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "y")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "z")); } break; case TRANSFORM: { - p_list->push_back( PropertyInfo(Variant::BASIS,"basis")); - p_list->push_back( PropertyInfo(Variant::VECTOR3,"origin")); + p_list->push_back(PropertyInfo(Variant::BASIS, "basis")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "origin")); } break; case COLOR: { - p_list->push_back( PropertyInfo(Variant::REAL,"r")); - p_list->push_back( PropertyInfo(Variant::REAL,"g")); - p_list->push_back( PropertyInfo(Variant::REAL,"b")); - p_list->push_back( PropertyInfo(Variant::REAL,"a")); - p_list->push_back( PropertyInfo(Variant::REAL,"h")); - p_list->push_back( PropertyInfo(Variant::REAL,"s")); - p_list->push_back( PropertyInfo(Variant::REAL,"v")); - p_list->push_back( PropertyInfo(Variant::INT,"r8")); - p_list->push_back( PropertyInfo(Variant::INT,"g8")); - p_list->push_back( PropertyInfo(Variant::INT,"b8")); - p_list->push_back( PropertyInfo(Variant::INT,"a8")); - - } break; - case IMAGE: { } break; - case NODE_PATH: { } break; // 15 - case _RID: { } break; + p_list->push_back(PropertyInfo(Variant::REAL, "r")); + p_list->push_back(PropertyInfo(Variant::REAL, "g")); + p_list->push_back(PropertyInfo(Variant::REAL, "b")); + p_list->push_back(PropertyInfo(Variant::REAL, "a")); + p_list->push_back(PropertyInfo(Variant::REAL, "h")); + p_list->push_back(PropertyInfo(Variant::REAL, "s")); + p_list->push_back(PropertyInfo(Variant::REAL, "v")); + p_list->push_back(PropertyInfo(Variant::INT, "r8")); + p_list->push_back(PropertyInfo(Variant::INT, "g8")); + p_list->push_back(PropertyInfo(Variant::INT, "b8")); + p_list->push_back(PropertyInfo(Variant::INT, "a8")); + + } break; + case IMAGE: { + } break; + case NODE_PATH: { + } break; // 15 + case _RID: { + } break; case OBJECT: { - Object *obj=_get_obj().obj; + Object *obj = _get_obj().obj; if (obj) { #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { @@ -2812,109 +2834,101 @@ void Variant::get_property_list(List<PropertyInfo> *p_list) const { InputEvent ie = operator InputEvent(); + p_list->push_back(PropertyInfo(Variant::INT, "type")); + p_list->push_back(PropertyInfo(Variant::INT, "device")); + p_list->push_back(PropertyInfo(Variant::INT, "ID")); + if (ie.type == InputEvent::KEY || ie.type == InputEvent::MOUSE_BUTTON || ie.type == InputEvent::MOUSE_MOTION) { - p_list->push_back( PropertyInfo(Variant::INT,"type")); - p_list->push_back( PropertyInfo(Variant::INT,"device")); - p_list->push_back( PropertyInfo(Variant::INT,"ID")); - - if (ie.type==InputEvent::KEY || ie.type==InputEvent::MOUSE_BUTTON || ie.type==InputEvent::MOUSE_MOTION) { - - p_list->push_back( PropertyInfo(Variant::BOOL,"shift")); - p_list->push_back( PropertyInfo(Variant::BOOL,"alt")); - p_list->push_back( PropertyInfo(Variant::BOOL,"control")); - p_list->push_back( PropertyInfo(Variant::BOOL,"meta")); - + p_list->push_back(PropertyInfo(Variant::BOOL, "shift")); + p_list->push_back(PropertyInfo(Variant::BOOL, "alt")); + p_list->push_back(PropertyInfo(Variant::BOOL, "control")); + p_list->push_back(PropertyInfo(Variant::BOOL, "meta")); } - if (ie.type==InputEvent::KEY) { + if (ie.type == InputEvent::KEY) { - p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") ); - p_list->push_back( PropertyInfo(Variant::BOOL,"echo") ); - p_list->push_back( PropertyInfo(Variant::INT,"scancode") ); - p_list->push_back( PropertyInfo(Variant::INT,"unicode") ); + p_list->push_back(PropertyInfo(Variant::BOOL, "pressed")); + p_list->push_back(PropertyInfo(Variant::BOOL, "echo")); + p_list->push_back(PropertyInfo(Variant::INT, "scancode")); + p_list->push_back(PropertyInfo(Variant::INT, "unicode")); } - if (ie.type==InputEvent::MOUSE_MOTION || ie.type==InputEvent::MOUSE_BUTTON) { - - p_list->push_back( PropertyInfo(Variant::INT,"button_mask") ); - p_list->push_back( PropertyInfo(Variant::REAL,"x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos") ); - p_list->push_back( PropertyInfo(Variant::REAL,"global_x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"global_y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"global_pos") ); + if (ie.type == InputEvent::MOUSE_MOTION || ie.type == InputEvent::MOUSE_BUTTON) { + p_list->push_back(PropertyInfo(Variant::INT, "button_mask")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos")); + p_list->push_back(PropertyInfo(Variant::REAL, "global_x")); + p_list->push_back(PropertyInfo(Variant::REAL, "global_y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "global_pos")); - if (ie.type==InputEvent::MOUSE_MOTION) { + if (ie.type == InputEvent::MOUSE_MOTION) { - p_list->push_back( PropertyInfo(Variant::REAL,"relative_x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"relative_y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"relative_pos") ); - p_list->push_back( PropertyInfo(Variant::REAL,"speed_x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"speed_y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"speed") ); + p_list->push_back(PropertyInfo(Variant::REAL, "relative_x")); + p_list->push_back(PropertyInfo(Variant::REAL, "relative_y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "relative_pos")); + p_list->push_back(PropertyInfo(Variant::REAL, "speed_x")); + p_list->push_back(PropertyInfo(Variant::REAL, "speed_y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "speed")); - } else if (ie.type==InputEvent::MOUSE_BUTTON) { - - p_list->push_back( PropertyInfo(Variant::INT,"button_index") ); - p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") ); - p_list->push_back( PropertyInfo(Variant::BOOL,"doubleclick") ); + } else if (ie.type == InputEvent::MOUSE_BUTTON) { + p_list->push_back(PropertyInfo(Variant::INT, "button_index")); + p_list->push_back(PropertyInfo(Variant::BOOL, "pressed")); + p_list->push_back(PropertyInfo(Variant::BOOL, "doubleclick")); } - } - if (ie.type==InputEvent::JOYPAD_BUTTON) { - - p_list->push_back( PropertyInfo(Variant::INT,"button_index") ); - p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") ); - p_list->push_back( PropertyInfo(Variant::REAL,"pressure") ); + if (ie.type == InputEvent::JOYPAD_BUTTON) { + p_list->push_back(PropertyInfo(Variant::INT, "button_index")); + p_list->push_back(PropertyInfo(Variant::BOOL, "pressed")); + p_list->push_back(PropertyInfo(Variant::REAL, "pressure")); } - if (ie.type==InputEvent::JOYPAD_MOTION) { - - p_list->push_back( PropertyInfo(Variant::INT,"axis") ); - p_list->push_back( PropertyInfo(Variant::REAL,"value") ); + if (ie.type == InputEvent::JOYPAD_MOTION) { + p_list->push_back(PropertyInfo(Variant::INT, "axis")); + p_list->push_back(PropertyInfo(Variant::REAL, "value")); } - if (ie.type==InputEvent::SCREEN_TOUCH) { + if (ie.type == InputEvent::SCREEN_TOUCH) { - p_list->push_back( PropertyInfo(Variant::INT,"index") ); - p_list->push_back( PropertyInfo(Variant::REAL,"x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos") ); - p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") ); + p_list->push_back(PropertyInfo(Variant::INT, "index")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos")); + p_list->push_back(PropertyInfo(Variant::BOOL, "pressed")); } - if (ie.type==InputEvent::SCREEN_DRAG) { + if (ie.type == InputEvent::SCREEN_DRAG) { - p_list->push_back( PropertyInfo(Variant::INT,"index") ); - p_list->push_back( PropertyInfo(Variant::REAL,"x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos") ); - p_list->push_back( PropertyInfo(Variant::REAL,"relative_x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"relative_y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"relative_pos") ); - p_list->push_back( PropertyInfo(Variant::REAL,"speed_x") ); - p_list->push_back( PropertyInfo(Variant::REAL,"speed_y") ); - p_list->push_back( PropertyInfo(Variant::VECTOR2,"speed") ); + p_list->push_back(PropertyInfo(Variant::INT, "index")); + p_list->push_back(PropertyInfo(Variant::REAL, "x")); + p_list->push_back(PropertyInfo(Variant::REAL, "y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos")); + p_list->push_back(PropertyInfo(Variant::REAL, "relative_x")); + p_list->push_back(PropertyInfo(Variant::REAL, "relative_y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "relative_pos")); + p_list->push_back(PropertyInfo(Variant::REAL, "speed_x")); + p_list->push_back(PropertyInfo(Variant::REAL, "speed_y")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "speed")); } } break; case DICTIONARY: { - const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem); + const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem); List<Variant> keys; dic->get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { - if (E->get().get_type()==Variant::STRING) { - p_list->push_back(PropertyInfo(Variant::STRING,E->get())); + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { + if (E->get().get_type() == Variant::STRING) { + p_list->push_back(PropertyInfo(Variant::STRING, E->get())); } } - } break; // 20 + } break; // 20 case ARRAY: case POOL_BYTE_ARRAY: case POOL_INT_ARRAY: @@ -2927,44 +2941,41 @@ void Variant::get_property_list(List<PropertyInfo> *p_list) const { } break; default: {} } - - } -bool Variant::iter_init(Variant& r_iter,bool &valid) const { +bool Variant::iter_init(Variant &r_iter, bool &valid) const { - - valid=true; - switch(type) { + valid = true; + switch (type) { case INT: { - r_iter=0; - return _data._int>0; + r_iter = 0; + return _data._int > 0; } break; case REAL: { - r_iter=0.0; - return _data._real>0.0; + r_iter = 0.0; + return _data._real > 0.0; } break; case VECTOR2: { - real_t from = reinterpret_cast<const Vector2*>(_data._mem)->x; - real_t to = reinterpret_cast<const Vector2*>(_data._mem)->y; + real_t from = reinterpret_cast<const Vector2 *>(_data._mem)->x; + real_t to = reinterpret_cast<const Vector2 *>(_data._mem)->y; - r_iter=from; + r_iter = from; return from < to; } break; case VECTOR3: { - real_t from = reinterpret_cast<const Vector3*>(_data._mem)->x; - real_t to = reinterpret_cast<const Vector3*>(_data._mem)->y; - real_t step = reinterpret_cast<const Vector3*>(_data._mem)->z; + real_t from = reinterpret_cast<const Vector3 *>(_data._mem)->x; + real_t to = reinterpret_cast<const Vector3 *>(_data._mem)->y; + real_t step = reinterpret_cast<const Vector3 *>(_data._mem)->z; - r_iter=from; + r_iter = from; - if (from == to ) { + if (from == to) { return false; } else if (from < to) { - return step>0.0; + return step > 0.0; } else { - return step<0.0; + return step < 0.0; } //return true; } break; @@ -2972,35 +2983,35 @@ bool Variant::iter_init(Variant& r_iter,bool &valid) const { #ifdef DEBUG_ENABLED if (!_get_obj().obj) { - valid=false; + valid = false; return false; } if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) { - valid=false; + valid = false; return false; } #endif Variant::CallError ce; - ce.error=Variant::CallError::CALL_OK; + ce.error = Variant::CallError::CALL_OK; Array ref; ref.push_back(r_iter); - Variant vref=ref; - const Variant *refp[]={&vref}; - Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_init,refp,1,ce); + Variant vref = ref; + const Variant *refp[] = { &vref }; + Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_init, refp, 1, ce); - if (ref.size()!=1 || ce.error!=Variant::CallError::CALL_OK) { - valid=false; + if (ref.size() != 1 || ce.error != Variant::CallError::CALL_OK) { + valid = false; return false; } - r_iter=ref[0]; + r_iter = ref[0]; return ret; } break; case STRING: { - const String *str=reinterpret_cast<const String*>(_data._mem); + const String *str = reinterpret_cast<const String *>(_data._mem); if (str->empty()) return false; r_iter = 0; @@ -3008,91 +3019,89 @@ bool Variant::iter_init(Variant& r_iter,bool &valid) const { } break; case DICTIONARY: { - const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem); + const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem); if (dic->empty()) return false; - const Variant *next=dic->next(NULL); - r_iter=*next; + const Variant *next = dic->next(NULL); + r_iter = *next; return true; } break; case ARRAY: { - const Array *arr=reinterpret_cast<const Array*>(_data._mem); + const Array *arr = reinterpret_cast<const Array *>(_data._mem); if (arr->empty()) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_BYTE_ARRAY: { - const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem); - if (arr->size()==0) + const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_INT_ARRAY: { - const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>*>(_data._mem); - if (arr->size()==0) + const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_REAL_ARRAY: { - const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>*>(_data._mem); - if (arr->size()==0) + const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_STRING_ARRAY: { - const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>*>(_data._mem); - if (arr->size()==0) + const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_VECTOR2_ARRAY: { - const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>*>(_data._mem); - if (arr->size()==0) + const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_VECTOR3_ARRAY: { - const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>*>(_data._mem); - if (arr->size()==0) + const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; case POOL_COLOR_ARRAY: { - const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>*>(_data._mem); - if (arr->size()==0) + const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem); + if (arr->size() == 0) return false; - r_iter=0; + r_iter = 0; return true; } break; default: {} - } - valid=false; + valid = false; return false; } -bool Variant::iter_next(Variant& r_iter,bool &valid) const { +bool Variant::iter_next(Variant &r_iter, bool &valid) const { - - valid=true; - switch(type) { + valid = true; + switch (type) { case INT: { int64_t idx = r_iter; @@ -3105,7 +3114,7 @@ bool Variant::iter_next(Variant& r_iter,bool &valid) const { case REAL: { double idx = r_iter; - idx+=1.0; + idx += 1.0; if (idx >= _data._real) return false; r_iter = idx; @@ -3113,62 +3122,62 @@ bool Variant::iter_next(Variant& r_iter,bool &valid) const { } break; case VECTOR2: { real_t idx = r_iter; - idx+=1.0; - if (idx>=reinterpret_cast<const Vector2*>(_data._mem)->y) + idx += 1.0; + if (idx >= reinterpret_cast<const Vector2 *>(_data._mem)->y) return false; - r_iter=idx; + r_iter = idx; return true; } break; case VECTOR3: { - real_t to = reinterpret_cast<const Vector3*>(_data._mem)->y; - real_t step = reinterpret_cast<const Vector3*>(_data._mem)->z; + real_t to = reinterpret_cast<const Vector3 *>(_data._mem)->y; + real_t step = reinterpret_cast<const Vector3 *>(_data._mem)->z; real_t idx = r_iter; - idx+=step; + idx += step; - if (step<0.0 && idx <= to) + if (step < 0.0 && idx <= to) return false; - if (step>0.0 && idx >= to) + if (step > 0.0 && idx >= to) return false; - r_iter=idx; + r_iter = idx; return true; } break; case OBJECT: { #ifdef DEBUG_ENABLED if (!_get_obj().obj) { - valid=false; + valid = false; return false; } if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) { - valid=false; + valid = false; return false; } #endif Variant::CallError ce; - ce.error=Variant::CallError::CALL_OK; + ce.error = Variant::CallError::CALL_OK; Array ref; ref.push_back(r_iter); - Variant vref=ref; - const Variant *refp[]={&vref}; - Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_next,refp,1,ce); + Variant vref = ref; + const Variant *refp[] = { &vref }; + Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_next, refp, 1, ce); - if (ref.size()!=1 || ce.error!=Variant::CallError::CALL_OK) { - valid=false; + if (ref.size() != 1 || ce.error != Variant::CallError::CALL_OK) { + valid = false; return false; } - r_iter=ref[0]; + r_iter = ref[0]; return ret; } break; case STRING: { - const String *str=reinterpret_cast<const String*>(_data._mem); + const String *str = reinterpret_cast<const String *>(_data._mem); int idx = r_iter; idx++; if (idx >= str->length()) @@ -3178,107 +3187,105 @@ bool Variant::iter_next(Variant& r_iter,bool &valid) const { } break; case DICTIONARY: { - const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem); - const Variant *next=dic->next(&r_iter); + const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem); + const Variant *next = dic->next(&r_iter); if (!next) return false; - r_iter=*next; + r_iter = *next; return true; } break; case ARRAY: { - const Array *arr=reinterpret_cast<const Array*>(_data._mem); - int idx=r_iter; + const Array *arr = reinterpret_cast<const Array *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_BYTE_ARRAY: { - const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem); - int idx=r_iter; + const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_INT_ARRAY: { - const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>*>(_data._mem); - int idx=r_iter; + const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_REAL_ARRAY: { - const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>*>(_data._mem); - int idx=r_iter; + const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_STRING_ARRAY: { - const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>*>(_data._mem); - int idx=r_iter; + const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_VECTOR2_ARRAY: { - const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>*>(_data._mem); - int idx=r_iter; + const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_VECTOR3_ARRAY: { - const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>*>(_data._mem); - int idx=r_iter; + const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; case POOL_COLOR_ARRAY: { - const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>*>(_data._mem); - int idx=r_iter; + const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem); + int idx = r_iter; idx++; - if (idx>=arr->size()) + if (idx >= arr->size()) return false; - r_iter=idx; + r_iter = idx; return true; } break; default: {} - } - valid=false; + valid = false; return false; } -Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const { - +Variant Variant::iter_get(const Variant &r_iter, bool &r_valid) const { - r_valid=true; - switch(type) { + r_valid = true; + switch (type) { case INT: { return r_iter; @@ -3299,22 +3306,22 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const { #ifdef DEBUG_ENABLED if (!_get_obj().obj) { - r_valid=false; + r_valid = false; return Variant(); } if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) { - r_valid=false; + r_valid = false; return Variant(); } #endif Variant::CallError ce; - ce.error=Variant::CallError::CALL_OK; - const Variant *refp[]={&r_iter}; - Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_get,refp,1,ce); + ce.error = Variant::CallError::CALL_OK; + const Variant *refp[] = { &r_iter }; + Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_get, refp, 1, ce); - if (ce.error!=Variant::CallError::CALL_OK) { - r_valid=false; + if (ce.error != Variant::CallError::CALL_OK) { + r_valid = false; return Variant(); } @@ -3325,8 +3332,8 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const { case STRING: { - const String *str=reinterpret_cast<const String*>(_data._mem); - return str->substr(r_iter,1); + const String *str = reinterpret_cast<const String *>(_data._mem); + return str->substr(r_iter, 1); } break; case DICTIONARY: { @@ -3335,55 +3342,55 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const { } break; case ARRAY: { - const Array *arr=reinterpret_cast<const Array*>(_data._mem); - int idx=r_iter; + const Array *arr = reinterpret_cast<const Array *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif return arr->get(idx); } break; case POOL_BYTE_ARRAY: { - const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem); - int idx=r_iter; + const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif return arr->get(idx); } break; case POOL_INT_ARRAY: { - const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>*>(_data._mem); - int idx=r_iter; + const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif return arr->get(idx); } break; case POOL_REAL_ARRAY: { - const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>*>(_data._mem); - int idx=r_iter; + const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif return arr->get(idx); } break; case POOL_STRING_ARRAY: { - const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>*>(_data._mem); - int idx=r_iter; + const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif @@ -3391,23 +3398,23 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const { } break; case POOL_VECTOR2_ARRAY: { - const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>*>(_data._mem); - int idx=r_iter; - #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); + int idx = r_iter; +#ifdef DEBUG_ENABLED + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } - #endif +#endif return arr->get(idx); } break; case POOL_VECTOR3_ARRAY: { - const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>*>(_data._mem); - int idx=r_iter; + const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif @@ -3415,240 +3422,318 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const { } break; case POOL_COLOR_ARRAY: { - const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>*>(_data._mem); - int idx=r_iter; + const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem); + int idx = r_iter; #ifdef DEBUG_ENABLED - if (idx<0 || idx>=arr->size()) { - r_valid=false; + if (idx < 0 || idx >= arr->size()) { + r_valid = false; return Variant(); } #endif return arr->get(idx); } break; default: {} - } - r_valid=false; + r_valid = false; return Variant(); - } -void Variant::blend(const Variant& a, const Variant& b, float c, Variant &r_dst) { - if (a.type!=b.type) { - if(a.is_num() && b.is_num()) { - real_t va=a; - real_t vb=b; - r_dst=va + vb * c; +void Variant::blend(const Variant &a, const Variant &b, float c, Variant &r_dst) { + if (a.type != b.type) { + if (a.is_num() && b.is_num()) { + real_t va = a; + real_t vb = b; + r_dst = va + vb * c; } else { - r_dst=a; + r_dst = a; } return; } - switch(a.type) { - case NIL: { r_dst=Variant(); } return; - case INT:{ - int64_t va=a._data._int; - int64_t vb=b._data._int; - r_dst=int(va + vb * c + 0.5); - } return; - case REAL:{ - double ra=a._data._real; - double rb=b._data._real; - r_dst=ra + rb * c; - } return; - case VECTOR2:{ r_dst=*reinterpret_cast<const Vector2*>(a._data._mem)+*reinterpret_cast<const Vector2*>(b._data._mem)*c; } return; - case RECT2:{ - const Rect2 *ra = reinterpret_cast<const Rect2*>(a._data._mem); - const Rect2 *rb = reinterpret_cast<const Rect2*>(b._data._mem); - r_dst=Rect2(ra->pos + rb->pos * c, ra->size + rb->size * c); - } return; - case VECTOR3:{ r_dst=*reinterpret_cast<const Vector3*>(a._data._mem)+*reinterpret_cast<const Vector3*>(b._data._mem)*c; } return; - case RECT3:{ - const Rect3 *ra = reinterpret_cast<const Rect3*>(a._data._mem); - const Rect3 *rb = reinterpret_cast<const Rect3*>(b._data._mem); - r_dst=Rect3(ra->pos + rb->pos * c, ra->size + rb->size * c); - } return; - case QUAT:{ - Quat empty_rot; - const Quat *qa = reinterpret_cast<const Quat*>(a._data._mem); - const Quat *qb = reinterpret_cast<const Quat*>(b._data._mem); - r_dst=*qa * empty_rot.slerp(*qb,c); - } return; - case COLOR:{ - const Color *ca = reinterpret_cast<const Color*>(a._data._mem); - const Color *cb = reinterpret_cast<const Color*>(b._data._mem); - float r = ca->r + cb->r * c; - float g = ca->g + cb->g * c; - float b = ca->b + cb->b * c; - float a = ca->a + cb->a * c; - r = r > 1.0 ? 1.0 : r; - g = g > 1.0 ? 1.0 : g; - b = b > 1.0 ? 1.0 : b; - a = a > 1.0 ? 1.0 : a; - r_dst=Color(r, g, b, a); - } return; - default:{ r_dst = c<0.5 ? a : b; } return; + switch (a.type) { + case NIL: { + r_dst = Variant(); + } + return; + case INT: { + int64_t va = a._data._int; + int64_t vb = b._data._int; + r_dst = int(va + vb * c + 0.5); + } + return; + case REAL: { + double ra = a._data._real; + double rb = b._data._real; + r_dst = ra + rb * c; + } + return; + case VECTOR2: { + r_dst = *reinterpret_cast<const Vector2 *>(a._data._mem) + *reinterpret_cast<const Vector2 *>(b._data._mem) * c; + } + return; + case RECT2: { + const Rect2 *ra = reinterpret_cast<const Rect2 *>(a._data._mem); + const Rect2 *rb = reinterpret_cast<const Rect2 *>(b._data._mem); + r_dst = Rect2(ra->pos + rb->pos * c, ra->size + rb->size * c); + } + return; + case VECTOR3: { + r_dst = *reinterpret_cast<const Vector3 *>(a._data._mem) + *reinterpret_cast<const Vector3 *>(b._data._mem) * c; + } + return; + case RECT3: { + const Rect3 *ra = reinterpret_cast<const Rect3 *>(a._data._mem); + const Rect3 *rb = reinterpret_cast<const Rect3 *>(b._data._mem); + r_dst = Rect3(ra->pos + rb->pos * c, ra->size + rb->size * c); + } + return; + case QUAT: { + Quat empty_rot; + const Quat *qa = reinterpret_cast<const Quat *>(a._data._mem); + const Quat *qb = reinterpret_cast<const Quat *>(b._data._mem); + r_dst = *qa * empty_rot.slerp(*qb, c); + } + return; + case COLOR: { + const Color *ca = reinterpret_cast<const Color *>(a._data._mem); + const Color *cb = reinterpret_cast<const Color *>(b._data._mem); + float r = ca->r + cb->r * c; + float g = ca->g + cb->g * c; + float b = ca->b + cb->b * c; + float a = ca->a + cb->a * c; + r = r > 1.0 ? 1.0 : r; + g = g > 1.0 ? 1.0 : g; + b = b > 1.0 ? 1.0 : b; + a = a > 1.0 ? 1.0 : a; + r_dst = Color(r, g, b, a); + } + return; + default: { r_dst = c < 0.5 ? a : b; } + return; } } -void Variant::interpolate(const Variant& a, const Variant& b, float c,Variant &r_dst) { +void Variant::interpolate(const Variant &a, const Variant &b, float c, Variant &r_dst) { - if (a.type!=b.type) { + if (a.type != b.type) { if (a.is_num() && b.is_num()) { //not as efficient but.. - real_t va=a; - real_t vb=b; - r_dst=(1.0-c) * va + vb * c; + real_t va = a; + real_t vb = b; + r_dst = (1.0 - c) * va + vb * c; } else { - r_dst=a; + r_dst = a; } return; } + switch (a.type) { - switch(a.type) { - - case NIL:{ r_dst=Variant(); } return; - case BOOL:{ r_dst=a; } return; - case INT:{ - int64_t va=a._data._int; - int64_t vb=b._data._int; - r_dst=int((1.0-c) * va + vb * c); - } return; - case REAL:{ - real_t va=a._data._real; - real_t vb=b._data._real; - r_dst=(1.0-c) * va + vb * c; - - } return; - case STRING:{ + case NIL: { + r_dst = Variant(); + } + return; + case BOOL: { + r_dst = a; + } + return; + case INT: { + int64_t va = a._data._int; + int64_t vb = b._data._int; + r_dst = int((1.0 - c) * va + vb * c); + } + return; + case REAL: { + real_t va = a._data._real; + real_t vb = b._data._real; + r_dst = (1.0 - c) * va + vb * c; + } + return; + case STRING: { //this is pretty funny and bizarre, but artists like to use it for typewritter effects - String sa = *reinterpret_cast<const String*>(a._data._mem); - String sb = *reinterpret_cast<const String*>(b._data._mem); + String sa = *reinterpret_cast<const String *>(a._data._mem); + String sb = *reinterpret_cast<const String *>(b._data._mem); String dst; - int csize=sb.length() * c + sa.length() * (1.0-c); - if (csize==0) { - r_dst=""; + int csize = sb.length() * c + sa.length() * (1.0 - c); + if (csize == 0) { + r_dst = ""; return; } - dst.resize(csize+1); - dst[csize]=0; - int split = csize/2; + dst.resize(csize + 1); + dst[csize] = 0; + int split = csize / 2; - for(int i=0;i<csize;i++) { + for (int i = 0; i < csize; i++) { - CharType chr=' '; + CharType chr = ' '; - if (i<split) { + if (i < split) { - if (i<sa.length()) - chr=sa[i]; - else if (i<sb.length()) - chr=sb[i]; + if (i < sa.length()) + chr = sa[i]; + else if (i < sb.length()) + chr = sb[i]; } else { - if (i<sb.length()) - chr=sb[i]; - else if (i<sa.length()) - chr=sa[i]; - } - - dst[i]=chr; - } - - r_dst=dst; - - - } return; - case VECTOR2:{ r_dst=reinterpret_cast<const Vector2*>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector2*>(b._data._mem),c); } return; - case RECT2:{ r_dst = Rect2( reinterpret_cast<const Rect2*>(a._data._mem)->pos.linear_interpolate(reinterpret_cast<const Rect2*>(b._data._mem)->pos,c), reinterpret_cast<const Rect2*>(a._data._mem)->size.linear_interpolate(reinterpret_cast<const Rect2*>(b._data._mem)->size,c) ); } return; - case VECTOR3:{ r_dst=reinterpret_cast<const Vector3*>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector3*>(b._data._mem),c); } return; - case TRANSFORM2D:{ r_dst=a._data._transform2d->interpolate_with(*b._data._transform2d,c); } return; - case PLANE:{ r_dst=a; } return; - case QUAT:{ r_dst=reinterpret_cast<const Quat*>(a._data._mem)->slerp(*reinterpret_cast<const Quat*>(b._data._mem),c); } return; - case RECT3:{ r_dst=Rect3( a._data._rect3->pos.linear_interpolate(b._data._rect3->pos,c), a._data._rect3->size.linear_interpolate(b._data._rect3->size,c) ); } return; - case BASIS:{ r_dst=Transform(*a._data._basis).interpolate_with(Transform(*b._data._basis),c).basis; } return; - case TRANSFORM:{ r_dst=a._data._transform->interpolate_with(*b._data._transform,c); } return; - case COLOR:{ r_dst=reinterpret_cast<const Color*>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Color*>(b._data._mem),c); } return; - case IMAGE:{ r_dst=a; } return; - case NODE_PATH:{ r_dst=a; } return; - case _RID:{ r_dst=a; } return; - case OBJECT:{ r_dst=a; } return; - case INPUT_EVENT:{ r_dst=a; } return; - case DICTIONARY:{ } return; - case ARRAY:{ r_dst=a; } return; - case POOL_BYTE_ARRAY:{ r_dst=a; } return; - case POOL_INT_ARRAY:{ r_dst=a; } return; - case POOL_REAL_ARRAY:{ r_dst=a; } return; - case POOL_STRING_ARRAY:{ r_dst=a; } return; - case POOL_VECTOR2_ARRAY:{ - const PoolVector<Vector2> *arr_a=reinterpret_cast<const PoolVector<Vector2>* >(a._data._mem); - const PoolVector<Vector2> *arr_b=reinterpret_cast<const PoolVector<Vector2>* >(b._data._mem); + if (i < sb.length()) + chr = sb[i]; + else if (i < sa.length()) + chr = sa[i]; + } + + dst[i] = chr; + } + + r_dst = dst; + } + return; + case VECTOR2: { + r_dst = reinterpret_cast<const Vector2 *>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector2 *>(b._data._mem), c); + } + return; + case RECT2: { + r_dst = Rect2(reinterpret_cast<const Rect2 *>(a._data._mem)->pos.linear_interpolate(reinterpret_cast<const Rect2 *>(b._data._mem)->pos, c), reinterpret_cast<const Rect2 *>(a._data._mem)->size.linear_interpolate(reinterpret_cast<const Rect2 *>(b._data._mem)->size, c)); + } + return; + case VECTOR3: { + r_dst = reinterpret_cast<const Vector3 *>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector3 *>(b._data._mem), c); + } + return; + case TRANSFORM2D: { + r_dst = a._data._transform2d->interpolate_with(*b._data._transform2d, c); + } + return; + case PLANE: { + r_dst = a; + } + return; + case QUAT: { + r_dst = reinterpret_cast<const Quat *>(a._data._mem)->slerp(*reinterpret_cast<const Quat *>(b._data._mem), c); + } + return; + case RECT3: { + r_dst = Rect3(a._data._rect3->pos.linear_interpolate(b._data._rect3->pos, c), a._data._rect3->size.linear_interpolate(b._data._rect3->size, c)); + } + return; + case BASIS: { + r_dst = Transform(*a._data._basis).interpolate_with(Transform(*b._data._basis), c).basis; + } + return; + case TRANSFORM: { + r_dst = a._data._transform->interpolate_with(*b._data._transform, c); + } + return; + case COLOR: { + r_dst = reinterpret_cast<const Color *>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Color *>(b._data._mem), c); + } + return; + case IMAGE: { + r_dst = a; + } + return; + case NODE_PATH: { + r_dst = a; + } + return; + case _RID: { + r_dst = a; + } + return; + case OBJECT: { + r_dst = a; + } + return; + case INPUT_EVENT: { + r_dst = a; + } + return; + case DICTIONARY: { + } + return; + case ARRAY: { + r_dst = a; + } + return; + case POOL_BYTE_ARRAY: { + r_dst = a; + } + return; + case POOL_INT_ARRAY: { + r_dst = a; + } + return; + case POOL_REAL_ARRAY: { + r_dst = a; + } + return; + case POOL_STRING_ARRAY: { + r_dst = a; + } + return; + case POOL_VECTOR2_ARRAY: { + const PoolVector<Vector2> *arr_a = reinterpret_cast<const PoolVector<Vector2> *>(a._data._mem); + const PoolVector<Vector2> *arr_b = reinterpret_cast<const PoolVector<Vector2> *>(b._data._mem); int sz = arr_a->size(); - if (sz==0 || arr_b->size()!=sz) { + if (sz == 0 || arr_b->size() != sz) { - r_dst=a; + r_dst = a; } else { PoolVector<Vector2> v; v.resize(sz); { - PoolVector<Vector2>::Write vw=v.write(); - PoolVector<Vector2>::Read ar=arr_a->read(); - PoolVector<Vector2>::Read br=arr_b->read(); + PoolVector<Vector2>::Write vw = v.write(); + PoolVector<Vector2>::Read ar = arr_a->read(); + PoolVector<Vector2>::Read br = arr_b->read(); - for(int i=0;i<sz;i++) { - vw[i]=ar[i].linear_interpolate(br[i],c); + for (int i = 0; i < sz; i++) { + vw[i] = ar[i].linear_interpolate(br[i], c); } } - r_dst=v; - + r_dst = v; } + } + return; + case POOL_VECTOR3_ARRAY: { - - } return; - case POOL_VECTOR3_ARRAY:{ - - - const PoolVector<Vector3> *arr_a=reinterpret_cast<const PoolVector<Vector3>* >(a._data._mem); - const PoolVector<Vector3> *arr_b=reinterpret_cast<const PoolVector<Vector3>* >(b._data._mem); + const PoolVector<Vector3> *arr_a = reinterpret_cast<const PoolVector<Vector3> *>(a._data._mem); + const PoolVector<Vector3> *arr_b = reinterpret_cast<const PoolVector<Vector3> *>(b._data._mem); int sz = arr_a->size(); - if (sz==0 || arr_b->size()!=sz) { + if (sz == 0 || arr_b->size() != sz) { - r_dst=a; + r_dst = a; } else { PoolVector<Vector3> v; v.resize(sz); { - PoolVector<Vector3>::Write vw=v.write(); - PoolVector<Vector3>::Read ar=arr_a->read(); - PoolVector<Vector3>::Read br=arr_b->read(); + PoolVector<Vector3>::Write vw = v.write(); + PoolVector<Vector3>::Read ar = arr_a->read(); + PoolVector<Vector3>::Read br = arr_b->read(); - for(int i=0;i<sz;i++) { - vw[i]=ar[i].linear_interpolate(br[i],c); + for (int i = 0; i < sz; i++) { + vw[i] = ar[i].linear_interpolate(br[i], c); } } - r_dst=v; - + r_dst = v; } - - } return; - case POOL_COLOR_ARRAY:{ r_dst=a; } return; + } + return; + case POOL_COLOR_ARRAY: { + r_dst = a; + } + return; default: { - r_dst=a; + r_dst = a; } - } } - -static const char *_op_names[Variant::OP_MAX]={ +static const char *_op_names[Variant::OP_MAX] = { "==", "!=", "<", @@ -3676,10 +3761,8 @@ static const char *_op_names[Variant::OP_MAX]={ }; - - String Variant::get_operator_name(Operator p_op) { - ERR_FAIL_INDEX_V(p_op,OP_MAX,""); + ERR_FAIL_INDEX_V(p_op, OP_MAX, ""); return _op_names[p_op]; } diff --git a/core/variant_parser.cpp b/core/variant_parser.cpp index a2ecb1516d..67e4673ad6 100644 --- a/core/variant_parser.cpp +++ b/core/variant_parser.cpp @@ -31,7 +31,6 @@ #include "io/resource_loader.h" #include "os/keyboard.h" - CharType VariantParser::StreamFile::get_char() { return f->get_8(); @@ -46,10 +45,9 @@ bool VariantParser::StreamFile::is_eof() const { return f->eof_reached(); } - CharType VariantParser::StreamString::get_char() { - if (pos>=s.length()) + if (pos >= s.length()) return 0; else return s[pos++]; @@ -59,15 +57,12 @@ bool VariantParser::StreamString::is_utf8() const { return false; } bool VariantParser::StreamString::is_eof() const { - return pos>s.length(); + return pos > s.length(); } - ///////////////////////////////////////////////////////////////////////////////////////////////// - - -const char * VariantParser::tk_name[TK_MAX] = { +const char *VariantParser::tk_name[TK_MAX] = { "'{'", "'}'", "'['", @@ -86,25 +81,23 @@ const char * VariantParser::tk_name[TK_MAX] = { "ERROR" }; - - -Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, String &r_err_str) { +Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, String &r_err_str) { while (true) { CharType cchar; if (p_stream->saved) { - cchar=p_stream->saved; - p_stream->saved=0; + cchar = p_stream->saved; + p_stream->saved = 0; } else { - cchar=p_stream->get_char(); + cchar = p_stream->get_char(); if (p_stream->is_eof()) { - r_token.type=TK_EOF; + r_token.type = TK_EOF; return OK; } } - switch(cchar) { + switch (cchar) { case '\n': { @@ -112,53 +105,53 @@ Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, Stri 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; return OK; }; case '}': { - r_token.type=TK_CURLY_BRACKET_CLOSE; + r_token.type = TK_CURLY_BRACKET_CLOSE; return OK; }; case '[': { - r_token.type=TK_BRACKET_OPEN; + r_token.type = TK_BRACKET_OPEN; return OK; }; case ']': { - r_token.type=TK_BRACKET_CLOSE; + r_token.type = TK_BRACKET_CLOSE; return OK; }; case '(': { - r_token.type=TK_PARENTHESIS_OPEN; + r_token.type = TK_PARENTHESIS_OPEN; return OK; }; case ')': { - r_token.type=TK_PARENTHESIS_CLOSE; + r_token.type = TK_PARENTHESIS_CLOSE; return OK; }; case ':': { - r_token.type=TK_COLON; + r_token.type = TK_COLON; return OK; }; case ';': { - while(true) { - CharType ch=p_stream->get_char(); + while (true) { + CharType ch = p_stream->get_char(); if (p_stream->is_eof()) { - r_token.type=TK_EOF; + r_token.type = TK_EOF; return OK; } - if (ch=='\n') + if (ch == '\n') break; } @@ -166,112 +159,104 @@ Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, Stri }; case ',': { - r_token.type=TK_COMMA; + r_token.type = TK_COMMA; return OK; }; case '.': { - r_token.type=TK_PERIOD; + r_token.type = TK_PERIOD; return OK; }; case '=': { - r_token.type=TK_EQUAL; + r_token.type = TK_EQUAL; return OK; }; case '#': { - - String color_str="#"; - while(true) { - CharType ch=p_stream->get_char(); + String color_str = "#"; + while (true) { + CharType ch = p_stream->get_char(); if (p_stream->is_eof()) { - r_token.type=TK_EOF; + r_token.type = TK_EOF; return OK; - } else if ( (ch>='0' && ch<='9') || (ch>='a' && ch<='f') || (ch>='A' && ch<='F') ) { - color_str+=String::chr(ch); + } else if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) { + color_str += String::chr(ch); } else { - p_stream->saved=ch; + p_stream->saved = ch; break; } } - r_token.value=Color::html(color_str); - r_token.type=TK_COLOR; + r_token.value = Color::html(color_str); + r_token.type = TK_COLOR; return OK; - }; case '"': { - String str; - while(true) { + while (true) { - CharType ch=p_stream->get_char(); + CharType ch = p_stream->get_char(); - if (ch==0) { - r_err_str="Unterminated String"; - r_token.type=TK_ERROR; + if (ch == 0) { + r_err_str = "Unterminated String"; + r_token.type = TK_ERROR; return ERR_PARSE_ERROR; - } else if (ch=='"') { + } else if (ch == '"') { break; - } else if (ch=='\\') { + } else if (ch == '\\') { //escaped characters... CharType next = p_stream->get_char(); - if (next==0) { - r_err_str="Unterminated String"; - r_token.type=TK_ERROR; - return ERR_PARSE_ERROR; + if (next == 0) { + r_err_str = "Unterminated String"; + r_token.type = TK_ERROR; + 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++) { + for (int j = 0; j < 4; j++) { CharType c = p_stream->get_char(); - if (c==0) { - r_err_str="Unterminated String"; - r_token.type=TK_ERROR; + if (c == 0) { + r_err_str = "Unterminated String"; + r_token.type = TK_ERROR; 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_token.type=TK_ERROR; + r_err_str = "Malformed hex constant in string"; + r_token.type = TK_ERROR; 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; } - - } break; //case '\"': res='\"'; break; //case '\\': res='\\'; break; @@ -283,259 +268,242 @@ Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, Stri } break; } - str+=res; + str += res; } else { - if (ch=='\n') + if (ch == '\n') line++; - str+=ch; + str += ch; } } if (p_stream->is_utf8()) { - str.parse_utf8( str.ascii(true).get_data() ); + str.parse_utf8(str.ascii(true).get_data()); } - r_token.type=TK_STRING; - r_token.value=str; + r_token.type = TK_STRING; + r_token.value = str; return OK; } break; default: { - if (cchar<=32) { + if (cchar <= 32) { break; } - if (cchar=='-' || (cchar>='0' && cchar<='9')) { + if (cchar == '-' || (cchar >= '0' && cchar <= '9')) { //a number - String num; #define READING_SIGN 0 #define READING_INT 1 #define READING_DEC 2 #define READING_EXP 3 #define READING_DONE 4 - int reading=READING_INT; - - if (cchar=='-') { - num+='-'; - cchar=p_stream->get_char(); + int reading = READING_INT; + if (cchar == '-') { + num += '-'; + cchar = p_stream->get_char(); } - - CharType c = cchar; - bool exp_sign=false; - bool exp_beg=false; - bool is_float=false; + bool exp_sign = false; + bool exp_beg = false; + bool is_float = false; - while(true) { + while (true) { - switch(reading) { + switch (reading) { case READING_INT: { - if (c>='0' && c<='9') { + if (c >= '0' && c <= '9') { //pass - } else if (c=='.') { - reading=READING_DEC; - is_float=true; - } else if (c=='e') { - reading=READING_EXP; + } else if (c == '.') { + reading = READING_DEC; + is_float = true; + } else if (c == 'e') { + reading = READING_EXP; } else { - reading=READING_DONE; + reading = READING_DONE; } - } break; + } break; case READING_DEC: { - if (c>='0' && c<='9') { + if (c >= '0' && c <= '9') { - } else if (c=='e') { - reading=READING_EXP; + } else if (c == 'e') { + reading = READING_EXP; } else { - reading=READING_DONE; + reading = READING_DONE; } - } break; + } break; case READING_EXP: { - if (c>='0' && c<='9') { - exp_beg=true; + if (c >= '0' && c <= '9') { + exp_beg = true; - } else if ((c=='-' || c=='+') && !exp_sign && !exp_beg) { - if (c=='-') - is_float=true; - exp_sign=true; + } else if ((c == '-' || c == '+') && !exp_sign && !exp_beg) { + if (c == '-') + is_float = true; + exp_sign = true; } else { - reading=READING_DONE; + reading = READING_DONE; } - } break; + } break; } - if (reading==READING_DONE) + if (reading == READING_DONE) break; - num+=String::chr(c); + num += String::chr(c); c = p_stream->get_char(); - - } - p_stream->saved=c; + p_stream->saved = c; - - r_token.type=TK_NUMBER; + r_token.type = TK_NUMBER; if (is_float) - r_token.value=num.to_double(); + r_token.value = num.to_double(); else - r_token.value=num.to_int(); + r_token.value = num.to_int(); return OK; - } else if ((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_') { + } else if ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_') { String id; - bool first=true; + bool first = true; - while((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_' || (!first && cchar>='0' && cchar<='9')) { + while ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_' || (!first && cchar >= '0' && cchar <= '9')) { - id+=String::chr(cchar); - cchar=p_stream->get_char(); - first=false; + id += String::chr(cchar); + cchar = p_stream->get_char(); + first = false; } - p_stream->saved=cchar; + p_stream->saved = cchar; - 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_token.type=TK_ERROR; + r_err_str = "Unexpected character."; + r_token.type = TK_ERROR; return ERR_PARSE_ERROR; } } } } - r_token.type=TK_ERROR; + r_token.type = TK_ERROR; return ERR_PARSE_ERROR; } -Error VariantParser::_parse_enginecfg(Stream *p_stream, Vector<String>& strings, int &line, String &r_err_str) { +Error VariantParser::_parse_enginecfg(Stream *p_stream, Vector<String> &strings, int &line, String &r_err_str) { Token token; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '(' in old-style godot.cfg construct"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '(' in old-style godot.cfg construct"; return ERR_PARSE_ERROR; } - String accum; - while(true) { + while (true) { - CharType c=p_stream->get_char(); + CharType c = p_stream->get_char(); if (p_stream->is_eof()) { - r_err_str="Unexpected EOF while parsing old-style godot.cfg construct"; + r_err_str = "Unexpected EOF while parsing old-style godot.cfg construct"; return ERR_PARSE_ERROR; } - if (c==',') { + if (c == ',') { strings.push_back(accum.strip_edges()); - accum=String(); - } else if (c==')') { + accum = String(); + } else if (c == ')') { strings.push_back(accum.strip_edges()); return OK; - } else if (c=='\n') { + } else if (c == '\n') { line++; } - } return OK; } -template<class T> -Error VariantParser::_parse_construct(Stream *p_stream,Vector<T>& r_construct,int &line,String &r_err_str) { - +template <class T> +Error VariantParser::_parse_construct(Stream *p_stream, Vector<T> &r_construct, int &line, String &r_err_str) { Token token; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '(' in constructor"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '(' in constructor"; return ERR_PARSE_ERROR; } - - bool first=true; - while(true) { + bool first = true; + while (true) { if (!first) { - get_token(p_stream,token,line,r_err_str); - if (token.type==TK_COMMA) { + get_token(p_stream, token, line, r_err_str); + if (token.type == TK_COMMA) { //do none - } else if (token.type==TK_PARENTHESIS_CLOSE) { + } else if (token.type == TK_PARENTHESIS_CLOSE) { break; } else { - r_err_str="Expected ',' or ')' in constructor"; + r_err_str = "Expected ',' or ')' in constructor"; return ERR_PARSE_ERROR; - } } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (first && token.type==TK_PARENTHESIS_CLOSE) { + if (first && token.type == TK_PARENTHESIS_CLOSE) { break; - } else if (token.type!=TK_NUMBER) { - r_err_str="Expected float in constructor"; + } else if (token.type != TK_NUMBER) { + r_err_str = "Expected float in constructor"; return ERR_PARSE_ERROR; } - r_construct.push_back(token.value); - first=false; + first = false; } return OK; - } -Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,int &line,String &r_err_str,ResourceParser *p_res_parser) { +Error VariantParser::parse_value(Token &token, Variant &value, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) { - - -/* { + /* { Error err = get_token(p_stream,token,line,r_err_str); if (err) return err; }*/ - - if (token.type==TK_CURLY_BRACKET_OPEN) { + if (token.type == TK_CURLY_BRACKET_OPEN) { Dictionary d; - Error err = _parse_dictionary(d,p_stream,line,r_err_str,p_res_parser); + Error err = _parse_dictionary(d, p_stream, line, r_err_str, p_res_parser); if (err) return err; - value=d; + value = d; return OK; - } else if (token.type==TK_BRACKET_OPEN) { + } else if (token.type == TK_BRACKET_OPEN) { Array a; - Error err = _parse_array(a,p_stream,line,r_err_str,p_res_parser); + Error err = _parse_array(a, p_stream, line, r_err_str, p_res_parser); if (err) return err; - value=a; + value = a; return OK; - } else if (token.type==TK_IDENTIFIER) { -/* + } else if (token.type == TK_IDENTIFIER) { + /* VECTOR2, // 5 RECT2, VECTOR3, @@ -569,878 +537,853 @@ Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,in */ String id = token.value; - if (id=="true") - value=true; - else if (id=="false") - value=false; - else if (id=="null" || id=="nil") - value=Variant(); - else if (id=="Vector2"){ + if (id == "true") + value = true; + else if (id == "false") + value = false; + else if (id == "null" || id == "nil") + value = Variant(); + else if (id == "Vector2") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=2) { - r_err_str="Expected 2 arguments for constructor"; + if (args.size() != 2) { + r_err_str = "Expected 2 arguments for constructor"; } - value=Vector2(args[0],args[1]); + value = Vector2(args[0], args[1]); return OK; - } else if (id=="Rect2"){ + } else if (id == "Rect2") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=4) { - r_err_str="Expected 4 arguments for constructor"; + if (args.size() != 4) { + r_err_str = "Expected 4 arguments for constructor"; } - value=Rect2(args[0],args[1],args[2],args[3]); + value = Rect2(args[0], args[1], args[2], args[3]); return OK; - } else if (id=="Vector3"){ + } else if (id == "Vector3") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=3) { - r_err_str="Expected 3 arguments for constructor"; + if (args.size() != 3) { + r_err_str = "Expected 3 arguments for constructor"; } - value=Vector3(args[0],args[1],args[2]); + value = Vector3(args[0], args[1], args[2]); return OK; - } else if (id=="Transform2D" || id=="Matrix32"){ //compatibility + } else if (id == "Transform2D" || id == "Matrix32") { //compatibility Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=6) { - r_err_str="Expected 6 arguments for constructor"; + if (args.size() != 6) { + r_err_str = "Expected 6 arguments for constructor"; } Transform2D m; - m[0]=Vector2(args[0],args[1]); - m[1]=Vector2(args[2],args[3]); - m[2]=Vector2(args[4],args[5]); - value=m; + m[0] = Vector2(args[0], args[1]); + m[1] = Vector2(args[2], args[3]); + m[2] = Vector2(args[4], args[5]); + value = m; return OK; - } else if (id=="Plane") { + } else if (id == "Plane") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=4) { - r_err_str="Expected 4 arguments for constructor"; + if (args.size() != 4) { + r_err_str = "Expected 4 arguments for constructor"; } - value=Plane(args[0],args[1],args[2],args[3]); + value = Plane(args[0], args[1], args[2], args[3]); return OK; - } else if (id=="Quat") { + } else if (id == "Quat") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=4) { - r_err_str="Expected 4 arguments for constructor"; + if (args.size() != 4) { + r_err_str = "Expected 4 arguments for constructor"; } - value=Quat(args[0],args[1],args[2],args[3]); + value = Quat(args[0], args[1], args[2], args[3]); return OK; - } else if (id=="Rect3" || id=="AABB"){ + } else if (id == "Rect3" || id == "AABB") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=6) { - r_err_str="Expected 6 arguments for constructor"; + if (args.size() != 6) { + r_err_str = "Expected 6 arguments for constructor"; } - value=Rect3(Vector3(args[0],args[1],args[2]),Vector3(args[3],args[4],args[5])); + value = Rect3(Vector3(args[0], args[1], args[2]), Vector3(args[3], args[4], args[5])); return OK; - } else if (id=="Basis" || id=="Matrix3"){ //compatibility + } else if (id == "Basis" || id == "Matrix3") { //compatibility Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=9) { - r_err_str="Expected 9 arguments for constructor"; + if (args.size() != 9) { + r_err_str = "Expected 9 arguments for constructor"; } - value=Basis(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]); + value = Basis(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); return OK; - } else if (id=="Transform"){ + } else if (id == "Transform") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=12) { - r_err_str="Expected 12 arguments for constructor"; + if (args.size() != 12) { + r_err_str = "Expected 12 arguments for constructor"; } - value=Transform(Basis(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]),Vector3(args[9],args[10],args[11])); + value = Transform(Basis(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]), Vector3(args[9], args[10], args[11])); return OK; - } else if (id=="Color") { + } else if (id == "Color") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; - if (args.size()!=4) { - r_err_str="Expected 4 arguments for constructor"; + if (args.size() != 4) { + r_err_str = "Expected 4 arguments for constructor"; } - value=Color(args[0],args[1],args[2],args[3]); + value = Color(args[0], args[1], args[2], args[3]); return OK; - } else if (id=="Image") { + } else if (id == "Image") { //:| - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '('"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '('"; return ERR_PARSE_ERROR; } - - get_token(p_stream,token,line,r_err_str); - if (token.type==TK_PARENTHESIS_CLOSE) { - value=Image(); // just an Image() + get_token(p_stream, token, line, r_err_str); + if (token.type == TK_PARENTHESIS_CLOSE) { + value = Image(); // just an Image() return OK; - } else if (token.type!=TK_NUMBER) { - r_err_str="Expected number (width)"; + } else if (token.type != TK_NUMBER) { + r_err_str = "Expected number (width)"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - int width=token.value; - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + int width = token.value; + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected number (height)"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected number (height)"; return ERR_PARSE_ERROR; } - int height=token.value; + int height = token.value; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - bool has_mipmaps=false; + bool has_mipmaps = false; - if (token.type==TK_NUMBER) { - has_mipmaps=bool(token.value); - } else if (token.type==TK_IDENTIFIER && String(token.value)=="true") { - has_mipmaps=true; - } else if (token.type==TK_IDENTIFIER && String(token.value)=="false") { - has_mipmaps=false; + if (token.type == TK_NUMBER) { + has_mipmaps = bool(token.value); + } else if (token.type == TK_IDENTIFIER && String(token.value) == "true") { + has_mipmaps = true; + } else if (token.type == TK_IDENTIFIER && String(token.value) == "false") { + has_mipmaps = false; } else { - r_err_str="Expected number/true/false (mipmaps)"; + r_err_str = "Expected number/true/false (mipmaps)"; return ERR_PARSE_ERROR; } - int mipmaps=token.value; + int mipmaps = token.value; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_IDENTIFIER) { - r_err_str="Expected identifier (format)"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_IDENTIFIER) { + r_err_str = "Expected identifier (format)"; return ERR_PARSE_ERROR; } + String sformat = token.value; - String sformat=token.value; - - Image::Format format=Image::FORMAT_MAX; + Image::Format format = Image::FORMAT_MAX; - for(int i=0;i<Image::FORMAT_MAX;i++) { - if (Image::get_format_name(format)==sformat) { - format=Image::Format(i); + for (int i = 0; i < Image::FORMAT_MAX; i++) { + if (Image::get_format_name(format) == sformat) { + format = Image::Format(i); } } - if (format==Image::FORMAT_MAX) { - r_err_str="Unknown image format: "+String(sformat); + if (format == Image::FORMAT_MAX) { + r_err_str = "Unknown image format: " + String(sformat); return ERR_PARSE_ERROR; } - int len = Image::get_image_data_size(width,height,format,mipmaps); + int len = Image::get_image_data_size(width, height, format, mipmaps); PoolVector<uint8_t> buffer; buffer.resize(len); - if (buffer.size()!=len) { - r_err_str="Couldn't allocate image buffer of size: "+itos(len); + if (buffer.size() != len) { + r_err_str = "Couldn't allocate image buffer of size: " + itos(len); } { - PoolVector<uint8_t>::Write w=buffer.write(); + PoolVector<uint8_t>::Write w = buffer.write(); - for(int i=0;i<len;i++) { - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + for (int i = 0; i < len; i++) { + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected number"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected number"; return ERR_PARSE_ERROR; } - w[i]=int(token.value); - + w[i] = int(token.value); } } + Image img(width, height, mipmaps, format, buffer); - Image img(width,height,mipmaps,format,buffer); - - value=img; + value = img; return OK; + } else if (id == "NodePath") { - } else if (id=="NodePath") { - - - - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '('"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '('"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_STRING) { - r_err_str="Expected string as argument for NodePath()"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_STRING) { + r_err_str = "Expected string as argument for NodePath()"; return ERR_PARSE_ERROR; } - value=NodePath(String(token.value)); + value = NodePath(String(token.value)); - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - } else if (id=="RID") { - - + } else if (id == "RID") { - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '('"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '('"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected number as argument"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected number as argument"; return ERR_PARSE_ERROR; } - value=token.value; + value = token.value; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - return OK; - } else if (id=="Resource" || id=="SubResource" || id=="ExtResource") { - - + } else if (id == "Resource" || id == "SubResource" || id == "ExtResource") { - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '('"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '('"; return ERR_PARSE_ERROR; } - - if (p_res_parser && id=="Resource" && p_res_parser->func){ + if (p_res_parser && id == "Resource" && p_res_parser->func) { RES res; - Error err = p_res_parser->func(p_res_parser->userdata,p_stream,res,line,r_err_str); + Error err = p_res_parser->func(p_res_parser->userdata, p_stream, res, line, r_err_str); if (err) return err; - value=res; + value = res; return OK; - } else if (p_res_parser && id=="ExtResource" && p_res_parser->ext_func){ + } else if (p_res_parser && id == "ExtResource" && p_res_parser->ext_func) { RES res; - Error err = p_res_parser->ext_func(p_res_parser->userdata,p_stream,res,line,r_err_str); + Error err = p_res_parser->ext_func(p_res_parser->userdata, p_stream, res, line, r_err_str); if (err) return err; - value=res; + value = res; return OK; - } else if (p_res_parser && id=="SubResource" && p_res_parser->sub_func){ + } else if (p_res_parser && id == "SubResource" && p_res_parser->sub_func) { RES res; - Error err = p_res_parser->sub_func(p_res_parser->userdata,p_stream,res,line,r_err_str); + Error err = p_res_parser->sub_func(p_res_parser->userdata, p_stream, res, line, r_err_str); if (err) return err; - value=res; + value = res; return OK; } else { - get_token(p_stream,token,line,r_err_str); - if (token.type==TK_STRING) { - String path=token.value; + get_token(p_stream, token, line, r_err_str); + if (token.type == TK_STRING) { + String path = token.value; RES res = ResourceLoader::load(path); if (res.is_null()) { - r_err_str="Can't load resource at path: '"+path+"'."; + r_err_str = "Can't load resource at path: '" + path + "'."; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - value=res; + value = res; return OK; } else { - r_err_str="Expected string as argument for Resource()."; + r_err_str = "Expected string as argument for Resource()."; return ERR_PARSE_ERROR; } } return OK; + } else if (id == "InputEvent") { - } else if (id=="InputEvent") { - - - - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '('"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '('"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type!=TK_IDENTIFIER) { - r_err_str="Expected identifier"; + if (token.type != TK_IDENTIFIER) { + r_err_str = "Expected identifier"; return ERR_PARSE_ERROR; } - String id = token.value; InputEvent ie; - if (id=="NONE") { + if (id == "NONE") { - ie.type=InputEvent::NONE; + ie.type = InputEvent::NONE; - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - } else if (id=="KEY") { + } else if (id == "KEY") { - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - ie.type=InputEvent::KEY; + ie.type = InputEvent::KEY; + get_token(p_stream, token, line, r_err_str); + if (token.type == TK_IDENTIFIER) { + String name = token.value; + ie.key.scancode = find_keycode(name); + } else if (token.type == TK_NUMBER) { - get_token(p_stream,token,line,r_err_str); - if (token.type==TK_IDENTIFIER) { - String name=token.value; - ie.key.scancode=find_keycode(name); - } else if (token.type==TK_NUMBER) { - - ie.key.scancode=token.value; + ie.key.scancode = token.value; } else { - r_err_str="Expected string or integer for keycode"; + r_err_str = "Expected string or integer for keycode"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type==TK_COMMA) { + if (token.type == TK_COMMA) { - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type!=TK_IDENTIFIER) { - r_err_str="Expected identifier with modifier flas"; + if (token.type != TK_IDENTIFIER) { + r_err_str = "Expected identifier with modifier flas"; return ERR_PARSE_ERROR; } - String mods=token.value; + String mods = token.value; - 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 (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; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - } else if (token.type!=TK_PARENTHESIS_CLOSE) { + } else if (token.type != TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')' or modifier flags."; + r_err_str = "Expected ')' or modifier flags."; return ERR_PARSE_ERROR; } + } else if (id == "MBUTTON") { - } else if (id=="MBUTTON") { - - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - ie.type=InputEvent::MOUSE_BUTTON; + ie.type = InputEvent::MOUSE_BUTTON; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected button index"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected button index"; return ERR_PARSE_ERROR; } ie.mouse_button.button_index = token.value; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - } else if (id=="JBUTTON") { + } else if (id == "JBUTTON") { - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - ie.type=InputEvent::JOYPAD_BUTTON; + ie.type = InputEvent::JOYPAD_BUTTON; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected button index"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected button index"; return ERR_PARSE_ERROR; } ie.joy_button.button_index = token.value; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - } else if (id=="JAXIS") { + } else if (id == "JAXIS") { - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ','"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_COMMA) { + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } - ie.type=InputEvent::JOYPAD_MOTION; + ie.type = InputEvent::JOYPAD_MOTION; - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected axis index"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected axis index"; return ERR_PARSE_ERROR; } ie.joy_motion.axis = token.value; - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type!=TK_COMMA) { - r_err_str="Expected ',' after axis index"; + if (token.type != TK_COMMA) { + r_err_str = "Expected ',' after axis index"; return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_NUMBER) { - r_err_str="Expected axis sign"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_NUMBER) { + r_err_str = "Expected axis sign"; return ERR_PARSE_ERROR; } ie.joy_motion.axis_value = token.value; - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type!=TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')' for jaxis"; + if (token.type != TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')' for jaxis"; return ERR_PARSE_ERROR; } } else { - r_err_str="Invalid input event type."; + r_err_str = "Invalid input event type."; return ERR_PARSE_ERROR; } - value=ie; + value = ie; return OK; - } else if (id=="PoolByteArray"|| id=="ByteArray") { + } else if (id == "PoolByteArray" || id == "ByteArray") { Vector<uint8_t> args; - Error err = _parse_construct<uint8_t>(p_stream,args,line,r_err_str); + Error err = _parse_construct<uint8_t>(p_stream, args, line, r_err_str); if (err) return err; PoolVector<uint8_t> arr; { - int len=args.size(); + int len = args.size(); arr.resize(len); PoolVector<uint8_t>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=args[i]; + for (int i = 0; i < len; i++) { + w[i] = args[i]; } } - value=arr; + value = arr; return OK; - } else if (id=="PoolIntArray"|| id=="IntArray") { + } else if (id == "PoolIntArray" || id == "IntArray") { Vector<int> args; - Error err = _parse_construct<int>(p_stream,args,line,r_err_str); + Error err = _parse_construct<int>(p_stream, args, line, r_err_str); if (err) return err; PoolVector<int> arr; { - int len=args.size(); + int len = args.size(); arr.resize(len); PoolVector<int>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=int(args[i]); + for (int i = 0; i < len; i++) { + w[i] = int(args[i]); } } - value=arr; + value = arr; return OK; - } else if (id=="PoolFloatArray"|| id=="FloatArray") { + } else if (id == "PoolFloatArray" || id == "FloatArray") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; PoolVector<float> arr; { - int len=args.size(); + int len = args.size(); arr.resize(len); PoolVector<float>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=args[i]; + for (int i = 0; i < len; i++) { + w[i] = args[i]; } } - value=arr; + value = arr; return OK; - } else if (id=="PoolStringArray"|| id=="StringArray") { + } else if (id == "PoolStringArray" || id == "StringArray") { - - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '('"; + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '('"; return ERR_PARSE_ERROR; } Vector<String> cs; - bool first=true; - while(true) { + bool first = true; + while (true) { if (!first) { - get_token(p_stream,token,line,r_err_str); - if (token.type==TK_COMMA) { + get_token(p_stream, token, line, r_err_str); + if (token.type == TK_COMMA) { //do none - } else if (token.type==TK_PARENTHESIS_CLOSE) { + } else if (token.type == TK_PARENTHESIS_CLOSE) { break; } else { - r_err_str="Expected ',' or ')'"; + r_err_str = "Expected ',' or ')'"; return ERR_PARSE_ERROR; - } } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type==TK_PARENTHESIS_CLOSE) { + if (token.type == TK_PARENTHESIS_CLOSE) { break; - } else if (token.type!=TK_STRING) { - r_err_str="Expected string"; + } else if (token.type != TK_STRING) { + r_err_str = "Expected string"; return ERR_PARSE_ERROR; } - first=false; + first = false; cs.push_back(token.value); } - PoolVector<String> arr; { - int len=cs.size(); + int len = cs.size(); arr.resize(len); PoolVector<String>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=cs[i]; + for (int i = 0; i < len; i++) { + w[i] = cs[i]; } } - value=arr; + value = arr; return OK; - - } else if (id=="PoolVector2Array"|| id=="Vector2Array") { + } else if (id == "PoolVector2Array" || id == "Vector2Array") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; PoolVector<Vector2> arr; { - int len=args.size()/2; + int len = args.size() / 2; arr.resize(len); PoolVector<Vector2>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=Vector2(args[i*2+0],args[i*2+1]); + for (int i = 0; i < len; i++) { + w[i] = Vector2(args[i * 2 + 0], args[i * 2 + 1]); } } - value=arr; + value = arr; return OK; - } else if (id=="PoolVector3Array"|| id=="Vector3Array") { + } else if (id == "PoolVector3Array" || id == "Vector3Array") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; PoolVector<Vector3> arr; { - int len=args.size()/3; + int len = args.size() / 3; arr.resize(len); PoolVector<Vector3>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=Vector3(args[i*3+0],args[i*3+1],args[i*3+2]); + for (int i = 0; i < len; i++) { + w[i] = Vector3(args[i * 3 + 0], args[i * 3 + 1], args[i * 3 + 2]); } } - value=arr; + value = arr; return OK; - } else if (id=="PoolColorArray"|| id=="ColorArray") { + } else if (id == "PoolColorArray" || id == "ColorArray") { Vector<float> args; - Error err = _parse_construct<float>(p_stream,args,line,r_err_str); + Error err = _parse_construct<float>(p_stream, args, line, r_err_str); if (err) return err; PoolVector<Color> arr; { - int len=args.size()/4; + int len = args.size() / 4; arr.resize(len); PoolVector<Color>::Write w = arr.write(); - for(int i=0;i<len;i++) { - w[i]=Color(args[i*4+0],args[i*4+1],args[i*4+2],args[i*4+3]); + for (int i = 0; i < len; i++) { + w[i] = Color(args[i * 4 + 0], args[i * 4 + 1], args[i * 4 + 2], args[i * 4 + 3]); } } - value=arr; + value = arr; return OK; - } else if (id=="key") { // compatibility with godot.cfg + } else if (id == "key") { // compatibility with godot.cfg Vector<String> params; - Error err = _parse_enginecfg(p_stream,params,line,r_err_str); + Error err = _parse_enginecfg(p_stream, params, line, r_err_str); if (err) return err; - ERR_FAIL_COND_V(params.size()!=1 && params.size()!=2,ERR_PARSE_ERROR); + ERR_FAIL_COND_V(params.size() != 1 && params.size() != 2, ERR_PARSE_ERROR); - int scode=0; + int scode = 0; if (params[0].is_numeric()) { - scode=params[0].to_int(); + scode = params[0].to_int(); if (scode < 10) { - scode=KEY_0+scode; + scode = KEY_0 + scode; } } else - scode=find_keycode(params[0]); + scode = find_keycode(params[0]); InputEvent ie; - 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; - } - value=ie; + 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; + } + value = ie; return OK; - } else if (id=="mbutton") { // compatibility with godot.cfg + } else if (id == "mbutton") { // compatibility with godot.cfg Vector<String> params; - Error err = _parse_enginecfg(p_stream,params,line,r_err_str); + Error err = _parse_enginecfg(p_stream, params, line, r_err_str); if (err) return err; - ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR); + ERR_FAIL_COND_V(params.size() != 2, ERR_PARSE_ERROR); 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(); - value=ie; + value = ie; return OK; - } else if (id=="jbutton") { // compatibility with godot.cfg + } else if (id == "jbutton") { // compatibility with godot.cfg Vector<String> params; - Error err = _parse_enginecfg(p_stream,params,line,r_err_str); + Error err = _parse_enginecfg(p_stream, params, line, r_err_str); if (err) return err; - ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR); + ERR_FAIL_COND_V(params.size() != 2, ERR_PARSE_ERROR); InputEvent ie; - ie.type=InputEvent::JOYPAD_BUTTON; - ie.device=params[0].to_int(); - ie.joy_button.button_index=params[1].to_int(); + ie.type = InputEvent::JOYPAD_BUTTON; + ie.device = params[0].to_int(); + ie.joy_button.button_index = params[1].to_int(); - value=ie; + value = ie; return OK; - } else if (id=="jaxis") { // compatibility with godot.cfg + } else if (id == "jaxis") { // compatibility with godot.cfg Vector<String> params; - Error err = _parse_enginecfg(p_stream,params,line,r_err_str); + Error err = _parse_enginecfg(p_stream, params, line, r_err_str); if (err) return err; - ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR); + ERR_FAIL_COND_V(params.size() != 2, ERR_PARSE_ERROR); InputEvent ie; - ie.type=InputEvent::JOYPAD_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::JOYPAD_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; - value= ie; + value = ie; return OK; - } else if (id=="img") { // compatibility with godot.cfg + } else if (id == "img") { // compatibility with godot.cfg - Token token; // FIXME: no need for this declaration? the first argument in line 509 is a Token& token. - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_PARENTHESIS_OPEN) { - r_err_str="Expected '(' in old-style godot.cfg construct"; + Token token; // FIXME: no need for this declaration? the first argument in line 509 is a Token& token. + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_PARENTHESIS_OPEN) { + r_err_str = "Expected '(' in old-style godot.cfg construct"; return ERR_PARSE_ERROR; } - while(true) { + while (true) { CharType c = p_stream->get_char(); if (p_stream->is_eof()) { - r_err_str="Unexpected EOF in old style godot.cfg img()"; + r_err_str = "Unexpected EOF in old style godot.cfg img()"; return ERR_PARSE_ERROR; } - if (c==')') + if (c == ')') break; } - value=Image(); + value = Image(); return OK; } else { - r_err_str="Unexpected identifier: '"+id+"'."; + r_err_str = "Unexpected identifier: '" + id + "'."; return ERR_PARSE_ERROR; } - /* VECTOR2, // 5 RECT2, @@ -1477,338 +1420,317 @@ Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,in 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 if (token.type==TK_COLOR) { + } else if (token.type == TK_COLOR) { - 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 VariantParser::_parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) { Token token; - bool need_comma=false; - + bool need_comma = false; - while(true) { + while (true) { if (p_stream->is_eof()) { - r_err_str="Unexpected End of File while parsing array"; + r_err_str = "Unexpected End of File while parsing array"; return ERR_FILE_CORRUPT; } - Error err = get_token(p_stream,token,line,r_err_str); - if (err!=OK) + Error err = get_token(p_stream, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_BRACKET_CLOSE) { + if (token.type == TK_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected ','"; + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } Variant v; - err = parse_value(token,v,p_stream,line,r_err_str,p_res_parser); + err = parse_value(token, v, p_stream, line, r_err_str, p_res_parser); if (err) return err; array.push_back(v); - need_comma=true; - + need_comma = true; } return OK; - } Error VariantParser::_parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) { - bool at_key=true; + bool at_key = true; Variant key; Token token; - bool need_comma=false; - - - while(true) { + bool need_comma = false; + while (true) { if (p_stream->is_eof()) { - r_err_str="Unexpected End of File while parsing dictionary"; + r_err_str = "Unexpected End of File while parsing dictionary"; return ERR_FILE_CORRUPT; } if (at_key) { - Error err = get_token(p_stream,token,line,r_err_str); - if (err!=OK) + Error err = get_token(p_stream, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_CURLY_BRACKET_CLOSE) { + if (token.type == TK_CURLY_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected '}' or ','"; + r_err_str = "Expected '}' or ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } - - - - err = parse_value(token,key,p_stream,line,r_err_str,p_res_parser); + err = parse_value(token, key, p_stream, line, r_err_str, p_res_parser); if (err) return err; - err = get_token(p_stream,token,line,r_err_str); + err = get_token(p_stream, token, line, r_err_str); - if (err!=OK) + if (err != OK) return err; - if (token.type!=TK_COLON) { + if (token.type != TK_COLON) { - r_err_str="Expected ':'"; + r_err_str = "Expected ':'"; return ERR_PARSE_ERROR; } - at_key=false; + at_key = false; } else { - - Error err = get_token(p_stream,token,line,r_err_str); - if (err!=OK) + Error err = get_token(p_stream, token, line, r_err_str); + if (err != OK) return err; Variant v; - err = parse_value(token,v,p_stream,line,r_err_str,p_res_parser); + err = parse_value(token, v, p_stream, line, r_err_str, p_res_parser); if (err) return err; - object[key]=v; - need_comma=true; - at_key=true; + object[key] = v; + need_comma = true; + at_key = true; } } return OK; } - -Error VariantParser::_parse_tag(Token& token, Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, ResourceParser *p_res_parser,bool p_simple_tag) { +Error VariantParser::_parse_tag(Token &token, Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser, bool p_simple_tag) { r_tag.fields.clear(); - if (token.type!=TK_BRACKET_OPEN) { - r_err_str="Expected '['"; + if (token.type != TK_BRACKET_OPEN) { + r_err_str = "Expected '['"; return ERR_PARSE_ERROR; } - if (p_simple_tag) { - r_tag.name=""; + r_tag.name = ""; r_tag.fields.clear(); - while(true) { + while (true) { CharType c = p_stream->get_char(); if (p_stream->is_eof()) { - r_err_str="Unexpected EOF while parsing simple tag"; + r_err_str = "Unexpected EOF while parsing simple tag"; return ERR_PARSE_ERROR; } - if (c==']') + if (c == ']') break; - r_tag.name+=String::chr(c); + r_tag.name += String::chr(c); } r_tag.name = r_tag.name.strip_edges(); return OK; - } - get_token(p_stream,token,line,r_err_str); - + get_token(p_stream, token, line, r_err_str); - if (token.type!=TK_IDENTIFIER) { - r_err_str="Expected identifier (tag name)"; + if (token.type != TK_IDENTIFIER) { + r_err_str = "Expected identifier (tag name)"; return ERR_PARSE_ERROR; } - r_tag.name=token.value; - bool parsing_tag=true; + r_tag.name = token.value; + bool parsing_tag = true; - while(true) { + while (true) { if (p_stream->is_eof()) { - r_err_str="Unexpected End of File while parsing tag: "+r_tag.name; + r_err_str = "Unexpected End of File while parsing tag: " + r_tag.name; return ERR_FILE_CORRUPT; } - get_token(p_stream,token,line,r_err_str); - if (token.type==TK_BRACKET_CLOSE) + get_token(p_stream, token, line, r_err_str); + if (token.type == TK_BRACKET_CLOSE) break; - if (parsing_tag && token.type==TK_PERIOD) { - r_tag.name+="."; //support tags such as [someprop.Anroid] for specific platforms - get_token(p_stream,token,line,r_err_str); - } else if (parsing_tag && token.type==TK_COLON) { - r_tag.name+=":"; //support tags such as [someprop.Anroid] for specific platforms - get_token(p_stream,token,line,r_err_str); + if (parsing_tag && token.type == TK_PERIOD) { + r_tag.name += "."; //support tags such as [someprop.Anroid] for specific platforms + get_token(p_stream, token, line, r_err_str); + } else if (parsing_tag && token.type == TK_COLON) { + r_tag.name += ":"; //support tags such as [someprop.Anroid] for specific platforms + get_token(p_stream, token, line, r_err_str); } else { - parsing_tag=false; + parsing_tag = false; } - if (token.type!=TK_IDENTIFIER) { - r_err_str="Expected Identifier"; + if (token.type != TK_IDENTIFIER) { + r_err_str = "Expected Identifier"; return ERR_PARSE_ERROR; } - String id=token.value; + String id = token.value; if (parsing_tag) { - r_tag.name+=id; + r_tag.name += id; continue; } - get_token(p_stream,token,line,r_err_str); - if (token.type!=TK_EQUAL) { + get_token(p_stream, token, line, r_err_str); + if (token.type != TK_EQUAL) { return ERR_PARSE_ERROR; } - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); Variant value; - Error err = parse_value(token,value,p_stream,line,r_err_str,p_res_parser); + Error err = parse_value(token, value, p_stream, line, r_err_str, p_res_parser); if (err) return err; - r_tag.fields[id]=value; - + r_tag.fields[id] = value; } - return OK; - } -Error VariantParser::parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, ResourceParser *p_res_parser, bool p_simple_tag) { +Error VariantParser::parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser, bool p_simple_tag) { Token token; - get_token(p_stream,token,line,r_err_str); + get_token(p_stream, token, line, r_err_str); - if (token.type==TK_EOF) { + if (token.type == TK_EOF) { return ERR_FILE_EOF; } - if (token.type!=TK_BRACKET_OPEN) { - r_err_str="Expected '['"; + if (token.type != TK_BRACKET_OPEN) { + r_err_str = "Expected '['"; return ERR_PARSE_ERROR; } - return _parse_tag(token,p_stream,line,r_err_str,r_tag,p_res_parser,p_simple_tag); - + return _parse_tag(token, p_stream, line, r_err_str, r_tag, p_res_parser, p_simple_tag); } -Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser, bool p_simple_tag) { - +Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser, bool p_simple_tag) { //assign.. - r_assign=""; + r_assign = ""; String what; - while(true) { - + while (true) { CharType c; if (p_stream->saved) { - c=p_stream->saved; - p_stream->saved=0; + c = p_stream->saved; + p_stream->saved = 0; } else { - c=p_stream->get_char(); + c = p_stream->get_char(); } if (p_stream->is_eof()) return ERR_FILE_EOF; - if (c==';') { //comment - while(true) { - CharType ch=p_stream->get_char(); + if (c == ';') { //comment + while (true) { + CharType ch = p_stream->get_char(); if (p_stream->is_eof()) { return ERR_FILE_EOF; } - if (ch=='\n') + if (ch == '\n') break; } continue; } - if (c=='[' && what.length()==0) { + if (c == '[' && what.length() == 0) { //it's a tag! - p_stream->saved='['; //go back one + p_stream->saved = '['; //go back one - Error err = parse_tag(p_stream,line,r_err_str,r_tag,p_res_parser,p_simple_tag); + Error err = parse_tag(p_stream, line, r_err_str, r_tag, p_res_parser, p_simple_tag); return err; } - if (c>32) { - if (c=='"') { //quoted - p_stream->saved='"'; + if (c > 32) { + if (c == '"') { //quoted + p_stream->saved = '"'; Token tk; - Error err = get_token(p_stream,tk,line,r_err_str); + Error err = get_token(p_stream, tk, line, r_err_str); if (err) return err; - if (tk.type!=TK_STRING) { - r_err_str="Error reading quoted string"; + if (tk.type != TK_STRING) { + r_err_str = "Error reading quoted string"; return err; } - what=tk.value; + what = tk.value; - } else if (c!='=') { - what+=String::chr(c); + } else if (c != '=') { + what += String::chr(c); } else { - r_assign=what; + r_assign = what; Token token; - get_token(p_stream,token,line,r_err_str); - Error err = parse_value(token,r_value,p_stream,line,r_err_str,p_res_parser); + get_token(p_stream, token, line, r_err_str); + Error err = parse_value(token, r_value, p_stream, line, r_err_str, p_res_parser); if (err) { - } return err; } - } else if (c=='\n') { + } else if (c == '\n') { line++; } } @@ -1816,198 +1738,192 @@ Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r return OK; } -Error VariantParser::parse(Stream *p_stream, Variant& r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser) { - +Error VariantParser::parse(Stream *p_stream, Variant &r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser) { Token token; - Error err = get_token(p_stream,token,r_err_line,r_err_str); + Error err = get_token(p_stream, token, r_err_line, r_err_str); if (err) return err; - if (token.type==TK_EOF) { + if (token.type == TK_EOF) { return ERR_FILE_EOF; } - return parse_value(token,r_ret,p_stream,r_err_line,r_err_str,p_res_parser); - + return parse_value(token, r_ret, p_stream, r_err_line, r_err_str, p_res_parser); } - - ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// static String rtosfix(double p_value) { - - if (p_value==0.0) + if (p_value == 0.0) return "0"; //avoid negative zero (-0) being written, which may annoy git, svn, etc. for changes when they don't exist. else return rtoss(p_value); } -Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud,EncodeResourceFunc p_encode_res_func,void* p_encode_res_ud) { +Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud) { - switch( p_variant.get_type() ) { + switch (p_variant.get_type()) { case Variant::NIL: { - p_store_string_func(p_store_string_ud,"null"); + p_store_string_func(p_store_string_ud, "null"); } break; case Variant::BOOL: { - p_store_string_func(p_store_string_ud,p_variant.operator bool() ? "true":"false" ); + p_store_string_func(p_store_string_ud, p_variant.operator bool() ? "true" : "false"); } break; case Variant::INT: { - p_store_string_func(p_store_string_ud, itos(p_variant.operator int()) ); + p_store_string_func(p_store_string_ud, itos(p_variant.operator int())); } break; case Variant::REAL: { String s = rtosfix(p_variant.operator real_t()); - if (s.find(".")==-1 && s.find("e")==-1) - s+=".0"; - p_store_string_func(p_store_string_ud, s ); + if (s.find(".") == -1 && s.find("e") == -1) + s += ".0"; + p_store_string_func(p_store_string_ud, s); } break; case Variant::STRING: { - String str=p_variant; + String str = p_variant; - str="\""+str.c_escape_multiline()+"\""; - p_store_string_func(p_store_string_ud, str ); + str = "\"" + str.c_escape_multiline() + "\""; + p_store_string_func(p_store_string_ud, str); } break; case Variant::VECTOR2: { Vector2 v = p_variant; - p_store_string_func(p_store_string_ud,"Vector2( "+rtosfix(v.x) +", "+rtosfix(v.y)+" )" ); + p_store_string_func(p_store_string_ud, "Vector2( " + rtosfix(v.x) + ", " + rtosfix(v.y) + " )"); } break; case Variant::RECT2: { Rect2 aabb = p_variant; - p_store_string_func(p_store_string_ud,"Rect2( "+rtosfix(aabb.pos.x) +", "+rtosfix(aabb.pos.y) +", "+rtosfix(aabb.size.x) +", "+rtosfix(aabb.size.y)+" )" ); + p_store_string_func(p_store_string_ud, "Rect2( " + rtosfix(aabb.pos.x) + ", " + rtosfix(aabb.pos.y) + ", " + rtosfix(aabb.size.x) + ", " + rtosfix(aabb.size.y) + " )"); } break; case Variant::VECTOR3: { Vector3 v = p_variant; - p_store_string_func(p_store_string_ud,"Vector3( "+rtosfix(v.x) +", "+rtosfix(v.y)+", "+rtosfix(v.z)+" )"); + p_store_string_func(p_store_string_ud, "Vector3( " + rtosfix(v.x) + ", " + rtosfix(v.y) + ", " + rtosfix(v.z) + " )"); } break; case Variant::PLANE: { Plane p = p_variant; - p_store_string_func(p_store_string_ud,"Plane( "+rtosfix(p.normal.x) +", "+rtosfix(p.normal.y)+", "+rtosfix(p.normal.z)+", "+rtosfix(p.d)+" )" ); + p_store_string_func(p_store_string_ud, "Plane( " + rtosfix(p.normal.x) + ", " + rtosfix(p.normal.y) + ", " + rtosfix(p.normal.z) + ", " + rtosfix(p.d) + " )"); } break; case Variant::RECT3: { Rect3 aabb = p_variant; - p_store_string_func(p_store_string_ud,"Rect3( "+rtosfix(aabb.pos.x) +", "+rtosfix(aabb.pos.y) +", "+rtosfix(aabb.pos.z) +", "+rtosfix(aabb.size.x) +", "+rtosfix(aabb.size.y) +", "+rtosfix(aabb.size.z)+" )" ); + p_store_string_func(p_store_string_ud, "Rect3( " + rtosfix(aabb.pos.x) + ", " + rtosfix(aabb.pos.y) + ", " + rtosfix(aabb.pos.z) + ", " + rtosfix(aabb.size.x) + ", " + rtosfix(aabb.size.y) + ", " + rtosfix(aabb.size.z) + " )"); } break; case Variant::QUAT: { Quat quat = p_variant; - p_store_string_func(p_store_string_ud,"Quat( "+rtosfix(quat.x)+", "+rtosfix(quat.y)+", "+rtosfix(quat.z)+", "+rtosfix(quat.w)+" )"); + p_store_string_func(p_store_string_ud, "Quat( " + rtosfix(quat.x) + ", " + rtosfix(quat.y) + ", " + rtosfix(quat.z) + ", " + rtosfix(quat.w) + " )"); } break; case Variant::TRANSFORM2D: { - String s="Transform2D( "; + String s = "Transform2D( "; Transform2D m3 = p_variant; - 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+=rtosfix( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtosfix(m3.elements[i][j]); } } - p_store_string_func(p_store_string_ud,s+" )"); + p_store_string_func(p_store_string_ud, s + " )"); } break; case Variant::BASIS: { - String s="Basis( "; + String s = "Basis( "; Basis m3 = p_variant; - 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+=rtosfix( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtosfix(m3.elements[i][j]); } } - p_store_string_func(p_store_string_ud,s+" )"); + p_store_string_func(p_store_string_ud, s + " )"); } break; case Variant::TRANSFORM: { - String s="Transform( "; + String s = "Transform( "; Transform t = p_variant; Basis &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+=rtosfix( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtosfix(m3.elements[i][j]); } } - s=s+", "+rtosfix(t.origin.x) +", "+rtosfix(t.origin.y)+", "+rtosfix(t.origin.z); + s = s + ", " + rtosfix(t.origin.x) + ", " + rtosfix(t.origin.y) + ", " + rtosfix(t.origin.z); - p_store_string_func(p_store_string_ud,s+" )"); + p_store_string_func(p_store_string_ud, s + " )"); } break; - // misc types + // misc types case Variant::COLOR: { Color c = p_variant; - p_store_string_func(p_store_string_ud,"Color( "+rtosfix(c.r) +", "+rtosfix(c.g)+", "+rtosfix(c.b)+", "+rtosfix(c.a)+" )"); + p_store_string_func(p_store_string_ud, "Color( " + rtosfix(c.r) + ", " + rtosfix(c.g) + ", " + rtosfix(c.b) + ", " + rtosfix(c.a) + " )"); } break; case Variant::IMAGE: { - - Image img=p_variant; + Image img = p_variant; if (img.empty()) { - p_store_string_func(p_store_string_ud,"Image()"); + p_store_string_func(p_store_string_ud, "Image()"); break; } - String imgstr="Image( "; - imgstr+=itos(img.get_width()); - imgstr+=", "+itos(img.get_height()); - imgstr+=", "+String(img.has_mipmaps()?"true":"false"); - imgstr+=", "+Image::get_format_name(img.get_format()); + String imgstr = "Image( "; + imgstr += itos(img.get_width()); + imgstr += ", " + itos(img.get_height()); + imgstr += ", " + String(img.has_mipmaps() ? "true" : "false"); + imgstr += ", " + Image::get_format_name(img.get_format()); String s; PoolVector<uint8_t> data = img.get_data(); int len = data.size(); PoolVector<uint8_t>::Read r = data.read(); - const uint8_t *ptr=r.ptr(); - for (int i=0;i<len;i++) { + const uint8_t *ptr = r.ptr(); + for (int i = 0; i < len; i++) { - if (i>0) - s+=", "; - s+=itos(ptr[i]); + if (i > 0) + s += ", "; + s += itos(ptr[i]); } - imgstr+=", "; - p_store_string_func(p_store_string_ud,imgstr); - p_store_string_func(p_store_string_ud,s); - p_store_string_func(p_store_string_ud," )"); + imgstr += ", "; + p_store_string_func(p_store_string_ud, imgstr); + p_store_string_func(p_store_string_ud, s); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::NODE_PATH: { - String str=p_variant; + String str = p_variant; - str="NodePath(\""+str.c_escape()+"\")"; - p_store_string_func(p_store_string_ud,str); + str = "NodePath(\"" + str.c_escape() + "\")"; + p_store_string_func(p_store_string_ud, str); } break; @@ -2015,7 +1931,7 @@ Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_str RES res = p_variant; if (res.is_null()) { - p_store_string_func(p_store_string_ud,"null"); + p_store_string_func(p_store_string_ud, "null"); break; // don't save it } @@ -2023,64 +1939,64 @@ Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_str if (p_encode_res_func) { - res_text=p_encode_res_func(p_encode_res_ud,res); + res_text = p_encode_res_func(p_encode_res_ud, res); } - if (res_text==String() && res->get_path().is_resource_file()) { + if (res_text == String() && res->get_path().is_resource_file()) { //external resource - String path=res->get_path(); - res_text="Resource( \""+path+"\")"; + String path = res->get_path(); + res_text = "Resource( \"" + path + "\")"; } - if (res_text==String()) - res_text="null"; + if (res_text == String()) + res_text = "null"; - p_store_string_func(p_store_string_ud,res_text); + p_store_string_func(p_store_string_ud, res_text); } break; case Variant::INPUT_EVENT: { - String str="InputEvent("; + String str = "InputEvent("; - InputEvent ev=p_variant; - switch(ev.type) { + InputEvent ev = p_variant; + switch (ev.type) { case InputEvent::KEY: { - str+="KEY,"+itos(ev.key.scancode); + str += "KEY," + itos(ev.key.scancode); String mod; if (ev.key.mod.alt) - mod+="A"; + mod += "A"; if (ev.key.mod.shift) - mod+="S"; + mod += "S"; if (ev.key.mod.control) - mod+="C"; + mod += "C"; if (ev.key.mod.meta) - mod+="M"; + mod += "M"; - if (mod!=String()) - str+=","+mod; + if (mod != String()) + str += "," + mod; } break; case InputEvent::MOUSE_BUTTON: { - str+="MBUTTON,"+itos(ev.mouse_button.button_index); + str += "MBUTTON," + itos(ev.mouse_button.button_index); } break; case InputEvent::JOYPAD_BUTTON: { - str+="JBUTTON,"+itos(ev.joy_button.button_index); + str += "JBUTTON," + itos(ev.joy_button.button_index); } break; case InputEvent::JOYPAD_MOTION: { - str+="JAXIS,"+itos(ev.joy_motion.axis)+","+itos(ev.joy_motion.axis_value); + str += "JAXIS," + itos(ev.joy_motion.axis) + "," + itos(ev.joy_motion.axis_value); } break; case InputEvent::NONE: { - str+="NONE"; + str += "NONE"; } break; default: {} } - str+=")"; + str += ")"; - p_store_string_func(p_store_string_ud,str); //will be added later + p_store_string_func(p_store_string_ud, str); //will be added later } break; case Variant::DICTIONARY: { @@ -2091,196 +2007,186 @@ Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_str dict.get_key_list(&keys); keys.sort(); - p_store_string_func(p_store_string_ud,"{\n"); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + p_store_string_func(p_store_string_ud, "{\n"); + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* if (!_check_type(dict[E->get()])) continue; */ - write(E->get(),p_store_string_func,p_store_string_ud,p_encode_res_func,p_encode_res_ud); - p_store_string_func(p_store_string_ud,": "); - write(dict[E->get()],p_store_string_func,p_store_string_ud,p_encode_res_func,p_encode_res_ud); + write(E->get(), p_store_string_func, p_store_string_ud, p_encode_res_func, p_encode_res_ud); + p_store_string_func(p_store_string_ud, ": "); + write(dict[E->get()], p_store_string_func, p_store_string_ud, p_encode_res_func, p_encode_res_ud); if (E->next()) - p_store_string_func(p_store_string_ud,",\n"); + p_store_string_func(p_store_string_ud, ",\n"); } - - p_store_string_func(p_store_string_ud,"\n}"); - + p_store_string_func(p_store_string_ud, "\n}"); } break; case Variant::ARRAY: { - p_store_string_func(p_store_string_ud,"[ "); + p_store_string_func(p_store_string_ud, "[ "); Array array = p_variant; - int len=array.size(); - for (int i=0;i<len;i++) { - - if (i>0) - p_store_string_func(p_store_string_ud,", "); - write(array[i],p_store_string_func,p_store_string_ud,p_encode_res_func,p_encode_res_ud); + int len = array.size(); + for (int i = 0; i < len; i++) { + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + write(array[i], p_store_string_func, p_store_string_ud, p_encode_res_func, p_encode_res_ud); } - p_store_string_func(p_store_string_ud," ]"); + p_store_string_func(p_store_string_ud, " ]"); } break; case Variant::POOL_BYTE_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolByteArray( "); + p_store_string_func(p_store_string_ud, "PoolByteArray( "); String s; PoolVector<uint8_t> data = p_variant; int len = data.size(); PoolVector<uint8_t>::Read r = data.read(); - const uint8_t *ptr=r.ptr(); - for (int i=0;i<len;i++) { - - if (i>0) - p_store_string_func(p_store_string_ud,", "); + const uint8_t *ptr = r.ptr(); + for (int i = 0; i < len; i++) { - p_store_string_func(p_store_string_ud,itos(ptr[i])); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + p_store_string_func(p_store_string_ud, itos(ptr[i])); } - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::POOL_INT_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolIntArray( "); + p_store_string_func(p_store_string_ud, "PoolIntArray( "); PoolVector<int> data = p_variant; int len = data.size(); PoolVector<int>::Read r = data.read(); - const int *ptr=r.ptr(); + const int *ptr = r.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - p_store_string_func(p_store_string_ud,", "); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); - p_store_string_func(p_store_string_ud,itos(ptr[i])); + p_store_string_func(p_store_string_ud, itos(ptr[i])); } - - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::POOL_REAL_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolFloatArray( "); + p_store_string_func(p_store_string_ud, "PoolFloatArray( "); PoolVector<real_t> data = p_variant; int len = data.size(); PoolVector<real_t>::Read r = data.read(); - const real_t *ptr=r.ptr(); + const real_t *ptr = r.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - p_store_string_func(p_store_string_ud,", "); - p_store_string_func(p_store_string_ud,rtosfix(ptr[i])); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + p_store_string_func(p_store_string_ud, rtosfix(ptr[i])); } - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::POOL_STRING_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolStringArray( "); + p_store_string_func(p_store_string_ud, "PoolStringArray( "); PoolVector<String> data = p_variant; int len = data.size(); PoolVector<String>::Read r = data.read(); - const String *ptr=r.ptr(); + const String *ptr = r.ptr(); String s; //write_string("\n"); + for (int i = 0; i < len; i++) { - - for (int i=0;i<len;i++) { - - if (i>0) - p_store_string_func(p_store_string_ud,", "); - String str=ptr[i]; - p_store_string_func(p_store_string_ud,"\""+str.c_escape()+"\""); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + String str = ptr[i]; + p_store_string_func(p_store_string_ud, "\"" + str.c_escape() + "\""); } - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::POOL_VECTOR2_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolVector2Array( "); + p_store_string_func(p_store_string_ud, "PoolVector2Array( "); PoolVector<Vector2> data = p_variant; int len = data.size(); PoolVector<Vector2>::Read r = data.read(); - const Vector2 *ptr=r.ptr(); + const Vector2 *ptr = r.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - p_store_string_func(p_store_string_ud,", "); - p_store_string_func(p_store_string_ud,rtosfix(ptr[i].x)+", "+rtosfix(ptr[i].y) ); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + p_store_string_func(p_store_string_ud, rtosfix(ptr[i].x) + ", " + rtosfix(ptr[i].y)); } - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::POOL_VECTOR3_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolVector3Array( "); + p_store_string_func(p_store_string_ud, "PoolVector3Array( "); PoolVector<Vector3> data = p_variant; int len = data.size(); PoolVector<Vector3>::Read r = data.read(); - const Vector3 *ptr=r.ptr(); + const Vector3 *ptr = r.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - p_store_string_func(p_store_string_ud,", "); - p_store_string_func(p_store_string_ud,rtosfix(ptr[i].x)+", "+rtosfix(ptr[i].y)+", "+rtosfix(ptr[i].z) ); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + p_store_string_func(p_store_string_ud, rtosfix(ptr[i].x) + ", " + rtosfix(ptr[i].y) + ", " + rtosfix(ptr[i].z)); } - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; case Variant::POOL_COLOR_ARRAY: { - p_store_string_func(p_store_string_ud,"PoolColorArray( "); + p_store_string_func(p_store_string_ud, "PoolColorArray( "); PoolVector<Color> data = p_variant; int len = data.size(); PoolVector<Color>::Read r = data.read(); - const Color *ptr=r.ptr(); + const Color *ptr = r.ptr(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - p_store_string_func(p_store_string_ud,", "); - - p_store_string_func(p_store_string_ud,rtosfix(ptr[i].r)+", "+rtosfix(ptr[i].g)+", "+rtosfix(ptr[i].b)+", "+rtosfix(ptr[i].a) ); + if (i > 0) + p_store_string_func(p_store_string_ud, ", "); + p_store_string_func(p_store_string_ud, rtosfix(ptr[i].r) + ", " + rtosfix(ptr[i].g) + ", " + rtosfix(ptr[i].b) + ", " + rtosfix(ptr[i].a)); } - p_store_string_func(p_store_string_ud," )"); + p_store_string_func(p_store_string_ud, " )"); } break; default: {} - } return OK; } -static Error _write_to_str(void *ud,const String& p_string) { +static Error _write_to_str(void *ud, const String &p_string) { - String *str=(String*)ud; - (*str)+=p_string; + String *str = (String *)ud; + (*str) += p_string; return OK; } -Error VariantWriter::write_to_string(const Variant& p_variant, String& r_string, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud) { - - r_string=String(); +Error VariantWriter::write_to_string(const Variant &p_variant, String &r_string, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud) { - return write(p_variant,_write_to_str,&r_string,p_encode_res_func,p_encode_res_ud); + r_string = String(); + return write(p_variant, _write_to_str, &r_string, p_encode_res_func, p_encode_res_ud); } diff --git a/core/variant_parser.h b/core/variant_parser.h index c69673b0e4..20cc72f20d 100644 --- a/core/variant_parser.h +++ b/core/variant_parser.h @@ -29,22 +29,21 @@ #ifndef VARIANT_PARSER_H #define VARIANT_PARSER_H -#include "variant.h" #include "os/file_access.h" #include "resource.h" +#include "variant.h" class VariantParser { public: - struct Stream { - virtual CharType get_char()=0; - virtual bool is_utf8() const=0; - virtual bool is_eof() const=0; + virtual CharType get_char() = 0; + virtual bool is_utf8() const = 0; + virtual bool is_eof() const = 0; CharType saved; - Stream() { saved=0; } + Stream() { saved = 0; } virtual ~Stream() {} }; @@ -56,8 +55,7 @@ public: virtual bool is_utf8() const; virtual bool is_eof() const; - StreamFile() { f=NULL; } - + StreamFile() { f = NULL; } }; struct StreamString : public Stream { @@ -69,11 +67,10 @@ public: virtual bool is_utf8() const; virtual bool is_eof() const; - StreamString() { pos=0; } - + StreamString() { pos = 0; } }; - typedef Error (*ParseResourceFunc)(void* p_self, Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str); + typedef Error (*ParseResourceFunc)(void *p_self, Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); struct ResourceParser { @@ -81,7 +78,6 @@ public: ParseResourceFunc func; ParseResourceFunc ext_func; ParseResourceFunc sub_func; - }; enum TokenType { @@ -121,47 +117,35 @@ public: struct Tag { String name; - Map<String,Variant> fields; + Map<String, Variant> fields; }; private: - static const char * tk_name[TK_MAX]; + static const char *tk_name[TK_MAX]; - template<class T> - static Error _parse_construct(Stream *p_stream, Vector<T>& r_construct, int &line, String &r_err_str); - static Error _parse_enginecfg(Stream *p_stream, Vector<String>& strings, int &line, String &r_err_str); - static Error _parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str,ResourceParser *p_res_parser=NULL); - static Error _parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str,ResourceParser *p_res_parser=NULL); - static Error _parse_tag(Token& token,Stream *p_stream, int &line, String &r_err_str,Tag& r_tag,ResourceParser *p_res_parser=NULL,bool p_simple_tag=false); + template <class T> + static Error _parse_construct(Stream *p_stream, Vector<T> &r_construct, int &line, String &r_err_str); + static Error _parse_enginecfg(Stream *p_stream, Vector<String> &strings, int &line, String &r_err_str); + static Error _parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser = NULL); + static Error _parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser = NULL); + static Error _parse_tag(Token &token, Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser = NULL, bool p_simple_tag = false); public: + static Error parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser = NULL, bool p_simple_tag = false); + static Error parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser = NULL, bool p_simple_tag = false); - static Error parse_tag(Stream *p_stream, int &line, String &r_err_str,Tag& r_tag,ResourceParser *p_res_parser=NULL,bool p_simple_tag=false); - static Error parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, String &r_assign, Variant &r_value,ResourceParser *p_res_parser=NULL,bool p_simple_tag=false); - - static Error parse_value(Token& token,Variant &value, Stream *p_stream, int &line, String &r_err_str,ResourceParser *p_res_parser=NULL); - static Error get_token(Stream *p_stream,Token& r_token,int &line,String &r_err_str); - static Error parse(Stream *p_stream, Variant &r_ret, String &r_err_str, int &r_err_line,ResourceParser *p_res_parser=NULL); + static Error parse_value(Token &token, Variant &value, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser = NULL); + static Error get_token(Stream *p_stream, Token &r_token, int &line, String &r_err_str); + static Error parse(Stream *p_stream, Variant &r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser = NULL); }; - - - class VariantWriter { public: + typedef Error (*StoreStringFunc)(void *ud, const String &p_string); + typedef String (*EncodeResourceFunc)(void *ud, const RES &p_resource); - typedef Error (*StoreStringFunc)(void *ud,const String& p_string); - typedef String (*EncodeResourceFunc)(void *ud,const RES& p_resource); - - static Error write(const Variant& p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud,EncodeResourceFunc p_encode_res_func,void* p_encode_res_ud); - static Error write_to_string(const Variant& p_variant, String& r_string, EncodeResourceFunc p_encode_res_func=NULL,void* p_encode_res_ud=NULL); - - + static Error write(const Variant &p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud); + static Error write_to_string(const Variant &p_variant, String &r_string, EncodeResourceFunc p_encode_res_func = NULL, void *p_encode_res_ud = NULL); }; - - - - - #endif // VARIANT_PARSER_H diff --git a/core/vector.h b/core/vector.h index 1cb3fee256..b7b6b92ed0 100644 --- a/core/vector.h +++ b/core/vector.h @@ -34,45 +34,43 @@ * @author Juan Linietsky * Vector container. Regular Vector Container. Use with care and for smaller arrays when possible. Use PoolVector for large arrays. */ -#include "os/memory.h" #include "error_macros.h" +#include "os/memory.h" #include "safe_refcount.h" #include "sort.h" -template<class T> +template <class T> class Vector { - mutable T* _ptr; + mutable T *_ptr; - // internal helpers + // internal helpers - _FORCE_INLINE_ uint32_t* _get_refcount() const { + _FORCE_INLINE_ uint32_t *_get_refcount() const { if (!_ptr) - return NULL; + return NULL; - return reinterpret_cast<uint32_t*>(_ptr)-2; - } + return reinterpret_cast<uint32_t *>(_ptr) - 2; + } - _FORCE_INLINE_ uint32_t* _get_size() const { + _FORCE_INLINE_ uint32_t *_get_size() const { if (!_ptr) return NULL; - return reinterpret_cast<uint32_t*>(_ptr)-1; - - } - _FORCE_INLINE_ T* _get_data() const { + return reinterpret_cast<uint32_t *>(_ptr) - 1; + } + _FORCE_INLINE_ T *_get_data() const { if (!_ptr) - return NULL; - return reinterpret_cast<T*>(_ptr); - - } + return NULL; + return reinterpret_cast<T *>(_ptr); + } _FORCE_INLINE_ size_t _get_alloc_size(size_t p_elements) const { //return nearest_power_of_2_templated(p_elements*sizeof(T)+sizeof(SafeRefCount)+sizeof(int)); - return nearest_power_of_2(p_elements*sizeof(T)); + return nearest_power_of_2(p_elements * sizeof(T)); } _FORCE_INLINE_ bool _get_alloc_size_checked(size_t p_elements, size_t *out) const { @@ -93,19 +91,24 @@ class Vector { void _unref(void *p_data); - void _copy_from(const Vector& p_from); + void _copy_from(const Vector &p_from); void _copy_on_write(); -public: - - - _FORCE_INLINE_ T *ptr() { if (!_ptr) return NULL; _copy_on_write(); return (T*)_get_data(); } - _FORCE_INLINE_ const T *ptr() const { if (!_ptr) return NULL; return _get_data(); } +public: + _FORCE_INLINE_ T *ptr() { + if (!_ptr) return NULL; + _copy_on_write(); + return (T *)_get_data(); + } + _FORCE_INLINE_ const T *ptr() const { + if (!_ptr) return NULL; + return _get_data(); + } _FORCE_INLINE_ void clear() { resize(0); } _FORCE_INLINE_ int size() const { - uint32_t* size = (uint32_t*)_get_size(); + uint32_t *size = (uint32_t *)_get_size(); if (size) return *size; else @@ -116,21 +119,23 @@ public: bool push_back(T p_elem); void remove(int p_index); - void erase(const T& p_val) { int idx = find(p_val); if (idx>=0) remove(idx); }; + void erase(const T &p_val) { + int idx = find(p_val); + if (idx >= 0) remove(idx); + }; void invert(); - template <class T_val> - int find(const T_val& p_val, int p_from=0) const; + int find(const T_val &p_val, int p_from = 0) const; - void set(int p_index,T p_elem); + void set(int p_index, T p_elem); T get(int p_index) const; - inline T& operator[](int p_index) { + inline 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); } _copy_on_write(); // wants to write, so copy on write. @@ -138,27 +143,27 @@ public: return _get_data()[p_index]; } - inline const T& operator[](int p_index) const { + inline const T &operator[](int p_index) const { - if (p_index<0 || p_index>=size()) { - const T& aux=*((T*)0); //nullreturn - ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux); + if (p_index < 0 || p_index >= size()) { + const T &aux = *((T *)0); //nullreturn + ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux); } // no cow needed, since it's reading return _get_data()[p_index]; } - Error insert(int p_pos,const T& p_val); + Error insert(int p_pos, const T &p_val); - template<class C> + template <class C> void sort_custom() { int len = size(); - if (len==0) + if (len == 0) return; T *data = &operator[](0); - SortArray<T,C> sorter; - sorter.sort(data,len); + SortArray<T, C> sorter; + sorter.sort(data, len); } void sort() { @@ -166,26 +171,25 @@ public: sort_custom<_DefaultComparator<T> >(); } - void ordered_insert(const T& p_val) { - int i; - for (i=0; i<size(); i++) { + void ordered_insert(const T &p_val) { + int i; + for (i = 0; i < size(); i++) { - if (p_val < operator[](i)) { - break; - }; + if (p_val < operator[](i)) { + break; }; - insert(i, p_val); + }; + insert(i, p_val); } - void operator=(const Vector& p_from); - Vector(const Vector& p_from); + void operator=(const Vector &p_from); + Vector(const Vector &p_from); _FORCE_INLINE_ Vector(); _FORCE_INLINE_ ~Vector(); - }; -template<class T> +template <class T> void Vector<T>::_unref(void *p_data) { if (!p_data) @@ -193,24 +197,23 @@ void Vector<T>::_unref(void *p_data) { uint32_t *refc = _get_refcount(); - if (atomic_decrement(refc)>0) + if (atomic_decrement(refc) > 0) return; // still in use // clean up uint32_t *count = _get_size(); - T *data = (T*)(count+1); + T *data = (T *)(count + 1); - for (uint32_t i=0;i<*count;i++) { + for (uint32_t i = 0; i < *count; i++) { // call destructors data[i].~T(); } // free mem - Memory::free_static((uint8_t*)p_data,true); - + Memory::free_static((uint8_t *)p_data, true); } -template<class T> +template <class T> void Vector<T>::_copy_on_write() { if (!_ptr) @@ -222,34 +225,33 @@ void Vector<T>::_copy_on_write() { /* in use by more than me */ uint32_t current_size = *_get_size(); - uint32_t* mem_new = (uint32_t*)Memory::alloc_static(_get_alloc_size(current_size),true); + uint32_t *mem_new = (uint32_t *)Memory::alloc_static(_get_alloc_size(current_size), true); + *(mem_new - 2) = 1; //refcount + *(mem_new - 1) = current_size; //size - *(mem_new-2)=1; //refcount - *(mem_new-1)=current_size; //size - - T*_data=(T*)(mem_new); + T *_data = (T *)(mem_new); // initialize new elements - for (uint32_t i=0;i<current_size;i++) { + for (uint32_t i = 0; i < current_size; i++) { - memnew_placement(&_data[i], T( _get_data()[i] ) ); + memnew_placement(&_data[i], T(_get_data()[i])); } _unref(_ptr); - _ptr=_data; + _ptr = _data; } - } -template<class T> template<class T_val> +template <class T> +template <class T_val> int Vector<T>::find(const T_val &p_val, int p_from) const { int ret = -1; if (p_from < 0 || size() == 0) return ret; - for (int i=p_from; i<size(); i++) { + for (int i = p_from; i < size(); i++) { if (operator[](i) == p_val) { ret = i; @@ -260,18 +262,18 @@ int Vector<T>::find(const T_val &p_val, int p_from) const { return ret; } -template<class T> +template <class T> Error Vector<T>::resize(int p_size) { - ERR_FAIL_COND_V(p_size<0,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER); - if (p_size==size()) + if (p_size == size()) return OK; - if (p_size==0) { + if (p_size == 0) { // wants to clean up _unref(_ptr); - _ptr=NULL; + _ptr = NULL; return OK; } @@ -281,159 +283,150 @@ Error Vector<T>::resize(int p_size) { size_t alloc_size; ERR_FAIL_COND_V(!_get_alloc_size_checked(p_size, &alloc_size), ERR_OUT_OF_MEMORY); - if (p_size>size()) { + if (p_size > size()) { - if (size()==0) { + if (size() == 0) { // alloc from scratch - uint32_t *ptr=(uint32_t*)Memory::alloc_static(alloc_size,true); - ERR_FAIL_COND_V( !ptr ,ERR_OUT_OF_MEMORY); - *(ptr-1)=0; //size, currently none - *(ptr-2)=1; //refcount + uint32_t *ptr = (uint32_t *)Memory::alloc_static(alloc_size, true); + ERR_FAIL_COND_V(!ptr, ERR_OUT_OF_MEMORY); + *(ptr - 1) = 0; //size, currently none + *(ptr - 2) = 1; //refcount - _ptr=(T*)ptr; + _ptr = (T *)ptr; } else { - void *_ptrnew = (T*)Memory::realloc_static(_ptr, alloc_size,true); - ERR_FAIL_COND_V( !_ptrnew ,ERR_OUT_OF_MEMORY); - _ptr=(T*)(_ptrnew); + void *_ptrnew = (T *)Memory::realloc_static(_ptr, alloc_size, true); + ERR_FAIL_COND_V(!_ptrnew, ERR_OUT_OF_MEMORY); + _ptr = (T *)(_ptrnew); } // construct the newly created elements - T*elems = _get_data(); + T *elems = _get_data(); - for (int i=*_get_size();i<p_size;i++) { + for (int i = *_get_size(); i < p_size; i++) { - memnew_placement(&elems[i], T) ; + memnew_placement(&elems[i], T); } - *_get_size()=p_size; + *_get_size() = p_size; - } else if (p_size<size()) { + } else if (p_size < size()) { // deinitialize no longer needed elements - for (uint32_t i=p_size;i<*_get_size();i++) { + for (uint32_t i = p_size; i < *_get_size(); i++) { - T* t = &_get_data()[i]; + T *t = &_get_data()[i]; t->~T(); } - void *_ptrnew = (T*)Memory::realloc_static(_ptr, alloc_size,true); - ERR_FAIL_COND_V( !_ptrnew ,ERR_OUT_OF_MEMORY); + void *_ptrnew = (T *)Memory::realloc_static(_ptr, alloc_size, true); + ERR_FAIL_COND_V(!_ptrnew, ERR_OUT_OF_MEMORY); - _ptr=(T*)(_ptrnew); - - *_get_size()=p_size; + _ptr = (T *)(_ptrnew); + *_get_size() = p_size; } return OK; } - -template<class T> +template <class T> void Vector<T>::invert() { - for(int i=0;i<size()/2;i++) { + for (int i = 0; i < size() / 2; i++) { - SWAP( operator[](i), operator[](size()-i-1) ); + SWAP(operator[](i), operator[](size() - i - 1)); } } -template<class T> -void Vector<T>::set(int p_index,T p_elem) { +template <class T> +void Vector<T>::set(int p_index, T p_elem) { - operator[](p_index)=p_elem; + operator[](p_index) = p_elem; } -template<class T> +template <class T> T Vector<T>::get(int p_index) const { return operator[](p_index); } -template<class T> +template <class T> bool Vector<T>::push_back(T p_elem) { - Error err = resize(size()+1); - ERR_FAIL_COND_V( err, true ) - set(size()-1,p_elem); + Error err = resize(size() + 1); + ERR_FAIL_COND_V(err, true) + set(size() - 1, p_elem); return false; } - -template<class T> +template <class T> void Vector<T>::remove(int p_index) { ERR_FAIL_INDEX(p_index, size()); - T*p=ptr(); - int len=size(); - for (int i=p_index; i<len-1; i++) { + T *p = ptr(); + int len = size(); + for (int i = p_index; i < len - 1; i++) { - p[i]=p[i+1]; + p[i] = p[i + 1]; }; - resize(len-1); + resize(len - 1); }; -template<class T> -void Vector<T>::_copy_from(const Vector& p_from) { +template <class T> +void Vector<T>::_copy_from(const Vector &p_from) { if (_ptr == p_from._ptr) return; // self assign, do nothing. _unref(_ptr); - _ptr=NULL; + _ptr = NULL; if (!p_from._ptr) return; //nothing to do - if (atomic_conditional_increment(p_from._get_refcount())>0) { // could reference - _ptr=p_from._ptr; + if (atomic_conditional_increment(p_from._get_refcount()) > 0) { // could reference + _ptr = p_from._ptr; } - } -template<class T> -void Vector<T>::operator=(const Vector& p_from) { +template <class T> +void Vector<T>::operator=(const Vector &p_from) { _copy_from(p_from); } +template <class T> +Error Vector<T>::insert(int p_pos, const T &p_val) { -template<class T> -Error Vector<T>::insert(int p_pos,const T& p_val) { - - ERR_FAIL_INDEX_V(p_pos,size()+1,ERR_INVALID_PARAMETER); - resize(size()+1); - for (int i=(size()-1);i>p_pos;i--) - set( i, get(i-1) ); - set( p_pos, p_val ); + ERR_FAIL_INDEX_V(p_pos, size() + 1, ERR_INVALID_PARAMETER); + resize(size() + 1); + for (int i = (size() - 1); i > p_pos; i--) + set(i, get(i - 1)); + set(p_pos, p_val); return OK; } -template<class T> -Vector<T>::Vector(const Vector& p_from) { - - _ptr=NULL; - _copy_from( p_from ); +template <class T> +Vector<T>::Vector(const Vector &p_from) { + _ptr = NULL; + _copy_from(p_from); } -template<class T> +template <class T> Vector<T>::Vector() { - _ptr=NULL; + _ptr = NULL; } - -template<class T> +template <class T> Vector<T>::~Vector() { _unref(_ptr); - } - #endif diff --git a/core/vmap.h b/core/vmap.h index 3708cbed5b..8446015568 100644 --- a/core/vmap.h +++ b/core/vmap.h @@ -32,7 +32,7 @@ #include "typedefs.h" #include "vector.h" -template<class T,class V> +template <class T, class V> class VMap { struct _Pair { @@ -42,64 +42,61 @@ class VMap { _FORCE_INLINE_ _Pair() {} - _FORCE_INLINE_ _Pair(const T& p_key, const V& p_value) { + _FORCE_INLINE_ _Pair(const T &p_key, const V &p_value) { - key=p_key; - value=p_value; + key = p_key; + value = p_value; } - }; Vector<_Pair> _data; - _FORCE_INLINE_ int _find(const T& p_val,bool &r_exact) const { + _FORCE_INLINE_ int _find(const T &p_val, bool &r_exact) const { - r_exact=false; + r_exact = false; if (_data.empty()) return 0; int low = 0; - int high = _data.size() -1; + int high = _data.size() - 1; int middle; - const _Pair *a=&_data[0]; + const _Pair *a = &_data[0]; - while( low <= high ) - { - middle = ( low + high ) / 2; + while (low <= high) { + middle = (low + high) / 2; - if( p_val < a[ middle].key ) { + if (p_val < a[middle].key) { high = middle - 1; //search low end of array - } else if ( a[middle].key < p_val) { + } else if (a[middle].key < p_val) { low = middle + 1; //search high end of array } else { - r_exact=true; + r_exact = true; return middle; } } //return the position where this would be inserted - if (a[middle].key<p_val) + if (a[middle].key < p_val) middle++; return middle; } - _FORCE_INLINE_ int _find_exact(const T& p_val) const { + _FORCE_INLINE_ int _find_exact(const T &p_val) const { if (_data.empty()) return -1; int low = 0; - int high = _data.size() -1; + int high = _data.size() - 1; int middle; - const _Pair *a=&_data[0]; + const _Pair *a = &_data[0]; - while( low <= high ) - { - middle = ( low + high ) / 2; + while (low <= high) { + middle = (low + high) / 2; - if( p_val < a[ middle].key ) { + if (p_val < a[middle].key) { high = middle - 1; //search low end of array - } else if ( a[middle].key < p_val) { + } else if (a[middle].key < p_val) { low = middle + 1; //search high end of array } else { return middle; @@ -110,49 +107,45 @@ class VMap { } public: - - int insert(const T& p_key,const V& p_val) { + int insert(const T &p_key, const V &p_val) { bool exact; - int pos = _find(p_key,exact); + int pos = _find(p_key, exact); if (exact) { - _data[pos].value=p_val; + _data[pos].value = p_val; return pos; } - _data.insert(pos,_Pair(p_key,p_val)); + _data.insert(pos, _Pair(p_key, p_val)); return pos; } - bool has(const T& p_val) const { + bool has(const T &p_val) const { - return _find_exact(p_val)!=-1; + return _find_exact(p_val) != -1; } - void erase(const T& p_val) { + void erase(const T &p_val) { int pos = _find_exact(p_val); - if (pos<0) + if (pos < 0) return; _data.remove(pos); } - int find(const T& p_val) const { + int find(const T &p_val) const { return _find_exact(p_val); - } - int find_nearest(const T& p_val) const { + int find_nearest(const T &p_val) const { bool exact; - return _find(p_val,exact); - + return _find(p_val, exact); } _FORCE_INLINE_ int size() const { return _data.size(); } _FORCE_INLINE_ bool empty() const { return _data.empty(); } - const _Pair *get_array() const { return _data.ptr(); @@ -163,55 +156,46 @@ public: return _data.ptr(); } - - const V& getv(int p_index) const { + const V &getv(int p_index) const { return _data[p_index].value; } - V& getv(int p_index) { + V &getv(int p_index) { return _data[p_index].value; } - - const T& getk(int p_index) const { + const T &getk(int p_index) const { return _data[p_index].key; } - T& getk(int p_index) { + T &getk(int p_index) { return _data[p_index].key; } - - inline const V& operator[](const T& p_key) const { + inline const V &operator[](const T &p_key) const { int pos = _find_exact(p_key); - if (pos<0) { - const T& aux=*((T*)0); //nullreturn - ERR_FAIL_COND_V(pos<1,aux); + if (pos < 0) { + const T &aux = *((T *)0); //nullreturn + ERR_FAIL_COND_V(pos < 1, aux); } return _data[pos].value; } - - - inline V& operator[](const T& p_key) { + inline V &operator[](const T &p_key) { int pos = _find_exact(p_key); - if (pos<0) { + if (pos < 0) { V val; - pos = insert(p_key,val); - + pos = insert(p_key, val); } return _data[pos].value; } - - - }; #endif // VMAP_H diff --git a/core/vset.h b/core/vset.h index e0b5181263..e7e204115f 100644 --- a/core/vset.h +++ b/core/vset.h @@ -32,60 +32,57 @@ #include "typedefs.h" #include "vector.h" -template<class T> +template <class T> class VSet { - Vector<T> _data; - _FORCE_INLINE_ int _find(const T& p_val,bool &r_exact) const { + _FORCE_INLINE_ int _find(const T &p_val, bool &r_exact) const { - r_exact=false; + r_exact = false; if (_data.empty()) return 0; int low = 0; - int high = _data.size() -1; + int high = _data.size() - 1; int middle; - const T *a=&_data[0]; + const T *a = &_data[0]; - while( low <= high ) - { - middle = ( low + high ) / 2; + while (low <= high) { + middle = (low + high) / 2; - if( p_val < a[ middle] ) { + if (p_val < a[middle]) { high = middle - 1; //search low end of array - } else if ( a[middle] < p_val) { + } else if (a[middle] < p_val) { low = middle + 1; //search high end of array } else { - r_exact=true; + r_exact = true; return middle; } } //return the position where this would be inserted - if (a[middle]<p_val) + if (a[middle] < p_val) middle++; return middle; } - _FORCE_INLINE_ int _find_exact(const T& p_val) const { + _FORCE_INLINE_ int _find_exact(const T &p_val) const { if (_data.empty()) return -1; int low = 0; - int high = _data.size() -1; + int high = _data.size() - 1; int middle; - const T *a=&_data[0]; + const T *a = &_data[0]; - while( low <= high ) - { - middle = ( low + high ) / 2; + while (low <= high) { + middle = (low + high) / 2; - if( p_val < a[ middle] ) { + if (p_val < a[middle]) { high = middle - 1; //search low end of array - } else if ( a[middle] < p_val) { + } else if (a[middle] < p_val) { low = middle + 1; //search high end of array } else { return middle; @@ -96,50 +93,46 @@ class VSet { } public: - - void insert(const T& p_val) { + void insert(const T &p_val) { bool exact; - int pos = _find(p_val,exact); + int pos = _find(p_val, exact); if (exact) return; - _data.insert(pos,p_val); + _data.insert(pos, p_val); } - bool has(const T& p_val) const { + bool has(const T &p_val) const { - return _find_exact(p_val)!=-1; + return _find_exact(p_val) != -1; } - void erase(const T& p_val) { + void erase(const T &p_val) { int pos = _find_exact(p_val); - if (pos<0) + if (pos < 0) return; _data.remove(pos); } - int find(const T& p_val) const { + int find(const T &p_val) const { return _find_exact(p_val); - } _FORCE_INLINE_ bool empty() const { return _data.empty(); } _FORCE_INLINE_ int size() const { return _data.size(); } - inline T& operator[](int p_index) { + inline T &operator[](int p_index) { return _data[p_index]; } - inline const T& operator[](int p_index) const { + inline const T &operator[](int p_index) const { return _data[p_index]; } - - }; #endif // VSET_H |