diff options
Diffstat (limited to 'modules')
108 files changed, 12619 insertions, 14621 deletions
diff --git a/modules/chibi/cp_config.h b/modules/chibi/cp_config.h index 35312b68b..59f15f8da 100644 --- a/modules/chibi/cp_config.h +++ b/modules/chibi/cp_config.h @@ -29,24 +29,23 @@ #ifndef CP_CONFIG_H #define CP_CONFIG_H - -#include "typedefs.h" #include "error_macros.h" #include "math_funcs.h" -#include "os/memory.h" #include "os/copymem.h" +#include "os/memory.h" +#include "typedefs.h" #define CP_PRINTERR(m_err) ERR_PRINT(m_err) #define CP_ERR_COND(m_cond) ERR_FAIL_COND(m_cond) -#define CP_ERR_COND_V(m_cond,m_ret) ERR_FAIL_COND_V(m_cond,m_ret) -#define CP_FAIL_INDEX(m_index,m_size) ERR_FAIL_INDEX(m_index,m_size) -#define CP_FAIL_INDEX_V(m_index,m_size,m_ret) ERR_FAIL_INDEX_V(m_index,m_size,m_ret) +#define CP_ERR_COND_V(m_cond, m_ret) ERR_FAIL_COND_V(m_cond, m_ret) +#define CP_FAIL_INDEX(m_index, m_size) ERR_FAIL_INDEX(m_index, m_size) +#define CP_FAIL_INDEX_V(m_index, m_size, m_ret) ERR_FAIL_INDEX_V(m_index, m_size, m_ret) #define cp_intabs(m_val) ABS(m_val) #define CP_ALLOC(m_mem) memalloc(m_mem) -#define CP_REALLOC(m_mem,m_size) memrealloc(m_mem,m_size) +#define CP_REALLOC(m_mem, m_size) memrealloc(m_mem, m_size) #define CP_FREE(m_mem) memfree(m_mem) -#define cp_memzero(m_mem,m_size) zeromem(m_mem,m_size) +#define cp_memzero(m_mem, m_size) zeromem(m_mem, m_size) #endif // CP_CONFIG_H diff --git a/modules/chibi/cp_envelope.cpp b/modules/chibi/cp_envelope.cpp index 36259e8d6..42920b4fb 100644 --- a/modules/chibi/cp_envelope.cpp +++ b/modules/chibi/cp_envelope.cpp @@ -28,58 +28,53 @@ /*************************************************************************/ #include "cp_envelope.h" - CPEnvelope::CPEnvelope() { - reset(); } void CPEnvelope::reset() { - - - on=false; - carry=false; - loop_on=false; - loop_begin_node=0; - loop_end_node=0; - sustain_loop_on=false; - sustain_loop_begin_node=0; - sustain_loop_end_node=0; - node_count=0; - + on = false; + carry = false; + loop_on = false; + loop_begin_node = 0; + loop_end_node = 0; + sustain_loop_on = false; + sustain_loop_begin_node = 0; + sustain_loop_end_node = 0; + node_count = 0; } int CPEnvelope::get_height_at_pos(int pos) { - if (node_count && pos>node[node_count-1].tick_offset) - return node[node_count-1].value; - - int begin_x,begin_y; - int end_x,end_y,xdif; - int count=0; - int limit=-1; + if (node_count && pos > node[node_count - 1].tick_offset) + return node[node_count - 1].value; - if (node_count<2) return NO_POINT; + int begin_x, begin_y; + int end_x, end_y, xdif; + int count = 0; + int limit = -1; - while ((count<node_count) && (limit==-1)) { + if (node_count < 2) return NO_POINT; - if (node[count].tick_offset>=pos) limit=count; + while ((count < node_count) && (limit == -1)) { + + if (node[count].tick_offset >= pos) limit = count; count++; } - if (pos==0) return node[0].value; + if (pos == 0) return node[0].value; - if (limit==-1) return NO_POINT; + if (limit == -1) return NO_POINT; - begin_x=node[limit-1].tick_offset; - end_x=node[limit].tick_offset; - begin_y=node[limit-1].value; - end_y=node[limit].value; + begin_x = node[limit - 1].tick_offset; + end_x = node[limit].tick_offset; + begin_y = node[limit - 1].value; + end_y = node[limit].value; - xdif=end_x-begin_x; - return begin_y+((pos-begin_x)*(end_y-begin_y))/(xdif?xdif:1); + xdif = end_x - begin_x; + return begin_y + ((pos - begin_x) * (end_y - begin_y)) / (xdif ? xdif : 1); } /* @@ -117,235 +112,194 @@ int CPEnvelope::get_fx_height_at_pos(int pos) { float CPEnvelope::get_interp_height_at_pos(float pos) { - if (node_count && pos>node[node_count-1].tick_offset) - return node[node_count-1].value; + if (node_count && pos > node[node_count - 1].tick_offset) + return node[node_count - 1].value; - int begin_x,begin_y; - int end_x,end_y,xdif; - int count=0; - int limit=-1; + int begin_x, begin_y; + int end_x, end_y, xdif; + int count = 0; + int limit = -1; - if (node_count<2) return NO_POINT; + if (node_count < 2) return NO_POINT; - while ((count<node_count) && (limit==-1)) { + while ((count < node_count) && (limit == -1)) { - if (node[count].tick_offset>=pos) limit=count; + if (node[count].tick_offset >= pos) limit = count; count++; } - if (pos==0) return node[0].value; + if (pos == 0) return node[0].value; - if (limit==-1) return NO_POINT; + if (limit == -1) return NO_POINT; - begin_x=node[limit-1].tick_offset; - end_x=node[limit].tick_offset; - begin_y=node[limit-1].value; - end_y=node[limit].value; + begin_x = node[limit - 1].tick_offset; + end_x = node[limit].tick_offset; + begin_y = node[limit - 1].value; + end_y = node[limit].value; - xdif=end_x-begin_x; - return begin_y+((pos-begin_x)*(end_y-begin_y))/(xdif?xdif:1); + xdif = end_x - begin_x; + return begin_y + ((pos - begin_x) * (end_y - begin_y)) / (xdif ? xdif : 1); } -void CPEnvelope::set_position(int p_node,int p_x,int p_y) { - - if (p_node>=node_count) return; - +void CPEnvelope::set_position(int p_node, int p_x, int p_y) { + if (p_node >= node_count) return; - if (p_node==0) { + if (p_node == 0) { - p_x=0; + p_x = 0; - } else if (p_x<=node[p_node-1].tick_offset) { + } else if (p_x <= node[p_node - 1].tick_offset) { - p_x=node[p_node-1].tick_offset+1; + p_x = node[p_node - 1].tick_offset + 1; - } else if ((p_node<(node_count-1)) && (p_x>=node[p_node+1].tick_offset)) { + } else if ((p_node < (node_count - 1)) && (p_x >= node[p_node + 1].tick_offset)) { - p_x=node[p_node+1].tick_offset-1; + p_x = node[p_node + 1].tick_offset - 1; } - if (p_x>=9999) p_x=9999; + if (p_x >= 9999) p_x = 9999; - if (p_y>max_value) p_y=max_value; - if (p_y<min_value) p_y=min_value; + if (p_y > max_value) p_y = max_value; + if (p_y < min_value) p_y = min_value; - - node[p_node].tick_offset=p_x; - node[p_node].value=p_y; - - - + node[p_node].tick_offset = p_x; + node[p_node].value = p_y; } -int CPEnvelope::add_position(int p_x,int p_y,bool p_move_loops) { +int CPEnvelope::add_position(int p_x, int p_y, bool p_move_loops) { - if (node_count==MAX_POINTS) return -1; + if (node_count == MAX_POINTS) return -1; - - int i,new_node; + int i, new_node; // if this is assigning an existing node, let's quit. - for (i=0;i<node_count;i++) if (p_x==node[i].tick_offset) return -1; + for (i = 0; i < node_count; i++) + if (p_x == node[i].tick_offset) return -1; + i = 0; + while ((i < node_count) && (p_x >= node[i].tick_offset)) + i++; - i=0; - while ((i<node_count) && (p_x>=node[i].tick_offset)) i++; - - new_node=i; + new_node = i; node_count++; if (p_move_loops) { - if (loop_begin_node>=new_node) loop_begin_node++; - if (loop_end_node>=new_node) loop_end_node++; - if (sustain_loop_begin_node>=new_node) sustain_loop_begin_node++; - if (sustain_loop_end_node>=new_node) sustain_loop_end_node++; + if (loop_begin_node >= new_node) loop_begin_node++; + if (loop_end_node >= new_node) loop_end_node++; + if (sustain_loop_begin_node >= new_node) sustain_loop_begin_node++; + if (sustain_loop_end_node >= new_node) sustain_loop_end_node++; } - for (i=node_count-1;i>new_node;i--) node[i]=node[i-1]; - + for (i = node_count - 1; i > new_node; i--) + node[i] = node[i - 1]; - - set_position(new_node,p_x,p_y); + set_position(new_node, p_x, p_y); - - return new_node; - } void CPEnvelope::set_loop_begin(int pos) { - if ((pos<0) || (pos>=node_count)) return; - - - - loop_begin_node=pos; - - if (loop_end_node<loop_begin_node) loop_end_node=loop_begin_node; - + if ((pos < 0) || (pos >= node_count)) return; + loop_begin_node = pos; + if (loop_end_node < loop_begin_node) loop_end_node = loop_begin_node; } void CPEnvelope::set_loop_end(int pos) { - if ((pos<0) || (pos>=node_count)) return; - - - - loop_end_node=pos; - - if (loop_end_node<loop_begin_node) loop_begin_node=loop_end_node; - + if ((pos < 0) || (pos >= node_count)) return; - + loop_end_node = pos; + if (loop_end_node < loop_begin_node) loop_begin_node = loop_end_node; } - void CPEnvelope::set_sustain_loop_begin(int pos) { - if ((pos<0) || (pos>=node_count)) return; - - - - sustain_loop_begin_node=pos; - - if (sustain_loop_end_node<sustain_loop_begin_node) sustain_loop_end_node=sustain_loop_begin_node; - + if ((pos < 0) || (pos >= node_count)) return; + sustain_loop_begin_node = pos; + if (sustain_loop_end_node < sustain_loop_begin_node) sustain_loop_end_node = sustain_loop_begin_node; } void CPEnvelope::set_sustain_loop_end(int pos) { - if ((pos<0) || (pos>=node_count)) return; - - - - sustain_loop_end_node=pos; - - if (sustain_loop_end_node<sustain_loop_begin_node) sustain_loop_begin_node=sustain_loop_end_node; - + if ((pos < 0) || (pos >= node_count)) return; + sustain_loop_end_node = pos; + if (sustain_loop_end_node < sustain_loop_begin_node) sustain_loop_begin_node = sustain_loop_end_node; } void CPEnvelope::set_loop_enabled(bool p_enabled) { - - loop_on=p_enabled; + + loop_on = p_enabled; } bool CPEnvelope::is_loop_enabled() { - + return loop_on; } - void CPEnvelope::set_sustain_loop_enabled(bool p_enabled) { - - sustain_loop_on=p_enabled; + + sustain_loop_on = p_enabled; } bool CPEnvelope::is_sustain_loop_enabled() { - + return sustain_loop_on; } void CPEnvelope::del_position(int p_node) { - if ((node_count<3) || (p_node<=0) || (p_node>=node_count)) return; + if ((node_count < 3) || (p_node <= 0) || (p_node >= node_count)) return; - - int i; - if (loop_begin_node>=p_node) loop_begin_node--; - if (loop_end_node>=p_node) loop_end_node--; - if (sustain_loop_begin_node>=p_node) sustain_loop_begin_node--; - if (sustain_loop_end_node>=p_node) sustain_loop_end_node--; + if (loop_begin_node >= p_node) loop_begin_node--; + if (loop_end_node >= p_node) loop_end_node--; + if (sustain_loop_begin_node >= p_node) sustain_loop_begin_node--; + if (sustain_loop_end_node >= p_node) sustain_loop_end_node--; - for (i=p_node;i<node_count-1;i++) node[i]=node[i+1]; + for (i = p_node; i < node_count - 1; i++) + node[i] = node[i + 1]; node_count--; - - - } uint8_t CPEnvelope::get_loop_begin() { - - + return loop_begin_node; } uint8_t CPEnvelope::get_loop_end() { - - return loop_end_node; + + return loop_end_node; } uint8_t CPEnvelope::get_sustain_loop_begin() { - - + return sustain_loop_begin_node; } uint8_t CPEnvelope::get_sustain_loop_end() { - - return sustain_loop_end_node; -} - + return sustain_loop_end_node; +} void CPEnvelope::set_enabled(bool p_enabled) { - - on=p_enabled; + + on = p_enabled; } bool CPEnvelope::is_enabled() { - - return on; + + return on; } void CPEnvelope::set_carry_enabled(bool p_enabled) { - - carry=p_enabled; + + carry = p_enabled; } bool CPEnvelope::is_carry_enabled() { @@ -353,17 +307,14 @@ bool CPEnvelope::is_carry_enabled() { } uint8_t CPEnvelope::get_node_count() { - - return node_count; -} -const CPEnvelope::Point& CPEnvelope::get_node(int p_idx) { - - if (p_idx<0 || p_idx>=node_count) - return node[node_count-1]; - - return node[p_idx]; - + return node_count; } +const CPEnvelope::Point &CPEnvelope::get_node(int p_idx) { + if (p_idx < 0 || p_idx >= node_count) + return node[node_count - 1]; + + return node[p_idx]; +} diff --git a/modules/chibi/cp_envelope.h b/modules/chibi/cp_envelope.h index af27f5f18..087455bb9 100644 --- a/modules/chibi/cp_envelope.h +++ b/modules/chibi/cp_envelope.h @@ -45,21 +45,20 @@ for it that can be used for both player and interface ********************************/ - class CPEnvelope { enum { - MAX_POINTS=25 + MAX_POINTS = 25 }; struct Point { - + uint16_t tick_offset; int16_t value; }; Point node[MAX_POINTS]; - + int8_t node_count; bool on; @@ -74,27 +73,25 @@ class CPEnvelope { uint8_t sustain_loop_begin_node; uint8_t sustain_loop_end_node; - int8_t max_value; int8_t min_value; - public: enum { - - NO_POINT=-5000, + + NO_POINT = -5000, }; - - void set_max(int8_t p_max) { max_value=p_max; } + + void set_max(int8_t p_max) { max_value = p_max; } int8_t get_max() { return max_value; } - void set_min(int8_t p_min) { min_value=p_min; } + void set_min(int8_t p_min) { min_value = p_min; } int8_t get_min() { return min_value; } uint8_t get_node_count(); - const Point& get_node(int p_idx); + const Point &get_node(int p_idx); - void set_position(int p_node,int p_x,int p_y); - int add_position(int p_x,int p_y,bool p_move_loops=true); + void set_position(int p_node, int p_x, int p_y); + int add_position(int p_x, int p_y, bool p_move_loops = true); void del_position(int p_node); void set_loop_enabled(bool p_enabled); @@ -110,20 +107,18 @@ public: void set_sustain_loop_end(int pos); uint8_t get_sustain_loop_begin(); uint8_t get_sustain_loop_end(); - + void set_enabled(bool p_enabled); bool is_enabled(); - + void set_carry_enabled(bool p_enabled); bool is_carry_enabled(); - + void reset(); int get_height_at_pos(int pos); float get_interp_height_at_pos(float pos); - - + CPEnvelope(); - }; #endif diff --git a/modules/chibi/cp_file_access_wrapper.h b/modules/chibi/cp_file_access_wrapper.h index ade077c1e..4cf087502 100644 --- a/modules/chibi/cp_file_access_wrapper.h +++ b/modules/chibi/cp_file_access_wrapper.h @@ -33,14 +33,13 @@ class CPFileAccessWrapper { public: + enum ModeFlags { - enum ModeFlags { - - READ=1, - WRITE=2, - READ_WRITE=3, + READ = 1, + WRITE = 2, + READ_WRITE = 3, }; - + enum Error { OK, @@ -55,42 +54,37 @@ public: ERROR_WRITING_FILE }; - virtual Error open(const char *p_filename, int p_mode_flags)=0; - virtual void close()=0; - - virtual void seek(uint32_t p_position)=0; - virtual void seek_end()=0; - virtual uint32_t get_pos()=0; + virtual Error open(const char *p_filename, int p_mode_flags) = 0; + virtual void close() = 0; - virtual bool eof_reached()=0; + virtual void seek(uint32_t p_position) = 0; + virtual void seek_end() = 0; + virtual uint32_t get_pos() = 0; - virtual uint8_t get_byte()=0; - virtual void get_byte_array(uint8_t *p_dest,int p_elements)=0; - virtual void get_word_array(uint16_t *p_dest,int p_elements)=0; + virtual bool eof_reached() = 0; - virtual uint16_t get_word()=0; - virtual uint32_t get_dword()=0; + virtual uint8_t get_byte() = 0; + virtual void get_byte_array(uint8_t *p_dest, int p_elements) = 0; + virtual void get_word_array(uint16_t *p_dest, int p_elements) = 0; + + virtual uint16_t get_word() = 0; + virtual uint32_t get_dword() = 0; // 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_conversion(bool p_swap)=0; - virtual bool is_open()=0; - - virtual Error get_error()=0; + virtual void set_endian_conversion(bool p_swap) = 0; + virtual bool is_open() = 0; - virtual void store_byte(uint8_t p_dest)=0; - virtual void store_byte_array(const uint8_t *p_dest,int p_elements)=0; + virtual Error get_error() = 0; - virtual void store_word(uint16_t p_dest)=0; - virtual void store_dword(uint32_t p_dest)=0; + virtual void store_byte(uint8_t p_dest) = 0; + virtual void store_byte_array(const uint8_t *p_dest, int p_elements) = 0; + virtual void store_word(uint16_t p_dest) = 0; + virtual void store_dword(uint32_t p_dest) = 0; - - virtual ~CPFileAccessWrapper(){} - + virtual ~CPFileAccessWrapper() {} }; - - #endif diff --git a/modules/chibi/cp_instrument.cpp b/modules/chibi/cp_instrument.cpp index 606a4217e..187a1ab7f 100644 --- a/modules/chibi/cp_instrument.cpp +++ b/modules/chibi/cp_instrument.cpp @@ -27,308 +27,285 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "cp_instrument.h" -#include "cp_song.h" #include "cp_note.h" - - +#include "cp_song.h" const char *CPInstrument::get_name() { return name; - } void CPInstrument::set_name(const char *p_name) { - - - if (p_name==NULL) { - name[0]=0; + + if (p_name == NULL) { + name[0] = 0; return; } - - - bool done=false; - for (int i=0;i<MAX_NAME_LEN;i++) { - - - name[i]=done?0:p_name[i]; - if (!done && p_name[i]==0) - done=true; + + bool done = false; + for (int i = 0; i < MAX_NAME_LEN; i++) { + + name[i] = done ? 0 : p_name[i]; + if (!done && p_name[i] == 0) + done = true; } - - name[MAX_NAME_LEN-1]=0; /* just in case */ - - + + name[MAX_NAME_LEN - 1] = 0; /* just in case */ } -void CPInstrument::set_sample_number(uint8_t p_note,uint8_t p_sample_id) { - - CP_ERR_COND(p_note>=CPNote::NOTES); - CP_ERR_COND(p_sample_id>CPSong::MAX_SAMPLES && p_sample_id!=CPNote::EMPTY); - data.sample_number[p_note]=p_sample_id; - - +void CPInstrument::set_sample_number(uint8_t p_note, uint8_t p_sample_id) { + + CP_ERR_COND(p_note >= CPNote::NOTES); + CP_ERR_COND(p_sample_id > CPSong::MAX_SAMPLES && p_sample_id != CPNote::EMPTY); + data.sample_number[p_note] = p_sample_id; } uint8_t CPInstrument::get_sample_number(uint8_t p_note) { - - CP_ERR_COND_V(p_note>=CPNote::NOTES,0); + + CP_ERR_COND_V(p_note >= CPNote::NOTES, 0); return data.sample_number[p_note]; } -void CPInstrument::set_note_number(uint8_t p_note,uint8_t p_note_id) { - - CP_ERR_COND(p_note>=CPNote::NOTES); - CP_ERR_COND(p_note_id>=CPNote::NOTES && p_note_id!=CPNote::EMPTY); - data.note_number[p_note]=p_note_id; - +void CPInstrument::set_note_number(uint8_t p_note, uint8_t p_note_id) { + + CP_ERR_COND(p_note >= CPNote::NOTES); + CP_ERR_COND(p_note_id >= CPNote::NOTES && p_note_id != CPNote::EMPTY); + data.note_number[p_note] = p_note_id; } uint8_t CPInstrument::get_note_number(uint8_t p_note) { - - CP_ERR_COND_V(p_note>=CPNote::NOTES,0); + + CP_ERR_COND_V(p_note >= CPNote::NOTES, 0); return data.note_number[p_note]; - } void CPInstrument::set_NNA_type(NNA_Type p_NNA_type) { - - data.NNA_type=p_NNA_type; + + data.NNA_type = p_NNA_type; } CPInstrument::NNA_Type CPInstrument::get_NNA_type() { - + return data.NNA_type; } void CPInstrument::set_DC_type(DC_Type p_DC_type) { - - data.DC_type=p_DC_type; + + data.DC_type = p_DC_type; } CPInstrument::DC_Type CPInstrument::get_DC_type() { - + return data.DC_type; - } - + void CPInstrument::set_DC_action(DC_Action p_DC_action) { - - data.DC_action=p_DC_action; + + data.DC_action = p_DC_action; } CPInstrument::DC_Action CPInstrument::get_DC_action() { - + return data.DC_action; } -/* Volume */ +/* Volume */ void CPInstrument::set_volume_global_amount(uint8_t p_amount) { - - CP_ERR_COND(p_amount>MAX_VOLUME); - data.volume.global_amount=p_amount; - + + CP_ERR_COND(p_amount > MAX_VOLUME); + data.volume.global_amount = p_amount; } uint8_t CPInstrument::get_volume_global_amount() { - + return data.volume.global_amount; } void CPInstrument::set_volume_fadeout(uint16_t p_amount) { - CP_ERR_COND(p_amount>MAX_FADEOUT); - data.volume.fadeout=p_amount; + CP_ERR_COND(p_amount > MAX_FADEOUT); + data.volume.fadeout = p_amount; } uint16_t CPInstrument::get_volume_fadeout() { - + return data.volume.fadeout; } void CPInstrument::set_volume_random_variation(uint8_t p_amount) { - - CP_ERR_COND(p_amount>MAX_VOLUME_RANDOM); - data.volume.random_variation=p_amount; + + CP_ERR_COND(p_amount > MAX_VOLUME_RANDOM); + data.volume.random_variation = p_amount; } uint8_t CPInstrument::get_volume_random_variation() { - + return data.volume.random_variation; } - + /* Panning */ void CPInstrument::set_pan_default_amount(uint8_t p_amount) { - - CP_ERR_COND(p_amount>MAX_PAN); - data.pan.default_amount=p_amount; + + CP_ERR_COND(p_amount > MAX_PAN); + data.pan.default_amount = p_amount; } uint8_t CPInstrument::get_pan_default_amount() { - + return data.pan.default_amount; } void CPInstrument::set_pan_default_enabled(bool p_enabled) { - - data.pan.use_default=p_enabled; + + data.pan.use_default = p_enabled; } bool CPInstrument::is_pan_default_enabled() { - + return data.pan.use_default; - } void CPInstrument::set_pan_pitch_separation(int8_t p_amount) { - - CP_ERR_COND(p_amount<-32); - CP_ERR_COND(p_amount>32); - data.pan.pitch_separation=p_amount; + + CP_ERR_COND(p_amount < -32); + CP_ERR_COND(p_amount > 32); + data.pan.pitch_separation = p_amount; } int8_t CPInstrument::get_pan_pitch_separation() { - + return data.pan.pitch_separation; } void CPInstrument::set_pan_pitch_center(uint8_t p_amount) { - - CP_ERR_COND(p_amount>=CPNote::NOTES); - data.pan.pitch_center=p_amount; + + CP_ERR_COND(p_amount >= CPNote::NOTES); + data.pan.pitch_center = p_amount; } uint8_t CPInstrument::get_pan_pitch_center() { - + return data.pan.pitch_center; } void CPInstrument::set_pan_random_variation(uint8_t p_amount) { - - CP_ERR_COND(p_amount>MAX_PAN_RANDOM); - data.pan.random_variation=p_amount; + + CP_ERR_COND(p_amount > MAX_PAN_RANDOM); + data.pan.random_variation = p_amount; } uint8_t CPInstrument::get_pan_random_variation() { - + return data.pan.random_variation; } /* Pitch / Filter */ void CPInstrument::set_pitch_use_as_filter(bool p_enabled) { - - data.pitch.use_as_filter=p_enabled; + + data.pitch.use_as_filter = p_enabled; } bool CPInstrument::is_pitch_use_as_filter() { - + return data.pitch.use_as_filter; } void CPInstrument::set_filter_use_default_cutoff(bool p_enabled) { - - data.pitch.use_default_cutoff=p_enabled; + data.pitch.use_default_cutoff = p_enabled; } bool CPInstrument::filter_use_default_cutoff() { - + return data.pitch.use_default_cutoff; } void CPInstrument::set_filter_default_cutoff(uint8_t p_amount) { - - CP_ERR_COND(p_amount>MAX_FILTER_CUTOFF); - data.pitch.default_cutoff=p_amount; + + CP_ERR_COND(p_amount > MAX_FILTER_CUTOFF); + data.pitch.default_cutoff = p_amount; } uint8_t CPInstrument::get_filter_default_cutoff() { - + return data.pitch.default_cutoff; } void CPInstrument::set_filter_use_default_resonance(bool p_enabled) { - - data.pitch.use_default_resonance=p_enabled; + + data.pitch.use_default_resonance = p_enabled; } bool CPInstrument::filter_use_default_resonance() { - + return data.pitch.use_default_resonance; } void CPInstrument::set_filter_default_resonance(uint8_t p_amount) { - - CP_ERR_COND(p_amount>MAX_FILTER_RESONANCE); - data.pitch.default_resonance=p_amount; - + + CP_ERR_COND(p_amount > MAX_FILTER_RESONANCE); + data.pitch.default_resonance = p_amount; } uint8_t CPInstrument::get_filter_default_resonance() { - + return data.pitch.default_resonance; } /* Envelopes */ +CPEnvelope *CPInstrument::get_volume_envelope() { -CPEnvelope* CPInstrument::get_volume_envelope() { - return &data.volume.envelope; } -CPEnvelope* CPInstrument::get_pan_envelope() { - - return &data.pan.envelope; -} -CPEnvelope* CPInstrument::get_pitch_filter_envelope() { - - return &data.pitch.envelope; - - +CPEnvelope *CPInstrument::get_pan_envelope() { + + return &data.pan.envelope; } +CPEnvelope *CPInstrument::get_pitch_filter_envelope() { + return &data.pitch.envelope; +} void CPInstrument::reset() { - - name[0]=0; - - data.NNA_type=NNA_NOTE_CUT; - data.DC_action=DCA_NOTE_CUT; - data.DC_type=DCT_DISABLED; - - for (int i=0;i<CPNote::NOTES;i++) { - - data.sample_number[i]=CPNote::EMPTY; - data.note_number[i]=i; + + name[0] = 0; + + data.NNA_type = NNA_NOTE_CUT; + data.DC_action = DCA_NOTE_CUT; + data.DC_type = DCT_DISABLED; + + for (int i = 0; i < CPNote::NOTES; i++) { + + data.sample_number[i] = CPNote::EMPTY; + data.note_number[i] = i; } - + data.volume.envelope.reset(); data.volume.envelope.set_max(64); data.volume.envelope.set_min(0); - data.volume.envelope.add_position(0,64,false); - data.volume.envelope.add_position(30,64,false); - - data.volume.global_amount=MAX_VOLUME; - data.volume.fadeout=0; - data.volume.random_variation=0; - + data.volume.envelope.add_position(0, 64, false); + data.volume.envelope.add_position(30, 64, false); + + data.volume.global_amount = MAX_VOLUME; + data.volume.fadeout = 0; + data.volume.random_variation = 0; + data.pan.envelope.reset(); data.pan.envelope.set_max(32); data.pan.envelope.set_min(-32); - data.pan.envelope.add_position(0,0,false); - data.pan.envelope.add_position(30,0,false); - - data.pan.default_amount=32; - data.pan.pitch_center=48; - data.pan.pitch_separation=0; - data.pan.use_default=false; - data.pan.random_variation=0; - - + data.pan.envelope.add_position(0, 0, false); + data.pan.envelope.add_position(30, 0, false); + + data.pan.default_amount = 32; + data.pan.pitch_center = 48; + data.pan.pitch_separation = 0; + data.pan.use_default = false; + data.pan.random_variation = 0; + data.pitch.envelope.reset(); data.pitch.envelope.set_max(32); data.pitch.envelope.set_min(-32); - data.pitch.envelope.add_position(0,0,false); - data.pitch.envelope.add_position(30,0,false); - data.pitch.use_as_filter=false; - data.pitch.use_default_cutoff=false; - data.pitch.use_default_resonance=false; - data.pitch.default_cutoff=0; - data.pitch.default_resonance=0; - + data.pitch.envelope.add_position(0, 0, false); + data.pitch.envelope.add_position(30, 0, false); + data.pitch.use_as_filter = false; + data.pitch.use_default_cutoff = false; + data.pitch.use_default_resonance = false; + data.pitch.default_cutoff = 0; + data.pitch.default_resonance = 0; } bool CPInstrument::is_empty() { - - bool has_sample=false; - - for (int i=0;i<CPNote::NOTES;i++) { - - if (data.sample_number[i]!=CPNote::EMPTY) { - - has_sample=true; + + bool has_sample = false; + + for (int i = 0; i < CPNote::NOTES; i++) { + + if (data.sample_number[i] != CPNote::EMPTY) { + + has_sample = true; break; } } @@ -337,8 +314,6 @@ bool CPInstrument::is_empty() { } CPInstrument::CPInstrument() { - + reset(); - } - diff --git a/modules/chibi/cp_instrument.h b/modules/chibi/cp_instrument.h index e51612a38..47b3de33d 100644 --- a/modules/chibi/cp_instrument.h +++ b/modules/chibi/cp_instrument.h @@ -29,15 +29,12 @@ #ifndef CP_INSTRUMENT_H #define CP_INSTRUMENT_H - #include "cp_config.h" -#include "cp_note.h" #include "cp_envelope.h" +#include "cp_note.h" class CPInstrument { public: - - enum NNA_Type { NNA_NOTE_CUT, @@ -54,8 +51,7 @@ public: DCT_INSTRUMENT }; - enum DC_Action - { + enum DC_Action { DCA_NOTE_CUT, DCA_NOTE_OFF, @@ -63,30 +59,27 @@ public: }; enum EnvelopeType { - VOLUME_ENVELOPE, + VOLUME_ENVELOPE, PAN_ENVELOPE, PITCH_ENVELOPE }; - enum { - MAX_NAME_LEN=26, - MAX_ENVELOPE_NODES=25, - ENVELOPE_FRAC_BITS=8, - MAX_VOLUME=128, - MAX_FADEOUT=256, - MAX_PAN=128, - MAX_VOLUME_RANDOM=100, - MAX_PAN_RANDOM=64, //what did this guy have inside his head? - - MAX_FILTER_CUTOFF=127, - MAX_FILTER_RESONANCE=127 - - }; + MAX_NAME_LEN = 26, + MAX_ENVELOPE_NODES = 25, + ENVELOPE_FRAC_BITS = 8, + MAX_VOLUME = 128, + MAX_FADEOUT = 256, + MAX_PAN = 128, + MAX_VOLUME_RANDOM = 100, + MAX_PAN_RANDOM = 64, //what did this guy have inside his head? + MAX_FILTER_CUTOFF = 127, + MAX_FILTER_RESONANCE = 127 - struct Data { + }; + struct Data { uint8_t sample_number[CPNote::NOTES]; uint8_t note_number[CPNote::NOTES]; @@ -124,27 +117,22 @@ public: bool use_default_resonance; uint8_t default_resonance; } pitch; - }; - -private: - - +private: Data data; char name[MAX_NAME_LEN]; - -public: +public: /* CPInstrument General */ - + const char *get_name(); void set_name(const char *p_name); - - void set_sample_number(uint8_t p_note,uint8_t p_sample_id); + + void set_sample_number(uint8_t p_note, uint8_t p_sample_id); uint8_t get_sample_number(uint8_t p_note); - - void set_note_number(uint8_t p_note,uint8_t p_note_id); + + void set_note_number(uint8_t p_note, uint8_t p_note_id); uint8_t get_note_number(uint8_t p_note); void set_NNA_type(NNA_Type p_NNA_type); @@ -152,11 +140,11 @@ public: void set_DC_type(DC_Type p_DC_type); DC_Type get_DC_type(); - + void set_DC_action(DC_Action p_DC_action); DC_Action get_DC_action(); - /* Volume */ + /* Volume */ void set_volume_global_amount(uint8_t p_amount); uint8_t get_volume_global_amount(); @@ -166,7 +154,7 @@ public: void set_volume_random_variation(uint8_t p_amount); uint8_t get_volume_random_variation(); - + /* Panning */ void set_pan_default_amount(uint8_t p_amount); @@ -174,10 +162,10 @@ public: void set_pan_default_enabled(bool p_enabled); bool is_pan_default_enabled(); - + void set_pan_pitch_separation(int8_t p_amount); int8_t get_pan_pitch_separation(); - + void set_pan_pitch_center(uint8_t p_amount); uint8_t get_pan_pitch_center(); @@ -188,32 +176,27 @@ public: void set_pitch_use_as_filter(bool p_enabled); bool is_pitch_use_as_filter(); - + void set_filter_use_default_cutoff(bool p_enabled); bool filter_use_default_cutoff(); void set_filter_default_cutoff(uint8_t p_amount); uint8_t get_filter_default_cutoff(); - + void set_filter_use_default_resonance(bool p_enabled); bool filter_use_default_resonance(); void set_filter_default_resonance(uint8_t p_amount); uint8_t get_filter_default_resonance(); - CPEnvelope* get_volume_envelope(); - CPEnvelope* get_pan_envelope(); - CPEnvelope* get_pitch_filter_envelope(); - + CPEnvelope *get_volume_envelope(); + CPEnvelope *get_pan_envelope(); + CPEnvelope *get_pitch_filter_envelope(); + bool is_empty(); - + void reset(); CPInstrument(); - }; - - #endif - - diff --git a/modules/chibi/cp_loader.h b/modules/chibi/cp_loader.h index 163044448..151d66a27 100644 --- a/modules/chibi/cp_loader.h +++ b/modules/chibi/cp_loader.h @@ -29,16 +29,14 @@ #ifndef CP_LOADER_H #define CP_LOADER_H - -#include "cp_song.h" #include "cp_file_access_wrapper.h" +#include "cp_song.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class CPLoader { public: - enum Error { FILE_OK, FILE_UNRECOGNIZED, @@ -46,19 +44,16 @@ public: FILE_CORRUPTED, FILE_OUT_OF_MEMORY, }; - - - virtual bool can_load_song()=0; - virtual bool can_load_sample()=0; - virtual bool can_load_instrument()=0; - - virtual Error load_song(const char *p_file,CPSong *p_song,bool p_sampleset)=0; - virtual Error load_sample(const char *p_file,CPSample *p_sample)=0; - virtual Error load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx)=0; - - - virtual ~CPLoader() {} + virtual bool can_load_song() = 0; + virtual bool can_load_sample() = 0; + virtual bool can_load_instrument() = 0; + + virtual Error load_song(const char *p_file, CPSong *p_song, bool p_sampleset) = 0; + virtual Error load_sample(const char *p_file, CPSample *p_sample) = 0; + virtual Error load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx) = 0; + + virtual ~CPLoader() {} }; #endif diff --git a/modules/chibi/cp_loader_it.cpp b/modules/chibi/cp_loader_it.cpp index bfffd9b50..15d2e7f60 100644 --- a/modules/chibi/cp_loader_it.cpp +++ b/modules/chibi/cp_loader_it.cpp @@ -28,50 +28,52 @@ /*************************************************************************/ #include "cp_loader_it.h" -bool CPLoader_IT::can_load_song() { return true; } -bool CPLoader_IT::can_load_sample() { return true; } -bool CPLoader_IT::can_load_instrument() { return true; } +bool CPLoader_IT::can_load_song() { + return true; +} +bool CPLoader_IT::can_load_sample() { + return true; +} +bool CPLoader_IT::can_load_instrument() { + return true; +} -CPLoader::Error CPLoader_IT::load_song(const char *p_file,CPSong *p_song, bool p_sampleset) { - - - song=p_song; +CPLoader::Error CPLoader_IT::load_song(const char *p_file, CPSong *p_song, bool p_sampleset) { - if (file->open( p_file, CPFileAccessWrapper::READ )!=CPFileAccessWrapper::OK) + song = p_song; + + if (file->open(p_file, CPFileAccessWrapper::READ) != CPFileAccessWrapper::OK) return CPLoader::FILE_CANNOT_OPEN; - - + Error err; - - char aux_identifier[4]; - file->get_byte_array((uint8_t*)aux_identifier,4); - if ( aux_identifier[0]!='I' || - aux_identifier[1]!='M' || - aux_identifier[2]!='P' || - aux_identifier[3]!='M') { + char aux_identifier[4]; + file->get_byte_array((uint8_t *)aux_identifier, 4); + if (aux_identifier[0] != 'I' || + aux_identifier[1] != 'M' || + aux_identifier[2] != 'P' || + aux_identifier[3] != 'M') { - CP_PRINTERR("IT CPLoader CPSong: Failed Identifier"); - return FILE_UNRECOGNIZED; + CP_PRINTERR("IT CPLoader CPSong: Failed Identifier"); + return FILE_UNRECOGNIZED; } - if (p_sampleset) { - song->reset(false,true,true,false); + song->reset(false, true, true, false); - if ((err=load_header(true))) { + if ((err = load_header(true))) { file->close(); return err; } - if ((err=load_samples())) { + if ((err = load_samples())) { file->close(); return err; } - if ((err=load_instruments())) { + if ((err = load_instruments())) { file->close(); return err; } @@ -81,136 +83,126 @@ CPLoader::Error CPLoader_IT::load_song(const char *p_file,CPSong *p_song, bool p song->reset(); - if ((err=load_header(false))) { + if ((err = load_header(false))) { file->close(); return err; } - - if ((err=load_orders())) { + + if ((err = load_orders())) { file->close(); return err; } - - if ((err=load_patterns())) { + + if ((err = load_patterns())) { file->close(); return err; } - - if ((err=load_samples())) { + + if ((err = load_samples())) { file->close(); return err; } - - if ((err=load_effects())) { + + if ((err = load_effects())) { file->close(); return err; } - if ((err=load_instruments())) { + if ((err = load_instruments())) { file->close(); return err; } - - if ((err=load_message())) { + + if ((err = load_message())) { file->close(); return err; } file->close(); return FILE_OK; - } +CPLoader::Error CPLoader_IT::load_sample(const char *p_file, CPSample *p_sample) { - - -CPLoader::Error CPLoader_IT::load_sample(const char *p_file,CPSample *p_sample) { - - if (file->open( p_file, CPFileAccessWrapper::READ )!=CPFileAccessWrapper::OK) + if (file->open(p_file, CPFileAccessWrapper::READ) != CPFileAccessWrapper::OK) return CPLoader::FILE_CANNOT_OPEN; - + p_sample->reset(); - CPLoader::Error res=load_sample(p_sample); - + CPLoader::Error res = load_sample(p_sample); + file->close(); - + return res; } -CPLoader::Error CPLoader_IT::load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx) { - - CP_FAIL_INDEX_V(p_instr_idx,CPSong::MAX_INSTRUMENTS,CPLoader::FILE_CANNOT_OPEN); - - if (file->open( p_file, CPFileAccessWrapper::READ )!=CPFileAccessWrapper::OK) +CPLoader::Error CPLoader_IT::load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx) { + + CP_FAIL_INDEX_V(p_instr_idx, CPSong::MAX_INSTRUMENTS, CPLoader::FILE_CANNOT_OPEN); + + if (file->open(p_file, CPFileAccessWrapper::READ) != CPFileAccessWrapper::OK) return CPLoader::FILE_CANNOT_OPEN; - - - p_song->get_instrument( p_instr_idx )->reset(); - - - int samples=0; - CPLoader::Error res=load_instrument( p_song->get_instrument( p_instr_idx ), &samples ); - + + p_song->get_instrument(p_instr_idx)->reset(); + + int samples = 0; + CPLoader::Error res = load_instrument(p_song->get_instrument(p_instr_idx), &samples); + if (res) { file->close(); return res; } - - + char exchange[CPSong::MAX_SAMPLES]; - for (int i=0;i<CPSong::MAX_SAMPLES;i++) - exchange[i]=0; - - for (int i=0;i<samples;i++) { - - file->seek( 554+i*80 ); //i think this should work?! seems to.. but i'm not sure - + for (int i = 0; i < CPSong::MAX_SAMPLES; i++) + exchange[i] = 0; + + for (int i = 0; i < samples; i++) { + + file->seek(554 + i * 80); //i think this should work?! seems to.. but i'm not sure + /* find free sample */ - - int free_idx=-1; - for (int s=0;s<CPSong::MAX_SAMPLES;s++) { - - if (p_song->get_sample( s )->get_sample_data().is_null()) { - free_idx=s; + + int free_idx = -1; + for (int s = 0; s < CPSong::MAX_SAMPLES; s++) { + + if (p_song->get_sample(s)->get_sample_data().is_null()) { + free_idx = s; break; } } - if (free_idx==-1) + if (free_idx == -1) break; //can't seem to be able to load more samples - - exchange[i]=free_idx; - res=load_sample( p_song->get_sample( free_idx ) ); - + + exchange[i] = free_idx; + res = load_sample(p_song->get_sample(free_idx)); + if (res) { - + file->close(); return res; } } - - for (int i=0;i<CPNote::NOTES;i++) { - - int smp=song->get_instrument(p_instr_idx)->get_sample_number(i); - - if (smp>=CPSong::MAX_SAMPLES) + + for (int i = 0; i < CPNote::NOTES; i++) { + + int smp = song->get_instrument(p_instr_idx)->get_sample_number(i); + + if (smp >= CPSong::MAX_SAMPLES) continue; - - if (smp<0) + + if (smp < 0) continue; - - smp=exchange[smp]; - - song->get_instrument(p_instr_idx)->set_sample_number(i,smp); - + + smp = exchange[smp]; + + song->get_instrument(p_instr_idx)->set_sample_number(i, smp); } - + file->close(); return res; - } CPLoader_IT::CPLoader_IT(CPFileAccessWrapper *p_file) { - file=p_file; - + file = p_file; } diff --git a/modules/chibi/cp_loader_it.h b/modules/chibi/cp_loader_it.h index 5ce62a6a4..20db7a672 100644 --- a/modules/chibi/cp_loader_it.h +++ b/modules/chibi/cp_loader_it.h @@ -47,31 +47,29 @@ midi. class AuxSampleData; //used for internal crap -class CPLoader_IT : public CPLoader { - - +class CPLoader_IT : public CPLoader { CPFileAccessWrapper *file; CPSong *song; struct IT_Header { - uint8_t blank01[2]; - uint16_t ordnum; - uint16_t insnum; - uint16_t smpnum; - uint16_t patnum; - uint16_t cwt; /* Created with tracker (y.xx = 0x0yxx) */ - uint16_t cmwt; /* Compatible with tracker ver > than val. */ - uint16_t flags; - uint16_t special; /* bit 0 set = song message attached */ - uint16_t msglength; - uint32_t msgoffset; + uint8_t blank01[2]; + uint16_t ordnum; + uint16_t insnum; + uint16_t smpnum; + uint16_t patnum; + uint16_t cwt; /* Created with tracker (y.xx = 0x0yxx) */ + uint16_t cmwt; /* Compatible with tracker ver > than val. */ + uint16_t flags; + uint16_t special; /* bit 0 set = song message attached */ + uint16_t msglength; + uint32_t msgoffset; bool is_chibi; - }; + }; /* Variables to store temp data */ IT_Header header; - + /* CPSong Info Methods */ Error load_header(bool p_dont_set); Error load_orders(); @@ -79,47 +77,41 @@ class CPLoader_IT : public CPLoader { /* CPPattern Methods */ Error load_patterns(); - + /* CPSample Methods */ - + Error load_samples(); Error load_sample(CPSample *p_sample); - CPSample_ID load_sample_data(AuxSampleData& p_sample_data); + CPSample_ID load_sample_data(AuxSampleData &p_sample_data); // CPSample decompression - + uint32_t read_n_bits_from_IT_compressed_block(uint8_t p_bits_to_read); - bool read_IT_compressed_block (bool p_16bits); - void free_IT_compressed_block (); - bool load_sample_8bits_IT_compressed(void *p_dest_buffer,int p_buffsize); - bool load_sample_16bits_IT_compressed(void *p_dest_buffer,int p_buffsize); - uint32_t *source_buffer; /* source buffer */ - uint32_t *source_position; /* actual reading position */ + bool read_IT_compressed_block(bool p_16bits); + void free_IT_compressed_block(); + bool load_sample_8bits_IT_compressed(void *p_dest_buffer, int p_buffsize); + bool load_sample_16bits_IT_compressed(void *p_dest_buffer, int p_buffsize); + uint32_t *source_buffer; /* source buffer */ + uint32_t *source_position; /* actual reading position */ uint8_t source_remaining_bits; /* bits remaining in read dword */ - uint8_t* pat_data; - - /* CPInstruments Methods */ + uint8_t *pat_data; + + /* CPInstruments Methods */ Error load_effects(); Error load_instruments(); - Error load_instrument(CPInstrument *p_instrument,int *p_samples=0); - void load_envelope(CPEnvelope *p_envelope,bool*p_has_filter_flag=0); - + Error load_instrument(CPInstrument *p_instrument, int *p_samples = 0); + void load_envelope(CPEnvelope *p_envelope, bool *p_has_filter_flag = 0); public: - - bool can_load_song(); bool can_load_sample(); bool can_load_instrument(); - - Error load_song(const char *p_file,CPSong *p_song, bool p_sampleset=false); - Error load_sample(const char *p_file,CPSample *p_sample); - Error load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx); + + Error load_song(const char *p_file, CPSong *p_song, bool p_sampleset = false); + Error load_sample(const char *p_file, CPSample *p_sample); + Error load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx); CPLoader_IT(CPFileAccessWrapper *p_file); - }; - - #endif diff --git a/modules/chibi/cp_loader_it_info.cpp b/modules/chibi/cp_loader_it_info.cpp index a474fcd2f..a98396df6 100644 --- a/modules/chibi/cp_loader_it_info.cpp +++ b/modules/chibi/cp_loader_it_info.cpp @@ -28,54 +28,50 @@ /*************************************************************************/ #include "cp_loader_it.h" - - CPLoader::Error CPLoader_IT::load_header(bool p_dont_set) { - - char aux_songname[26]; - - file->get_byte_array((uint8_t*)aux_songname,26); + char aux_songname[26]; + + file->get_byte_array((uint8_t *)aux_songname, 26); if (!p_dont_set) - song->set_name( aux_songname ); - - uint8_t aux_hlmin=file->get_byte(); - uint8_t aux_hlmaj=file->get_byte(); + song->set_name(aux_songname); + + uint8_t aux_hlmin = file->get_byte(); + uint8_t aux_hlmaj = file->get_byte(); - if (aux_hlmin==0) aux_hlmin=4; - if (aux_hlmaj==0) aux_hlmaj=16; + if (aux_hlmin == 0) aux_hlmin = 4; + if (aux_hlmaj == 0) aux_hlmaj = 16; if (!p_dont_set) { - song->set_row_highlight_minor( aux_hlmin ); - song->set_row_highlight_major( aux_hlmaj ); + song->set_row_highlight_minor(aux_hlmin); + song->set_row_highlight_major(aux_hlmaj); } - header.ordnum=file->get_word(); - header.insnum=file->get_word(); - header.smpnum=file->get_word(); - header.patnum=file->get_word(); - - header.cwt=file->get_word(); /* Created with tracker (y.xx = 0x0yxx) */ - header.cmwt=file->get_word(); /* Compatible with tracker ver > than val. */ - header.flags=file->get_word(); - + header.ordnum = file->get_word(); + header.insnum = file->get_word(); + header.smpnum = file->get_word(); + header.patnum = file->get_word(); + + header.cwt = file->get_word(); /* Created with tracker (y.xx = 0x0yxx) */ + header.cmwt = file->get_word(); /* Compatible with tracker ver > than val. */ + header.flags = file->get_word(); + if (!p_dont_set) { - song->set_stereo( header.flags & 1 ); - song->set_linear_slides( header.flags & 8 ); - song->set_old_effects( header.flags & 16 ); - song->set_compatible_gxx( header.flags & 32 ); - song->set_instruments( header.flags & 4 ); + song->set_stereo(header.flags & 1); + song->set_linear_slides(header.flags & 8); + song->set_old_effects(header.flags & 16); + song->set_compatible_gxx(header.flags & 32); + song->set_instruments(header.flags & 4); } - - - header.special=file->get_word(); + + header.special = file->get_word(); if (!p_dont_set) { - song->set_global_volume( file->get_byte() ); - song->set_mixing_volume( file->get_byte() ); - song->set_speed( file->get_byte() ); - song->set_tempo( file->get_byte() ); - song->set_stereo_separation( file->get_byte() ); + song->set_global_volume(file->get_byte()); + song->set_mixing_volume(file->get_byte()); + song->set_speed(file->get_byte()); + song->set_tempo(file->get_byte()); + song->set_stereo_separation(file->get_byte()); } else { @@ -86,127 +82,122 @@ CPLoader::Error CPLoader_IT::load_header(bool p_dont_set) { file->get_byte(); // skip } file->get_byte(); // ZERO Byte - header.msglength=file->get_word(); - header.msgoffset=file->get_dword(); + header.msglength = file->get_word(); + header.msgoffset = file->get_dword(); char chibi[4]; - file->get_byte_array((uint8_t*)chibi,4); - header.is_chibi=(chibi[0]=='C' && chibi[1]=='H' && chibi[2]=='B' && chibi[3]=='I'); - - for (int i=0;i<64;i++) { - - uint8_t panbyte=file->get_byte(); - - uint8_t pan_dst=(panbyte<65) ? panbyte : 32; - bool surround_dst=(panbyte==100); - bool mute_dst=(panbyte>=128); + file->get_byte_array((uint8_t *)chibi, 4); + header.is_chibi = (chibi[0] == 'C' && chibi[1] == 'H' && chibi[2] == 'B' && chibi[3] == 'I'); + + for (int i = 0; i < 64; i++) { + + uint8_t panbyte = file->get_byte(); + + uint8_t pan_dst = (panbyte < 65) ? panbyte : 32; + bool surround_dst = (panbyte == 100); + bool mute_dst = (panbyte >= 128); if (!p_dont_set) { - song->set_channel_pan( i, pan_dst ); - song->set_channel_surround( i, surround_dst ); - song->set_channel_mute( i, mute_dst ); + song->set_channel_pan(i, pan_dst); + song->set_channel_surround(i, surround_dst); + song->set_channel_mute(i, mute_dst); } } - for (int i=0;i<64;i++) { + for (int i = 0; i < 64; i++) { unsigned char cv = file->get_byte(); if (!p_dont_set) - song->set_channel_volume( i, cv ); + song->set_channel_volume(i, cv); } - CP_ERR_COND_V( file->eof_reached(),FILE_CORRUPTED ); - CP_ERR_COND_V( file->get_error(),FILE_CORRUPTED ); + CP_ERR_COND_V(file->eof_reached(), FILE_CORRUPTED); + CP_ERR_COND_V(file->get_error(), FILE_CORRUPTED); return FILE_OK; } CPLoader::Error CPLoader_IT::load_effects() { - + if (!header.is_chibi) return FILE_OK; //no effects, regular IT file - + /* GOTO End of IT header */ - file->seek(0xC0+header.ordnum+header.insnum*4+header.smpnum*4+header.patnum*4); - - - if (file->get_byte()>0) //not made with this version, ignore extended info + file->seek(0xC0 + header.ordnum + header.insnum * 4 + header.smpnum * 4 + header.patnum * 4); + + if (file->get_byte() > 0) //not made with this version, ignore extended info return FILE_OK; - + /* Chibitracker Extended info */ - switch(file->get_byte()) { - + switch (file->get_byte()) { + case CPSong::REVERB_MODE_ROOM: { - - song->set_reverb_mode( CPSong::REVERB_MODE_ROOM ); + + song->set_reverb_mode(CPSong::REVERB_MODE_ROOM); } break; case CPSong::REVERB_MODE_STUDIO_SMALL: { - - song->set_reverb_mode( CPSong::REVERB_MODE_STUDIO_SMALL ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_STUDIO_SMALL); + } break; case CPSong::REVERB_MODE_STUDIO_MEDIUM: { - - song->set_reverb_mode( CPSong::REVERB_MODE_STUDIO_MEDIUM ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_STUDIO_MEDIUM); + } break; case CPSong::REVERB_MODE_STUDIO_LARGE: { - - song->set_reverb_mode( CPSong::REVERB_MODE_STUDIO_LARGE ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_STUDIO_LARGE); + } break; case CPSong::REVERB_MODE_HALL: { - - song->set_reverb_mode( CPSong::REVERB_MODE_HALL ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_HALL); + } break; case CPSong::REVERB_MODE_SPACE_ECHO: { - - song->set_reverb_mode( CPSong::REVERB_MODE_SPACE_ECHO ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_SPACE_ECHO); + } break; case CPSong::REVERB_MODE_ECHO: { - - song->set_reverb_mode( CPSong::REVERB_MODE_ECHO ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_ECHO); + } break; case CPSong::REVERB_MODE_DELAY: { - - song->set_reverb_mode( CPSong::REVERB_MODE_DELAY ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_DELAY); + } break; case CPSong::REVERB_MODE_HALF_ECHO: { - - song->set_reverb_mode( CPSong::REVERB_MODE_HALF_ECHO ); - + + song->set_reverb_mode(CPSong::REVERB_MODE_HALF_ECHO); + } break; - } - + //chorus - song->set_chorus_speed_hz10( file->get_byte() ); - song->set_chorus_delay_ms( file->get_byte() ); - song->set_chorus_depth_ms10( file->get_byte() ); - song->set_chorus_separation_ms( file->get_byte() ); - - for (int i=0;i<CPPattern::WIDTH;i++) { - song->set_channel_reverb(i,file->get_byte()); + song->set_chorus_speed_hz10(file->get_byte()); + song->set_chorus_delay_ms(file->get_byte()); + song->set_chorus_depth_ms10(file->get_byte()); + song->set_chorus_separation_ms(file->get_byte()); + + for (int i = 0; i < CPPattern::WIDTH; i++) { + song->set_channel_reverb(i, file->get_byte()); } - for (int i=0;i<CPPattern::WIDTH;i++) { - song->set_channel_chorus(i,file->get_byte()); + for (int i = 0; i < CPPattern::WIDTH; i++) { + song->set_channel_chorus(i, file->get_byte()); } - + return FILE_OK; - } CPLoader::Error CPLoader_IT::load_message() { - if (!(header.special & 1)) { return FILE_OK; - } - + } file->seek(header.msgoffset); @@ -214,55 +205,46 @@ CPLoader::Error CPLoader_IT::load_message() { char message[8000]; - char *tmpmsg = message; - file->get_byte_array((uint8_t*)tmpmsg,header.msglength); - tmpmsg[header.msglength]=0; - - for (int i=0;i<header.msglength;i++) if (tmpmsg[i]=='\r') tmpmsg[i]='\n'; + file->get_byte_array((uint8_t *)tmpmsg, header.msglength); + tmpmsg[header.msglength] = 0; + + for (int i = 0; i < header.msglength; i++) + if (tmpmsg[i] == '\r') tmpmsg[i] = '\n'; song->set_message(tmpmsg); - + return FILE_OK; } CPLoader::Error CPLoader_IT::load_orders() { file->seek(0xC0); - - - for (int i=0;i<header.ordnum;i++) { - - uint8_t aux_order=file->get_byte(); - CPOrder order=CP_ORDER_NONE; - - - if (i>=CPSong::MAX_ORDERS) + + for (int i = 0; i < header.ordnum; i++) { + + uint8_t aux_order = file->get_byte(); + CPOrder order = CP_ORDER_NONE; + + if (i >= CPSong::MAX_ORDERS) continue; - if (aux_order==254) { + if (aux_order == 254) { - order=CP_ORDER_BREAK; + order = CP_ORDER_BREAK; - } else if (aux_order<200) { + } else if (aux_order < 200) { - order=aux_order; + order = aux_order; //nothing! - - } - song->set_order(i,order); - + } + song->set_order(i, order); } - - if (file->eof_reached() || file->get_error()) { + if (file->eof_reached() || file->get_error()) { return FILE_CORRUPTED; - } - + return FILE_OK; } - - - diff --git a/modules/chibi/cp_loader_it_instruments.cpp b/modules/chibi/cp_loader_it_instruments.cpp index 446e841c5..cd44d0061 100644 --- a/modules/chibi/cp_loader_it_instruments.cpp +++ b/modules/chibi/cp_loader_it_instruments.cpp @@ -30,189 +30,171 @@ #include "cp_loader_it.h" enum EnvFlags { - ENV_ON=1, - ENV_LOOP=2, - ENV_SUSLOOP=4, - ENV_CARRY=8, - ENV_FILTER=128 + ENV_ON = 1, + ENV_LOOP = 2, + ENV_SUSLOOP = 4, + ENV_CARRY = 8, + ENV_FILTER = 128 }; -void CPLoader_IT::load_envelope(CPEnvelope *p_envelope,bool*p_has_filter_flag) { +void CPLoader_IT::load_envelope(CPEnvelope *p_envelope, bool *p_has_filter_flag) { + + uint8_t flags = file->get_byte(); + uint8_t points = file->get_byte(); + uint8_t begin = file->get_byte(); + uint8_t end = file->get_byte(); + uint8_t susbegin = file->get_byte(); + uint8_t susend = file->get_byte(); - uint8_t flags=file->get_byte(); - uint8_t points=file->get_byte(); - uint8_t begin=file->get_byte(); - uint8_t end=file->get_byte(); - uint8_t susbegin=file->get_byte(); - uint8_t susend=file->get_byte(); - p_envelope->reset(); - - for (int i=0;i<25;i++) { - uint8_t height=file->get_byte(); - int8_t &signed_height=(int8_t&)height; - uint16_t tick=file->get_word(); - - if (i>=points) + for (int i = 0; i < 25; i++) { + + uint8_t height = file->get_byte(); + int8_t &signed_height = (int8_t &)height; + uint16_t tick = file->get_word(); + + if (i >= points) continue; - p_envelope->add_position( tick, signed_height ); - + p_envelope->add_position(tick, signed_height); } - p_envelope->set_enabled( flags & ENV_ON ); - p_envelope->set_carry_enabled( flags & ENV_CARRY); - - p_envelope->set_loop_enabled( flags & ENV_LOOP ); - p_envelope->set_loop_begin( begin ); - p_envelope->set_loop_end( end ); - - p_envelope->set_sustain_loop_enabled( flags & ENV_SUSLOOP ); - p_envelope->set_sustain_loop_begin( susbegin ); - p_envelope->set_sustain_loop_end( susend ); - + p_envelope->set_enabled(flags & ENV_ON); + p_envelope->set_carry_enabled(flags & ENV_CARRY); + + p_envelope->set_loop_enabled(flags & ENV_LOOP); + p_envelope->set_loop_begin(begin); + p_envelope->set_loop_end(end); + + p_envelope->set_sustain_loop_enabled(flags & ENV_SUSLOOP); + p_envelope->set_sustain_loop_begin(susbegin); + p_envelope->set_sustain_loop_end(susend); + if (p_has_filter_flag) - *p_has_filter_flag=flags&ENV_FILTER; - + *p_has_filter_flag = flags & ENV_FILTER; + file->get_byte(); //zerobyte - + //fill with stuff if the envelope hass less than 2 points - while(p_envelope->get_node_count()<2) { - - p_envelope->add_position( 30*p_envelope->get_node_count(), p_envelope->get_min()==0 ? 64 : 0, false ); + while (p_envelope->get_node_count() < 2) { + + p_envelope->add_position(30 * p_envelope->get_node_count(), p_envelope->get_min() == 0 ? 64 : 0, false); } } - -CPLoader::Error CPLoader_IT::load_instrument(CPInstrument *p_instrument,int *p_samples) { - - +CPLoader::Error CPLoader_IT::load_instrument(CPInstrument *p_instrument, int *p_samples) { char aux_header[4]; - - file->get_byte_array((uint8_t*)aux_header,4); - - if ( aux_header[0]!='I' || - aux_header[1]!='M' || - aux_header[2]!='P' || - aux_header[3]!='I') { + file->get_byte_array((uint8_t *)aux_header, 4); + + if (aux_header[0] != 'I' || + aux_header[1] != 'M' || + aux_header[2] != 'P' || + aux_header[3] != 'I') { CP_PRINTERR("IT CPLoader CPInstrument: Failed Identifier"); - + return FILE_UNRECOGNIZED; } - - // Ignore deprecated 8.3 filename field - for (int i=0;i<12;i++) file->get_byte(); - + for (int i = 0; i < 12; i++) + file->get_byte(); + //Ignore zerobyte - file->get_byte(); /* (byte) CPInstrument type (always 0) */ - - switch( file->get_byte() ) { /* New CPNote Action [0,1,2,3] */ - case 0: p_instrument->set_NNA_type( CPInstrument::NNA_NOTE_CUT ) ; break; - case 1: p_instrument->set_NNA_type( CPInstrument::NNA_NOTE_CONTINUE ) ; break; - case 2: p_instrument->set_NNA_type( CPInstrument::NNA_NOTE_OFF ) ; break; - case 3: p_instrument->set_NNA_type( CPInstrument::NNA_NOTE_FADE ) ; break; + file->get_byte(); /* (byte) CPInstrument type (always 0) */ + + switch (file->get_byte()) { /* New CPNote Action [0,1,2,3] */ + case 0: p_instrument->set_NNA_type(CPInstrument::NNA_NOTE_CUT); break; + case 1: p_instrument->set_NNA_type(CPInstrument::NNA_NOTE_CONTINUE); break; + case 2: p_instrument->set_NNA_type(CPInstrument::NNA_NOTE_OFF); break; + case 3: p_instrument->set_NNA_type(CPInstrument::NNA_NOTE_FADE); break; }; - switch( file->get_byte() ) { // Duplicate Check Type - case 0: p_instrument->set_DC_type( CPInstrument::DCT_DISABLED ); break ; - case 1: p_instrument->set_DC_type( CPInstrument::DCT_NOTE ); break ; - case 2: p_instrument->set_DC_type( CPInstrument::DCT_SAMPLE ); break ; - case 3: p_instrument->set_DC_type( CPInstrument::DCT_INSTRUMENT ); break ; + switch (file->get_byte()) { // Duplicate Check Type + case 0: p_instrument->set_DC_type(CPInstrument::DCT_DISABLED); break; + case 1: p_instrument->set_DC_type(CPInstrument::DCT_NOTE); break; + case 2: p_instrument->set_DC_type(CPInstrument::DCT_SAMPLE); break; + case 3: p_instrument->set_DC_type(CPInstrument::DCT_INSTRUMENT); break; } - switch( file->get_byte() ) { //Duplicate Check Action - case 0: p_instrument->set_DC_action( CPInstrument::DCA_NOTE_CUT ); break ; - case 1: p_instrument->set_DC_action( CPInstrument::DCA_NOTE_OFF ); break ; - case 2: p_instrument->set_DC_action( CPInstrument::DCA_NOTE_FADE ); break ; + switch (file->get_byte()) { //Duplicate Check Action + case 0: p_instrument->set_DC_action(CPInstrument::DCA_NOTE_CUT); break; + case 1: p_instrument->set_DC_action(CPInstrument::DCA_NOTE_OFF); break; + case 2: p_instrument->set_DC_action(CPInstrument::DCA_NOTE_FADE); break; } - + int fade = file->get_word(); //intf("AFADE: %i\n",fade); - if (fade>CPInstrument::MAX_FADEOUT) //needs to be clipped because of horrible modplug doings - fade=CPInstrument::MAX_FADEOUT; - - p_instrument->set_volume_fadeout( fade ); - p_instrument->set_pan_pitch_separation( file->get_byte() ); - p_instrument->set_pan_pitch_center( file->get_byte() ); - p_instrument->set_volume_global_amount( file->get_byte() ); - uint8_t pan=file->get_byte(); - p_instrument->set_pan_default_amount(pan&0x7F); - p_instrument->set_pan_default_enabled( !(pan&0x80) ); - p_instrument->set_volume_random_variation( file->get_byte() ); - p_instrument->set_pan_random_variation( file->get_byte() ); - - - + if (fade > CPInstrument::MAX_FADEOUT) //needs to be clipped because of horrible modplug doings + fade = CPInstrument::MAX_FADEOUT; + + p_instrument->set_volume_fadeout(fade); + p_instrument->set_pan_pitch_separation(file->get_byte()); + p_instrument->set_pan_pitch_center(file->get_byte()); + p_instrument->set_volume_global_amount(file->get_byte()); + uint8_t pan = file->get_byte(); + p_instrument->set_pan_default_amount(pan & 0x7F); + p_instrument->set_pan_default_enabled(!(pan & 0x80)); + p_instrument->set_volume_random_variation(file->get_byte()); + p_instrument->set_pan_random_variation(file->get_byte()); + file->get_word(); //empty (version) - uint8_t samples=file->get_byte(); + uint8_t samples = file->get_byte(); if (p_samples) - *p_samples=samples; + *p_samples = samples; file->get_byte(); //empty - char aux_name[26]; - file->get_byte_array((uint8_t*)aux_name,26); + char aux_name[26]; + file->get_byte_array((uint8_t *)aux_name, 26); p_instrument->set_name(aux_name); - - uint8_t cutoff=file->get_byte(); - - p_instrument->set_filter_default_cutoff(cutoff&0x7F); - p_instrument->set_filter_use_default_cutoff(cutoff&0x80); - - uint8_t resonance=file->get_byte(); - - p_instrument->set_filter_default_resonance(resonance&0x7F); - p_instrument->set_filter_use_default_resonance(resonance&0x80); - + + uint8_t cutoff = file->get_byte(); + + p_instrument->set_filter_default_cutoff(cutoff & 0x7F); + p_instrument->set_filter_use_default_cutoff(cutoff & 0x80); + + uint8_t resonance = file->get_byte(); + + p_instrument->set_filter_default_resonance(resonance & 0x7F); + p_instrument->set_filter_use_default_resonance(resonance & 0x80); + file->get_dword(); //MIDI, IGNORED! - + /* CPNote -> CPSample table */ - for (uint8_t i=0;i<CPNote::NOTES;i++) { - - - uint8_t note=file->get_byte(); - if (note>=CPNote::NOTES) - note=0; - p_instrument->set_note_number(i,note); - - uint8_t samp=file->get_byte(); - if (samp==0 || samp>99) - samp=CPNote::EMPTY; - else + for (uint8_t i = 0; i < CPNote::NOTES; i++) { + + uint8_t note = file->get_byte(); + if (note >= CPNote::NOTES) + note = 0; + p_instrument->set_note_number(i, note); + + uint8_t samp = file->get_byte(); + if (samp == 0 || samp > 99) + samp = CPNote::EMPTY; + else samp--; - - - p_instrument->set_sample_number(i,samp); - + p_instrument->set_sample_number(i, samp); } - - load_envelope( p_instrument->get_volume_envelope() ); - load_envelope( p_instrument->get_pan_envelope() ); + load_envelope(p_instrument->get_volume_envelope()); + load_envelope(p_instrument->get_pan_envelope()); bool use_as_filter; - load_envelope( p_instrument->get_pitch_filter_envelope(), &use_as_filter ); - p_instrument->set_pitch_use_as_filter( use_as_filter ); + load_envelope(p_instrument->get_pitch_filter_envelope(), &use_as_filter); + p_instrument->set_pitch_use_as_filter(use_as_filter); return FILE_OK; - } - CPLoader::Error CPLoader_IT::load_instruments() { + for (int i = 0; i < header.insnum; i++) { - for (int i=0;i<header.insnum;i++) { + file->seek(0xC0 + header.ordnum + i * 4); + uint32_t final_location = file->get_dword(); + file->seek(final_location); - - file->seek(0xC0+header.ordnum+i*4); - uint32_t final_location=file->get_dword(); - file->seek( final_location ); - - Error err=load_instrument( song->get_instrument( i ) ); + Error err = load_instrument(song->get_instrument(i)); if (err) return err; - } return FILE_OK; @@ -220,5 +202,3 @@ CPLoader::Error CPLoader_IT::load_instruments() { if (file->eof_reached() || file->get_error()) return FILE_CORRUPTED; } - - diff --git a/modules/chibi/cp_loader_it_patterns.cpp b/modules/chibi/cp_loader_it_patterns.cpp index 528d99fff..156e49742 100644 --- a/modules/chibi/cp_loader_it_patterns.cpp +++ b/modules/chibi/cp_loader_it_patterns.cpp @@ -28,139 +28,132 @@ /*************************************************************************/ #include "cp_loader_it.h" - CPLoader::Error CPLoader_IT::load_patterns() { + for (int i = 0; i < header.patnum; i++) { - for (int i=0;i<header.patnum;i++) { - - if (i>=CPSong::MAX_PATTERNS) + if (i >= CPSong::MAX_PATTERNS) break; - + /* Position where pattern offsets are stored */ - file->seek(0xC0+header.ordnum+header.insnum*4+header.smpnum*4+i*4); - uint32_t pattern_offset=file->get_dword(); - - if (pattern_offset==0) { + file->seek(0xC0 + header.ordnum + header.insnum * 4 + header.smpnum * 4 + i * 4); + uint32_t pattern_offset = file->get_dword(); + + if (pattern_offset == 0) { continue; } - + uint16_t pat_size; uint16_t pat_length; - int row=0,flag,channel,j; + int row = 0, flag, channel, j; uint8_t aux_byte; uint32_t reserved; uint8_t chan_mask[64]; //mask cache for each CPNote last_value[64]; //last value of each - for (j=0;j<64;j++) { + for (j = 0; j < 64; j++) { - chan_mask[j]=0; + chan_mask[j] = 0; last_value[j].clear(); } file->seek(pattern_offset); - pat_size=file->get_word(); - pat_length=file->get_word(); - reserved=file->get_dword(); + pat_size = file->get_word(); + pat_length = file->get_word(); + reserved = file->get_dword(); + + song->get_pattern(i)->set_length(pat_length); - song->get_pattern(i)->set_length( pat_length ); - do { - aux_byte=file->get_byte(); - flag=aux_byte; + aux_byte = file->get_byte(); + flag = aux_byte; - if ( flag==0 ) { + if (flag == 0) { row++; } else { - channel=(flag-1) & 63; + channel = (flag - 1) & 63; - if ( flag & 128 ) { + if (flag & 128) { - aux_byte=file->get_byte(); - chan_mask[channel]=aux_byte; + aux_byte = file->get_byte(); + chan_mask[channel] = aux_byte; } CPNote note; //note used for reading - if ( chan_mask[channel]&1 ) { // read note - - aux_byte=file->get_byte(); - - if ( aux_byte<120 ) - note.note=aux_byte; - else if ( aux_byte==255 ) - note.note=CPNote::OFF; - else if ( aux_byte==254 ) - note.note=CPNote::CUT; + if (chan_mask[channel] & 1) { // read note - last_value[channel].note=note.note; + aux_byte = file->get_byte(); + + if (aux_byte < 120) + note.note = aux_byte; + else if (aux_byte == 255) + note.note = CPNote::OFF; + else if (aux_byte == 254) + note.note = CPNote::CUT; + + last_value[channel].note = note.note; } - - if ( chan_mask[channel]&2 ) { + if (chan_mask[channel] & 2) { - aux_byte=file->get_byte(); - if ( aux_byte<100 ) - note.instrument=aux_byte-1; + aux_byte = file->get_byte(); + if (aux_byte < 100) + note.instrument = aux_byte - 1; - last_value[channel].instrument=note.instrument; + last_value[channel].instrument = note.instrument; } - if ( chan_mask[channel]&4 ) { + if (chan_mask[channel] & 4) { - aux_byte=file->get_byte(); - if ( aux_byte<213 ) - note.volume=aux_byte; + aux_byte = file->get_byte(); + if (aux_byte < 213) + note.volume = aux_byte; - last_value[channel].volume=note.volume; + last_value[channel].volume = note.volume; } - if ( chan_mask[channel]&8 ) { + if (chan_mask[channel] & 8) { + + aux_byte = file->get_byte(); + if (aux_byte > 0) + note.command = aux_byte - 1; - aux_byte=file->get_byte(); - if ( aux_byte>0 ) - note.command=aux_byte-1; - - - last_value[channel].command=note.command; + last_value[channel].command = note.command; - note.parameter=file->get_byte(); - - last_value[channel].parameter=note.parameter; + note.parameter = file->get_byte(); + + last_value[channel].parameter = note.parameter; } - if ( chan_mask[channel]&16 ) { + if (chan_mask[channel] & 16) { - note.note=last_value[channel].note; + note.note = last_value[channel].note; } - if ( chan_mask[channel]&32 ) { + if (chan_mask[channel] & 32) { - note.instrument=last_value[channel].instrument; + note.instrument = last_value[channel].instrument; } - if ( chan_mask[channel]&64 ) { + if (chan_mask[channel] & 64) { - note.volume=last_value[channel].volume; + note.volume = last_value[channel].volume; } - if ( chan_mask[channel]&128 ) { + if (chan_mask[channel] & 128) { - note.command=last_value[channel].command; - note.parameter=last_value[channel].parameter; + note.command = last_value[channel].command; + note.parameter = last_value[channel].parameter; } - - song->get_pattern(i)->set_note(channel,row,note); + + song->get_pattern(i)->set_note(channel, row, note); } - - - } while(row<pat_length); + } while (row < pat_length); } return FILE_OK; } - diff --git a/modules/chibi/cp_loader_it_samples.cpp b/modules/chibi/cp_loader_it_samples.cpp index 60db9b7f7..414424f27 100644 --- a/modules/chibi/cp_loader_it_samples.cpp +++ b/modules/chibi/cp_loader_it_samples.cpp @@ -31,7 +31,6 @@ struct AuxSampleData { - uint32_t fileofs; uint32_t c5spd; uint32_t length; @@ -43,168 +42,159 @@ struct AuxSampleData { bool stereo; bool exists; bool compressed; - }; - enum IT_Sample_Flags { - IT_SAMPLE_EXISTS=1, - IT_SAMPLE_16BITS=2, - IT_SAMPLE_STEREO=4, - IT_SAMPLE_COMPRESSED=8, - IT_SAMPLE_LOOPED=16, - IT_SAMPLE_SUSTAIN_LOOPED=32, - IT_SAMPLE_LOOP_IS_PINGPONG=64, - IT_SAMPLE_SUSTAIN_LOOP_IS_PINGPONG=128 + IT_SAMPLE_EXISTS = 1, + IT_SAMPLE_16BITS = 2, + IT_SAMPLE_STEREO = 4, + IT_SAMPLE_COMPRESSED = 8, + IT_SAMPLE_LOOPED = 16, + IT_SAMPLE_SUSTAIN_LOOPED = 32, + IT_SAMPLE_LOOP_IS_PINGPONG = 64, + IT_SAMPLE_SUSTAIN_LOOP_IS_PINGPONG = 128 }; - CPLoader::Error CPLoader_IT::load_sample(CPSample *p_sample) { - AuxSampleData aux_sample_data; char aux_header[4]; - file->get_byte_array((uint8_t*)aux_header,4); - - if ( aux_header[0]!='I' || - aux_header[1]!='M' || - aux_header[2]!='P' || - aux_header[3]!='S') { - + file->get_byte_array((uint8_t *)aux_header, 4); + + if (aux_header[0] != 'I' || + aux_header[1] != 'M' || + aux_header[2] != 'P' || + aux_header[3] != 'S') { + //CP_PRINTERR("IT CPLoader CPSample: Failed Identifier"); return FILE_UNRECOGNIZED; } - // Ignore deprecated 8.3 filename - for (int i=0;i<12;i++) file->get_byte(); - + for (int i = 0; i < 12; i++) + file->get_byte(); + file->get_byte(); //ignore zerobyte - - p_sample->set_global_volume( file->get_byte() ); - + + p_sample->set_global_volume(file->get_byte()); + /* SAMPLE FLAGS */ - uint8_t flags=file->get_byte(); - aux_sample_data.loop_enabled=flags&IT_SAMPLE_LOOPED; - aux_sample_data.pingpong_enabled=flags&IT_SAMPLE_LOOP_IS_PINGPONG; - aux_sample_data.is16bit=flags&IT_SAMPLE_16BITS; - aux_sample_data.exists=flags&IT_SAMPLE_EXISTS; - aux_sample_data.stereo=flags&IT_SAMPLE_STEREO; - aux_sample_data.compressed=flags&IT_SAMPLE_COMPRESSED; - + uint8_t flags = file->get_byte(); + aux_sample_data.loop_enabled = flags & IT_SAMPLE_LOOPED; + aux_sample_data.pingpong_enabled = flags & IT_SAMPLE_LOOP_IS_PINGPONG; + aux_sample_data.is16bit = flags & IT_SAMPLE_16BITS; + aux_sample_data.exists = flags & IT_SAMPLE_EXISTS; + aux_sample_data.stereo = flags & IT_SAMPLE_STEREO; + aux_sample_data.compressed = flags & IT_SAMPLE_COMPRESSED; + p_sample->set_default_volume(file->get_byte()); /* SAMPLE NAME */ char aux_name[26]; - file->get_byte_array((uint8_t*)aux_name,26); + file->get_byte_array((uint8_t *)aux_name, 26); p_sample->set_name(aux_name); - + // ?? - uint8_t convert_flag=file->get_byte(); + uint8_t convert_flag = file->get_byte(); // PAN - uint8_t pan=file->get_byte(); - p_sample->set_pan( pan&0x7F ); - p_sample->set_pan_enabled( pan & 0x80 ); + uint8_t pan = file->get_byte(); + p_sample->set_pan(pan & 0x7F); + p_sample->set_pan_enabled(pan & 0x80); - aux_sample_data.length=file->get_dword(); + aux_sample_data.length = file->get_dword(); - - aux_sample_data.loop_begin= file->get_dword(); - aux_sample_data.loop_end= file->get_dword(); - aux_sample_data.c5spd=file->get_dword(); + aux_sample_data.loop_begin = file->get_dword(); + aux_sample_data.loop_end = file->get_dword(); + aux_sample_data.c5spd = file->get_dword(); /*p_sample->data.set_sustain_loop_begin=*/file->get_dword(); /*p_sample->data.sustain_loop_end=*/file->get_dword(); - aux_sample_data.fileofs=file->get_dword(); - p_sample->set_vibrato_speed( file->get_byte() ); - p_sample->set_vibrato_depth( file->get_byte() ); - p_sample->set_vibrato_rate( file->get_byte() ); - switch( file->get_byte() ) { + aux_sample_data.fileofs = file->get_dword(); + p_sample->set_vibrato_speed(file->get_byte()); + p_sample->set_vibrato_depth(file->get_byte()); + p_sample->set_vibrato_rate(file->get_byte()); + switch (file->get_byte()) { /* Vibrato Wave: 0=sine, 1=rampdown, 2=square, 3=random */ - case 0: p_sample->set_vibrato_type( CPSample::VIBRATO_SINE ); break; - case 1: p_sample->set_vibrato_type( CPSample::VIBRATO_SAW ); break; - case 2: p_sample->set_vibrato_type( CPSample::VIBRATO_SQUARE ); break; - case 3: p_sample->set_vibrato_type( CPSample::VIBRATO_RANDOM ); break; - default: p_sample->set_vibrato_type( CPSample::VIBRATO_SINE ); break; + case 0: p_sample->set_vibrato_type(CPSample::VIBRATO_SINE); break; + case 1: p_sample->set_vibrato_type(CPSample::VIBRATO_SAW); break; + case 2: p_sample->set_vibrato_type(CPSample::VIBRATO_SQUARE); break; + case 3: p_sample->set_vibrato_type(CPSample::VIBRATO_RANDOM); break; + default: p_sample->set_vibrato_type(CPSample::VIBRATO_SINE); break; } - + //printf("Name %s - Flags: fileofs :%i - c5spd %i - len %i 16b %i - data?: %i\n",p_sample->get_name(),aux_sample_data.fileofs,aux_sample_data.c5spd, aux_sample_data.length, aux_sample_data.is16bit,aux_sample_data.exists); CPSample_ID samp_id; - + if (aux_sample_data.exists) { - samp_id=load_sample_data(aux_sample_data); - CPSampleManager::get_singleton()->set_c5_freq(samp_id,aux_sample_data.c5spd); - CPSampleManager::get_singleton()->set_loop_begin( samp_id,aux_sample_data.loop_begin ); - CPSampleManager::get_singleton()->set_loop_end( samp_id,aux_sample_data.loop_end ); - CPSample_Loop_Type loop_type=aux_sample_data.loop_enabled?( aux_sample_data.pingpong_enabled? CP_LOOP_BIDI: CP_LOOP_FORWARD):CP_LOOP_NONE; - CPSampleManager::get_singleton()->set_loop_end( samp_id,aux_sample_data.loop_end ); - CPSampleManager::get_singleton()->set_loop_type( samp_id, loop_type); - + samp_id = load_sample_data(aux_sample_data); + CPSampleManager::get_singleton()->set_c5_freq(samp_id, aux_sample_data.c5spd); + CPSampleManager::get_singleton()->set_loop_begin(samp_id, aux_sample_data.loop_begin); + CPSampleManager::get_singleton()->set_loop_end(samp_id, aux_sample_data.loop_end); + CPSample_Loop_Type loop_type = aux_sample_data.loop_enabled ? (aux_sample_data.pingpong_enabled ? CP_LOOP_BIDI : CP_LOOP_FORWARD) : CP_LOOP_NONE; + CPSampleManager::get_singleton()->set_loop_end(samp_id, aux_sample_data.loop_end); + CPSampleManager::get_singleton()->set_loop_type(samp_id, loop_type); } - + //printf("Loaded id is null?: %i\n",samp_id.is_null()); p_sample->set_sample_data(samp_id); if (!samp_id.is_null()) { - - // printf("Loaded ID: stereo: %i len %i 16bit %i\n",CPSampleManager::get_singleton()->is_stereo(samp_id), CPSampleManager::get_singleton()->get_size( samp_id), CPSampleManager::get_singleton()->is_16bits( samp_id) ); + + // printf("Loaded ID: stereo: %i len %i 16bit %i\n",CPSampleManager::get_singleton()->is_stereo(samp_id), CPSampleManager::get_singleton()->get_size( samp_id), CPSampleManager::get_singleton()->is_16bits( samp_id) ); } - - CP_ERR_COND_V( file->eof_reached(),FILE_CORRUPTED ); - CP_ERR_COND_V( file->get_error(),FILE_CORRUPTED ); - - return FILE_OK; -} + CP_ERR_COND_V(file->eof_reached(), FILE_CORRUPTED); + CP_ERR_COND_V(file->get_error(), FILE_CORRUPTED); -CPSample_ID CPLoader_IT::load_sample_data(AuxSampleData& p_sample_data) { + return FILE_OK; +} +CPSample_ID CPLoader_IT::load_sample_data(AuxSampleData &p_sample_data) { - int aux_sample_properties = (p_sample_data.is16bit?IT_SAMPLE_16BITS:0)|(p_sample_data.compressed?IT_SAMPLE_COMPRESSED:0)|(p_sample_data.stereo?IT_SAMPLE_STEREO:0); + int aux_sample_properties = (p_sample_data.is16bit ? IT_SAMPLE_16BITS : 0) | (p_sample_data.compressed ? IT_SAMPLE_COMPRESSED : 0) | (p_sample_data.stereo ? IT_SAMPLE_STEREO : 0); file->seek(p_sample_data.fileofs); - - CPSampleManager *sm=CPSampleManager::get_singleton(); + + CPSampleManager *sm = CPSampleManager::get_singleton(); CPSample_ID id; - + switch (aux_sample_properties) { - case (0): // 8 bits, mono - case (IT_SAMPLE_16BITS): // 16 bits mono - case (IT_SAMPLE_STEREO): // 8 bits stereo - case (IT_SAMPLE_16BITS|IT_SAMPLE_STEREO): { // 16 bits mono + case (0): // 8 bits, mono + case (IT_SAMPLE_16BITS): // 16 bits mono + case (IT_SAMPLE_STEREO): // 8 bits stereo + case (IT_SAMPLE_16BITS | IT_SAMPLE_STEREO): { // 16 bits mono - id=sm->create(p_sample_data.is16bit,p_sample_data.stereo,p_sample_data.length); + id = sm->create(p_sample_data.is16bit, p_sample_data.stereo, p_sample_data.length); if (id.is_null()) break; sm->lock_data(id); - int16_t *ptr16 = (int16_t*)sm->get_data(id); - int8_t *ptr8=(int8_t*)ptr16; + int16_t *ptr16 = (int16_t *)sm->get_data(id); + int8_t *ptr8 = (int8_t *)ptr16; - int chans=p_sample_data.stereo?2:1; + int chans = p_sample_data.stereo ? 2 : 1; if (p_sample_data.is16bit) { - for (int c=0;c<chans;c++) { + for (int c = 0; c < chans; c++) { - for (int i=0;i<p_sample_data.length;i++) { + for (int i = 0; i < p_sample_data.length; i++) { - ptr16[i*chans+c]=file->get_word(); + ptr16[i * chans + c] = file->get_word(); } } } else { - for (int c=0;c<chans;c++) { + for (int c = 0; c < chans; c++) { - for (int i=0;i<p_sample_data.length;i++) { + for (int i = 0; i < p_sample_data.length; i++) { - ptr8[i*chans+c]=file->get_byte(); + ptr8[i * chans + c] = file->get_byte(); } } - } sm->unlock_data(id); @@ -212,33 +202,30 @@ CPSample_ID CPLoader_IT::load_sample_data(AuxSampleData& p_sample_data) { } break; case (IT_SAMPLE_COMPRESSED): { // 8 bits compressed - - id=sm->create(false,false,p_sample_data.length); + id = sm->create(false, false, p_sample_data.length); if (id.is_null()) break; sm->lock_data(id); - - if ( load_sample_8bits_IT_compressed((void*)sm->get_data( id),p_sample_data.length) ) { + + if (load_sample_8bits_IT_compressed((void *)sm->get_data(id), p_sample_data.length)) { sm->unlock_data(id); sm->destroy(id); - + break; } sm->unlock_data(id); - } break; - case (IT_SAMPLE_16BITS|IT_SAMPLE_COMPRESSED): { // 16 bits compressed - + case (IT_SAMPLE_16BITS | IT_SAMPLE_COMPRESSED): { // 16 bits compressed - id=sm->create(true,false,p_sample_data.length); + id = sm->create(true, false, p_sample_data.length); if (id.is_null()) break; sm->lock_data(id); - - if ( load_sample_16bits_IT_compressed((void*)sm->get_data(id),p_sample_data.length) ) { + + if (load_sample_16bits_IT_compressed((void *)sm->get_data(id), p_sample_data.length)) { sm->unlock_data(id); sm->destroy(id); @@ -249,31 +236,26 @@ CPSample_ID CPLoader_IT::load_sample_data(AuxSampleData& p_sample_data) { } break; default: { - + // I dont know how to handle stereo compressed, does that exist? } break; - } - return id; } - CPLoader::Error CPLoader_IT::load_samples() { - for (int i=0;i<header.smpnum;i++) { + for (int i = 0; i < header.smpnum; i++) { - //seek to sample - file->seek(0xC0+header.ordnum+header.insnum*4+i*4); - - uint32_t final_location=file->get_dword(); - file->seek( final_location ); - + //seek to sample + file->seek(0xC0 + header.ordnum + header.insnum * 4 + i * 4); - Error err=load_sample(song->get_sample(i)); - CP_ERR_COND_V(err,err); + uint32_t final_location = file->get_dword(); + file->seek(final_location); + Error err = load_sample(song->get_sample(i)); + CP_ERR_COND_V(err, err); } if (file->eof_reached() || file->get_error()) @@ -287,208 +269,200 @@ CPLoader::Error CPLoader_IT::load_samples() { * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE * NOTICE */ -uint32_t CPLoader_IT::read_n_bits_from_IT_compressed_block (uint8_t p_bits_to_read) { +uint32_t CPLoader_IT::read_n_bits_from_IT_compressed_block(uint8_t p_bits_to_read) { - uint32_t aux_return_value; - uint32_t val; + uint32_t aux_return_value; + uint32_t val; - uint8_t *buffer=(uint8_t*)source_position; - if ( p_bits_to_read <= source_remaining_bits ) { + uint8_t *buffer = (uint8_t *)source_position; + if (p_bits_to_read <= source_remaining_bits) { - val=buffer[3]; - val<<=8; - val|=buffer[2]; - val<<=8; - val|=buffer[1]; - val<<=8; - val|=buffer[0]; + val = buffer[3]; + val <<= 8; + val |= buffer[2]; + val <<= 8; + val |= buffer[1]; + val <<= 8; + val |= buffer[0]; - aux_return_value = val & ((1 << p_bits_to_read) - 1); - val >>= p_bits_to_read; - source_remaining_bits -= p_bits_to_read; + aux_return_value = val & ((1 << p_bits_to_read) - 1); + val >>= p_bits_to_read; + source_remaining_bits -= p_bits_to_read; - buffer[3]=val>>24; - buffer[2]=(val>>16)&0xFF; - buffer[1]=(val>>8)&0xFF; - buffer[0]=(val)&0xFF; + buffer[3] = val >> 24; + buffer[2] = (val >> 16) & 0xFF; + buffer[1] = (val >> 8) & 0xFF; + buffer[0] = (val)&0xFF; - } else { - aux_return_value=buffer[3]; - aux_return_value<<=8; - aux_return_value|=buffer[2]; - aux_return_value<<=8; - aux_return_value|=buffer[1]; - aux_return_value<<=8; - aux_return_value|=buffer[0]; + } else { + aux_return_value = buffer[3]; + aux_return_value <<= 8; + aux_return_value |= buffer[2]; + aux_return_value <<= 8; + aux_return_value |= buffer[1]; + aux_return_value <<= 8; + aux_return_value |= buffer[0]; - uint32_t nbits = p_bits_to_read - source_remaining_bits; - source_position++; + uint32_t nbits = p_bits_to_read - source_remaining_bits; + source_position++; - buffer+=4; - val=buffer[3]; - val<<=8; - val|=buffer[2]; - val<<=8; - val|=buffer[1]; - val<<=8; - val|=buffer[0]; - aux_return_value |= ((val & ((1 << nbits) - 1)) << source_remaining_bits); - val >>= nbits; - source_remaining_bits = 32 - nbits; - buffer[3]=val>>24; - buffer[2]=(val>>16)&0xFF; - buffer[1]=(val>>8)&0xFF; - buffer[0]=(val)&0xFF; - - } + buffer += 4; + val = buffer[3]; + val <<= 8; + val |= buffer[2]; + val <<= 8; + val |= buffer[1]; + val <<= 8; + val |= buffer[0]; + aux_return_value |= ((val & ((1 << nbits) - 1)) << source_remaining_bits); + val >>= nbits; + source_remaining_bits = 32 - nbits; + buffer[3] = val >> 24; + buffer[2] = (val >> 16) & 0xFF; + buffer[1] = (val >> 8) & 0xFF; + buffer[0] = (val)&0xFF; + } - return aux_return_value; + return aux_return_value; } -bool CPLoader_IT::read_IT_compressed_block (bool p_16bits) { +bool CPLoader_IT::read_IT_compressed_block(bool p_16bits) { uint16_t size; - size=file->get_word(); + size = file->get_word(); if (file->eof_reached() || file->get_error()) return true; - pat_data = (uint8_t*)CP_ALLOC( 4* ((size >> 2) + 2) ); + pat_data = (uint8_t *)CP_ALLOC(4 * ((size >> 2) + 2)); if (!pat_data) return true; - - source_buffer=(uint32_t*)pat_data; - file->get_byte_array((uint8_t*)source_buffer,size); - + source_buffer = (uint32_t *)pat_data; + file->get_byte_array((uint8_t *)source_buffer, size); + if (file->eof_reached() || file->get_error()) { - + free_IT_compressed_block(); return true; } - + source_position = source_buffer; source_remaining_bits = 32; return false; } -void CPLoader_IT::free_IT_compressed_block () { - +void CPLoader_IT::free_IT_compressed_block() { if (pat_data) { CP_FREE(pat_data); - pat_data=NULL; + pat_data = NULL; } - } -bool CPLoader_IT::load_sample_8bits_IT_compressed(void *p_dest_buffer,int p_buffsize) { +bool CPLoader_IT::load_sample_8bits_IT_compressed(void *p_dest_buffer, int p_buffsize) { - int8_t *dest_buffer; /* destination buffer which will be returned */ - uint16_t block_length; /* length of compressed data block in samples */ - uint16_t block_position; /* position in block */ - uint8_t bit_width; /* actual "bit width" */ - uint16_t aux_value; /* value read from file to be processed */ - int8_t d1, d2; /* integrator buffers (d2 for it2.15) */ - int8_t *dest_position; /* position in output buffer */ - int8_t v; /* sample value */ + int8_t *dest_buffer; /* destination buffer which will be returned */ + uint16_t block_length; /* length of compressed data block in samples */ + uint16_t block_position; /* position in block */ + uint8_t bit_width; /* actual "bit width" */ + uint16_t aux_value; /* value read from file to be processed */ + int8_t d1, d2; /* integrator buffers (d2 for it2.15) */ + int8_t *dest_position; /* position in output buffer */ + int8_t v; /* sample value */ bool it215; // is this an it215 module? - dest_buffer = (int8_t *) p_dest_buffer; + dest_buffer = (int8_t *)p_dest_buffer; - if (dest_buffer==NULL) + if (dest_buffer == NULL) return true; - for (int i=0;i<p_buffsize;i++) - dest_buffer[i]=0; - + for (int i = 0; i < p_buffsize; i++) + dest_buffer[i] = 0; dest_position = dest_buffer; - it215=(header.cmwt==0x215); + it215 = (header.cmwt == 0x215); /* now unpack data till the dest buffer is full */ while (p_buffsize) { - /* read a new block of compressed data and reset variables */ - if ( read_IT_compressed_block(false) ) { + /* read a new block of compressed data and reset variables */ + if (read_IT_compressed_block(false)) { CP_PRINTERR("Out of memory decompressing IT CPSample"); return true; } - block_length = (p_buffsize < 0x8000) ? p_buffsize : 0x8000; block_position = 0; - bit_width = 9; /* start with width of 9 bits */ + bit_width = 9; /* start with width of 9 bits */ - d1 = d2 = 0; /* reset integrator buffers */ + d1 = d2 = 0; /* reset integrator buffers */ - /* now uncompress the data block */ - while ( block_position < block_length ) { + /* now uncompress the data block */ + while (block_position < block_length) { - aux_value = read_n_bits_from_IT_compressed_block(bit_width); /* read bits */ + aux_value = read_n_bits_from_IT_compressed_block(bit_width); /* read bits */ - if ( bit_width < 7 ) { /* method 1 (1-6 bits) */ + if (bit_width < 7) { /* method 1 (1-6 bits) */ - if ( aux_value == (1 << (bit_width - 1)) ) { /* check for "100..." */ + if (aux_value == (1 << (bit_width - 1))) { /* check for "100..." */ aux_value = read_n_bits_from_IT_compressed_block(3) + 1; /* yes -> read new width; */ - bit_width = (aux_value < bit_width) ? aux_value : aux_value + 1; - /* and expand it */ - continue; /* ... next value */ + bit_width = (aux_value < bit_width) ? aux_value : aux_value + 1; + /* and expand it */ + continue; /* ... next value */ } - } else if ( bit_width < 9 ) { /* method 2 (7-8 bits) */ + } else if (bit_width < 9) { /* method 2 (7-8 bits) */ uint8_t border = (0xFF >> (9 - bit_width)) - 4; - /* lower border for width chg */ + /* lower border for width chg */ - if ( aux_value > border && aux_value <= (border + 8) ) { + if (aux_value > border && aux_value <= (border + 8)) { aux_value -= border; /* convert width to 1-8 */ bit_width = (aux_value < bit_width) ? aux_value : aux_value + 1; - /* and expand it */ - continue; /* ... next value */ + /* and expand it */ + continue; /* ... next value */ } + } else if (bit_width == 9) { /* method 3 (9 bits) */ - } else if ( bit_width == 9 ) { /* method 3 (9 bits) */ + if (aux_value & 0x100) { /* bit 8 set? */ - if ( aux_value & 0x100 ) { /* bit 8 set? */ - - bit_width = (aux_value + 1) & 0xff; /* new width... */ - continue; /* ... and next value */ + bit_width = (aux_value + 1) & 0xff; /* new width... */ + continue; /* ... and next value */ } } else { /* illegal width, abort */ - free_IT_compressed_block(); CP_PRINTERR("CPSample has illegal BitWidth "); return true; } /* now expand value to signed byte */ - if ( bit_width < 8 ) { + if (bit_width < 8) { uint8_t tmp_shift = 8 - bit_width; - v=(aux_value << tmp_shift); - v>>=tmp_shift; + v = (aux_value << tmp_shift); + v >>= tmp_shift; - } else v = (int8_t) aux_value; + } else + v = (int8_t)aux_value; /* integrate upon the sample values */ d1 += v; - d2 += d1; + d2 += d1; /* ... and store it into the buffer */ *(dest_position++) = it215 ? d2 : d1; block_position++; - } /* now subtract block lenght from total length and go on */ @@ -496,85 +470,81 @@ bool CPLoader_IT::load_sample_8bits_IT_compressed(void *p_dest_buffer,int p_buff p_buffsize -= block_length; } - return false; } -bool CPLoader_IT::load_sample_16bits_IT_compressed(void *p_dest_buffer,int p_buffsize) { +bool CPLoader_IT::load_sample_16bits_IT_compressed(void *p_dest_buffer, int p_buffsize) { - int16_t *dest_buffer; /* destination buffer which will be returned */ - uint16_t block_length; /* length of compressed data block in samples */ - uint16_t block_position; /* position in block */ - uint8_t bit_width; /* actual "bit width" */ - uint32_t aux_value; /* value read from file to be processed */ - int16_t d1, d2; /* integrator buffers (d2 for it2.15) */ - int16_t *dest_position; /* position in output buffer */ - int16_t v; /* sample value */ + int16_t *dest_buffer; /* destination buffer which will be returned */ + uint16_t block_length; /* length of compressed data block in samples */ + uint16_t block_position; /* position in block */ + uint8_t bit_width; /* actual "bit width" */ + uint32_t aux_value; /* value read from file to be processed */ + int16_t d1, d2; /* integrator buffers (d2 for it2.15) */ + int16_t *dest_position; /* position in output buffer */ + int16_t v; /* sample value */ bool it215; // is this an it215 module? - dest_buffer = (int16_t *) p_dest_buffer; + dest_buffer = (int16_t *)p_dest_buffer; - if (dest_buffer==NULL) + if (dest_buffer == NULL) return true; - for (int i=0;i<p_buffsize;i++) - dest_buffer[i]=0; + for (int i = 0; i < p_buffsize; i++) + dest_buffer[i] = 0; dest_position = dest_buffer; - it215=(header.cmwt==0x215); - + it215 = (header.cmwt == 0x215); while (p_buffsize) { - /* read a new block of compressed data and reset variables */ - if ( read_IT_compressed_block(true) ) { + /* read a new block of compressed data and reset variables */ + if (read_IT_compressed_block(true)) { return true; } - block_length = (p_buffsize < 0x4000) ? p_buffsize : 0x4000; block_position = 0; - bit_width = 17; /* start with width of 9 bits */ + bit_width = 17; /* start with width of 9 bits */ - d1 = d2 = 0; /* reset integrator buffers */ + d1 = d2 = 0; /* reset integrator buffers */ - while ( block_position < block_length ) { + while (block_position < block_length) { - aux_value = read_n_bits_from_IT_compressed_block(bit_width); /* read bits */ + aux_value = read_n_bits_from_IT_compressed_block(bit_width); /* read bits */ - if ( bit_width < 7 ) { /* method 1 (1-6 bits) */ + if (bit_width < 7) { /* method 1 (1-6 bits) */ - if ( (signed)aux_value == (1 << (bit_width - 1)) ) { /* check for "100..." */ + if ((signed)aux_value == (1 << (bit_width - 1))) { /* check for "100..." */ aux_value = read_n_bits_from_IT_compressed_block(4) + 1; /* yes -> read new width; */ - bit_width = (aux_value < bit_width) ? aux_value : aux_value + 1; - /* and expand it */ - continue; /* ... next value */ + bit_width = (aux_value < bit_width) ? aux_value : aux_value + 1; + /* and expand it */ + continue; /* ... next value */ } - } else if ( bit_width < 17 ) { + } else if (bit_width < 17) { uint16_t border = (0xFFFF >> (17 - bit_width)) - 8; - if ( (int)aux_value > (int)border && (int)aux_value <= ((int)border + 16) ) { + if ((int)aux_value > (int)border && (int)aux_value <= ((int)border + 16)) { aux_value -= border; /* convert width to 1-8 */ bit_width = (aux_value < bit_width) ? aux_value : aux_value + 1; - /* and expand it */ - continue; /* ... next value */ + /* and expand it */ + continue; /* ... next value */ } + } else if (bit_width == 17) { - } else if ( bit_width == 17 ) { - - if ( aux_value & 0x10000 ) { /* bit 8 set? */ + if (aux_value & 0x10000) { /* bit 8 set? */ - bit_width = (aux_value + 1) & 0xff; /* new width... */ - continue; /* ... and next value */ + bit_width = (aux_value + 1) & 0xff; /* new width... */ + continue; /* ... and next value */ } } else { /* illegal width, abort */ @@ -582,28 +552,28 @@ bool CPLoader_IT::load_sample_16bits_IT_compressed(void *p_dest_buffer,int p_buf CP_PRINTERR("CPSample has illegal BitWidth "); free_IT_compressed_block(); - + return true; } /* now expand value to signed byte */ - if ( bit_width < 16 ) { + if (bit_width < 16) { uint8_t tmp_shift = 16 - bit_width; - v=(aux_value << tmp_shift); - v>>=tmp_shift; + v = (aux_value << tmp_shift); + v >>= tmp_shift; - } else v = (int16_t) aux_value; + } else + v = (int16_t)aux_value; /* integrate upon the sample values */ d1 += v; - d2 += d1; + d2 += d1; /* ... and store it into the buffer */ *(dest_position++) = it215 ? d2 : d1; block_position++; - } /* now subtract block lenght from total length and go on */ @@ -611,10 +581,5 @@ bool CPLoader_IT::load_sample_16bits_IT_compressed(void *p_dest_buffer,int p_buf p_buffsize -= block_length; } - return false; - } - - - diff --git a/modules/chibi/cp_loader_mod.cpp b/modules/chibi/cp_loader_mod.cpp index 4a47ce5c4..68d1bb2fc 100644 --- a/modules/chibi/cp_loader_mod.cpp +++ b/modules/chibi/cp_loader_mod.cpp @@ -28,455 +28,427 @@ /*************************************************************************/ #include "cp_loader_mod.h" - static bool tag_equal_to(const char *p_tag, const char *p_string) { - return( p_tag[0]==p_string[0] && - p_tag[1]==p_string[1] && - p_tag[2]==p_string[2] && - p_tag[3]==p_string[3]); + return (p_tag[0] == p_string[0] && + p_tag[1] == p_string[1] && + p_tag[2] == p_string[2] && + p_tag[3] == p_string[3]); } /* ProTracker period table */ -uint16_t period_table[6*12] = { - 1712,1616,1524,1440,1356,1280,1208,1140,1076,1016,960,907, - 856,808,762,720,678,640,604,570,538,508,480,453, - 428,404,381,360,339,320,302,285,269,254,240,226, - 214,202,190,180,170,160,151,143,135,127,120,113, - 107,101,95,90,85,80,75,71,67,63,60,56, - 53,50,47,45,42,40,37,35,33,31,30,28 +uint16_t period_table[6 * 12] = { + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 907, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, + 53, 50, 47, 45, 42, 40, 37, 35, 33, 31, 30, 28 }; +CPLoader::Error CPLoader_MOD::load_song(const char *p_file, CPSong *p_song, bool p_sampleset) { -CPLoader::Error CPLoader_MOD::load_song(const char *p_file,CPSong *p_song,bool p_sampleset) { - - if (file->open(p_file,CPFileAccessWrapper::READ)) { - //printf("Can't open file! %s\n",p_file); + if (file->open(p_file, CPFileAccessWrapper::READ)) { + //printf("Can't open file! %s\n",p_file); return FILE_CANNOT_OPEN; }; /* FIRST OF ALL, one needs to read the .mod file format tag */ - file->seek( 1080 ); //located at 1080 - + file->seek(1080); //located at 1080 + char format_tag[4]; - - file->get_byte_array( (uint8_t*)format_tag, 4 ); - - int channels=-1; - + + file->get_byte_array((uint8_t *)format_tag, 4); + + int channels = -1; + /** THE PAIN!! - COMPARE TAGS */ - + /* Classic 4-chan */ - if (tag_equal_to(format_tag,"M.K.") ) - channels=4; - if (tag_equal_to(format_tag,"FLT4") ) - channels=4; - if (tag_equal_to(format_tag,"M!K!") ) - channels=4; - + if (tag_equal_to(format_tag, "M.K.")) + channels = 4; + if (tag_equal_to(format_tag, "FLT4")) + channels = 4; + if (tag_equal_to(format_tag, "M!K!")) + channels = 4; + /* 8 Channel MODS */ - - if (tag_equal_to(format_tag,"FLT8") ) - channels=2; - - if (tag_equal_to(format_tag,"CD81") ) - channels=2; - + + if (tag_equal_to(format_tag, "FLT8")) + channels = 2; + + if (tag_equal_to(format_tag, "CD81")) + channels = 2; + /* Custom channel MODS */ - - for (int i=1;i<=32;i++) { - - if (i<10) { // up to 9 channels mods - + + for (int i = 1; i <= 32; i++) { + + if (i < 10) { // up to 9 channels mods + /* Old Take Tracker */ - char old_take_tracker[4]={'T','D','Z',char('0'+i)}; - - if (tag_equal_to(format_tag,old_take_tracker)) { - - channels=i; + char old_take_tracker[4] = { 'T', 'D', 'Z', char('0' + i) }; + + if (tag_equal_to(format_tag, old_take_tracker)) { + + channels = i; break; } - + /* Contemplates many XCHN Formats */ - char xchn[4]={char('0'+i),'C','H','N'}; - - if (tag_equal_to(format_tag,xchn)) { - - channels=i; + char xchn[4] = { char('0' + i), 'C', 'H', 'N' }; + + if (tag_equal_to(format_tag, xchn)) { + + channels = i; break; } } - + /* Fast Tracker */ - char fast_tracker[4]={char('0'+(i/10)),char('0'+(i%10)),'C','H'}; - - if (tag_equal_to(format_tag,fast_tracker)) { - - channels=i; + char fast_tracker[4] = { char('0' + (i / 10)), char('0' + (i % 10)), 'C', 'H' }; + + if (tag_equal_to(format_tag, fast_tracker)) { + + channels = i; break; } - } - - - if (channels==-1) { - + + if (channels == -1) { + file->close(); return FILE_UNRECOGNIZED; } - - - + /** Load CPSong INFO */ - - file->seek( 0 ); //go to begining of file - - file->set_endian_conversion( true ); + + file->seek(0); //go to begining of file + + file->set_endian_conversion(true); p_song->reset(); - p_song->set_instruments( false ); - + p_song->set_instruments(false); + char name[21]; - - file->get_byte_array( (uint8_t*)name,20); - name[20]=0; - + + file->get_byte_array((uint8_t *)name, 20); + name[20] = 0; + p_song->set_name(name); - p_song->set_old_effects( true ); - p_song->set_linear_slides( false ); - p_song->set_compatible_gxx( true ); - - - - CPSampleManager *sm=CPSampleManager::get_singleton(); - - int instruments=31; - - for (int i=0;i<instruments;i++) { - + p_song->set_old_effects(true); + p_song->set_linear_slides(false); + p_song->set_compatible_gxx(true); + + CPSampleManager *sm = CPSampleManager::get_singleton(); + + int instruments = 31; + + for (int i = 0; i < instruments; i++) { + char sample_name[23]; - file->get_byte_array( (uint8_t*)sample_name,22); - sample_name[22]=0; - - uint32_t sample_len=file->get_word(); - sample_len<<=1; - - uint8_t fine_nibble=file->get_byte()&0xF; - - + file->get_byte_array((uint8_t *)sample_name, 22); + sample_name[22] = 0; + + uint32_t sample_len = file->get_word(); + sample_len <<= 1; + + uint8_t fine_nibble = file->get_byte() & 0xF; + //(int8_t)(fine_nibble & 7) - (int8_t)(fine_nibble & 8); //yesso's genius trick // boo, I can't use it :( but i leave it here because of how cool it is - uint8_t linear_volume=file->get_byte(); //0 .. ? - - uint32_t loop_begin=file->get_word(); //0 .. ? - loop_begin<<=1; - uint32_t loop_end=file->get_word(); //0 .. ? - loop_end<<=1; - - if (sample_len>0) { - - CPSample_ID sid=sm->create( false, false, sample_len ); - + uint8_t linear_volume = file->get_byte(); //0 .. ? + + uint32_t loop_begin = file->get_word(); //0 .. ? + loop_begin <<= 1; + uint32_t loop_end = file->get_word(); //0 .. ? + loop_end <<= 1; + + if (sample_len > 0) { + + CPSample_ID sid = sm->create(false, false, sample_len); + if (sid.is_null()) { - + file->close(); return FILE_OUT_OF_MEMORY; } - - if (loop_end>2) { - sm->set_loop_begin( sid, loop_begin ); - sm->set_loop_end( sid, loop_end+loop_begin ); - sm->set_loop_type( sid,CP_LOOP_FORWARD ); + + if (loop_end > 2) { + sm->set_loop_begin(sid, loop_begin); + sm->set_loop_end(sid, loop_end + loop_begin); + sm->set_loop_type(sid, CP_LOOP_FORWARD); } - static const uint16_t fine_to_freq[16]={ - 8363,8413,8463,8529,8581,8651,8723,8757, - 7895,7941,7985,8046,8107,8169,8232,8280 + static const uint16_t fine_to_freq[16] = { + 8363, 8413, 8463, 8529, 8581, 8651, 8723, 8757, + 7895, 7941, 7985, 8046, 8107, 8169, 8232, 8280 }; - - sm->set_c5_freq( sid, fine_to_freq[fine_nibble] ); + + sm->set_c5_freq(sid, fine_to_freq[fine_nibble]); p_song->get_sample(i)->set_sample_data(sid); } - + p_song->get_sample(i)->set_name(sample_name); - p_song->get_sample(i)->set_default_volume( linear_volume ); - - - + p_song->get_sample(i)->set_default_volume(linear_volume); } - + /* pan for MODs */ - for (int i=0;i<channels;i++) - p_song->set_channel_pan( i, (((i&3)==1) || ((i&3)==2)) ? 0: 64); + for (int i = 0; i < channels; i++) + p_song->set_channel_pan(i, (((i & 3) == 1) || ((i & 3) == 2)) ? 0 : 64); + + uint8_t order_count = file->get_byte(); + // uint8_t loop_to=file->get_byte(); + + int pattern_count = 0; + + for (int i = 0; i < 128; i++) { + + uint8_t order = file->get_byte(); + + if (i < order_count) { + p_song->set_order(i, order); - - uint8_t order_count=file->get_byte(); -// uint8_t loop_to=file->get_byte(); - - - int pattern_count=0; - - for (int i=0;i<128;i++) { - - uint8_t order=file->get_byte(); - - - if (i<order_count) { - p_song->set_order(i,order); - /* Determine the amount of patterns */ - if ((order+1)>pattern_count) - pattern_count=order+1; + if ((order + 1) > pattern_count) + pattern_count = order + 1; } else - p_song->set_order( i, CP_ORDER_NONE ); + p_song->set_order(i, CP_ORDER_NONE); } - - if (instruments==31) + + if (instruments == 31) file->get_dword(); // identiefier, now skip it - - for (int i=0;i<pattern_count;i++) { - - for(int line=0;line<64;line++) { - - for(int column=0;column<channels;column++) { - - uint32_t note_w=file->get_dword(); - + + for (int i = 0; i < pattern_count; i++) { + + for (int line = 0; line < 64; line++) { + + for (int column = 0; column < channels; column++) { + + uint32_t note_w = file->get_dword(); + CPNote note; - - note.instrument=(note_w>>12)&0xF; - note.instrument|=(note_w>>24)&0xF0; - - if (note.instrument==0) - note.instrument=CPNote::EMPTY; + + note.instrument = (note_w >> 12) & 0xF; + note.instrument |= (note_w >> 24) & 0xF0; + + if (note.instrument == 0) + note.instrument = CPNote::EMPTY; else note.instrument--; - - note.parameter=note_w&0xFF; - - int cmd=(note_w>>8)&0xF; - - uint32_t period=(note_w>>16)&0xFFF; - - if (period>0 && period<0xFFF) { - + + note.parameter = note_w & 0xFF; + + int cmd = (note_w >> 8) & 0xF; + + uint32_t period = (note_w >> 16) & 0xFFF; + + if (period > 0 && period < 0xFFF) { + //period>>=2; //period<<=1; - for (int n=0; n<6*12; n++) { - + for (int n = 0; n < 6 * 12; n++) { + if (period >= period_table[n]) { - - if ((period!=period_table[n]) && (n)) - { - uint32_t p1 = period_table[n-1]; + + if ((period != period_table[n]) && (n)) { + uint32_t p1 = period_table[n - 1]; uint32_t p2 = period_table[n]; if (p1 - period < (period - p2)) { - - note.note=n+36; + + note.note = n + 36; break; } } - note.note=n+1+36; + note.note = n + 1 + 36; break; } } - if (note.note==CPNote::EMPTY) - note.note=6*12+36; - + if (note.note == CPNote::EMPTY) + note.note = 6 * 12 + 36; + note.note--; - } - - - switch(cmd) { - + } + + switch (cmd) { + case 0x0: { - - if (note.parameter>0) - note.command='J'-'A'; + + if (note.parameter > 0) + note.command = 'J' - 'A'; } break; case 0x1: { - note.command='F'-'A'; + note.command = 'F' - 'A'; } break; case 0x2: { - - note.command='E'-'A'; + + note.command = 'E' - 'A'; } break; case 0x3: { - - note.command='G'-'A'; + + note.command = 'G' - 'A'; } break; case 0x4: { - - note.command='H'-'A'; + + note.command = 'H' - 'A'; } break; case 0x5: { - note.command='L'-'A'; + note.command = 'L' - 'A'; } break; case 0x6: { - - note.command='K'-'A'; + + note.command = 'K' - 'A'; } break; case 0x7: { - note.command='R'-'A'; + note.command = 'R' - 'A'; } break; case 0x8: { - - note.command='X'-'A'; + + note.command = 'X' - 'A'; } break; case 0x9: { - - note.command='O'-'A'; - + + note.command = 'O' - 'A'; + } break; case 0xA: { - - note.command='D'-'A'; - + + note.command = 'D' - 'A'; + } break; case 0xB: { - - note.command='B'-'A'; - + + note.command = 'B' - 'A'; + } break; case 0xC: { - - note.volume=note.parameter; - if (note.volume>64) - note.volume=64; - note.parameter=0; - + + note.volume = note.parameter; + if (note.volume > 64) + note.volume = 64; + note.parameter = 0; + } break; case 0xD: { - - note.command='C'-'A'; - note.parameter=(note.parameter>>4)*10 + (note.parameter&0xF); - + + note.command = 'C' - 'A'; + note.parameter = (note.parameter >> 4) * 10 + (note.parameter & 0xF); + } break; case 0xE: { //SPECIAL EFFECT! - - note.command='S'-'A'; - - switch(note.parameter>>4) { - + + note.command = 'S' - 'A'; + + switch (note.parameter >> 4) { + case 0x1: { - - note.command='F'-'A'; - note.parameter=0xF0|(note.parameter&0xF); + + note.command = 'F' - 'A'; + note.parameter = 0xF0 | (note.parameter & 0xF); } break; case 0x2: { - - note.command='E'-'A'; - note.parameter=0xF0|(note.parameter&0xF); + + note.command = 'E' - 'A'; + note.parameter = 0xF0 | (note.parameter & 0xF); } break; case 0x4: { - - note.command='S'-'A'; - note.parameter=0x30|(note.parameter&0x3); - + + note.command = 'S' - 'A'; + note.parameter = 0x30 | (note.parameter & 0x3); + } break; case 0x6: { - - note.command='S'-'A'; - note.parameter=0xB0|(note.parameter&0xF); - + + note.command = 'S' - 'A'; + note.parameter = 0xB0 | (note.parameter & 0xF); + } break; case 0x7: { - note.command='S'-'A'; - note.parameter=0x40|(note.parameter&0x3); - + note.command = 'S' - 'A'; + note.parameter = 0x40 | (note.parameter & 0x3); + } break; case 0x8: { - - note.command='S'-'A'; // wow, it's the same! - + + note.command = 'S' - 'A'; // wow, it's the same! + } break; case 0x9: { - note.command='Q'-'A'; - note.parameter=(note.parameter&0xF); - + note.command = 'Q' - 'A'; + note.parameter = (note.parameter & 0xF); + } break; case 0xA: { - - note.command='D'-'A'; - note.parameter=0xF|((note.parameter&0xF)<<4); - + + note.command = 'D' - 'A'; + note.parameter = 0xF | ((note.parameter & 0xF) << 4); + } break; case 0xB: { - note.command='D'-'A'; - note.parameter=0xF0|(note.parameter&0xF); - + note.command = 'D' - 'A'; + note.parameter = 0xF0 | (note.parameter & 0xF); + } break; case 0xC: case 0xD: { - - note.command='S'-'A'; //wow, they are the same! - + + note.command = 'S' - 'A'; //wow, they are the same! + } break; case 0xE: { - note.command='S'-'A'; - note.parameter=0x60|(note.parameter&0xF); - + note.command = 'S' - 'A'; + note.parameter = 0x60 | (note.parameter & 0xF); + } break; - + default: { - - note.command=CPNote::EMPTY; - note.parameter=0; + + note.command = CPNote::EMPTY; + note.parameter = 0; } break; - } } break; case 0xF: { - - if (note.parameter<32) - note.command='A'-'A'; + + if (note.parameter < 32) + note.command = 'A' - 'A'; else - note.command='T'-'A'; - + note.command = 'T' - 'A'; + } break; } - - p_song->get_pattern(i)->set_note( column,line, note ); + + p_song->get_pattern(i)->set_note(column, line, note); } } } - - - - for (int i=0;i<instruments;i++) { - - CPSample_ID sid=p_song->get_sample(i)->get_sample_data(); + + for (int i = 0; i < instruments; i++) { + + CPSample_ID sid = p_song->get_sample(i)->get_sample_data(); if (sid.is_null()) { continue; //empty sample, not stored? } sm->lock_data(sid); - uint8_t *dataptr = (uint8_t*)sm->get_data(sid); + uint8_t *dataptr = (uint8_t *)sm->get_data(sid); - int len=sm->get_size(sid); - for (int s=0;s<len;s++) { - - uint8_t d=file->get_byte(); + int len = sm->get_size(sid); + for (int s = 0; s < len; s++) { + + uint8_t d = file->get_byte(); //d-=128; //convert to signed - int8_t*ds=(int8_t*)&d; - dataptr[s]=*ds; - + int8_t *ds = (int8_t *)&d; + dataptr[s] = *ds; } sm->unlock_data(sid); } - + file->close(); - - return FILE_OK; - + return FILE_OK; } - CPLoader_MOD::CPLoader_MOD(CPFileAccessWrapper *p_file) { - - file=p_file; -} - -CPLoader_MOD::~CPLoader_MOD() -{ + file = p_file; } - +CPLoader_MOD::~CPLoader_MOD() { +} diff --git a/modules/chibi/cp_loader_mod.h b/modules/chibi/cp_loader_mod.h index 57f7128bc..00e5adc86 100644 --- a/modules/chibi/cp_loader_mod.h +++ b/modules/chibi/cp_loader_mod.h @@ -35,16 +35,16 @@ class CPLoader_MOD : public CPLoader { CPFileAccessWrapper *file; -public: +public: bool can_load_song() { return true; } bool can_load_sample() { return false; } bool can_load_instrument() { return false; } - - Error load_song(const char *p_file,CPSong *p_song,bool p_sampleset); - Error load_sample(const char *p_file,CPSample *p_sample) { return FILE_UNRECOGNIZED; } - Error load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx) { return FILE_UNRECOGNIZED; } - + + Error load_song(const char *p_file, CPSong *p_song, bool p_sampleset); + Error load_sample(const char *p_file, CPSample *p_sample) { return FILE_UNRECOGNIZED; } + Error load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx) { return FILE_UNRECOGNIZED; } + CPLoader_MOD(CPFileAccessWrapper *p_file); ~CPLoader_MOD(); }; diff --git a/modules/chibi/cp_loader_s3m.cpp b/modules/chibi/cp_loader_s3m.cpp index eb5fad12e..c54e0c395 100644 --- a/modules/chibi/cp_loader_s3m.cpp +++ b/modules/chibi/cp_loader_s3m.cpp @@ -29,305 +29,276 @@ #include "cp_loader_s3m.h" -#define BITBOOL(m_exp) ((m_exp)?1:0) - +#define BITBOOL(m_exp) ((m_exp) ? 1 : 0) CPLoader::Error CPLoader_S3M::load_header() { int i; - - file->get_byte_array((uint8_t*)header.songname,28); - header.t1a=file->get_byte(); - header.type=file->get_byte(); - file->get_byte_array((uint8_t*)header.unused1,2); - header.ordnum=file->get_word(); - header.insnum=file->get_word(); - header.patnum=file->get_word(); - header.flags=file->get_word(); - header.tracker=file->get_word(); - header.fileformat=file->get_word(); - file->get_byte_array((uint8_t*)header.scrm,4); - header.scrm[4]=0; - - if (header.scrm[0]!='S' || header.scrm[1]!='C' || header.scrm[2]!='R' || header.scrm[3]!='M') + file->get_byte_array((uint8_t *)header.songname, 28); + header.t1a = file->get_byte(); + header.type = file->get_byte(); + file->get_byte_array((uint8_t *)header.unused1, 2); + header.ordnum = file->get_word(); + header.insnum = file->get_word(); + header.patnum = file->get_word(); + header.flags = file->get_word(); + header.tracker = file->get_word(); + header.fileformat = file->get_word(); + file->get_byte_array((uint8_t *)header.scrm, 4); + header.scrm[4] = 0; + + if (header.scrm[0] != 'S' || header.scrm[1] != 'C' || header.scrm[2] != 'R' || header.scrm[3] != 'M') return FILE_UNRECOGNIZED; - header.mastervol=file->get_byte(); - header.initspeed=file->get_byte(); - header.inittempo=file->get_byte(); - header.mastermult=file->get_byte(); - header.ultraclick=file->get_byte(); - header.pantable=file->get_byte(); - file->get_byte_array((uint8_t*)header.unused2,8); - header.special=file->get_word(); - file->get_byte_array((uint8_t*)header.channels,32); + header.mastervol = file->get_byte(); + header.initspeed = file->get_byte(); + header.inittempo = file->get_byte(); + header.mastermult = file->get_byte(); + header.ultraclick = file->get_byte(); + header.pantable = file->get_byte(); + file->get_byte_array((uint8_t *)header.unused2, 8); + header.special = file->get_word(); + file->get_byte_array((uint8_t *)header.channels, 32); - file->get_byte_array((uint8_t*)header.orderlist,header.ordnum); + file->get_byte_array((uint8_t *)header.orderlist, header.ordnum); - header.scrm[4]=0; - if (header.scrm[0]!='S' || header.scrm[1]!='C' || header.scrm[2]!='R' || header.scrm[3]!='M') //again? + header.scrm[4] = 0; + if (header.scrm[0] != 'S' || header.scrm[1] != 'C' || header.scrm[2] != 'R' || header.scrm[3] != 'M') //again? return FILE_UNRECOGNIZED; //sample parapointers - for (i=0;i<header.insnum;i++) { + for (i = 0; i < header.insnum; i++) { int parapointer; - parapointer=file->get_word(); - parapointer=(parapointer*16); - sample_parapointers[i]=parapointer; + parapointer = file->get_word(); + parapointer = (parapointer * 16); + sample_parapointers[i] = parapointer; } //pattern - for (i=0;i<header.patnum;i++) { + for (i = 0; i < header.patnum; i++) { int parapointer; - parapointer=file->get_word(); - parapointer=(parapointer*16); - pattern_parapointers[i]=parapointer; + parapointer = file->get_word(); + parapointer = (parapointer * 16); + pattern_parapointers[i] = parapointer; } - if (header.pantable==252) { + if (header.pantable == 252) { - file->get_byte_array((uint8_t*)header.pannings,32); + file->get_byte_array((uint8_t *)header.pannings, 32); } return FILE_OK; - - } - void CPLoader_S3M::set_header() { - - + song->set_name(header.songname); + // song->variables.filename= - song->set_name( header.songname ); -// song->variables.filename= - - song->set_row_highlight_minor( 4 ); - song->set_row_highlight_major( 16 ); - song->set_mixing_volume( header.mastervol ); - song->set_linear_slides( false ); - song->set_old_effects( !(header.flags&64) ); - song->set_compatible_gxx( true ); + song->set_row_highlight_minor(4); + song->set_row_highlight_major(16); + song->set_mixing_volume(header.mastervol); + song->set_linear_slides(false); + song->set_old_effects(!(header.flags & 64)); + song->set_compatible_gxx(true); - song->set_global_volume( header.mastermult ); - song->set_speed( header.initspeed ); - song->set_tempo( header.inittempo ); + song->set_global_volume(header.mastermult); + song->set_speed(header.initspeed); + song->set_tempo(header.inittempo); //[TODO] Set Panning Positions.. ? - for (int i=0;i<header.ordnum;i++) song->set_order(i,header.orderlist[i]); - + for (int i = 0; i < header.ordnum; i++) + song->set_order(i, header.orderlist[i]); } -CPLoader::Error CPLoader_S3M::load_sample(CPSample *p_sample) { +CPLoader::Error CPLoader_S3M::load_sample(CPSample *p_sample) { + int type = file->get_byte(); + char filename[13]; + file->get_byte_array((uint8_t *)filename, 12); + filename[12] = 0; - int type=file->get_byte(); - - char filename[13]; - file->get_byte_array((uint8_t*)filename,12); - filename[12]=0; - - - uint32_t samplepos=(uint32_t)file->get_byte() << 16; - samplepos|=file->get_word(); - samplepos*=16; -// printf("sample at %i\n",samplepos); - /**/ - int sample_size=file->get_dword(); - - - int loop_begin=file->get_dword(); - int loop_end=file->get_dword(); + uint32_t samplepos = (uint32_t)file->get_byte() << 16; + samplepos |= file->get_word(); + samplepos *= 16; + // printf("sample at %i\n",samplepos); + /**/ + int sample_size = file->get_dword(); - int def_volume=file->get_byte();; - int dsk=file->get_byte(); - int pack=file->get_byte(); - - int flags=file->get_byte(); - int c2speed=file->get_dword(); - - file->get_dword(); //useless crap - file->get_dword(); - file->get_dword(); - - - char name[29]; - file->get_byte_array((uint8_t*)name,28); - name[28]=0; - - p_sample->set_default_volume(def_volume); - p_sample->set_name(name); - - char scrs[5]; - file->get_byte_array((uint8_t*)scrs,4); - scrs[4]=0; + int loop_begin = file->get_dword(); + int loop_end = file->get_dword(); - + int def_volume = file->get_byte(); + ; + int dsk = file->get_byte(); + int pack = file->get_byte(); - bool data_is_16bits=flags&4; - bool data_is_stereo=flags&2; + int flags = file->get_byte(); + int c2speed = file->get_dword(); - if (type==0) { - //empty sample - return FILE_OK; - } - + file->get_dword(); //useless crap + file->get_dword(); + file->get_dword(); - if ((type!=1) || scrs[0]!='S' || scrs[1]!='C' || scrs[2]!='R' || scrs[3]!='S' ) { -// printf("type: %i, %c%c%c%c\n",type,scrs[0],scrs[1],scrs[2],scrs[3]); - CP_PRINTERR("Not an S3M CPSample!"); - return FILE_CORRUPTED; - } + char name[29]; + file->get_byte_array((uint8_t *)name, 28); + name[28] = 0; - //p_sample->data.set_c5_freq(p_sample->c2spd<<1); + p_sample->set_default_volume(def_volume); + p_sample->set_name(name); - file->seek(samplepos); + char scrs[5]; + file->get_byte_array((uint8_t *)scrs, 4); + scrs[4] = 0; - int real_sample_size=sample_size<<BITBOOL(data_is_16bits); - real_sample_size<<=BITBOOL(data_is_stereo); + bool data_is_16bits = flags & 4; + bool data_is_stereo = flags & 2; - CPSampleManager *sm=CPSampleManager::get_singleton(); - - CPSample_ID id =sm->create( data_is_16bits, data_is_stereo, sample_size ); - - if (id.is_null()) - return FILE_OUT_OF_MEMORY; + if (type == 0) { + //empty sample + return FILE_OK; + } - sm->lock_data(id); - void *dataptr = sm->get_data(id); - - int chans = (data_is_stereo?2:1); - for (int c=0;c<chans;c++) { - for (int i=0;i<sample_size;i++) { - - if (data_is_16bits) { - - uint16_t s=file->get_word(); - s-=32768; //toggle sign - - int16_t *v=(int16_t*)&s; - ((int16_t*)dataptr)[i*chans+c]=*v; - } else { - - - int8_t *v; - uint8_t s=file->get_byte(); - s-=128; //toggle sign - v=(int8_t*)&s; - ((int8_t*)dataptr)[i*chans+c]=*v; + if ((type != 1) || scrs[0] != 'S' || scrs[1] != 'C' || scrs[2] != 'R' || scrs[3] != 'S') { + // printf("type: %i, %c%c%c%c\n",type,scrs[0],scrs[1],scrs[2],scrs[3]); + CP_PRINTERR("Not an S3M CPSample!"); + return FILE_CORRUPTED; + } - } + //p_sample->data.set_c5_freq(p_sample->c2spd<<1); - } - - } + file->seek(samplepos); + + int real_sample_size = sample_size << BITBOOL(data_is_16bits); + real_sample_size <<= BITBOOL(data_is_stereo); - sm->unlock_data(id); + CPSampleManager *sm = CPSampleManager::get_singleton(); - - sm->set_loop_begin( id, loop_begin ); - sm->set_loop_end( id, loop_end ); - sm->set_loop_type( id, (flags&1) ? CP_LOOP_FORWARD : CP_LOOP_NONE ); - sm->set_c5_freq( id, c2speed << 1 ); - p_sample->set_sample_data(id); - - /* Scream tracker previous to 3.10 seems to be buggy, as in, wont save what is after the sample loop, including the loop end point. Because of this I must fix it by habd */ - if (flags&1) { - - for (int c=0;c<(data_is_stereo?2:1);c++) { - sm->set_data( id, loop_end, sm->get_data( id, loop_begin,c ),c ); - + CPSample_ID id = sm->create(data_is_16bits, data_is_stereo, sample_size); + + if (id.is_null()) + return FILE_OUT_OF_MEMORY; + + sm->lock_data(id); + void *dataptr = sm->get_data(id); + + int chans = (data_is_stereo ? 2 : 1); + for (int c = 0; c < chans; c++) { + for (int i = 0; i < sample_size; i++) { + + if (data_is_16bits) { + + uint16_t s = file->get_word(); + s -= 32768; //toggle sign + + int16_t *v = (int16_t *)&s; + ((int16_t *)dataptr)[i * chans + c] = *v; + } else { + + int8_t *v; + uint8_t s = file->get_byte(); + s -= 128; //toggle sign + v = (int8_t *)&s; + ((int8_t *)dataptr)[i * chans + c] = *v; } } - + } - return FILE_OK; + sm->unlock_data(id); -} + sm->set_loop_begin(id, loop_begin); + sm->set_loop_end(id, loop_end); + sm->set_loop_type(id, (flags & 1) ? CP_LOOP_FORWARD : CP_LOOP_NONE); + sm->set_c5_freq(id, c2speed << 1); + p_sample->set_sample_data(id); + /* Scream tracker previous to 3.10 seems to be buggy, as in, wont save what is after the sample loop, including the loop end point. Because of this I must fix it by habd */ + if (flags & 1) { + + for (int c = 0; c < (data_is_stereo ? 2 : 1); c++) { + sm->set_data(id, loop_end, sm->get_data(id, loop_begin, c), c); + } + } + + return FILE_OK; +} CPLoader::Error CPLoader_S3M::load_pattern(CPPattern *p_pattern) { - int row=0,flag,ch; + int row = 0, flag, ch; CPNote n; - int length,accum=0; + int length, accum = 0; - length=file->get_word(); - p_pattern->set_length(64); + length = file->get_word(); + p_pattern->set_length(64); - /* clear pattern data */ - while((row<64) && (accum<=length) ) { - flag=file->get_byte(); + /* clear pattern data */ + while ((row < 64) && (accum <= length)) { + flag = file->get_byte(); accum++; n.clear(); - if(flag) { - // ch=remap[flag&31]; -// ch=remap[flag&31]; -// if(ch!=-1) -// n=s3mbuf[(64U*ch)+row]; -// else -// n=&dummy; + if (flag) { + // ch=remap[flag&31]; + // ch=remap[flag&31]; + // if(ch!=-1) + // n=s3mbuf[(64U*ch)+row]; + // else + // n=&dummy; - ch=flag&31; + ch = flag & 31; - if(flag&32) { - n.note=file->get_byte(); - if (n.note==255) { + if (flag & 32) { + n.note = file->get_byte(); + if (n.note == 255) { - n.note=CPNote::EMPTY; - } else if (n.note==254) { + n.note = CPNote::EMPTY; + } else if (n.note == 254) { - n.note=CPNote::CUT; + n.note = CPNote::CUT; } else { - - n.note=((n.note>>4)*12)+(n.note&0xF); - } - n.instrument=file->get_byte()-1; - accum+=2; + n.note = ((n.note >> 4) * 12) + (n.note & 0xF); + } - } - if(flag&64) { - n.volume=file->get_byte(); - if (n.volume>64) n.volume=64; + n.instrument = file->get_byte() - 1; + accum += 2; + } + if (flag & 64) { + n.volume = file->get_byte(); + if (n.volume > 64) n.volume = 64; accum++; + } + if (flag & 128) { + n.command = file->get_byte() - 1; + n.parameter = file->get_byte(); + accum += 2; + } - } - if(flag&128) { - n.command=file->get_byte()-1; - n.parameter=file->get_byte(); - accum+=2; - } - - p_pattern->set_note(ch,row,n); - } else row++; - } - return FILE_OK; - - + p_pattern->set_note(ch, row, n); + } else + row++; + } + return FILE_OK; } -CPLoader::Error CPLoader_S3M::load_sample(const char *p_file,CPSample *p_sample) { - +CPLoader::Error CPLoader_S3M::load_sample(const char *p_file, CPSample *p_sample) { + return FILE_UNRECOGNIZED; } -CPLoader::Error CPLoader_S3M::load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx) { - +CPLoader::Error CPLoader_S3M::load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx) { + return FILE_UNRECOGNIZED; - } - CPLoader::Error CPLoader_S3M::load_samples() { int i; - for(i=0;i<header.insnum;i++) { + for (i = 0; i < header.insnum; i++) { file->seek(sample_parapointers[i]); load_sample(song->get_sample(i)); @@ -342,72 +313,65 @@ CPLoader::Error CPLoader_S3M::load_patterns() { int i; Error err; - for(i=0;i<header.patnum;i++) { + for (i = 0; i < header.patnum; i++) { file->seek(pattern_parapointers[i]); - - err=load_pattern(song->get_pattern(i) ); - CP_ERR_COND_V(err,err); - + err = load_pattern(song->get_pattern(i)); + CP_ERR_COND_V(err, err); + pattern_count++; } return FILE_OK; - } -CPLoader::Error CPLoader_S3M::load_song(const char *p_file,CPSong *p_song,bool p_sampleset) { +CPLoader::Error CPLoader_S3M::load_song(const char *p_file, CPSong *p_song, bool p_sampleset) { - song=p_song; + song = p_song; - if (file->open(p_file,CPFileAccessWrapper::READ)) { + if (file->open(p_file, CPFileAccessWrapper::READ)) { //printf("Can't open file! %s\n",p_file); return FILE_CANNOT_OPEN; }; - - sample_count=0; - pattern_count=0; + + sample_count = 0; + pattern_count = 0; //printf("LOADING HEADER\n"); CPLoader::Error err; - if ((err=load_header())) { + if ((err = load_header())) { file->close(); - CP_ERR_COND_V(err,err); - - } + CP_ERR_COND_V(err, err); + } song->reset(); //file type recognized, reset song! - + set_header(); - + //printf("LOADING SAMPLES\n"); - - if ((err=load_samples())) { + + if ((err = load_samples())) { file->close(); - CP_ERR_COND_V(err,err); - } + CP_ERR_COND_V(err, err); + } //printf("LOADING PATTERNS\n"); - - if ((err=load_patterns())) { + + if ((err = load_patterns())) { file->close(); return err; - } + } file->close(); return FILE_OK; } +CPLoader_S3M::CPLoader_S3M(CPFileAccessWrapper *p_file) { - -CPLoader_S3M::CPLoader_S3M(CPFileAccessWrapper *p_file){ - - file=p_file; - + file = p_file; } -CPLoader_S3M::~CPLoader_S3M(){ +CPLoader_S3M::~CPLoader_S3M() { } - diff --git a/modules/chibi/cp_loader_s3m.h b/modules/chibi/cp_loader_s3m.h index 04ee0b291..7bf373d84 100644 --- a/modules/chibi/cp_loader_s3m.h +++ b/modules/chibi/cp_loader_s3m.h @@ -44,40 +44,36 @@ individual sample loading and reorganizing the columns. ********************************/ - - - -class CPLoader_S3M : public CPLoader { +class CPLoader_S3M : public CPLoader { struct S3M_Header { - char songname[28]; - uint8_t t1a; - uint8_t type; - uint8_t unused1[2]; - uint16_t ordnum; - uint16_t insnum; - uint16_t patnum; - uint16_t flags; - uint16_t tracker; - uint16_t fileformat; - char scrm[5]; - uint8_t mastervol; - uint8_t initspeed; - uint8_t inittempo; - uint8_t mastermult; - uint8_t ultraclick; - uint8_t pantable; - uint8_t unused2[8]; - uint16_t special; - uint8_t channels[32]; + char songname[28]; + uint8_t t1a; + uint8_t type; + uint8_t unused1[2]; + uint16_t ordnum; + uint16_t insnum; + uint16_t patnum; + uint16_t flags; + uint16_t tracker; + uint16_t fileformat; + char scrm[5]; + uint8_t mastervol; + uint8_t initspeed; + uint8_t inittempo; + uint8_t mastermult; + uint8_t ultraclick; + uint8_t pantable; + uint8_t unused2[8]; + uint16_t special; + uint8_t channels[32]; uint8_t pannings[32]; uint8_t orderlist[300]; }; - int sample_parapointers[CPSong::MAX_SAMPLES]; int pattern_parapointers[CPSong::MAX_PATTERNS]; - + Error load_header(); void set_header(); Error load_sample(CPSample *p_sample); @@ -85,27 +81,25 @@ class CPLoader_S3M : public CPLoader { Error load_patterns(); Error load_samples(); - + S3M_Header header; - int sample_count; + int sample_count; int pattern_count; - + CPFileAccessWrapper *file; CPSong *song; -public: +public: bool can_load_song() { return true; } bool can_load_sample() { return false; } bool can_load_instrument() { return false; } - - Error load_song(const char *p_file,CPSong *p_song,bool p_sampleset); - Error load_sample(const char *p_file,CPSample *p_sample); - Error load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx); - + + Error load_song(const char *p_file, CPSong *p_song, bool p_sampleset); + Error load_sample(const char *p_file, CPSample *p_sample); + Error load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx); + CPLoader_S3M(CPFileAccessWrapper *p_file); ~CPLoader_S3M(); }; - - #endif diff --git a/modules/chibi/cp_loader_xm.cpp b/modules/chibi/cp_loader_xm.cpp index 65c7bc7ee..9f743904b 100644 --- a/modules/chibi/cp_loader_xm.cpp +++ b/modules/chibi/cp_loader_xm.cpp @@ -30,705 +30,683 @@ #include "cp_loader_xm.h" #include "cp_tables.h" -#define ABORT_LOAD { file->close(); return FILE_CORRUPTED; } - - - +#define ABORT_LOAD \ + { \ + file->close(); \ + return FILE_CORRUPTED; \ + } -CPLoader::Error CPLoader_XM::load_song(const char *p_file,CPSong *p_song,bool p_sampleset) { +CPLoader::Error CPLoader_XM::load_song(const char *p_file, CPSong *p_song, bool p_sampleset) { - song=p_song; + song = p_song; - if (file->open(p_file,CPFileAccessWrapper::READ)) { + if (file->open(p_file, CPFileAccessWrapper::READ)) { return FILE_CANNOT_OPEN; - }; - + }; - /************************************** + /************************************** LOAD HEADER ***************************************/ - file->get_byte_array(header.idtext,17); - header.idtext[17]=0; + file->get_byte_array(header.idtext, 17); + header.idtext[17] = 0; - file->get_byte_array(header.songname,20); - + file->get_byte_array(header.songname, 20); + header.songname[20] = 0; + header.hex1a = file->get_byte(); + if (header.hex1a != 0x1A) { //XM "magic" byte.. this sucks :) - header.songname[20]=0; - header.hex1a=file->get_byte(); - if (header.hex1a!=0x1A) { //XM "magic" byte.. this sucks :) - - file->close(); + file->close(); return FILE_UNRECOGNIZED; - - } + } + + //magic byte sucks, but can't do much about it.. - - //magic byte sucks, but can't do much about it.. - song->reset(); //must reset the song - song->set_name( (const char*)header.songname ); - - file->get_byte_array(header.trackername,20); - header.trackername[20]=0; + song->set_name((const char *)header.songname); + + file->get_byte_array(header.trackername, 20); + header.trackername[20] = 0; + header.version = file->get_word(); - header.version=file->get_word(); + header.headersize = file->get_dword(); - header.headersize=file->get_dword(); + header.songlength = file->get_word(); - header.songlength=file->get_word(); + header.restart_pos = file->get_word(); - header.restart_pos=file->get_word(); + header.channels_used = file->get_word(); - header.channels_used=file->get_word(); + header.patterns_used = file->get_word(); - header.patterns_used=file->get_word(); + header.instruments_used = file->get_word(); - header.instruments_used=file->get_word(); + song->set_linear_slides(file->get_word()); - song->set_linear_slides( file->get_word() ); + song->set_speed(file->get_word()); - song->set_speed( file->get_word() ); + song->set_tempo(file->get_word()); + song->set_instruments(true); - song->set_tempo( file->get_word() ); - song->set_instruments( true ); + file->get_byte_array(header.orderlist, 256); - file->get_byte_array(header.orderlist,256); - - for (int i=0;i<header.songlength;i++) { + for (int i = 0; i < header.songlength; i++) { - if (i>199) + if (i > 199) break; - song->set_order(i,header.orderlist[i]); + song->set_order(i, header.orderlist[i]); } - /************************************** + /************************************** LOAD PATTERNS ***************************************/ - for (int i=0;i<header.patterns_used;i++) { + for (int i = 0; i < header.patterns_used; i++) { - uint32_t aux,rows; + uint32_t aux, rows; - aux=file->get_dword(); //length - aux=file->get_byte(); //packing type - rows=aux=file->get_word(); //rows! + aux = file->get_dword(); //length + aux = file->get_byte(); //packing type + rows = aux = file->get_word(); //rows! - song->get_pattern(i)->set_length( aux ); + song->get_pattern(i)->set_length(aux); - aux=file->get_word(); //packed size - if (aux==0) - continue; - //unpaaack! - for(int j=0;j<(int)rows;j++) - for(int k=0;k<header.channels_used;k++) { + aux = file->get_word(); //packed size + if (aux == 0) + continue; + //unpaaack! + for (int j = 0; j < (int)rows; j++) + for (int k = 0; k < header.channels_used; k++) { CPNote aux_note; - uint8_t aux_byte; + uint8_t aux_byte; //uint8_t field; - aux_byte=file->get_byte(); //packing type - if (!(aux_byte&0x80)) { - - aux_note.note=aux_byte; - aux_byte=0xFE; //if bit 7 not set, read all of them except the note - } - - if (aux_byte&1) aux_note.note=file->get_byte(); - if (aux_byte&2) aux_note.instrument=file->get_byte(); - if (aux_byte&4) aux_note.volume=file->get_byte(); - if (aux_byte&8) aux_note.command=file->get_byte(); - if (aux_byte&16) aux_note.parameter=file->get_byte(); - - if (aux_note.note!=CPNote::EMPTY) { - - if (aux_note.note==97) aux_note.note=CPNote::OFF; - else { - aux_note.note+=11; //octave minus one (XM C-0 is 1, not zero ) - } - } - if (aux_note.instrument!=CPNote::EMPTY) { + aux_byte = file->get_byte(); //packing type + if (!(aux_byte & 0x80)) { - if ((aux_note.instrument>0) && (aux_note.instrument<100)) - aux_note.instrument--; - else - aux_note.instrument=CPNote::EMPTY; - } - if (aux_note.volume!=CPNote::EMPTY) { - - if (aux_note.volume<0x10) {} - else if (aux_note.volume<0x50) { + aux_note.note = aux_byte; + aux_byte = 0xFE; //if bit 7 not set, read all of them except the note + } - aux_note.volume-=0x10; + if (aux_byte & 1) aux_note.note = file->get_byte(); + if (aux_byte & 2) aux_note.instrument = file->get_byte(); + if (aux_byte & 4) aux_note.volume = file->get_byte(); + if (aux_byte & 8) aux_note.command = file->get_byte(); + if (aux_byte & 16) aux_note.parameter = file->get_byte(); - } else if (aux_note.volume<0x60) { - // - aux_note.volume=CPNote::EMPTY; + if (aux_note.note != CPNote::EMPTY) { - } else if (aux_note.volume<0x70) { - //60 -- volume slide down - aux_note.volume-=0x60; - if (aux_note.volume>9) aux_note.volume=9; - aux_note.volume+=95; - - } else if (aux_note.volume<0x80) { - //70 -- volume slide up - aux_note.volume-=0x70; - if (aux_note.volume>9) aux_note.volume=9; - aux_note.volume+=85; + if (aux_note.note == 97) + aux_note.note = CPNote::OFF; + else { + aux_note.note += 11; //octave minus one (XM C-0 is 1, not zero ) + } + } + if (aux_note.instrument != CPNote::EMPTY) { + if ((aux_note.instrument > 0) && (aux_note.instrument < 100)) + aux_note.instrument--; + else + aux_note.instrument = CPNote::EMPTY; + } + if (aux_note.volume != CPNote::EMPTY) { - } else if (aux_note.volume<0x90) { - //80 -- fine volume slide down - aux_note.volume-=0x80; - if (aux_note.volume>9) aux_note.volume=9; - aux_note.volume+=75; + if (aux_note.volume < 0x10) { + } else if (aux_note.volume < 0x50) { + aux_note.volume -= 0x10; - } else if (aux_note.volume<0xA0) { - //9 -- fine volume slide up + } else if (aux_note.volume < 0x60) { + // + aux_note.volume = CPNote::EMPTY; - aux_note.volume-=0x90; - if (aux_note.volume>9) aux_note.volume=9; + } else if (aux_note.volume < 0x70) { + //60 -- volume slide down + aux_note.volume -= 0x60; + if (aux_note.volume > 9) aux_note.volume = 9; + aux_note.volume += 95; - aux_note.volume+=65; + } else if (aux_note.volume < 0x80) { + //70 -- volume slide up + aux_note.volume -= 0x70; + if (aux_note.volume > 9) aux_note.volume = 9; + aux_note.volume += 85; + } else if (aux_note.volume < 0x90) { + //80 -- fine volume slide down + aux_note.volume -= 0x80; + if (aux_note.volume > 9) aux_note.volume = 9; + aux_note.volume += 75; + } else if (aux_note.volume < 0xA0) { + //9 -- fine volume slide up - } else if (aux_note.volume<0xB0) { - //A -- set vibrato speed - aux_note.volume=CPNote::EMPTY; + aux_note.volume -= 0x90; + if (aux_note.volume > 9) aux_note.volume = 9; - } else if (aux_note.volume<0xC0) { - //B -- vibrato - aux_note.volume-=0xB0; - if (aux_note.volume>9) aux_note.volume=9; - aux_note.volume+=203; + aux_note.volume += 65; + } else if (aux_note.volume < 0xB0) { + //A -- set vibrato speed + aux_note.volume = CPNote::EMPTY; - } else if (aux_note.volume<0xD0) { - //C -- set panning - int aux=aux_note.volume-=0xC0; - aux=aux*65/0xF; - aux_note.volume=128+aux; + } else if (aux_note.volume < 0xC0) { + //B -- vibrato + aux_note.volume -= 0xB0; + if (aux_note.volume > 9) aux_note.volume = 9; + aux_note.volume += 203; - } else if (aux_note.volume<0xE0) { - aux_note.volume=CPNote::EMPTY; + } else if (aux_note.volume < 0xD0) { + //C -- set panning + int aux = aux_note.volume -= 0xC0; + aux = aux * 65 / 0xF; + aux_note.volume = 128 + aux; + } else if (aux_note.volume < 0xE0) { + aux_note.volume = CPNote::EMPTY; - } else if (aux_note.volume<0xF0) { - aux_note.volume=CPNote::EMPTY; + } else if (aux_note.volume < 0xF0) { + aux_note.volume = CPNote::EMPTY; + } else { + //F -- tone porta + aux_note.volume -= 0xF0; + aux_note.volume *= 9; + aux_note.volume /= 0xF; + aux_note.volume += 193; + } + } + if (aux_note.command != CPNote::EMPTY) { - } else { - //F -- tone porta - aux_note.volume-=0xF0; - aux_note.volume*=9; - aux_note.volume/=0xF; - aux_note.volume+=193; - } - } - if (aux_note.command!=CPNote::EMPTY) { + switch (aux_note.command) { - switch(aux_note.command) { + case 0x0: + aux_note.command = 'J' - 'A'; + break; + case 0x1: + aux_note.command = 'F' - 'A'; + break; + case 0x2: + aux_note.command = 'E' - 'A'; + break; + case 0x3: + aux_note.command = 'G' - 'A'; + break; + case 0x4: + aux_note.command = 'H' - 'A'; + break; + case 0x5: + aux_note.command = 'L' - 'A'; + break; + case 0x6: + aux_note.command = 'K' - 'A'; + break; + case 0x7: + aux_note.command = 'R' - 'A'; + break; + case 0x8: + aux_note.command = 'X' - 'A'; + break; + case 0x9: + aux_note.command = 'O' - 'A'; + break; + case 0xa: + aux_note.command = 'D' - 'A'; + break; + case 0xb: + aux_note.command = 'B' - 'A'; + break; + case 0xc: + //printf("XM Import: Warning! effect C (set volume) not implemented!\n"); + break; + case 0xd: + aux_note.command = 'C' - 'A'; + break; - case 0x0: - aux_note.command='J'-'A'; - break; - case 0x1: - aux_note.command='F'-'A'; - break; - case 0x2: - aux_note.command='E'-'A'; - break; - case 0x3: - aux_note.command='G'-'A'; - break; - case 0x4: - aux_note.command='H'-'A'; - break; - case 0x5: - aux_note.command='L'-'A'; - break; - case 0x6: - aux_note.command='K'-'A'; - break; - case 0x7: - aux_note.command='R'-'A'; - break; - case 0x8: - aux_note.command='X'-'A'; - break; - case 0x9: - aux_note.command='O'-'A'; - break; - case 0xa: - aux_note.command='D'-'A'; - break; - case 0xb: - aux_note.command='B'-'A'; - break; - case 0xc: - //printf("XM Import: Warning! effect C (set volume) not implemented!\n"); - break; - case 0xd: - aux_note.command='C'-'A'; - break; + case 0xe: /* Extended effects */ - case 0xe: /* Extended effects */ + aux_note.command = 'S' - 'A'; + switch (aux_note.parameter >> 4) { + case 0x1: /* XM fine porta up */ + if (!(aux_note.parameter & 0xF)) { + aux_note.command = CPNote::EMPTY; + aux_note.parameter = 0; + break; + } + aux_note.command = 'F' - 'A'; + aux_note.parameter = 0xF0 | (aux_note.parameter & 0xF); + break; + case 0x2: /* XM fine porta down */ + if (!(aux_note.parameter & 0xF)) { + aux_note.command = CPNote::EMPTY; + aux_note.parameter = 0; + break; + } + aux_note.command = 'E' - 'A'; + aux_note.parameter = 0xF0 | (aux_note.parameter & 0xF); + break; + case 0xa: /* XM fine volume up */ + if (!(aux_note.parameter & 0xF)) { + aux_note.command = CPNote::EMPTY; + aux_note.parameter = 0; + break; + } + aux_note.command = 'D' - 'A'; + aux_note.parameter = 0x0F | ((aux_note.parameter & 0xF) << 4); - aux_note.command='S'-'A'; - switch(aux_note.parameter>>4) { - case 0x1: /* XM fine porta up */ - if (!(aux_note.parameter&0xF)) { aux_note.command=CPNote::EMPTY; aux_note.parameter=0; break; } - aux_note.command='F'-'A'; - aux_note.parameter=0xF0|(aux_note.parameter&0xF); - break; - case 0x2: /* XM fine porta down */ - if (!(aux_note.parameter&0xF)) { aux_note.command=CPNote::EMPTY; aux_note.parameter=0; break; } - aux_note.command='E'-'A'; - aux_note.parameter=0xF0|(aux_note.parameter&0xF); - break; - case 0xa: /* XM fine volume up */ - if (!(aux_note.parameter&0xF)) { aux_note.command=CPNote::EMPTY; aux_note.parameter=0; break; } - aux_note.command='D'-'A'; - aux_note.parameter=0x0F|((aux_note.parameter&0xF)<<4); + break; + case 0xb: /* XM fine volume down */ + if (!(aux_note.parameter & 0xF)) { + aux_note.command = CPNote::EMPTY; + aux_note.parameter = 0; + break; + } + aux_note.command = 'D' - 'A'; + aux_note.parameter = 0xF0 | (aux_note.parameter & 0xF); - break; - case 0xb: /* XM fine volume down */ - if (!(aux_note.parameter&0xF)) { aux_note.command=CPNote::EMPTY; aux_note.parameter=0; break; } - aux_note.command='D'-'A'; - aux_note.parameter=0xF0|(aux_note.parameter&0xF); + break; + case 0x9: /* XM fine volume down */ + if (!(aux_note.parameter & 0xF)) { + aux_note.command = CPNote::EMPTY; + aux_note.parameter = 0; + break; + } + aux_note.command = 'Q' - 'A'; + aux_note.parameter = 0x00 | (aux_note.parameter & 0xF); + break; - break; - case 0x9: /* XM fine volume down */ - if (!(aux_note.parameter&0xF)) { aux_note.command=CPNote::EMPTY; aux_note.parameter=0; break; } - aux_note.command='Q'-'A'; - aux_note.parameter=0x00|(aux_note.parameter&0xF); - break; + case 0xc: //notecut - case 0xc: //notecut - - aux_note.parameter=0xC0|(aux_note.parameter&0xF); - break; + aux_note.parameter = 0xC0 | (aux_note.parameter & 0xF); + break; - case 0xd: //notedelay - - aux_note.parameter=0xD0|(aux_note.parameter&0xF); - break; + case 0xd: //notedelay - case 0xe: //patterndelay - - aux_note.parameter=0xE0|(aux_note.parameter&0xF); - break; - } + aux_note.parameter = 0xD0 | (aux_note.parameter & 0xF); + break; - break; - case 0xf: - if (aux_note.parameter<32) { - aux_note.command='A'-'A'; - } else { - aux_note.command='T'-'A'; - } - break; - case 'G'-55: - aux_note.command='V'-'A'; - break; - case 'H'-55: - aux_note.command='W'-'A'; - break; - case 'K'-55: - if (aux_note.note!=CPNote::EMPTY) break; - aux_note.note=CPNote::OFF; - break; - case 'P'-55: - aux_note.command='P'-'A'; - break; - case 'R'-55: - aux_note.command='Q'-'A'; - break; - case 'T'-55: - aux_note.command='I'-'A'; - break; - default: { + case 0xe: //patterndelay - aux_note.command=CPNote::EMPTY; - } - } + aux_note.parameter = 0xE0 | (aux_note.parameter & 0xF); + break; + } + break; + case 0xf: + if (aux_note.parameter < 32) { + aux_note.command = 'A' - 'A'; + } else { + aux_note.command = 'T' - 'A'; + } + break; + case 'G' - 55: + aux_note.command = 'V' - 'A'; + break; + case 'H' - 55: + aux_note.command = 'W' - 'A'; + break; + case 'K' - 55: + if (aux_note.note != CPNote::EMPTY) break; + aux_note.note = CPNote::OFF; + break; + case 'P' - 55: + aux_note.command = 'P' - 'A'; + break; + case 'R' - 55: + aux_note.command = 'Q' - 'A'; + break; + case 'T' - 55: + aux_note.command = 'I' - 'A'; + break; + default: { + aux_note.command = CPNote::EMPTY; + } + } } - song->get_pattern( i)->set_note( k,j,aux_note ); - } + song->get_pattern(i)->set_note(k, j, aux_note); + } } - /************************************** + /************************************** LOAD INSTRUMENTS! ***************************************/ - for (int i=0;i<header.instruments_used;i++) { + for (int i = 0; i < header.instruments_used; i++) { + uint32_t aux; + int sampnum; - uint32_t aux; - int sampnum; - - CPInstrument &instrument=*song->get_instrument(i); - uint32_t cpos=file->get_pos(); + CPInstrument &instrument = *song->get_instrument(i); + uint32_t cpos = file->get_pos(); //printf("pos is %i\n",cpos); - - -/* +4 */ uint32_t hsize=file->get_dword(); //header length + /* +4 */ uint32_t hsize = file->get_dword(); //header length char instrname[23]; - instrname[22]=0; - - file->get_byte_array((uint8_t*)instrname,22); -//XM_LOAD_DEBUG printf("name is %s\n",instrname); + instrname[22] = 0; -/* +27 */ aux=file->get_byte(); //byte that must be ignored -//XM_LOAD_DEBUG printf("header size is %i\n",hsize); + file->get_byte_array((uint8_t *)instrname, 22); + //XM_LOAD_DEBUG printf("name is %s\n",instrname); -/* +29 */ sampnum=file->get_word(); + /* +27 */ aux = file->get_byte(); //byte that must be ignored + //XM_LOAD_DEBUG printf("header size is %i\n",hsize); -//XM_LOAD_DEBUG printf("samples %i\n",sampnum); + /* +29 */ sampnum = file->get_word(); + //XM_LOAD_DEBUG printf("samples %i\n",sampnum); - instrument.set_name( instrname ); -// printf("Header Len: %i, CPInstrument %i, %i samples , name: s,\n",hsize,i,sampnum,instrname); - - if (sampnum==0) { + instrument.set_name(instrname); + // printf("Header Len: %i, CPInstrument %i, %i samples , name: s,\n",hsize,i,sampnum,instrname); + + if (sampnum == 0) { //aux=file->get_dword(); //Why is this for? -- for nothing, skipped if (hsize) { - - file->seek( cpos+hsize ); //skip header if size has been specified + + file->seek(cpos + hsize); //skip header if size has been specified } continue; } -/* +33 */ file->get_dword(); + /* +33 */ file->get_dword(); - if (Error result=load_instrument_internal(&instrument,false,cpos,hsize,sampnum)) { + if (Error result = load_instrument_internal(&instrument, false, cpos, hsize, sampnum)) { CP_PRINTERR("Error loading instrument"); file->close(); return result; } - } -// + // file->close(); return FILE_OK; } -CPLoader::Error CPLoader_XM::load_instrument_internal(CPInstrument *p_instr,bool p_xi,int p_cpos, int p_hsize, int p_sampnum) { +CPLoader::Error CPLoader_XM::load_instrument_internal(CPInstrument *p_instr, bool p_xi, int p_cpos, int p_hsize, int p_sampnum) { - int sampnum; - uint32_t aux; - uint8_t notenumb[96]; - uint16_t panenv[24],volenv[24]; - int volpoints,panpoints; - int vol_loop_begin,vol_loop_end,vol_sustain_loop; - int pan_loop_begin,pan_loop_end,pan_sustain_loop; - char instrname[23]; - int sample_index[16]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //-1 means no index! + int sampnum; + uint32_t aux; + uint8_t notenumb[96]; + uint16_t panenv[24], volenv[24]; + int volpoints, panpoints; + int vol_loop_begin, vol_loop_end, vol_sustain_loop; + int pan_loop_begin, pan_loop_end, pan_sustain_loop; + char instrname[23]; + int sample_index[16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; //-1 means no index! - instrname[22]=0; + instrname[22] = 0; + /* +129 */ file->get_byte_array((uint8_t *)notenumb, 96); + for (int j = 0; j < 24; j++) { + volenv[j] = file->get_word(); + } + for (int j = 0; j < 24; j++) { + panenv[j] = file->get_word(); + } -/* +129 */ file->get_byte_array((uint8_t*)notenumb,96); - for (int j=0;j<24;j++) { - volenv[j]=file->get_word(); - } - for (int j=0;j<24;j++) { - panenv[j]=file->get_word(); - } + /* +177 */ + /* +225 */ + /* +226 */ volpoints = file->get_byte(); + /* +227 */ panpoints = file->get_byte(); + /* +230 */ vol_sustain_loop = file->get_byte(); + /* +228 */ vol_loop_begin = file->get_byte(); + /* +229 */ vol_loop_end = file->get_byte(); + + //XM_LOAD_DEBUG printf("1- volpoints: %i, panpoints: %i, susloop: %i, loop begin: %i, loop end %i\n",volpoints,panpoints,vol_sustain_loop,vol_loop_begin,vol_loop_end); + pan_sustain_loop = file->get_byte(); + /* +231 */ pan_loop_begin = file->get_byte(); + /* +232 */ pan_loop_end = file->get_byte(); + + /* +234 */ aux = file->get_byte(); + p_instr->get_volume_envelope()->reset(); + p_instr->get_volume_envelope()->set_enabled(aux & 1); + p_instr->get_volume_envelope()->set_sustain_loop_enabled((aux & 2) ? true : false); + p_instr->get_volume_envelope()->set_loop_enabled((aux & 4) ? true : false); + /* +235 */ aux = file->get_byte(); + p_instr->get_pan_envelope()->reset(); + p_instr->get_pan_envelope()->set_enabled(aux & 1); + p_instr->get_pan_envelope()->set_sustain_loop_enabled((aux & 2) ? true : false); + p_instr->get_pan_envelope()->set_loop_enabled((aux & 4) ? true : false); + + /* +239 */ aux = file->get_dword(); // sadly, cant use those + /* +241 */ p_instr->set_volume_fadeout(file->get_word() >> 4); + /* +243 */ aux = file->get_word(); // reserved! + + for (int j = 0; j < volpoints; j++) { + int ofs = volenv[j * 2]; + int val = volenv[j * 2 + 1]; + p_instr->get_volume_envelope()->add_position(ofs, val); + } -/* +177 */ -/* +225 */ -/* +226 */ volpoints=file->get_byte(); -/* +227 */ panpoints=file->get_byte(); -/* +230 */ vol_sustain_loop=file->get_byte(); -/* +228 */ vol_loop_begin=file->get_byte(); -/* +229 */ vol_loop_end=file->get_byte(); + //make sure minimum is 2 + while (p_instr->get_volume_envelope()->get_node_count() < 2) { -//XM_LOAD_DEBUG printf("1- volpoints: %i, panpoints: %i, susloop: %i, loop begin: %i, loop end %i\n",volpoints,panpoints,vol_sustain_loop,vol_loop_begin,vol_loop_end); - pan_sustain_loop=file->get_byte(); -/* +231 */ pan_loop_begin=file->get_byte(); -/* +232 */ pan_loop_end=file->get_byte(); + p_instr->get_volume_envelope()->add_position(p_instr->get_volume_envelope()->get_node_count() * 20, 64); + } + for (int j = 0; j < panpoints; j++) { + int ofs = panenv[j * 2]; + int val = panenv[j * 2 + 1]; + p_instr->get_pan_envelope()->add_position(ofs, val - 32); + } + //make sure minimum is 2 + while (p_instr->get_pan_envelope()->get_node_count() < 2) { -/* +234 */ aux=file->get_byte(); - p_instr->get_volume_envelope()->reset(); - p_instr->get_volume_envelope()->set_enabled(aux&1); - p_instr->get_volume_envelope()->set_sustain_loop_enabled((aux&2)?true:false); - p_instr->get_volume_envelope()->set_loop_enabled((aux&4)?true:false); -/* +235 */ aux=file->get_byte(); - p_instr->get_pan_envelope()->reset(); - p_instr->get_pan_envelope()->set_enabled(aux&1); - p_instr->get_pan_envelope()->set_sustain_loop_enabled((aux&2)?true:false); - p_instr->get_pan_envelope()->set_loop_enabled((aux&4)?true:false); + p_instr->get_pan_envelope()->add_position(p_instr->get_pan_envelope()->get_node_count() * 20, 0); + } -/* +239 */ aux=file->get_dword(); // sadly, cant use those -/* +241 */ p_instr->set_volume_fadeout( file->get_word() >> 4 ); -/* +243 */ aux=file->get_word(); // reserved! + p_instr->get_volume_envelope()->set_loop_begin(vol_loop_begin); + p_instr->get_volume_envelope()->set_loop_end(vol_loop_end); + p_instr->get_volume_envelope()->set_sustain_loop_end(vol_sustain_loop); + p_instr->get_volume_envelope()->set_sustain_loop_begin(vol_sustain_loop); + p_instr->get_pan_envelope()->set_loop_begin(pan_loop_begin); + p_instr->get_pan_envelope()->set_loop_end(pan_loop_end); + p_instr->get_pan_envelope()->set_sustain_loop_end(pan_sustain_loop); + p_instr->get_pan_envelope()->set_sustain_loop_begin(pan_sustain_loop); + if (!p_xi) { + if ((file->get_pos() - p_cpos) < p_hsize) { - for (int j=0;j<volpoints;j++) { - int ofs=volenv[j*2]; - int val=volenv[j*2+1]; - p_instr->get_volume_envelope()->add_position(ofs,val); + uint8_t junkbuster[500]; + //printf("extra junk XM instrument in header! hsize is %i, extra junk: %i\n",p_hsize,(file->get_pos()-p_cpos)); + //printf("extra: %i\n",p_hsize-(file->get_pos()-p_cpos)); + file->get_byte_array((uint8_t *)junkbuster, p_hsize - (file->get_pos() - p_cpos)); } - //make sure minimum is 2 - while (p_instr->get_volume_envelope()->get_node_count()<2) { - - p_instr->get_volume_envelope()->add_position( p_instr->get_volume_envelope()->get_node_count()*20,64 ); - } - - for (int j=0;j<panpoints;j++) { - int ofs=panenv[j*2]; - int val=panenv[j*2+1]; - p_instr->get_pan_envelope()->add_position(ofs,val-32); - } - - //make sure minimum is 2 - while (p_instr->get_pan_envelope()->get_node_count()<2) { - - p_instr->get_pan_envelope()->add_position( p_instr->get_pan_envelope()->get_node_count()*20,0 ); - } - - - p_instr->get_volume_envelope()->set_loop_begin(vol_loop_begin); - p_instr->get_volume_envelope()->set_loop_end(vol_loop_end); - p_instr->get_volume_envelope()->set_sustain_loop_end(vol_sustain_loop); - p_instr->get_volume_envelope()->set_sustain_loop_begin(vol_sustain_loop); - p_instr->get_pan_envelope()->set_loop_begin(pan_loop_begin); - p_instr->get_pan_envelope()->set_loop_end(pan_loop_end); - p_instr->get_pan_envelope()->set_sustain_loop_end(pan_sustain_loop); - p_instr->get_pan_envelope()->set_sustain_loop_begin(pan_sustain_loop); + sampnum = p_sampnum; + } else { + uint8_t junkbuster[500]; + file->get_byte_array((uint8_t *)junkbuster, 20); //14 bytes? - if (!p_xi) { + sampnum = file->get_word(); + } - if ((file->get_pos()-p_cpos)<p_hsize) { + CPSampleManager *sm = CPSampleManager::get_singleton(); - uint8_t junkbuster[500]; + /*SAMPLE!!*/ - //printf("extra junk XM instrument in header! hsize is %i, extra junk: %i\n",p_hsize,(file->get_pos()-p_cpos)); - //printf("extra: %i\n",p_hsize-(file->get_pos()-p_cpos)); - file->get_byte_array((uint8_t*)junkbuster,p_hsize-(file->get_pos()-p_cpos)); - } - - sampnum=p_sampnum; - } else { + for (int j = 0; j < sampnum; j++) { - uint8_t junkbuster[500]; - file->get_byte_array((uint8_t*)junkbuster,20); //14 bytes? + if (j > 16) ABORT_LOAD; - sampnum=file->get_word(); + int s_idx = -1; + for (int s = 0; s < CPSong::MAX_SAMPLES; s++) { + if (song->get_sample(s)->get_sample_data().is_null()) { + //empty sample! + s_idx = s; + break; + } } + if (s_idx == -1) ABORT_LOAD; + //printf("free sample: %i\n",s_idx); - CPSampleManager *sm=CPSampleManager::get_singleton(); + CPSample &sample = *song->get_sample(s_idx); - /*SAMPLE!!*/ + int sample_size = file->get_dword(); + int tmp_loop_begin = file->get_dword(); - for (int j=0;j<sampnum;j++) { + int tmp_loop_end = file->get_dword(); - if (j>16) ABORT_LOAD; + sample.set_default_volume(file->get_byte()); - - int s_idx=-1; - for (int s=0;s<CPSong::MAX_SAMPLES;s++) { - - if (song->get_sample(s)->get_sample_data().is_null()) { - //empty sample! - s_idx=s; - break; - } - } - - if (s_idx==-1) ABORT_LOAD; - //printf("free sample: %i\n",s_idx); - + uint8_t ftb = file->get_byte(); + int8_t *fts = (int8_t *)&ftb; + int finetune = *fts; + uint32_t flags = file->get_byte(); - CPSample& sample=*song->get_sample(s_idx); - - int sample_size=file->get_dword(); - int tmp_loop_begin=file->get_dword(); + if (flags & 16) { // is 16 bits.. at flag 16.. fun :) - int tmp_loop_end=file->get_dword(); - - sample.set_default_volume(file->get_byte()); + tmp_loop_end /= 2; + tmp_loop_begin /= 2; + sample_size /= 2; + } - uint8_t ftb=file->get_byte(); - int8_t *fts=(int8_t*)&ftb; - int finetune=*fts; - uint32_t flags=file->get_byte(); - - if (flags&16) { // is 16 bits.. at flag 16.. fun :) - - tmp_loop_end/=2; - tmp_loop_begin/=2; - sample_size/=2; - } - - - CPSample_ID sample_data=sm->create( flags&16, false, sample_size ); - - sample.set_sample_data(sample_data); - sm->set_loop_begin(sample_data,tmp_loop_begin); - sm->set_loop_end(sample_data,tmp_loop_end+tmp_loop_begin); - - sm->set_loop_type( sample_data, (flags&3)?( (flags&2) ? CP_LOOP_BIDI : CP_LOOP_FORWARD ):CP_LOOP_NONE ); - - + CPSample_ID sample_data = sm->create(flags & 16, false, sample_size); - sample.set_pan_enabled(true); - sample.set_pan(file->get_byte()*64/255); - uint8_t noteb=file->get_byte(); - int8_t *notes=(int8_t*)¬eb; - int note_offset=*notes; - note_offset+=48; - //note_offset+=60; - - - - //int linear_period=10*12*16*4 - (note_offset)*16*4 - finetune/2; - //int freq=(int)(8363*pow(2.0,(double)(6*12*16*4 - linear_period) / (double)(12*16*4))); - - //sm->set_c5_freq( sample_data, freq); - sm->set_c5_freq( sample_data, CPTables::get_linear_frequency(CPTables::get_linear_period(note_offset<<1,finetune)) ); - //printf("NOTE %i,fine %i\n",note_offset,finetune); + sample.set_sample_data(sample_data); + sm->set_loop_begin(sample_data, tmp_loop_begin); + sm->set_loop_end(sample_data, tmp_loop_end + tmp_loop_begin); - char auxb; - auxb=file->get_byte(); //reserved? - file->get_byte_array((uint8_t*)instrname,22); - sample.set_name(instrname); + sm->set_loop_type(sample_data, (flags & 3) ? ((flags & 2) ? CP_LOOP_BIDI : CP_LOOP_FORWARD) : CP_LOOP_NONE); - sample_index[j]=s_idx; - } + sample.set_pan_enabled(true); + sample.set_pan(file->get_byte() * 64 / 255); + uint8_t noteb = file->get_byte(); + int8_t *notes = (int8_t *)¬eb; + int note_offset = *notes; + note_offset += 48; + //note_offset+=60; - /*SAMPLE __DATA__!!*/ + //int linear_period=10*12*16*4 - (note_offset)*16*4 - finetune/2; + //int freq=(int)(8363*pow(2.0,(double)(6*12*16*4 - linear_period) / (double)(12*16*4))); - for (int j=0;j<sampnum;j++) { + //sm->set_c5_freq( sample_data, freq); + sm->set_c5_freq(sample_data, CPTables::get_linear_frequency(CPTables::get_linear_period(note_offset << 1, finetune))); + //printf("NOTE %i,fine %i\n",note_offset,finetune); - if (sample_index[j]==-1) continue; + char auxb; + auxb = file->get_byte(); //reserved? + file->get_byte_array((uint8_t *)instrname, 22); + sample.set_name(instrname); - CPSample *sample=song->get_sample(sample_index[j]); - CPSample_ID sid=sample->get_sample_data(); + sample_index[j] = s_idx; + } - sm->lock_data(sid); + /*SAMPLE __DATA__!!*/ - void*dataptr=sm->get_data(sid); + for (int j = 0; j < sampnum; j++) { - if (sm->is_16bits( sid)) { + if (sample_index[j] == -1) continue; - int16_t old=0; + CPSample *sample = song->get_sample(sample_index[j]); + CPSample_ID sid = sample->get_sample_data(); + sm->lock_data(sid); - for (int k=0;k<sm->get_size(sid);k++) { + void *dataptr = sm->get_data(sid); - int16_t newsample; - int16_t sampleval=file->get_word(); - newsample=sampleval+old; - old=newsample; + if (sm->is_16bits(sid)) { - ((int16_t*)dataptr)[k]=newsample; - //sm->set_data( sid, k, newsample ); - } - } else { + int16_t old = 0; - int8_t old=0; + for (int k = 0; k < sm->get_size(sid); k++) { + int16_t newsample; + int16_t sampleval = file->get_word(); + newsample = sampleval + old; + old = newsample; - for (int k=0;k<sm->get_size(sid);k++) { + ((int16_t *)dataptr)[k] = newsample; + //sm->set_data( sid, k, newsample ); + } + } else { - int8_t newsample; - int8_t sampleval=file->get_byte(); - newsample=sampleval+old; - old=newsample; - - ((int8_t*)dataptr)[k]=newsample; + int8_t old = 0; - //sm->set_data( sid, k, (int16_t)newsample << 8 ); - - } - } + for (int k = 0; k < sm->get_size(sid); k++) { + + int8_t newsample; + int8_t sampleval = file->get_byte(); + newsample = sampleval + old; + old = newsample; - sm->unlock_data(sid); + ((int8_t *)dataptr)[k] = newsample; + //sm->set_data( sid, k, (int16_t)newsample << 8 ); + } } - for (int j=0;j<96;j++) { + sm->unlock_data(sid); + } - int val=notenumb[j]; - if ((val<0) || (val>15)) continue; - else val=sample_index[val]; - if (val==-1) continue; - p_instr->set_sample_number( 12+j,val ); - } + for (int j = 0; j < 96; j++) { + int val = notenumb[j]; + if ((val < 0) || (val > 15)) + continue; + else + val = sample_index[val]; + if (val == -1) continue; + p_instr->set_sample_number(12 + j, val); + } return FILE_OK; } +CPLoader::Error CPLoader_XM::load_sample(const char *p_file, CPSample *p_sample) { - -CPLoader::Error CPLoader_XM::load_sample(const char *p_file,CPSample *p_sample) { - return FILE_UNRECOGNIZED; } - /* Compute CPInstrument Info */ -CPLoader::Error CPLoader_XM::load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx) { +CPLoader::Error CPLoader_XM::load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx) { - if ( file->open(p_file,CPFileAccessWrapper::READ) ) return FILE_CANNOT_OPEN; + if (file->open(p_file, CPFileAccessWrapper::READ)) return FILE_CANNOT_OPEN; //int i; - song=p_song; - CPInstrument& instr=*p_song->get_instrument( p_instr_idx ); - int aux; - + song = p_song; + CPInstrument &instr = *p_song->get_instrument(p_instr_idx); + int aux; - char buffer[500]; - file->get_byte_array((uint8_t*)buffer,0x15); - buffer[8]=0; - if ( buffer[0]!='E' || - buffer[1]!='x' || - buffer[2]!='t' || - buffer[3]!='e' || - buffer[4]!='n' || - buffer[5]!='d' || - buffer[6]!='e' || - buffer[7]!='d') { + char buffer[500]; + file->get_byte_array((uint8_t *)buffer, 0x15); + buffer[8] = 0; + if (buffer[0] != 'E' || + buffer[1] != 'x' || + buffer[2] != 't' || + buffer[3] != 'e' || + buffer[4] != 'n' || + buffer[5] != 'd' || + buffer[6] != 'e' || + buffer[7] != 'd') { file->close(); return FILE_UNRECOGNIZED; - } + } - file->get_byte_array((uint8_t*)buffer,0x16); - buffer[0x16]=0; + file->get_byte_array((uint8_t *)buffer, 0x16); + buffer[0x16] = 0; instr.set_name(buffer); - aux=file->get_byte(); //says ignore ti + aux = file->get_byte(); //says ignore ti /*if(aux!=0x1a) { I'm not sure. this is supposed to be ignored... file->close(); return FILE_UNRECOGNIZED; } */ - file->get_byte_array((uint8_t*)buffer,0x14); //somethingaboutthename - aux=file->get_word(); //version or blahblah - - if (load_instrument_internal(&instr,true,0,0)) { + file->get_byte_array((uint8_t *)buffer, 0x14); //somethingaboutthename + aux = file->get_word(); //version or blahblah + + if (load_instrument_internal(&instr, true, 0, 0)) { file->close(); return FILE_CORRUPTED; @@ -736,17 +714,12 @@ CPLoader::Error CPLoader_XM::load_instrument(const char *p_file,CPSong *p_song,i file->close(); //ook, we got it.. - return FILE_OK; - } +CPLoader_XM::CPLoader_XM(CPFileAccessWrapper *p_file) { - -CPLoader_XM::CPLoader_XM(CPFileAccessWrapper *p_file){ - - file=p_file; + file = p_file; } -CPLoader_XM::~CPLoader_XM(){ +CPLoader_XM::~CPLoader_XM() { } - diff --git a/modules/chibi/cp_loader_xm.h b/modules/chibi/cp_loader_xm.h index 0889569b3..9f0ce1076 100644 --- a/modules/chibi/cp_loader_xm.h +++ b/modules/chibi/cp_loader_xm.h @@ -32,58 +32,49 @@ #include "cp_loader.h" - /** *@author red */ - - - -class CPLoader_XM : public CPLoader { - +class CPLoader_XM : public CPLoader { struct XM_Header { - uint8_t idtext[18]; - uint8_t songname[21]; - uint8_t hex1a; // ? - uint8_t trackername[21]; - uint16_t version; - uint32_t headersize; //from here - - uint16_t songlength; //pattern ordertable - uint16_t restart_pos; - uint16_t channels_used; - uint16_t patterns_used; - uint16_t instruments_used; - uint16_t use_linear_freq; - uint16_t tempo; - uint16_t speed; - uint8_t orderlist[256]; + uint8_t idtext[18]; + uint8_t songname[21]; + uint8_t hex1a; // ? + uint8_t trackername[21]; + uint16_t version; + uint32_t headersize; //from here + + uint16_t songlength; //pattern ordertable + uint16_t restart_pos; + uint16_t channels_used; + uint16_t patterns_used; + uint16_t instruments_used; + uint16_t use_linear_freq; + uint16_t tempo; + uint16_t speed; + uint8_t orderlist[256]; } header; - + CPFileAccessWrapper *file; - - Error load_instrument_internal(CPInstrument *pint,bool p_xi,int p_cpos, int p_hsize, int p_sampnumb=-1); + + Error load_instrument_internal(CPInstrument *pint, bool p_xi, int p_cpos, int p_hsize, int p_sampnumb = -1); CPSong *song; public: - bool can_load_song() { return true; } bool can_load_sample() { return false; } bool can_load_instrument() { return true; } - - Error load_song(const char *p_file,CPSong *p_song,bool p_sampleset); - Error load_sample(const char *p_file,CPSample *p_sample); - Error load_instrument(const char *p_file,CPSong *p_song,int p_instr_idx); - + Error load_song(const char *p_file, CPSong *p_song, bool p_sampleset); + Error load_sample(const char *p_file, CPSample *p_sample); + Error load_instrument(const char *p_file, CPSong *p_song, int p_instr_idx); + CPLoader_XM(CPFileAccessWrapper *p_file); ~CPLoader_XM(); }; - - #endif diff --git a/modules/chibi/cp_mixer.h b/modules/chibi/cp_mixer.h index d8564bae0..4b929b901 100644 --- a/modules/chibi/cp_mixer.h +++ b/modules/chibi/cp_mixer.h @@ -36,7 +36,6 @@ *@author Juan Linietsky */ - /****************************** mixer.h ---------- @@ -51,14 +50,13 @@ devices or other stuff.. class CPSample_ID; /* need this */ class CPMixer { -public: - +public: enum { - - FREQUENCY_BITS=8 - + + FREQUENCY_BITS = 8 + }; - + enum ReverbMode { REVERB_MODE_ROOM, REVERB_MODE_STUDIO_SMALL, @@ -70,45 +68,43 @@ public: REVERB_MODE_DELAY, REVERB_MODE_HALF_ECHO }; - - /* Callback */ - - virtual void set_callback_interval(int p_interval_us)=0; //in usecs, for tracker it's 2500000/tempo - virtual void set_callback(void (*p_callback)(void*),void *p_userdata)=0; - + + /* Callback */ + + virtual void set_callback_interval(int p_interval_us) = 0; //in usecs, for tracker it's 2500000/tempo + virtual void set_callback(void (*p_callback)(void *), void *p_userdata) = 0; + /* Voice Control */ - - virtual void setup_voice(int p_voice_index,CPSample_ID p_sample_id,int32_t p_start_index) =0; - virtual void stop_voice(int p_voice_index) =0; - virtual void set_voice_frequency(int p_voice_index,int32_t p_freq) =0; //in freq*FREQUENCY_BITS - virtual void set_voice_panning(int p_voice_index,int p_pan) =0; - virtual void set_voice_volume(int p_voice_index,int p_vol) =0; - virtual void set_voice_filter(int p_filter,bool p_enabled,uint8_t p_cutoff, uint8_t p_resonance )=0; - virtual void set_voice_reverb_send(int p_voice_index,int p_reverb)=0; - virtual void set_voice_chorus_send(int p_voice_index,int p_chorus)=0; /* 0 - 255 */ - - virtual void set_reverb_mode(ReverbMode p_mode)=0; - virtual void set_chorus_params(unsigned int p_delay_ms,unsigned int p_separation_ms,unsigned int p_depth_ms10,unsigned int p_speed_hz10)=0; - - - /* Info retrieving */ - - virtual int32_t get_voice_sample_pos_index(int p_voice_index) =0; - virtual int get_voice_panning(int p_voice_index) =0; - virtual int get_voice_volume(int p_voice_index) =0; - virtual CPSample_ID get_voice_sample_id(int p_voice_index) =0; - virtual bool is_voice_active(int p_voice_index) =0; - virtual int get_active_voice_count()=0; - virtual int get_total_voice_count()=0; - - - virtual uint32_t get_mix_frequency()=0; //if mixer is not software, return 0 + + virtual void setup_voice(int p_voice_index, CPSample_ID p_sample_id, int32_t p_start_index) = 0; + virtual void stop_voice(int p_voice_index) = 0; + virtual void set_voice_frequency(int p_voice_index, int32_t p_freq) = 0; //in freq*FREQUENCY_BITS + virtual void set_voice_panning(int p_voice_index, int p_pan) = 0; + virtual void set_voice_volume(int p_voice_index, int p_vol) = 0; + virtual void set_voice_filter(int p_filter, bool p_enabled, uint8_t p_cutoff, uint8_t p_resonance) = 0; + virtual void set_voice_reverb_send(int p_voice_index, int p_reverb) = 0; + virtual void set_voice_chorus_send(int p_voice_index, int p_chorus) = 0; /* 0 - 255 */ + + virtual void set_reverb_mode(ReverbMode p_mode) = 0; + virtual void set_chorus_params(unsigned int p_delay_ms, unsigned int p_separation_ms, unsigned int p_depth_ms10, unsigned int p_speed_hz10) = 0; + + /* Info retrieving */ + + virtual int32_t get_voice_sample_pos_index(int p_voice_index) = 0; + virtual int get_voice_panning(int p_voice_index) = 0; + virtual int get_voice_volume(int p_voice_index) = 0; + virtual CPSample_ID get_voice_sample_id(int p_voice_index) = 0; + virtual bool is_voice_active(int p_voice_index) = 0; + virtual int get_active_voice_count() = 0; + virtual int get_total_voice_count() = 0; + + virtual uint32_t get_mix_frequency() = 0; //if mixer is not software, return 0 /* Methods below only work with software mixers, meant for software-based sound drivers, hardware mixers ignore them */ - virtual int32_t process(int32_t p_frames)=0; /* Call this to process N frames, returns how much it was processed */ - virtual int32_t *get_mixdown_buffer_ptr()=0; /* retrieve what was mixed */ - virtual void set_mix_frequency(int32_t p_mix_frequency)=0; - + virtual int32_t process(int32_t p_frames) = 0; /* Call this to process N frames, returns how much it was processed */ + virtual int32_t *get_mixdown_buffer_ptr() = 0; /* retrieve what was mixed */ + virtual void set_mix_frequency(int32_t p_mix_frequency) = 0; + virtual ~CPMixer() {} }; diff --git a/modules/chibi/cp_note.h b/modules/chibi/cp_note.h index f9a3ef39f..aab7f64aa 100644 --- a/modules/chibi/cp_note.h +++ b/modules/chibi/cp_note.h @@ -35,14 +35,13 @@ struct CPNote { enum { - NOTES=120, - OFF=254, - CUT=253, - EMPTY=255, - SCRIPT=252, + NOTES = 120, + OFF = 254, + CUT = 253, + EMPTY = 255, + SCRIPT = 252, }; - uint8_t note; uint8_t instrument; uint8_t volume; @@ -53,50 +52,46 @@ struct CPNote { void clear() { - note=EMPTY; - instrument=EMPTY; - volume=EMPTY; - command=EMPTY; - parameter=0; - script_source_sign='\0'; - cloned=false; + note = EMPTY; + instrument = EMPTY; + volume = EMPTY; + command = EMPTY; + parameter = 0; + script_source_sign = '\0'; + cloned = false; } - + void raise() { - if (note<(NOTES-1)) - note++; - else if (note==SCRIPT && parameter<0xFF) - parameter++; + if (note < (NOTES - 1)) + note++; + else if (note == SCRIPT && parameter < 0xFF) + parameter++; } void lower() { - if ((note>0) && (note<NOTES)) - note--; - else if (note==SCRIPT && parameter>0) - parameter--; - + if ((note > 0) && (note < NOTES)) + note--; + else if (note == SCRIPT && parameter > 0) + parameter--; } - bool operator== (const CPNote &rvalue) { + bool operator==(const CPNote &rvalue) { return ( - (note==rvalue.note) && - (instrument==rvalue.instrument) && - (volume==rvalue.volume) && - (command==rvalue.command) && - (parameter==rvalue.parameter) - ); + (note == rvalue.note) && + (instrument == rvalue.instrument) && + (volume == rvalue.volume) && + (command == rvalue.command) && + (parameter == rvalue.parameter)); } - bool is_empty() const { return (note==EMPTY && instrument==EMPTY && volume==EMPTY && command==EMPTY && parameter==0 && !cloned); } + bool is_empty() const { return (note == EMPTY && instrument == EMPTY && volume == EMPTY && command == EMPTY && parameter == 0 && !cloned); } CPNote() { clear(); } }; - #endif - diff --git a/modules/chibi/cp_order.h b/modules/chibi/cp_order.h index 8df67df40..2472b0a4e 100644 --- a/modules/chibi/cp_order.h +++ b/modules/chibi/cp_order.h @@ -29,15 +29,13 @@ #ifndef CP_ORDER_H #define CP_ORDER_H - #include "cp_config.h" enum CPOrderType { - CP_ORDER_NONE=255, - CP_ORDER_BREAK=254 + CP_ORDER_NONE = 255, + CP_ORDER_BREAK = 254 }; typedef uint8_t CPOrder; #endif - diff --git a/modules/chibi/cp_pattern.cpp b/modules/chibi/cp_pattern.cpp index 8671b6247..699c769e3 100644 --- a/modules/chibi/cp_pattern.cpp +++ b/modules/chibi/cp_pattern.cpp @@ -30,68 +30,60 @@ void CPPattern::clear() { - if (event_count>0) { - - + if (event_count > 0) { + CP_FREE(events); - events=NULL; - event_count=0; + events = NULL; + event_count = 0; } - length=DEFAULT_LEN; - + length = DEFAULT_LEN; } - bool CPPattern::resize_event_list_to(uint32_t p_events) { - //Module is slow in some cpus, so this should be fast enough - uint32_t new_size=((p_events-1)&(~((1<<RESIZE_EVERY_BITS)-1)))+(1<<RESIZE_EVERY_BITS); - - CP_ERR_COND_V(new_size<p_events,true); //bugARM_INFO - - if (event_count==0 && new_size==0) + uint32_t new_size = ((p_events - 1) & (~((1 << RESIZE_EVERY_BITS) - 1))) + (1 << RESIZE_EVERY_BITS); + + CP_ERR_COND_V(new_size < p_events, true); //bugARM_INFO + + if (event_count == 0 && new_size == 0) return false; //nothing to do - - if (event_count==0) { - - events=(Event*)CP_ALLOC( new_size*sizeof(Event) ); - } else if (new_size==0) { - + if (event_count == 0) { + + events = (Event *)CP_ALLOC(new_size * sizeof(Event)); + + } else if (new_size == 0) { + CP_FREE(events); - events=NULL; + events = NULL; } else { - - CP_ERR_COND_V(events==NULL,true); - events=(Event*)CP_REALLOC(events, new_size*sizeof(Event)); + CP_ERR_COND_V(events == NULL, true); + events = (Event *)CP_REALLOC(events, new_size * sizeof(Event)); } - - event_count=p_events; - + + event_count = p_events; + return false; } - int32_t CPPattern::get_event_pos(uint16_t p_target_pos) { - - - if (event_count==0) + + if (event_count == 0) return -1; - + int low = 0; - int high = event_count -1; + int high = event_count - 1; int middle; - - while( low <= high ) - { - middle = ( low + high ) / 2; - if( p_target_pos == events[middle].pos ) { //match + while (low <= high) { + middle = (low + high) / 2; + + if (p_target_pos == events[middle].pos) { //match break; - } else if( p_target_pos < events[middle].pos ) + } else if (p_target_pos < events[middle].pos) high = middle - 1; //search low end of array else low = middle + 1; //search high end of array @@ -99,10 +91,10 @@ int32_t CPPattern::get_event_pos(uint16_t p_target_pos) { /* adapt so we are behind 2 */ - if (events[middle].pos<p_target_pos) + if (events[middle].pos < p_target_pos) middle++; return middle; - + /* Linear search for now */ /* @@ -114,386 +106,346 @@ int32_t CPPattern::get_event_pos(uint16_t p_target_pos) { break; } */ - + //return pos_idx; } bool CPPattern::erase_event_at_pos(uint16_t p_pos) { - - if (event_count==0) + + if (event_count == 0) return false; - - - Event *event_list=events; + Event *event_list = events; int32_t pos_idx = get_event_pos(p_pos); - if (pos_idx==-1) { - CP_ERR_COND_V(pos_idx==-1,true); + if (pos_idx == -1) { + CP_ERR_COND_V(pos_idx == -1, true); } - - if (pos_idx==event_count || event_list[pos_idx].pos!=p_pos) { + + if (pos_idx == event_count || event_list[pos_idx].pos != p_pos) { /* Nothing to Erase */ return false; } - - for (int32_t i=pos_idx;i<(event_count-1);i++) { - - event_list[i]=event_list[i+1]; + + for (int32_t i = pos_idx; i < (event_count - 1); i++) { + + event_list[i] = event_list[i + 1]; } - - resize_event_list_to(event_count-1); - + resize_event_list_to(event_count - 1); + return false; } -bool CPPattern::set_note(uint8_t p_column, uint16_t p_row,const CPNote& p_note) { +bool CPPattern::set_note(uint8_t p_column, uint16_t p_row, const CPNote &p_note) { + + CP_ERR_COND_V(p_column >= WIDTH, true); + CP_ERR_COND_V(p_row >= length, true); - CP_ERR_COND_V(p_column>=WIDTH,true); - CP_ERR_COND_V(p_row>=length,true); - int32_t new_pos; - uint16_t target_pos=p_row*WIDTH+p_column; - + uint16_t target_pos = p_row * WIDTH + p_column; - if (p_note.is_empty()) { - bool res=erase_event_at_pos(target_pos); + bool res = erase_event_at_pos(target_pos); - return res;; + return res; + ; } - - Event *event_list=0; - - if (event_count==0) { + + Event *event_list = 0; + + if (event_count == 0) { /* If no events, create the first */ - + if (resize_event_list_to(1)) { CP_PRINTERR("Can't resize event list to 1"); return true; } - event_list=events; - if (event_list==0) { - + event_list = events; + if (event_list == 0) { CP_PRINTERR("Can't get event list"); return true; } - - new_pos=0; - + + new_pos = 0; + } else { /* Prepare to add */ - - event_list=events; - if (event_list==0) { - + + event_list = events; + if (event_list == 0) { CP_PRINTERR("Can't get event list"); return true; } - + int32_t pos_idx = get_event_pos(target_pos); - - if (pos_idx==-1) { + if (pos_idx == -1) { CP_PRINTERR("Can't find add position"); return true; } - - - if (pos_idx==event_count || event_list[pos_idx].pos!=target_pos) { + + if (pos_idx == event_count || event_list[pos_idx].pos != target_pos) { /* If the note being modified didnt exist, then we add it */ //resize, and return if out of mem - if (resize_event_list_to( event_count+1)) { - + if (resize_event_list_to(event_count + 1)) { CP_PRINTERR("Can't resize event list"); return true; } - event_list=events; - if (event_list==0) { - + event_list = events; + if (event_list == 0) { CP_PRINTERR("Can't get event list"); return true; } - + //make room for new pos, this wont do a thing if pos_idx was ==event_count - for(int32_t i=(event_count-1);i>pos_idx;i--) { - event_list[i]=event_list[i-1]; - + for (int32_t i = (event_count - 1); i > pos_idx; i--) { + event_list[i] = event_list[i - 1]; } - + } /* Else it means that position is taken, so we just modify it! */ - - - new_pos=pos_idx; + + new_pos = pos_idx; } - - event_list[new_pos].pos=target_pos; - event_list[new_pos].note=p_note.note; - event_list[new_pos].instrument=p_note.instrument; - event_list[new_pos].volume=p_note.volume; - event_list[new_pos].command=p_note.command; - event_list[new_pos].parameter=p_note.parameter; - event_list[new_pos].script_source_sign=p_note.script_source_sign; - event_list[new_pos].cloned=p_note.cloned; - - + event_list[new_pos].pos = target_pos; + event_list[new_pos].note = p_note.note; + event_list[new_pos].instrument = p_note.instrument; + event_list[new_pos].volume = p_note.volume; + event_list[new_pos].command = p_note.command; + event_list[new_pos].parameter = p_note.parameter; + event_list[new_pos].script_source_sign = p_note.script_source_sign; + event_list[new_pos].cloned = p_note.cloned; return false; - } -CPNote CPPattern::get_note(uint8_t p_column,uint16_t p_row) { +CPNote CPPattern::get_note(uint8_t p_column, uint16_t p_row) { + + if (p_column == CPNote::EMPTY) return CPNote(); - if (p_column==CPNote::EMPTY) return CPNote(); - - CP_ERR_COND_V(p_column>=WIDTH,CPNote()); - CP_ERR_COND_V(p_row>=length,CPNote()); + CP_ERR_COND_V(p_column >= WIDTH, CPNote()); + CP_ERR_COND_V(p_row >= length, CPNote()); - if (event_count==0) + if (event_count == 0) return CPNote(); - - Event *event_list=events; - - CP_ERR_COND_V(event_list==0,CPNote()); - - uint16_t target_pos=p_row*WIDTH+p_column; + Event *event_list = events; + + CP_ERR_COND_V(event_list == 0, CPNote()); + + uint16_t target_pos = p_row * WIDTH + p_column; int32_t pos_idx = get_event_pos(target_pos); - if (pos_idx==-1) { + if (pos_idx == -1) { CP_PRINTERR("Can't find event pos"); return CPNote(); } - - if (pos_idx>=event_count || event_list[pos_idx].pos!=target_pos) { + + if (pos_idx >= event_count || event_list[pos_idx].pos != target_pos) { /* no note found */ return CPNote(); } - + CPNote n; - n.note=event_list[pos_idx].note; - n.instrument=event_list[pos_idx].instrument; - n.volume=event_list[pos_idx].volume; - n.command=event_list[pos_idx].command; - n.parameter=event_list[pos_idx].parameter; - n.script_source_sign=event_list[pos_idx].script_source_sign; - n.cloned=event_list[pos_idx].cloned; - + n.note = event_list[pos_idx].note; + n.instrument = event_list[pos_idx].instrument; + n.volume = event_list[pos_idx].volume; + n.command = event_list[pos_idx].command; + n.parameter = event_list[pos_idx].parameter; + n.script_source_sign = event_list[pos_idx].script_source_sign; + n.cloned = event_list[pos_idx].cloned; return n; - } -CPNote CPPattern::get_transformed_script_note(uint8_t p_column,uint16_t p_row ) { - - CPNote n = get_note( p_column, p_row ); - +CPNote CPPattern::get_transformed_script_note(uint8_t p_column, uint16_t p_row) { + + CPNote n = get_note(p_column, p_row); + // get source channel and note - - int channel = get_scripted_note_target_channel( p_column, p_row ); - CPNote src_n = get_note( channel, 0 ); - - if ( src_n.note == CPNote::SCRIPT ) return CPNote(); - - script_transform_note( src_n, n ); - + + int channel = get_scripted_note_target_channel(p_column, p_row); + CPNote src_n = get_note(channel, 0); + + if (src_n.note == CPNote::SCRIPT) return CPNote(); + + script_transform_note(src_n, n); + return src_n; - } int CPPattern::get_scripted_note_target_channel(uint8_t p_column, uint16_t p_row) { - - CPNote n = get_note( p_column, p_row ); - - if ( n.note != CPNote::SCRIPT ) return CPNote::EMPTY; - + + CPNote n = get_note(p_column, p_row); + + if (n.note != CPNote::SCRIPT) return CPNote::EMPTY; + int channel = n.instrument; - - if ( n.script_source_sign == '\0' ) { - - if ( channel < 0 || channel >= CPPattern::WIDTH ) return CPNote::EMPTY; - + + if (n.script_source_sign == '\0') { + + if (channel < 0 || channel >= CPPattern::WIDTH) return CPNote::EMPTY; + } else { - - channel = p_column + ( ( n.script_source_sign=='+') ? 1 : -1 ) * (channel+1); - if ( channel < 0 || channel >= CPPattern::WIDTH ) return CPNote::EMPTY; - + + channel = p_column + ((n.script_source_sign == '+') ? 1 : -1) * (channel + 1); + if (channel < 0 || channel >= CPPattern::WIDTH) return CPNote::EMPTY; } - + return channel; } void CPPattern::scripted_clone(uint8_t p_column, uint16_t p_row) { - - int channel = get_scripted_note_target_channel( p_column, p_row ); + + int channel = get_scripted_note_target_channel(p_column, p_row); int src_row = 1; - CPNote script_n = get_note( p_column, p_row ); - - for ( int row = p_row+1; row < length; ++row ) { - - CPNote src_n = get_note( channel, src_row ); - CPNote target_n = get_note( p_column, row ); - - if ( target_n.note != CPNote::SCRIPT ) { - if ( src_n.note == CPNote::SCRIPT ) { - src_n = CPNote(); - channel = CPNote::EMPTY; + CPNote script_n = get_note(p_column, p_row); + + for (int row = p_row + 1; row < length; ++row) { + + CPNote src_n = get_note(channel, src_row); + CPNote target_n = get_note(p_column, row); + + if (target_n.note != CPNote::SCRIPT) { + if (src_n.note == CPNote::SCRIPT) { + src_n = CPNote(); + channel = CPNote::EMPTY; + } + + script_transform_note(src_n, script_n); + + src_n.cloned = true; + set_note(p_column, row, src_n); + + } else { + + return; } - - script_transform_note( src_n, script_n ); - - src_n.cloned = true; - set_note( p_column, row, src_n ); - - } else { - - return; - - } - - src_row++; + + src_row++; } - } void CPPattern::scripted_clone_remove(uint8_t p_column, uint16_t p_row) { - - if ( get_note( p_column, p_row ).cloned ) - set_note( p_column, p_row, CPNote() ); - - for ( int row = p_row+1; row < length; ++row ) { - - CPNote target_n = get_note( p_column, row ); - - if ( target_n.note != CPNote::SCRIPT ) { - - set_note( p_column, row, CPNote() ); - - } else { - - return; - - } - + + if (get_note(p_column, p_row).cloned) + set_note(p_column, p_row, CPNote()); + + for (int row = p_row + 1; row < length; ++row) { + + CPNote target_n = get_note(p_column, row); + + if (target_n.note != CPNote::SCRIPT) { + + set_note(p_column, row, CPNote()); + + } else { + + return; + } } - } -void CPPattern::script_transform_note(CPNote& n, const CPNote& p_note) { - +void CPPattern::script_transform_note(CPNote &n, const CPNote &p_note) { + // set instrument - - if ( n.note < CPNote::NOTES && p_note.volume != CPNote::EMPTY ) { - - n.instrument = p_note.volume; - + + if (n.note < CPNote::NOTES && p_note.volume != CPNote::EMPTY) { + + n.instrument = p_note.volume; } - + // transpose - - if ( n.note < CPNote::NOTES && p_note.command != CPNote::EMPTY ) { - - int transpose = ( p_note.parameter & 0xF ) + ( p_note.parameter / 0x10 ) * 12; - - if ( p_note.command == '^' ) { - - if ( n.note >= CPNote::NOTES-transpose ) - n.note = CPNote::NOTES-1; - else - n.note += transpose; - - } else if ( p_note.command == 'v' ) { - - if ( n.note <= transpose ) - n.note = 0; - else - n.note -= transpose; - - } + + if (n.note < CPNote::NOTES && p_note.command != CPNote::EMPTY) { + + int transpose = (p_note.parameter & 0xF) + (p_note.parameter / 0x10) * 12; + + if (p_note.command == '^') { + + if (n.note >= CPNote::NOTES - transpose) + n.note = CPNote::NOTES - 1; + else + n.note += transpose; + + } else if (p_note.command == 'v') { + + if (n.note <= transpose) + n.note = 0; + else + n.note -= transpose; + } } - } -bool CPPattern::update_scripted_clones_sourcing_channel( int channel ) { - - bool updated = false; - - for ( int x = 0; x < WIDTH; ++x ) { - - for (int y = 0; y < length; ++y ) { - - if ( channel == get_scripted_note_target_channel( x, y ) ) { - - scripted_clone( x, y ); - updated = true; - } - +bool CPPattern::update_scripted_clones_sourcing_channel(int channel) { + + bool updated = false; + + for (int x = 0; x < WIDTH; ++x) { + + for (int y = 0; y < length; ++y) { + + if (channel == get_scripted_note_target_channel(x, y)) { + + scripted_clone(x, y); + updated = true; + } + } } - - } - - return updated; + + return updated; } void CPPattern::set_length(uint16_t p_rows) { - - - if (event_count==0) { - - if (p_rows>=MIN_ROWS) - length=p_rows; + if (event_count == 0) { - - return; - + if (p_rows >= MIN_ROWS) + length = p_rows; + + return; } - - if (p_rows<MIN_ROWS) { + + if (p_rows < MIN_ROWS) { return; } - - if (p_rows<length) { - - Event* event_list=events; - if (event_list==0) { + + if (p_rows < length) { + + Event *event_list = events; + if (event_list == 0) { CP_PRINTERR("get_event_list() Failed"); return; } - - uint16_t target_pos=p_rows*WIDTH; + uint16_t target_pos = p_rows * WIDTH; int32_t pos_idx = get_event_pos(target_pos); - - if (pos_idx==-1) { + if (pos_idx == -1) { - CP_ERR_COND(pos_idx==-1); + CP_ERR_COND(pos_idx == -1); } - + if (resize_event_list_to(pos_idx)) { CP_PRINTERR("resize_event_list_to(pos_idx) Failed"); return; } - } - - length=p_rows; - + length = p_rows; } #if 0 void CPPattern::copy_to(CPPattern *p_pattern) const { @@ -551,24 +503,21 @@ void CPPattern::copy_to(CPPattern *p_pattern) const { } #endif uint16_t CPPattern::get_length() { - - + return length; } CPPattern::CPPattern() { - - - length=DEFAULT_LEN; - event_count=0; + + length = DEFAULT_LEN; + event_count = 0; clear(); - } bool CPPattern::is_empty() { - - return events==NULL; + + return events == NULL; } CPPattern::~CPPattern() { - + clear(); } diff --git a/modules/chibi/cp_pattern.h b/modules/chibi/cp_pattern.h index fc3b03252..90cabe779 100644 --- a/modules/chibi/cp_pattern.h +++ b/modules/chibi/cp_pattern.h @@ -33,20 +33,18 @@ class CPPattern { public: - - - enum { - WIDTH=64, - DEFAULT_LEN=64, - RESIZE_EVERY_BITS=4, - MIN_ROWS=1, //otherwise clipboard wont work - MAX_LEN=256 - - }; - -private: + enum { + WIDTH = 64, + DEFAULT_LEN = 64, + RESIZE_EVERY_BITS = 4, + MIN_ROWS = 1, //otherwise clipboard wont work + MAX_LEN = 256 + + }; + +private: struct Event { - + uint16_t pos; //column*WIDTH+row uint8_t note; uint8_t instrument; @@ -59,36 +57,33 @@ private: uint16_t length; uint32_t event_count; - Event* events; - + Event *events; + int32_t get_event_pos(uint16_t p_target_pos); bool erase_event_at_pos(uint16_t p_pos); - + bool resize_event_list_to(uint32_t p_events); - - void operator=(const CPPattern& p_pattern); //no operator= + + void operator=(const CPPattern &p_pattern); //no operator= public: - bool is_empty(); void clear(); - bool set_note(uint8_t p_column, uint16_t p_row,const CPNote& p_note); //true if no more memory - CPNote get_note(uint8_t p_column,uint16_t p_row); - + bool set_note(uint8_t p_column, uint16_t p_row, const CPNote &p_note); //true if no more memory + CPNote get_note(uint8_t p_column, uint16_t p_row); + CPNote get_transformed_script_note(uint8_t p_column, uint16_t p_row); int get_scripted_note_target_channel(uint8_t p_column, uint16_t p_row); void scripted_clone(uint8_t p_column, uint16_t p_row); void scripted_clone_remove(uint8_t p_column, uint16_t p_row); - void script_transform_note(CPNote& n, const CPNote& p_note); + void script_transform_note(CPNote &n, const CPNote &p_note); bool update_scripted_clones_sourcing_channel(int channel); - + //void copy_to(CPPattern *p_pattern) const; void set_length(uint16_t p_rows); uint16_t get_length(); CPPattern(); ~CPPattern(); - - }; #endif diff --git a/modules/chibi/cp_player_data.cpp b/modules/chibi/cp_player_data.cpp index c8cbfbd06..9810dadda 100644 --- a/modules/chibi/cp_player_data.cpp +++ b/modules/chibi/cp_player_data.cpp @@ -30,122 +30,112 @@ #include "cp_player_data.h" #include <stdio.h> +CPPlayer::CPPlayer(CPMixer *p_mixer, CPSong *p_song) { -CPPlayer::CPPlayer(CPMixer *p_mixer,CPSong *p_song){ - - song=p_song; - mixer=p_mixer; - control.max_voices=p_mixer->get_total_voice_count()-1; //leave one for the sample - control.force_no_nna=false; - control.external_vibrato=false; - control.filters=true; - control.random_seed=128364; //anything - control.play_mode=0; + song = p_song; + mixer = p_mixer; + control.max_voices = p_mixer->get_total_voice_count() - 1; //leave one for the sample + control.force_no_nna = false; + control.external_vibrato = false; + control.filters = true; + control.random_seed = 128364; //anything + control.play_mode = 0; set_virtual_channels(p_mixer->get_total_voice_count()); - mixer->set_callback( &CPPlayer::callback_function, this ); + mixer->set_callback(&CPPlayer::callback_function, this); reset(); } -CPPlayer::~CPPlayer(){ +CPPlayer::~CPPlayer() { } void CPPlayer::set_virtual_channels(int p_amount) { - if (p_amount<1) return; - if (p_amount>mixer->get_total_voice_count()) + if (p_amount < 1) return; + if (p_amount > mixer->get_total_voice_count()) return; - - control.max_voices=p_amount; + control.max_voices = p_amount; } - void CPPlayer::callback_function(void *p_userdata) { - - CPPlayer*pd=(CPPlayer*)p_userdata; - pd->process_tick(); + CPPlayer *pd = (CPPlayer *)p_userdata; + pd->process_tick(); } void CPPlayer::process_tick() { handle_tick(); - mixer->set_callback_interval( 2500000/control.tempo ); - song_usecs+=2500000/control.tempo; + mixer->set_callback_interval(2500000 / control.tempo); + song_usecs += 2500000 / control.tempo; } void CPPlayer::reset() { - if ( mixer==NULL ) return ; - if ( song==NULL ) return ; + if (mixer == NULL) return; + if (song == NULL) return; int i; - for (i=0;i<control.max_voices;i++) { + for (i = 0; i < control.max_voices; i++) { - voice[i].reset(); + voice[i].reset(); mixer->stop_voice(i); } - - for (i=0;i<CPPattern::WIDTH;i++) { - control.channel[i].reset(); - control.channel[i].channel_volume=song->get_channel_volume(i); - control.channel[i].channel_panning=((int)song->get_channel_pan( i)*PAN_RIGHT/64); + for (i = 0; i < CPPattern::WIDTH; i++) { + + control.channel[i].reset(); + control.channel[i].channel_volume = song->get_channel_volume(i); + control.channel[i].channel_panning = ((int)song->get_channel_pan(i) * PAN_RIGHT / 64); if (song->is_channel_surround(i)) - control.channel[i].channel_panning=PAN_SURROUND; - control.channel[i].mute=song->is_channel_mute( i ); - control.channel[i].chorus_send=song->get_channel_chorus(i)*0xFF/64; - control.channel[i].reverb_send=song->get_channel_reverb(i)*0xFF/64; + control.channel[i].channel_panning = PAN_SURROUND; + control.channel[i].mute = song->is_channel_mute(i); + control.channel[i].chorus_send = song->get_channel_chorus(i) * 0xFF / 64; + control.channel[i].reverb_send = song->get_channel_reverb(i) * 0xFF / 64; } + control.speed = song->get_speed(); + control.tempo = song->get_tempo(); + control.global_volume = song->get_global_volume(); - control.speed=song->get_speed(); - control.tempo=song->get_tempo(); - control.global_volume=song->get_global_volume(); + control.position.current_pattern = 0; + control.position.current_row = 0; + control.position.current_order = 0; + control.position.force_next_order = -1; + control.ticks_counter = control.speed; + control.position.forbid_jump = false; - control.position.current_pattern=0; - control.position.current_row=0; - control.position.current_order=0; - control.position.force_next_order=-1; - control.ticks_counter=control.speed; - control.position.forbid_jump=false; - - song_usecs=0; - + song_usecs = 0; } int64_t CPPlayer::get_channel_last_note_time_usec(int p_channel) const { - CP_FAIL_INDEX_V(p_channel,64,-1); + CP_FAIL_INDEX_V(p_channel, 64, -1); return control.channel[p_channel].last_event_usecs; - } -void CPPlayer::set_channel_global_volume(int p_channel,int p_volume) { - - CP_FAIL_INDEX(p_channel,64); - control.channel[p_channel].channel_global_volume=CLAMP(p_volume,0,255); +void CPPlayer::set_channel_global_volume(int p_channel, int p_volume) { + CP_FAIL_INDEX(p_channel, 64); + control.channel[p_channel].channel_global_volume = CLAMP(p_volume, 0, 255); } -int CPPlayer::get_channel_global_volume(int p_channel) const{ +int CPPlayer::get_channel_global_volume(int p_channel) const { - CP_FAIL_INDEX_V(p_channel,64,-1); + CP_FAIL_INDEX_V(p_channel, 64, -1); return control.channel[p_channel].channel_global_volume; - } bool CPPlayer::reached_end_of_song() { return control.reached_end; - } void CPPlayer::set_force_external_vibratos(bool p_force) { - control.external_vibrato=p_force; + control.external_vibrato = p_force; } void CPPlayer::set_force_no_nna(bool p_force) { - control.force_no_nna=p_force; + control.force_no_nna = p_force; } diff --git a/modules/chibi/cp_player_data.h b/modules/chibi/cp_player_data.h index c59df5f0d..a6ff6c1d1 100644 --- a/modules/chibi/cp_player_data.h +++ b/modules/chibi/cp_player_data.h @@ -31,8 +31,8 @@ #define CP_PLAYER_DATA_H #include "cp_config.h" -#include "cp_song.h" #include "cp_mixer.h" +#include "cp_song.h" #include "cp_tables.h" /**CPPlayer Data @@ -49,46 +49,43 @@ I hope you dont get sick reading this //Default pan values - class CPPlayer { enum { - PAN_SURROUND=512, - PAN_RIGHT=255, - PAN_LEFT=0, - PAN_CENTER=128 + PAN_SURROUND = 512, + PAN_RIGHT = 255, + PAN_LEFT = 0, + PAN_CENTER = 128 }; - CPSong *song; CPMixer *mixer; - struct Filter_Control { + struct Filter_Control { int32_t it_reso; int32_t it_cutoff; int32_t envelope_cutoff; int32_t final_cutoff; - - void process(); - void set_filter_parameters(int *p_cutoff,uint8_t *p_reso); - }; + void process(); + void set_filter_parameters(int *p_cutoff, uint8_t *p_reso); + }; //tells you if a channel is doing //noteoff/notekill/notefade/etc enum { - - END_NOTE_NOTHING=0, - END_NOTE_OFF=1, - END_NOTE_FADE=2, - END_NOTE_KILL=4 + + END_NOTE_NOTHING = 0, + END_NOTE_OFF = 1, + END_NOTE_FADE = 2, + END_NOTE_KILL = 4 }; - + //Tells you what should a channel restart enum { - + KICK_NOTHING, KICK_NOTE, KICK_NOTEOFF, @@ -96,13 +93,13 @@ class CPPlayer { }; enum { - - MAX_VOICES=256 + + MAX_VOICES = 256 }; - + struct Channel_Control; - struct Voice_Control { + struct Voice_Control { struct Envelope_Control { @@ -114,25 +111,24 @@ class CPPlayer { bool terminated; bool active; bool kill; - }; - Filter_Control filter; - uint16_t reverb_send; - uint16_t chorus_send; + Filter_Control filter; + uint16_t reverb_send; + uint16_t chorus_send; - CPInstrument* instrument_ptr; - CPSample* sample_ptr; + CPInstrument *instrument_ptr; + CPSample *sample_ptr; -// Sample_Data *sample_data; + // Sample_Data *sample_data; - int32_t period; + int32_t period; - int32_t sample_start_index; /* The starting byte index in the sample */ + int32_t sample_start_index; /* The starting byte index in the sample */ bool has_master_channel; int master_channel_index; - int instruement_index; + int instruement_index; int instrument_index; int sample_index; @@ -140,27 +136,27 @@ class CPPlayer { int note_end_flags; - uint8_t sample; /* which instrument number */ + uint8_t sample; /* which instrument number */ - int16_t output_volume; /* output volume (vol + sampcol + instvol) */ - int8_t channel_volume; /* channel's "global" volume */ - uint16_t fadeout_volume; /* fading volume rate */ - int32_t total_volume; /* total volume of channel (before global mixings) */ - uint8_t kick; /* if true = sample has to be restarted */ - - uint8_t note; /* the audible note (as heard, direct rep of period) */ + int16_t output_volume; /* output volume (vol + sampcol + instvol) */ + int8_t channel_volume; /* channel's "global" volume */ + uint16_t fadeout_volume; /* fading volume rate */ + int32_t total_volume; /* total volume of channel (before global mixings) */ + uint8_t kick; /* if true = sample has to be restarted */ - int16_t panning; /* panning position */ - - uint8_t nna; /* New note action type + master/slave flags */ - uint8_t volflg; /* volume envelope settings */ - uint8_t panflg; /* panning envelope settings */ - uint8_t pitflg; /* pitch envelope settings */ - uint8_t keyoff; /* if true = fade out and stuff */ - int16_t handle; /* which sample-handle */ - int32_t start; /* The start byte index in the sample */ - - /* Below here is info NOT in MP_CONTROL!! */ + uint8_t note; /* the audible note (as heard, direct rep of period) */ + + int16_t panning; /* panning position */ + + uint8_t nna; /* New note action type + master/slave flags */ + uint8_t volflg; /* volume envelope settings */ + uint8_t panflg; /* panning envelope settings */ + uint8_t pitflg; /* pitch envelope settings */ + uint8_t keyoff; /* if true = fade out and stuff */ + int16_t handle; /* which sample-handle */ + int32_t start; /* The start byte index in the sample */ + + /* Below here is info NOT in MP_CONTROL!! */ //ENVPR venv; //ENVPR penv; //ENVPR cenv; @@ -168,60 +164,56 @@ class CPPlayer { Envelope_Control volume_envelope_ctrl; Envelope_Control panning_envelope_ctrl; Envelope_Control pitch_envelope_ctrl; - - uint16_t auto_vibrato_pos; /* autovibrato pos */ - uint16_t auto_vibrato_sweep_pos; /* autovibrato sweep pos */ - - int16_t masterchn; - uint16_t masterperiod; - - Channel_Control* master_channel; /* index of "master" effects channel */ - void start_envelope(CPEnvelope *p_envelope,Envelope_Control *p_envelope_ctrl,Envelope_Control *p_from_env); - bool process_envelope(CPEnvelope *p_envelope,Envelope_Control *p_envelope_ctrl); + uint16_t auto_vibrato_pos; /* autovibrato pos */ + uint16_t auto_vibrato_sweep_pos; /* autovibrato sweep pos */ + + int16_t masterchn; + uint16_t masterperiod; + + Channel_Control *master_channel; /* index of "master" effects channel */ + + void start_envelope(CPEnvelope *p_envelope, Envelope_Control *p_envelope_ctrl, Envelope_Control *p_from_env); + bool process_envelope(CPEnvelope *p_envelope, Envelope_Control *p_envelope_ctrl); uint16_t display_volume; - + Voice_Control() { - + reset(); } void reset(); - void update_info_from_master_channel(); - - + void update_info_from_master_channel(); }; - struct Channel_Control { /* NOTE info */ - uint8_t note; /* the audible note as heard, direct rep of period */ - uint8_t real_note; /* the note that indexes the audible */ - int32_t sample_start_index; /* The starting byte index in the sample */ - uint8_t old_note; + uint8_t note; /* the audible note as heard, direct rep of period */ + uint8_t real_note; /* the note that indexes the audible */ + int32_t sample_start_index; /* The starting byte index in the sample */ + uint8_t old_note; uint8_t kick; - - Filter_Control filter; - uint16_t reverb_send; - uint16_t chorus_send; - + Filter_Control filter; + uint16_t reverb_send; + uint16_t chorus_send; + int note_end_flags; /* INSTRUMENT INFO */ - CPInstrument* instrument_ptr; - CPSample* sample_ptr; + CPInstrument *instrument_ptr; + CPSample *sample_ptr; - uint8_t instrument_index; - uint8_t sample_index; + uint8_t instrument_index; + uint8_t sample_index; bool new_instrument; /* SAMPLE SPECIFIC INFO */ - int32_t base_speed; /* what finetune to use */ + int32_t base_speed; /* what finetune to use */ /* INSTRUMENT SPECIFIC INFO */ @@ -233,13 +225,13 @@ class CPPlayer { bool panning_envelope_on; bool pitch_envelope_on; - bool has_own_period; + bool has_own_period; bool row_has_note; /* VOLUME COLUMN */ - int16_t volume; /* amiga volume (0 t/m 64) to play the sample at */ + int16_t volume; /* amiga volume (0 t/m 64) to play the sample at */ int16_t aux_volume; bool has_own_volume; bool mute; @@ -247,34 +239,32 @@ class CPPlayer { /* VOLUME/PAN/PITCH MODIFIERS */ - int8_t default_volume; // CHANNEL default volume (0-64) - int16_t channel_volume; // CHANNEL current volume //chanvol - current! - int16_t output_volume; /* output volume (vol + sampcol + instvol) //volume */ - int16_t channel_global_volume; - - uint16_t fadeout_volume; /* fading volume rate */ + int8_t default_volume; // CHANNEL default volume (0-64) + int16_t channel_volume; // CHANNEL current volume //chanvol - current! + int16_t output_volume; /* output volume (vol + sampcol + instvol) //volume */ + int16_t channel_global_volume; - int32_t period; /* period to play the sample at */ - - /* PAN */ + uint16_t fadeout_volume; /* fading volume rate */ - int16_t panning; /* panning position */ - int16_t channel_panning; - int8_t sliding; + int32_t period; /* period to play the sample at */ - uint16_t aux_period; /* temporary period */ + /* PAN */ + int16_t panning; /* panning position */ + int16_t channel_panning; + int8_t sliding; + uint16_t aux_period; /* temporary period */ /* TIMING */ - uint8_t note_delay; /* (used for note delay) */ + uint8_t note_delay; /* (used for note delay) */ /* Slave Voice Control */ - Voice_Control *slave_voice; /* Audio Slave of current effects control channel */ - + Voice_Control *slave_voice; /* Audio Slave of current effects control channel */ + struct Carry { - + Voice_Control::Envelope_Control vol; Voice_Control::Envelope_Control pan; Voice_Control::Envelope_Control pitch; @@ -282,11 +272,9 @@ class CPPlayer { } carry; + uint8_t slave_voice_index; /* Audio Slave of current effects control channel */ - - uint8_t slave_voice_index; /* Audio Slave of current effects control channel */ - - uint8_t* row; /* row currently playing on this channel */ + uint8_t *row; /* row currently playing on this channel */ /* effect memory variables */ @@ -302,65 +290,65 @@ class CPPlayer { int32_t hi_offset; /* Panbrello waveform */ - uint8_t panbrello_type; /* current panbrello waveform */ - uint8_t panbrello_position; /* current panbrello position */ - int8_t panbrello_speed; /* "" speed */ - uint8_t panbrello_depth; /* "" depth */ - uint8_t panbrello_info; - /* Arpegio */ + uint8_t panbrello_type; /* current panbrello waveform */ + uint8_t panbrello_position; /* current panbrello position */ + int8_t panbrello_speed; /* "" speed */ + uint8_t panbrello_depth; /* "" depth */ + uint8_t panbrello_info; + /* Arpegio */ - uint8_t arpegio_info; - /* CPPattern Loop */ + uint8_t arpegio_info; + /* CPPattern Loop */ int pattern_loop_position; int8_t pattern_loop_count; - /* Vibrato */ - bool doing_vibrato; - int8_t vibrato_position; /* current vibrato position */ - uint8_t vibrato_speed; /* "" speed */ - uint8_t vibrato_depth; /* "" depth */ - uint8_t vibrato_type; + /* Vibrato */ + bool doing_vibrato; + int8_t vibrato_position; /* current vibrato position */ + uint8_t vibrato_speed; /* "" speed */ + uint8_t vibrato_depth; /* "" depth */ + uint8_t vibrato_type; /* Tremor */ - int8_t tremor_position; - uint8_t tremor_speed; /* s3m tremor ontime/offtime */ - uint8_t tremor_depth; - uint8_t tremor_info; + int8_t tremor_position; + uint8_t tremor_speed; /* s3m tremor ontime/offtime */ + uint8_t tremor_depth; + uint8_t tremor_info; /* Tremolo */ - int8_t tremolo_position; - uint8_t tremolo_speed; /* s3m tremor ontime/offtime */ - uint8_t tremolo_depth; - uint8_t tremolo_info; - uint8_t tremolo_type; + int8_t tremolo_position; + uint8_t tremolo_speed; /* s3m tremor ontime/offtime */ + uint8_t tremolo_depth; + uint8_t tremolo_info; + uint8_t tremolo_type; /* Retrig */ - int8_t retrig_counter; /* retrig value (0 means don't retrig) */ - uint8_t retrig_speed; /* last used retrig speed */ - uint8_t retrig_volslide; /* last used retrig slide */ + int8_t retrig_counter; /* retrig value (0 means don't retrig) */ + uint8_t retrig_speed; /* last used retrig speed */ + uint8_t retrig_volslide; /* last used retrig slide */ /* CPSample Offset */ - int32_t sample_offset_hi; /* last used high order of sample offset */ - uint16_t sample_offset; /* last used low order of sample-offset (effect 9) */ - uint16_t sample_offset_fine; /* fine sample offset memory */ + int32_t sample_offset_hi; /* last used high order of sample offset */ + uint16_t sample_offset; /* last used low order of sample-offset (effect 9) */ + uint16_t sample_offset_fine; /* fine sample offset memory */ /* Portamento */ uint16_t slide_to_period; /* period to slide to (with effect 3 or 5) */ uint8_t portamento_speed; - /* Volume Slide */ + /* Volume Slide */ uint8_t volume_slide_info; - /* Channel Volume Slide */ + /* Channel Volume Slide */ uint8_t channel_volume_slide_info; - /* Global Volume Slide */ + /* Global Volume Slide */ - uint8_t global_volume_slide_info; + uint8_t global_volume_slide_info; - /* Channel Pan Slide */ + /* Channel Pan Slide */ uint8_t channel_pan_slide_info; @@ -371,30 +359,33 @@ class CPPlayer { uint8_t tempo_slide_info; - /* S effects memory */ + /* S effects memory */ - uint8_t current_S_effect; - uint8_t current_S_data; + uint8_t current_S_effect; + uint8_t current_S_data; /* Volume column memory */ - uint8_t volume_column_effect_mem; - uint8_t volume_column_data_mem; + uint8_t volume_column_effect_mem; + uint8_t volume_column_data_mem; int64_t last_event_usecs; bool reserved; - + void reset(); - Channel_Control() { channel_global_volume=255; last_event_usecs=-1; } + Channel_Control() { + channel_global_volume = 255; + last_event_usecs = -1; + } }; - + struct Control_Variables { // control variables (dynamic version) of initial variables bool reached_end; - + char play_mode; - bool filters; + bool filters; int global_volume; int speed; int tempo; @@ -412,7 +403,7 @@ class CPPlayer { bool force_no_nna; bool external_vibrato; - + struct Position { int current_order; @@ -426,156 +417,144 @@ class CPPlayer { Position position; Position previous_position; - }; - Voice_Control voice[MAX_VOICES]; - + Control_Variables control; /* VOICE SETUP */ - + void setup_voices(); /* MIXER SETUP */ void handle_tick(); void update_mixer(); - + /* NOTE / INSTRUMENT PROCESSING */ - void process_new_note(int p_track,uint8_t p_note); - bool process_new_instrument(int p_track,uint8_t p_instrument); - bool process_note_and_instrument(int p_track,int p_note,int p_instrument); - + void process_new_note(int p_track, uint8_t p_note); + bool process_new_instrument(int p_track, uint8_t p_instrument); + bool process_note_and_instrument(int p_track, int p_note, int p_instrument); + /* EFFECT PROCESSING */ void do_effect_S(int p_track); void do_panbrello(int p_track); void do_global_volume_slide(int p_track); - void do_tremolo(int p_track); - void do_retrig(int p_track); + void do_tremolo(int p_track); + void do_retrig(int p_track); void do_pan_slide(int p_track); - void do_channel_volume_slide(int p_track); - void do_volume_slide(int p_track,int inf); - void do_pitch_slide_down(int p_track,uint8_t inf); - void do_pitch_slide_up(int p_track,uint8_t inf); - void do_tremor(int p_track); - void do_vibrato(int p_track,bool fine); - void do_pitch_slide_to_note(int p_track); - void run_effects(int p_track); - void run_volume_column_effects(int p_track); - void pre_process_effects(); - void do_arpegio(int p_track); + void do_channel_volume_slide(int p_track); + void do_volume_slide(int p_track, int inf); + void do_pitch_slide_down(int p_track, uint8_t inf); + void do_pitch_slide_up(int p_track, uint8_t inf); + void do_tremor(int p_track); + void do_vibrato(int p_track, bool fine); + void do_pitch_slide_to_note(int p_track); + void run_effects(int p_track); + void run_volume_column_effects(int p_track); + void pre_process_effects(); + void do_arpegio(int p_track); uint64_t song_usecs; /* NNA */ void process_NNAs(); - /* MISC UTILS */ - - int find_empty_voice(); - void process_volume_column(int p_track,uint8_t p_volume); - void process_note(int p_track,CPNote p_note); + int find_empty_voice(); + void process_volume_column(int p_track, uint8_t p_volume); + void process_note(int p_track, CPNote p_note); /* CPTables */ - static uint8_t auto_vibrato_table[128]; - static uint8_t vibrato_table[32]; - static int8_t panbrello_table[256]; + static uint8_t auto_vibrato_table[128]; + static uint8_t vibrato_table[32]; + static int8_t panbrello_table[256]; static void callback_function(void *p_userdata); public: - //Play modes + //Play modes enum { - - PLAY_NOTHING =0, - PLAY_PATTERN =1, - PLAY_SONG =2 - }; + PLAY_NOTHING = 0, + PLAY_PATTERN = 1, + PLAY_SONG = 2 + }; - int32_t get_frequency(int32_t period); - int32_t get_period(uint16_t note,int32_t p_c5freq); - + int32_t get_frequency(int32_t period); + int32_t get_period(uint16_t note, int32_t p_c5freq); int get_current_tempo() { return control.tempo; }; int get_current_speed() { return control.speed; }; - int get_voices_used() { return control.voices_used;}; - int get_voice_envelope_pos(int p_voice,CPEnvelope *p_envelope); + int get_voices_used() { return control.voices_used; }; + int get_voice_envelope_pos(int p_voice, CPEnvelope *p_envelope); int get_voice_amount_limit() { return control.max_voices; }; void set_voice_amount_limit(int p_limit); void set_reserved_voices(int p_amount); int get_reserved_voices_amount(); - + bool is_voice_active(int p_voice); int get_channel_voice(int p_channel); - const char* get_voice_sample_name(int p_voice); - const char* get_voice_instrument_name(int p_voice); - CPEnvelope* get_voice_envelope(int p_voice,CPInstrument::EnvelopeType p_env_type); - int get_voice_envelope_pos(int p_voice,CPInstrument::EnvelopeType p_env_type); + const char *get_voice_sample_name(int p_voice); + const char *get_voice_instrument_name(int p_voice); + CPEnvelope *get_voice_envelope(int p_voice, CPInstrument::EnvelopeType p_env_type); + int get_voice_envelope_pos(int p_voice, CPInstrument::EnvelopeType p_env_type); int get_voice_volume(int p_voice); - + int get_voice_sample_index(int p_voice); void set_virtual_channels(int p_amount); int get_virtual_channels() { return control.max_voices; }; - /* Play Info/Position */ - bool is_playing() { return (control.play_mode>0); }; - int get_play_mode() {return (control.play_mode);}; + bool is_playing() { return (control.play_mode > 0); }; + int get_play_mode() { return (control.play_mode); }; int get_current_order() { return control.position.current_order; }; int get_current_row() { return control.position.current_row; }; int get_current_pattern() { return control.position.current_pattern; }; - void goto_next_order(); - void goto_previous_order(); + void goto_next_order(); + void goto_previous_order(); void process_tick(); + CPMixer *get_mixer_ptr() { - CPMixer* get_mixer_ptr() { - - return mixer; + return mixer; } - void reset(); - - /* External player control - editor - */ - void play_start_pattern(int p_pattern); + void play_start_pattern(int p_pattern); void play_start_song(); void play_start_song_from_order(int p_order); - void play_start_song_from_order_and_row(int p_order,int p_row); - void play_start(int p_pattern, int p_order, int p_row,bool p_lock=true); + void play_start_song_from_order_and_row(int p_order, int p_row); + void play_start(int p_pattern, int p_order, int p_row, bool p_lock = true); + + void play_stop(); + void play_note(int p_channel, CPNote note, bool p_reserve = false); - void play_stop(); - void play_note(int p_channel,CPNote note,bool p_reserve=false); + bool reached_end_of_song(); - bool reached_end_of_song(); - - void set_force_no_nna(bool p_force); - void set_force_external_vibratos(bool p_force); + void set_force_no_nna(bool p_force); + void set_force_external_vibratos(bool p_force); - void set_filters_enabled(bool p_enable); - bool are_filters_enabled() { return control.filters; } + void set_filters_enabled(bool p_enable); + bool are_filters_enabled() { return control.filters; } - void set_channel_global_volume(int p_channel,int p_volume); //0-255 + void set_channel_global_volume(int p_channel, int p_volume); //0-255 int get_channel_global_volume(int p_channel) const; int64_t get_channel_last_note_time_usec(int p_channel) const; CPSong *get_song() { return song; }; - - CPPlayer(CPMixer *p_mixer,CPSong *p_song); + CPPlayer(CPMixer *p_mixer, CPSong *p_song); ~CPPlayer(); }; diff --git a/modules/chibi/cp_player_data_control.cpp b/modules/chibi/cp_player_data_control.cpp index 2ef1c1de8..19837cc39 100644 --- a/modules/chibi/cp_player_data_control.cpp +++ b/modules/chibi/cp_player_data_control.cpp @@ -31,291 +31,238 @@ void CPPlayer::play_start_pattern(int p_pattern) { - play_start(p_pattern,-1,-1); + play_start(p_pattern, -1, -1); } void CPPlayer::play_start_song() { - play_start(-1,-1,-1); + play_start(-1, -1, -1); } void CPPlayer::play_start_song_from_order(int p_order) { - play_start(-1,p_order,-1); + play_start(-1, p_order, -1); } -void CPPlayer::play_start_song_from_order_and_row(int p_order,int p_row) { +void CPPlayer::play_start_song_from_order_and_row(int p_order, int p_row) { - play_start(-1,p_order,p_row); + play_start(-1, p_order, p_row); } -void CPPlayer::play_start(int p_pattern, int p_order, int p_row,bool p_lock) { - - - if (control.play_mode!=PLAY_NOTHING) play_stop(); +void CPPlayer::play_start(int p_pattern, int p_order, int p_row, bool p_lock) { + if (control.play_mode != PLAY_NOTHING) play_stop(); reset(); - if (p_pattern!=-1) { + if (p_pattern != -1) { - control.play_mode=PLAY_PATTERN; - control.position.current_pattern=p_pattern; - control.position.current_row=(p_row!=-1)?p_row:0; + control.play_mode = PLAY_PATTERN; + control.position.current_pattern = p_pattern; + control.position.current_row = (p_row != -1) ? p_row : 0; } else { - - control.position.current_order=get_song_next_order_idx(song,(p_order==-1)?p_order:p_order-1); - if (control.position.current_order!=-1) { - control.play_mode=PLAY_SONG; - control.position.current_pattern=song->get_order(control.position.current_order); - control.position.current_row=(p_row!=-1)?p_row:0; - } - } + control.position.current_order = get_song_next_order_idx(song, (p_order == -1) ? p_order : p_order - 1); + if (control.position.current_order != -1) { + control.play_mode = PLAY_SONG; + control.position.current_pattern = song->get_order(control.position.current_order); + control.position.current_row = (p_row != -1) ? p_row : 0; + } + } - control.reached_end=(control.play_mode==PLAY_NOTHING); - - + control.reached_end = (control.play_mode == PLAY_NOTHING); } void CPPlayer::play_stop() { int i; + control.play_mode = PLAY_NOTHING; - control.play_mode=PLAY_NOTHING; - - for (i=0;i<control.max_voices;i++) { + for (i = 0; i < control.max_voices; i++) { voice[i].reset(); mixer->stop_voice(i); } - for (i=0;i<CPPattern::WIDTH;i++) { + for (i = 0; i < CPPattern::WIDTH; i++) { control.channel[i].reset(); } reset(); - } -void CPPlayer::play_note(int p_channel,CPNote note,bool p_reserve) { - +void CPPlayer::play_note(int p_channel, CPNote note, bool p_reserve) { + if (control.play_mode == PLAY_NOTHING) { - if (control.play_mode==PLAY_NOTHING) { - - control.ticks_counter=0; + control.ticks_counter = 0; } /*control.channel[p_channel].reset(); control.channel[p_channel].channel_volume=song->get_channel_volume(p_channel); control.channel[p_channel].channel_panning=((int)song->get_channel_pan( p_channel)*255/64);*/ if (p_reserve) { - control.channel[p_channel].mute=false; - control.channel[p_channel].reserved=true; + control.channel[p_channel].mute = false; + control.channel[p_channel].reserved = true; } else { - - control.channel[p_channel].reserved=false; - - } - process_note(p_channel,note); - - + control.channel[p_channel].reserved = false; + } + process_note(p_channel, note); } - int CPPlayer::get_voice_volume(int p_voice) { - + return voice[p_voice].display_volume; } +int CPPlayer::get_voice_envelope_pos(int p_voice, CPEnvelope *p_envelope) { -int CPPlayer::get_voice_envelope_pos(int p_voice,CPEnvelope *p_envelope) { - - int i,tmp_index=-1; + int i, tmp_index = -1; - i=p_voice; + i = p_voice; + if ((song->has_instruments()) && (voice[i].instrument_ptr != NULL) && (voice[i].fadeout_volume > 0)) { + if ((p_envelope == voice[i].instrument_ptr->get_volume_envelope()) && (voice[i].instrument_ptr->get_volume_envelope()->is_enabled())) { - - if ((song->has_instruments()) && (voice[i].instrument_ptr!=NULL) && (voice[i].fadeout_volume>0)) { - - if ((p_envelope==voice[i].instrument_ptr->get_volume_envelope()) && (voice[i].instrument_ptr->get_volume_envelope()->is_enabled())) { - - tmp_index=voice[i].volume_envelope_ctrl.pos_index; + tmp_index = voice[i].volume_envelope_ctrl.pos_index; } - if ((p_envelope==voice[i].instrument_ptr->get_pan_envelope()) && (voice[i].instrument_ptr->get_pan_envelope()->is_enabled())) { + if ((p_envelope == voice[i].instrument_ptr->get_pan_envelope()) && (voice[i].instrument_ptr->get_pan_envelope()->is_enabled())) { - tmp_index=voice[i].panning_envelope_ctrl.pos_index; + tmp_index = voice[i].panning_envelope_ctrl.pos_index; } - if ((p_envelope==voice[i].instrument_ptr->get_pitch_filter_envelope()) && (voice[i].instrument_ptr->get_pitch_filter_envelope()->is_enabled())) { - + if ((p_envelope == voice[i].instrument_ptr->get_pitch_filter_envelope()) && (voice[i].instrument_ptr->get_pitch_filter_envelope()->is_enabled())) { - tmp_index=voice[i].pitch_envelope_ctrl.pos_index; + tmp_index = voice[i].pitch_envelope_ctrl.pos_index; } - } - - return tmp_index; } void CPPlayer::goto_next_order() { + if (control.play_mode != PLAY_SONG) return; - if (control.play_mode!=PLAY_SONG) return; - - + control.position.current_row = 0; - control.position.current_row=0; + control.position.current_order = get_song_next_order_idx(song, control.position.current_order); + if (control.position.current_order == -1) { - control.position.current_order=get_song_next_order_idx(song, control.position.current_order); - - - - if (control.position.current_order==-1) { - - reset(); + reset(); } - control.position.current_pattern=song->get_order(control.position.current_order); - - + control.position.current_pattern = song->get_order(control.position.current_order); } void CPPlayer::goto_previous_order() { - if (control.play_mode!=PLAY_SONG) return; - + if (control.play_mode != PLAY_SONG) return; - int next_order,current_order; + int next_order, current_order; - control.position.current_row=0; + control.position.current_row = 0; - current_order=control.position.current_order; + current_order = control.position.current_order; - next_order=get_song_next_order_idx(song, current_order); + next_order = get_song_next_order_idx(song, current_order); - while ((next_order!=control.position.current_order) && (next_order!=-1)) { + while ((next_order != control.position.current_order) && (next_order != -1)) { - current_order=next_order; - next_order=get_song_next_order_idx(song, current_order); + current_order = next_order; + next_order = get_song_next_order_idx(song, current_order); } - if (next_order==-1) { + if (next_order == -1) { - reset(); + reset(); } else { - control.position.current_order=current_order; - control.position.current_pattern=song->get_order(control.position.current_order); - + control.position.current_order = current_order; + control.position.current_pattern = song->get_order(control.position.current_order); } - - - } int CPPlayer::get_channel_voice(int p_channel) { - if (control.channel[p_channel].slave_voice==NULL) return -1; - else return control.channel[p_channel].slave_voice_index; + if (control.channel[p_channel].slave_voice == NULL) + return -1; + else + return control.channel[p_channel].slave_voice_index; } -const char* CPPlayer::get_voice_sample_name(int p_voice) { +const char *CPPlayer::get_voice_sample_name(int p_voice) { const char *name = NULL; - - - if (!voice[p_voice].sample_ptr) name=voice[p_voice].sample_ptr->get_name(); - - + if (!voice[p_voice].sample_ptr) name = voice[p_voice].sample_ptr->get_name(); return name; - } - bool CPPlayer::is_voice_active(int p_voice) { - return !( ((voice[p_voice].kick==KICK_NOTHING)||(voice[p_voice].kick==KICK_ENVELOPE))&&!mixer->is_voice_active(p_voice) ); - -} - + return !(((voice[p_voice].kick == KICK_NOTHING) || (voice[p_voice].kick == KICK_ENVELOPE)) && !mixer->is_voice_active(p_voice)); +} +int CPPlayer::get_voice_envelope_pos(int p_voice, CPInstrument::EnvelopeType p_env_type) { -int CPPlayer::get_voice_envelope_pos(int p_voice,CPInstrument::EnvelopeType p_env_type) { - if (!is_voice_active(p_voice)) return -1; - - Voice_Control::Envelope_Control *env=0; - + + Voice_Control::Envelope_Control *env = 0; + switch (p_env_type) { - - case CPInstrument::VOLUME_ENVELOPE: env=&voice[p_voice].volume_envelope_ctrl; break; - case CPInstrument::PAN_ENVELOPE: env=&voice[p_voice].panning_envelope_ctrl; break; - case CPInstrument::PITCH_ENVELOPE: env=&voice[p_voice].pitch_envelope_ctrl; break; - + + case CPInstrument::VOLUME_ENVELOPE: env = &voice[p_voice].volume_envelope_ctrl; break; + case CPInstrument::PAN_ENVELOPE: env = &voice[p_voice].panning_envelope_ctrl; break; + case CPInstrument::PITCH_ENVELOPE: env = &voice[p_voice].pitch_envelope_ctrl; break; } - + if (!env) return -1; - + if (!env->active || env->terminated) return -1; - + return env->pos_index; } +CPEnvelope *CPPlayer::get_voice_envelope(int p_voice, CPInstrument::EnvelopeType p_env_type) { + + CPInstrument *ins = voice[p_voice].instrument_ptr; -CPEnvelope* CPPlayer::get_voice_envelope(int p_voice,CPInstrument::EnvelopeType p_env_type) { - - CPInstrument *ins=voice[p_voice].instrument_ptr; - if (!ins) return 0; - - switch( p_env_type ) { - - - case CPInstrument::VOLUME_ENVELOPE: return ins->get_volume_envelope(); - case CPInstrument::PAN_ENVELOPE: return ins->get_pan_envelope(); + + switch (p_env_type) { + + case CPInstrument::VOLUME_ENVELOPE: return ins->get_volume_envelope(); + case CPInstrument::PAN_ENVELOPE: return ins->get_pan_envelope(); case CPInstrument::PITCH_ENVELOPE: return ins->get_pitch_filter_envelope(); }; - + return 0; - } -const char * CPPlayer::get_voice_instrument_name(int p_voice) { - - +const char *CPPlayer::get_voice_instrument_name(int p_voice) { const char *name = NULL; - - - if (voice[p_voice].instrument_ptr!=NULL) name=voice[p_voice].instrument_ptr->get_name(); - - + if (voice[p_voice].instrument_ptr != NULL) name = voice[p_voice].instrument_ptr->get_name(); return name; - } -void CPPlayer::set_filters_enabled(bool p_enable){ +void CPPlayer::set_filters_enabled(bool p_enable) { - control.filters=p_enable; + control.filters = p_enable; } int CPPlayer::get_voice_sample_index(int p_voice) { diff --git a/modules/chibi/cp_player_data_effects.cpp b/modules/chibi/cp_player_data_effects.cpp index 6c774afb1..29ddacce3 100644 --- a/modules/chibi/cp_player_data_effects.cpp +++ b/modules/chibi/cp_player_data_effects.cpp @@ -29,8 +29,6 @@ #include "cp_player_data.h" - - /********************** complex effects ***********************/ @@ -49,737 +47,722 @@ static inline int32_t cp_random_generate(int32_t *seed) { return (int32_t)(s & RANDOM_MAX); } +void CPPlayer::do_vibrato(int p_track, bool fine) { + uint8_t q; + uint16_t temp = 0; -void CPPlayer::do_vibrato(int p_track,bool fine) { - - uint8_t q; - uint16_t temp=0; + if ((control.ticks_counter == 0) && control.channel[p_track].row_has_note) control.channel[p_track].vibrato_position = 0; - if ((control.ticks_counter==0) && control.channel[p_track].row_has_note) control.channel[p_track].vibrato_position=0; + q = (control.channel[p_track].vibrato_position >> 2) & 0x1f; - q=(control.channel[p_track].vibrato_position>>2)&0x1f; - - switch (control.channel[p_track].vibrato_type) { - case 0: /* sine */ - temp=vibrato_table[q]; - break; - case 1: /* square wave */ - temp=255; - break; - case 2: /* ramp down */ - q<<=3; - if (control.channel[p_track].vibrato_position<0) q=255-q; - temp=q; - break; - case 3: /* random */ - temp=cp_random_generate(&control.random_seed) %256;//getrandom(256); - break; - } + switch (control.channel[p_track].vibrato_type) { + case 0: /* sine */ + temp = vibrato_table[q]; + break; + case 1: /* square wave */ + temp = 255; + break; + case 2: /* ramp down */ + q <<= 3; + if (control.channel[p_track].vibrato_position < 0) q = 255 - q; + temp = q; + break; + case 3: /* random */ + temp = cp_random_generate(&control.random_seed) % 256; //getrandom(256); + break; + } - temp*=control.channel[p_track].vibrato_depth; + temp *= control.channel[p_track].vibrato_depth; if (song->has_old_effects()) { - temp>>=7; + temp >>= 7; } else { - temp>>=8; + temp >>= 8; } - if (!fine) temp<<=2; + if (!fine) temp <<= 2; - if (control.channel[p_track].vibrato_position>=0) { + if (control.channel[p_track].vibrato_position >= 0) { - control.channel[p_track].period=control.channel[p_track].aux_period+temp; - } else { - - control.channel[p_track].period=control.channel[p_track].aux_period-temp; + control.channel[p_track].period = control.channel[p_track].aux_period + temp; + } else { + + control.channel[p_track].period = control.channel[p_track].aux_period - temp; } - if (!song->has_old_effects() || control.ticks_counter) control.channel[p_track].vibrato_position+=control.channel[p_track].vibrato_speed; + if (!song->has_old_effects() || control.ticks_counter) control.channel[p_track].vibrato_position += control.channel[p_track].vibrato_speed; } +void CPPlayer::do_pitch_slide_down(int p_track, uint8_t inf) { -void CPPlayer::do_pitch_slide_down(int p_track,uint8_t inf) { + uint8_t hi, lo; - uint8_t hi,lo; + if (inf) + control.channel[p_track].pitch_slide_info = inf; + else + inf = control.channel[p_track].pitch_slide_info; - if (inf) control.channel[p_track].pitch_slide_info=inf; - else inf=control.channel[p_track].pitch_slide_info; + hi = inf >> 4; + lo = inf & 0xf; - hi=inf>>4; - lo=inf&0xf; - - if (hi==0xf) { + if (hi == 0xf) { - if (!control.ticks_counter) control.channel[p_track].aux_period+=(uint16_t)lo<<2; - } else if (hi==0xe) { + if (!control.ticks_counter) control.channel[p_track].aux_period += (uint16_t)lo << 2; + } else if (hi == 0xe) { - if (!control.ticks_counter) control.channel[p_track].aux_period+=lo; - } else { + if (!control.ticks_counter) control.channel[p_track].aux_period += lo; + } else { - if (control.ticks_counter) control.channel[p_track].aux_period+=(uint16_t)inf<<2; - } + if (control.ticks_counter) control.channel[p_track].aux_period += (uint16_t)inf << 2; + } } -void CPPlayer::do_pitch_slide_up(int p_track,uint8_t inf) { +void CPPlayer::do_pitch_slide_up(int p_track, uint8_t inf) { - uint8_t hi,lo; + uint8_t hi, lo; - if (inf) control.channel[p_track].pitch_slide_info=inf; - else inf=control.channel[p_track].pitch_slide_info; + if (inf) + control.channel[p_track].pitch_slide_info = inf; + else + inf = control.channel[p_track].pitch_slide_info; - hi=inf>>4; - lo=inf&0xf; - - if (hi==0xf) { + hi = inf >> 4; + lo = inf & 0xf; - if (!control.ticks_counter) control.channel[p_track].aux_period-=(uint16_t)lo<<2; - } else if (hi==0xe) { + if (hi == 0xf) { - if (!control.ticks_counter) control.channel[p_track].aux_period-=lo; - } else { + if (!control.ticks_counter) control.channel[p_track].aux_period -= (uint16_t)lo << 2; + } else if (hi == 0xe) { - if (control.ticks_counter) control.channel[p_track].aux_period-=(uint16_t)inf<<2; - } + if (!control.ticks_counter) control.channel[p_track].aux_period -= lo; + } else { + + if (control.ticks_counter) control.channel[p_track].aux_period -= (uint16_t)inf << 2; + } } void CPPlayer::do_pitch_slide_to_note(int p_track) { - if (control.ticks_counter) { - int dist; + if (control.ticks_counter) { + int dist; - /* We have to slide a->period towards a->wantedperiod, compute the + /* We have to slide a->period towards a->wantedperiod, compute the difference between those two values */ - dist=control.channel[p_track].period-control.channel[p_track].slide_to_period; + dist = control.channel[p_track].period - control.channel[p_track].slide_to_period; - /* if they are equal or if portamentospeed is too big... */ - if ((!dist)||((control.channel[p_track].portamento_speed<<2)>cp_intabs(dist))) { - /* ... make tmpperiod equal tperiod */ - control.channel[p_track].aux_period=control.channel[p_track].period=control.channel[p_track].slide_to_period; - } else { + /* if they are equal or if portamentospeed is too big... */ + if ((!dist) || ((control.channel[p_track].portamento_speed << 2) > cp_intabs(dist))) { + /* ... make tmpperiod equal tperiod */ + control.channel[p_track].aux_period = control.channel[p_track].period = control.channel[p_track].slide_to_period; + } else { - if (dist>0) { + if (dist > 0) { - control.channel[p_track].aux_period-=control.channel[p_track].portamento_speed<<2; - control.channel[p_track].period-=control.channel[p_track].portamento_speed<<2; /* dist>0 slide up */ - } else { - control.channel[p_track].aux_period+=control.channel[p_track].portamento_speed<<2; - control.channel[p_track].period+=control.channel[p_track].portamento_speed<<2; /* dist<0 slide down */ + control.channel[p_track].aux_period -= control.channel[p_track].portamento_speed << 2; + control.channel[p_track].period -= control.channel[p_track].portamento_speed << 2; /* dist>0 slide up */ + } else { + control.channel[p_track].aux_period += control.channel[p_track].portamento_speed << 2; + control.channel[p_track].period += control.channel[p_track].portamento_speed << 2; /* dist<0 slide down */ } } - } else { + } else { - control.channel[p_track].aux_period=control.channel[p_track].period; + control.channel[p_track].aux_period = control.channel[p_track].period; } } void CPPlayer::do_tremor(int p_track) { - uint8_t on,off,inf; + uint8_t on, off, inf; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) { - control.channel[p_track].tremor_info=inf; - } else { - inf= control.channel[p_track].tremor_info; - if (!inf) return; - } + if (inf) { + control.channel[p_track].tremor_info = inf; + } else { + inf = control.channel[p_track].tremor_info; + if (!inf) return; + } - //if (!control.ticks_counter) return; + //if (!control.ticks_counter) return; - on=(inf>>4); - off=(inf&0xf); + on = (inf >> 4); + off = (inf & 0xf); - control.channel[p_track].tremor_position%=(on+off); - control.channel[p_track].volume=(control.channel[p_track].tremor_position<on)?control.channel[p_track].aux_volume:0; - control.channel[p_track].tremor_position++; + control.channel[p_track].tremor_position %= (on + off); + control.channel[p_track].volume = (control.channel[p_track].tremor_position < on) ? control.channel[p_track].aux_volume : 0; + control.channel[p_track].tremor_position++; } void CPPlayer::do_pan_slide(int p_track) { - uint8_t lo,hi,inf; - int16_t pan; + uint8_t lo, hi, inf; + int16_t pan; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) control.channel[p_track].channel_pan_slide_info=inf; - else inf=control.channel[p_track].channel_pan_slide_info; + if (inf) + control.channel[p_track].channel_pan_slide_info = inf; + else + inf = control.channel[p_track].channel_pan_slide_info; - lo=inf&0xf; - hi=inf>>4; + lo = inf & 0xf; + hi = inf >> 4; - pan=(control.channel[p_track].panning==PAN_SURROUND)?PAN_CENTER:control.channel[p_track].panning; + pan = (control.channel[p_track].panning == PAN_SURROUND) ? PAN_CENTER : control.channel[p_track].panning; - if (!hi) - pan+=lo<<2; - else - if (!lo) { - pan-=hi<<2; - } else - if (hi==0xf) { - if (!control.ticks_counter) pan+=lo<<2; - } else - if (lo==0xf) { - if (!control.ticks_counter) pan-=hi<<2; - } + if (!hi) + pan += lo << 2; + else if (!lo) { + pan -= hi << 2; + } else if (hi == 0xf) { + if (!control.ticks_counter) pan += lo << 2; + } else if (lo == 0xf) { + if (!control.ticks_counter) pan -= hi << 2; + } //this sets both chan & voice paning - control.channel[p_track].panning=(pan<PAN_LEFT)?PAN_LEFT:(pan>PAN_RIGHT?PAN_RIGHT:pan); - control.channel[p_track].channel_panning=control.channel[p_track].panning; + control.channel[p_track].panning = (pan < PAN_LEFT) ? PAN_LEFT : (pan > PAN_RIGHT ? PAN_RIGHT : pan); + control.channel[p_track].channel_panning = control.channel[p_track].panning; } -void CPPlayer::do_volume_slide(int p_track,int inf) { +void CPPlayer::do_volume_slide(int p_track, int inf) { - uint8_t hi,lo; + uint8_t hi, lo; + + lo = inf & 0xf; + hi = inf >> 4; - lo=inf&0xf; - hi=inf>>4; - if (!lo) { - if ((control.ticks_counter)) control.channel[p_track].aux_volume+=hi; + if ((control.ticks_counter)) control.channel[p_track].aux_volume += hi; } else if (!hi) { - if ((control.ticks_counter)) control.channel[p_track].aux_volume-=lo; + if ((control.ticks_counter)) control.channel[p_track].aux_volume -= lo; - } else if (lo==0xf) { + } else if (lo == 0xf) { - if (!control.ticks_counter) control.channel[p_track].aux_volume+=(hi?hi:0xf); - } else if (hi==0xf) { + if (!control.ticks_counter) control.channel[p_track].aux_volume += (hi ? hi : 0xf); + } else if (hi == 0xf) { - if (!control.ticks_counter) control.channel[p_track].aux_volume-=(lo?lo:0xf); - } else return; + if (!control.ticks_counter) control.channel[p_track].aux_volume -= (lo ? lo : 0xf); + } else + return; - if (control.channel[p_track].aux_volume<0) { + if (control.channel[p_track].aux_volume < 0) { - control.channel[p_track].aux_volume=0; - } else if (control.channel[p_track].aux_volume>64) { + control.channel[p_track].aux_volume = 0; + } else if (control.channel[p_track].aux_volume > 64) { - control.channel[p_track].aux_volume=64; + control.channel[p_track].aux_volume = 64; } } void CPPlayer::do_channel_volume_slide(int p_track) { - uint8_t lo, hi,inf; + uint8_t lo, hi, inf; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) control.channel[p_track].channel_volume_slide_info=inf; - inf=control.channel[p_track].channel_volume_slide_info; + if (inf) control.channel[p_track].channel_volume_slide_info = inf; + inf = control.channel[p_track].channel_volume_slide_info; - lo=inf&0xf; - hi=inf>>4; + lo = inf & 0xf; + hi = inf >> 4; - if (!hi) - control.channel[p_track].channel_volume-=lo; - else - if (!lo) { - control.channel[p_track].channel_volume+=hi; - } else - if (hi==0xf) { - if (!control.ticks_counter) control.channel[p_track].channel_volume-=lo; - } else - if (lo==0xf) { - if (!control.ticks_counter) control.channel[p_track].channel_volume+=hi; - } + if (!hi) + control.channel[p_track].channel_volume -= lo; + else if (!lo) { + control.channel[p_track].channel_volume += hi; + } else if (hi == 0xf) { + if (!control.ticks_counter) control.channel[p_track].channel_volume -= lo; + } else if (lo == 0xf) { + if (!control.ticks_counter) control.channel[p_track].channel_volume += hi; + } - if (control.channel[p_track].channel_volume<0) control.channel[p_track].channel_volume=0; - if (control.channel[p_track].channel_volume>64) control.channel[p_track].channel_volume=64; + if (control.channel[p_track].channel_volume < 0) control.channel[p_track].channel_volume = 0; + if (control.channel[p_track].channel_volume > 64) control.channel[p_track].channel_volume = 64; } void CPPlayer::do_tremolo(int p_track) { - uint8_t q; - int16_t temp=0; + uint8_t q; + int16_t temp = 0; - if ((control.ticks_counter==0) && control.channel[p_track].row_has_note) control.channel[p_track].tremolo_position=0; + if ((control.ticks_counter == 0) && control.channel[p_track].row_has_note) control.channel[p_track].tremolo_position = 0; - q=(control.channel[p_track].tremolo_position>>2)&0x1f; + q = (control.channel[p_track].tremolo_position >> 2) & 0x1f; - switch (control.channel[p_track].tremolo_type) { - case 0: /* sine */ - temp=vibrato_table[q]; - break; - case 1: /* ramp down */ - q<<=3; - if (control.channel[p_track].tremolo_position<0) q=255-q; - temp=q; - break; - case 2: /* square wave */ - temp=255; - break; - case 3: /* random */ - temp=cp_random_generate(&control.random_seed) % 256;//getrandom(256); - break; - } - - temp*=control.channel[p_track].tremolo_depth; - temp>>=7; - - - - if (control.channel[p_track].tremolo_position>=0) { + switch (control.channel[p_track].tremolo_type) { + case 0: /* sine */ + temp = vibrato_table[q]; + break; + case 1: /* ramp down */ + q <<= 3; + if (control.channel[p_track].tremolo_position < 0) q = 255 - q; + temp = q; + break; + case 2: /* square wave */ + temp = 255; + break; + case 3: /* random */ + temp = cp_random_generate(&control.random_seed) % 256; //getrandom(256); + break; + } + temp *= control.channel[p_track].tremolo_depth; + temp >>= 7; - control.channel[p_track].volume=control.channel[p_track].aux_volume+temp; - if (control.channel[p_track].volume>64) control.channel[p_track].volume=64; - } else { + if (control.channel[p_track].tremolo_position >= 0) { - control.channel[p_track].volume=control.channel[p_track].aux_volume-temp; - if (control.channel[p_track].volume<0) control.channel[p_track].volume=0; - } + control.channel[p_track].volume = control.channel[p_track].aux_volume + temp; + if (control.channel[p_track].volume > 64) control.channel[p_track].volume = 64; + } else { - /*if (control.ticks_counter)*/ control.channel[p_track].tremolo_position+=control.channel[p_track].tremolo_speed; + control.channel[p_track].volume = control.channel[p_track].aux_volume - temp; + if (control.channel[p_track].volume < 0) control.channel[p_track].volume = 0; + } + /*if (control.ticks_counter)*/ control.channel[p_track].tremolo_position += control.channel[p_track].tremolo_speed; } void CPPlayer::do_arpegio(int p_track) { - uint8_t note,dat; + uint8_t note, dat; //note=control.channel[p_track].note; - note=0; + note = 0; if (control.channel[p_track].current_parameter) { - control.channel[p_track].arpegio_info=control.channel[p_track].current_parameter; + control.channel[p_track].arpegio_info = control.channel[p_track].current_parameter; } - dat=control.channel[p_track].arpegio_info; - + dat = control.channel[p_track].arpegio_info; + if (dat) { - switch (control.ticks_counter%3) { - + switch (control.ticks_counter % 3) { + case 1: { - note+=(dat>>4); + note += (dat >> 4); } break; case 2: { - - note+=(dat&0xf); + + note += (dat & 0xf); } break; } if (song->has_linear_slides()) { - control.channel[p_track].period=control.channel[p_track].aux_period-cp_intabs(get_period((uint16_t)46,0)-get_period((uint16_t)44,0))*note; + control.channel[p_track].period = control.channel[p_track].aux_period - cp_intabs(get_period((uint16_t)46, 0) - get_period((uint16_t)44, 0)) * note; } else if (control.channel[p_track].sample_ptr) { - - control.channel[p_track].period=get_period( (((uint16_t)control.channel[p_track].note)+note)<<1,CPSampleManager::get_singleton()->get_c5_freq( (control.channel[p_track].sample_ptr->get_sample_data()))); - } - - control.channel[p_track].has_own_period=true; - } + control.channel[p_track].period = get_period((((uint16_t)control.channel[p_track].note) + note) << 1, CPSampleManager::get_singleton()->get_c5_freq((control.channel[p_track].sample_ptr->get_sample_data()))); + } + control.channel[p_track].has_own_period = true; + } } - void CPPlayer::do_retrig(int p_track) { uint8_t inf; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) { + if (inf) { - control.channel[p_track].retrig_volslide=inf>>4; - control.channel[p_track].retrig_speed=inf&0xf; - } + control.channel[p_track].retrig_volslide = inf >> 4; + control.channel[p_track].retrig_speed = inf & 0xf; + } - /* only retrigger if low nibble > 0 */ - if ( control.channel[p_track].retrig_speed>0) { + /* only retrigger if low nibble > 0 */ + if (control.channel[p_track].retrig_speed > 0) { - if ( !control.channel[p_track].retrig_counter ) { - /* when retrig counter reaches 0, reset counter and restart the + if (!control.channel[p_track].retrig_counter) { + /* when retrig counter reaches 0, reset counter and restart the sample */ - if (control.channel[p_track].kick!=KICK_NOTE) control.channel[p_track].kick=KICK_NOTEOFF; - control.channel[p_track].retrig_counter=control.channel[p_track].retrig_speed; - + if (control.channel[p_track].kick != KICK_NOTE) control.channel[p_track].kick = KICK_NOTEOFF; + control.channel[p_track].retrig_counter = control.channel[p_track].retrig_speed; - if ((control.ticks_counter)/*||(pf->flags&UF_S3MSLIDES)*/) { - switch (control.channel[p_track].retrig_volslide) { - case 1: - case 2: - case 3: - case 4: - case 5: - control.channel[p_track].aux_volume-=(1<<(control.channel[p_track].retrig_volslide-1)); - break; - case 6: - control.channel[p_track].aux_volume=(2*control.channel[p_track].aux_volume)/3; - break; - case 7: - control.channel[p_track].aux_volume>>=1; - break; - case 9: - case 0xa: - case 0xb: - case 0xc: - case 0xd: - control.channel[p_track].aux_volume+=(1<<(control.channel[p_track].retrig_volslide-9)); - break; - case 0xe: - control.channel[p_track].aux_volume=(3*control.channel[p_track].aux_volume)>>1; - break; - case 0xf: - control.channel[p_track].aux_volume=control.channel[p_track].aux_volume<<1; - break; - } - if (control.channel[p_track].aux_volume<0) control.channel[p_track].aux_volume=0; - else if (control.channel[p_track].aux_volume>64) control.channel[p_track].aux_volume=64; - } - } - control.channel[p_track].retrig_counter--; /* countdown */ - } + if ((control.ticks_counter) /*||(pf->flags&UF_S3MSLIDES)*/) { + switch (control.channel[p_track].retrig_volslide) { + case 1: + case 2: + case 3: + case 4: + case 5: + control.channel[p_track].aux_volume -= (1 << (control.channel[p_track].retrig_volslide - 1)); + break; + case 6: + control.channel[p_track].aux_volume = (2 * control.channel[p_track].aux_volume) / 3; + break; + case 7: + control.channel[p_track].aux_volume >>= 1; + break; + case 9: + case 0xa: + case 0xb: + case 0xc: + case 0xd: + control.channel[p_track].aux_volume += (1 << (control.channel[p_track].retrig_volslide - 9)); + break; + case 0xe: + control.channel[p_track].aux_volume = (3 * control.channel[p_track].aux_volume) >> 1; + break; + case 0xf: + control.channel[p_track].aux_volume = control.channel[p_track].aux_volume << 1; + break; + } + if (control.channel[p_track].aux_volume < 0) + control.channel[p_track].aux_volume = 0; + else if (control.channel[p_track].aux_volume > 64) + control.channel[p_track].aux_volume = 64; + } + } + control.channel[p_track].retrig_counter--; /* countdown */ + } } void CPPlayer::do_global_volume_slide(int p_track) { - uint8_t lo,hi,inf; + uint8_t lo, hi, inf; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) control.channel[p_track].global_volume_slide_info=inf; - inf=control.channel[p_track].global_volume_slide_info; + if (inf) control.channel[p_track].global_volume_slide_info = inf; + inf = control.channel[p_track].global_volume_slide_info; - lo=inf&0xf; - hi=inf>>4; + lo = inf & 0xf; + hi = inf >> 4; - if (!lo) { - if (control.ticks_counter) control.global_volume+=hi; - } else - if (!hi) { - if (control.ticks_counter) control.global_volume-=lo; - } else - if (lo==0xf) { - if (!control.ticks_counter) control.global_volume+=hi; - } else - if (hi==0xf) { - if (!control.ticks_counter) control.global_volume-=lo; - } + if (!lo) { + if (control.ticks_counter) control.global_volume += hi; + } else if (!hi) { + if (control.ticks_counter) control.global_volume -= lo; + } else if (lo == 0xf) { + if (!control.ticks_counter) control.global_volume += hi; + } else if (hi == 0xf) { + if (!control.ticks_counter) control.global_volume -= lo; + } - if (control.global_volume<0) control.global_volume=0; - if (control.global_volume>128) control.global_volume=128; + if (control.global_volume < 0) control.global_volume = 0; + if (control.global_volume > 128) control.global_volume = 128; } void CPPlayer::do_panbrello(int p_track) { - uint8_t q; - int32_t temp=0; + uint8_t q; + int32_t temp = 0; - q=control.channel[p_track].panbrello_position; + q = control.channel[p_track].panbrello_position; - switch (control.channel[p_track].panbrello_type) { - case 0: {/* sine */ - temp=panbrello_table[q]; - } break; - case 1: {/* square wave */ - temp=(q<0x80)?64:0; - } break; - case 2: {/* ramp down */ - q<<=3; - temp=q; - } break; - case 3: {/* random */ - if (control.channel[p_track].panbrello_position>=control.channel[p_track].panbrello_speed) { - control.channel[p_track].panbrello_position=0; - temp=cp_random_generate(&control.random_seed)%256;//getrandom(256); + switch (control.channel[p_track].panbrello_type) { + case 0: { /* sine */ + temp = panbrello_table[q]; + } break; + case 1: { /* square wave */ + temp = (q < 0x80) ? 64 : 0; + } break; + case 2: { /* ramp down */ + q <<= 3; + temp = q; + } break; + case 3: { /* random */ + if (control.channel[p_track].panbrello_position >= control.channel[p_track].panbrello_speed) { + control.channel[p_track].panbrello_position = 0; + temp = cp_random_generate(&control.random_seed) % 256; //getrandom(256); } - } break; - } - + } break; + } - - temp=temp*(int)control.channel[p_track].panbrello_depth/0xF; - temp<<=1; - if (control.channel[p_track].channel_panning!=PAN_SURROUND) - temp+=control.channel[p_track].channel_panning; + temp = temp * (int)control.channel[p_track].panbrello_depth / 0xF; + temp <<= 1; + if (control.channel[p_track].channel_panning != PAN_SURROUND) + temp += control.channel[p_track].channel_panning; - control.channel[p_track].panning=(temp<PAN_LEFT)?PAN_LEFT:(temp>PAN_RIGHT?PAN_RIGHT:temp); - control.channel[p_track].panbrello_position+=control.channel[p_track].panbrello_speed; + control.channel[p_track].panning = (temp < PAN_LEFT) ? PAN_LEFT : (temp > PAN_RIGHT ? PAN_RIGHT : temp); + control.channel[p_track].panbrello_position += control.channel[p_track].panbrello_speed; } /****************** S effect *******************/ - void CPPlayer::do_effect_S(int p_track) { - uint8_t inf,c,dat; + uint8_t inf, c, dat; - dat=control.channel[p_track].current_parameter; - - inf=dat&0xf; - c=dat>>4; + dat = control.channel[p_track].current_parameter; - if (!dat) { - c=control.channel[p_track].current_S_effect; - inf=control.channel[p_track].current_S_data; - } else { - control.channel[p_track].current_S_effect=c; - control.channel[p_track].current_S_data=inf; - } + inf = dat & 0xf; + c = dat >> 4; - switch (c) { - case 1: {/* S1x set glissando voice */ - // this is unsupported in IT! + if (!dat) { + c = control.channel[p_track].current_S_effect; + inf = control.channel[p_track].current_S_data; + } else { + control.channel[p_track].current_S_effect = c; + control.channel[p_track].current_S_data = inf; + } + + switch (c) { + case 1: { /* S1x set glissando voice */ + // this is unsupported in IT! - control.channel[p_track].chorus_send=inf*0xFF/0xF; - - }break; - case 2: /* S2x set finetune */ - //Also not supported! - break; - case 3: /* S3x set vibrato waveform */ - if (inf<4) control.channel[p_track].vibrato_type=inf; - break; - case 4: /* S4x set tremolo waveform */ - if (inf<4) control.channel[p_track].tremolo_type=inf; - break; - case 5: /* S5x panbrello */ - if (inf<4) control.channel[p_track].panbrello_type=inf; - break; - case 6: {/* S6x delay x number of frames (patdly) */ + control.channel[p_track].chorus_send = inf * 0xFF / 0xF; + + } break; + case 2: /* S2x set finetune */ + //Also not supported! + break; + case 3: /* S3x set vibrato waveform */ + if (inf < 4) control.channel[p_track].vibrato_type = inf; + break; + case 4: /* S4x set tremolo waveform */ + if (inf < 4) control.channel[p_track].tremolo_type = inf; + break; + case 5: /* S5x panbrello */ + if (inf < 4) control.channel[p_track].panbrello_type = inf; + break; + case 6: { /* S6x delay x number of frames (patdly) */ if (control.ticks_counter) break; - if (!control.pattern_delay_2) control.pattern_delay_1=inf+1; /* only once, when vbtick=0 */ + if (!control.pattern_delay_2) control.pattern_delay_1 = inf + 1; /* only once, when vbtick=0 */ + + } break; + case 7: /* S7x instrument / NNA commands */ - } break; - case 7: /* S7x instrument / NNA commands */ - if (!song->has_instruments()) break; - switch(inf) { - + switch (inf) { + case 0x3: { - - control.channel[p_track].NNA_type=CPInstrument::NNA_NOTE_CUT; + + control.channel[p_track].NNA_type = CPInstrument::NNA_NOTE_CUT; } break; - case 0x4: { - - control.channel[p_track].NNA_type=CPInstrument::NNA_NOTE_CONTINUE; + case 0x4: { + + control.channel[p_track].NNA_type = CPInstrument::NNA_NOTE_CONTINUE; } break; - case 0x5: { - - control.channel[p_track].NNA_type=CPInstrument::NNA_NOTE_OFF; + case 0x5: { + + control.channel[p_track].NNA_type = CPInstrument::NNA_NOTE_OFF; } break; - case 0x6: { - - control.channel[p_track].NNA_type=CPInstrument::NNA_NOTE_FADE; + case 0x6: { + + control.channel[p_track].NNA_type = CPInstrument::NNA_NOTE_FADE; } break; - case 0x7: { - + case 0x7: { + if (control.channel[p_track].slave_voice) - control.channel[p_track].slave_voice->volume_envelope_ctrl.active=false; + control.channel[p_track].slave_voice->volume_envelope_ctrl.active = false; } break; - case 0x8: { - + case 0x8: { + if (control.channel[p_track].slave_voice) - control.channel[p_track].slave_voice->volume_envelope_ctrl.active=true; - + control.channel[p_track].slave_voice->volume_envelope_ctrl.active = true; + } break; - case 0x9: { - + case 0x9: { + if (control.channel[p_track].slave_voice) - control.channel[p_track].slave_voice->panning_envelope_ctrl.active=false; - + control.channel[p_track].slave_voice->panning_envelope_ctrl.active = false; + } break; case 0xA: { - + if (control.channel[p_track].slave_voice) - control.channel[p_track].slave_voice->panning_envelope_ctrl.active=true; - + control.channel[p_track].slave_voice->panning_envelope_ctrl.active = true; + } break; case 0xB: { if (control.channel[p_track].slave_voice) - control.channel[p_track].slave_voice->pitch_envelope_ctrl.active=false; - + control.channel[p_track].slave_voice->pitch_envelope_ctrl.active = false; + } break; case 0xC: { - + if (control.channel[p_track].slave_voice) - control.channel[p_track].slave_voice->pitch_envelope_ctrl.active=true; - + control.channel[p_track].slave_voice->pitch_envelope_ctrl.active = true; + } break; - - } break; - - break; - case 8: {/* S8x set panning position */ + } + break; -// if (pf->panflag) { - if (inf<=8) inf<<=4; - else inf*=17; - control.channel[p_track].panning=control.channel[p_track].channel_panning=inf; -// } - } break; + break; + case 8: { /* S8x set panning position */ - case 9: { /* S9x set surround sound */ - //if (pf->panflag) - control.channel[p_track].panning=control.channel[p_track].channel_panning=PAN_SURROUND; - } break; - case 0xA:{ /* SAy set high order sample offset yxx00h */ + // if (pf->panflag) { + if (inf <= 8) + inf <<= 4; + else + inf *= 17; + control.channel[p_track].panning = control.channel[p_track].channel_panning = inf; + // } + } break; + + case 9: { /* S9x set surround sound */ + //if (pf->panflag) + control.channel[p_track].panning = control.channel[p_track].channel_panning = PAN_SURROUND; + } break; + case 0xA: { /* SAy set high order sample offset yxx00h */ - if (control.channel[p_track].current_parameter) control.channel[p_track].hi_offset=(int32_t)inf<<16; - control.channel[p_track].sample_start_index=control.channel[p_track].hi_offset|control.channel[p_track].lo_offset; - } break; - case 0xB: { /* SBx pattern loop */ - if (control.ticks_counter) break; + if (control.channel[p_track].current_parameter) control.channel[p_track].hi_offset = (int32_t)inf << 16; + control.channel[p_track].sample_start_index = control.channel[p_track].hi_offset | control.channel[p_track].lo_offset; + } break; + case 0xB: { /* SBx pattern loop */ + if (control.ticks_counter) break; - if (inf) { /* set reppos or repcnt ? */ - /* set repcnt, so check if repcnt already is set, which means we + if (inf) { /* set reppos or repcnt ? */ + /* set repcnt, so check if repcnt already is set, which means we are already looping */ - if (control.channel[p_track].pattern_loop_count>0) - control.channel[p_track].pattern_loop_count--; /* already looping, decrease counter */ - else { - control.channel[p_track].pattern_loop_count=inf; /* not yet looping, so set repcnt */ - } + if (control.channel[p_track].pattern_loop_count > 0) + control.channel[p_track].pattern_loop_count--; /* already looping, decrease counter */ + else { + control.channel[p_track].pattern_loop_count = inf; /* not yet looping, so set repcnt */ + } - if (control.channel[p_track].pattern_loop_count>0) { /* jump to reppos if repcnt>0 */ + if (control.channel[p_track].pattern_loop_count > 0) { /* jump to reppos if repcnt>0 */ - control.position=control.previous_position; // This will also anulate any Cxx or break.. + control.position = control.previous_position; // This will also anulate any Cxx or break.. - control.position.current_row=control.channel[p_track].pattern_loop_position; - control.position.forbid_jump=true; + control.position.current_row = control.channel[p_track].pattern_loop_position; + control.position.forbid_jump = true; } - } else { - + } else { - control.channel[p_track].pattern_loop_position=control.position.current_row-1; + control.channel[p_track].pattern_loop_position = control.position.current_row - 1; } - } break; - case 0xC: { /* SCx notecut */ + } break; + case 0xC: { /* SCx notecut */ - if (control.ticks_counter>=inf) { + if (control.ticks_counter >= inf) { - control.channel[p_track].aux_volume=0; - control.channel[p_track].note_end_flags|=END_NOTE_OFF; - control.channel[p_track].note_end_flags|=END_NOTE_KILL; + control.channel[p_track].aux_volume = 0; + control.channel[p_track].note_end_flags |= END_NOTE_OFF; + control.channel[p_track].note_end_flags |= END_NOTE_KILL; } - } break; - case 0xD: {/* SDx notedelay */ + } break; + case 0xD: { /* SDx notedelay */ if (!control.ticks_counter) { - control.channel[p_track].note_delay=inf; + control.channel[p_track].note_delay = inf; - } else if (control.channel[p_track].note_delay) { + } else if (control.channel[p_track].note_delay) { - control.channel[p_track].note_delay--; - } - - } break; - case 0xF: {/* SEx patterndelay */ + control.channel[p_track].note_delay--; + } + + } break; + case 0xF: { /* SEx patterndelay */ if (control.ticks_counter) break; - if (!control.pattern_delay_2) control.pattern_delay_1=inf+1; /* only once, when vbtick=0 */ + if (!control.pattern_delay_2) control.pattern_delay_1 = inf + 1; /* only once, when vbtick=0 */ - } break; - } + } break; + } } - - - - - - - /********************* volume effects **********************/ void CPPlayer::run_volume_column_effects(int p_track) { - uint8_t param=control.channel[p_track].current_volume_parameter; + uint8_t param = control.channel[p_track].current_volume_parameter; - - switch ('A'+control.channel[p_track].current_volume_command) { + switch ('A' + control.channel[p_track].current_volume_command) { case 'A': { - if (param>0) control.channel[p_track].volcol_volume_slide=param; - else param=control.channel[p_track].volcol_volume_slide; - - do_volume_slide(p_track,param*0x10+0xF); + if (param > 0) + control.channel[p_track].volcol_volume_slide = param; + else + param = control.channel[p_track].volcol_volume_slide; + + do_volume_slide(p_track, param * 0x10 + 0xF); } break; case 'B': { - if (param>0) control.channel[p_track].volcol_volume_slide=param; - else param=control.channel[p_track].volcol_volume_slide; + if (param > 0) + control.channel[p_track].volcol_volume_slide = param; + else + param = control.channel[p_track].volcol_volume_slide; - do_volume_slide(p_track,0xF0+param); + do_volume_slide(p_track, 0xF0 + param); } break; case 'C': { - if (param>0) control.channel[p_track].volcol_volume_slide=param; - else param=control.channel[p_track].volcol_volume_slide; + if (param > 0) + control.channel[p_track].volcol_volume_slide = param; + else + param = control.channel[p_track].volcol_volume_slide; - do_volume_slide(p_track,param*0x10); + do_volume_slide(p_track, param * 0x10); } break; case 'D': { - if (param>0) control.channel[p_track].volcol_volume_slide=param; - else param=control.channel[p_track].volcol_volume_slide; - do_volume_slide(p_track,param); + if (param > 0) + control.channel[p_track].volcol_volume_slide = param; + else + param = control.channel[p_track].volcol_volume_slide; + do_volume_slide(p_track, param); } break; case 'E': { - do_pitch_slide_down(p_track,param<<2); + do_pitch_slide_down(p_track, param << 2); } break; case 'F': { - do_pitch_slide_up(p_track,param<<2); + do_pitch_slide_up(p_track, param << 2); } break; case 'G': { - - const uint8_t slide_table[]={0,1,4,8,16,32,64,96,128,255}; + + const uint8_t slide_table[] = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }; if (param) { - control.channel[p_track].portamento_speed=slide_table[param]; + control.channel[p_track].portamento_speed = slide_table[param]; } - if (control.channel[p_track].period && (control.channel[p_track].old_note<=120)) { + if (control.channel[p_track].period && (control.channel[p_track].old_note <= 120)) { + + if ((!control.ticks_counter) && (control.channel[p_track].new_instrument)) { - if ( (!control.ticks_counter) && (control.channel[p_track].new_instrument) ){ - //control.channel[p_track].kick=KICK_NOTE; //control.channel[p_track].sample_start_index=0; // < am i stupid? } else { - control.channel[p_track].kick=(control.channel[p_track].kick==KICK_NOTE)?KICK_ENVELOPE:KICK_NOTHING; + control.channel[p_track].kick = (control.channel[p_track].kick == KICK_NOTE) ? KICK_ENVELOPE : KICK_NOTHING; do_pitch_slide_to_note(p_track); - control.channel[p_track].has_own_period=true; + control.channel[p_track].has_own_period = true; } - } } break; case 'H': { - if (!control.ticks_counter) { - if (param&0x0f) control.channel[p_track].vibrato_depth=param; + if (param & 0x0f) control.channel[p_track].vibrato_depth = param; } - control.channel[p_track].doing_vibrato=true; - if (control.external_vibrato) break; + control.channel[p_track].doing_vibrato = true; + if (control.external_vibrato) break; if (control.channel[p_track].period) { - do_vibrato(p_track,false); - control.channel[p_track].has_own_period=true; - } + do_vibrato(p_track, false); + control.channel[p_track].has_own_period = true; + } } break; } @@ -788,164 +771,164 @@ void CPPlayer::run_volume_column_effects(int p_track) { table **********************/ - void CPPlayer::run_effects(int p_track) { - switch ('A'+control.channel[p_track].current_command) { + switch ('A' + control.channel[p_track].current_command) { case 'A': { - if ((control.ticks_counter>0) || (control.pattern_delay_2>0)) break; + if ((control.ticks_counter > 0) || (control.pattern_delay_2 > 0)) break; - int new_speed; + int new_speed; - new_speed=control.channel[p_track].current_parameter % 128; + new_speed = control.channel[p_track].current_parameter % 128; - if (new_speed>0) { - control.speed=new_speed; - control.ticks_counter=0; - } + if (new_speed > 0) { + control.speed = new_speed; + control.ticks_counter = 0; + } } break; case 'B': { - int next_order; + int next_order; - if (control.ticks_counter || control.position.forbid_jump) break; + if (control.ticks_counter || control.position.forbid_jump) break; - control.position.current_row=0; + control.position.current_row = 0; - if (control.play_mode==PLAY_PATTERN) break; + if (control.play_mode == PLAY_PATTERN) break; - next_order=get_song_next_order_idx(song, (int)control.channel[p_track].current_parameter-1); + next_order = get_song_next_order_idx(song, (int)control.channel[p_track].current_parameter - 1); - if (next_order!=-1) { - // Do we have a "next order?" - control.position.current_pattern=song->get_order(next_order); - control.position.force_next_order=next_order; - - } else { - // no, probably the user deleted the orderlist. - control.play_mode=PLAY_NOTHING; - reset(); - } + if (next_order != -1) { + // Do we have a "next order?" + control.position.current_pattern = song->get_order(next_order); + control.position.force_next_order = next_order; + + } else { + // no, probably the user deleted the orderlist. + control.play_mode = PLAY_NOTHING; + reset(); + } } break; case 'C': { int next_order; - if (control.ticks_counter || control.position.forbid_jump) break; + if (control.ticks_counter || control.position.forbid_jump) break; - control.position.current_row=control.channel[p_track].current_parameter; + control.position.current_row = control.channel[p_track].current_parameter; - if (control.play_mode==PLAY_PATTERN) { + if (control.play_mode == PLAY_PATTERN) { - if (control.position.current_row>=song->get_pattern(control.position.current_pattern)->get_length()) { + if (control.position.current_row >= song->get_pattern(control.position.current_pattern)->get_length()) { - control.position.current_row=0; + control.position.current_row = 0; } break; } - next_order=get_song_next_order_idx(song, (int)control.position.current_order); + next_order = get_song_next_order_idx(song, (int)control.position.current_order); - if (next_order!=-1) { - // Do we have a "next order?" - control.position.current_pattern=song->get_order(next_order); + if (next_order != -1) { + // Do we have a "next order?" + control.position.current_pattern = song->get_order(next_order); - if (control.position.current_row>=song->get_pattern(song->get_order(next_order))->get_length()) { + if (control.position.current_row >= song->get_pattern(song->get_order(next_order))->get_length()) { - control.position.current_row=0; + control.position.current_row = 0; } - control.position.force_next_order=next_order; - - } else { - // no, probably the user deleted the orderlist. - control.play_mode=PLAY_NOTHING; - reset(); - } + control.position.force_next_order = next_order; + + } else { + // no, probably the user deleted the orderlist. + control.play_mode = PLAY_NOTHING; + reset(); + } } break; case 'D': { - - uint8_t inf ; + + uint8_t inf; //explicitslides=1; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) control.channel[p_track].volume_slide_info=inf; - else inf=control.channel[p_track].volume_slide_info; - - do_volume_slide(p_track,inf); + if (inf) + control.channel[p_track].volume_slide_info = inf; + else + inf = control.channel[p_track].volume_slide_info; + + do_volume_slide(p_track, inf); } break; case 'E': { - - uint8_t inf; - - inf=control.channel[p_track].current_parameter; - do_pitch_slide_down(p_track,inf); + + uint8_t inf; + + inf = control.channel[p_track].current_parameter; + do_pitch_slide_down(p_track, inf); } break; case 'F': { - - uint8_t inf; - - inf=control.channel[p_track].current_parameter; - do_pitch_slide_up(p_track,inf); + + uint8_t inf; + + inf = control.channel[p_track].current_parameter; + do_pitch_slide_up(p_track, inf); } break; case 'G': { if (control.channel[p_track].current_parameter) { - control.channel[p_track].portamento_speed=control.channel[p_track].current_parameter; + control.channel[p_track].portamento_speed = control.channel[p_track].current_parameter; } - if (control.channel[p_track].period && (control.channel[p_track].old_note<=120)) { + if (control.channel[p_track].period && (control.channel[p_track].old_note <= 120)) { - if ( (!control.ticks_counter) && (control.channel[p_track].new_instrument) ){ - + if ((!control.ticks_counter) && (control.channel[p_track].new_instrument)) { - control.channel[p_track].kick=KICK_NOTE; - control.channel[p_track].sample_start_index=0; + control.channel[p_track].kick = KICK_NOTE; + control.channel[p_track].sample_start_index = 0; } else { - control.channel[p_track].kick=(control.channel[p_track].kick==KICK_NOTE)?KICK_ENVELOPE:KICK_NOTHING; + control.channel[p_track].kick = (control.channel[p_track].kick == KICK_NOTE) ? KICK_ENVELOPE : KICK_NOTHING; } do_pitch_slide_to_note(p_track); - control.channel[p_track].has_own_period=true; + control.channel[p_track].has_own_period = true; } } break; - case 'H': { + case 'H': { uint8_t dat; - - control.channel[p_track].doing_vibrato=true; - dat=control.channel[p_track].current_parameter; + control.channel[p_track].doing_vibrato = true; + + dat = control.channel[p_track].current_parameter; if (!control.ticks_counter) { - if (dat&0x0f) control.channel[p_track].vibrato_depth=dat&0xf; - if (dat&0xf0) control.channel[p_track].vibrato_speed=(dat&0xf0)>>2; + if (dat & 0x0f) control.channel[p_track].vibrato_depth = dat & 0xf; + if (dat & 0xf0) control.channel[p_track].vibrato_speed = (dat & 0xf0) >> 2; } - if (control.external_vibrato) break; - + if (control.external_vibrato) break; + if (control.channel[p_track].period) { - do_vibrato(p_track,false); - control.channel[p_track].has_own_period=true; - } + do_vibrato(p_track, false); + control.channel[p_track].has_own_period = true; + } } break; case 'I': { - do_tremor(p_track); - control.channel[p_track].has_own_volume=true; + do_tremor(p_track); + control.channel[p_track].has_own_volume = true; } break; case 'J': { @@ -953,56 +936,61 @@ void CPPlayer::run_effects(int p_track) { } break; case 'K': { - uint8_t inf ; + uint8_t inf; //explicitslides=1; - inf=control.channel[p_track].current_parameter; - - control.channel[p_track].doing_vibrato=true; + inf = control.channel[p_track].current_parameter; + + control.channel[p_track].doing_vibrato = true; + if (inf) + control.channel[p_track].volume_slide_info = inf; + else + inf = control.channel[p_track].volume_slide_info; - if (inf) control.channel[p_track].volume_slide_info=inf; - else inf=control.channel[p_track].volume_slide_info; - - do_volume_slide(p_track,inf); + do_volume_slide(p_track, inf); + + if (control.external_vibrato) break; - if (control.external_vibrato) break; - if (control.channel[p_track].period) { - do_vibrato(p_track,false); - control.channel[p_track].has_own_period=true; - } + do_vibrato(p_track, false); + control.channel[p_track].has_own_period = true; + } } break; case 'L': { - uint8_t inf ; + uint8_t inf; //explicitslides=1; - inf=control.channel[p_track].current_parameter; + inf = control.channel[p_track].current_parameter; - if (inf) control.channel[p_track].volume_slide_info=inf; - else inf=control.channel[p_track].volume_slide_info; - - do_volume_slide(p_track,inf); + if (inf) + control.channel[p_track].volume_slide_info = inf; + else + inf = control.channel[p_track].volume_slide_info; - if (control.channel[p_track].period && (control.channel[p_track].old_note<=120)) { - if ( (!control.ticks_counter) && (control.channel[p_track].new_instrument) ){ - - control.channel[p_track].kick=KICK_NOTE; - control.channel[p_track].sample_start_index=0; + do_volume_slide(p_track, inf); + + if (control.channel[p_track].period && (control.channel[p_track].old_note <= 120)) { + if ((!control.ticks_counter) && (control.channel[p_track].new_instrument)) { + + control.channel[p_track].kick = KICK_NOTE; + control.channel[p_track].sample_start_index = 0; } else { - control.channel[p_track].kick=(control.channel[p_track].kick==KICK_NOTE)?KICK_ENVELOPE:KICK_NOTHING; + control.channel[p_track].kick = (control.channel[p_track].kick == KICK_NOTE) ? KICK_ENVELOPE : KICK_NOTHING; } do_pitch_slide_to_note(p_track); - control.channel[p_track].has_own_period=true; + control.channel[p_track].has_own_period = true; } } break; case 'M': { - control.channel[p_track].channel_volume=control.channel[p_track].current_parameter; - if (control.channel[p_track].channel_volume>64) control.channel[p_track].channel_volume=64; - else if (control.channel[p_track].channel_volume<0) control.channel[p_track].channel_volume=0; + control.channel[p_track].channel_volume = control.channel[p_track].current_parameter; + if (control.channel[p_track].channel_volume > 64) + control.channel[p_track].channel_volume = 64; + else if (control.channel[p_track].channel_volume < 0) + control.channel[p_track].channel_volume = 0; } break; case 'N': { @@ -1011,14 +999,14 @@ void CPPlayer::run_effects(int p_track) { case 'O': { if (!control.ticks_counter) { - - if (control.channel[p_track].current_parameter) control.channel[p_track].lo_offset=(uint16_t)control.channel[p_track].current_parameter<<8; - control.channel[p_track].sample_start_index=control.channel[p_track].hi_offset|control.channel[p_track].lo_offset; + + if (control.channel[p_track].current_parameter) control.channel[p_track].lo_offset = (uint16_t)control.channel[p_track].current_parameter << 8; + control.channel[p_track].sample_start_index = control.channel[p_track].hi_offset | control.channel[p_track].lo_offset; //if ((control.channel[p_track].sample_ptr!=NULL)&&(control.channel[p_track].sample_start_index>control.channel[p_track].sample_ptr->data.size)) { - //TODO, O effect - //a->start=a->s->flags&(SF_LOOP|SF_BIDI)?a->s->loopstart:a->s->length; - //} + //TODO, O effect + //a->start=a->s->flags&(SF_LOOP|SF_BIDI)?a->s->loopstart:a->s->length; + //} } } break; case 'P': { @@ -1031,93 +1019,92 @@ void CPPlayer::run_effects(int p_track) { } break; case 'R': { - uint8_t dat; if (control.channel[p_track].current_parameter) { - control.channel[p_track].tremolo_info=control.channel[p_track].current_parameter; + control.channel[p_track].tremolo_info = control.channel[p_track].current_parameter; } - dat=control.channel[p_track].tremolo_info; - + dat = control.channel[p_track].tremolo_info; + if (!control.ticks_counter && dat) { - if (dat&0x0f) control.channel[p_track].tremolo_depth=dat&0xf; - if (dat&0xf0) control.channel[p_track].tremolo_speed=(dat&0xf0)>>2; + if (dat & 0x0f) control.channel[p_track].tremolo_depth = dat & 0xf; + if (dat & 0xf0) control.channel[p_track].tremolo_speed = (dat & 0xf0) >> 2; } do_tremolo(p_track); - control.channel[p_track].has_own_volume=true; - + control.channel[p_track].has_own_volume = true; + } break; case 'S': { do_effect_S(p_track); } break; case 'T': { - uint8_t dat; - int16_t temp=control.tempo; + uint8_t dat; + int16_t temp = control.tempo; if (control.pattern_delay_2) return; if (control.channel[p_track].current_parameter) { - control.channel[p_track].tempo_slide_info=control.channel[p_track].current_parameter; + control.channel[p_track].tempo_slide_info = control.channel[p_track].current_parameter; } - dat=control.channel[p_track].tempo_slide_info; + dat = control.channel[p_track].tempo_slide_info; - if (dat>=0x20) { + if (dat >= 0x20) { if (control.ticks_counter) break; - control.tempo=dat; + control.tempo = dat; } else { if (!control.ticks_counter) break; - if (dat&0x10) { - - temp+=(dat&0x0f); + if (dat & 0x10) { + + temp += (dat & 0x0f); } else { - temp-=dat; + temp -= dat; } - control.tempo=(temp>255)?255:(temp<0x20?0x20:temp); - } - + control.tempo = (temp > 255) ? 255 : (temp < 0x20 ? 0x20 : temp); + } + } break; case 'U': { - + uint8_t dat; - dat=control.channel[p_track].current_parameter; - control.channel[p_track].doing_vibrato=true; + dat = control.channel[p_track].current_parameter; + control.channel[p_track].doing_vibrato = true; if (!control.ticks_counter) { - if (dat&0x0f) control.channel[p_track].vibrato_depth=dat&0xf; - if (dat&0xf0) control.channel[p_track].vibrato_speed=(dat&0xf0)>>2; + if (dat & 0x0f) control.channel[p_track].vibrato_depth = dat & 0xf; + if (dat & 0xf0) control.channel[p_track].vibrato_speed = (dat & 0xf0) >> 2; } - if (control.external_vibrato) break; + if (control.external_vibrato) break; if (control.channel[p_track].period) { - do_vibrato(p_track,true); - control.channel[p_track].has_own_period=true; - } + do_vibrato(p_track, true); + control.channel[p_track].has_own_period = true; + } } break; case 'V': { - control.global_volume=control.channel[p_track].current_parameter; - if (control.global_volume>128) control.global_volume=128; + control.global_volume = control.channel[p_track].current_parameter; + if (control.global_volume > 128) control.global_volume = 128; } break; case 'W': { - do_global_volume_slide(p_track); + do_global_volume_slide(p_track); } break; case 'X': { //sets both channel and current - control.channel[p_track].channel_panning=control.channel[p_track].current_parameter; - control.channel[p_track].panning=control.channel[p_track].current_parameter; + control.channel[p_track].channel_panning = control.channel[p_track].current_parameter; + control.channel[p_track].panning = control.channel[p_track].current_parameter; } break; case 'Y': { @@ -1125,108 +1112,102 @@ void CPPlayer::run_effects(int p_track) { if (control.channel[p_track].current_parameter) { - control.channel[p_track].panbrello_info=control.channel[p_track].current_parameter; + control.channel[p_track].panbrello_info = control.channel[p_track].current_parameter; } - dat=control.channel[p_track].panbrello_info; + dat = control.channel[p_track].panbrello_info; if (!control.ticks_counter) { - if (dat&0x0f) control.channel[p_track].panbrello_depth=(dat&0xf); - if (dat&0xf0) control.channel[p_track].panbrello_speed=(dat&0xf0)>>4; + if (dat & 0x0f) control.channel[p_track].panbrello_depth = (dat & 0xf); + if (dat & 0xf0) control.channel[p_track].panbrello_speed = (dat & 0xf0) >> 4; } //if (pf->panflag) - if (control.channel[p_track].panning!=PAN_SURROUND)do_panbrello(p_track); - + if (control.channel[p_track].panning != PAN_SURROUND) do_panbrello(p_track); + } break; case 'Z': { //I DO! cuttoff! - uint16_t dat=control.channel[p_track].current_parameter; - - if (dat<0x80) { - - control.channel[p_track].filter.it_cutoff=dat*2; - if (control.channel[p_track].filter.it_cutoff>0x80) + uint16_t dat = control.channel[p_track].current_parameter; + + if (dat < 0x80) { + + control.channel[p_track].filter.it_cutoff = dat * 2; + if (control.channel[p_track].filter.it_cutoff > 0x80) control.channel[p_track].filter.it_cutoff++; - } else if (dat<0x90) { - - control.channel[p_track].filter.it_reso=(dat-0x80)*0x10; + } else if (dat < 0x90) { + + control.channel[p_track].filter.it_reso = (dat - 0x80) * 0x10; } else { - - control.channel[p_track].reverb_send=(dat-0x90)*255/0x6F; + + control.channel[p_track].reverb_send = (dat - 0x90) * 255 / 0x6F; } - - } break; + } break; } - } void CPPlayer::pre_process_effects() { -// MP_VOICE *aout; + // MP_VOICE *aout; int i; - for (i=0;i<CPPattern::WIDTH;i++) { + for (i = 0; i < CPPattern::WIDTH; i++) { + + //a=&pf->control[mp_channel]; - //a=&pf->control[mp_channel]; + // if ((aout=a->slave)) { + // a->fadevol=aout->fadevol; + // a->period=aout->period; + // if (a->kick==KICK_KEYOFF) a->keyoff=aout->keyoff; + //} - // if ((aout=a->slave)) { - // a->fadevol=aout->fadevol; - // a->period=aout->period; - // if (a->kick==KICK_KEYOFF) a->keyoff=aout->keyoff; - //} + //if (!a->row) continue; + //UniSetRow(a->row); + control.channel[i].has_own_period = false; + control.channel[i].has_own_volume = false; + control.channel[i].doing_vibrato = false; + //explicitslides=0; + //pt_playeffects(); + if (control.ticks_counter < control.speed) { - //if (!a->row) continue; - //UniSetRow(a->row); - control.channel[i].has_own_period=false; - control.channel[i].has_own_volume=false; - control.channel[i].doing_vibrato=false; - //explicitslides=0; - //pt_playeffects(); - if (control.ticks_counter<control.speed) { - run_effects(i); run_volume_column_effects(i); } - /* continue volume slide if necessary for XM and IT */ - //if (pf->flags&UF_BGSLIDES) { - // if (!explicitslides && a->sliding) - // DoS3MVolSlide(0); - // else if (a->tmpvolume) a->sliding=explicitslides; - //} + /* continue volume slide if necessary for XM and IT */ + //if (pf->flags&UF_BGSLIDES) { + // if (!explicitslides && a->sliding) + // DoS3MVolSlide(0); + // else if (a->tmpvolume) a->sliding=explicitslides; + //} - if (!control.channel[i].has_own_period) control.channel[i].period=control.channel[i].aux_period; - if (!control.channel[i].has_own_volume) control.channel[i].volume=control.channel[i].aux_volume; + if (!control.channel[i].has_own_period) control.channel[i].period = control.channel[i].aux_period; + if (!control.channel[i].has_own_volume) control.channel[i].volume = control.channel[i].aux_volume; - if ((control.channel[i].sample_ptr!=NULL) && !(song->has_instruments() && (control.channel[i].instrument_ptr==NULL))) { + if ((control.channel[i].sample_ptr != NULL) && !(song->has_instruments() && (control.channel[i].instrument_ptr == NULL))) { if (song->has_instruments()) { - control.channel[i].output_volume= - (control.channel[i].volume*control.channel[i].sample_ptr->get_global_volume()*control.channel[i].instrument_ptr->get_volume_global_amount())/2048; - control.channel[i].output_volume=control.channel[i].output_volume*control.channel[i].random_volume_variation/100; - - } else { + control.channel[i].output_volume = + (control.channel[i].volume * control.channel[i].sample_ptr->get_global_volume() * control.channel[i].instrument_ptr->get_volume_global_amount()) / 2048; + control.channel[i].output_volume = control.channel[i].output_volume * control.channel[i].random_volume_variation / 100; - control.channel[i].output_volume= - (control.channel[i].volume*control.channel[i].sample_ptr->get_global_volume())>>4; - + } else { + + control.channel[i].output_volume = + (control.channel[i].volume * control.channel[i].sample_ptr->get_global_volume()) >> 4; } - if (control.channel[i].output_volume>256) { - - control.channel[i].output_volume=256; + if (control.channel[i].output_volume > 256) { - } else if (control.channel[i].output_volume<0) { + control.channel[i].output_volume = 256; - control.channel[i].output_volume=0; - } - - - } - } + } else if (control.channel[i].output_volume < 0) { + control.channel[i].output_volume = 0; + } + } + } } diff --git a/modules/chibi/cp_player_data_envelopes.cpp b/modules/chibi/cp_player_data_envelopes.cpp index a720eaf73..f444f7d24 100644 --- a/modules/chibi/cp_player_data_envelopes.cpp +++ b/modules/chibi/cp_player_data_envelopes.cpp @@ -29,60 +29,55 @@ #include "cp_player_data.h" - -void CPPlayer::Voice_Control::start_envelope(CPEnvelope *p_envelope,Envelope_Control *p_envelope_ctrl,Envelope_Control *p_from_env) { - +void CPPlayer::Voice_Control::start_envelope(CPEnvelope *p_envelope, Envelope_Control *p_envelope_ctrl, Envelope_Control *p_from_env) { if (p_from_env && p_envelope->is_carry_enabled() && !p_from_env->terminated) { - - *p_envelope_ctrl=*p_from_env; + *p_envelope_ctrl = *p_from_env; } else { - p_envelope_ctrl->pos_index=0; - p_envelope_ctrl->status=1; - p_envelope_ctrl->sustain_looping=p_envelope->is_sustain_loop_enabled(); - p_envelope_ctrl->looping=p_envelope->is_loop_enabled(); - p_envelope_ctrl->terminated=false; - p_envelope_ctrl->kill=false; - p_envelope_ctrl->value=p_envelope->get_height_at_pos(p_envelope_ctrl->pos_index); + p_envelope_ctrl->pos_index = 0; + p_envelope_ctrl->status = 1; + p_envelope_ctrl->sustain_looping = p_envelope->is_sustain_loop_enabled(); + p_envelope_ctrl->looping = p_envelope->is_loop_enabled(); + p_envelope_ctrl->terminated = false; + p_envelope_ctrl->kill = false; + p_envelope_ctrl->value = p_envelope->get_height_at_pos(p_envelope_ctrl->pos_index); } } -bool CPPlayer::Voice_Control::process_envelope(CPEnvelope *p_envelope,Envelope_Control *p_envelope_ctrl) { +bool CPPlayer::Voice_Control::process_envelope(CPEnvelope *p_envelope, Envelope_Control *p_envelope_ctrl) { - if (!p_envelope_ctrl->active) + if (!p_envelope_ctrl->active) return false; - if (note_end_flags&END_NOTE_OFF) p_envelope_ctrl->sustain_looping=false; + if (note_end_flags & END_NOTE_OFF) p_envelope_ctrl->sustain_looping = false; - p_envelope_ctrl->value=p_envelope->get_height_at_pos(p_envelope_ctrl->pos_index); - if (p_envelope_ctrl->value==CPEnvelope::NO_POINT) + p_envelope_ctrl->value = p_envelope->get_height_at_pos(p_envelope_ctrl->pos_index); + if (p_envelope_ctrl->value == CPEnvelope::NO_POINT) return false; - p_envelope_ctrl->pos_index++; if (p_envelope_ctrl->sustain_looping) { - if (p_envelope_ctrl->pos_index>p_envelope->get_node(p_envelope->get_sustain_loop_end()).tick_offset) { + if (p_envelope_ctrl->pos_index > p_envelope->get_node(p_envelope->get_sustain_loop_end()).tick_offset) { - p_envelope_ctrl->pos_index=p_envelope->get_node(p_envelope->get_sustain_loop_begin()).tick_offset; + p_envelope_ctrl->pos_index = p_envelope->get_node(p_envelope->get_sustain_loop_begin()).tick_offset; } } else if (p_envelope_ctrl->looping) { - if (p_envelope_ctrl->pos_index>p_envelope->get_node(p_envelope->get_loop_end()).tick_offset) { + if (p_envelope_ctrl->pos_index > p_envelope->get_node(p_envelope->get_loop_end()).tick_offset) { - p_envelope_ctrl->pos_index=p_envelope->get_node(p_envelope->get_loop_begin()).tick_offset; + p_envelope_ctrl->pos_index = p_envelope->get_node(p_envelope->get_loop_begin()).tick_offset; } - } - if (p_envelope_ctrl->pos_index>p_envelope->get_node(p_envelope->get_node_count()-1).tick_offset) { + if (p_envelope_ctrl->pos_index > p_envelope->get_node(p_envelope->get_node_count() - 1).tick_offset) { - p_envelope_ctrl->terminated=true; - p_envelope_ctrl->pos_index=p_envelope->get_node(p_envelope->get_node_count()-1).tick_offset; - if (p_envelope->get_node(p_envelope->get_node_count()-1).value==0) p_envelope_ctrl->kill=true; + p_envelope_ctrl->terminated = true; + p_envelope_ctrl->pos_index = p_envelope->get_node(p_envelope->get_node_count() - 1).tick_offset; + if (p_envelope->get_node(p_envelope->get_node_count() - 1).value == 0) p_envelope_ctrl->kill = true; } return true; diff --git a/modules/chibi/cp_player_data_events.cpp b/modules/chibi/cp_player_data_events.cpp index 7ec3f1931..a0b355d9a 100644 --- a/modules/chibi/cp_player_data_events.cpp +++ b/modules/chibi/cp_player_data_events.cpp @@ -39,283 +39,254 @@ will just find one and do it. */ - #define C5FREQ 261.6255653006 -static const int32_t C5FREQ_MIXER = ((int32_t)(C5FREQ*(float)(1<<CPMixer::FREQUENCY_BITS))); - +static const int32_t C5FREQ_MIXER = ((int32_t)(C5FREQ * (float)(1 << CPMixer::FREQUENCY_BITS))); void CPPlayer::setup_voices() { - int i,voice_index; + int i, voice_index; - - + for (i = 0; i < CPPattern::WIDTH; i++) { - for (i=0;i<CPPattern::WIDTH;i++) { - - voice_index=-1; + voice_index = -1; if (control.channel[i].note_delay) continue; - // check if we need a new empty voice - if (control.channel[i].kick==KICK_NOTE) { + if (control.channel[i].kick == KICK_NOTE) { /* if no channel was cut above, find an empty or quiet channel here */ - if ( song->has_instruments() && !control.force_no_nna) { + if (song->has_instruments() && !control.force_no_nna) { - if (control.channel[i].slave_voice==NULL) { // no slave?? + if (control.channel[i].slave_voice == NULL) { // no slave?? int newchn; - if ((newchn=find_empty_voice())!=-1) { + if ((newchn = find_empty_voice()) != -1) { - control.channel[i].slave_voice_index=newchn; - control.channel[i].slave_voice=&voice[newchn]; + control.channel[i].slave_voice_index = newchn; + control.channel[i].slave_voice = &voice[newchn]; } } - } else { - if (i<control.max_voices) { + } else { + if (i < control.max_voices) { - control.channel[i].slave_voice_index=i; - control.channel[i].slave_voice=&voice[i]; - } else { + control.channel[i].slave_voice_index = i; + control.channel[i].slave_voice = &voice[i]; + } else { //This is a _DIRTY_ hack, but i cant think a better way. - control.channel[i].slave_voice_index=control.max_voices-1; - control.channel[i].slave_voice=&voice[control.max_voices-1]; + control.channel[i].slave_voice_index = control.max_voices - 1; + control.channel[i].slave_voice = &voice[control.max_voices - 1]; } - } - /* assign parts of MP_VOICE only done for a KICK_NOTE */ - if ( ( control.channel[i].slave_voice!=NULL ) ) { + if ((control.channel[i].slave_voice != NULL)) { - voice_index=control.channel[i].slave_voice_index; - Voice_Control &v=voice[voice_index]; - - if (v.has_master_channel && (v.master_channel!=NULL) ) { - // If this voice already has a master channel, make sure to remove the reference to it. - v.master_channel->slave_voice=NULL; + voice_index = control.channel[i].slave_voice_index; + Voice_Control &v = voice[voice_index]; + if (v.has_master_channel && (v.master_channel != NULL)) { + // If this voice already has a master channel, make sure to remove the reference to it. + v.master_channel->slave_voice = NULL; } //notify the voice that the current channel is the master - v.master_channel=&control.channel[i]; + v.master_channel = &control.channel[i]; //set the voice as slave of the current channel - control.channel[i].slave_voice=&v; + control.channel[i].slave_voice = &v; //master channel index of the voice - v.master_channel_index=i; - v.has_master_channel=true; + v.master_channel_index = i; + v.has_master_channel = true; } } else { - // nope.. - // so if we DO have a slave voice then use it. - if ( control.channel[i].slave_voice!=NULL ) { - - voice_index=control.channel[i].slave_voice_index; + // nope.. + // so if we DO have a slave voice then use it. + if (control.channel[i].slave_voice != NULL) { + + voice_index = control.channel[i].slave_voice_index; } } - //assuming this channel has a slave voice.. - if (voice_index>=0) { + //assuming this channel has a slave voice.. + if (voice_index >= 0) { // IMPROVE: Code a method for this: voice[voice_index].update_info_from_master_channel(); } - control.channel[i].kick=KICK_NOTHING; + control.channel[i].kick = KICK_NOTHING; } } void CPPlayer::Voice_Control::reset() { - cp_memzero(this,sizeof(*this)); - - instrument_ptr=NULL; - sample_ptr=NULL; - has_master_channel=false; - instrument_index=-1; - reverb_send=0; - chorus_send=0; - filter.it_cutoff=255; - filter.it_reso=0; - display_volume=0; + cp_memzero(this, sizeof(*this)); - + instrument_ptr = NULL; + sample_ptr = NULL; + has_master_channel = false; + instrument_index = -1; + reverb_send = 0; + chorus_send = 0; + filter.it_cutoff = 255; + filter.it_reso = 0; + display_volume = 0; } void CPPlayer::Channel_Control::reset() { - int prev_gv =channel_global_volume; - cp_memzero(this,sizeof(*this)); + int prev_gv = channel_global_volume; + cp_memzero(this, sizeof(*this)); - slave_voice=NULL; - slave_voice_index=255; + slave_voice = NULL; + slave_voice_index = 255; - mute=false; - old_note=255; - real_note=255; - instrument_index=255; - filter.it_cutoff=255; - filter.it_reso=0; - reverb_send=0; - chorus_send=0; - reserved=false; - carry.maybe=false; - last_event_usecs=-1; - channel_global_volume=prev_gv; + mute = false; + old_note = 255; + real_note = 255; + instrument_index = 255; + filter.it_cutoff = 255; + filter.it_reso = 0; + reverb_send = 0; + chorus_send = 0; + reserved = false; + carry.maybe = false; + last_event_usecs = -1; + channel_global_volume = prev_gv; } void CPPlayer::Voice_Control::update_info_from_master_channel() { - instrument_ptr=master_channel->instrument_ptr; - sample_ptr=master_channel->sample_ptr; + instrument_ptr = master_channel->instrument_ptr; + sample_ptr = master_channel->sample_ptr; - instrument_index=master_channel->instrument_index; - sample_index=master_channel->sample_index; + instrument_index = master_channel->instrument_index; + sample_index = master_channel->sample_index; - note=master_channel->note; - output_volume=master_channel->output_volume; + note = master_channel->note; + output_volume = master_channel->output_volume; - channel_volume=master_channel->channel_volume; + channel_volume = master_channel->channel_volume; - panning=master_channel->panning; + panning = master_channel->panning; - kick=master_channel->kick; - note_end_flags=master_channel->note_end_flags; - period=master_channel->period; + kick = master_channel->kick; + note_end_flags = master_channel->note_end_flags; + period = master_channel->period; - volume_envelope_ctrl.active=master_channel->volume_envelope_on; - panning_envelope_ctrl.active=master_channel->panning_envelope_on; - pitch_envelope_ctrl.active=master_channel->pitch_envelope_on; + volume_envelope_ctrl.active = master_channel->volume_envelope_on; + panning_envelope_ctrl.active = master_channel->panning_envelope_on; + pitch_envelope_ctrl.active = master_channel->pitch_envelope_on; + NNA_type = master_channel->NNA_type; + reverb_send = master_channel->reverb_send; + chorus_send = master_channel->chorus_send; - NNA_type=master_channel->NNA_type; - reverb_send=master_channel->reverb_send; - chorus_send=master_channel->chorus_send; - -// last_note_type=master_channel->last_note_type; - - sample_start_index=master_channel->sample_start_index; - filter=master_channel->filter; + // last_note_type=master_channel->last_note_type; + sample_start_index = master_channel->sample_start_index; + filter = master_channel->filter; } - void CPPlayer::update_mixer() { int tmp_mixer_period; - int32_t tmp_vibrato_value,tmp_vibrato_depth,tmp_volenv_value; + int32_t tmp_vibrato_value, tmp_vibrato_depth, tmp_volenv_value; uint64_t tmpvol; // 64bits should be the only way to avoid getting notes raped out int i; + control.voices_used = 0; - control.voices_used=0; + for (i = 0; i < control.max_voices; i++) { - for (i=0;i<control.max_voices;i++) { + int filter_env = -1; + Voice_Control &v = voice[i]; + + if (!((v.kick == KICK_NOTE) || (v.kick == KICK_NOTEOFF)) && !is_voice_active(i)) + continue; - - int filter_env=-1; - Voice_Control &v=voice[i]; - - if ( !((v.kick==KICK_NOTE)||(v.kick==KICK_NOTEOFF)) && !is_voice_active(i)) - continue; - //if voice doesnt have a sample set or size is 0.. forget it - if ( v.sample_ptr==NULL) continue; - + if (v.sample_ptr == NULL) continue; //TODO set limits somewhere else - if (v.period<40) { - - v.period=40; + if (v.period < 40) { - } else if (v.period>50000) { + v.period = 40; - v.period=50000; - } + } else if (v.period > 50000) { + v.period = 50000; + } - if ((v.kick==KICK_NOTE)||(v.kick==KICK_NOTEOFF)) { + if ((v.kick == KICK_NOTE) || (v.kick == KICK_NOTEOFF)) { int real_start_index; - if (v.sample_start_index==-1) { + if (v.sample_start_index == -1) { - real_start_index=0; + real_start_index = 0; } else { - real_start_index=v.sample_start_index; + real_start_index = v.sample_start_index; } - mixer->setup_voice(i,v.sample_ptr->get_sample_data(),real_start_index); - v.fadeout_volume=1024; //IT Docs it is 1024 internally - v.auto_vibrato_sweep_pos=0; - - - + mixer->setup_voice(i, v.sample_ptr->get_sample_data(), real_start_index); + v.fadeout_volume = 1024; //IT Docs it is 1024 internally + v.auto_vibrato_sweep_pos = 0; } + /* Start Envelopes */ + if (song->has_instruments() && ((v.kick == KICK_NOTE) || (v.kick == KICK_ENVELOPE))) { + + // Voice_Control *carry=0; - /* Start Envelopes */ - if ( song->has_instruments() && ((v.kick==KICK_NOTE)||(v.kick==KICK_ENVELOPE))) { - -// Voice_Control *carry=0; - - if (v.has_master_channel && v.master_channel->carry.maybe) { - - v.start_envelope(v.instrument_ptr->get_volume_envelope(),&v.volume_envelope_ctrl,&v.master_channel->carry.vol); - v.start_envelope(v.instrument_ptr->get_pan_envelope(),&v.panning_envelope_ctrl,&v.master_channel->carry.pan); - v.start_envelope(v.instrument_ptr->get_pitch_filter_envelope(),&v.pitch_envelope_ctrl,&v.master_channel->carry.pitch); - - } else { - - v.start_envelope(v.instrument_ptr->get_volume_envelope(),&v.volume_envelope_ctrl,NULL); - v.start_envelope(v.instrument_ptr->get_pan_envelope(),&v.panning_envelope_ctrl,NULL); - v.start_envelope(v.instrument_ptr->get_pitch_filter_envelope(),&v.pitch_envelope_ctrl,NULL); - - } + v.start_envelope(v.instrument_ptr->get_volume_envelope(), &v.volume_envelope_ctrl, &v.master_channel->carry.vol); + v.start_envelope(v.instrument_ptr->get_pan_envelope(), &v.panning_envelope_ctrl, &v.master_channel->carry.pan); + v.start_envelope(v.instrument_ptr->get_pitch_filter_envelope(), &v.pitch_envelope_ctrl, &v.master_channel->carry.pitch); + + } else { + v.start_envelope(v.instrument_ptr->get_volume_envelope(), &v.volume_envelope_ctrl, NULL); + v.start_envelope(v.instrument_ptr->get_pan_envelope(), &v.panning_envelope_ctrl, NULL); + v.start_envelope(v.instrument_ptr->get_pitch_filter_envelope(), &v.pitch_envelope_ctrl, NULL); + } } - v.kick=KICK_NOTHING; + v.kick = KICK_NOTHING; - if (song->has_instruments()) { + if (song->has_instruments()) { - if (!v.process_envelope(v.instrument_ptr->get_volume_envelope(),&v.volume_envelope_ctrl)) - v.volume_envelope_ctrl.value=64; + if (!v.process_envelope(v.instrument_ptr->get_volume_envelope(), &v.volume_envelope_ctrl)) + v.volume_envelope_ctrl.value = 64; - if (!v.process_envelope(v.instrument_ptr->get_pan_envelope(),&v.panning_envelope_ctrl)) - v.panning_envelope_ctrl.value=0; - - if (!v.process_envelope(v.instrument_ptr->get_pitch_filter_envelope(),&v.pitch_envelope_ctrl)) - v.pitch_envelope_ctrl.value=0; - + if (!v.process_envelope(v.instrument_ptr->get_pan_envelope(), &v.panning_envelope_ctrl)) + v.panning_envelope_ctrl.value = 0; + + if (!v.process_envelope(v.instrument_ptr->get_pitch_filter_envelope(), &v.pitch_envelope_ctrl)) + v.pitch_envelope_ctrl.value = 0; if (v.volume_envelope_ctrl.terminated) { if (v.volume_envelope_ctrl.kill) { - - v.fadeout_volume=0; + + v.fadeout_volume = 0; } else { - v.note_end_flags|=END_NOTE_FADE; - } + v.note_end_flags |= END_NOTE_FADE; + } } - } if (song->has_instruments()) { - tmp_volenv_value=v.volume_envelope_ctrl.value; + tmp_volenv_value = v.volume_envelope_ctrl.value; } else { - tmp_volenv_value=64; - + tmp_volenv_value = 64; } /*printf("fadeout %i\n",(int)v.fadeout_volume); @@ -325,349 +296,314 @@ void CPPlayer::update_mixer() { printf("cgb %i\n",(int)v.master_channel->channel_global_volume); */ - - tmpvol=(uint64_t)v.fadeout_volume; /* max 1024 - 10 bits */ - tmpvol*=(uint64_t)v.channel_volume; /* * max 64 - 6 bits */ - tmpvol*=(uint64_t)v.output_volume; /* * max 256 - 8 bits */ - tmpvol*=(uint64_t)tmp_volenv_value; /* max 64 - 6 bits*/ - tmpvol*=(uint64_t)v.master_channel->channel_global_volume; - v.display_volume=tmpvol>>22; //volume used for display purposes , 0 -- 256 - - tmpvol*=(uint64_t)song->get_mixing_volume(); /* max 128 - 7 bits */ - tmpvol*=(uint64_t)control.global_volume; /* max 128 - 7 bits*/ - /* total 10+6+8+6+7+7=44 bits */ + tmpvol = (uint64_t)v.fadeout_volume; /* max 1024 - 10 bits */ + tmpvol *= (uint64_t)v.channel_volume; /* * max 64 - 6 bits */ + tmpvol *= (uint64_t)v.output_volume; /* * max 256 - 8 bits */ + tmpvol *= (uint64_t)tmp_volenv_value; /* max 64 - 6 bits*/ + tmpvol *= (uint64_t)v.master_channel->channel_global_volume; + v.display_volume = tmpvol >> 22; //volume used for display purposes , 0 -- 256 + + tmpvol *= (uint64_t)song->get_mixing_volume(); /* max 128 - 7 bits */ + tmpvol *= (uint64_t)control.global_volume; /* max 128 - 7 bits*/ + /* total 10+6+8+6+7+7=44 bits */ + + tmpvol >>= 43; /* Move back to 8 bits range , 44-19+8=43*/ + + if (tmpvol > CP_VOL_MAX) + tmpvol = CP_VOL_MAX; - tmpvol>>=43; /* Move back to 8 bits range , 44-19+8=43*/ - - if (tmpvol>CP_VOL_MAX) - tmpvol=CP_VOL_MAX; - //printf("volume check - fade %i, channel %i, output %i, env %i, mix %i, global %i -- final %i\n",v.fadeout_volume, v.channel_volume,v.output_volume,tmp_volenv_value, song->get_mixing_volume(),control.global_volume,tmpvol); - - v.total_volume=tmpvol; + v.total_volume = tmpvol; - if ((v.master_channel!=NULL) && song->is_channel_mute( v.master_channel_index ) && !v.master_channel->reserved) { + if ((v.master_channel != NULL) && song->is_channel_mute(v.master_channel_index) && !v.master_channel->reserved) { - mixer->set_voice_volume(i,0); + mixer->set_voice_volume(i, 0); } else { - mixer->set_voice_volume(i,tmpvol); - if (v.fadeout_volume>0) control.voices_used++; + mixer->set_voice_volume(i, tmpvol); + if (v.fadeout_volume > 0) control.voices_used++; } - if (!song->is_stereo()) { - mixer->set_voice_panning(i,PAN_CENTER); + mixer->set_voice_panning(i, PAN_CENTER); - } else if (v.panning==PAN_SURROUND) { + } else if (v.panning == PAN_SURROUND) { - mixer->set_voice_panning(i,PAN_SURROUND); + mixer->set_voice_panning(i, PAN_SURROUND); } else if (song->has_instruments()) { - int newpan,real_modifier; + int newpan, real_modifier; - - real_modifier=(v.panning_envelope_ctrl.value*(PAN_CENTER-cp_intabs(v.panning-PAN_CENTER)))/32; + real_modifier = (v.panning_envelope_ctrl.value * (PAN_CENTER - cp_intabs(v.panning - PAN_CENTER))) / 32; - newpan=v.panning+real_modifier; + newpan = v.panning + real_modifier; - newpan=(newpan<PAN_LEFT)?PAN_LEFT:(newpan>PAN_RIGHT)?PAN_RIGHT:newpan; + newpan = (newpan < PAN_LEFT) ? PAN_LEFT : (newpan > PAN_RIGHT) ? PAN_RIGHT : newpan; //printf("panenv val: %i, finalpan val %i\n",v.panning_envelope_ctrl.value,newpan); - - mixer->set_voice_panning(i,newpan); + + mixer->set_voice_panning(i, newpan); } else { - mixer->set_voice_panning(i,v.panning); + mixer->set_voice_panning(i, v.panning); } - - /* VIBRATO */ - if ( (v.period>0) && (v.sample_ptr->get_vibrato_depth()>0) ) { + if ((v.period > 0) && (v.sample_ptr->get_vibrato_depth() > 0)) { switch (v.sample_ptr->get_vibrato_type()) { case CPSample::VIBRATO_SINE: - tmp_vibrato_value=auto_vibrato_table[v.auto_vibrato_pos&127]; - if (v.auto_vibrato_pos & 0x80) tmp_vibrato_value=-tmp_vibrato_value; + tmp_vibrato_value = auto_vibrato_table[v.auto_vibrato_pos & 127]; + if (v.auto_vibrato_pos & 0x80) tmp_vibrato_value = -tmp_vibrato_value; break; case CPSample::VIBRATO_SQUARE: - tmp_vibrato_value=64; - if (v.auto_vibrato_pos & 0x80) tmp_vibrato_value=-tmp_vibrato_value; + tmp_vibrato_value = 64; + if (v.auto_vibrato_pos & 0x80) tmp_vibrato_value = -tmp_vibrato_value; break; case CPSample::VIBRATO_SAW: - tmp_vibrato_value=63-(((v.auto_vibrato_pos+128)&255)>>1); + tmp_vibrato_value = 63 - (((v.auto_vibrato_pos + 128) & 255) >> 1); break; default: - tmp_vibrato_value=(((v.auto_vibrato_pos+128)&255)>>1)-64; + tmp_vibrato_value = (((v.auto_vibrato_pos + 128) & 255) >> 1) - 64; break; } } else { - tmp_vibrato_value=0; + tmp_vibrato_value = 0; } - if ((v.auto_vibrato_sweep_pos>>8)<v.sample_ptr->get_vibrato_depth()) { + if ((v.auto_vibrato_sweep_pos >> 8) < v.sample_ptr->get_vibrato_depth()) { - v.auto_vibrato_sweep_pos+=v.sample_ptr->get_vibrato_speed(); //FIXME - speed? i think so - tmp_vibrato_depth=v.auto_vibrato_sweep_pos; + v.auto_vibrato_sweep_pos += v.sample_ptr->get_vibrato_speed(); //FIXME - speed? i think so + tmp_vibrato_depth = v.auto_vibrato_sweep_pos; } else { - tmp_vibrato_depth=v.sample_ptr->get_vibrato_depth()<<8; + tmp_vibrato_depth = v.sample_ptr->get_vibrato_depth() << 8; } - - tmp_vibrato_value=(tmp_vibrato_value*tmp_vibrato_depth)>>16; - if (song->has_linear_slides()) - tmp_vibrato_value>>=1; - v.period-=tmp_vibrato_value; + tmp_vibrato_value = (tmp_vibrato_value * tmp_vibrato_depth) >> 16; + if (song->has_linear_slides()) + tmp_vibrato_value >>= 1; + v.period -= tmp_vibrato_value; /* update vibrato position */ - v.auto_vibrato_pos=(v.auto_vibrato_pos+v.sample_ptr->get_vibrato_rate())&0xff; - - + v.auto_vibrato_pos = (v.auto_vibrato_pos + v.sample_ptr->get_vibrato_rate()) & 0xff; + /* process pitch envelope */ - tmp_mixer_period=v.period; + tmp_mixer_period = v.period; if (v.pitch_envelope_ctrl.active) { long aux_pitch_diff; - int pe_value=v.pitch_envelope_ctrl.value; - + int pe_value = v.pitch_envelope_ctrl.value; + if (!v.instrument_ptr->is_pitch_use_as_filter()) { - - - if (((uint16_t)v.note<<1)+pe_value<=0) - pe_value=-(v.note<<1); - int smp_c5=CPSampleManager::get_singleton()->get_c5_freq( v.sample_ptr->get_sample_data()); - - int base=get_period(((uint16_t)v.note<<1),smp_c5); - int env=get_period(((uint16_t)v.note<<1)+pe_value,smp_c5); + if (((uint16_t)v.note << 1) + pe_value <= 0) + pe_value = -(v.note << 1); + + int smp_c5 = CPSampleManager::get_singleton()->get_c5_freq(v.sample_ptr->get_sample_data()); + + int base = get_period(((uint16_t)v.note << 1), smp_c5); + int env = get_period(((uint16_t)v.note << 1) + pe_value, smp_c5); /* int env_next=(pe_value<0)?get_period(((uint16_t)(v.note-1)<<1)+pe_value,smp_c5):get_period(((uint16_t)(v.note+1)<<1)+pe_value,smp_c5); env=env+(abs(v.pitch_envelope_ctrl.value)&((1<<CPEnvelope::FX_HEIGHT_BITS)-1))*(env_next-env)/(1<<CPEnvelope::FX_HEIGHT_BITS); printf("env %i\n",env); - */ - aux_pitch_diff=env-base; + */ + aux_pitch_diff = env - base; + if (((int)tmp_mixer_period - aux_pitch_diff) < 0) aux_pitch_diff = 0; - if ( ((int)tmp_mixer_period-aux_pitch_diff)<0 ) aux_pitch_diff=0; - - tmp_mixer_period+=aux_pitch_diff; + tmp_mixer_period += aux_pitch_diff; } else { - filter_env=pe_value+32; //max 64 -// printf("pitch envelope at %i",filter_env); - + filter_env = pe_value + 32; //max 64 + // printf("pitch envelope at %i",filter_env); } } - if (v.fadeout_volume==0 || (v.note_end_flags & END_NOTE_KILL)) { /* check for a dead note (fadevol=0) */ + if (v.fadeout_volume == 0 || (v.note_end_flags & END_NOTE_KILL)) { /* check for a dead note (fadevol=0) */ mixer->stop_voice(i); } else { - - int32_t freq=get_frequency(tmp_mixer_period); - int32_t tracker_c5=get_frequency(get_period(60<<1,CPSampleManager::get_singleton()->get_c5_freq( v.sample_ptr->get_sample_data()))); - - freq=(int32_t)((uint64_t)freq*(uint64_t)C5FREQ_MIXER/(uint64_t)tracker_c5); //numbers may become very high - mixer->set_voice_frequency(i,freq); + int32_t freq = get_frequency(tmp_mixer_period); + int32_t tracker_c5 = get_frequency(get_period(60 << 1, CPSampleManager::get_singleton()->get_c5_freq(v.sample_ptr->get_sample_data()))); + + freq = (int32_t)((uint64_t)freq * (uint64_t)C5FREQ_MIXER / (uint64_t)tracker_c5); //numbers may become very high + mixer->set_voice_frequency(i, freq); /* if keyfade, start substracting fadeoutspeed from fadevol: */ - if ((song->has_instruments())&&(v.note_end_flags & END_NOTE_FADE)) { + if ((song->has_instruments()) && (v.note_end_flags & END_NOTE_FADE)) { - if (v.fadeout_volume>=(v.instrument_ptr->get_volume_fadeout())) { + if (v.fadeout_volume >= (v.instrument_ptr->get_volume_fadeout())) { - v.fadeout_volume-=(v.instrument_ptr->get_volume_fadeout()); + v.fadeout_volume -= (v.instrument_ptr->get_volume_fadeout()); } else { - v.fadeout_volume=0; + v.fadeout_volume = 0; } } - - /*FILTARSSSSSSSS*/ + /*FILTARSSSSSSSS*/ - - v.filter.envelope_cutoff=filter_env; + v.filter.envelope_cutoff = filter_env; v.filter.process(); - - if ((v.filter.final_cutoff<0xFF) && (control.filters)) { - + + if ((v.filter.final_cutoff < 0xFF) && (control.filters)) { + //int final_cutoff; //uint8_t final_reso; - + //v.filter.set_filter_parameters( &final_cutoff, &final_reso ); - - mixer->set_voice_filter(i,true,v.filter.final_cutoff,v.filter.it_reso); - } else { - - - mixer->set_voice_filter(i,false,0,0); - } - - /* RAIVERV */ - - mixer->set_voice_reverb_send(i,v.reverb_send); - /* CHAURUZ */ + mixer->set_voice_filter(i, true, v.filter.final_cutoff, v.filter.it_reso); + } else { + + mixer->set_voice_filter(i, false, 0, 0); + } + + /* RAIVERV */ + + mixer->set_voice_reverb_send(i, v.reverb_send); - mixer->set_voice_chorus_send(i,v.chorus_send); + /* CHAURUZ */ - } + mixer->set_voice_chorus_send(i, v.chorus_send); + } } - - switch(song->get_reverb_mode()) { - + switch (song->get_reverb_mode()) { + case CPSong::REVERB_MODE_ROOM: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_ROOM ); + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_ROOM); } break; case CPSong::REVERB_MODE_STUDIO_SMALL: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_STUDIO_SMALL ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_STUDIO_SMALL); + } break; case CPSong::REVERB_MODE_STUDIO_MEDIUM: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_STUDIO_MEDIUM ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_STUDIO_MEDIUM); + } break; case CPSong::REVERB_MODE_STUDIO_LARGE: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_STUDIO_LARGE ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_STUDIO_LARGE); + } break; case CPSong::REVERB_MODE_HALL: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_HALL ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_HALL); + } break; case CPSong::REVERB_MODE_SPACE_ECHO: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_SPACE_ECHO ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_SPACE_ECHO); + } break; case CPSong::REVERB_MODE_ECHO: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_ECHO ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_ECHO); + } break; case CPSong::REVERB_MODE_DELAY: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_DELAY ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_DELAY); + } break; case CPSong::REVERB_MODE_HALF_ECHO: { - - mixer->set_reverb_mode( CPMixer::REVERB_MODE_HALF_ECHO ); - + + mixer->set_reverb_mode(CPMixer::REVERB_MODE_HALF_ECHO); + } break; - } - - mixer->set_chorus_params(song->get_chorus_delay_ms(),song->get_chorus_separation_ms(),song->get_chorus_depth_ms10(),song->get_chorus_speed_hz10() ); - + mixer->set_chorus_params(song->get_chorus_delay_ms(), song->get_chorus_separation_ms(), song->get_chorus_depth_ms10(), song->get_chorus_speed_hz10()); } - - - - - - - void CPPlayer::handle_tick() { int i; - - if ( mixer==NULL ) return; - if ( song==NULL ) return; - + if (mixer == NULL) return; + if (song == NULL) return; /* update time counter (sngtime is in milliseconds (in fact 2^-10)) */ - if (control.ticks_counter>=control.speed) { // time to process... ***THE ROW***! + if (control.ticks_counter >= control.speed) { // time to process... ***THE ROW***! /* process pattern-delay. pf->patdly2 is the counter and pf->patdly is the command memory. */ -// if (control.pattern_delay_1) { + // if (control.pattern_delay_1) { -// control.pattern_delay_2=control.pattern_delay_1; -// control.pattern_delay_1=0; -// } -// if (control.pattern_delay_2) { -// patterndelay active -// if (--control.pattern_delay_2) -// so turn back pf->patpos by 1 -// if (pf->patpos) pf->patpos--; -// } + // control.pattern_delay_2=control.pattern_delay_1; + // control.pattern_delay_1=0; + // } + // if (control.pattern_delay_2) { + // patterndelay active + // if (--control.pattern_delay_2) + // so turn back pf->patpos by 1 + // if (pf->patpos) pf->patpos--; + // } - if (control.play_mode!=PLAY_NOTHING) { + if (control.play_mode != PLAY_NOTHING) { - control.ticks_counter=0; - + control.ticks_counter = 0; - if (control.position.force_next_order>=0) { + if (control.position.force_next_order >= 0) { - control.position.current_order=control.position.force_next_order; + control.position.current_order = control.position.force_next_order; } - control.position.force_next_order=-1; + control.position.force_next_order = -1; - control.previous_position=control.position; // for those special cases... - control.position.forbid_jump=false; + control.previous_position = control.position; // for those special cases... + control.position.forbid_jump = false; - for (i=0;i<CPPattern::WIDTH;i++) { + for (i = 0; i < CPPattern::WIDTH; i++) { - process_note(i,song->get_pattern(control.position.current_pattern)->get_note(i,control.position.current_row)); + process_note(i, song->get_pattern(control.position.current_pattern)->get_note(i, control.position.current_row)); } control.position.current_row++; - - if ( control.position.current_row>=song->get_pattern(control.position.current_pattern)->get_length() ) { - if (control.play_mode==PLAY_SONG) { + if (control.position.current_row >= song->get_pattern(control.position.current_pattern)->get_length()) { + + if (control.play_mode == PLAY_SONG) { int next_order; - next_order=get_song_next_order_idx(song,control.position.current_order); + next_order = get_song_next_order_idx(song, control.position.current_order); - if (next_order!=-1) { + if (next_order != -1) { // Do we have a "next order?" - control.position.current_pattern=song->get_order(next_order); - if (next_order<=control.position.current_order) - control.reached_end=true; - control.position.current_order=next_order; - + control.position.current_pattern = song->get_order(next_order); + if (next_order <= control.position.current_order) + control.reached_end = true; + control.position.current_order = next_order; + } else { // no, probably the user deleted the orderlist. - control.play_mode=PLAY_NOTHING; + control.play_mode = PLAY_NOTHING; reset(); - control.reached_end=true; + control.reached_end = true; } } - control.position.current_row=0; + control.position.current_row = 0; } - } - - } - - pre_process_effects(); process_NNAs(); setup_voices(); diff --git a/modules/chibi/cp_player_data_filter.cpp b/modules/chibi/cp_player_data_filter.cpp index e04ae126f..db5c9f262 100644 --- a/modules/chibi/cp_player_data_filter.cpp +++ b/modules/chibi/cp_player_data_filter.cpp @@ -27,63 +27,56 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ - #include "cp_player_data.h" static float filter_cutoff[256] = { - 130, 132, 134, 136, 138, 140, 142, 144, - 146, 148, 151, 153, 155, 157, 160, 162, - 164, 167, 169, 172, 174, 177, 179, 182, - 184, 187, 190, 193, 195, 198, 201, 204, - 207, 210, 213, 216, 220, 223, 226, 229, - 233, 236, 239, 243, 246, 250, 254, 257, - 261, 265, 269, 273, 277, 281, 285, 289, - 293, 297, 302, 306, 311, 315, 320, 324, - 329, 334, 339, 344, 349, 354, 359, 364, - 369, 375, 380, 386, 391, 397, 403, 409, - 415, 421, 427, 433, 440, 446, 452, 459, - 466, 472, 479, 486, 493, 501, 508, 515, - 523, 530, 538, 546, 554, 562, 570, 578, - 587, 595, 604, 613, 622, 631, 640, 649, - 659, 668, 678, 688, 698, 708, 718, 729, - 739, 750, 761, 772, 783, 795, 806, 818, - 830, 842, 854, 867, 880, 892, 905, 918, - 932, 945, 959, 973, 987, 1002, 1016, 1031, - 1046, 1061, 1077, 1092, 1108, 1124, 1141, 1157, - 1174, 1191, 1209, 1226, 1244, 1262, 1280, 1299, - 1318, 1337, 1357, 1376, 1396, 1417, 1437, 1458, - 1479, 1501, 1523, 1545, 1567, 1590, 1613, 1637, - 1661, 1685, 1709, 1734, 1760, 1785, 1811, 1837, - 1864, 1891, 1919, 1947, 1975, 2004, 2033, 2062, - 2093, 2123, 2154, 2185, 2217, 2249, 2282, 2315, - 2349, 2383, 2418, 2453, 2489, 2525, 2561, 2599, - 2637, 2675, 2714, 2753, 2793, 2834, 2875, 2917, - 2959, 3003, 3046, 3091, 3135, 3181, 3227, 3274, - 3322, 3370, 3419, 3469, 3520, 3571, 3623, 3675, - 3729, 3783, 3838, 3894, 3951, 4008, 4066, 4125, - 4186, 4246, 4308, 4371, 4434, 4499, 4564, 4631, - 4698, 4766, 4836, 4906, 4978, 5050, 5123, 5198 + 130, 132, 134, 136, 138, 140, 142, 144, + 146, 148, 151, 153, 155, 157, 160, 162, + 164, 167, 169, 172, 174, 177, 179, 182, + 184, 187, 190, 193, 195, 198, 201, 204, + 207, 210, 213, 216, 220, 223, 226, 229, + 233, 236, 239, 243, 246, 250, 254, 257, + 261, 265, 269, 273, 277, 281, 285, 289, + 293, 297, 302, 306, 311, 315, 320, 324, + 329, 334, 339, 344, 349, 354, 359, 364, + 369, 375, 380, 386, 391, 397, 403, 409, + 415, 421, 427, 433, 440, 446, 452, 459, + 466, 472, 479, 486, 493, 501, 508, 515, + 523, 530, 538, 546, 554, 562, 570, 578, + 587, 595, 604, 613, 622, 631, 640, 649, + 659, 668, 678, 688, 698, 708, 718, 729, + 739, 750, 761, 772, 783, 795, 806, 818, + 830, 842, 854, 867, 880, 892, 905, 918, + 932, 945, 959, 973, 987, 1002, 1016, 1031, + 1046, 1061, 1077, 1092, 1108, 1124, 1141, 1157, + 1174, 1191, 1209, 1226, 1244, 1262, 1280, 1299, + 1318, 1337, 1357, 1376, 1396, 1417, 1437, 1458, + 1479, 1501, 1523, 1545, 1567, 1590, 1613, 1637, + 1661, 1685, 1709, 1734, 1760, 1785, 1811, 1837, + 1864, 1891, 1919, 1947, 1975, 2004, 2033, 2062, + 2093, 2123, 2154, 2185, 2217, 2249, 2282, 2315, + 2349, 2383, 2418, 2453, 2489, 2525, 2561, 2599, + 2637, 2675, 2714, 2753, 2793, 2834, 2875, 2917, + 2959, 3003, 3046, 3091, 3135, 3181, 3227, 3274, + 3322, 3370, 3419, 3469, 3520, 3571, 3623, 3675, + 3729, 3783, 3838, 3894, 3951, 4008, 4066, 4125, + 4186, 4246, 4308, 4371, 4434, 4499, 4564, 4631, + 4698, 4766, 4836, 4906, 4978, 5050, 5123, 5198 }; - void CPPlayer::Filter_Control::process() { - - - final_cutoff=it_cutoff; - if (envelope_cutoff>=0) { - - envelope_cutoff=envelope_cutoff*255/64; - final_cutoff=final_cutoff*envelope_cutoff/255; - if (final_cutoff>=0xFF) final_cutoff=0xFE; - + + final_cutoff = it_cutoff; + if (envelope_cutoff >= 0) { + + envelope_cutoff = envelope_cutoff * 255 / 64; + final_cutoff = final_cutoff * envelope_cutoff / 255; + if (final_cutoff >= 0xFF) final_cutoff = 0xFE; } - } -void CPPlayer::Filter_Control::set_filter_parameters(int *p_cutoff,uint8_t *p_reso) { - - +void CPPlayer::Filter_Control::set_filter_parameters(int *p_cutoff, uint8_t *p_reso) { - *p_cutoff=filter_cutoff[final_cutoff]; - *p_reso=it_reso; + *p_cutoff = filter_cutoff[final_cutoff]; + *p_reso = it_reso; } diff --git a/modules/chibi/cp_player_data_nna.cpp b/modules/chibi/cp_player_data_nna.cpp index 3c50bfb01..84da4c4c0 100644 --- a/modules/chibi/cp_player_data_nna.cpp +++ b/modules/chibi/cp_player_data_nna.cpp @@ -35,38 +35,36 @@ void CPPlayer::process_NNAs() { if (!song->has_instruments()) return; - for (i=0;i<CPPattern::WIDTH;i++) { + for (i = 0; i < CPPattern::WIDTH; i++) { Channel_Control *aux_chn_ctrl = &control.channel[i]; - if (aux_chn_ctrl->kick==KICK_NOTE) { + if (aux_chn_ctrl->kick == KICK_NOTE) { - bool k=false; + bool k = false; - if (aux_chn_ctrl->slave_voice!=NULL) { + if (aux_chn_ctrl->slave_voice != NULL) { Voice_Control *aux_voc_ctrl; - aux_voc_ctrl=aux_chn_ctrl->slave_voice; - - if (aux_chn_ctrl->instrument_index==aux_chn_ctrl->slave_voice->instrument_index) { //maybe carry - - aux_chn_ctrl->carry.pan=aux_chn_ctrl->slave_voice->panning_envelope_ctrl; - aux_chn_ctrl->carry.vol=aux_chn_ctrl->slave_voice->volume_envelope_ctrl; - aux_chn_ctrl->carry.pitch=aux_chn_ctrl->slave_voice->pitch_envelope_ctrl; - aux_chn_ctrl->carry.maybe=true; - } else - aux_chn_ctrl->carry.maybe=false; - + aux_voc_ctrl = aux_chn_ctrl->slave_voice; + + if (aux_chn_ctrl->instrument_index == aux_chn_ctrl->slave_voice->instrument_index) { //maybe carry + + aux_chn_ctrl->carry.pan = aux_chn_ctrl->slave_voice->panning_envelope_ctrl; + aux_chn_ctrl->carry.vol = aux_chn_ctrl->slave_voice->volume_envelope_ctrl; + aux_chn_ctrl->carry.pitch = aux_chn_ctrl->slave_voice->pitch_envelope_ctrl; + aux_chn_ctrl->carry.maybe = true; + } else + aux_chn_ctrl->carry.maybe = false; + if (aux_voc_ctrl->NNA_type != CPInstrument::NNA_NOTE_CUT) { /* Make sure the old MP_VOICE channel knows it has no master now ! */ - - - aux_chn_ctrl->slave_voice=NULL; + aux_chn_ctrl->slave_voice = NULL; /* assume the channel is taken by NNA */ - aux_voc_ctrl->has_master_channel=false; + aux_voc_ctrl->has_master_channel = false; switch (aux_voc_ctrl->NNA_type) { case CPInstrument::NNA_NOTE_CONTINUE: { @@ -74,71 +72,69 @@ void CPPlayer::process_NNAs() { } break; case CPInstrument::NNA_NOTE_OFF: { - - aux_voc_ctrl->note_end_flags|=END_NOTE_OFF; + aux_voc_ctrl->note_end_flags |= END_NOTE_OFF; if (!aux_voc_ctrl->volume_envelope_ctrl.active || aux_voc_ctrl->instrument_ptr->get_volume_envelope()->is_loop_enabled()) { - aux_voc_ctrl->note_end_flags|=END_NOTE_FADE; + aux_voc_ctrl->note_end_flags |= END_NOTE_FADE; } } break; case CPInstrument::NNA_NOTE_FADE: { - aux_voc_ctrl->note_end_flags|=END_NOTE_FADE; + aux_voc_ctrl->note_end_flags |= END_NOTE_FADE; } break; } - } + } } - if (aux_chn_ctrl->duplicate_check_type!=CPInstrument::DCT_DISABLED) { + if (aux_chn_ctrl->duplicate_check_type != CPInstrument::DCT_DISABLED) { int i; - for (i=0;i<control.max_voices;i++) { - if (!mixer->is_voice_active(i)|| - (voice[i].master_channel!=aux_chn_ctrl) || - (aux_chn_ctrl->instrument_index!=voice[i].instrument_index)) + for (i = 0; i < control.max_voices; i++) { + if (!mixer->is_voice_active(i) || + (voice[i].master_channel != aux_chn_ctrl) || + (aux_chn_ctrl->instrument_index != voice[i].instrument_index)) continue; Voice_Control *aux_voc_ctrl; - aux_voc_ctrl=&voice[i]; + aux_voc_ctrl = &voice[i]; - k=false; + k = false; switch (aux_chn_ctrl->duplicate_check_type) { case CPInstrument::DCT_NOTE: - if (aux_chn_ctrl->note==aux_voc_ctrl->note) - k=true; + if (aux_chn_ctrl->note == aux_voc_ctrl->note) + k = true; break; case CPInstrument::DCT_SAMPLE: - if (aux_chn_ctrl->sample_ptr==aux_voc_ctrl->sample_ptr) - k=true; + if (aux_chn_ctrl->sample_ptr == aux_voc_ctrl->sample_ptr) + k = true; break; case CPInstrument::DCT_INSTRUMENT: - k=true; + k = true; break; } if (k) { switch (aux_chn_ctrl->duplicate_check_action) { case CPInstrument::DCA_NOTE_CUT: { - aux_voc_ctrl->fadeout_volume=0; + aux_voc_ctrl->fadeout_volume = 0; } break; case CPInstrument::DCA_NOTE_OFF: { - aux_voc_ctrl->note_end_flags|=END_NOTE_OFF; + aux_voc_ctrl->note_end_flags |= END_NOTE_OFF; if (!aux_voc_ctrl->volume_envelope_ctrl.active || aux_chn_ctrl->instrument_ptr->get_volume_envelope()->is_loop_enabled()) { - aux_voc_ctrl->note_end_flags|=END_NOTE_FADE; + aux_voc_ctrl->note_end_flags |= END_NOTE_FADE; } } break; case CPInstrument::DCA_NOTE_FADE: { - aux_voc_ctrl->note_end_flags|=END_NOTE_FADE; + aux_voc_ctrl->note_end_flags |= END_NOTE_FADE; } break; } - } + } } - - } + } } /* if (aux_chn_ctrl->kick==KICK_NOTE) */ } } diff --git a/modules/chibi/cp_player_data_notes.cpp b/modules/chibi/cp_player_data_notes.cpp index 1bfe24bc2..abe2f1b46 100644 --- a/modules/chibi/cp_player_data_notes.cpp +++ b/modules/chibi/cp_player_data_notes.cpp @@ -45,301 +45,274 @@ static inline int32_t cp_random_generate(int32_t *seed) { return (int32_t)(s & RANDOM_MAX); } +void CPPlayer::process_new_note(int p_track, uint8_t p_note) { // if there's really a new note.... -void CPPlayer::process_new_note(int p_track,uint8_t p_note) { // if there's really a new note.... - - if (control.channel[p_track].real_note!=255) { - control.channel[p_track].old_note=control.channel[p_track].real_note; - + if (control.channel[p_track].real_note != 255) { + control.channel[p_track].old_note = control.channel[p_track].real_note; } - control.channel[p_track].real_note=p_note; + control.channel[p_track].real_note = p_note; - control.channel[p_track].kick=KICK_NOTE; + control.channel[p_track].kick = KICK_NOTE; - control.channel[p_track].sample_start_index=-1; - control.channel[p_track].sliding=0; - control.channel[p_track].row_has_note=true; - control.channel[p_track].last_event_usecs=song_usecs; + control.channel[p_track].sample_start_index = -1; + control.channel[p_track].sliding = 0; + control.channel[p_track].row_has_note = true; + control.channel[p_track].last_event_usecs = song_usecs; - if (control.channel[p_track].panbrello_type) control.channel[p_track].panbrello_position=0; + if (control.channel[p_track].panbrello_type) control.channel[p_track].panbrello_position = 0; } -bool CPPlayer::process_new_instrument(int p_track,uint8_t p_instrument) { +bool CPPlayer::process_new_instrument(int p_track, uint8_t p_instrument) { -// bool different_instrument=false; - ERR_FAIL_INDEX_V(p_instrument,CPSong::MAX_INSTRUMENTS,false); - - if ( song->has_instruments() ) { + // bool different_instrument=false; + ERR_FAIL_INDEX_V(p_instrument, CPSong::MAX_INSTRUMENTS, false); + if (song->has_instruments()) { - control.channel[p_track].instrument_ptr=song->get_instrument(p_instrument); + control.channel[p_track].instrument_ptr = song->get_instrument(p_instrument); } else { - control.channel[p_track].instrument_ptr=NULL; + control.channel[p_track].instrument_ptr = NULL; } - control.channel[p_track].retrig_counter=0; - control.channel[p_track].tremor_position=0; - control.channel[p_track].sample_offset_fine=0; - int old_instr_index=control.channel[p_track].instrument_index; - control.channel[p_track].instrument_index=p_instrument; - - return (old_instr_index!=p_instrument); - - -} + control.channel[p_track].retrig_counter = 0; + control.channel[p_track].tremor_position = 0; + control.channel[p_track].sample_offset_fine = 0; + int old_instr_index = control.channel[p_track].instrument_index; + control.channel[p_track].instrument_index = p_instrument; + return (old_instr_index != p_instrument); +} - // returns if it was able to process -bool CPPlayer::process_note_and_instrument(int p_track,int p_note,int p_instrument) { +// returns if it was able to process +bool CPPlayer::process_note_and_instrument(int p_track, int p_note, int p_instrument) { bool aux_result; - aux_result=false; - CPSample *aux_sample=0; // current sample + aux_result = false; + CPSample *aux_sample = 0; // current sample int dest_sample_index; - bool new_instrument=false; + bool new_instrument = false; - control.channel[p_track].row_has_note=false; // wise man says.. "we dont have a note... until we really know we have a note". - control.channel[p_track].new_instrument=false; + control.channel[p_track].row_has_note = false; // wise man says.. "we dont have a note... until we really know we have a note". + control.channel[p_track].new_instrument = false; - if ( (p_note<0) && (p_instrument<0) ) return aux_result; // nothing to do here - if ( (p_note==255) && (p_instrument==255) ) return aux_result; + if ((p_note < 0) && (p_instrument < 0)) return aux_result; // nothing to do here + if ((p_note == 255) && (p_instrument == 255)) return aux_result; - if ( (p_note>=0) && (p_note<120) ) { + if ((p_note >= 0) && (p_note < 120)) { - process_new_note(p_track,p_note); + process_new_note(p_track, p_note); - } else if (p_note==CPNote::CUT) { - - control.channel[p_track].aux_volume=0; - control.channel[p_track].note_end_flags|=END_NOTE_OFF; - control.channel[p_track].note_end_flags|=END_NOTE_KILL; + } else if (p_note == CPNote::CUT) { + + control.channel[p_track].aux_volume = 0; + control.channel[p_track].note_end_flags |= END_NOTE_OFF; + control.channel[p_track].note_end_flags |= END_NOTE_KILL; return aux_result; - } else if ((p_note==CPNote::OFF) && (song->has_instruments())) { + } else if ((p_note == CPNote::OFF) && (song->has_instruments())) { + + if (control.channel[p_track].instrument_ptr != NULL) { - if (control.channel[p_track].instrument_ptr!=NULL) { - - control.channel[p_track].note_end_flags|=END_NOTE_OFF; + control.channel[p_track].note_end_flags |= END_NOTE_OFF; if (!control.channel[p_track].instrument_ptr->get_volume_envelope()->is_enabled() || control.channel[p_track].instrument_ptr->get_volume_envelope()->is_loop_enabled()) { - control.channel[p_track].note_end_flags|=END_NOTE_FADE; + control.channel[p_track].note_end_flags |= END_NOTE_FADE; } - } + } return aux_result; - } else return aux_result; // invalid note! + } else + return aux_result; // invalid note! + if ((p_instrument >= 0) && (p_instrument < CPSong::MAX_INSTRUMENTS)) { + new_instrument = process_new_instrument(p_track, p_instrument); - if ( (p_instrument>=0) && (p_instrument<CPSong::MAX_INSTRUMENTS)) { - new_instrument=process_new_instrument(p_track,p_instrument); - - if ( song->has_instruments() ) { + if (song->has_instruments()) { // If we're in instrument mode... - if ( control.channel[p_track].instrument_ptr->get_sample_number(control.channel[p_track].real_note) >= CPSong::MAX_SAMPLES) { - - control.channel[p_track].kick=KICK_NOTHING; + if (control.channel[p_track].instrument_ptr->get_sample_number(control.channel[p_track].real_note) >= CPSong::MAX_SAMPLES) { + + control.channel[p_track].kick = KICK_NOTHING; return aux_result; - + } else { - dest_sample_index=control.channel[p_track].instrument_ptr->get_sample_number(control.channel[p_track].real_note); - control.channel[p_track].note=control.channel[p_track].instrument_ptr->get_note_number(control.channel[p_track].real_note); + dest_sample_index = control.channel[p_track].instrument_ptr->get_sample_number(control.channel[p_track].real_note); + control.channel[p_track].note = control.channel[p_track].instrument_ptr->get_note_number(control.channel[p_track].real_note); } - + } else { // If we're in sample mode... - dest_sample_index=control.channel[p_track].instrument_index; - control.channel[p_track].note=control.channel[p_track].real_note; + dest_sample_index = control.channel[p_track].instrument_index; + control.channel[p_track].note = control.channel[p_track].real_note; } - - control.channel[p_track].sample_index=dest_sample_index; - aux_sample=song->get_sample(dest_sample_index); - - if (!CPSampleManager::get_singleton()->check( aux_sample->get_sample_data() )) { + + control.channel[p_track].sample_index = dest_sample_index; + aux_sample = song->get_sample(dest_sample_index); + + if (!CPSampleManager::get_singleton()->check(aux_sample->get_sample_data())) { /* INVALID SAMPLE */ - control.channel[p_track].kick=KICK_NOTHING; + control.channel[p_track].kick = KICK_NOTHING; return aux_result; - } - - aux_sample=song->get_sample(dest_sample_index); + + aux_sample = song->get_sample(dest_sample_index); } else { - - + if (!control.channel[p_track].sample_ptr) return aux_result; - + if (song->has_instruments()) { - + if (!control.channel[p_track].instrument_ptr) return aux_result; - - control.channel[p_track].note=control.channel[p_track].instrument_ptr->get_note_number(control.channel[p_track].real_note); - + + control.channel[p_track].note = control.channel[p_track].instrument_ptr->get_note_number(control.channel[p_track].real_note); + } else { - - control.channel[p_track].note=control.channel[p_track].real_note; - + + control.channel[p_track].note = control.channel[p_track].real_note; } - - aux_sample=control.channel[p_track].sample_ptr; - + + aux_sample = control.channel[p_track].sample_ptr; } - - - if (p_instrument>=CPSong::MAX_INSTRUMENTS && control.channel[p_track].sample_ptr!=aux_sample) { + if (p_instrument >= CPSong::MAX_INSTRUMENTS && control.channel[p_track].sample_ptr != aux_sample) { - control.channel[p_track].new_instrument=(control.channel[p_track].period>0); + control.channel[p_track].new_instrument = (control.channel[p_track].period > 0); } - control.channel[p_track].sample_ptr=aux_sample; + control.channel[p_track].sample_ptr = aux_sample; /* channel or instrument determined panning ? */ - control.channel[p_track].panning=control.channel[p_track].channel_panning; + control.channel[p_track].panning = control.channel[p_track].channel_panning; - /* set filter,if any ? */ - + /* set filter,if any ? */ if (aux_sample->is_pan_enabled()) { - - control.channel[p_track].panning=(int)aux_sample->get_pan()*255/64; - } else if ( song->has_instruments() && (control.channel[p_track].instrument_ptr->is_pan_default_enabled()) ) { + control.channel[p_track].panning = (int)aux_sample->get_pan() * 255 / 64; - control.channel[p_track].panning=(int)control.channel[p_track].instrument_ptr->get_pan_default_amount()*255/64; - } + } else if (song->has_instruments() && (control.channel[p_track].instrument_ptr->is_pan_default_enabled())) { + control.channel[p_track].panning = (int)control.channel[p_track].instrument_ptr->get_pan_default_amount() * 255 / 64; + } if (song->has_instruments()) { - - /* Pitch-Pan Separation */ - if ((control.channel[p_track].instrument_ptr->get_pan_pitch_separation()!=0) && (control.channel[p_track].channel_panning!=PAN_SURROUND)){ + /* Pitch-Pan Separation */ + if ((control.channel[p_track].instrument_ptr->get_pan_pitch_separation() != 0) && (control.channel[p_track].channel_panning != PAN_SURROUND)) { - control.channel[p_track].panning+=((control.channel[p_track].real_note-control.channel[p_track].instrument_ptr->get_pan_pitch_center())*control.channel[p_track].instrument_ptr->get_pan_pitch_separation())/8; + control.channel[p_track].panning += ((control.channel[p_track].real_note - control.channel[p_track].instrument_ptr->get_pan_pitch_center()) * control.channel[p_track].instrument_ptr->get_pan_pitch_separation()) / 8; - if (control.channel[p_track].panning<PAN_LEFT) control.channel[p_track].panning=PAN_LEFT; - if (control.channel[p_track].panning>PAN_RIGHT) control.channel[p_track].panning=PAN_RIGHT; + if (control.channel[p_track].panning < PAN_LEFT) control.channel[p_track].panning = PAN_LEFT; + if (control.channel[p_track].panning > PAN_RIGHT) control.channel[p_track].panning = PAN_RIGHT; } /* Random Volume Variation */ - if (control.channel[p_track].instrument_ptr->get_volume_random_variation()>0) { + if (control.channel[p_track].instrument_ptr->get_volume_random_variation() > 0) { - control.channel[p_track].random_volume_variation=100-(cp_random_generate(&control.random_seed) % control.channel[p_track].instrument_ptr->get_volume_random_variation()); + control.channel[p_track].random_volume_variation = 100 - (cp_random_generate(&control.random_seed) % control.channel[p_track].instrument_ptr->get_volume_random_variation()); } else { - control.channel[p_track].random_volume_variation=100; + control.channel[p_track].random_volume_variation = 100; } - /* Random Pan Variation */ - if ((control.channel[p_track].instrument_ptr->get_pan_random_variation()>0) && (control.channel[p_track].panning!=PAN_SURROUND)){ + if ((control.channel[p_track].instrument_ptr->get_pan_random_variation() > 0) && (control.channel[p_track].panning != PAN_SURROUND)) { int aux_pan_modifier; - aux_pan_modifier=(cp_random_generate(&control.random_seed) % (control.channel[p_track].instrument_ptr->get_pan_random_variation() << 2)); - if ((cp_random_generate(&control.random_seed) % 2)==1) aux_pan_modifier=0-aux_pan_modifier; /* it's 5am, let me sleep :) */ + aux_pan_modifier = (cp_random_generate(&control.random_seed) % (control.channel[p_track].instrument_ptr->get_pan_random_variation() << 2)); + if ((cp_random_generate(&control.random_seed) % 2) == 1) aux_pan_modifier = 0 - aux_pan_modifier; /* it's 5am, let me sleep :) */ - control.channel[p_track].panning+=aux_pan_modifier; - - if (control.channel[p_track].panning<PAN_LEFT) control.channel[p_track].panning=PAN_LEFT; - if (control.channel[p_track].panning>PAN_RIGHT) control.channel[p_track].panning=PAN_RIGHT; - + control.channel[p_track].panning += aux_pan_modifier; + if (control.channel[p_track].panning < PAN_LEFT) control.channel[p_track].panning = PAN_LEFT; + if (control.channel[p_track].panning > PAN_RIGHT) control.channel[p_track].panning = PAN_RIGHT; } /*filter*/ - + if (control.channel[p_track].instrument_ptr->filter_use_default_cutoff()) { - - control.channel[p_track].filter.it_cutoff=control.channel[p_track].instrument_ptr->get_filter_default_cutoff()*2; - + + control.channel[p_track].filter.it_cutoff = control.channel[p_track].instrument_ptr->get_filter_default_cutoff() * 2; } - + if (control.channel[p_track].instrument_ptr->filter_use_default_resonance()) { - - control.channel[p_track].filter.it_reso=control.channel[p_track].instrument_ptr->get_filter_default_resonance()*2; - + + control.channel[p_track].filter.it_reso = control.channel[p_track].instrument_ptr->get_filter_default_resonance() * 2; } - + /*envelopes*/ - - - control.channel[p_track].volume_envelope_on=control.channel[p_track].instrument_ptr->get_volume_envelope()->is_enabled(); - control.channel[p_track].panning_envelope_on=control.channel[p_track].instrument_ptr->get_pan_envelope()->is_enabled(); - control.channel[p_track].pitch_envelope_on=control.channel[p_track].instrument_ptr->get_pitch_filter_envelope()->is_enabled(); - control.channel[p_track].NNA_type=control.channel[p_track].instrument_ptr->get_NNA_type(); - control.channel[p_track].duplicate_check_type=control.channel[p_track].instrument_ptr->get_DC_type(); - control.channel[p_track].duplicate_check_action=control.channel[p_track].instrument_ptr->get_DC_action(); + control.channel[p_track].volume_envelope_on = control.channel[p_track].instrument_ptr->get_volume_envelope()->is_enabled(); + control.channel[p_track].panning_envelope_on = control.channel[p_track].instrument_ptr->get_pan_envelope()->is_enabled(); + control.channel[p_track].pitch_envelope_on = control.channel[p_track].instrument_ptr->get_pitch_filter_envelope()->is_enabled(); + control.channel[p_track].NNA_type = control.channel[p_track].instrument_ptr->get_NNA_type(); + control.channel[p_track].duplicate_check_type = control.channel[p_track].instrument_ptr->get_DC_type(); + control.channel[p_track].duplicate_check_action = control.channel[p_track].instrument_ptr->get_DC_action(); } else { - control.channel[p_track].NNA_type=CPInstrument::NNA_NOTE_CUT; - control.channel[p_track].duplicate_check_type=CPInstrument::DCT_DISABLED; - control.channel[p_track].duplicate_check_action=CPInstrument::DCA_NOTE_CUT; + control.channel[p_track].NNA_type = CPInstrument::NNA_NOTE_CUT; + control.channel[p_track].duplicate_check_type = CPInstrument::DCT_DISABLED; + control.channel[p_track].duplicate_check_action = CPInstrument::DCA_NOTE_CUT; } + if (p_instrument < CPSong::MAX_INSTRUMENTS) { // instrument change - if (p_instrument<CPSong::MAX_INSTRUMENTS) { // instrument change - - control.channel[p_track].volume=control.channel[p_track].aux_volume=aux_sample->get_default_volume(); - + control.channel[p_track].volume = control.channel[p_track].aux_volume = aux_sample->get_default_volume(); } + control.channel[p_track].slide_to_period = control.channel[p_track].aux_period = get_period((uint16_t)(control.channel[p_track].note) << 1, CPSampleManager::get_singleton()->get_c5_freq((aux_sample->get_sample_data()))); - control.channel[p_track].slide_to_period=control.channel[p_track].aux_period=get_period((uint16_t)(control.channel[p_track].note)<<1,CPSampleManager::get_singleton()->get_c5_freq( (aux_sample->get_sample_data()))); - - control.channel[p_track].note_end_flags=END_NOTE_NOTHING; /* clears flags */ + control.channel[p_track].note_end_flags = END_NOTE_NOTHING; /* clears flags */ return true; } -void CPPlayer::process_volume_column(int p_track,uint8_t p_volume) { +void CPPlayer::process_volume_column(int p_track, uint8_t p_volume) { - control.channel[p_track].current_volume_command=CPNote::EMPTY; - control.channel[p_track].current_volume_parameter=CPNote::EMPTY; + control.channel[p_track].current_volume_command = CPNote::EMPTY; + control.channel[p_track].current_volume_parameter = CPNote::EMPTY; - if (p_volume<65) { // VOLUME + if (p_volume < 65) { // VOLUME - control.channel[p_track].aux_volume=p_volume; - } else if (p_volume<125) { // Volume Command + control.channel[p_track].aux_volume = p_volume; + } else if (p_volume < 125) { // Volume Command - - control.channel[p_track].current_volume_command=(p_volume-65) / 10; - control.channel[p_track].current_volume_parameter=(p_volume-65) % 10; - } else if (p_volume<193) { // PAN + control.channel[p_track].current_volume_command = (p_volume - 65) / 10; + control.channel[p_track].current_volume_parameter = (p_volume - 65) % 10; + } else if (p_volume < 193) { // PAN - control.channel[p_track].channel_panning=(p_volume-128)*PAN_RIGHT/64; - control.channel[p_track].panning=control.channel[p_track].channel_panning; + control.channel[p_track].channel_panning = (p_volume - 128) * PAN_RIGHT / 64; + control.channel[p_track].panning = control.channel[p_track].channel_panning; - } else if (p_volume<213) { //More volume Commands + } else if (p_volume < 213) { //More volume Commands - control.channel[p_track].current_volume_command=((p_volume-193) / 10)+6; - control.channel[p_track].current_volume_parameter=(p_volume-193) % 10; + control.channel[p_track].current_volume_command = ((p_volume - 193) / 10) + 6; + control.channel[p_track].current_volume_parameter = (p_volume - 193) % 10; } } +void CPPlayer::process_note(int p_track, CPNote p_note) { + + if (p_note.note != CPNote::SCRIPT) { -void CPPlayer::process_note(int p_track,CPNote p_note) { + process_note_and_instrument(p_track, p_note.note, p_note.instrument); + process_volume_column(p_track, p_note.volume); + control.channel[p_track].current_command = p_note.command; + control.channel[p_track].current_parameter = p_note.parameter; - if ( p_note.note!=CPNote::SCRIPT ) { - - process_note_and_instrument(p_track,p_note.note,p_note.instrument); - process_volume_column(p_track,p_note.volume); - control.channel[p_track].current_command=p_note.command; - control.channel[p_track].current_parameter=p_note.parameter; - } else { - - CPNote n = song->get_pattern( control.position.current_pattern )->get_transformed_script_note( p_track, control.position.current_row ); - process_note( p_track, n ); - - song->get_pattern( control.position.current_pattern )->scripted_clone( p_track, control.position.current_row ); + + CPNote n = song->get_pattern(control.position.current_pattern)->get_transformed_script_note(p_track, control.position.current_row); + process_note(p_track, n); + + song->get_pattern(control.position.current_pattern)->scripted_clone(p_track, control.position.current_row); } } diff --git a/modules/chibi/cp_player_data_utils.cpp b/modules/chibi/cp_player_data_utils.cpp index 1ee3f30b3..7a96aba33 100644 --- a/modules/chibi/cp_player_data_utils.cpp +++ b/modules/chibi/cp_player_data_utils.cpp @@ -28,60 +28,52 @@ /*************************************************************************/ #include "cp_player_data.h" -uint8_t CPPlayer::vibrato_table[32]={ - 0, 24, 49, 74, 97,120,141,161,180,197,212,224,235,244,250,253, - 255,253,250,244,235,224,212,197,180,161,141,120, 97, 74, 49, 24 +uint8_t CPPlayer::vibrato_table[32] = { + 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, + 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 }; -uint8_t CPPlayer::auto_vibrato_table[128]={ - 0, 1, 3, 4, 6, 7, 9,10,12,14,15,17,18,20,21,23, - 24,25,27,28,30,31,32,34,35,36,38,39,40,41,42,44, - 45,46,47,48,49,50,51,52,53,54,54,55,56,57,57,58, - 59,59,60,60,61,61,62,62,62,63,63,63,63,63,63,63, - 64,63,63,63,63,63,63,63,62,62,62,61,61,60,60,59, - 59,58,57,57,56,55,54,54,53,52,51,50,49,48,47,46, - 45,44,42,41,40,39,38,36,35,34,32,31,30,28,27,25, - 24,23,21,20,18,17,15,14,12,10, 9, 7, 6, 4, 3, 1 +uint8_t CPPlayer::auto_vibrato_table[128] = { + 0, 1, 3, 4, 6, 7, 9, 10, 12, 14, 15, 17, 18, 20, 21, 23, + 24, 25, 27, 28, 30, 31, 32, 34, 35, 36, 38, 39, 40, 41, 42, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57, 57, 58, + 59, 59, 60, 60, 61, 61, 62, 62, 62, 63, 63, 63, 63, 63, 63, 63, + 64, 63, 63, 63, 63, 63, 63, 63, 62, 62, 62, 61, 61, 60, 60, 59, + 59, 58, 57, 57, 56, 55, 54, 54, 53, 52, 51, 50, 49, 48, 47, 46, + 45, 44, 42, 41, 40, 39, 38, 36, 35, 34, 32, 31, 30, 28, 27, 25, + 24, 23, 21, 20, 18, 17, 15, 14, 12, 10, 9, 7, 6, 4, 3, 1 }; - -int8_t CPPlayer::panbrello_table[256]={ - 0, 2, 3, 5, 6, 8, 9, 11, 12, 14, 16, 17, 19, 20, 22, 23, - 24, 26, 27, 29, 30, 32, 33, 34, 36, 37, 38, 39, 41, 42, 43, 44, - 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 58, 59, - 59, 60, 60, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 63, 63, 63, 62, 62, 62, 61, 61, 60, 60, - 59, 59, 58, 57, 56, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, - 45, 44, 43, 42, 41, 39, 38, 37, 36, 34, 33, 32, 30, 29, 27, 26, - 24, 23, 22, 20, 19, 17, 16, 14, 12, 11, 9, 8, 6, 5, 3, 2, - 0,- 2,- 3,- 5,- 6,- 8,- 9,-11,-12,-14,-16,-17,-19,-20,-22,-23, - -24,-26,-27,-29,-30,-32,-33,-34,-36,-37,-38,-39,-41,-42,-43,-44, - -45,-46,-47,-48,-49,-50,-51,-52,-53,-54,-55,-56,-56,-57,-58,-59, - -59,-60,-60,-61,-61,-62,-62,-62,-63,-63,-63,-64,-64,-64,-64,-64, - -64,-64,-64,-64,-64,-64,-63,-63,-63,-62,-62,-62,-61,-61,-60,-60, - -59,-59,-58,-57,-56,-56,-55,-54,-53,-52,-51,-50,-49,-48,-47,-46, - -45,-44,-43,-42,-41,-39,-38,-37,-36,-34,-33,-32,-30,-29,-27,-26, - -24,-23,-22,-20,-19,-17,-16,-14,-12,-11,- 9,- 8,- 6,- 5,- 3,- 2 +int8_t CPPlayer::panbrello_table[256] = { + 0, 2, 3, 5, 6, 8, 9, 11, 12, 14, 16, 17, 19, 20, 22, 23, + 24, 26, 27, 29, 30, 32, 33, 34, 36, 37, 38, 39, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 58, 59, + 59, 60, 60, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 63, 63, 63, 62, 62, 62, 61, 61, 60, 60, + 59, 59, 58, 57, 56, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, + 45, 44, 43, 42, 41, 39, 38, 37, 36, 34, 33, 32, 30, 29, 27, 26, + 24, 23, 22, 20, 19, 17, 16, 14, 12, 11, 9, 8, 6, 5, 3, 2, + 0, -2, -3, -5, -6, -8, -9, -11, -12, -14, -16, -17, -19, -20, -22, -23, + -24, -26, -27, -29, -30, -32, -33, -34, -36, -37, -38, -39, -41, -42, -43, -44, + -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -56, -57, -58, -59, + -59, -60, -60, -61, -61, -62, -62, -62, -63, -63, -63, -64, -64, -64, -64, -64, + -64, -64, -64, -64, -64, -64, -63, -63, -63, -62, -62, -62, -61, -61, -60, -60, + -59, -59, -58, -57, -56, -56, -55, -54, -53, -52, -51, -50, -49, -48, -47, -46, + -45, -44, -43, -42, -41, -39, -38, -37, -36, -34, -33, -32, -30, -29, -27, -26, + -24, -23, -22, -20, -19, -17, -16, -14, -12, -11, -9, -8, -6, -5, -3, -2 }; - - - - - -int32_t CPPlayer::get_period(uint16_t p_note,int32_t p_c5speed) { +int32_t CPPlayer::get_period(uint16_t p_note, int32_t p_c5speed) { if (song->has_linear_slides()) { - return CPTables::get_linear_period(p_note,0); + return CPTables::get_linear_period(p_note, 0); } else { - - - return CPTables::get_log_period(p_note>>1,p_c5speed >>1); + + return CPTables::get_log_period(p_note >> 1, p_c5speed >> 1); } } - int32_t CPPlayer::get_frequency(int32_t period) { if (song->has_linear_slides()) { @@ -96,43 +88,40 @@ int32_t CPPlayer::get_frequency(int32_t period) { int CPPlayer::find_empty_voice() { int i; - int min_priority,min_priority_chan=0,priority; + int min_priority, min_priority_chan = 0, priority; - for (i=0;i<control.max_voices;i++) { - - if ( ((voice[i].kick==KICK_NOTHING)||(voice[i].kick==KICK_ENVELOPE))&&!mixer->is_voice_active(i) ) { - - return i; + for (i = 0; i < control.max_voices; i++) { + + if (((voice[i].kick == KICK_NOTHING) || (voice[i].kick == KICK_ENVELOPE)) && !mixer->is_voice_active(i)) { + return i; } } // todo more - for (i=0;i<control.max_voices;i++) { + for (i = 0; i < control.max_voices; i++) { /* allow us to take over a nonexisting sample */ -// if ((voice[i].s==NULL) -// return k; - - if ((voice[i].kick==KICK_NOTHING)||(voice[i].kick==KICK_ENVELOPE)) { + // if ((voice[i].s==NULL) + // return k; - priority=voice[i].total_volume<<((CPSampleManager::get_singleton()->get_loop_type( voice[i].sample_ptr->get_sample_data())!=CP_LOOP_NONE)?1:0); + if ((voice[i].kick == KICK_NOTHING) || (voice[i].kick == KICK_ENVELOPE)) { - if ((voice[i].has_master_channel)&&(&voice[i]==voice[i].master_channel->slave_voice)) { + priority = voice[i].total_volume << ((CPSampleManager::get_singleton()->get_loop_type(voice[i].sample_ptr->get_sample_data()) != CP_LOOP_NONE) ? 1 : 0); - priority<<=2; + if ((voice[i].has_master_channel) && (&voice[i] == voice[i].master_channel->slave_voice)) { + priority <<= 2; } - if ((i==0) || (priority<min_priority)) { - min_priority=priority; - min_priority_chan=i; + if ((i == 0) || (priority < min_priority)) { + min_priority = priority; + min_priority_chan = i; } } } - if (min_priority>8000*7) return -1; /* what the fuck is this? */ + if (min_priority > 8000 * 7) return -1; /* what the fuck is this? */ return min_priority_chan; } - diff --git a/modules/chibi/cp_sample.cpp b/modules/chibi/cp_sample.cpp index bea883554..925881e62 100644 --- a/modules/chibi/cp_sample.cpp +++ b/modules/chibi/cp_sample.cpp @@ -28,81 +28,76 @@ /*************************************************************************/ #include "cp_sample.h" -const char * CPSample::get_name() const { +const char *CPSample::get_name() const { return name; } void CPSample::set_name(const char *p_name) { - if (p_name==NULL) { - name[0]=0; + if (p_name == NULL) { + name[0] = 0; return; } - - - bool done=false; - for (int i=0;i<NAME_MAX_LEN;i++) { - - - name[i]=done?0:p_name[i]; - if (!done && p_name[i]==0) - done=true; + + bool done = false; + for (int i = 0; i < NAME_MAX_LEN; i++) { + + name[i] = done ? 0 : p_name[i]; + if (!done && p_name[i] == 0) + done = true; } - - name[NAME_MAX_LEN-1]=0; /* just in case */ - + + name[NAME_MAX_LEN - 1] = 0; /* just in case */ } void CPSample::set_default_volume(uint8_t p_vol) { - default_volume=p_vol; + default_volume = p_vol; } -uint8_t CPSample::get_default_volume() const{ +uint8_t CPSample::get_default_volume() const { return default_volume; } void CPSample::set_global_volume(uint8_t p_vol) { - global_volume=p_vol; + global_volume = p_vol; } -uint8_t CPSample::get_global_volume() const{ +uint8_t CPSample::get_global_volume() const { return global_volume; } void CPSample::set_pan_enabled(bool p_vol) { - pan_enabled=p_vol; + pan_enabled = p_vol; } -bool CPSample::is_pan_enabled() const{ +bool CPSample::is_pan_enabled() const { return pan_enabled; } void CPSample::set_pan(uint8_t p_pan) { - pan=p_pan; - + pan = p_pan; } -uint8_t CPSample::get_pan() const{ +uint8_t CPSample::get_pan() const { return pan; } - void CPSample::set_vibrato_type(VibratoType p_vibrato_type) { - vibrato_type=p_vibrato_type; + vibrato_type = p_vibrato_type; } -CPSample::VibratoType CPSample::get_vibrato_type() const{ +CPSample::VibratoType CPSample::get_vibrato_type() const { return vibrato_type; } void CPSample::set_vibrato_speed(uint8_t p_vibrato_speed) { - vibrato_speed=p_vibrato_speed; + vibrato_speed = p_vibrato_speed; } uint8_t CPSample::get_vibrato_speed() const { @@ -111,84 +106,78 @@ uint8_t CPSample::get_vibrato_speed() const { void CPSample::set_vibrato_depth(uint8_t p_vibrato_depth) { - vibrato_depth=p_vibrato_depth; + vibrato_depth = p_vibrato_depth; } -uint8_t CPSample::get_vibrato_depth() const{ +uint8_t CPSample::get_vibrato_depth() const { return vibrato_depth; } void CPSample::set_vibrato_rate(uint8_t p_vibrato_rate) { - vibrato_rate=p_vibrato_rate; + vibrato_rate = p_vibrato_rate; } -uint8_t CPSample::get_vibrato_rate() const{ +uint8_t CPSample::get_vibrato_rate() const { return vibrato_rate; } void CPSample::set_sample_data(CPSample_ID p_ID) { - - id=p_ID; + + id = p_ID; } -CPSample_ID CPSample::get_sample_data() const{ - +CPSample_ID CPSample::get_sample_data() const { + return id; } void CPSample::operator=(const CPSample &p_sample) { - + copy_from(p_sample); } void CPSample::copy_from(const CPSample &p_sample) { - + reset(); set_name(p_sample.get_name()); - - default_volume=p_sample.default_volume; - global_volume=p_sample.global_volume; - - pan_enabled=p_sample.pan_enabled; - pan=p_sample.pan; - vibrato_type=p_sample.vibrato_type; - vibrato_speed=p_sample.vibrato_speed; - vibrato_depth=p_sample.vibrato_depth; - vibrato_rate=p_sample.vibrato_rate; - - if (CPSampleManager::get_singleton() && !p_sample.id.is_null()) - CPSampleManager::get_singleton()->copy_to( p_sample.id, id ); -} + default_volume = p_sample.default_volume; + global_volume = p_sample.global_volume; + pan_enabled = p_sample.pan_enabled; + pan = p_sample.pan; - + vibrato_type = p_sample.vibrato_type; + vibrato_speed = p_sample.vibrato_speed; + vibrato_depth = p_sample.vibrato_depth; + vibrato_rate = p_sample.vibrato_rate; + if (CPSampleManager::get_singleton() && !p_sample.id.is_null()) + CPSampleManager::get_singleton()->copy_to(p_sample.id, id); +} void CPSample::reset() { - - name[0]=0; + name[0] = 0; - default_volume=64; - global_volume=64; + default_volume = 64; + global_volume = 64; - pan_enabled=false; - pan=32; + pan_enabled = false; + pan = 32; - vibrato_type=VIBRATO_SINE; - vibrato_speed=0; - vibrato_depth=0; - vibrato_rate=0; + vibrato_type = VIBRATO_SINE; + vibrato_speed = 0; + vibrato_depth = 0; + vibrato_rate = 0; if (!id.is_null() && CPSampleManager::get_singleton()) - CPSampleManager::get_singleton()->destroy( id ); - - id=CPSample_ID(); - + CPSampleManager::get_singleton()->destroy(id); + + id = CPSample_ID(); } -CPSample::CPSample(const CPSample&p_from) { - +CPSample::CPSample(const CPSample &p_from) { + reset(); copy_from(p_from); } diff --git a/modules/chibi/cp_sample.h b/modules/chibi/cp_sample.h index c02b220c8..65c6abee9 100644 --- a/modules/chibi/cp_sample.h +++ b/modules/chibi/cp_sample.h @@ -29,7 +29,6 @@ #ifndef CPSAMPLE_H #define CPSAMPLE_H - #include "cp_config.h" #include "cp_sample_manager.h" class CPSample { @@ -44,16 +43,15 @@ public: }; private: - - enum { NAME_MAX_LEN=26 }; - + enum { NAME_MAX_LEN = 26 }; + char name[NAME_MAX_LEN]; uint8_t default_volume; /* 0.. 64 */ uint8_t global_volume; /* 0.. 64 */ bool pan_enabled; - uint8_t pan; /* 0.. 64 */ + uint8_t pan; /* 0.. 64 */ VibratoType vibrato_type; uint8_t vibrato_speed; /* 0.. 64 */ @@ -61,32 +59,31 @@ private: uint8_t vibrato_rate; /* 0.. 64 */ CPSample_ID id; - + void copy_from(const CPSample &p_sample); -public: - +public: void operator=(const CPSample &p_sample); - - const char * get_name() const; + + const char *get_name() const; void set_name(const char *p_name); void set_default_volume(uint8_t p_vol); uint8_t get_default_volume() const; - + void set_global_volume(uint8_t p_vol); uint8_t get_global_volume() const; - + void set_pan_enabled(bool p_vol); bool is_pan_enabled() const; - + void set_pan(uint8_t p_pan); uint8_t get_pan() const; void set_vibrato_type(VibratoType p_vibrato_type); VibratoType get_vibrato_type() const; - void set_vibrato_speed(uint8_t p_vibrato_speed) ; + void set_vibrato_speed(uint8_t p_vibrato_speed); uint8_t get_vibrato_speed() const; void set_vibrato_depth(uint8_t p_vibrato_depth); @@ -97,16 +94,12 @@ public: void set_sample_data(CPSample_ID); CPSample_ID get_sample_data() const; - + void reset(); - - CPSample(const CPSample&p_from); + + CPSample(const CPSample &p_from); CPSample(); ~CPSample(); - }; - - - #endif diff --git a/modules/chibi/cp_sample_defs.h b/modules/chibi/cp_sample_defs.h index 5ae57aed8..9797ddb39 100644 --- a/modules/chibi/cp_sample_defs.h +++ b/modules/chibi/cp_sample_defs.h @@ -32,7 +32,7 @@ #include "cp_config.h" enum CPSample_Loop_Type { - + CP_LOOP_NONE, CP_LOOP_FORWARD, CP_LOOP_BIDI @@ -46,41 +46,39 @@ enum CPSample_Loop_Type { #define CP_MIXING_FRAC_BITS_MASK_TEXT "8191" enum CPMixConstants { - CP_MIXING_FRAC_BITS=CP_MIXING_FRAC_BITS_MACRO, - CP_MIXING_FRAC_LENGTH=(1<<CP_MIXING_FRAC_BITS), - CP_MIXING_FRAC_MASK=CP_MIXING_FRAC_LENGTH-1, - CP_MIXING_VOL_FRAC_BITS=8, - CP_MIXING_FREQ_FRAC_BITS=8 + CP_MIXING_FRAC_BITS = CP_MIXING_FRAC_BITS_MACRO, + CP_MIXING_FRAC_LENGTH = (1 << CP_MIXING_FRAC_BITS), + CP_MIXING_FRAC_MASK = CP_MIXING_FRAC_LENGTH - 1, + CP_MIXING_VOL_FRAC_BITS = 8, + CP_MIXING_FREQ_FRAC_BITS = 8 }; enum CPFilterConstants { - CP_FILTER_SHIFT=16, - CP_FILTER_LENGTH=(1<<CP_FILTER_SHIFT) + CP_FILTER_SHIFT = 16, + CP_FILTER_LENGTH = (1 << CP_FILTER_SHIFT) }; - enum CPInterpolationType { CP_INTERPOLATION_RAW, CP_INTERPOLATION_LINEAR, CP_INTERPOLATION_CUBIC }; - + enum CPPanConstants { - - CP_PAN_BITS=8, // 0 .. 256 - CP_PAN_LEFT=0, - CP_PAN_RIGHT=((1<<CP_PAN_BITS)-1), // 255 - CP_PAN_CENTER=CP_PAN_RIGHT/2, // 128 - CP_PAN_SURROUND=512 + + CP_PAN_BITS = 8, // 0 .. 256 + CP_PAN_LEFT = 0, + CP_PAN_RIGHT = ((1 << CP_PAN_BITS) - 1), // 255 + CP_PAN_CENTER = CP_PAN_RIGHT / 2, // 128 + CP_PAN_SURROUND = 512 }; enum CPMixerVolConstants { - CP_VOL_MAX=512, - CP_VOL_RAMP_BITS=9, - CP_VOL_SHIFT=2 - - -}; + CP_VOL_MAX = 512, + CP_VOL_RAMP_BITS = 9, + CP_VOL_SHIFT = 2 + +}; enum CPStereoCannels { CP_CHAN_LEFT, @@ -93,5 +91,4 @@ enum CPStereoCannels { typedef signed char CPFrame8; typedef signed short CPFrame16; - #endif diff --git a/modules/chibi/cp_sample_manager.cpp b/modules/chibi/cp_sample_manager.cpp index 2ad0a720b..001c10a83 100644 --- a/modules/chibi/cp_sample_manager.cpp +++ b/modules/chibi/cp_sample_manager.cpp @@ -28,48 +28,41 @@ /*************************************************************************/ #include "cp_sample_manager.h" +CPSampleManager *CPSampleManager::singleton = NULL; -CPSampleManager * CPSampleManager::singleton=NULL; +void CPSampleManager::copy_to(CPSample_ID p_from, CPSample_ID &p_to) { + ERR_FAIL_COND(!check(p_from)); -void CPSampleManager::copy_to(CPSample_ID p_from,CPSample_ID &p_to) { - - ERR_FAIL_COND(!check( p_from )); - - if (p_to.is_null()) { - - p_to=create( is_16bits( p_from), is_stereo( p_from), get_size(p_from)); + + p_to = create(is_16bits(p_from), is_stereo(p_from), get_size(p_from)); } else { - - recreate( p_to, is_16bits( p_from), is_stereo( p_from), get_size(p_from)); - + + recreate(p_to, is_16bits(p_from), is_stereo(p_from), get_size(p_from)); } - - int len=get_size( p_from ); - int ch=is_stereo( p_from ) ? 2 : 1; - - for (int c=0;c<ch;c++) { - - for (int i=0;i<len;i++) { - - int16_t s=get_data( p_from, i, c ); - set_data( p_to, i, s, c ); + + int len = get_size(p_from); + int ch = is_stereo(p_from) ? 2 : 1; + + for (int c = 0; c < ch; c++) { + + for (int i = 0; i < len; i++) { + + int16_t s = get_data(p_from, i, c); + set_data(p_to, i, s, c); } } - - set_loop_type( p_to, get_loop_type( p_from ) ); - set_loop_begin( p_to, get_loop_begin( p_from ) ); - set_loop_end( p_to, get_loop_end( p_from ) ); - set_c5_freq( p_to, get_c5_freq( p_from ) ); - - - + + set_loop_type(p_to, get_loop_type(p_from)); + set_loop_begin(p_to, get_loop_begin(p_from)); + set_loop_end(p_to, get_loop_end(p_from)); + set_c5_freq(p_to, get_c5_freq(p_from)); } CPSampleManager::CPSampleManager() { - singleton=this; + singleton = this; } CPSampleManager *CPSampleManager::get_singleton() { diff --git a/modules/chibi/cp_sample_manager.h b/modules/chibi/cp_sample_manager.h index b6d47a301..c42b7ef4a 100644 --- a/modules/chibi/cp_sample_manager.h +++ b/modules/chibi/cp_sample_manager.h @@ -32,68 +32,61 @@ #include "cp_config.h" #include "cp_sample_defs.h" - - /** @author Juan Linietsky */ - /* abstract base CPSample_ID class */ struct CPSample_ID { void *_private; - - bool operator==(const CPSample_ID&p_other) const { return _private==p_other._private; } - bool operator!=(const CPSample_ID&p_other) const { return _private!=p_other._private; } - bool is_null() const { return _private==0; } - CPSample_ID(void *p_private=0) { _private=p_private; }; -}; + bool operator==(const CPSample_ID &p_other) const { return _private == p_other._private; } + bool operator!=(const CPSample_ID &p_other) const { return _private != p_other._private; } + bool is_null() const { return _private == 0; } + CPSample_ID(void *p_private = 0) { _private = p_private; }; +}; class CPSampleManager { - - static CPSampleManager * singleton; -public: + static CPSampleManager *singleton; +public: /* get the singleton instance */ static CPSampleManager *get_singleton(); - virtual void copy_to(CPSample_ID p_from,CPSample_ID &p_to); ///< if p_to is null, it gets created - - virtual CPSample_ID create(bool p_16bits,bool p_stereo,int32_t p_len)=0; - virtual void recreate(CPSample_ID p_id,bool p_16bits,bool p_stereo,int32_t p_len)=0; - virtual void destroy(CPSample_ID p_id)=0; - virtual bool check(CPSample_ID p_id)=0; // return false if invalid + virtual void copy_to(CPSample_ID p_from, CPSample_ID &p_to); ///< if p_to is null, it gets created - virtual void set_c5_freq(CPSample_ID p_id,int32_t p_freq)=0; - virtual void set_loop_begin(CPSample_ID p_id,int32_t p_begin)=0; - virtual void set_loop_end(CPSample_ID p_id,int32_t p_end)=0; - virtual void set_loop_type(CPSample_ID p_id,CPSample_Loop_Type p_type)=0; - virtual void set_chunk(CPSample_ID p_id,int32_t p_index,void *p_data,int p_data_len)=0; + virtual CPSample_ID create(bool p_16bits, bool p_stereo, int32_t p_len) = 0; + virtual void recreate(CPSample_ID p_id, bool p_16bits, bool p_stereo, int32_t p_len) = 0; + virtual void destroy(CPSample_ID p_id) = 0; + virtual bool check(CPSample_ID p_id) = 0; // return false if invalid + virtual void set_c5_freq(CPSample_ID p_id, int32_t p_freq) = 0; + virtual void set_loop_begin(CPSample_ID p_id, int32_t p_begin) = 0; + virtual void set_loop_end(CPSample_ID p_id, int32_t p_end) = 0; + virtual void set_loop_type(CPSample_ID p_id, CPSample_Loop_Type p_type) = 0; + virtual void set_chunk(CPSample_ID p_id, int32_t p_index, void *p_data, int p_data_len) = 0; - virtual int32_t get_loop_begin(CPSample_ID p_id)=0; - virtual int32_t get_loop_end(CPSample_ID p_id)=0; - virtual CPSample_Loop_Type get_loop_type(CPSample_ID p_id)=0; - virtual int32_t get_c5_freq(CPSample_ID p_id)=0; - virtual int32_t get_size(CPSample_ID p_id)=0; - virtual bool is_16bits(CPSample_ID p_id)=0; - virtual bool is_stereo(CPSample_ID p_id)=0; - virtual bool lock_data(CPSample_ID p_id)=0; - virtual void *get_data(CPSample_ID p_id)=0; /* WARNING: Not all sample managers + virtual int32_t get_loop_begin(CPSample_ID p_id) = 0; + virtual int32_t get_loop_end(CPSample_ID p_id) = 0; + virtual CPSample_Loop_Type get_loop_type(CPSample_ID p_id) = 0; + virtual int32_t get_c5_freq(CPSample_ID p_id) = 0; + virtual int32_t get_size(CPSample_ID p_id) = 0; + virtual bool is_16bits(CPSample_ID p_id) = 0; + virtual bool is_stereo(CPSample_ID p_id) = 0; + virtual bool lock_data(CPSample_ID p_id) = 0; + virtual void *get_data(CPSample_ID p_id) = 0; /* WARNING: Not all sample managers may be able to implement this, it depends on the mixer in use! */ - virtual int16_t get_data(CPSample_ID p_id, int p_sample, int p_channel=0)=0; /// Does not need locking - virtual void set_data(CPSample_ID p_id, int p_sample, int16_t p_data,int p_channel=0)=0; /// Does not need locking - virtual void unlock_data(CPSample_ID p_id)=0; + virtual int16_t get_data(CPSample_ID p_id, int p_sample, int p_channel = 0) = 0; /// Does not need locking + virtual void set_data(CPSample_ID p_id, int p_sample, int16_t p_data, int p_channel = 0) = 0; /// Does not need locking + virtual void unlock_data(CPSample_ID p_id) = 0; - virtual void get_chunk(CPSample_ID p_id,int32_t p_index,void *p_data,int p_data_len)=0; - - CPSampleManager(); - virtual ~CPSampleManager(){} + virtual void get_chunk(CPSample_ID p_id, int32_t p_index, void *p_data, int p_data_len) = 0; + CPSampleManager(); + virtual ~CPSampleManager() {} }; #endif diff --git a/modules/chibi/cp_song.cpp b/modules/chibi/cp_song.cpp index 197e44f69..b3ef361d3 100644 --- a/modules/chibi/cp_song.cpp +++ b/modules/chibi/cp_song.cpp @@ -30,58 +30,53 @@ void CPSong::set_name(const char *p_name) { - if (p_name==NULL) { - variables.name[0]=0; + if (p_name == NULL) { + variables.name[0] = 0; return; } - - bool done=false; - for (int i=0;i<MAX_SONG_NAME;i++) { + bool done = false; + for (int i = 0; i < MAX_SONG_NAME; i++) { - - variables.name[i]=done?0:p_name[i]; - if (!done && p_name[i]==0) - done=true; + variables.name[i] = done ? 0 : p_name[i]; + if (!done && p_name[i] == 0) + done = true; } - variables.name[MAX_SONG_NAME-1]=0; /* just in case */ + variables.name[MAX_SONG_NAME - 1] = 0; /* just in case */ } -const char * CPSong::get_name() { +const char *CPSong::get_name() { return variables.name; - } void CPSong::set_message(const char *p_message) { - if (p_message==NULL) { - variables.message[0]=0; + if (p_message == NULL) { + variables.message[0] = 0; return; } - bool done=false; - for (int i=0;i<MAX_MESSAGE_LEN;i++) { + bool done = false; + for (int i = 0; i < MAX_MESSAGE_LEN; i++) { - - variables.message[i]=done?0:p_message[i]; - if (!done && p_message[i]==0) - done=true; + variables.message[i] = done ? 0 : p_message[i]; + if (!done && p_message[i] == 0) + done = true; } - variables.message[MAX_MESSAGE_LEN-1]=0; /* just in case */ + variables.message[MAX_MESSAGE_LEN - 1] = 0; /* just in case */ } -const char * CPSong::get_message() { +const char *CPSong::get_message() { return variables.message; - } void CPSong::set_row_highlight_minor(int p_hl_minor) { - variables.row_highlight_minor=p_hl_minor; + variables.row_highlight_minor = p_hl_minor; } int CPSong::get_row_highlight_minor() { @@ -90,21 +85,18 @@ int CPSong::get_row_highlight_minor() { void CPSong::set_row_highlight_major(int p_hl_major) { - variables.row_highlight_major=p_hl_major; - + variables.row_highlight_major = p_hl_major; } /* 0 .. 256 */ int CPSong::get_row_highlight_major() { return variables.row_highlight_major; - } /* 0 .. 256 */ void CPSong::set_mixing_volume(int p_mix_volume) { - - variables.mixing_volume=p_mix_volume; + variables.mixing_volume = p_mix_volume; } /* 0 .. 128 */ int CPSong::get_mixing_volume() { @@ -114,8 +106,7 @@ int CPSong::get_mixing_volume() { void CPSong::set_global_volume(int p_global_volume) { - - initial_variables.global_volume=p_global_volume; + initial_variables.global_volume = p_global_volume; } /* 0 .. 128 */ int CPSong::get_global_volume() { @@ -126,7 +117,7 @@ int CPSong::get_global_volume() { void CPSong::set_stereo_separation(int p_separation) { - variables.stereo_separation=p_separation; + variables.stereo_separation = p_separation; } /* 0 .. 128 */ int CPSong::get_stereo_separation() { @@ -136,8 +127,7 @@ int CPSong::get_stereo_separation() { void CPSong::set_stereo(bool p_stereo) { - variables.use_stereo=p_stereo; - + variables.use_stereo = p_stereo; } bool CPSong::is_stereo() { @@ -146,35 +136,25 @@ bool CPSong::is_stereo() { void CPSong::set_instruments(bool p_instruments) { - variables.use_instruments=p_instruments; - - + variables.use_instruments = p_instruments; } bool CPSong::has_instruments() { - return variables.use_instruments; - } void CPSong::set_linear_slides(bool p_linear_slides) { - variables.use_linear_slides=p_linear_slides; - - + variables.use_linear_slides = p_linear_slides; } bool CPSong::has_linear_slides() { return variables.use_linear_slides; - - } void CPSong::set_old_effects(bool p_old_effects) { - variables.old_effects=p_old_effects; - - + variables.old_effects = p_old_effects; } bool CPSong::has_old_effects() { @@ -183,21 +163,19 @@ bool CPSong::has_old_effects() { void CPSong::set_compatible_gxx(bool p_compatible_gxx) { - - variables.compatible_gxx=p_compatible_gxx; + variables.compatible_gxx = p_compatible_gxx; } bool CPSong::has_compatible_gxx() { return variables.compatible_gxx; - } void CPSong::set_speed(int p_speed) { - CP_ERR_COND(p_speed<MIN_SPEED); - CP_ERR_COND(p_speed>MAX_SPEED); - - initial_variables.speed=p_speed; + CP_ERR_COND(p_speed < MIN_SPEED); + CP_ERR_COND(p_speed > MAX_SPEED); + + initial_variables.speed = p_speed; } /* 1 .. 255 */ int CPSong::get_speed() { @@ -208,535 +186,465 @@ int CPSong::get_speed() { void CPSong::set_tempo(int p_tempo) { - CP_ERR_COND( p_tempo<MIN_TEMPO ); - CP_ERR_COND( p_tempo>MAX_TEMPO ); - - initial_variables.tempo=p_tempo; + CP_ERR_COND(p_tempo < MIN_TEMPO); + CP_ERR_COND(p_tempo > MAX_TEMPO); + + initial_variables.tempo = p_tempo; } /* MIN_TEMPO .. MAX_TEMPO */ int CPSong::get_tempo() { return initial_variables.tempo; - } /* MIN_TEMPO .. MAX_TEMPO */ -void CPSong::set_channel_pan(int p_channel,int p_pan) { +void CPSong::set_channel_pan(int p_channel, int p_pan) { + + CP_FAIL_INDEX(p_channel, CPPattern::WIDTH); + CP_FAIL_INDEX(p_pan, CHANNEL_MAX_PAN + 1); - CP_FAIL_INDEX(p_channel,CPPattern::WIDTH); - CP_FAIL_INDEX(p_pan,CHANNEL_MAX_PAN+1); - - initial_variables.channel[p_channel].pan=p_pan; + initial_variables.channel[p_channel].pan = p_pan; } /* 0 .. CHANNEL_MAX_PAN */ int CPSong::get_channel_pan(int p_channel) { - CP_FAIL_INDEX_V(p_channel,CPPattern::WIDTH,-1); - + CP_FAIL_INDEX_V(p_channel, CPPattern::WIDTH, -1); + return initial_variables.channel[p_channel].pan; } -void CPSong::set_channel_volume(int p_channel,int p_volume) { +void CPSong::set_channel_volume(int p_channel, int p_volume) { - CP_FAIL_INDEX(p_channel,CPPattern::WIDTH); - CP_FAIL_INDEX(p_volume,CHANNEL_MAX_VOLUME+1); - - - initial_variables.channel[p_channel].volume=p_volume; + CP_FAIL_INDEX(p_channel, CPPattern::WIDTH); + CP_FAIL_INDEX(p_volume, CHANNEL_MAX_VOLUME + 1); + initial_variables.channel[p_channel].volume = p_volume; } /* 0 .. CHANNEL_MAX_VOLUME */ - int CPSong::get_channel_volume(int p_channel) { - CP_FAIL_INDEX_V(p_channel,CPPattern::WIDTH,-1); - - return initial_variables.channel[p_channel].volume; + CP_FAIL_INDEX_V(p_channel, CPPattern::WIDTH, -1); + return initial_variables.channel[p_channel].volume; } -void CPSong::set_channel_chorus(int p_channel,int p_chorus) { +void CPSong::set_channel_chorus(int p_channel, int p_chorus) { - CP_FAIL_INDEX(p_channel,CPPattern::WIDTH); - CP_FAIL_INDEX(p_chorus,CHANNEL_MAX_CHORUS+1); - - - initial_variables.channel[p_channel].chorus=p_chorus; + CP_FAIL_INDEX(p_channel, CPPattern::WIDTH); + CP_FAIL_INDEX(p_chorus, CHANNEL_MAX_CHORUS + 1); + initial_variables.channel[p_channel].chorus = p_chorus; } /* 0 .. CHANNEL_MAX_CHORUS */ - int CPSong::get_channel_chorus(int p_channel) { - CP_FAIL_INDEX_V(p_channel,CPPattern::WIDTH,-1); - - return initial_variables.channel[p_channel].chorus; + CP_FAIL_INDEX_V(p_channel, CPPattern::WIDTH, -1); + return initial_variables.channel[p_channel].chorus; } -void CPSong::set_channel_reverb(int p_channel,int p_reverb) { +void CPSong::set_channel_reverb(int p_channel, int p_reverb) { - CP_FAIL_INDEX(p_channel,CPPattern::WIDTH); - CP_FAIL_INDEX(p_reverb,CHANNEL_MAX_REVERB+1); - - - initial_variables.channel[p_channel].reverb=p_reverb; + CP_FAIL_INDEX(p_channel, CPPattern::WIDTH); + CP_FAIL_INDEX(p_reverb, CHANNEL_MAX_REVERB + 1); + initial_variables.channel[p_channel].reverb = p_reverb; } /* 0 .. CHANNEL_MAX_CHORUS */ - int CPSong::get_channel_reverb(int p_channel) { - CP_FAIL_INDEX_V(p_channel,CPPattern::WIDTH,-1); - - return initial_variables.channel[p_channel].reverb; + CP_FAIL_INDEX_V(p_channel, CPPattern::WIDTH, -1); + return initial_variables.channel[p_channel].reverb; } -void CPSong::set_channel_surround(int p_channel,bool p_surround) { - - CP_FAIL_INDEX(p_channel,CPPattern::WIDTH); - initial_variables.channel[p_channel].surround=p_surround; +void CPSong::set_channel_surround(int p_channel, bool p_surround) { + CP_FAIL_INDEX(p_channel, CPPattern::WIDTH); + initial_variables.channel[p_channel].surround = p_surround; } bool CPSong::is_channel_surround(int p_channel) { - CP_FAIL_INDEX_V(p_channel,CPPattern::WIDTH,false); - - return initial_variables.channel[p_channel].surround; - + CP_FAIL_INDEX_V(p_channel, CPPattern::WIDTH, false); + return initial_variables.channel[p_channel].surround; } -void CPSong::set_channel_mute(int p_channel,bool p_mute) { +void CPSong::set_channel_mute(int p_channel, bool p_mute) { - CP_FAIL_INDEX(p_channel,CPPattern::WIDTH); - - initial_variables.channel[p_channel].mute=p_mute; + CP_FAIL_INDEX(p_channel, CPPattern::WIDTH); + initial_variables.channel[p_channel].mute = p_mute; } bool CPSong::is_channel_mute(int p_channel) { - CP_FAIL_INDEX_V(p_channel,CPPattern::WIDTH,false); - - return initial_variables.channel[p_channel].mute; + CP_FAIL_INDEX_V(p_channel, CPPattern::WIDTH, false); + return initial_variables.channel[p_channel].mute; } /* arrays of stuff */ -CPPattern* CPSong::get_pattern(int p_pattern) { +CPPattern *CPSong::get_pattern(int p_pattern) { - CP_FAIL_INDEX_V(p_pattern,MAX_PATTERNS, NULL); - - return &pattern[p_pattern]; + CP_FAIL_INDEX_V(p_pattern, MAX_PATTERNS, NULL); + return &pattern[p_pattern]; } -CPSample* CPSong::get_sample(int p_sample) { +CPSample *CPSong::get_sample(int p_sample) { - CP_FAIL_INDEX_V(p_sample,MAX_SAMPLES,NULL); + CP_FAIL_INDEX_V(p_sample, MAX_SAMPLES, NULL); return &sample[p_sample]; - - } -CPInstrument* CPSong::get_instrument(int p_instrument) { - +CPInstrument *CPSong::get_instrument(int p_instrument) { - CP_FAIL_INDEX_V(p_instrument,MAX_INSTRUMENTS,NULL); + CP_FAIL_INDEX_V(p_instrument, MAX_INSTRUMENTS, NULL); return &instrument[p_instrument]; - } int CPSong::get_order(int p_order) { - CP_FAIL_INDEX_V(p_order,MAX_ORDERS,CP_ORDER_NONE); - + CP_FAIL_INDEX_V(p_order, MAX_ORDERS, CP_ORDER_NONE); return order[p_order]; - } -void CPSong::set_order(int p_order,int p_pattern) { - - CP_FAIL_INDEX(p_order,MAX_ORDERS); +void CPSong::set_order(int p_order, int p_pattern) { - order[p_order]=p_pattern; + CP_FAIL_INDEX(p_order, MAX_ORDERS); + order[p_order] = p_pattern; } - void CPSong::clear_instrument_with_samples(int p_instrument) { - - CPInstrument *ins = get_instrument( p_instrument ); + + CPInstrument *ins = get_instrument(p_instrument); if (!ins) return; - - for (int i=0;i<CPNote::NOTES;i++) { - - CPSample *s=get_sample( ins->get_sample_number( i ) ); - + + for (int i = 0; i < CPNote::NOTES; i++) { + + CPSample *s = get_sample(ins->get_sample_number(i)); + if (!s) continue; - + if (s->get_sample_data().is_null()) continue; - + s->reset(); } ins->reset(); } void CPSong::make_instrument_from_sample(int p_sample) { - + if (!has_instruments()) return; - CP_ERR_COND(!get_sample( p_sample )); - - for (int i=0;i<MAX_INSTRUMENTS;i++) { - - - CPInstrument *ins=get_instrument(i); - - bool empty_slot=true; - for (int n=0;n<CPNote::NOTES;n++) { - - if (ins->get_sample_number(n)<MAX_SAMPLES) { - - empty_slot=false; + CP_ERR_COND(!get_sample(p_sample)); + + for (int i = 0; i < MAX_INSTRUMENTS; i++) { + + CPInstrument *ins = get_instrument(i); + + bool empty_slot = true; + for (int n = 0; n < CPNote::NOTES; n++) { + + if (ins->get_sample_number(n) < MAX_SAMPLES) { + + empty_slot = false; break; } } - + if (!empty_slot) continue; - - for (int n=0;n<CPNote::NOTES;n++) { - - ins->set_sample_number(n,p_sample); - ins->set_note_number(n,n); + + for (int n = 0; n < CPNote::NOTES; n++) { + + ins->set_sample_number(n, p_sample); + ins->set_note_number(n, n); } - - ins->set_name( get_sample( p_sample )->get_name() ); + + ins->set_name(get_sample(p_sample)->get_name()); break; } - } void CPSong::make_instruments_from_samples() { - - for (int i=0;i<MAX_SAMPLES;i++) { - - CPInstrument *ins=get_instrument( i ); - + + for (int i = 0; i < MAX_SAMPLES; i++) { + + CPInstrument *ins = get_instrument(i); + if (!ins) continue; - + ins->reset(); - - CPSample *s=get_sample( i ); - + + CPSample *s = get_sample(i); + if (!s) continue; - - ins->set_name( s->get_name() ); - + + ins->set_name(s->get_name()); + if (s->get_sample_data().is_null()) continue; - - - - - for(int j=0;j<CPNote::NOTES;j++) - ins->set_sample_number( j, i ); - - - + + for (int j = 0; j < CPNote::NOTES; j++) + ins->set_sample_number(j, i); } } -void CPSong::reset(bool p_clear_patterns,bool p_clear_samples,bool p_clear_instruments,bool p_clear_variables) { - +void CPSong::reset(bool p_clear_patterns, bool p_clear_samples, bool p_clear_instruments, bool p_clear_variables) { + if (p_clear_variables) { - variables.name[0]=0; - variables.message[0]=0; - variables.row_highlight_major=16; - variables.row_highlight_minor=4; - variables.mixing_volume=48; - variables.old_effects=false; + variables.name[0] = 0; + variables.message[0] = 0; + variables.row_highlight_major = 16; + variables.row_highlight_minor = 4; + variables.mixing_volume = 48; + variables.old_effects = false; if (p_clear_instruments) //should not be cleared, if not clearing instruments!! - variables.use_instruments=false; - variables.stereo_separation=128; - variables.use_linear_slides=true; - variables.use_stereo=true; - - initial_variables.global_volume=128; - initial_variables.speed=6; - initial_variables.tempo=125; - - for (int i=0;i<CPPattern::WIDTH;i++) { - - initial_variables.channel[i].pan=32; - initial_variables.channel[i].volume=CHANNEL_MAX_VOLUME; - initial_variables.channel[i].mute=false; - initial_variables.channel[i].surround=false; - initial_variables.channel[i].chorus=0; - initial_variables.channel[i].reverb=0; - + variables.use_instruments = false; + variables.stereo_separation = 128; + variables.use_linear_slides = true; + variables.use_stereo = true; + + initial_variables.global_volume = 128; + initial_variables.speed = 6; + initial_variables.tempo = 125; + + for (int i = 0; i < CPPattern::WIDTH; i++) { + + initial_variables.channel[i].pan = 32; + initial_variables.channel[i].volume = CHANNEL_MAX_VOLUME; + initial_variables.channel[i].mute = false; + initial_variables.channel[i].surround = false; + initial_variables.channel[i].chorus = 0; + initial_variables.channel[i].reverb = 0; } - - effects.chorus.delay_ms=6; - effects.chorus.separation_ms=3; - effects.chorus.depth_ms10=6, - effects.chorus.speed_hz10=5; - effects.reverb_mode=REVERB_MODE_ROOM; + + effects.chorus.delay_ms = 6; + effects.chorus.separation_ms = 3; + effects.chorus.depth_ms10 = 6, + effects.chorus.speed_hz10 = 5; + effects.reverb_mode = REVERB_MODE_ROOM; } - + if (p_clear_samples) { - for (int i=0;i<MAX_SAMPLES;i++) + for (int i = 0; i < MAX_SAMPLES; i++) get_sample(i)->reset(); } - + if (p_clear_instruments) { - for (int i=0;i<MAX_INSTRUMENTS;i++) + for (int i = 0; i < MAX_INSTRUMENTS; i++) get_instrument(i)->reset(); } - + if (p_clear_patterns) { - for (int i=0;i<MAX_PATTERNS;i++) + for (int i = 0; i < MAX_PATTERNS; i++) get_pattern(i)->clear(); - - for (int i=0;i<MAX_ORDERS;i++) - set_order( i, CP_ORDER_NONE ); + + for (int i = 0; i < MAX_ORDERS; i++) + set_order(i, CP_ORDER_NONE); } - - } - CPSong::ReverbMode CPSong::get_reverb_mode() { - + return effects.reverb_mode; } void CPSong::set_reverb_mode(ReverbMode p_mode) { - - effects.reverb_mode=p_mode; + + effects.reverb_mode = p_mode; } void CPSong::set_chorus_delay_ms(int p_amount) { - - effects.chorus.delay_ms=p_amount; + + effects.chorus.delay_ms = p_amount; } void CPSong::set_chorus_separation_ms(int p_amount) { - - effects.chorus.separation_ms=p_amount; + effects.chorus.separation_ms = p_amount; } void CPSong::set_chorus_depth_ms10(int p_amount) { - - effects.chorus.depth_ms10=p_amount; - + + effects.chorus.depth_ms10 = p_amount; } void CPSong::set_chorus_speed_hz10(int p_amount) { - - effects.chorus.speed_hz10=p_amount; - + + effects.chorus.speed_hz10 = p_amount; } int CPSong::get_chorus_delay_ms() { - + return effects.chorus.delay_ms; - } int CPSong::get_chorus_separation_ms() { - + return effects.chorus.separation_ms; } int CPSong::get_chorus_depth_ms10() { - + return effects.chorus.depth_ms10; - } int CPSong::get_chorus_speed_hz10() { - + return effects.chorus.speed_hz10; - } void CPSong::cleanup_unused_patterns() { - - for (int i=0;i<MAX_PATTERNS;i++) { - - bool used=false; + + for (int i = 0; i < MAX_PATTERNS; i++) { + + bool used = false; if (get_pattern(i)->is_empty()) continue; - - for (int j=0;j<MAX_ORDERS;j++) { - - if (get_order(j)==i) { - used=true; - + + for (int j = 0; j < MAX_ORDERS; j++) { + + if (get_order(j) == i) { + used = true; } } - + if (!used) get_pattern(i)->clear(); } - } -void CPSong::cleanup_unused_instruments(){ - +void CPSong::cleanup_unused_instruments() { + if (!has_instruments()) return; - + bool instr_found[MAX_INSTRUMENTS]; - for (int i=0;i<MAX_INSTRUMENTS;i++) - instr_found[i]=false; - - for (int i=0;i<MAX_PATTERNS;i++) { - + for (int i = 0; i < MAX_INSTRUMENTS; i++) + instr_found[i] = false; + + for (int i = 0; i < MAX_PATTERNS; i++) { + if (get_pattern(i)->is_empty()) continue; - - for (int row=0;row<get_pattern(i)->get_length();row++) { - - - for (int col=0;col<CPPattern::WIDTH;col++) { - + + for (int row = 0; row < get_pattern(i)->get_length(); row++) { + + for (int col = 0; col < CPPattern::WIDTH; col++) { + CPNote n; - n=get_pattern(i)->get_note( col,row ); - - if (n.instrument<MAX_INSTRUMENTS) - instr_found[n.instrument]=true; - + n = get_pattern(i)->get_note(col, row); + + if (n.instrument < MAX_INSTRUMENTS) + instr_found[n.instrument] = true; } - } - } - - for (int i=0;i<MAX_INSTRUMENTS;i++) + + for (int i = 0; i < MAX_INSTRUMENTS; i++) if (!instr_found[i]) get_instrument(i)->reset(); - - } -void CPSong::cleanup_unused_samples(){ - +void CPSong::cleanup_unused_samples() { + if (!has_instruments()) return; - + bool sample_found[MAX_SAMPLES]; - for (int i=0;i<MAX_INSTRUMENTS;i++) - sample_found[i]=false; - - for (int i=0;i<MAX_PATTERNS;i++) { - + for (int i = 0; i < MAX_INSTRUMENTS; i++) + sample_found[i] = false; + + for (int i = 0; i < MAX_PATTERNS; i++) { + if (get_pattern(i)->is_empty()) continue; - - - for (int row=0;row<get_pattern(i)->get_length();row++) { - - - for (int col=0;col<CPPattern::WIDTH;col++) { - + + for (int row = 0; row < get_pattern(i)->get_length(); row++) { + + for (int col = 0; col < CPPattern::WIDTH; col++) { + CPNote n; - n=get_pattern(i)->get_note( col,row ); - - if (n.instrument>=MAX_SAMPLES) + n = get_pattern(i)->get_note(col, row); + + if (n.instrument >= MAX_SAMPLES) continue; - + if (has_instruments()) { - - for (int nt=0;nt<CPNote::NOTES;nt++) { - - int smp=get_instrument(n.instrument)->get_sample_number(nt); - if (smp<MAX_SAMPLES) - sample_found[smp]=true; + + for (int nt = 0; nt < CPNote::NOTES; nt++) { + + int smp = get_instrument(n.instrument)->get_sample_number(nt); + if (smp < MAX_SAMPLES) + sample_found[smp] = true; } - + } else { - if (n.instrument<MAX_SAMPLES) - sample_found[n.instrument]=true; + if (n.instrument < MAX_SAMPLES) + sample_found[n.instrument] = true; } - } - } - } - - for (int i=0;i<MAX_SAMPLES;i++) + + for (int i = 0; i < MAX_SAMPLES; i++) if (!sample_found[i]) get_sample(i)->reset(); - } -void CPSong::cleanup_unused_orders(){ - - bool finito=false; - for (int j=0;j<MAX_ORDERS;j++) { - - - if (get_order(j)==CP_ORDER_NONE) - finito=true; +void CPSong::cleanup_unused_orders() { + + bool finito = false; + for (int j = 0; j < MAX_ORDERS; j++) { + + if (get_order(j) == CP_ORDER_NONE) + finito = true; if (finito) - set_order(j,CP_ORDER_NONE); - + set_order(j, CP_ORDER_NONE); } - } void CPSong::clear_all_default_pan() { - - for (int i=0;i<MAX_INSTRUMENTS;i++) - get_instrument(i)->set_pan_default_enabled( false ); //die! - - for (int i=0;i<MAX_SAMPLES;i++) - get_sample(i)->set_pan_enabled( false ); //die! - -} + for (int i = 0; i < MAX_INSTRUMENTS; i++) + get_instrument(i)->set_pan_default_enabled(false); //die! -void CPSong::clear_all_default_vol(){ - - for (int i=0;i<MAX_SAMPLES;i++) - get_sample(i)->set_default_volume( 64 ); //die! - for (int i=0;i<MAX_INSTRUMENTS;i++) - get_instrument(i)->set_volume_global_amount( CPInstrument::MAX_VOLUME ); - + for (int i = 0; i < MAX_SAMPLES; i++) + get_sample(i)->set_pan_enabled(false); //die! } +void CPSong::clear_all_default_vol() { -int CPSong::get_order_in_use_count() { + for (int i = 0; i < MAX_SAMPLES; i++) + get_sample(i)->set_default_volume(64); //die! + for (int i = 0; i < MAX_INSTRUMENTS; i++) + get_instrument(i)->set_volume_global_amount(CPInstrument::MAX_VOLUME); +} +int CPSong::get_order_in_use_count() { int order_count = 0; - - for (int i=(MAX_ORDERS-1);i>=0;i--) { - - if (get_order(i)!=CP_ORDER_NONE) { - order_count=i+1; + for (int i = (MAX_ORDERS - 1); i >= 0; i--) { + + if (get_order(i) != CP_ORDER_NONE) { + order_count = i + 1; break; } } - + return order_count; } int CPSong::get_pattern_in_use_count() { - - int pattern_count=0; - - for (int i=(CPSong::MAX_PATTERNS-1);i>=0;i--) { + int pattern_count = 0; + + for (int i = (CPSong::MAX_PATTERNS - 1); i >= 0; i--) { - if (!get_pattern(i)->is_empty()) { - pattern_count=i+1; + pattern_count = i + 1; break; } } @@ -746,28 +654,27 @@ int CPSong::get_pattern_in_use_count() { int CPSong::get_instrument_in_use_count() { - int instrument_count=0; - - for (int i=(CPSong::MAX_INSTRUMENTS-1);i>=0;i--) { + int instrument_count = 0; + + for (int i = (CPSong::MAX_INSTRUMENTS - 1); i >= 0; i--) { CPInstrument *ins = get_instrument(i); - bool in_use=false; - - for (int s = 0 ; s < CPNote::NOTES ; s++ ) { - + bool in_use = false; + + for (int s = 0; s < CPNote::NOTES; s++) { + int smp_idx = ins->get_sample_number(s); - if (smp_idx<0 || smp_idx>=CPSong::MAX_SAMPLES) + if (smp_idx < 0 || smp_idx >= CPSong::MAX_SAMPLES) continue; - + if (!get_sample(smp_idx)->get_sample_data().is_null()) { - in_use=true; + in_use = true; break; } - } - + if (in_use) { - instrument_count=i+1; + instrument_count = i + 1; break; } } @@ -777,33 +684,32 @@ int CPSong::get_instrument_in_use_count() { #include <stdio.h> int CPSong::get_channels_in_use() { - int max=0; - - for (int p=0;p<CPSong::MAX_PATTERNS;p++) { - + int max = 0; + + for (int p = 0; p < CPSong::MAX_PATTERNS; p++) { + CPPattern *pat = get_pattern(p); if (pat->is_empty()) continue; - - - for (int c=(CPPattern::WIDTH-1);c>=0;c--) { - - if (c<max) + + for (int c = (CPPattern::WIDTH - 1); c >= 0; c--) { + + if (c < max) break; - - bool has_note=false; - for (int r=0;r<pat->get_length();r++) { - - CPNote n = pat->get_note( c, r ); + + bool has_note = false; + for (int r = 0; r < pat->get_length(); r++) { + + CPNote n = pat->get_note(c, r); if (!n.is_empty()) { - has_note=true; + has_note = true; break; } } - + if (has_note) { - - max=c+1; + + max = c + 1; } } } @@ -811,141 +717,132 @@ int CPSong::get_channels_in_use() { return max; } - void CPSong::separate_in_one_sample_instruments(int p_instrument) { - CP_ERR_COND( !variables.use_instruments ); - CP_FAIL_INDEX( p_instrument, MAX_INSTRUMENTS ); + CP_ERR_COND(!variables.use_instruments); + CP_FAIL_INDEX(p_instrument, MAX_INSTRUMENTS); + + int remapped_count = 0; - int remapped_count=0; - signed char remap[MAX_SAMPLES]; - - for (int i=0;i<MAX_SAMPLES;i++) { - - remap[i]=-1; + + for (int i = 0; i < MAX_SAMPLES; i++) { + + remap[i] = -1; } - + /* Find remaps */ - CPInstrument *ins=get_instrument(p_instrument); - for (int i=0;i<CPNote::NOTES;i++) { - + CPInstrument *ins = get_instrument(p_instrument); + for (int i = 0; i < CPNote::NOTES; i++) { + int sn = ins->get_sample_number(i); - + // check for unusable sample - if (sn<0 || sn>=MAX_SAMPLES || get_sample(sn)->get_sample_data().is_null()) + if (sn < 0 || sn >= MAX_SAMPLES || get_sample(sn)->get_sample_data().is_null()) continue; - printf("sample %i\n",sn); - if ( remap[sn] !=-1 ) { - printf("already mapped to %i\n",remap[sn]); + printf("sample %i\n", sn); + if (remap[sn] != -1) { + printf("already mapped to %i\n", remap[sn]); continue; } - - printf("isn't remapped\n"); - + + printf("isn't remapped\n"); + // find remap - - for (int j=0;j<MAX_INSTRUMENTS;j++) { - - if (!get_instrument(j)->is_empty()) + + for (int j = 0; j < MAX_INSTRUMENTS; j++) { + + if (!get_instrument(j)->is_empty()) continue; - - printf("map to %i\n",j); - + + printf("map to %i\n", j); + //copy - *get_instrument(j)=*ins; - + *get_instrument(j) = *ins; + // assign samples - for (int k=0;k<CPNote::NOTES;k++) { - - get_instrument(j)->set_note_number(k,k); - get_instrument(j)->set_sample_number(k,sn); - } - remap[sn]=j; + for (int k = 0; k < CPNote::NOTES; k++) { + + get_instrument(j)->set_note_number(k, k); + get_instrument(j)->set_sample_number(k, sn); + } + remap[sn] = j; remapped_count++; break; } - - CP_ERR_COND(remap[sn]==-1); // no more free instruments + + CP_ERR_COND(remap[sn] == -1); // no more free instruments } - - printf("remapped %i\n",remapped_count); - - if (remapped_count<2) { + + printf("remapped %i\n", remapped_count); + + if (remapped_count < 2) { //undo if only one is remapped - for (int i=0;i<MAX_SAMPLES;i++) { - - if (remap[i]!=-1) { - + for (int i = 0; i < MAX_SAMPLES; i++) { + + if (remap[i] != -1) { + get_instrument(remap[i])->reset(); } } return; } - + /* remap all song */ - - for (int p=0;p<CPSong::MAX_PATTERNS;p++) { - + + for (int p = 0; p < CPSong::MAX_PATTERNS; p++) { + CPPattern *pat = get_pattern(p); if (pat->is_empty()) continue; - - - for (int c=0;c<CPPattern::WIDTH;c++) { - - for (int r=0;r<pat->get_length();r++) { - - CPNote n = pat->get_note(c,r); - if (n.note<CPNote::NOTES && n.instrument==p_instrument) { - + + for (int c = 0; c < CPPattern::WIDTH; c++) { + + for (int r = 0; r < pat->get_length(); r++) { + + CPNote n = pat->get_note(c, r); + if (n.note < CPNote::NOTES && n.instrument == p_instrument) { + int sn = ins->get_sample_number(n.note); - if (remap[sn]==-1) - pat->set_note(c,r,CPNote()); + if (remap[sn] == -1) + pat->set_note(c, r, CPNote()); else { - - n.instrument=remap[sn]; - pat->set_note(c,r,n); + + n.instrument = remap[sn]; + pat->set_note(c, r, n); } } } } } - + ins->reset(); - } - CPSong::CPSong() { - + reset(); } CPSong::~CPSong() { - } - - - int get_song_next_order_idx(CPSong *p_song, int p_order_idx) { - int baseorder,order_counter; + int baseorder, order_counter; - order_counter=-1; + order_counter = -1; - baseorder=p_order_idx; + baseorder = p_order_idx; do { baseorder++; - if ( baseorder>(CPSong::MAX_ORDERS-1) ) baseorder=0; + if (baseorder > (CPSong::MAX_ORDERS - 1)) baseorder = 0; order_counter++; - } while ( (p_song->get_order(baseorder)>=(CPSong::MAX_PATTERNS) ) && (order_counter<CPSong::MAX_ORDERS) ); + } while ((p_song->get_order(baseorder) >= (CPSong::MAX_PATTERNS)) && (order_counter < CPSong::MAX_ORDERS)); - - if (order_counter==CPSong::MAX_ORDERS) { + if (order_counter == CPSong::MAX_ORDERS) { return -1; @@ -953,5 +850,4 @@ int get_song_next_order_idx(CPSong *p_song, int p_order_idx) { return baseorder; } - } diff --git a/modules/chibi/cp_song.h b/modules/chibi/cp_song.h index ba0fa3e80..18fb59adb 100644 --- a/modules/chibi/cp_song.h +++ b/modules/chibi/cp_song.h @@ -29,40 +29,37 @@ #ifndef CPSONG_H #define CPSONG_H - /**CPSong Class *@author Juan Linietsky */ +#include "cp_instrument.h" #include "cp_order.h" #include "cp_pattern.h" #include "cp_sample.h" -#include "cp_instrument.h" class CPSong { public: enum { - MAX_SONG_NAME=26, - MAX_ORDERS=200, - MAX_PATTERNS=200, - MAX_SAMPLES=99, - MAX_INSTRUMENTS=99, - - CHANNEL_MAX_PAN=64, - CHANNEL_MAX_VOLUME=64, - CHANNEL_MAX_CHORUS=64, - CHANNEL_MAX_REVERB=64, - - MIN_TEMPO=31, - MAX_TEMPO=255, - MIN_SPEED=1, - MAX_SPEED=255, - MAX_MESSAGE_LEN=8000, - - - + MAX_SONG_NAME = 26, + MAX_ORDERS = 200, + MAX_PATTERNS = 200, + MAX_SAMPLES = 99, + MAX_INSTRUMENTS = 99, + + CHANNEL_MAX_PAN = 64, + CHANNEL_MAX_VOLUME = 64, + CHANNEL_MAX_CHORUS = 64, + CHANNEL_MAX_REVERB = 64, + + MIN_TEMPO = 31, + MAX_TEMPO = 255, + MIN_SPEED = 1, + MAX_SPEED = 255, + MAX_MESSAGE_LEN = 8000, + }; - + enum ReverbMode { REVERB_MODE_ROOM, REVERB_MODE_STUDIO_SMALL, @@ -74,15 +71,13 @@ public: REVERB_MODE_DELAY, REVERB_MODE_HALF_ECHO }; - + private: CPOrder order[MAX_ORDERS]; CPPattern pattern[MAX_PATTERNS]; CPSample sample[MAX_SAMPLES]; - CPInstrument instrument[MAX_INSTRUMENTS]; - + CPInstrument instrument[MAX_INSTRUMENTS]; - struct Song_Variables { // variables that wont change in playback char name[MAX_SONG_NAME]; @@ -106,46 +101,45 @@ private: struct Initial_Variables { // Initial values used for playback - struct Channel_State { + struct Channel_State { - int pan,volume; // 0-- CHANNEL_MAX_PAN, CHANNEL_MAX_VOLUME + int pan, volume; // 0-- CHANNEL_MAX_PAN, CHANNEL_MAX_VOLUME bool surround; bool mute; int chorus; //0 - 64 int reverb; //0 - 64 }; - + int global_volume; int speed; int tempo; Channel_State channel[CPPattern::WIDTH]; } initial_variables; - + struct Effects { - + ReverbMode reverb_mode; - + struct Chorus { - + int delay_ms; int separation_ms; int depth_ms10; int speed_hz10; } chorus; - + } effects; public: - /* Properties */ - + const char *get_name(); void set_name(const char *p_name); const char *get_message(); void set_message(const char *p_message); - + void set_row_highlight_minor(int p_hl_minor); /* 0 .. 256 */ int get_row_highlight_minor(); /* 0 .. 256 */ @@ -157,16 +151,16 @@ public: void set_global_volume(int p_global_volume); /* 0 .. 128 */ int get_global_volume(); /* 0 .. 128 */ - + void set_stereo_separation(int p_separation); /* 0 .. 128 */ int get_stereo_separation(); /* 0 .. 128 */ - + void set_stereo(bool p_stereo); bool is_stereo(); void set_instruments(bool p_instruments); bool has_instruments(); - + void set_linear_slides(bool p_linear_slides); bool has_linear_slides(); @@ -182,52 +176,51 @@ public: void set_tempo(int p_tempo); /* 31 .. 255 */ int get_tempo(); /* 31 .. 255 */ - void set_channel_pan(int p_channel,int p_pan); /* 0 .. 64 */ + void set_channel_pan(int p_channel, int p_pan); /* 0 .. 64 */ int get_channel_pan(int p_channel); - - void set_channel_volume(int p_channel,int p_volume); /* 0 .. 64 */ + + void set_channel_volume(int p_channel, int p_volume); /* 0 .. 64 */ int get_channel_volume(int p_channel); - void set_channel_surround(int p_channel,bool p_surround); + void set_channel_surround(int p_channel, bool p_surround); bool is_channel_surround(int p_channel); - void set_channel_mute(int p_channel,bool p_mute); + void set_channel_mute(int p_channel, bool p_mute); bool is_channel_mute(int p_channel); - - void set_channel_chorus(int p_channel,int p_chorus); /* 0 .. 64 */ + + void set_channel_chorus(int p_channel, int p_chorus); /* 0 .. 64 */ int get_channel_chorus(int p_channel); - - void set_channel_reverb(int p_channel,int p_reverb); /* 0 .. 64 */ + + void set_channel_reverb(int p_channel, int p_reverb); /* 0 .. 64 */ int get_channel_reverb(int p_channel); - + /* arrays of stuff */ - CPPattern* get_pattern(int p_pattern); - CPSample* get_sample(int p_sample); - CPInstrument* get_instrument(int p_instrument); + CPPattern *get_pattern(int p_pattern); + CPSample *get_sample(int p_sample); + CPInstrument *get_instrument(int p_instrument); int get_order(int p_position); - void set_order(int p_position,int p_order); + void set_order(int p_position, int p_order); - /* Effects */ - + ReverbMode get_reverb_mode(); void set_reverb_mode(ReverbMode p_mode); - + void set_chorus_delay_ms(int p_amount); void set_chorus_separation_ms(int p_amount); void set_chorus_depth_ms10(int p_amount); void set_chorus_speed_hz10(int p_amount); - + int get_chorus_delay_ms(); int get_chorus_separation_ms(); int get_chorus_depth_ms10(); int get_chorus_speed_hz10(); - - /* utils */ - void reset(bool p_clear_patterns=true,bool p_clear_samples=true,bool p_clear_instruments=true,bool p_clear_variables=true); + /* utils */ + + void reset(bool p_clear_patterns = true, bool p_clear_samples = true, bool p_clear_instruments = true, bool p_clear_variables = true); void cleanup_unused_patterns(); void cleanup_unused_instruments(); @@ -235,9 +228,9 @@ public: void cleanup_unused_orders(); void clear_all_default_pan(); void clear_all_default_vol(); - + void clear_instrument_with_samples(int p_instrument); - + void make_instruments_from_samples(); void make_instrument_from_sample(int p_sample); @@ -250,10 +243,8 @@ public: CPSong(); ~CPSong(); - }; - /* Some helper for something used a lot */ int get_song_next_order_idx(CPSong *p_song, int p_order_idx); diff --git a/modules/chibi/cp_tables.cpp b/modules/chibi/cp_tables.cpp index a7ed34ff3..5145abc2a 100644 --- a/modules/chibi/cp_tables.cpp +++ b/modules/chibi/cp_tables.cpp @@ -29,162 +29,158 @@ #include "cp_tables.h" -int32_t CPTables::linear_period_to_freq_tab[768]={ +int32_t CPTables::linear_period_to_freq_tab[768] = { - 535232,534749,534266,533784,533303,532822,532341,531861, - 531381,530902,530423,529944,529466,528988,528511,528034, - 527558,527082,526607,526131,525657,525183,524709,524236, - 523763,523290,522818,522346,521875,521404,520934,520464, - 519994,519525,519057,518588,518121,517653,517186,516720, - 516253,515788,515322,514858,514393,513929,513465,513002, - 512539,512077,511615,511154,510692,510232,509771,509312, - 508852,508393,507934,507476,507018,506561,506104,505647, - 505191,504735,504280,503825,503371,502917,502463,502010, - 501557,501104,500652,500201,499749,499298,498848,498398, - 497948,497499,497050,496602,496154,495706,495259,494812, - 494366,493920,493474,493029,492585,492140,491696,491253, - 490809,490367,489924,489482,489041,488600,488159,487718, - 487278,486839,486400,485961,485522,485084,484647,484210, - 483773,483336,482900,482465,482029,481595,481160,480726, - 480292,479859,479426,478994,478562,478130,477699,477268, - 476837,476407,475977,475548,475119,474690,474262,473834, - 473407,472979,472553,472126,471701,471275,470850,470425, - 470001,469577,469153,468730,468307,467884,467462,467041, - 466619,466198,465778,465358,464938,464518,464099,463681, - 463262,462844,462427,462010,461593,461177,460760,460345, - 459930,459515,459100,458686,458272,457859,457446,457033, - 456621,456209,455797,455386,454975,454565,454155,453745, - 453336,452927,452518,452110,451702,451294,450887,450481, - 450074,449668,449262,448857,448452,448048,447644,447240, - 446836,446433,446030,445628,445226,444824,444423,444022, - 443622,443221,442821,442422,442023,441624,441226,440828, - 440430,440033,439636,439239,438843,438447,438051,437656, - 437261,436867,436473,436079,435686,435293,434900,434508, - 434116,433724,433333,432942,432551,432161,431771,431382, - 430992,430604,430215,429827,429439,429052,428665,428278, - 427892,427506,427120,426735,426350,425965,425581,425197, - 424813,424430,424047,423665,423283,422901,422519,422138, - 421757,421377,420997,420617,420237,419858,419479,419101, - 418723,418345,417968,417591,417214,416838,416462,416086, - 415711,415336,414961,414586,414212,413839,413465,413092, - 412720,412347,411975,411604,411232,410862,410491,410121, - 409751,409381,409012,408643,408274,407906,407538,407170, - 406803,406436,406069,405703,405337,404971,404606,404241, - 403876,403512,403148,402784,402421,402058,401695,401333, - 400970,400609,400247,399886,399525,399165,398805,398445, - 398086,397727,397368,397009,396651,396293,395936,395579, - 395222,394865,394509,394153,393798,393442,393087,392733, - 392378,392024,391671,391317,390964,390612,390259,389907, - 389556,389204,388853,388502,388152,387802,387452,387102, - 386753,386404,386056,385707,385359,385012,384664,384317, - 383971,383624,383278,382932,382587,382242,381897,381552, - 381208,380864,380521,380177,379834,379492,379149,378807, - 378466,378124,377783,377442,377102,376762,376422,376082, - 375743,375404,375065,374727,374389,374051,373714,373377, - 373040,372703,372367,372031,371695,371360,371025,370690, - 370356,370022,369688,369355,369021,368688,368356,368023, - 367691,367360,367028,366697,366366,366036,365706,365376, - 365046,364717,364388,364059,363731,363403,363075,362747, - 362420,362093,361766,361440,361114,360788,360463,360137, - 359813,359488,359164,358840,358516,358193,357869,357547, - 357224,356902,356580,356258,355937,355616,355295,354974, - 354654,354334,354014,353695,353376,353057,352739,352420, - 352103,351785,351468,351150,350834,350517,350201,349885, - 349569,349254,348939,348624,348310,347995,347682,347368, - 347055,346741,346429,346116,345804,345492,345180,344869, - 344558,344247,343936,343626,343316,343006,342697,342388, - 342079,341770,341462,341154,340846,340539,340231,339924, - 339618,339311,339005,338700,338394,338089,337784,337479, - 337175,336870,336566,336263,335959,335656,335354,335051, - 334749,334447,334145,333844,333542,333242,332941,332641, - 332341,332041,331741,331442,331143,330844,330546,330247, - 329950,329652,329355,329057,328761,328464,328168,327872, - 327576,327280,326985,326690,326395,326101,325807,325513, - 325219,324926,324633,324340,324047,323755,323463,323171, - 322879,322588,322297,322006,321716,321426,321136,320846, - 320557,320267,319978,319690,319401,319113,318825,318538, - 318250,317963,317676,317390,317103,316817,316532,316246, - 315961,315676,315391,315106,314822,314538,314254,313971, - 313688,313405,313122,312839,312557,312275,311994,311712, - 311431,311150,310869,310589,310309,310029,309749,309470, - 309190,308911,308633,308354,308076,307798,307521,307243, - 306966,306689,306412,306136,305860,305584,305308,305033, - 304758,304483,304208,303934,303659,303385,303112,302838, - 302565,302292,302019,301747,301475,301203,300931,300660, - 300388,300117,299847,299576,299306,299036,298766,298497, - 298227,297958,297689,297421,297153,296884,296617,296349, - 296082,295815,295548,295281,295015,294749,294483,294217, - 293952,293686,293421,293157,292892,292628,292364,292100, - 291837,291574,291311,291048,290785,290523,290261,289999, - 289737,289476,289215,288954,288693,288433,288173,287913, - 287653,287393,287134,286875,286616,286358,286099,285841, - 285583,285326,285068,284811,284554,284298,284041,283785, - 283529,283273,283017,282762,282507,282252,281998,281743, - 281489,281235,280981,280728,280475,280222,279969,279716, - 279464,279212,278960,278708,278457,278206,277955,277704, - 277453,277203,276953,276703,276453,276204,275955,275706, - 275457,275209,274960,274712,274465,274217,273970,273722, - 273476,273229,272982,272736,272490,272244,271999,271753, - 271508,271263,271018,270774,270530,270286,270042,269798, - 269555,269312,269069,268826,268583,268341,268099,267857 + 535232, 534749, 534266, 533784, 533303, 532822, 532341, 531861, + 531381, 530902, 530423, 529944, 529466, 528988, 528511, 528034, + 527558, 527082, 526607, 526131, 525657, 525183, 524709, 524236, + 523763, 523290, 522818, 522346, 521875, 521404, 520934, 520464, + 519994, 519525, 519057, 518588, 518121, 517653, 517186, 516720, + 516253, 515788, 515322, 514858, 514393, 513929, 513465, 513002, + 512539, 512077, 511615, 511154, 510692, 510232, 509771, 509312, + 508852, 508393, 507934, 507476, 507018, 506561, 506104, 505647, + 505191, 504735, 504280, 503825, 503371, 502917, 502463, 502010, + 501557, 501104, 500652, 500201, 499749, 499298, 498848, 498398, + 497948, 497499, 497050, 496602, 496154, 495706, 495259, 494812, + 494366, 493920, 493474, 493029, 492585, 492140, 491696, 491253, + 490809, 490367, 489924, 489482, 489041, 488600, 488159, 487718, + 487278, 486839, 486400, 485961, 485522, 485084, 484647, 484210, + 483773, 483336, 482900, 482465, 482029, 481595, 481160, 480726, + 480292, 479859, 479426, 478994, 478562, 478130, 477699, 477268, + 476837, 476407, 475977, 475548, 475119, 474690, 474262, 473834, + 473407, 472979, 472553, 472126, 471701, 471275, 470850, 470425, + 470001, 469577, 469153, 468730, 468307, 467884, 467462, 467041, + 466619, 466198, 465778, 465358, 464938, 464518, 464099, 463681, + 463262, 462844, 462427, 462010, 461593, 461177, 460760, 460345, + 459930, 459515, 459100, 458686, 458272, 457859, 457446, 457033, + 456621, 456209, 455797, 455386, 454975, 454565, 454155, 453745, + 453336, 452927, 452518, 452110, 451702, 451294, 450887, 450481, + 450074, 449668, 449262, 448857, 448452, 448048, 447644, 447240, + 446836, 446433, 446030, 445628, 445226, 444824, 444423, 444022, + 443622, 443221, 442821, 442422, 442023, 441624, 441226, 440828, + 440430, 440033, 439636, 439239, 438843, 438447, 438051, 437656, + 437261, 436867, 436473, 436079, 435686, 435293, 434900, 434508, + 434116, 433724, 433333, 432942, 432551, 432161, 431771, 431382, + 430992, 430604, 430215, 429827, 429439, 429052, 428665, 428278, + 427892, 427506, 427120, 426735, 426350, 425965, 425581, 425197, + 424813, 424430, 424047, 423665, 423283, 422901, 422519, 422138, + 421757, 421377, 420997, 420617, 420237, 419858, 419479, 419101, + 418723, 418345, 417968, 417591, 417214, 416838, 416462, 416086, + 415711, 415336, 414961, 414586, 414212, 413839, 413465, 413092, + 412720, 412347, 411975, 411604, 411232, 410862, 410491, 410121, + 409751, 409381, 409012, 408643, 408274, 407906, 407538, 407170, + 406803, 406436, 406069, 405703, 405337, 404971, 404606, 404241, + 403876, 403512, 403148, 402784, 402421, 402058, 401695, 401333, + 400970, 400609, 400247, 399886, 399525, 399165, 398805, 398445, + 398086, 397727, 397368, 397009, 396651, 396293, 395936, 395579, + 395222, 394865, 394509, 394153, 393798, 393442, 393087, 392733, + 392378, 392024, 391671, 391317, 390964, 390612, 390259, 389907, + 389556, 389204, 388853, 388502, 388152, 387802, 387452, 387102, + 386753, 386404, 386056, 385707, 385359, 385012, 384664, 384317, + 383971, 383624, 383278, 382932, 382587, 382242, 381897, 381552, + 381208, 380864, 380521, 380177, 379834, 379492, 379149, 378807, + 378466, 378124, 377783, 377442, 377102, 376762, 376422, 376082, + 375743, 375404, 375065, 374727, 374389, 374051, 373714, 373377, + 373040, 372703, 372367, 372031, 371695, 371360, 371025, 370690, + 370356, 370022, 369688, 369355, 369021, 368688, 368356, 368023, + 367691, 367360, 367028, 366697, 366366, 366036, 365706, 365376, + 365046, 364717, 364388, 364059, 363731, 363403, 363075, 362747, + 362420, 362093, 361766, 361440, 361114, 360788, 360463, 360137, + 359813, 359488, 359164, 358840, 358516, 358193, 357869, 357547, + 357224, 356902, 356580, 356258, 355937, 355616, 355295, 354974, + 354654, 354334, 354014, 353695, 353376, 353057, 352739, 352420, + 352103, 351785, 351468, 351150, 350834, 350517, 350201, 349885, + 349569, 349254, 348939, 348624, 348310, 347995, 347682, 347368, + 347055, 346741, 346429, 346116, 345804, 345492, 345180, 344869, + 344558, 344247, 343936, 343626, 343316, 343006, 342697, 342388, + 342079, 341770, 341462, 341154, 340846, 340539, 340231, 339924, + 339618, 339311, 339005, 338700, 338394, 338089, 337784, 337479, + 337175, 336870, 336566, 336263, 335959, 335656, 335354, 335051, + 334749, 334447, 334145, 333844, 333542, 333242, 332941, 332641, + 332341, 332041, 331741, 331442, 331143, 330844, 330546, 330247, + 329950, 329652, 329355, 329057, 328761, 328464, 328168, 327872, + 327576, 327280, 326985, 326690, 326395, 326101, 325807, 325513, + 325219, 324926, 324633, 324340, 324047, 323755, 323463, 323171, + 322879, 322588, 322297, 322006, 321716, 321426, 321136, 320846, + 320557, 320267, 319978, 319690, 319401, 319113, 318825, 318538, + 318250, 317963, 317676, 317390, 317103, 316817, 316532, 316246, + 315961, 315676, 315391, 315106, 314822, 314538, 314254, 313971, + 313688, 313405, 313122, 312839, 312557, 312275, 311994, 311712, + 311431, 311150, 310869, 310589, 310309, 310029, 309749, 309470, + 309190, 308911, 308633, 308354, 308076, 307798, 307521, 307243, + 306966, 306689, 306412, 306136, 305860, 305584, 305308, 305033, + 304758, 304483, 304208, 303934, 303659, 303385, 303112, 302838, + 302565, 302292, 302019, 301747, 301475, 301203, 300931, 300660, + 300388, 300117, 299847, 299576, 299306, 299036, 298766, 298497, + 298227, 297958, 297689, 297421, 297153, 296884, 296617, 296349, + 296082, 295815, 295548, 295281, 295015, 294749, 294483, 294217, + 293952, 293686, 293421, 293157, 292892, 292628, 292364, 292100, + 291837, 291574, 291311, 291048, 290785, 290523, 290261, 289999, + 289737, 289476, 289215, 288954, 288693, 288433, 288173, 287913, + 287653, 287393, 287134, 286875, 286616, 286358, 286099, 285841, + 285583, 285326, 285068, 284811, 284554, 284298, 284041, 283785, + 283529, 283273, 283017, 282762, 282507, 282252, 281998, 281743, + 281489, 281235, 280981, 280728, 280475, 280222, 279969, 279716, + 279464, 279212, 278960, 278708, 278457, 278206, 277955, 277704, + 277453, 277203, 276953, 276703, 276453, 276204, 275955, 275706, + 275457, 275209, 274960, 274712, 274465, 274217, 273970, 273722, + 273476, 273229, 272982, 272736, 272490, 272244, 271999, 271753, + 271508, 271263, 271018, 270774, 270530, 270286, 270042, 269798, + 269555, 269312, 269069, 268826, 268583, 268341, 268099, 267857 }; -uint16_t CPTables::old_period_table[OCTAVE*2]={ +uint16_t CPTables::old_period_table[OCTAVE * 2] = { - 0x6b00, 0x6800, 0x6500, 0x6220, 0x5f50, 0x5c80, - 0x5a00, 0x5740, 0x54d0, 0x5260, 0x5010, 0x4dc0, - 0x4b90, 0x4960, 0x4750, 0x4540, 0x4350, 0x4160, - 0x3f90, 0x3dc0, 0x3c10, 0x3a40, 0x38b0, 0x3700 + 0x6b00, 0x6800, 0x6500, 0x6220, 0x5f50, 0x5c80, + 0x5a00, 0x5740, 0x54d0, 0x5260, 0x5010, 0x4dc0, + 0x4b90, 0x4960, 0x4750, 0x4540, 0x4350, 0x4160, + 0x3f90, 0x3dc0, 0x3c10, 0x3a40, 0x38b0, 0x3700 }; -#define LOGFAC 2*16 +#define LOGFAC 2 * 16 -uint16_t CPTables::log_table[104]= { - LOGFAC*907,LOGFAC*900,LOGFAC*894,LOGFAC*887, - LOGFAC*881,LOGFAC*875,LOGFAC*868,LOGFAC*862, - LOGFAC*856,LOGFAC*850,LOGFAC*844,LOGFAC*838, - LOGFAC*832,LOGFAC*826,LOGFAC*820,LOGFAC*814, - LOGFAC*808,LOGFAC*802,LOGFAC*796,LOGFAC*791, - LOGFAC*785,LOGFAC*779,LOGFAC*774,LOGFAC*768, - LOGFAC*762,LOGFAC*757,LOGFAC*752,LOGFAC*746, - LOGFAC*741,LOGFAC*736,LOGFAC*730,LOGFAC*725, - LOGFAC*720,LOGFAC*715,LOGFAC*709,LOGFAC*704, - LOGFAC*699,LOGFAC*694,LOGFAC*689,LOGFAC*684, - LOGFAC*678,LOGFAC*675,LOGFAC*670,LOGFAC*665, - LOGFAC*660,LOGFAC*655,LOGFAC*651,LOGFAC*646, - LOGFAC*640,LOGFAC*636,LOGFAC*632,LOGFAC*628, - LOGFAC*623,LOGFAC*619,LOGFAC*614,LOGFAC*610, - LOGFAC*604,LOGFAC*601,LOGFAC*597,LOGFAC*592, - LOGFAC*588,LOGFAC*584,LOGFAC*580,LOGFAC*575, - LOGFAC*570,LOGFAC*567,LOGFAC*563,LOGFAC*559, - LOGFAC*555,LOGFAC*551,LOGFAC*547,LOGFAC*543, - LOGFAC*538,LOGFAC*535,LOGFAC*532,LOGFAC*528, - LOGFAC*524,LOGFAC*520,LOGFAC*516,LOGFAC*513, - LOGFAC*508,LOGFAC*505,LOGFAC*502,LOGFAC*498, - LOGFAC*494,LOGFAC*491,LOGFAC*487,LOGFAC*484, - LOGFAC*480,LOGFAC*477,LOGFAC*474,LOGFAC*470, - LOGFAC*467,LOGFAC*463,LOGFAC*460,LOGFAC*457, - LOGFAC*453,LOGFAC*450,LOGFAC*447,LOGFAC*443, - LOGFAC*440,LOGFAC*437,LOGFAC*434,LOGFAC*431 +uint16_t CPTables::log_table[104] = { + LOGFAC * 907, LOGFAC * 900, LOGFAC * 894, LOGFAC * 887, + LOGFAC * 881, LOGFAC * 875, LOGFAC * 868, LOGFAC * 862, + LOGFAC * 856, LOGFAC * 850, LOGFAC * 844, LOGFAC * 838, + LOGFAC * 832, LOGFAC * 826, LOGFAC * 820, LOGFAC * 814, + LOGFAC * 808, LOGFAC * 802, LOGFAC * 796, LOGFAC * 791, + LOGFAC * 785, LOGFAC * 779, LOGFAC * 774, LOGFAC * 768, + LOGFAC * 762, LOGFAC * 757, LOGFAC * 752, LOGFAC * 746, + LOGFAC * 741, LOGFAC * 736, LOGFAC * 730, LOGFAC * 725, + LOGFAC * 720, LOGFAC * 715, LOGFAC * 709, LOGFAC * 704, + LOGFAC * 699, LOGFAC * 694, LOGFAC * 689, LOGFAC * 684, + LOGFAC * 678, LOGFAC * 675, LOGFAC * 670, LOGFAC * 665, + LOGFAC * 660, LOGFAC * 655, LOGFAC * 651, LOGFAC * 646, + LOGFAC * 640, LOGFAC * 636, LOGFAC * 632, LOGFAC * 628, + LOGFAC * 623, LOGFAC * 619, LOGFAC * 614, LOGFAC * 610, + LOGFAC * 604, LOGFAC * 601, LOGFAC * 597, LOGFAC * 592, + LOGFAC * 588, LOGFAC * 584, LOGFAC * 580, LOGFAC * 575, + LOGFAC * 570, LOGFAC * 567, LOGFAC * 563, LOGFAC * 559, + LOGFAC * 555, LOGFAC * 551, LOGFAC * 547, LOGFAC * 543, + LOGFAC * 538, LOGFAC * 535, LOGFAC * 532, LOGFAC * 528, + LOGFAC * 524, LOGFAC * 520, LOGFAC * 516, LOGFAC * 513, + LOGFAC * 508, LOGFAC * 505, LOGFAC * 502, LOGFAC * 498, + LOGFAC * 494, LOGFAC * 491, LOGFAC * 487, LOGFAC * 484, + LOGFAC * 480, LOGFAC * 477, LOGFAC * 474, LOGFAC * 470, + LOGFAC * 467, LOGFAC * 463, LOGFAC * 460, LOGFAC * 457, + LOGFAC * 453, LOGFAC * 450, LOGFAC * 447, LOGFAC * 443, + LOGFAC * 440, LOGFAC * 437, LOGFAC * 434, LOGFAC * 431 }; - - -int32_t CPTables::get_linear_period(uint16_t note,int32_t fine) { +int32_t CPTables::get_linear_period(uint16_t note, int32_t fine) { int32_t t; - t=(24L*OCTAVE-(int32_t)note)*32L-(fine>>1); + t = (24L * OCTAVE - (int32_t)note) * 32L - (fine >> 1); return t; } -static int s3m_period_table[12]={1712,1616,1524,1440,1356,1280,1208,1140,1076,1016,960,907}; +static int s3m_period_table[12] = { 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 907 }; +int32_t CPTables::get_log_period(uint16_t note, int32_t p_c5freq) { -int32_t CPTables::get_log_period(uint16_t note,int32_t p_c5freq) { - - return (8363L * 16 * s3m_period_table[note%12] >> (note/12)) / p_c5freq; - + return (8363L * 16 * s3m_period_table[note % 12] >> (note / 12)) / p_c5freq; } /* @@ -213,42 +209,42 @@ int32_t CPTables::get_log_period(uint16_t note,int32_t p_c5freq) } */ -int32_t CPTables::get_old_period(uint16_t note,int32_t speed) { +int32_t CPTables::get_old_period(uint16_t note, int32_t speed) { - uint16_t n,o,res; + uint16_t n, o, res; -// if (!speed) { + // if (!speed) { - // return 4242; /* <- prevent divide overflow */ - // } + // return 4242; /* <- prevent divide overflow */ + // } - n=note%(2*OCTAVE); - o=note/(2*OCTAVE); + n = note % (2 * OCTAVE); + o = note / (2 * OCTAVE); - res=((8363L*(int32_t)old_period_table[n])>>o)/((old_period_table[17]>>1)+(speed<<2)); /*/(128-speed)*/; + res = ((8363L * (int32_t)old_period_table[n]) >> o) / ((old_period_table[17] >> 1) + (speed << 2)); /*/(128-speed)*/ + ; - return res; + return res; } int32_t CPTables::get_linear_frequency(int32_t period) { - int32_t shift_value=(((int32_t)period/768)-2); - if (shift_value>0) { + int32_t shift_value = (((int32_t)period / 768) - 2); + if (shift_value > 0) { - return linear_period_to_freq_tab[period%768]>>shift_value; + return linear_period_to_freq_tab[period % 768] >> shift_value; } else { - shift_value=0-shift_value; - return linear_period_to_freq_tab[period%768]<<shift_value; + shift_value = 0 - shift_value; + return linear_period_to_freq_tab[period % 768] << shift_value; } } int32_t CPTables::get_old_frequency(int32_t period) { - return (8363L*1712L)/(period?period:1); - + return (8363L * 1712L) / (period ? period : 1); } -CPTables::CPTables(){ +CPTables::CPTables() { } -CPTables::~CPTables(){ +CPTables::~CPTables() { } diff --git a/modules/chibi/cp_tables.h b/modules/chibi/cp_tables.h index 4baa1c648..958e57859 100644 --- a/modules/chibi/cp_tables.h +++ b/modules/chibi/cp_tables.h @@ -46,19 +46,18 @@ conversion utilities class CPTables { public: + enum { OCTAVE = 12 }; - enum { OCTAVE=12 }; - - static uint16_t old_period_table[OCTAVE*2]; + static uint16_t old_period_table[OCTAVE * 2]; static uint16_t log_table[104]; static int32_t linear_period_to_freq_tab[768]; - static int32_t get_old_period(uint16_t note,int32_t speed); - static int32_t get_amiga_period(uint16_t note,int32_t fine); - static int32_t get_linear_period(uint16_t note,int32_t fine); - static int32_t get_linear_frequency(int32_t period); + static int32_t get_old_period(uint16_t note, int32_t speed); + static int32_t get_amiga_period(uint16_t note, int32_t fine); + static int32_t get_linear_period(uint16_t note, int32_t fine); + static int32_t get_linear_frequency(int32_t period); static int32_t get_old_frequency(int32_t period); - static int32_t get_log_period(uint16_t note,int32_t p_c5freq); + static int32_t get_log_period(uint16_t note, int32_t p_c5freq); CPTables(); ~CPTables(); diff --git a/modules/chibi/event_stream_chibi.cpp b/modules/chibi/event_stream_chibi.cpp index d910d86d7..bede079a3 100644 --- a/modules/chibi/event_stream_chibi.cpp +++ b/modules/chibi/event_stream_chibi.cpp @@ -28,55 +28,55 @@ /*************************************************************************/ #include "event_stream_chibi.h" #include "cp_loader_it.h" -#include "cp_loader_xm.h" -#include "cp_loader_s3m.h" #include "cp_loader_mod.h" +#include "cp_loader_s3m.h" +#include "cp_loader_xm.h" static CPSampleManagerImpl *sample_manager; static ResourceFormatLoaderChibi *resource_loader; -CPSample_ID CPSampleManagerImpl::create(bool p_16bits,bool p_stereo,int32_t p_len) { +CPSample_ID CPSampleManagerImpl::create(bool p_16bits, bool p_stereo, int32_t p_len) { - AudioServer::SampleFormat sf=p_16bits?AudioServer::SAMPLE_FORMAT_PCM16:AudioServer::SAMPLE_FORMAT_PCM8; + AudioServer::SampleFormat sf = p_16bits ? AudioServer::SAMPLE_FORMAT_PCM16 : AudioServer::SAMPLE_FORMAT_PCM8; - SampleData *sd = memnew( SampleData ); - sd->rid = AudioServer::get_singleton()->sample_create(sf,p_stereo,p_len); - sd->stereo=p_stereo; - sd->len=p_len; - sd->is16=p_16bits; - sd->mixfreq=44100; - sd->loop_begin=0; - sd->loop_end=0; - sd->loop_type=CP_LOOP_NONE; - sd->locks=0; + SampleData *sd = memnew(SampleData); + sd->rid = AudioServer::get_singleton()->sample_create(sf, p_stereo, p_len); + sd->stereo = p_stereo; + sd->len = p_len; + sd->is16 = p_16bits; + sd->mixfreq = 44100; + sd->loop_begin = 0; + sd->loop_end = 0; + sd->loop_type = CP_LOOP_NONE; + sd->locks = 0; #ifdef DEBUG_ENABLED valid.insert(sd); #endif CPSample_ID sid; - sid._private=sd; + sid._private = sd; return sid; } -void CPSampleManagerImpl::recreate(CPSample_ID p_id,bool p_16bits,bool p_stereo,int32_t p_len){ +void CPSampleManagerImpl::recreate(CPSample_ID p_id, bool p_16bits, bool p_stereo, int32_t p_len) { - AudioServer::SampleFormat sf=p_16bits?AudioServer::SAMPLE_FORMAT_PCM16:AudioServer::SAMPLE_FORMAT_PCM8; - SampleData *sd=_getsd(p_id); + AudioServer::SampleFormat sf = p_16bits ? AudioServer::SAMPLE_FORMAT_PCM16 : AudioServer::SAMPLE_FORMAT_PCM8; + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif AudioServer::get_singleton()->free(sd->rid); - sd->rid = AudioServer::get_singleton()->sample_create(sf,p_stereo,p_len); - sd->stereo=p_stereo; - sd->len=p_len; - sd->is16=p_16bits; - sd->mixfreq=44100; - sd->loop_begin=0; - sd->loop_end=0; - sd->loop_type=CP_LOOP_NONE; + sd->rid = AudioServer::get_singleton()->sample_create(sf, p_stereo, p_len); + sd->stereo = p_stereo; + sd->len = p_len; + sd->is16 = p_16bits; + sd->mixfreq = 44100; + sd->loop_begin = 0; + sd->loop_end = 0; + sd->loop_type = CP_LOOP_NONE; } -void CPSampleManagerImpl::destroy(CPSample_ID p_id){ +void CPSampleManagerImpl::destroy(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); valid.erase(sd); @@ -85,61 +85,56 @@ void CPSampleManagerImpl::destroy(CPSample_ID p_id){ memdelete(sd); } -bool CPSampleManagerImpl::check(CPSample_ID p_id){ +bool CPSampleManagerImpl::check(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED return valid.has(sd); #else - return _getsd(p_id)!=NULL; + return _getsd(p_id) != NULL; #endif } -void CPSampleManagerImpl::set_c5_freq(CPSample_ID p_id,int32_t p_freq){ +void CPSampleManagerImpl::set_c5_freq(CPSample_ID p_id, int32_t p_freq) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif - sd->mixfreq=p_freq; - AudioServer::get_singleton()->sample_set_mix_rate(sd->rid,p_freq); - + sd->mixfreq = p_freq; + AudioServer::get_singleton()->sample_set_mix_rate(sd->rid, p_freq); } -void CPSampleManagerImpl::set_loop_begin(CPSample_ID p_id,int32_t p_begin){ +void CPSampleManagerImpl::set_loop_begin(CPSample_ID p_id, int32_t p_begin) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif - sd->loop_begin=p_begin; - AudioServer::get_singleton()->sample_set_loop_begin(sd->rid,p_begin); - + sd->loop_begin = p_begin; + AudioServer::get_singleton()->sample_set_loop_begin(sd->rid, p_begin); } -void CPSampleManagerImpl::set_loop_end(CPSample_ID p_id,int32_t p_end){ +void CPSampleManagerImpl::set_loop_end(CPSample_ID p_id, int32_t p_end) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif - sd->loop_end=p_end; - AudioServer::get_singleton()->sample_set_loop_end(sd->rid,p_end); - + sd->loop_end = p_end; + AudioServer::get_singleton()->sample_set_loop_end(sd->rid, p_end); } -void CPSampleManagerImpl::set_loop_type(CPSample_ID p_id,CPSample_Loop_Type p_type){ +void CPSampleManagerImpl::set_loop_type(CPSample_ID p_id, CPSample_Loop_Type p_type) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif - sd->loop_type=p_type; - AudioServer::get_singleton()->sample_set_loop_format(sd->rid,AudioServer::SampleLoopFormat(p_type)); - - + sd->loop_type = p_type; + AudioServer::get_singleton()->sample_set_loop_format(sd->rid, AudioServer::SampleLoopFormat(p_type)); } -void CPSampleManagerImpl::set_chunk(CPSample_ID p_id,int32_t p_index,void *p_data,int p_data_len){ +void CPSampleManagerImpl::set_chunk(CPSample_ID p_id, int32_t p_index, void *p_data, int p_data_len) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif @@ -147,127 +142,121 @@ void CPSampleManagerImpl::set_chunk(CPSample_ID p_id,int32_t p_index,void *p_dat ERR_FAIL(); } +int32_t CPSampleManagerImpl::get_loop_begin(CPSample_ID p_id) { -int32_t CPSampleManagerImpl::get_loop_begin(CPSample_ID p_id){ - - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif return sd->loop_begin; - } -int32_t CPSampleManagerImpl::get_loop_end(CPSample_ID p_id){ +int32_t CPSampleManagerImpl::get_loop_end(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif return sd->loop_end; } -CPSample_Loop_Type CPSampleManagerImpl::get_loop_type(CPSample_ID p_id){ +CPSample_Loop_Type CPSampleManagerImpl::get_loop_type(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),CP_LOOP_NONE); + ERR_FAIL_COND_V(!valid.has(sd), CP_LOOP_NONE); #endif return sd->loop_type; } -int32_t CPSampleManagerImpl::get_c5_freq(CPSample_ID p_id){ +int32_t CPSampleManagerImpl::get_c5_freq(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif return sd->mixfreq; } -int32_t CPSampleManagerImpl::get_size(CPSample_ID p_id){ +int32_t CPSampleManagerImpl::get_size(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif return sd->len; - } -bool CPSampleManagerImpl::is_16bits(CPSample_ID p_id){ +bool CPSampleManagerImpl::is_16bits(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),false); + ERR_FAIL_COND_V(!valid.has(sd), false); #endif return sd->is16; - } -bool CPSampleManagerImpl::is_stereo(CPSample_ID p_id){ +bool CPSampleManagerImpl::is_stereo(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),false); + ERR_FAIL_COND_V(!valid.has(sd), false); #endif return sd->stereo; - - } -bool CPSampleManagerImpl::lock_data(CPSample_ID p_id){ +bool CPSampleManagerImpl::lock_data(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif sd->locks++; - if (sd->locks==1) { - sd->lock=AudioServer::get_singleton()->sample_get_data(sd->rid); - sd->w=sd->lock.write(); + if (sd->locks == 1) { + sd->lock = AudioServer::get_singleton()->sample_get_data(sd->rid); + sd->w = sd->lock.write(); } return true; } -void *CPSampleManagerImpl::get_data(CPSample_ID p_id){ +void *CPSampleManagerImpl::get_data(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif - ERR_FAIL_COND_V(sd->locks==0,0); + ERR_FAIL_COND_V(sd->locks == 0, 0); return sd->w.ptr(); } -int16_t CPSampleManagerImpl::get_data(CPSample_ID p_id, int p_sample, int p_channel){ +int16_t CPSampleManagerImpl::get_data(CPSample_ID p_id, int p_sample, int p_channel) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V(!valid.has(sd),0); + ERR_FAIL_COND_V(!valid.has(sd), 0); #endif ERR_FAIL_V(0); lock_data(p_id); - int sofs = sd->stereo ? 2:1; - uint16_t v=0; + int sofs = sd->stereo ? 2 : 1; + uint16_t v = 0; if (sd->is16) { - int16_t *p=(int16_t*)sd->w.ptr(); - v=p[p_sample*sofs+p_channel]; + int16_t *p = (int16_t *)sd->w.ptr(); + v = p[p_sample * sofs + p_channel]; } else { - int8_t *p=(int8_t*)sd->w.ptr(); - v=p[p_sample*sofs+p_channel]; + int8_t *p = (int8_t *)sd->w.ptr(); + v = p[p_sample * sofs + p_channel]; } unlock_data(p_id); return v; } -void CPSampleManagerImpl::set_data(CPSample_ID p_id, int p_sample, int16_t p_data,int p_channel){ +void CPSampleManagerImpl::set_data(CPSample_ID p_id, int p_sample, int16_t p_data, int p_channel) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif @@ -275,38 +264,37 @@ void CPSampleManagerImpl::set_data(CPSample_ID p_id, int p_sample, int16_t p_dat ERR_FAIL(); lock_data(p_id); - int sofs = sd->stereo ? 2:1; + int sofs = sd->stereo ? 2 : 1; if (sd->is16) { - int16_t *p=(int16_t*)sd->w.ptr(); - p[p_sample*sofs+p_channel]=p_data; + int16_t *p = (int16_t *)sd->w.ptr(); + p[p_sample * sofs + p_channel] = p_data; } else { - int8_t *p=(int8_t*)sd->w.ptr(); - p[p_sample*sofs+p_channel]=p_data; + int8_t *p = (int8_t *)sd->w.ptr(); + p[p_sample * sofs + p_channel] = p_data; } unlock_data(p_id); - } -void CPSampleManagerImpl::unlock_data(CPSample_ID p_id){ +void CPSampleManagerImpl::unlock_data(CPSample_ID p_id) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif - ERR_FAIL_COND(sd->locks==0); + ERR_FAIL_COND(sd->locks == 0); sd->locks--; - if (sd->locks==0) { - sd->w=DVector<uint8_t>::Write(); - AudioServer::get_singleton()->sample_set_data(sd->rid,sd->lock); - sd->lock=DVector<uint8_t>(); + if (sd->locks == 0) { + sd->w = DVector<uint8_t>::Write(); + AudioServer::get_singleton()->sample_set_data(sd->rid, sd->lock); + sd->lock = DVector<uint8_t>(); } } -void CPSampleManagerImpl::get_chunk(CPSample_ID p_id,int32_t p_index,void *p_data,int p_data_len) { +void CPSampleManagerImpl::get_chunk(CPSample_ID p_id, int32_t p_index, void *p_data, int p_data_len) { - SampleData *sd=_getsd(p_id); + SampleData *sd = _getsd(p_id); #ifdef DEBUG_ENABLED ERR_FAIL_COND(!valid.has(sd)); #endif @@ -314,435 +302,399 @@ void CPSampleManagerImpl::get_chunk(CPSample_ID p_id,int32_t p_index,void *p_dat ERR_FAIL(); } - /** MIXER **/ void CPMixerImpl::set_callback_interval(int p_interval_us) { - callback_interval=p_interval_us; + callback_interval = p_interval_us; } -void CPMixerImpl::set_callback(void (*p_callback)(void*),void *p_userdata) { +void CPMixerImpl::set_callback(void (*p_callback)(void *), void *p_userdata) { - callback=p_callback; - userdata=p_userdata; + callback = p_callback; + userdata = p_userdata; } -void CPMixerImpl::setup_voice(int p_voice_index,CPSample_ID p_sample_id,int32_t p_start_index) { +void CPMixerImpl::setup_voice(int p_voice_index, CPSample_ID p_sample_id, int32_t p_start_index) { - Voice &v=voices[p_voice_index]; - if (v.channel!=AudioMixer::INVALID_CHANNEL) { + Voice &v = voices[p_voice_index]; + if (v.channel != AudioMixer::INVALID_CHANNEL) { mixer->channel_free(v.channel); } - v.channel=mixer->channel_alloc(sample_manager->get_rid(p_sample_id)); - v.freq_mult = sample_manager->get_c5_freq(p_sample_id)/261.6255653006; + v.channel = mixer->channel_alloc(sample_manager->get_rid(p_sample_id)); + v.freq_mult = sample_manager->get_c5_freq(p_sample_id) / 261.6255653006; v.sample = p_sample_id; } -void CPMixerImpl::stop_voice(int p_voice_index) { +void CPMixerImpl::stop_voice(int p_voice_index) { - Voice &v=voices[p_voice_index]; - if (v.channel==AudioMixer::INVALID_CHANNEL) + Voice &v = voices[p_voice_index]; + if (v.channel == AudioMixer::INVALID_CHANNEL) return; mixer->channel_free(v.channel); - v.channel=AudioMixer::INVALID_CHANNEL; - + v.channel = AudioMixer::INVALID_CHANNEL; } -void CPMixerImpl::set_voice_frequency(int p_voice_index,int32_t p_freq) { +void CPMixerImpl::set_voice_frequency(int p_voice_index, int32_t p_freq) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND(v.channel == AudioMixer::INVALID_CHANNEL); float f = p_freq / 256.0; - f*=pitch_scale; - mixer->channel_set_mix_rate(v.channel,f * v.freq_mult ); + f *= pitch_scale; + mixer->channel_set_mix_rate(v.channel, f * v.freq_mult); } -void CPMixerImpl::set_voice_panning(int p_voice_index,int p_pan) { +void CPMixerImpl::set_voice_panning(int p_voice_index, int p_pan) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); - if (p_pan==CP_PAN_SURROUND) - p_pan=CP_PAN_CENTER; + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND(v.channel == AudioMixer::INVALID_CHANNEL); + if (p_pan == CP_PAN_SURROUND) + p_pan = CP_PAN_CENTER; float p = p_pan / 256.0; - mixer->channel_set_pan(v.channel,p); - + mixer->channel_set_pan(v.channel, p); } -void CPMixerImpl::set_voice_volume(int p_voice_index,int p_vol) { +void CPMixerImpl::set_voice_volume(int p_voice_index, int p_vol) { - - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); - float vol = p_vol/512.0; - vol*=voice_scale; - mixer->channel_set_volume(v.channel,vol); - mixer->channel_set_reverb(v.channel,reverb_type,vol*v.reverb); + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND(v.channel == AudioMixer::INVALID_CHANNEL); + float vol = p_vol / 512.0; + vol *= voice_scale; + mixer->channel_set_volume(v.channel, vol); + mixer->channel_set_reverb(v.channel, reverb_type, vol * v.reverb); } -void CPMixerImpl::set_voice_filter(int p_voice_index,bool p_enabled,uint8_t p_cutoff, uint8_t p_resonance ){ - - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); +void CPMixerImpl::set_voice_filter(int p_voice_index, bool p_enabled, uint8_t p_cutoff, uint8_t p_resonance) { + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND(v.channel == AudioMixer::INVALID_CHANNEL); } -void CPMixerImpl::set_voice_reverb_send(int p_voice_index,int p_reverb){ +void CPMixerImpl::set_voice_reverb_send(int p_voice_index, int p_reverb) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); - v.reverb=p_reverb/255.0; + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND(v.channel == AudioMixer::INVALID_CHANNEL); + v.reverb = p_reverb / 255.0; //mixer->channel_set_reverb(v.channel,reverb_type,p_reverb/255.0); - } -void CPMixerImpl::set_voice_chorus_send(int p_voice_index,int p_chorus){ - - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); - mixer->channel_set_chorus(v.channel,p_chorus/255.0); +void CPMixerImpl::set_voice_chorus_send(int p_voice_index, int p_chorus) { + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND(v.channel == AudioMixer::INVALID_CHANNEL); + mixer->channel_set_chorus(v.channel, p_chorus / 255.0); } +void CPMixerImpl::set_reverb_mode(ReverbMode p_mode) { -void CPMixerImpl::set_reverb_mode(ReverbMode p_mode){ - -// Voice &v=voices[p_voice_index]; -// ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); - switch(p_mode) { - case CPMixer::REVERB_MODE_STUDIO_SMALL: reverb_type=AudioMixer::REVERB_SMALL; break; - case CPMixer::REVERB_MODE_STUDIO_MEDIUM: reverb_type=AudioMixer::REVERB_MEDIUM; break; - case CPMixer::REVERB_MODE_STUDIO_LARGE: reverb_type=AudioMixer::REVERB_LARGE; break; - case CPMixer::REVERB_MODE_HALL: reverb_type=AudioMixer::REVERB_HALL; break; - default: reverb_type=AudioMixer::REVERB_SMALL; break; + // Voice &v=voices[p_voice_index]; + // ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); + switch (p_mode) { + case CPMixer::REVERB_MODE_STUDIO_SMALL: reverb_type = AudioMixer::REVERB_SMALL; break; + case CPMixer::REVERB_MODE_STUDIO_MEDIUM: reverb_type = AudioMixer::REVERB_MEDIUM; break; + case CPMixer::REVERB_MODE_STUDIO_LARGE: reverb_type = AudioMixer::REVERB_LARGE; break; + case CPMixer::REVERB_MODE_HALL: reverb_type = AudioMixer::REVERB_HALL; break; + default: reverb_type = AudioMixer::REVERB_SMALL; break; } - } -void CPMixerImpl::set_chorus_params(unsigned int p_delay_ms,unsigned int p_separation_ms,unsigned int p_depth_ms10,unsigned int p_speed_hz10){ - -// Voice &v=voices[p_voice_index]; -// ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); +void CPMixerImpl::set_chorus_params(unsigned int p_delay_ms, unsigned int p_separation_ms, unsigned int p_depth_ms10, unsigned int p_speed_hz10) { + // Voice &v=voices[p_voice_index]; + // ERR_FAIL_COND(v.channel==AudioMixer::INVALID_CHANNEL); } - - /* Info retrieving */ int32_t CPMixerImpl::get_voice_sample_pos_index(int p_voice_index) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND_V(v.channel==AudioMixer::INVALID_CHANNEL,0); + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND_V(v.channel == AudioMixer::INVALID_CHANNEL, 0); return 0; - } int CPMixerImpl::get_voice_panning(int p_voice_index) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND_V(!is_voice_active(p_voice_index),0); - return mixer->channel_get_pan(v.channel)*CP_PAN_RIGHT; - + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND_V(!is_voice_active(p_voice_index), 0); + return mixer->channel_get_pan(v.channel) * CP_PAN_RIGHT; } int CPMixerImpl::get_voice_volume(int p_voice_index) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND_V(!is_voice_active(p_voice_index),0); + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND_V(!is_voice_active(p_voice_index), 0); return mixer->channel_get_volume(v.channel); - - } CPSample_ID CPMixerImpl::get_voice_sample_id(int p_voice_index) { - Voice &v=voices[p_voice_index]; - ERR_FAIL_COND_V(v.channel==AudioMixer::INVALID_CHANNEL,CPSample_ID()); + Voice &v = voices[p_voice_index]; + ERR_FAIL_COND_V(v.channel == AudioMixer::INVALID_CHANNEL, CPSample_ID()); return v.sample; - - } -bool CPMixerImpl::is_voice_active(int p_voice_index){ +bool CPMixerImpl::is_voice_active(int p_voice_index) { - Voice &v=voices[p_voice_index]; - if (v.channel==AudioMixer::INVALID_CHANNEL) + Voice &v = voices[p_voice_index]; + if (v.channel == AudioMixer::INVALID_CHANNEL) return false; if (!mixer->channel_is_valid(v.channel)) - v.channel=AudioMixer::INVALID_CHANNEL; + v.channel = AudioMixer::INVALID_CHANNEL; - return v.channel!=AudioMixer::INVALID_CHANNEL; + return v.channel != AudioMixer::INVALID_CHANNEL; } -void CPMixerImpl::process_usecs(int p_usec,float p_volume,float p_pitch_scale,float p_tempo_scale) { +void CPMixerImpl::process_usecs(int p_usec, float p_volume, float p_pitch_scale, float p_tempo_scale) { - ERR_FAIL_COND(callback_interval==0); + ERR_FAIL_COND(callback_interval == 0); //update this somewhere - pitch_scale=p_pitch_scale; - tempo_scale=p_tempo_scale; - voice_scale = AudioServer::get_singleton()->get_event_voice_global_volume_scale()*p_volume; - while(p_usec) { + pitch_scale = p_pitch_scale; + tempo_scale = p_tempo_scale; + voice_scale = AudioServer::get_singleton()->get_event_voice_global_volume_scale() * p_volume; + while (p_usec) { - if (p_usec>=callback_timeout) { + if (p_usec >= callback_timeout) { - p_usec-=callback_timeout; - callback_timeout=0; + p_usec -= callback_timeout; + callback_timeout = 0; if (callback) { callback(userdata); } - callback_timeout=callback_interval*(1.0/p_tempo_scale); + callback_timeout = callback_interval * (1.0 / p_tempo_scale); } else { - callback_timeout-=p_usec; - p_usec=0; + callback_timeout -= p_usec; + p_usec = 0; } } } - CPMixerImpl::CPMixerImpl(AudioMixer *p_mixer) { - callback_interval=1; - callback_timeout=0; - userdata=0; - callback=0; - tempo_scale=1.0; - pitch_scale=1.0; - mixer=p_mixer; + callback_interval = 1; + callback_timeout = 0; + userdata = 0; + callback = 0; + tempo_scale = 1.0; + pitch_scale = 1.0; + mixer = p_mixer; voice_scale = AudioServer::get_singleton()->get_event_voice_global_volume_scale(); reverb_type = AudioMixer::REVERB_SMALL; - } /** FILE ACCESS WRAPPER **/ - CPFileAccessWrapperImpl::Error CPFileAccessWrapperImpl::open(const char *p_filename, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags&WRITE,ERROR_WRITING_FILE); + ERR_FAIL_COND_V(p_mode_flags & WRITE, ERROR_WRITING_FILE); close(); - f = FileAccess::open(String::utf8(p_filename),p_mode_flags); + f = FileAccess::open(String::utf8(p_filename), p_mode_flags); if (!f) return ERROR_FILE_NOT_FOUND; return OK; } -void CPFileAccessWrapperImpl::close(){ +void CPFileAccessWrapperImpl::close() { if (f) memdelete(f); - f=NULL; - - + f = NULL; } -void CPFileAccessWrapperImpl::seek(uint32_t p_position){ +void CPFileAccessWrapperImpl::seek(uint32_t p_position) { f->seek(p_position); } -void CPFileAccessWrapperImpl::seek_end(){ +void CPFileAccessWrapperImpl::seek_end() { f->seek_end(); } -uint32_t CPFileAccessWrapperImpl::get_pos(){ +uint32_t CPFileAccessWrapperImpl::get_pos() { return f->get_pos(); } -bool CPFileAccessWrapperImpl::eof_reached(){ +bool CPFileAccessWrapperImpl::eof_reached() { return f->eof_reached(); } -uint8_t CPFileAccessWrapperImpl::get_byte(){ +uint8_t CPFileAccessWrapperImpl::get_byte() { return f->get_8(); } -void CPFileAccessWrapperImpl::get_byte_array(uint8_t *p_dest,int p_elements){ +void CPFileAccessWrapperImpl::get_byte_array(uint8_t *p_dest, int p_elements) { - f->get_buffer(p_dest,p_elements); + f->get_buffer(p_dest, p_elements); } -void CPFileAccessWrapperImpl::get_word_array(uint16_t *p_dest,int p_elements){ +void CPFileAccessWrapperImpl::get_word_array(uint16_t *p_dest, int p_elements) { - for(int i=0;i<p_elements;i++) { - p_dest[i]=f->get_16(); + for (int i = 0; i < p_elements; i++) { + p_dest[i] = f->get_16(); } - } -uint16_t CPFileAccessWrapperImpl::get_word(){ +uint16_t CPFileAccessWrapperImpl::get_word() { return f->get_16(); } -uint32_t CPFileAccessWrapperImpl::get_dword(){ +uint32_t CPFileAccessWrapperImpl::get_dword() { return f->get_32(); } -void CPFileAccessWrapperImpl::set_endian_conversion(bool p_swap){ +void CPFileAccessWrapperImpl::set_endian_conversion(bool p_swap) { f->set_endian_swap(p_swap); } -bool CPFileAccessWrapperImpl::is_open(){ +bool CPFileAccessWrapperImpl::is_open() { - return f!=NULL; + return f != NULL; } -CPFileAccessWrapperImpl::Error CPFileAccessWrapperImpl::get_error(){ +CPFileAccessWrapperImpl::Error CPFileAccessWrapperImpl::get_error() { - return (f->get_error()!=::OK)?ERROR_READING_FILE:OK; + return (f->get_error() != ::OK) ? ERROR_READING_FILE : OK; } -void CPFileAccessWrapperImpl::store_byte(uint8_t p_dest){ - +void CPFileAccessWrapperImpl::store_byte(uint8_t p_dest) { } -void CPFileAccessWrapperImpl::store_byte_array(const uint8_t *p_dest,int p_elements){ - +void CPFileAccessWrapperImpl::store_byte_array(const uint8_t *p_dest, int p_elements) { } -void CPFileAccessWrapperImpl::store_word(uint16_t p_dest){ - +void CPFileAccessWrapperImpl::store_word(uint16_t p_dest) { } -void CPFileAccessWrapperImpl::store_dword(uint32_t p_dest){ - +void CPFileAccessWrapperImpl::store_dword(uint32_t p_dest) { } //////////////////////////////////////////////// - Error EventStreamPlaybackChibi::_play() { - last_order=0; - loops=0; + last_order = 0; + loops = 0; player->play_start_song(); - total_usec=0; + total_usec = 0; return OK; } -bool EventStreamPlaybackChibi::_update(AudioMixer* p_mixer, uint64_t p_usec){ +bool EventStreamPlaybackChibi::_update(AudioMixer *p_mixer, uint64_t p_usec) { - total_usec+=p_usec; - mixer.process_usecs(p_usec,volume,pitch_scale,tempo_scale); - int order=player->get_current_order(); - if (order<last_order) { + total_usec += p_usec; + mixer.process_usecs(p_usec, volume, pitch_scale, tempo_scale); + int order = player->get_current_order(); + if (order < last_order) { if (!loop) { stop(); } else { loops++; } } - last_order=order; + last_order = order; return false; } -void EventStreamPlaybackChibi::_stop(){ +void EventStreamPlaybackChibi::_stop() { player->play_stop(); } -void EventStreamPlaybackChibi::set_paused(bool p_paused){ - +void EventStreamPlaybackChibi::set_paused(bool p_paused) { } -bool EventStreamPlaybackChibi::is_paused() const{ +bool EventStreamPlaybackChibi::is_paused() const { return false; } -void EventStreamPlaybackChibi::set_loop(bool p_loop){ - - loop=p_loop; +void EventStreamPlaybackChibi::set_loop(bool p_loop) { + loop = p_loop; } -bool EventStreamPlaybackChibi::is_loop_enabled() const{ +bool EventStreamPlaybackChibi::is_loop_enabled() const { return loop; } -int EventStreamPlaybackChibi::get_loop_count() const{ +int EventStreamPlaybackChibi::get_loop_count() const { //return player->is return loops; } -float EventStreamPlaybackChibi::get_pos() const{ +float EventStreamPlaybackChibi::get_pos() const { - return double(total_usec)/1000000.0; + return double(total_usec) / 1000000.0; } -void EventStreamPlaybackChibi::seek_pos(float p_time){ +void EventStreamPlaybackChibi::seek_pos(float p_time) { WARN_PRINT("seek_pos unimplemented."); } void EventStreamPlaybackChibi::set_volume(float p_volume) { - volume=p_volume; + volume = p_volume; } -float EventStreamPlaybackChibi::get_volume() const{ +float EventStreamPlaybackChibi::get_volume() const { return volume; } void EventStreamPlaybackChibi::set_pitch_scale(float p_pitch_scale) { - pitch_scale=p_pitch_scale; + pitch_scale = p_pitch_scale; } -float EventStreamPlaybackChibi::get_pitch_scale() const{ +float EventStreamPlaybackChibi::get_pitch_scale() const { return pitch_scale; } void EventStreamPlaybackChibi::set_tempo_scale(float p_tempo_scale) { - tempo_scale=p_tempo_scale; + tempo_scale = p_tempo_scale; } -float EventStreamPlaybackChibi::get_tempo_scale() const{ +float EventStreamPlaybackChibi::get_tempo_scale() const { return tempo_scale; } +void EventStreamPlaybackChibi::set_channel_volume(int p_channel, float p_volume) { -void EventStreamPlaybackChibi::set_channel_volume(int p_channel,float p_volume) { - - - if (p_channel>=64) + if (p_channel >= 64) return; - player->set_channel_global_volume(p_channel,p_volume*256); + player->set_channel_global_volume(p_channel, p_volume * 256); } +float EventStreamPlaybackChibi::get_channel_volume(int p_channel) const { - -float EventStreamPlaybackChibi::get_channel_volume(int p_channel) const{ - - return player->get_channel_global_volume(p_channel)/256.0; - + return player->get_channel_global_volume(p_channel) / 256.0; } float EventStreamPlaybackChibi::get_last_note_time(int p_channel) const { - - double v = (player->get_channel_last_note_time_usec(p_channel))/1000000.0; - if (v<0) - v=-1; + double v = (player->get_channel_last_note_time_usec(p_channel)) / 1000000.0; + if (v < 0) + v = -1; return v; } -EventStreamPlaybackChibi::EventStreamPlaybackChibi(Ref<EventStreamChibi> p_stream) : mixer(_get_mixer()) { +EventStreamPlaybackChibi::EventStreamPlaybackChibi(Ref<EventStreamChibi> p_stream) + : mixer(_get_mixer()) { - stream=p_stream; - player = memnew( CPPlayer(&mixer,&p_stream->song) ); - loop=false; - last_order=0; - loops=0; - volume=1.0; - pitch_scale=1.0; - tempo_scale=1.0; + stream = p_stream; + player = memnew(CPPlayer(&mixer, &p_stream->song)); + loop = false; + last_order = 0; + loops = 0; + volume = 1.0; + pitch_scale = 1.0; + tempo_scale = 1.0; } -EventStreamPlaybackChibi::~EventStreamPlaybackChibi(){ +EventStreamPlaybackChibi::~EventStreamPlaybackChibi() { player->play_stop(); memdelete(player); @@ -752,88 +704,76 @@ EventStreamPlaybackChibi::~EventStreamPlaybackChibi(){ Ref<EventStreamPlayback> EventStreamChibi::instance_playback() { - return Ref<EventStreamPlayback>( memnew(EventStreamPlaybackChibi(Ref<EventStreamChibi>(this))) ); + return Ref<EventStreamPlayback>(memnew(EventStreamPlaybackChibi(Ref<EventStreamChibi>(this)))); } -String EventStreamChibi::get_stream_name() const{ +String EventStreamChibi::get_stream_name() const { return song.get_name(); - } - - -float EventStreamChibi::get_length() const{ +float EventStreamChibi::get_length() const { return 1; } - EventStreamChibi::EventStreamChibi() { - - } - - ////////////////////////////////////////////////////////////////// - - - -RES ResourceFormatLoaderChibi::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderChibi::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; String el = p_path.extension().to_lower(); CPFileAccessWrapperImpl f; - if (el=="it") { + if (el == "it") { - Ref<EventStreamChibi> esc( memnew( EventStreamChibi ) ); + Ref<EventStreamChibi> esc(memnew(EventStreamChibi)); CPLoader_IT loader(&f); - CPLoader::Error err = loader.load_song(p_path.utf8().get_data(),&esc->song,false); - ERR_FAIL_COND_V(err!=CPLoader::FILE_OK,RES()); + CPLoader::Error err = loader.load_song(p_path.utf8().get_data(), &esc->song, false); + ERR_FAIL_COND_V(err != CPLoader::FILE_OK, RES()); if (r_error) - *r_error=OK; + *r_error = OK; return esc; - } else if (el=="xm") { + } else if (el == "xm") { - Ref<EventStreamChibi> esc( memnew( EventStreamChibi ) ); + Ref<EventStreamChibi> esc(memnew(EventStreamChibi)); CPLoader_XM loader(&f); - CPLoader::Error err=loader.load_song(p_path.utf8().get_data(),&esc->song,false); - ERR_FAIL_COND_V(err!=CPLoader::FILE_OK,RES()); + CPLoader::Error err = loader.load_song(p_path.utf8().get_data(), &esc->song, false); + ERR_FAIL_COND_V(err != CPLoader::FILE_OK, RES()); if (r_error) - *r_error=OK; + *r_error = OK; return esc; - } else if (el=="s3m") { + } else if (el == "s3m") { - Ref<EventStreamChibi> esc( memnew( EventStreamChibi ) ); + Ref<EventStreamChibi> esc(memnew(EventStreamChibi)); CPLoader_S3M loader(&f); - CPLoader::Error err=loader.load_song(p_path.utf8().get_data(),&esc->song,false); - ERR_FAIL_COND_V(err!=CPLoader::FILE_OK,RES()); + CPLoader::Error err = loader.load_song(p_path.utf8().get_data(), &esc->song, false); + ERR_FAIL_COND_V(err != CPLoader::FILE_OK, RES()); if (r_error) - *r_error=OK; + *r_error = OK; return esc; - } else if (el=="mod") { + } else if (el == "mod") { - Ref<EventStreamChibi> esc( memnew( EventStreamChibi ) ); + Ref<EventStreamChibi> esc(memnew(EventStreamChibi)); CPLoader_MOD loader(&f); - CPLoader::Error err=loader.load_song(p_path.utf8().get_data(),&esc->song,false); - ERR_FAIL_COND_V(err!=CPLoader::FILE_OK,RES()); + CPLoader::Error err = loader.load_song(p_path.utf8().get_data(), &esc->song, false); + ERR_FAIL_COND_V(err != CPLoader::FILE_OK, RES()); if (r_error) - *r_error=OK; + *r_error = OK; return esc; } return RES(); - } void ResourceFormatLoaderChibi::get_recognized_extensions(List<String> *p_extensions) const { @@ -843,14 +783,14 @@ void ResourceFormatLoaderChibi::get_recognized_extensions(List<String> *p_extens p_extensions->push_back("s3m"); p_extensions->push_back("mod"); } -bool ResourceFormatLoaderChibi::handles_type(const String& p_type) const { +bool ResourceFormatLoaderChibi::handles_type(const String &p_type) const { - return (p_type=="EventStreamChibi" || p_type=="EventStream"); + return (p_type == "EventStreamChibi" || p_type == "EventStream"); } String ResourceFormatLoaderChibi::get_resource_type(const String &p_path) const { String el = p_path.extension().to_lower(); - if (el=="it" || el=="s3m" || el=="xm" || el=="mod") + if (el == "it" || el == "s3m" || el == "xm" || el == "mod") return "EventStreamChibi"; return ""; } @@ -858,15 +798,14 @@ String ResourceFormatLoaderChibi::get_resource_type(const String &p_path) const ///////////////////////////////////////////////////////////////// void initialize_chibi() { - sample_manager = memnew( CPSampleManagerImpl ); - resource_loader = memnew( ResourceFormatLoaderChibi ); + sample_manager = memnew(CPSampleManagerImpl); + resource_loader = memnew(ResourceFormatLoaderChibi); ObjectTypeDB::register_type<EventStreamChibi>(); - ResourceLoader::add_resource_format_loader( resource_loader ); + ResourceLoader::add_resource_format_loader(resource_loader); } void finalize_chibi() { - memdelete( sample_manager ); - memdelete( resource_loader ); + memdelete(sample_manager); + memdelete(resource_loader); } - diff --git a/modules/chibi/event_stream_chibi.h b/modules/chibi/event_stream_chibi.h index 57aa307a8..8712fead2 100644 --- a/modules/chibi/event_stream_chibi.h +++ b/modules/chibi/event_stream_chibi.h @@ -29,16 +29,16 @@ #ifndef EVENT_STREAM_CHIBI_H #define EVENT_STREAM_CHIBI_H -#include "scene/resources/event_stream.h" -#include "cp_sample_manager.h" -#include "cp_mixer.h" -#include "cp_song.h" #include "cp_file_access_wrapper.h" +#include "cp_mixer.h" #include "cp_player_data.h" +#include "cp_sample_manager.h" +#include "cp_song.h" +#include "io/resource_loader.h" +#include "os/file_access.h" #include "resource.h" +#include "scene/resources/event_stream.h" #include "servers/audio_server.h" -#include "os/file_access.h" -#include "io/resource_loader.h" /** SAMPLE MANAGER **/ @@ -59,27 +59,24 @@ class CPSampleManagerImpl : public CPSampleManager { CPSample_Loop_Type loop_type; }; + _FORCE_INLINE_ SampleData *_getsd(CPSample_ID p_id) { - _FORCE_INLINE_ SampleData* _getsd(CPSample_ID p_id) { - - return ((SampleData*)p_id._private); + return ((SampleData *)p_id._private); } - Set<SampleData*> valid; + Set<SampleData *> valid; public: - _FORCE_INLINE_ RID get_rid(CPSample_ID p_id) { return _getsd(p_id)->rid; } - virtual CPSample_ID create(bool p_16bits,bool p_stereo,int32_t p_len); - virtual void recreate(CPSample_ID p_id,bool p_16bits,bool p_stereo,int32_t p_len); + virtual CPSample_ID create(bool p_16bits, bool p_stereo, int32_t p_len); + virtual void recreate(CPSample_ID p_id, bool p_16bits, bool p_stereo, int32_t p_len); virtual void destroy(CPSample_ID p_id); virtual bool check(CPSample_ID p_id); // return false if invalid - virtual void set_c5_freq(CPSample_ID p_id,int32_t p_freq); - virtual void set_loop_begin(CPSample_ID p_id,int32_t p_begin); - virtual void set_loop_end(CPSample_ID p_id,int32_t p_end); - virtual void set_loop_type(CPSample_ID p_id,CPSample_Loop_Type p_type); - virtual void set_chunk(CPSample_ID p_id,int32_t p_index,void *p_data,int p_data_len); - + virtual void set_c5_freq(CPSample_ID p_id, int32_t p_freq); + virtual void set_loop_begin(CPSample_ID p_id, int32_t p_begin); + virtual void set_loop_end(CPSample_ID p_id, int32_t p_end); + virtual void set_loop_type(CPSample_ID p_id, CPSample_Loop_Type p_type); + virtual void set_chunk(CPSample_ID p_id, int32_t p_index, void *p_data, int p_data_len); virtual int32_t get_loop_begin(CPSample_ID p_id); virtual int32_t get_loop_end(CPSample_ID p_id); @@ -91,21 +88,19 @@ public: virtual bool lock_data(CPSample_ID p_id); virtual void *get_data(CPSample_ID p_id); /* WARNING: Not all sample managers may be able to implement this, it depends on the mixer in use! */ - virtual int16_t get_data(CPSample_ID p_id, int p_sample, int p_channel=0); /// Does not need locking - virtual void set_data(CPSample_ID p_id, int p_sample, int16_t p_data,int p_channel=0); /// Does not need locking + virtual int16_t get_data(CPSample_ID p_id, int p_sample, int p_channel = 0); /// Does not need locking + virtual void set_data(CPSample_ID p_id, int p_sample, int16_t p_data, int p_channel = 0); /// Does not need locking virtual void unlock_data(CPSample_ID p_id); - virtual void get_chunk(CPSample_ID p_id,int32_t p_index,void *p_data,int p_data_len); - + virtual void get_chunk(CPSample_ID p_id, int32_t p_index, void *p_data, int p_data_len); }; - /** MIXER **/ class CPMixerImpl : public CPMixer { enum { - MAX_VOICES=64 + MAX_VOICES = 64 }; struct Voice { @@ -114,64 +109,61 @@ class CPMixerImpl : public CPMixer { CPSample_ID sample; float freq_mult; float reverb; - Voice() { reverb=0.0; } + Voice() { reverb = 0.0; } }; Voice voices[MAX_VOICES]; - int callback_interval; int callback_timeout; - void (*callback)(void*); + void (*callback)(void *); void *userdata; float voice_scale; float tempo_scale; float pitch_scale; AudioMixer::ReverbRoomType reverb_type; AudioMixer *mixer; -public: - void process_usecs(int p_usec,float p_volume,float p_pitch_scale,float p_tempo_scale); +public: + void process_usecs(int p_usec, float p_volume, float p_pitch_scale, float p_tempo_scale); /* Callback */ virtual void set_callback_interval(int p_interval_us); //in usecs, for tracker it's 2500000/tempo - virtual void set_callback(void (*p_callback)(void*),void *p_userdata); + virtual void set_callback(void (*p_callback)(void *), void *p_userdata); /* Voice Control */ - virtual void setup_voice(int p_voice_index,CPSample_ID p_sample_id,int32_t p_start_index) ; - virtual void stop_voice(int p_voice_index) ; - virtual void set_voice_frequency(int p_voice_index,int32_t p_freq) ; //in freq*FREQUENCY_BITS - virtual void set_voice_panning(int p_voice_index,int p_pan) ; - virtual void set_voice_volume(int p_voice_index,int p_vol) ; - virtual void set_voice_filter(int p_filter,bool p_enabled,uint8_t p_cutoff, uint8_t p_resonance ); - virtual void set_voice_reverb_send(int p_voice_index,int p_reverb); - virtual void set_voice_chorus_send(int p_voice_index,int p_chorus); /* 0 - 255 */ + virtual void setup_voice(int p_voice_index, CPSample_ID p_sample_id, int32_t p_start_index); + virtual void stop_voice(int p_voice_index); + virtual void set_voice_frequency(int p_voice_index, int32_t p_freq); //in freq*FREQUENCY_BITS + virtual void set_voice_panning(int p_voice_index, int p_pan); + virtual void set_voice_volume(int p_voice_index, int p_vol); + virtual void set_voice_filter(int p_filter, bool p_enabled, uint8_t p_cutoff, uint8_t p_resonance); + virtual void set_voice_reverb_send(int p_voice_index, int p_reverb); + virtual void set_voice_chorus_send(int p_voice_index, int p_chorus); /* 0 - 255 */ virtual void set_reverb_mode(ReverbMode p_mode); - virtual void set_chorus_params(unsigned int p_delay_ms,unsigned int p_separation_ms,unsigned int p_depth_ms10,unsigned int p_speed_hz10); - + virtual void set_chorus_params(unsigned int p_delay_ms, unsigned int p_separation_ms, unsigned int p_depth_ms10, unsigned int p_speed_hz10); /* Info retrieving */ - virtual int32_t get_voice_sample_pos_index(int p_voice_index) ; - virtual int get_voice_panning(int p_voice_index) ; - virtual int get_voice_volume(int p_voice_index) ; - virtual CPSample_ID get_voice_sample_id(int p_voice_index) ; + virtual int32_t get_voice_sample_pos_index(int p_voice_index); + virtual int get_voice_panning(int p_voice_index); + virtual int get_voice_volume(int p_voice_index); + virtual CPSample_ID get_voice_sample_id(int p_voice_index); virtual bool is_voice_active(int p_voice_index); virtual int get_active_voice_count() { return 0; } virtual int get_total_voice_count() { return MAX_VOICES; } - virtual uint32_t get_mix_frequency() { return 0; } /* Methods below only work with software mixers, meant for software-based sound drivers, hardware mixers ignore them */ virtual int32_t process(int32_t p_frames) { return 0; } virtual int32_t *get_mixdown_buffer_ptr() { return NULL; } - virtual void set_mix_frequency(int32_t p_mix_frequency) {}; + virtual void set_mix_frequency(int32_t p_mix_frequency){}; - CPMixerImpl(AudioMixer *p_mixer=NULL); + CPMixerImpl(AudioMixer *p_mixer = NULL); virtual ~CPMixerImpl() {} }; @@ -180,9 +172,8 @@ public: class CPFileAccessWrapperImpl : public CPFileAccessWrapper { FileAccess *f; -public: - +public: virtual Error open(const char *p_filename, int p_mode_flags); virtual void close(); @@ -193,8 +184,8 @@ public: virtual bool eof_reached(); virtual uint8_t get_byte(); - virtual void get_byte_array(uint8_t *p_dest,int p_elements); - virtual void get_word_array(uint16_t *p_dest,int p_elements); + virtual void get_byte_array(uint8_t *p_dest, int p_elements); + virtual void get_word_array(uint16_t *p_dest, int p_elements); virtual uint16_t get_word(); virtual uint32_t get_dword(); @@ -205,25 +196,24 @@ public: virtual Error get_error(); virtual void store_byte(uint8_t p_dest); - virtual void store_byte_array(const uint8_t *p_dest,int p_elements); + virtual void store_byte_array(const uint8_t *p_dest, int p_elements); virtual void store_word(uint16_t p_dest); virtual void store_dword(uint32_t p_dest); - CPFileAccessWrapperImpl() { f=NULL; } - virtual ~CPFileAccessWrapperImpl(){ if (f) memdelete(f); } - + CPFileAccessWrapperImpl() { f = NULL; } + virtual ~CPFileAccessWrapperImpl() { + if (f) memdelete(f); + } }; - - ///////////////////// class EventStreamChibi; class EventStreamPlaybackChibi : public EventStreamPlayback { - OBJ_TYPE(EventStreamPlaybackChibi,EventStreamPlayback); + OBJ_TYPE(EventStreamPlaybackChibi, EventStreamPlayback); CPMixerImpl mixer; uint64_t total_usec; @@ -233,16 +223,13 @@ class EventStreamPlaybackChibi : public EventStreamPlayback { int last_order; int loops; virtual Error _play(); - virtual bool _update(AudioMixer* p_mixer, uint64_t p_usec); + virtual bool _update(AudioMixer *p_mixer, uint64_t p_usec); virtual void _stop(); float volume; float tempo_scale; float pitch_scale; - public: - - virtual void set_paused(bool p_paused); virtual bool is_paused() const; @@ -263,29 +250,26 @@ public: virtual void set_tempo_scale(float p_tempo_scale); virtual float get_tempo_scale() const; - virtual void set_channel_volume(int p_channel,float p_volume); + virtual void set_channel_volume(int p_channel, float p_volume); virtual float get_channel_volume(int p_channel) const; virtual float get_last_note_time(int p_channel) const; - EventStreamPlaybackChibi(Ref<EventStreamChibi> p_stream=Ref<EventStreamChibi>()); + EventStreamPlaybackChibi(Ref<EventStreamChibi> p_stream = Ref<EventStreamChibi>()); ~EventStreamPlaybackChibi(); }; - class EventStreamChibi : public EventStream { - OBJ_TYPE(EventStreamChibi,EventStream); + OBJ_TYPE(EventStreamChibi, EventStream); -friend class ResourceFormatLoaderChibi; -friend class EventStreamPlaybackChibi; + friend class ResourceFormatLoaderChibi; + friend class EventStreamPlaybackChibi; //I think i didn't know what const was when i wrote this more than a decade ago //so it goes mutable :( mutable CPSong song; - public: - virtual Ref<EventStreamPlayback> instance_playback(); virtual String get_stream_name() const; @@ -297,15 +281,13 @@ public: EventStreamChibi(); }; - class ResourceFormatLoaderChibi : public ResourceFormatLoader { public: - 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 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; - }; void initialize_chibi(); diff --git a/modules/cscript/godot_c.cpp b/modules/cscript/godot_c.cpp index d5c1b53df..dd2e240f4 100644 --- a/modules/cscript/godot_c.cpp +++ b/modules/cscript/godot_c.cpp @@ -1,2 +1 @@ #include "godot_c.h" - diff --git a/modules/cscript/godot_c.h b/modules/cscript/godot_c.h index b0465d852..5f5910169 100644 --- a/modules/cscript/godot_c.h +++ b/modules/cscript/godot_c.h @@ -5,7 +5,6 @@ extern "C" { #endif - #if defined(GDAPI_BUILT_IN) || !defined(WINDOWS_ENABLED) #define GDAPI #elif defined(GDAPI_EXPORTS) @@ -14,10 +13,8 @@ extern "C" { #define GDAPI __declspec(dllimport) #endif - #define GODOT_API_VERSION 1 - typedef int godot_bool; #define GODOT_FALSE 0 @@ -25,7 +22,6 @@ typedef int godot_bool; ////// Image - #define GODOT_IMAGE_FORMAT_GRAYSCALE 0 #define GODOT_IMAGE_FORMAT_INTENSITY 1 #define GODOT_IMAGE_FORMAT_GRAYSCALE_ALPHA 2 @@ -49,11 +45,11 @@ typedef int godot_bool; #define GODOT_IMAGE_FORMAT_ATC_ALPHA_EXPLICIT 20 #define GODOT_IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED 21 -typedef void* godot_image; +typedef void *godot_image; godot_image GDAPI godot_image_create_empty(); -godot_image GDAPI godot_image_create(int p_width,int p_height,int p_format,int p_use_mipmaps); -godot_image GDAPI godot_image_create_with_data(int p_width,int p_height,int p_format,int p_use_mipmaps,unsigned char* p_buffer); +godot_image GDAPI godot_image_create(int p_width, int p_height, int p_format, int p_use_mipmaps); +godot_image GDAPI godot_image_create_with_data(int p_width, int p_height, int p_format, int p_use_mipmaps, unsigned char *p_buffer); int GDAPI godot_image_get_width(godot_image p_image); int GDAPI godot_image_get_height(godot_image p_image); int GDAPI godot_image_get_format(godot_image p_image); @@ -61,10 +57,9 @@ int GDAPI godot_image_get_mipmap_count(godot_image p_image); godot_image GDAPI godot_image_copy(godot_image p_image); void GDAPI godot_image_free(godot_image p_image); - ////// RID -typedef void* godot_rid; +typedef void *godot_rid; godot_rid GDAPI godot_rid_create(); godot_rid GDAPI godot_rid_copy(godot_rid p_rid); @@ -72,37 +67,36 @@ void GDAPI godot_rid_free(godot_rid p_rid); ////// Variant (forward declared) -typedef void* godot_variant; - +typedef void *godot_variant; ////// Dictionary -typedef void* godot_dictionary; +typedef void *godot_dictionary; godot_dictionary GDAPI godot_dictionary_create(); -void GDAPI godot_dictionary_has(godot_dictionary p_dictionary,godot_variant p_key); -godot_variant GDAPI godot_dictionary_get(godot_dictionary p_dictionary,godot_variant p_key); -void GDAPI godot_dictionary_insert(godot_dictionary p_dictionary,godot_variant p_key,godot_variant p_value); -void GDAPI godot_dictionary_remove(godot_dictionary p_dictionary,godot_variant p_key); +void GDAPI godot_dictionary_has(godot_dictionary p_dictionary, godot_variant p_key); +godot_variant GDAPI godot_dictionary_get(godot_dictionary p_dictionary, godot_variant p_key); +void GDAPI godot_dictionary_insert(godot_dictionary p_dictionary, godot_variant p_key, godot_variant p_value); +void GDAPI godot_dictionary_remove(godot_dictionary p_dictionary, godot_variant p_key); void GDAPI godot_dictionary_clear(godot_dictionary p_dictionary); int GDAPI godot_dictionary_get_size(godot_dictionary p_dictionary); -void GDAPI godot_dictionary_get_keys(godot_dictionary p_dictionary,godot_variant* p_keys); +void GDAPI godot_dictionary_get_keys(godot_dictionary p_dictionary, godot_variant *p_keys); godot_dictionary GDAPI godot_dictionary_copy(godot_dictionary p_dictionary); void GDAPI godot_dictionary_free(godot_dictionary p_dictionary); ////// Array -typedef void* godot_array; +typedef void *godot_array; godot_array GDAPI godot_array_create(); -godot_variant GDAPI godot_array_get(godot_array p_array,int p_index); -void GDAPI godot_array_set(godot_array p_array,int p_index,godot_variant p_value); -void GDAPI godot_array_resize(godot_array p_array,int p_size); -void GDAPI godot_array_insert(godot_array p_array,int p_position,godot_variant p_value); -void GDAPI godot_array_remove(godot_array p_array,int p_position); +godot_variant GDAPI godot_array_get(godot_array p_array, int p_index); +void GDAPI godot_array_set(godot_array p_array, int p_index, godot_variant p_value); +void GDAPI godot_array_resize(godot_array p_array, int p_size); +void GDAPI godot_array_insert(godot_array p_array, int p_position, godot_variant p_value); +void GDAPI godot_array_remove(godot_array p_array, int p_position); void GDAPI godot_array_clear(godot_array p_array); int GDAPI godot_array_get_size(godot_array p_array); -int GDAPI godot_array_find(godot_array p_array,godot_variant p_value,int p_from_pos=-1); +int GDAPI godot_array_find(godot_array p_array, godot_variant p_value, int p_from_pos = -1); godot_array GDAPI godot_array_copy(godot_array p_array); void GDAPI godot_array_free(godot_array p_array); @@ -115,9 +109,9 @@ void GDAPI godot_array_free(godot_array p_array); #define INPUT_EVENT_BUTTON_WHEEL_DOWN 5 #define INPUT_EVENT_BUTTON_WHEEL_LEFT 6 #define INPUT_EVENT_BUTTON_WHEEL_RIGHT 7 -#define INPUT_EVENT_BUTTON_MASK_LEFT (1<<(INPUT_EVENT_BUTTON_LEFT-1)) -#define INPUT_EVENT_BUTTON_MASK_RIGHT (1<<(INPUT_EVENT_BUTTON_RIGHT-1)) -#define INPUT_EVENT_BUTTON_MASK_MIDDLE (1<<(INPUT_EVENT_BUTTON_MIDDLE-1)) +#define INPUT_EVENT_BUTTON_MASK_LEFT (1 << (INPUT_EVENT_BUTTON_LEFT - 1)) +#define INPUT_EVENT_BUTTON_MASK_RIGHT (1 << (INPUT_EVENT_BUTTON_RIGHT - 1)) +#define INPUT_EVENT_BUTTON_MASK_MIDDLE (1 << (INPUT_EVENT_BUTTON_MIDDLE - 1)) #define INPUT_EVENT_TYPE_NONE 0 #define INPUT_EVENT_TYPE_KEY 1 @@ -129,8 +123,7 @@ void GDAPI godot_array_free(godot_array p_array); #define INPUT_EVENT_TYPE_SCREEN_DRAG 7 #define INPUT_EVENT_TYPE_ACTION 8 -typedef void* godot_input_event; - +typedef void *godot_input_event; godot_input_event GDAPI godot_input_event_create(); godot_input_event GDAPI godot_input_event_copy(godot_input_event p_input_event); @@ -173,7 +166,6 @@ int GDAPI godot_input_event_joystick_button_get_button_index(godot_input_event p godot_bool GDAPI godot_input_event_joystick_button_is_pressed(godot_input_event p_event); float GDAPI godot_input_event_joystick_button_get_pressure(godot_input_event p_event); - int GDAPI godot_input_event_screen_touch_get_index(godot_input_event p_event); int GDAPI godot_input_event_screen_touch_get_x(godot_input_event p_event); int GDAPI godot_input_event_screen_touch_get_y(godot_input_event p_event); @@ -187,49 +179,47 @@ int GDAPI godot_input_event_screen_drag_get_relative_y(godot_input_event p_event int GDAPI godot_input_event_screen_drag_get_speed_x(godot_input_event p_event); int GDAPI godot_input_event_screen_drag_get_speed_y(godot_input_event p_event); -int GDAPI godot_input_event_is_action(godot_input_event p_event,char *p_action); -int GDAPI godot_input_event_is_action_pressed(godot_input_event p_event,char *p_action); +int GDAPI godot_input_event_is_action(godot_input_event p_event, char *p_action); +int GDAPI godot_input_event_is_action_pressed(godot_input_event p_event, char *p_action); ////// ByteArray -typedef void* godot_byte_array; +typedef void *godot_byte_array; godot_byte_array GDAPI godot_byte_array_create(); godot_byte_array GDAPI godot_byte_array_copy(godot_byte_array p_byte_array); void GDAPI godot_byte_array_free(godot_byte_array p_byte_array); int GDAPI godot_byte_array_get_size(godot_byte_array p_byte_array); -unsigned char GDAPI godot_byte_array_get(godot_byte_array p_byte_array,int p_index); -void GDAPI godot_byte_array_set(godot_byte_array p_byte_array,int p_index,unsigned char p_value); -void GDAPI godot_byte_array_remove(godot_byte_array p_byte_array,int p_index); +unsigned char GDAPI godot_byte_array_get(godot_byte_array p_byte_array, int p_index); +void GDAPI godot_byte_array_set(godot_byte_array p_byte_array, int p_index, unsigned char p_value); +void GDAPI godot_byte_array_remove(godot_byte_array p_byte_array, int p_index); void GDAPI godot_byte_array_clear(godot_byte_array p_byte_array); -typedef void* godot_byte_array_lock; +typedef void *godot_byte_array_lock; godot_byte_array_lock GDAPI godot_byte_array_get_lock(godot_byte_array p_byte_array); unsigned char GDAPI *godot_byte_array_lock_get_pointer(godot_byte_array_lock p_byte_array_lock); void GDAPI godot_byte_array_lock_free(godot_byte_array_lock p_byte_array_lock); - -godot_image GDAPI godot_image_create_with_array(int p_width,int p_height,int p_format,int p_use_mipmaps,godot_array p_array); +godot_image GDAPI godot_image_create_with_array(int p_width, int p_height, int p_format, int p_use_mipmaps, godot_array p_array); godot_byte_array GDAPI godot_image_get_data(godot_image p_image); - ////// IntArray -typedef void* godot_int_array; +typedef void *godot_int_array; godot_int_array GDAPI godot_int_array_create(); godot_int_array GDAPI godot_int_array_copy(godot_int_array p_int_array); void GDAPI godot_int_array_free(godot_int_array p_int_array); int GDAPI godot_int_array_get_size(godot_int_array p_int_array); -int GDAPI godot_int_array_get(godot_int_array p_int_array,int p_index); -void GDAPI godot_int_array_set(godot_int_array p_int_array,int p_index,int p_value); -void GDAPI godot_int_array_remove(godot_int_array p_int_array,int p_index); +int GDAPI godot_int_array_get(godot_int_array p_int_array, int p_index); +void GDAPI godot_int_array_set(godot_int_array p_int_array, int p_index, int p_value); +void GDAPI godot_int_array_remove(godot_int_array p_int_array, int p_index); void GDAPI godot_int_array_clear(godot_int_array p_int_array); -typedef void* godot_int_array_lock; +typedef void *godot_int_array_lock; godot_int_array_lock GDAPI godot_int_array_get_lock(godot_int_array p_int_array); int GDAPI *godot_int_array_lock_get_pointer(godot_int_array_lock p_int_array_lock); @@ -237,44 +227,41 @@ void GDAPI godot_int_array_lock_free(godot_int_array_lock p_int_array_lock); ////// RealArray -typedef void* godot_real_array; - +typedef void *godot_real_array; godot_real_array GDAPI godot_real_array_create(); godot_real_array GDAPI godot_real_array_copy(godot_real_array p_real_array); void GDAPI godot_real_array_free(godot_real_array p_real_array); int GDAPI godot_real_array_get_size(godot_real_array p_real_array); -float GDAPI godot_real_array_get(godot_real_array p_real_array,int p_index); -void GDAPI godot_real_array_set(godot_real_array p_real_array,int p_index,float p_value); -void GDAPI godot_real_array_remove(godot_real_array p_real_array,int p_index); +float GDAPI godot_real_array_get(godot_real_array p_real_array, int p_index); +void GDAPI godot_real_array_set(godot_real_array p_real_array, int p_index, float p_value); +void GDAPI godot_real_array_remove(godot_real_array p_real_array, int p_index); void GDAPI godot_real_array_clear(godot_real_array p_real_array); -typedef void* godot_real_array_lock; +typedef void *godot_real_array_lock; godot_real_array_lock GDAPI godot_real_array_get_lock(godot_real_array p_real_array); float GDAPI *godot_real_array_lock_get_pointer(godot_real_array_lock p_real_array_lock); void GDAPI godot_real_array_lock_free(godot_real_array_lock p_real_array_lock); - ////// StringArray -typedef void* godot_string_array; - +typedef void *godot_string_array; godot_string_array GDAPI godot_string_array_create(); godot_string_array GDAPI godot_string_array_copy(godot_string_array p_string_array); void GDAPI godot_string_array_free(godot_string_array p_string_array); int GDAPI godot_string_array_get_size(godot_string_array p_string_array); -int GDAPI godot_string_array_get(godot_string_array p_string_array,int p_index,unsigned char* p_string,int p_max_len); -void GDAPI godot_string_array_set(godot_string_array p_string_array,int p_index,unsigned char *p_string); -void GDAPI godot_string_array_remove(godot_string_array p_string_array,int p_index); +int GDAPI godot_string_array_get(godot_string_array p_string_array, int p_index, unsigned char *p_string, int p_max_len); +void GDAPI godot_string_array_set(godot_string_array p_string_array, int p_index, unsigned char *p_string); +void GDAPI godot_string_array_remove(godot_string_array p_string_array, int p_index); void GDAPI godot_string_array_clear(godot_string_array p_string_array); ////// Vector2Array -typedef void* godot_vector2_array; +typedef void *godot_vector2_array; godot_vector2_array GDAPI godot_vector2_array_create(); godot_vector2_array GDAPI godot_vector2_array_copy(godot_vector2_array p_vector2_array); @@ -282,13 +269,12 @@ void GDAPI godot_vector2_array_free(godot_vector2_array p_vector2_array); int GDAPI godot_vector2_array_get_size(godot_vector2_array p_vector2_array); int GDAPI godot_vector2_array_get_stride(godot_vector2_array p_vector2_array); -void GDAPI godot_vector2_array_get(godot_vector2_array p_vector2_array,int p_index,float* p_vector2); -void GDAPI godot_vector2_array_set(godot_vector2_array p_vector2_array,int p_index,float *p_vector2); -void GDAPI godot_vector2_array_remove(godot_vector2_array p_vector2_array,int p_index); +void GDAPI godot_vector2_array_get(godot_vector2_array p_vector2_array, int p_index, float *p_vector2); +void GDAPI godot_vector2_array_set(godot_vector2_array p_vector2_array, int p_index, float *p_vector2); +void GDAPI godot_vector2_array_remove(godot_vector2_array p_vector2_array, int p_index); void GDAPI godot_vector2_array_clear(godot_vector2_array p_vector2_array); - -typedef void* godot_vector2_array_lock; +typedef void *godot_vector2_array_lock; godot_vector2_array_lock GDAPI godot_vector2_array_get_lock(godot_vector2_array p_vector2_array); float GDAPI *godot_vector2_array_lock_get_pointer(godot_vector2_array_lock p_vector2_array_lock); @@ -296,7 +282,7 @@ void GDAPI godot_vector2_array_lock_free(godot_vector2_array_lock p_vector2_arra ////// Vector3Array -typedef void* godot_vector3_array; +typedef void *godot_vector3_array; godot_vector3_array GDAPI godot_vector3_array_create(); godot_vector3_array GDAPI godot_vector3_array_copy(godot_vector3_array p_vector3_array); @@ -304,13 +290,12 @@ void GDAPI godot_vector3_array_free(godot_vector3_array p_vector3_array); int GDAPI godot_vector3_array_get_size(godot_vector3_array p_vector3_array); int GDAPI godot_vector3_array_get_stride(godot_vector3_array p_vector3_array); -void GDAPI godot_vector3_array_get(godot_vector3_array p_vector3_array,int p_index,float* p_vector3); -void GDAPI godot_vector3_array_set(godot_vector3_array p_vector3_array,int p_index,float *p_vector3); -void GDAPI godot_vector3_array_remove(godot_vector3_array p_vector3_array,int p_index); +void GDAPI godot_vector3_array_get(godot_vector3_array p_vector3_array, int p_index, float *p_vector3); +void GDAPI godot_vector3_array_set(godot_vector3_array p_vector3_array, int p_index, float *p_vector3); +void GDAPI godot_vector3_array_remove(godot_vector3_array p_vector3_array, int p_index); void GDAPI godot_vector3_array_clear(godot_vector3_array p_vector3_array); - -typedef void* godot_vector3_array_lock; +typedef void *godot_vector3_array_lock; godot_vector3_array_lock GDAPI godot_vector3_array_get_lock(godot_vector3_array p_vector3_array); float GDAPI *godot_vector3_array_lock_get_pointer(godot_vector3_array_lock p_vector3_array_lock); @@ -318,7 +303,7 @@ void GDAPI godot_vector3_array_lock_free(godot_vector3_array_lock p_vector3_arra ////// ColorArray -typedef void* godot_color_array; +typedef void *godot_color_array; godot_color_array GDAPI godot_color_array_create(); godot_color_array GDAPI godot_color_array_copy(godot_color_array p_color_array); @@ -326,19 +311,17 @@ void GDAPI godot_color_array_free(godot_color_array p_color_array); int GDAPI godot_color_array_get_size(godot_color_array p_color_array); int GDAPI godot_color_array_get_stride(godot_color_array p_color_array); -void GDAPI godot_color_array_get(godot_color_array p_color_array,int p_index,float* p_color); -void GDAPI godot_color_array_set(godot_color_array p_color_array,int p_index,float *p_color); -void GDAPI godot_color_array_remove(godot_color_array p_color_array,int p_index); +void GDAPI godot_color_array_get(godot_color_array p_color_array, int p_index, float *p_color); +void GDAPI godot_color_array_set(godot_color_array p_color_array, int p_index, float *p_color); +void GDAPI godot_color_array_remove(godot_color_array p_color_array, int p_index); void GDAPI godot_color_array_clear(godot_color_array p_color_array); - -typedef void* godot_color_array_lock; +typedef void *godot_color_array_lock; godot_color_array_lock GDAPI godot_color_array_get_lock(godot_color_array p_color_array); float GDAPI *godot_color_array_lock_get_pointer(godot_color_array_lock p_color_array_lock); void GDAPI godot_color_array_lock_free(godot_color_array_lock p_color_array_lock); - ////// Instance (forward declared) typedef void *godot_instance; @@ -381,52 +364,52 @@ godot_variant *godot_variant_new(); int GDAPI godot_variant_get_type(godot_variant p_variant); void GDAPI godot_variant_set_null(godot_variant p_variant); -void GDAPI godot_variant_set_bool(godot_variant p_variant,godot_bool p_bool); -void GDAPI godot_variant_set_int(godot_variant p_variant,int p_int); -void GDAPI godot_variant_set_float(godot_variant p_variant,int p_float); -void GDAPI godot_variant_set_string(godot_variant p_variant,char *p_string); -void GDAPI godot_variant_set_vector2(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_rect2(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_vector3(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_matrix32(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_plane(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_aabb(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_matrix3(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_transform(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_color(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_set_image(godot_variant p_variant,godot_image *p_image); -void GDAPI godot_variant_set_node_path(godot_variant p_variant,char *p_path); -void GDAPI godot_variant_set_rid(godot_variant p_variant,char *p_path); -void GDAPI godot_variant_set_instance(godot_variant p_variant,godot_instance p_instance); -void GDAPI godot_variant_set_input_event(godot_variant p_variant,godot_input_event p_instance); -void GDAPI godot_variant_set_dictionary(godot_variant p_variant,godot_dictionary p_dictionary); -void GDAPI godot_variant_set_array(godot_variant p_variant,godot_array p_array); -void GDAPI godot_variant_set_byte_array(godot_variant p_variant,godot_byte_array p_array); -void GDAPI godot_variant_set_int_array(godot_variant p_variant,godot_byte_array p_array); -void GDAPI godot_variant_set_string_array(godot_variant p_variant,godot_string_array p_array); -void GDAPI godot_variant_set_vector2_array(godot_variant p_variant,godot_vector2_array p_array); -void GDAPI godot_variant_set_vector3_array(godot_variant p_variant,godot_vector3_array p_array); -void GDAPI godot_variant_set_color_array(godot_variant p_variant,godot_color_array p_array); +void GDAPI godot_variant_set_bool(godot_variant p_variant, godot_bool p_bool); +void GDAPI godot_variant_set_int(godot_variant p_variant, int p_int); +void GDAPI godot_variant_set_float(godot_variant p_variant, int p_float); +void GDAPI godot_variant_set_string(godot_variant p_variant, char *p_string); +void GDAPI godot_variant_set_vector2(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_rect2(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_vector3(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_matrix32(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_plane(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_aabb(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_matrix3(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_transform(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_color(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_set_image(godot_variant p_variant, godot_image *p_image); +void GDAPI godot_variant_set_node_path(godot_variant p_variant, char *p_path); +void GDAPI godot_variant_set_rid(godot_variant p_variant, char *p_path); +void GDAPI godot_variant_set_instance(godot_variant p_variant, godot_instance p_instance); +void GDAPI godot_variant_set_input_event(godot_variant p_variant, godot_input_event p_instance); +void GDAPI godot_variant_set_dictionary(godot_variant p_variant, godot_dictionary p_dictionary); +void GDAPI godot_variant_set_array(godot_variant p_variant, godot_array p_array); +void GDAPI godot_variant_set_byte_array(godot_variant p_variant, godot_byte_array p_array); +void GDAPI godot_variant_set_int_array(godot_variant p_variant, godot_byte_array p_array); +void GDAPI godot_variant_set_string_array(godot_variant p_variant, godot_string_array p_array); +void GDAPI godot_variant_set_vector2_array(godot_variant p_variant, godot_vector2_array p_array); +void GDAPI godot_variant_set_vector3_array(godot_variant p_variant, godot_vector3_array p_array); +void GDAPI godot_variant_set_color_array(godot_variant p_variant, godot_color_array p_array); godot_bool GDAPI godot_variant_get_bool(godot_variant p_variant); int GDAPI godot_variant_get_int(godot_variant p_variant); float GDAPI godot_variant_get_float(godot_variant p_variant); -int GDAPI godot_variant_get_string(godot_variant p_variant,char *p_string,int p_bufsize); -void GDAPI godot_variant_get_vector2(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_rect2(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_vector3(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_matrix32(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_plane(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_aabb(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_matrix3(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_transform(godot_variant p_variant,float *p_elems); -void GDAPI godot_variant_get_color(godot_variant p_variant,float *p_elems); +int GDAPI godot_variant_get_string(godot_variant p_variant, char *p_string, int p_bufsize); +void GDAPI godot_variant_get_vector2(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_rect2(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_vector3(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_matrix32(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_plane(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_aabb(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_matrix3(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_transform(godot_variant p_variant, float *p_elems); +void GDAPI godot_variant_get_color(godot_variant p_variant, float *p_elems); godot_image GDAPI *godot_variant_get_image(godot_variant p_variant); -int GDAPI godot_variant_get_node_path(godot_variant p_variant,char *p_path, int p_bufsize); +int GDAPI godot_variant_get_node_path(godot_variant p_variant, char *p_path, int p_bufsize); godot_rid GDAPI godot_variant_get_rid(godot_variant p_variant); godot_instance GDAPI godot_variant_get_instance(godot_variant p_variant); -void GDAPI godot_variant_get_input_event(godot_variant p_variant,godot_input_event); -void GDAPI godot_variant_get_dictionary(godot_variant p_variant,godot_dictionary); +void GDAPI godot_variant_get_input_event(godot_variant p_variant, godot_input_event); +void GDAPI godot_variant_get_dictionary(godot_variant p_variant, godot_dictionary); godot_array GDAPI godot_variant_get_array(godot_variant p_variant); godot_byte_array GDAPI godot_variant_get_byte_array(godot_variant p_variant); godot_byte_array GDAPI godot_variant_get_int_array(godot_variant p_variant); @@ -435,7 +418,6 @@ godot_vector2_array GDAPI godot_variant_get_vector2_array(godot_variant p_varian godot_vector3_array GDAPI godot_variant_get_vector3_array(godot_variant p_variant); godot_color_array GDAPI godot_variant_get_color_array(godot_variant p_variant); - void GDAPI godot_variant_delete(godot_variant p_variant); ////// Class @@ -443,17 +425,16 @@ void GDAPI godot_variant_delete(godot_variant p_variant); char GDAPI **godot_class_get_list(); //get list of classes in array to array of strings, must be freed, use godot_list_free() -int GDAPI godot_class_get_base(char* p_class,char *p_base,int p_max_len); -int GDAPI godot_class_get_name(char* p_class,char *p_base,int p_max_len); - -char GDAPI **godot_class_get_method_list(char* p_class); //free with godot_list_free() -int GDAPI godot_class_method_get_argument_count(char* p_class,char *p_method); -int GDAPI godot_class_method_get_argument_type(char* p_class,char *p_method,int p_argument); -godot_variant GDAPI godot_class_method_get_argument_default_value(char* p_class,char *p_method,int p_argument); +int GDAPI godot_class_get_base(char *p_class, char *p_base, int p_max_len); +int GDAPI godot_class_get_name(char *p_class, char *p_base, int p_max_len); -char GDAPI **godot_class_get_constant_list(char* p_class); //free with godot_list_free() -int GDAPI godot_class_constant_get_value(char* p_class,char *p_constant); +char GDAPI **godot_class_get_method_list(char *p_class); //free with godot_list_free() +int GDAPI godot_class_method_get_argument_count(char *p_class, char *p_method); +int GDAPI godot_class_method_get_argument_type(char *p_class, char *p_method, int p_argument); +godot_variant GDAPI godot_class_method_get_argument_default_value(char *p_class, char *p_method, int p_argument); +char GDAPI **godot_class_get_constant_list(char *p_class); //free with godot_list_free() +int GDAPI godot_class_constant_get_value(char *p_class, char *p_constant); ////// Instance @@ -463,8 +444,8 @@ typedef int godot_call_error; #define GODOT_CALL_ERROR_WRONG_ARGUMENTS #define GODOT_CALL_ERROR_INVALID_INSTANCE -godot_instance GDAPI godot_instance_new(char* p_class); -int GDAPI godot_instance_get_class(godot_instance p_instance,char* p_class,int p_max_len); +godot_instance GDAPI godot_instance_new(char *p_class); +int GDAPI godot_instance_get_class(godot_instance p_instance, char *p_class, int p_max_len); typedef struct { char *name; @@ -473,34 +454,32 @@ typedef struct { int usage; } godot_property_info; -godot_call_error GDAPI godot_instance_call(godot_instance p_instance, char* p_method, ...); -godot_call_error GDAPI godot_instance_call_ret(godot_instance p_instance, godot_variant r_return, char* p_method, ...); -godot_bool GDAPI godot_instance_set(godot_instance p_instance, char* p_prop,godot_variant p_value); -godot_variant GDAPI godot_instance_get(godot_instance p_instance, char* p_prop); - +godot_call_error GDAPI godot_instance_call(godot_instance p_instance, char *p_method, ...); +godot_call_error GDAPI godot_instance_call_ret(godot_instance p_instance, godot_variant r_return, char *p_method, ...); +godot_bool GDAPI godot_instance_set(godot_instance p_instance, char *p_prop, godot_variant p_value); +godot_variant GDAPI godot_instance_get(godot_instance p_instance, char *p_prop); #define GODOT_PROPERTY_HINT_NONE 0 ///< no hint provided. -#define GODOT_PROPERTY_HINT_RANGE 1///< hint_text = "min,max,step,slider; //slider is optional" -#define GODOT_PROPERTY_HINT_EXP_RANGE 2///< hint_text = "min,max,step", exponential edit -#define GODOT_PROPERTY_HINT_ENUM 3///< hint_text= "val1,val2,val3,etc" -#define GODOT_PROPERTY_HINT_EXP_EASING 4/// exponential easing funciton (Math::ease) -#define GODOT_PROPERTY_HINT_LENGTH 5///< hint_text= "length" (as integer) +#define GODOT_PROPERTY_HINT_RANGE 1 ///< hint_text = "min,max,step,slider; //slider is optional" +#define GODOT_PROPERTY_HINT_EXP_RANGE 2 ///< hint_text = "min,max,step", exponential edit +#define GODOT_PROPERTY_HINT_ENUM 3 ///< hint_text= "val1,val2,val3,etc" +#define GODOT_PROPERTY_HINT_EXP_EASING 4 /// exponential easing funciton (Math::ease) +#define GODOT_PROPERTY_HINT_LENGTH 5 ///< hint_text= "length" (as integer) #define GODOT_PROPERTY_HINT_SPRITE_FRAME 6 -#define GODOT_PROPERTY_HINT_KEY_ACCEL 7///< hint_text= "length" (as integer) -#define GODOT_PROPERTY_HINT_FLAGS 8///< hint_text= "flag1,flag2,etc" (as bit flags) +#define GODOT_PROPERTY_HINT_KEY_ACCEL 7 ///< hint_text= "length" (as integer) +#define GODOT_PROPERTY_HINT_FLAGS 8 ///< hint_text= "flag1,flag2,etc" (as bit flags) #define GODOT_PROPERTY_HINT_ALL_FLAGS 9 #define GODOT_PROPERTY_HINT_FILE 10 ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," #define GODOT_PROPERTY_HINT_DIR 11 ///< a directort path must be passed -#define GODOT_PROPERTY_HINT_GLOBAL_FILE 12///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," +#define GODOT_PROPERTY_HINT_GLOBAL_FILE 12 ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," #define GODOT_PROPERTY_HINT_GLOBAL_DIR 13 ///< a directort path must be passed -#define GODOT_PROPERTY_HINT_RESOURCE_TYPE 14///< a resource object type -#define GODOT_PROPERTY_HINT_MULTILINE_TEXT 15///< used for string properties that can contain multiple lines -#define GODOT_PROPERTY_HINT_COLOR_NO_ALPHA 16///< used for ignoring alpha component when editing a color +#define GODOT_PROPERTY_HINT_RESOURCE_TYPE 14 ///< a resource object type +#define GODOT_PROPERTY_HINT_MULTILINE_TEXT 15 ///< used for string properties that can contain multiple lines +#define GODOT_PROPERTY_HINT_COLOR_NO_ALPHA 16 ///< used for ignoring alpha component when editing a color #define GODOT_PROPERTY_HINT_IMAGE_COMPRESS_LOSSY 17 #define GODOT_PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS 18 #define GODOT_PROPERTY_HINT_OBJECT_ID 19 - #define GODOT_PROPERTY_USAGE_STORAGE 1 #define GODOT_PROPERTY_USAGE_EDITOR 2 #define GODOT_PROPERTY_USAGE_NETWORK 4 @@ -518,51 +497,43 @@ godot_variant GDAPI godot_instance_get(godot_instance p_instance, char* p_prop); #define GODOT_PROPERTY_USAGE_STORE_IF_NULL 16384 #define GODOT_PROPERTY_USAGE_ANIMATE_AS_TRIGGER 32768 -#define GODOT_PROPERTY_USAGE_DEFAULT GODOT_PROPERTY_USAGE_STORAGE|GODOT_PROPERTY_USAGE_EDITOR|GODOT_PROPERTY_USAGE_NETWORK -#define GODOT_PROPERTY_USAGE_DEFAULT_INTL GODOT_PROPERTY_USAGE_STORAGE|GODOT_PROPERTY_USAGE_EDITOR|GODOT_PROPERTY_USAGE_NETWORK|GODOT_PROPERTY_USAGE_INTERNATIONALIZED -#define GODOT_PROPERTY_USAGE_NOEDITOR GODOT_PROPERTY_USAGE_STORAGE|GODOT_PROPERTY_USAGE_NETWORK - +#define GODOT_PROPERTY_USAGE_DEFAULT GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK +#define GODOT_PROPERTY_USAGE_DEFAULT_INTL GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK | GODOT_PROPERTY_USAGE_INTERNATIONALIZED +#define GODOT_PROPERTY_USAGE_NOEDITOR GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_NETWORK godot_property_info GDAPI **godot_instance_get_property_list(godot_instance p_instance); -void GDAPI godot_instance_free_property_list(godot_instance p_instance,godot_property_info** p_list); - - +void GDAPI godot_instance_free_property_list(godot_instance p_instance, godot_property_info **p_list); void GDAPI godot_list_free(char **p_name); //helper to free all the class list - ////// Script API -typedef void* (godot_script_instance_func)(godot_instance); //passed an instance, return a pointer to your userdata -typedef void (godot_script_free_func)(godot_instance,void*); //passed an instance, please free your userdata - -void GDAPI godot_script_register(char* p_base,char* p_name,godot_script_instance_func p_instance_func,godot_script_free_func p_free_func); -void GDAPI godot_script_unregister(char* p_name); +typedef void *(godot_script_instance_func)(godot_instance); //passed an instance, return a pointer to your userdata +typedef void(godot_script_free_func)(godot_instance, void *); //passed an instance, please free your userdata -typedef GDAPI godot_variant (godot_script_func)(godot_instance,void*,godot_variant*,int); //instance,userdata,arguments,argument count. Return something or NULL. Arguments must not be freed. +void GDAPI godot_script_register(char *p_base, char *p_name, godot_script_instance_func p_instance_func, godot_script_free_func p_free_func); +void GDAPI godot_script_unregister(char *p_name); +typedef GDAPI godot_variant(godot_script_func)(godot_instance, void *, godot_variant *, int); //instance,userdata,arguments,argument count. Return something or NULL. Arguments must not be freed. -void GDAPI godot_script_add_function(char* p_name,char* p_function_name,godot_script_func p_func); -void GDAPI godot_script_add_validated_function(char* p_name,char* p_function_name,godot_script_func p_func,int* p_arg_types,int p_arg_count,godot_variant* p_default_args,int p_default_arg_count); +void GDAPI godot_script_add_function(char *p_name, char *p_function_name, godot_script_func p_func); +void GDAPI godot_script_add_validated_function(char *p_name, char *p_function_name, godot_script_func p_func, int *p_arg_types, int p_arg_count, godot_variant *p_default_args, int p_default_arg_count); -typedef void (godot_set_property_func)(godot_instance,void*,godot_variant); //instance,userdata,value. Value must not be freed. -typedef godot_variant (godot_get_property_func)(godot_instance,void*); //instance,userdata. Return a value or NULL. - -void GDAPI godot_script_add_property(char* p_name,char* p_path,godot_set_property_func p_set_func,godot_get_property_func p_get_func); -void GDAPI godot_script_add_listed_property(char* p_name,char* p_path,godot_set_property_func p_set_func,godot_get_property_func p_get_func,int p_type,int p_hint,char* p_hint_string,int p_usage); +typedef void(godot_set_property_func)(godot_instance, void *, godot_variant); //instance,userdata,value. Value must not be freed. +typedef godot_variant(godot_get_property_func)(godot_instance, void *); //instance,userdata. Return a value or NULL. +void GDAPI godot_script_add_property(char *p_name, char *p_path, godot_set_property_func p_set_func, godot_get_property_func p_get_func); +void GDAPI godot_script_add_listed_property(char *p_name, char *p_path, godot_set_property_func p_set_func, godot_get_property_func p_get_func, int p_type, int p_hint, char *p_hint_string, int p_usage); ////// System Functions //using these will help Godot track how much memory is in use in debug mode void GDAPI *godot_alloc(int p_bytes); -void GDAPI *godot_realloc(void* p_ptr,int p_bytes); -void GDAPI godot_free(void* p_ptr); - +void GDAPI *godot_realloc(void *p_ptr, int p_bytes); +void GDAPI godot_free(void *p_ptr); #ifdef __cplusplus } #endif - #endif // GODOT_C_H diff --git a/modules/cscript/register_types.cpp b/modules/cscript/register_types.cpp index d2101bbd4..2477bc51e 100644 --- a/modules/cscript/register_types.cpp +++ b/modules/cscript/register_types.cpp @@ -28,10 +28,7 @@ /*************************************************************************/ #include "register_types.h" - void register_cscript_types() { - } void unregister_cscript_types() { - } diff --git a/modules/dds/register_types.cpp b/modules/dds/register_types.cpp index 917305f54..d0eaf3f99 100644 --- a/modules/dds/register_types.cpp +++ b/modules/dds/register_types.cpp @@ -34,7 +34,7 @@ static ResourceFormatDDS *resource_loader_dds = NULL; void register_dds_types() { - resource_loader_dds = memnew( ResourceFormatDDS ); + resource_loader_dds = memnew(ResourceFormatDDS); ResourceLoader::add_resource_format_loader(resource_loader_dds); } diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index 59d4238e4..0b34872b7 100644 --- a/modules/dds/texture_loader_dds.cpp +++ b/modules/dds/texture_loader_dds.cpp @@ -29,18 +29,17 @@ #include "texture_loader_dds.h" #include "os/file_access.h" - enum { - DDS_MAGIC=0x20534444, - DDSD_CAPS=0x00000001, - DDSD_PIXELFORMAT=0x00001000, - DDSD_PITCH=0x00000008, - DDSD_LINEARSIZE=0x00080000, - DDSD_MIPMAPCOUNT=0x00020000, - DDPF_FOURCC=0x00000004, - DDPF_ALPHAPIXELS=0x00000001, - DDPF_INDEXED=0x00000020, - DDPF_RGB=0x00000040, + DDS_MAGIC = 0x20534444, + DDSD_CAPS = 0x00000001, + DDSD_PIXELFORMAT = 0x00001000, + DDSD_PITCH = 0x00000008, + DDSD_LINEARSIZE = 0x00080000, + DDSD_MIPMAPCOUNT = 0x00020000, + DDPF_FOURCC = 0x00000004, + DDPF_ALPHAPIXELS = 0x00000001, + DDPF_INDEXED = 0x00000020, + DDPF_RGB = 0x00000040, }; enum DDSFormat { @@ -72,42 +71,40 @@ struct DDSFormatInfo { Image::Format format; }; - -static const DDSFormatInfo dds_format_info[DDS_MAX]={ - {"DXT1",true,false,4,8,Image::FORMAT_BC1}, - {"DXT3",true,false,4,16,Image::FORMAT_BC2}, - {"DXT5",true,false,4,16,Image::FORMAT_BC3}, - {"ATI1",true,false,4,8,Image::FORMAT_BC4}, - {"ATI2",true,false,4,16,Image::FORMAT_BC5}, - {"BGRA8",false,false,1,4,Image::FORMAT_RGBA}, - {"BGR8",false,false,1,3,Image::FORMAT_RGB}, - {"RGBA8",false,false,1,4,Image::FORMAT_RGBA}, - {"RGB8",false,false,1,3,Image::FORMAT_RGB}, - {"BGR5A1",false,false,1,2,Image::FORMAT_RGBA}, - {"BGR565",false,false,1,2,Image::FORMAT_RGB}, - {"BGR10A2",false,false,1,4,Image::FORMAT_RGBA}, - {"INDEXED",false,true,1,1,Image::FORMAT_INDEXED}, - {"GRAYSCALE",false,false,1,1,Image::FORMAT_GRAYSCALE}, - {"GRAYSCALE_ALPHA",false,false,1,2,Image::FORMAT_GRAYSCALE_ALPHA} +static const DDSFormatInfo dds_format_info[DDS_MAX] = { + { "DXT1", true, false, 4, 8, Image::FORMAT_BC1 }, + { "DXT3", true, false, 4, 16, Image::FORMAT_BC2 }, + { "DXT5", true, false, 4, 16, Image::FORMAT_BC3 }, + { "ATI1", true, false, 4, 8, Image::FORMAT_BC4 }, + { "ATI2", true, false, 4, 16, Image::FORMAT_BC5 }, + { "BGRA8", false, false, 1, 4, Image::FORMAT_RGBA }, + { "BGR8", false, false, 1, 3, Image::FORMAT_RGB }, + { "RGBA8", false, false, 1, 4, Image::FORMAT_RGBA }, + { "RGB8", false, false, 1, 3, Image::FORMAT_RGB }, + { "BGR5A1", false, false, 1, 2, Image::FORMAT_RGBA }, + { "BGR565", false, false, 1, 2, Image::FORMAT_RGB }, + { "BGR10A2", false, false, 1, 4, Image::FORMAT_RGBA }, + { "INDEXED", false, true, 1, 1, Image::FORMAT_INDEXED }, + { "GRAYSCALE", false, false, 1, 1, Image::FORMAT_GRAYSCALE }, + { "GRAYSCALE_ALPHA", false, false, 1, 2, Image::FORMAT_GRAYSCALE_ALPHA } }; - -RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return RES(); FileAccessRef fref(f); if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; - ERR_EXPLAIN("Unable to open DDS texture file: "+p_path); - ERR_FAIL_COND_V(err!=OK,RES()); + ERR_EXPLAIN("Unable to open DDS texture file: " + p_path); + ERR_FAIL_COND_V(err != OK, RES()); uint32_t magic = f->get_32(); uint32_t hsize = f->get_32(); @@ -119,18 +116,17 @@ RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path, uint32_t mipmaps = f->get_32(); //skip 11 - for(int i=0;i<11;i++) + for (int i = 0; i < 11; i++) f->get_32(); //validate - if (magic!=DDS_MAGIC || hsize!=124 || !(flags&DDSD_PIXELFORMAT) || !(flags&DDSD_CAPS)) { + if (magic != DDS_MAGIC || hsize != 124 || !(flags & DDSD_PIXELFORMAT) || !(flags & DDSD_CAPS)) { - ERR_EXPLAIN("Invalid or Unsupported DDS texture file: "+p_path); + ERR_EXPLAIN("Invalid or Unsupported DDS texture file: " + p_path); ERR_FAIL_V(RES()); } - uint32_t format_size = f->get_32(); uint32_t format_flags = f->get_32(); uint32_t format_fourcc = f->get_32(); @@ -156,258 +152,249 @@ RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path, //printf("rmask: %x gmask: %x, bmask: %x, amask: %x\n",format_red_mask,format_green_mask,format_blue_mask,format_alpha_mask); //must avoid this later - while(f->get_pos()<128) + while (f->get_pos() < 128) f->get_8(); - DDSFormat dds_format; - if (format_flags&DDPF_FOURCC && format_fourcc==0x31545844) { //'1TXD' + if (format_flags & DDPF_FOURCC && format_fourcc == 0x31545844) { //'1TXD' - dds_format=DDS_DXT1; - } else if (format_flags&DDPF_FOURCC && format_fourcc==0x33545844) { //'3TXD' + dds_format = DDS_DXT1; + } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x33545844) { //'3TXD' - dds_format=DDS_DXT3; + dds_format = DDS_DXT3; - } else if (format_flags&DDPF_FOURCC && format_fourcc==0x35545844) { //'5TXD' + } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x35545844) { //'5TXD' - dds_format=DDS_DXT5; - } else if (format_flags&DDPF_FOURCC && format_fourcc==0x31495441) { //'1ITA' + dds_format = DDS_DXT5; + } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x31495441) { //'1ITA' - dds_format=DDS_ATI1; - } else if (format_flags&DDPF_FOURCC && format_fourcc==0x32495441) { //'2ITA' + dds_format = DDS_ATI1; + } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x32495441) { //'2ITA' - dds_format=DDS_ATI2; + dds_format = DDS_ATI2; - } else if (format_flags&DDPF_RGB && format_flags&DDPF_ALPHAPIXELS && format_rgb_bits==32 && format_red_mask==0xff0000 && format_green_mask==0xff00 && format_blue_mask==0xff && format_alpha_mask==0xff000000) { + } else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0xff0000 && format_green_mask == 0xff00 && format_blue_mask == 0xff && format_alpha_mask == 0xff000000) { - dds_format=DDS_BGRA8; - } else if (format_flags&DDPF_RGB && !(format_flags&DDPF_ALPHAPIXELS ) && format_rgb_bits==24 && format_red_mask==0xff0000 && format_green_mask==0xff00 && format_blue_mask==0xff) { + dds_format = DDS_BGRA8; + } else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 24 && format_red_mask == 0xff0000 && format_green_mask == 0xff00 && format_blue_mask == 0xff) { - dds_format=DDS_BGR8; - } else if (format_flags&DDPF_RGB && format_flags&DDPF_ALPHAPIXELS && format_rgb_bits==32 && format_red_mask==0xff && format_green_mask==0xff00 && format_blue_mask==0xff0000 && format_alpha_mask==0xff000000) { + dds_format = DDS_BGR8; + } else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0xff && format_green_mask == 0xff00 && format_blue_mask == 0xff0000 && format_alpha_mask == 0xff000000) { - dds_format=DDS_RGBA8; - } else if (format_flags&DDPF_RGB && !(format_flags&DDPF_ALPHAPIXELS ) && format_rgb_bits==24 && format_red_mask==0xff && format_green_mask==0xff00 && format_blue_mask==0xff0000) { + dds_format = DDS_RGBA8; + } else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 24 && format_red_mask == 0xff && format_green_mask == 0xff00 && format_blue_mask == 0xff0000) { - dds_format=DDS_RGB8; + dds_format = DDS_RGB8; - } else if (format_flags&DDPF_RGB && format_flags&DDPF_ALPHAPIXELS && format_rgb_bits==16 && format_red_mask==0x00007c00 && format_green_mask==0x000003e0 && format_blue_mask==0x0000001f && format_alpha_mask==0x00008000) { + } else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 16 && format_red_mask == 0x00007c00 && format_green_mask == 0x000003e0 && format_blue_mask == 0x0000001f && format_alpha_mask == 0x00008000) { - dds_format=DDS_BGR5A1; - } else if (format_flags&DDPF_RGB && format_flags&DDPF_ALPHAPIXELS && format_rgb_bits==32 && format_red_mask==0x3ff00000 && format_green_mask==0xffc00 && format_blue_mask==0x3ff && format_alpha_mask==0xc0000000) { + dds_format = DDS_BGR5A1; + } else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0x3ff00000 && format_green_mask == 0xffc00 && format_blue_mask == 0x3ff && format_alpha_mask == 0xc0000000) { - dds_format=DDS_BGR10A2; - } else if (format_flags&DDPF_RGB && !(format_flags&DDPF_ALPHAPIXELS) && format_rgb_bits==16 && format_red_mask==0x0000f800 && format_green_mask==0x000007e0 && format_blue_mask==0x0000001f) { + dds_format = DDS_BGR10A2; + } else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0x0000f800 && format_green_mask == 0x000007e0 && format_blue_mask == 0x0000001f) { - dds_format=DDS_BGR565; - } else if (!(format_flags&DDPF_ALPHAPIXELS) && format_rgb_bits==8 && format_red_mask==0xff && format_green_mask==0xff && format_blue_mask==0xff) { + dds_format = DDS_BGR565; + } else if (!(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 8 && format_red_mask == 0xff && format_green_mask == 0xff && format_blue_mask == 0xff) { - dds_format=DDS_LUMINANCE; - } else if ((format_flags&DDPF_ALPHAPIXELS) && format_rgb_bits==16 && format_red_mask==0xff && format_green_mask==0xff && format_blue_mask==0xff && format_alpha_mask==0xff00) { + dds_format = DDS_LUMINANCE; + } else if ((format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0xff && format_green_mask == 0xff && format_blue_mask == 0xff && format_alpha_mask == 0xff00) { - dds_format=DDS_LUMINANCE_ALPHA; - } else if (format_flags&DDPF_INDEXED && format_rgb_bits==8) { + dds_format = DDS_LUMINANCE_ALPHA; + } else if (format_flags & DDPF_INDEXED && format_rgb_bits == 8) { - dds_format=DDS_BGR565; + dds_format = DDS_BGR565; } else { - printf("unrecognized fourcc %x format_flags: %x - rgbbits %i - red_mask %x green mask %x blue mask %x alpha mask %x\n",format_fourcc,format_flags,format_rgb_bits,format_red_mask,format_green_mask,format_blue_mask,format_alpha_mask); - ERR_EXPLAIN("Unrecognized or Unsupported color layout in DDS: "+p_path); + printf("unrecognized fourcc %x format_flags: %x - rgbbits %i - red_mask %x green mask %x blue mask %x alpha mask %x\n", format_fourcc, format_flags, format_rgb_bits, format_red_mask, format_green_mask, format_blue_mask, format_alpha_mask); + ERR_EXPLAIN("Unrecognized or Unsupported color layout in DDS: " + p_path); ERR_FAIL_V(RES()); - } - if (!(flags&DDSD_MIPMAPCOUNT)) - mipmaps=1; + if (!(flags & DDSD_MIPMAPCOUNT)) + mipmaps = 1; -// print_line("found format: "+String(dds_format_info[dds_format].name)); + // print_line("found format: "+String(dds_format_info[dds_format].name)); DVector<uint8_t> src_data; - const DDSFormatInfo &info=dds_format_info[dds_format]; + const DDSFormatInfo &info = dds_format_info[dds_format]; uint32_t w = width; uint32_t h = height; - if (info.compressed) { //compressed bc - uint32_t size = MAX( info.divisor, w )/info.divisor * MAX( info.divisor, h )/info.divisor * info.block_size; - ERR_FAIL_COND_V( size!=pitch, RES() ); - ERR_FAIL_COND_V( !(flags&DDSD_LINEARSIZE), RES() ); + uint32_t size = MAX(info.divisor, w) / info.divisor * MAX(info.divisor, h) / info.divisor * info.block_size; + ERR_FAIL_COND_V(size != pitch, RES()); + ERR_FAIL_COND_V(!(flags & DDSD_LINEARSIZE), RES()); - for(uint32_t i=1;i<mipmaps;i++) { + for (uint32_t i = 1; i < mipmaps; i++) { - w=MAX(1,w>>1); - h=MAX(1,h>>1); - uint32_t bsize = MAX( info.divisor, w )/info.divisor * MAX( info.divisor, h )/info.divisor * info.block_size; + w = MAX(1, w >> 1); + h = MAX(1, h >> 1); + uint32_t bsize = MAX(info.divisor, w) / info.divisor * MAX(info.divisor, h) / info.divisor * info.block_size; //printf("%i x %i - block: %i\n",w,h,bsize); - size+= bsize; + size += bsize; } src_data.resize(size); DVector<uint8_t>::Write wb = src_data.write(); - f->get_buffer(wb.ptr(),size); - wb=DVector<uint8_t>::Write(); + f->get_buffer(wb.ptr(), size); + wb = DVector<uint8_t>::Write(); } else if (info.palette) { //indexed - ERR_FAIL_COND_V( !(flags&DDSD_PITCH), RES()); - ERR_FAIL_COND_V( format_rgb_bits!=8, RES() ); + ERR_FAIL_COND_V(!(flags & DDSD_PITCH), RES()); + ERR_FAIL_COND_V(format_rgb_bits != 8, RES()); - uint32_t size = pitch*height; - ERR_FAIL_COND_V( size != width*height * info.block_size, RES()); + uint32_t size = pitch * height; + ERR_FAIL_COND_V(size != width * height * info.block_size, RES()); - uint8_t pallete[256*4]; - f->get_buffer(pallete,256*4); + uint8_t pallete[256 * 4]; + f->get_buffer(pallete, 256 * 4); - int colsize=3; - for(int i=0;i<256;i++) { + int colsize = 3; + for (int i = 0; i < 256; i++) { - if (pallete[i*4+3]<255) - colsize=4; + if (pallete[i * 4 + 3] < 255) + colsize = 4; } int w = width; int h = height; - for(uint32_t i=1;i<mipmaps;i++) { + for (uint32_t i = 1; i < mipmaps; i++) { - w=(w+1)>>1; - h=(h+1)>>1; - size+= w*h*info.block_size; + w = (w + 1) >> 1; + h = (h + 1) >> 1; + size += w * h * info.block_size; } - src_data.resize(size + 256*colsize ); + src_data.resize(size + 256 * colsize); DVector<uint8_t>::Write wb = src_data.write(); - f->get_buffer(wb.ptr(),size); + f->get_buffer(wb.ptr(), size); - for(int i=0;i<256;i++) { + for (int i = 0; i < 256; i++) { - int dst_ofs = size+i*colsize; - int src_ofs = i*4; - wb[dst_ofs+0]=pallete[src_ofs+2]; - wb[dst_ofs+1]=pallete[src_ofs+1]; - wb[dst_ofs+2]=pallete[src_ofs+0]; - if (colsize==4) - wb[dst_ofs+3]=pallete[src_ofs+3]; + int dst_ofs = size + i * colsize; + int src_ofs = i * 4; + wb[dst_ofs + 0] = pallete[src_ofs + 2]; + wb[dst_ofs + 1] = pallete[src_ofs + 1]; + wb[dst_ofs + 2] = pallete[src_ofs + 0]; + if (colsize == 4) + wb[dst_ofs + 3] = pallete[src_ofs + 3]; } - - wb=DVector<uint8_t>::Write(); + wb = DVector<uint8_t>::Write(); } else { //uncompressed generic... - uint32_t size = width*height*info.block_size; - + uint32_t size = width * height * info.block_size; - for(uint32_t i=1;i<mipmaps;i++) { + for (uint32_t i = 1; i < mipmaps; i++) { - w=(w+1)>>1; - h=(h+1)>>1; - size+= w*h*info.block_size; + w = (w + 1) >> 1; + h = (h + 1) >> 1; + size += w * h * info.block_size; } - if (dds_format==DDS_BGR565) - size=size*3/2; - else if (dds_format==DDS_BGR5A1) - size=size*2; + if (dds_format == DDS_BGR565) + size = size * 3 / 2; + else if (dds_format == DDS_BGR5A1) + size = size * 2; src_data.resize(size); DVector<uint8_t>::Write wb = src_data.write(); - f->get_buffer(wb.ptr(),size); - + f->get_buffer(wb.ptr(), size); - switch(dds_format) { + switch (dds_format) { case DDS_BGR5A1: { // TO RGBA - int colcount = size/4; + int colcount = size / 4; - for(int i=colcount-1;i>=0;i--) { + for (int i = colcount - 1; i >= 0; i--) { - int src_ofs = i*2; - int dst_ofs = i*4; + int src_ofs = i * 2; + int dst_ofs = i * 4; - uint8_t a=wb[src_ofs+1]&0x80; - uint8_t b= wb[src_ofs]&0x1F; - uint8_t g= (wb[src_ofs]>>5) | ((wb[src_ofs+1]&0x3)<<3); - uint8_t r= (wb[src_ofs+1]>>2)&0x1F; - wb[dst_ofs+0]=r<<3; - wb[dst_ofs+1]=g<<3; - wb[dst_ofs+2]=b<<3; - wb[dst_ofs+3]=a?255:0; + uint8_t a = wb[src_ofs + 1] & 0x80; + uint8_t b = wb[src_ofs] & 0x1F; + uint8_t g = (wb[src_ofs] >> 5) | ((wb[src_ofs + 1] & 0x3) << 3); + uint8_t r = (wb[src_ofs + 1] >> 2) & 0x1F; + wb[dst_ofs + 0] = r << 3; + wb[dst_ofs + 1] = g << 3; + wb[dst_ofs + 2] = b << 3; + wb[dst_ofs + 3] = a ? 255 : 0; } } break; case DDS_BGR565: { - int colcount = size/3; - - for(int i=colcount-1;i>=0;i--) { + int colcount = size / 3; - int src_ofs = i*2; - int dst_ofs = i*3; + for (int i = colcount - 1; i >= 0; i--) { - uint8_t b= wb[src_ofs]&0x1F; - uint8_t g= (wb[src_ofs]>>5) | ((wb[src_ofs+1]&0x7)<<3); - uint8_t r= wb[src_ofs+1]>>3; - wb[dst_ofs+0]=r<<3; - wb[dst_ofs+1]=g<<2; - wb[dst_ofs+2]=b<<3;//b<<3; + int src_ofs = i * 2; + int dst_ofs = i * 3; + uint8_t b = wb[src_ofs] & 0x1F; + uint8_t g = (wb[src_ofs] >> 5) | ((wb[src_ofs + 1] & 0x7) << 3); + uint8_t r = wb[src_ofs + 1] >> 3; + wb[dst_ofs + 0] = r << 3; + wb[dst_ofs + 1] = g << 2; + wb[dst_ofs + 2] = b << 3; //b<<3; } } break; case DDS_BGR10A2: { // TO RGBA - int colcount = size/4; - - for(int i=colcount-1;i>=0;i--) { - - int ofs = i*4; + int colcount = size / 4; - uint32_t w32 = uint32_t(wb[ofs+0]) | (uint32_t(wb[ofs+1])<<8) | (uint32_t(wb[ofs+2])<<16) | (uint32_t(wb[ofs+3])<<24); + for (int i = colcount - 1; i >= 0; i--) { - uint8_t a= (w32&0xc0000000) >> 24; - uint8_t r= (w32&0x3ff00000) >> 22; - uint8_t g= (w32&0xffc00) >> 12; - uint8_t b= (w32&0x3ff) >> 2; + int ofs = i * 4; + uint32_t w32 = uint32_t(wb[ofs + 0]) | (uint32_t(wb[ofs + 1]) << 8) | (uint32_t(wb[ofs + 2]) << 16) | (uint32_t(wb[ofs + 3]) << 24); - wb[ofs+0]=r; - wb[ofs+1]=g; - wb[ofs+2]=b; - wb[ofs+3]=a==0xc0 ? 255 : a; //0xc0 should be opaque + uint8_t a = (w32 & 0xc0000000) >> 24; + uint8_t r = (w32 & 0x3ff00000) >> 22; + uint8_t g = (w32 & 0xffc00) >> 12; + uint8_t b = (w32 & 0x3ff) >> 2; + wb[ofs + 0] = r; + wb[ofs + 1] = g; + wb[ofs + 2] = b; + wb[ofs + 3] = a == 0xc0 ? 255 : a; //0xc0 should be opaque } } break; case DDS_BGRA8: { - int colcount = size/4; + int colcount = size / 4; - for(int i=0;i<colcount;i++) { + for (int i = 0; i < colcount; i++) { - SWAP( wb[i*4+0],wb[i*4+2] ); + SWAP(wb[i * 4 + 0], wb[i * 4 + 2]); } } break; case DDS_BGR8: { - int colcount = size/3; + int colcount = size / 3; - for(int i=0;i<colcount;i++) { + for (int i = 0; i < colcount; i++) { - SWAP( wb[i*3+0],wb[i*3+2] ); + SWAP(wb[i * 3 + 0], wb[i * 3 + 2]); } } break; case DDS_RGBA8: { - /* do nothing either + /* do nothing either int colcount = size/4; for(int i=0;i<colcount;i++) { @@ -447,24 +434,20 @@ RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path, } break; default: {} - } - wb=DVector<uint8_t>::Write(); + wb = DVector<uint8_t>::Write(); } + Image img(width, height, mipmaps - 1, info.format, src_data); - Image img(width,height,mipmaps-1,info.format,src_data); - - Ref<ImageTexture> texture = memnew( ImageTexture ); + Ref<ImageTexture> texture = memnew(ImageTexture); texture->create_from_image(img); if (r_error) - *r_error=OK; - + *r_error = OK; return texture; - } void ResourceFormatDDS::get_recognized_extensions(List<String> *p_extensions) const { @@ -472,14 +455,14 @@ void ResourceFormatDDS::get_recognized_extensions(List<String> *p_extensions) co p_extensions->push_back("dds"); } -bool ResourceFormatDDS::handles_type(const String& p_type) const { +bool ResourceFormatDDS::handles_type(const String &p_type) const { - return ObjectTypeDB::is_type(p_type,"Texture"); + return ObjectTypeDB::is_type(p_type, "Texture"); } String ResourceFormatDDS::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="dds") + if (p_path.extension().to_lower() == "dds") return "ImageTexture"; return ""; } diff --git a/modules/dds/texture_loader_dds.h b/modules/dds/texture_loader_dds.h index d09af680c..c347937cd 100644 --- a/modules/dds/texture_loader_dds.h +++ b/modules/dds/texture_loader_dds.h @@ -29,15 +29,14 @@ #ifndef TEXTURE_LOADER_DDS_H #define TEXTURE_LOADER_DDS_H -#include "scene/resources/texture.h" #include "io/resource_loader.h" +#include "scene/resources/texture.h" -class ResourceFormatDDS : public ResourceFormatLoader{ +class ResourceFormatDDS : public ResourceFormatLoader { public: - - 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 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 ~ResourceFormatDDS() {} diff --git a/modules/etc1/image_etc.cpp b/modules/etc1/image_etc.cpp index fdca19046..b3ceb60ed 100644 --- a/modules/etc1/image_etc.cpp +++ b/modules/etc1/image_etc.cpp @@ -28,174 +28,152 @@ /*************************************************************************/ #include "image_etc.h" #include "image.h" -#include "rg_etc1.h" -#include "print_string.h" #include "os/copymem.h" +#include "print_string.h" +#include "rg_etc1.h" static void _decompress_etc(Image *p_img) { - ERR_FAIL_COND(p_img->get_format()!=Image::FORMAT_ETC); + ERR_FAIL_COND(p_img->get_format() != Image::FORMAT_ETC); int imgw = p_img->get_width(); int imgh = p_img->get_height(); - DVector<uint8_t> src=p_img->get_data(); + DVector<uint8_t> src = p_img->get_data(); DVector<uint8_t> dst; DVector<uint8_t>::Read r = src.read(); - int mmc=p_img->get_mipmaps(); + int mmc = p_img->get_mipmaps(); + for (int i = 0; i <= mmc; i++) { - for(int i=0;i<=mmc;i++) { - - dst.resize(dst.size()+imgw*imgh*3); - const uint8_t *srcbr=&r[p_img->get_mipmap_offset(i)]; + dst.resize(dst.size() + imgw * imgh * 3); + const uint8_t *srcbr = &r[p_img->get_mipmap_offset(i)]; DVector<uint8_t>::Write w = dst.write(); - uint8_t *wptr = &w[dst.size()-imgw*imgh*3]; - - int bw=MAX(imgw/4,1); - int bh=MAX(imgh/4,1); - - for(int y=0;y<bh;y++) { + uint8_t *wptr = &w[dst.size() - imgw * imgh * 3]; - for(int x=0;x<bw;x++) { + int bw = MAX(imgw / 4, 1); + int bh = MAX(imgh / 4, 1); - uint8_t block[4*4*4]; + for (int y = 0; y < bh; y++) { + for (int x = 0; x < bw; x++) { - rg_etc1::unpack_etc1_block(srcbr,(unsigned int*)block); - srcbr+=8; + uint8_t block[4 * 4 * 4]; - int maxx=MIN(imgw,4); - int maxy=MIN(imgh,4); + rg_etc1::unpack_etc1_block(srcbr, (unsigned int *)block); + srcbr += 8; - for(int yy=0;yy<maxy;yy++) { + int maxx = MIN(imgw, 4); + int maxy = MIN(imgh, 4); - for(int xx=0;xx<maxx;xx++) { + for (int yy = 0; yy < maxy; yy++) { - uint32_t src_ofs = (yy*4+xx)*4; - uint32_t dst_ofs = ((y*4+yy)*imgw+x*4+xx)*3; - wptr[dst_ofs+0]=block[src_ofs+0]; - wptr[dst_ofs+1]=block[src_ofs+1]; - wptr[dst_ofs+2]=block[src_ofs+2]; + for (int xx = 0; xx < maxx; xx++) { + uint32_t src_ofs = (yy * 4 + xx) * 4; + uint32_t dst_ofs = ((y * 4 + yy) * imgw + x * 4 + xx) * 3; + wptr[dst_ofs + 0] = block[src_ofs + 0]; + wptr[dst_ofs + 1] = block[src_ofs + 1]; + wptr[dst_ofs + 2] = block[src_ofs + 2]; } } - } - } - imgw=MAX(1,imgw/2); - imgh=MAX(1,imgh/2); + imgw = MAX(1, imgw / 2); + imgh = MAX(1, imgh / 2); } - - r=DVector<uint8_t>::Read(); + r = DVector<uint8_t>::Read(); //print_line("Re Creating ETC into regular image: w "+itos(p_img->get_width())+" h "+itos(p_img->get_height())+" mm "+itos(p_img->get_mipmaps())); - *p_img=Image(p_img->get_width(),p_img->get_height(),p_img->get_mipmaps(),Image::FORMAT_RGB,dst); + *p_img = Image(p_img->get_width(), p_img->get_height(), p_img->get_mipmaps(), Image::FORMAT_RGB, dst); if (p_img->get_mipmaps()) - p_img->generate_mipmaps(-1,true); - - + p_img->generate_mipmaps(-1, true); } static void _compress_etc(Image *p_img) { Image img = *p_img; - int imgw=img.get_width(),imgh=img.get_height(); + int imgw = img.get_width(), imgh = img.get_height(); - ERR_FAIL_COND( nearest_power_of_2(imgw)!=imgw || nearest_power_of_2(imgh)!=imgh ); + ERR_FAIL_COND(nearest_power_of_2(imgw) != imgw || nearest_power_of_2(imgh) != imgh); - if (img.get_format()!=Image::FORMAT_RGB) + if (img.get_format() != Image::FORMAT_RGB) img.convert(Image::FORMAT_RGB); - - int mmc=img.get_mipmaps(); - if (mmc==0) + int mmc = img.get_mipmaps(); + if (mmc == 0) img.generate_mipmaps(); // force mipmaps, so it works on most hardware - DVector<uint8_t> res_data; DVector<uint8_t> dst_data; DVector<uint8_t>::Read r = img.get_data().read(); - int mc=0; - + int mc = 0; rg_etc1::etc1_pack_params pp; - pp.m_quality=rg_etc1::cLowQuality; - for(int i=0;i<=mmc;i++) { + pp.m_quality = rg_etc1::cLowQuality; + for (int i = 0; i <= mmc; i++) { - - int bw=MAX(imgw/4,1); - int bh=MAX(imgh/4,1); + int bw = MAX(imgw / 4, 1); + int bh = MAX(imgh / 4, 1); const uint8_t *src = &r[img.get_mipmap_offset(i)]; - int mmsize = MAX(bw,1)*MAX(bh,1)*8; - dst_data.resize(dst_data.size()+mmsize); - DVector<uint8_t>::Write w=dst_data.write(); - uint8_t *dst = &w[dst_data.size()-mmsize]; - + int mmsize = MAX(bw, 1) * MAX(bh, 1) * 8; + dst_data.resize(dst_data.size() + mmsize); + DVector<uint8_t>::Write w = dst_data.write(); + uint8_t *dst = &w[dst_data.size() - mmsize]; -// print_line("bh: "+itos(bh)+" bw: "+itos(bw)); + // print_line("bh: "+itos(bh)+" bw: "+itos(bw)); - for(int y=0;y<bh;y++) { + for (int y = 0; y < bh; y++) { - for(int x=0;x<bw;x++) { + for (int x = 0; x < bw; x++) { -// print_line("x: "+itos(x)+" y: "+itos(y)); + // print_line("x: "+itos(x)+" y: "+itos(y)); - uint8_t block[4*4*4]; - zeromem(block,4*4*4); + uint8_t block[4 * 4 * 4]; + zeromem(block, 4 * 4 * 4); uint8_t cblock[8]; - int maxy = MIN(imgh,4); - int maxx = MIN(imgw,4); - - - for(int yy=0;yy<maxy;yy++) { - - for(int xx=0;xx<maxx;xx++) { + int maxy = MIN(imgh, 4); + int maxx = MIN(imgw, 4); + for (int yy = 0; yy < maxy; yy++) { - uint32_t dst_ofs = (yy*4+xx)*4; - uint32_t src_ofs = ((y*4+yy)*imgw+x*4+xx)*3; - block[dst_ofs+0]=src[src_ofs+0]; - block[dst_ofs+1]=src[src_ofs+1]; - block[dst_ofs+2]=src[src_ofs+2]; - block[dst_ofs+3]=255; + for (int xx = 0; xx < maxx; xx++) { + uint32_t dst_ofs = (yy * 4 + xx) * 4; + uint32_t src_ofs = ((y * 4 + yy) * imgw + x * 4 + xx) * 3; + block[dst_ofs + 0] = src[src_ofs + 0]; + block[dst_ofs + 1] = src[src_ofs + 1]; + block[dst_ofs + 2] = src[src_ofs + 2]; + block[dst_ofs + 3] = 255; } } - rg_etc1::pack_etc1_block(cblock, (const unsigned int*)block, pp); - for(int j=0;j<8;j++) { + rg_etc1::pack_etc1_block(cblock, (const unsigned int *)block, pp); + for (int j = 0; j < 8; j++) { - dst[j]=cblock[j]; + dst[j] = cblock[j]; } - dst+=8; + dst += 8; } - } - imgw=MAX(1,imgw/2); - imgh=MAX(1,imgh/2); + imgw = MAX(1, imgw / 2); + imgh = MAX(1, imgh / 2); mc++; - } - *p_img=Image(p_img->get_width(),p_img->get_height(),mc-1,Image::FORMAT_ETC,dst_data); - - + *p_img = Image(p_img->get_width(), p_img->get_height(), mc - 1, Image::FORMAT_ETC, dst_data); } void _register_etc1_compress_func() { rg_etc1::pack_etc1_block_init(); - Image::_image_compress_etc_func=_compress_etc; - Image::_image_decompress_etc=_decompress_etc; - - + Image::_image_compress_etc_func = _compress_etc; + Image::_image_decompress_etc = _decompress_etc; } diff --git a/modules/etc1/image_etc.h b/modules/etc1/image_etc.h index 6ab10126f..18461819d 100644 --- a/modules/etc1/image_etc.h +++ b/modules/etc1/image_etc.h @@ -29,7 +29,6 @@ #ifndef IMAGE_ETC1_H #define IMAGE_ETC1_H - void _register_etc1_compress_func(); #endif // IMAGE_ETC_H diff --git a/modules/etc1/register_types.cpp b/modules/etc1/register_types.cpp index d02ef8347..b3b6419d2 100644 --- a/modules/etc1/register_types.cpp +++ b/modules/etc1/register_types.cpp @@ -35,7 +35,7 @@ static ResourceFormatPKM *resource_loader_pkm = NULL; void register_etc1_types() { - resource_loader_pkm = memnew( ResourceFormatPKM ); + resource_loader_pkm = memnew(ResourceFormatPKM); ResourceLoader::add_resource_format_loader(resource_loader_pkm); _register_etc1_compress_func(); diff --git a/modules/etc1/texture_loader_pkm.cpp b/modules/etc1/texture_loader_pkm.cpp index 275afc1fd..00c6eca46 100644 --- a/modules/etc1/texture_loader_pkm.cpp +++ b/modules/etc1/texture_loader_pkm.cpp @@ -3,38 +3,38 @@ #include <string.h> struct ETC1Header { - char tag[6]; // "PKM 10" - uint16_t format; // Format == number of mips (== zero) - uint16_t texWidth; // Texture dimensions, multiple of 4 (big-endian) - uint16_t texHeight; - uint16_t origWidth; // Original dimensions (big-endian) - uint16_t origHeight; + char tag[6]; // "PKM 10" + uint16_t format; // Format == number of mips (== zero) + uint16_t texWidth; // Texture dimensions, multiple of 4 (big-endian) + uint16_t texHeight; + uint16_t origWidth; // Original dimensions (big-endian) + uint16_t origHeight; }; -RES ResourceFormatPKM::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return RES(); FileAccessRef fref(f); if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; - ERR_EXPLAIN("Unable to open PKM texture file: "+p_path); - ERR_FAIL_COND_V(err!=OK,RES()); + ERR_EXPLAIN("Unable to open PKM texture file: " + p_path); + ERR_FAIL_COND_V(err != OK, RES()); // big endian f->set_endian_swap(true); ETC1Header h; - ERR_EXPLAIN("Invalid or Unsupported PKM texture file: "+p_path); - f->get_buffer((uint8_t *) &h.tag, sizeof(h.tag)); - if(strncmp(h.tag, "PKM 10", sizeof(h.tag))) + ERR_EXPLAIN("Invalid or Unsupported PKM texture file: " + p_path); + f->get_buffer((uint8_t *)&h.tag, sizeof(h.tag)); + if (strncmp(h.tag, "PKM 10", sizeof(h.tag))) ERR_FAIL_V(RES()); h.format = f->get_16(); @@ -48,20 +48,20 @@ RES ResourceFormatPKM::load(const String &p_path, const String& p_original_path, uint32_t size = h.texWidth * h.texHeight / 2; src_data.resize(size); DVector<uint8_t>::Write wb = src_data.write(); - f->get_buffer(wb.ptr(),size); - wb=DVector<uint8_t>::Write(); + f->get_buffer(wb.ptr(), size); + wb = DVector<uint8_t>::Write(); int mipmaps = h.format; int width = h.origWidth; int height = h.origHeight; - Image img(width,height,mipmaps,Image::FORMAT_ETC,src_data); + Image img(width, height, mipmaps, Image::FORMAT_ETC, src_data); - Ref<ImageTexture> texture = memnew( ImageTexture ); + Ref<ImageTexture> texture = memnew(ImageTexture); texture->create_from_image(img); if (r_error) - *r_error=OK; + *r_error = OK; return texture; } @@ -71,14 +71,14 @@ void ResourceFormatPKM::get_recognized_extensions(List<String> *p_extensions) co p_extensions->push_back("pkm"); } -bool ResourceFormatPKM::handles_type(const String& p_type) const { +bool ResourceFormatPKM::handles_type(const String &p_type) const { - return ObjectTypeDB::is_type(p_type,"Texture"); + return ObjectTypeDB::is_type(p_type, "Texture"); } String ResourceFormatPKM::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="pkm") + if (p_path.extension().to_lower() == "pkm") return "ImageTexture"; return ""; } diff --git a/modules/etc1/texture_loader_pkm.h b/modules/etc1/texture_loader_pkm.h index 5788716d9..b7c208061 100644 --- a/modules/etc1/texture_loader_pkm.h +++ b/modules/etc1/texture_loader_pkm.h @@ -1,15 +1,14 @@ #ifndef TEXTURE_LOADER_PKM_H #define TEXTURE_LOADER_PKM_H -#include "scene/resources/texture.h" #include "io/resource_loader.h" +#include "scene/resources/texture.h" -class ResourceFormatPKM : public ResourceFormatLoader{ +class ResourceFormatPKM : public ResourceFormatLoader { public: - - 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 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 ~ResourceFormatPKM() {} diff --git a/modules/gdscript/gd_compiler.cpp b/modules/gdscript/gd_compiler.cpp index e5cb70da6..9cb5ffedc 100644 --- a/modules/gdscript/gd_compiler.cpp +++ b/modules/gdscript/gd_compiler.cpp @@ -29,28 +29,27 @@ #include "gd_compiler.h" #include "gd_script.h" +void GDCompiler::_set_error(const String &p_error, const GDParser::Node *p_node) { -void GDCompiler::_set_error(const String& p_error,const GDParser::Node *p_node) { - - if (error!="") + if (error != "") return; - error=p_error; + error = p_error; if (p_node) { - err_line=p_node->line; - err_column=p_node->column; + err_line = p_node->line; + err_column = p_node->column; } else { - err_line=0; - err_column=0; + err_line = 0; + err_column = 0; } } -bool GDCompiler::_create_unary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level) { +bool GDCompiler::_create_unary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level) { - ERR_FAIL_COND_V(on->arguments.size()!=1,false); + ERR_FAIL_COND_V(on->arguments.size() != 1, false); - int src_address_a = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (src_address_a<0) + int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (src_address_a < 0) return false; codegen.opcodes.push_back(GDFunction::OPCODE_OPERATOR); // perform operator @@ -61,22 +60,20 @@ bool GDCompiler::_create_unary_operator(CodeGen& codegen,const GDParser::Operato return true; } -bool GDCompiler::_create_binary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level,bool p_initializer) { - - ERR_FAIL_COND_V(on->arguments.size()!=2,false); +bool GDCompiler::_create_binary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer) { + ERR_FAIL_COND_V(on->arguments.size() != 2, false); - int src_address_a = _parse_expression(codegen,on->arguments[0],p_stack_level,false,p_initializer); - if (src_address_a<0) + int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level, false, p_initializer); + if (src_address_a < 0) return false; - if (src_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) + if (src_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) p_stack_level++; //uses stack for return, increase stack - int src_address_b = _parse_expression(codegen,on->arguments[1],p_stack_level,false,p_initializer); - if (src_address_b<0) + int src_address_b = _parse_expression(codegen, on->arguments[1], p_stack_level, false, p_initializer); + if (src_address_b < 0) return false; - codegen.opcodes.push_back(GDFunction::OPCODE_OPERATOR); // perform operator codegen.opcodes.push_back(op); //which operator codegen.opcodes.push_back(src_address_a); // argument 1 @@ -84,7 +81,6 @@ bool GDCompiler::_create_binary_operator(CodeGen& codegen,const GDParser::Operat return true; } - /* int GDCompiler::_parse_subexpression(CodeGen& codegen,const GDParser::Node *p_expression) { @@ -103,55 +99,52 @@ int GDCompiler::_parse_subexpression(CodeGen& codegen,const GDParser::Node *p_ex } */ -int GDCompiler::_parse_assign_right_expression(CodeGen& codegen,const GDParser::OperatorNode *p_expression, int p_stack_level) { - - Variant::Operator var_op=Variant::OP_MAX; +int GDCompiler::_parse_assign_right_expression(CodeGen &codegen, const GDParser::OperatorNode *p_expression, int p_stack_level) { + Variant::Operator var_op = Variant::OP_MAX; - switch(p_expression->op) { + switch (p_expression->op) { - case GDParser::OperatorNode::OP_ASSIGN_ADD: var_op=Variant::OP_ADD; break; - case GDParser::OperatorNode::OP_ASSIGN_SUB: var_op=Variant::OP_SUBSTRACT; break; - case GDParser::OperatorNode::OP_ASSIGN_MUL: var_op=Variant::OP_MULTIPLY; break; - case GDParser::OperatorNode::OP_ASSIGN_DIV: var_op=Variant::OP_DIVIDE; break; - case GDParser::OperatorNode::OP_ASSIGN_MOD: var_op=Variant::OP_MODULE; break; - case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op=Variant::OP_SHIFT_LEFT; break; - case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op=Variant::OP_SHIFT_RIGHT; break; - case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op=Variant::OP_BIT_AND; break; - case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op=Variant::OP_BIT_OR; break; - case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op=Variant::OP_BIT_XOR; break; + case GDParser::OperatorNode::OP_ASSIGN_ADD: var_op = Variant::OP_ADD; break; + case GDParser::OperatorNode::OP_ASSIGN_SUB: var_op = Variant::OP_SUBSTRACT; break; + case GDParser::OperatorNode::OP_ASSIGN_MUL: var_op = Variant::OP_MULTIPLY; break; + case GDParser::OperatorNode::OP_ASSIGN_DIV: var_op = Variant::OP_DIVIDE; break; + case GDParser::OperatorNode::OP_ASSIGN_MOD: var_op = Variant::OP_MODULE; break; + case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op = Variant::OP_SHIFT_LEFT; break; + case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op = Variant::OP_SHIFT_RIGHT; break; + case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op = Variant::OP_BIT_AND; break; + case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op = Variant::OP_BIT_OR; break; + case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op = Variant::OP_BIT_XOR; break; case GDParser::OperatorNode::OP_INIT_ASSIGN: case GDParser::OperatorNode::OP_ASSIGN: { //none } break; - default: { + default: { ERR_FAIL_V(-1); } } - bool initializer = p_expression->op==GDParser::OperatorNode::OP_INIT_ASSIGN; + bool initializer = p_expression->op == GDParser::OperatorNode::OP_INIT_ASSIGN; - if (var_op==Variant::OP_MAX) { + if (var_op == Variant::OP_MAX) { - return _parse_expression(codegen,p_expression->arguments[1],p_stack_level,false,initializer); + return _parse_expression(codegen, p_expression->arguments[1], p_stack_level, false, initializer); } - if (!_create_binary_operator(codegen,p_expression,var_op,p_stack_level,initializer)) + if (!_create_binary_operator(codegen, p_expression, var_op, p_stack_level, initializer)) return -1; - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; - } -int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expression, int p_stack_level,bool p_root,bool p_initializer) { +int GDCompiler::_parse_expression(CodeGen &codegen, const GDParser::Node *p_expression, int p_stack_level, bool p_root, bool p_initializer) { - - switch(p_expression->type) { + switch (p_expression->type) { //should parse variable declaration and adjust stack accordingly... case GDParser::Node::TYPE_IDENTIFIER: { //return identifier @@ -160,7 +153,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre //This could be made much simpler by just indexing "self", but done this way (with custom self-addressing modes) increases peformance a lot. - const GDParser::IdentifierNode *in = static_cast<const GDParser::IdentifierNode*>(p_expression); + const GDParser::IdentifierNode *in = static_cast<const GDParser::IdentifierNode *>(p_expression); StringName identifier = in->name; @@ -168,8 +161,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre if (!p_initializer && codegen.stack_identifiers.has(identifier)) { int pos = codegen.stack_identifiers[identifier]; - return pos|(GDFunction::ADDR_TYPE_STACK_VARIABLE<<GDFunction::ADDR_BITS); - + return pos | (GDFunction::ADDR_TYPE_STACK_VARIABLE << GDFunction::ADDR_BITS); } //TRY MEMBERS! if (!codegen.function_node || !codegen.function_node->_static) { @@ -179,7 +171,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre if (codegen.script->member_indices.has(identifier)) { int idx = codegen.script->member_indices[identifier].index; - return idx|(GDFunction::ADDR_TYPE_MEMBER<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_MEMBER << GDFunction::ADDR_BITS); //argument (stack root) } } @@ -189,45 +181,44 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre while (owner) { GDScript *scr = owner; - GDNativeClass *nc=NULL; - while(scr) { + GDNativeClass *nc = NULL; + while (scr) { if (scr->constants.has(identifier)) { //int idx=scr->constants[identifier]; int idx = codegen.get_name_map_pos(identifier); - return idx|(GDFunction::ADDR_TYPE_CLASS_CONSTANT<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_CLASS_CONSTANT << GDFunction::ADDR_BITS); //argument (stack root) } if (scr->native.is_valid()) - nc=scr->native.ptr(); - scr=scr->_base; + nc = scr->native.ptr(); + scr = scr->_base; } // CLASS C++ Integer Constant if (nc) { - bool success=false; - int constant = ObjectTypeDB::get_integer_constant(nc->get_name(),identifier,&success); + bool success = false; + int constant = ObjectTypeDB::get_integer_constant(nc->get_name(), identifier, &success); if (success) { - Variant key=constant; + Variant key = constant; int idx; if (!codegen.constant_map.has(key)) { - idx=codegen.constant_map.size(); - codegen.constant_map[key]=idx; + idx = codegen.constant_map.size(); + codegen.constant_map[key] = idx; } else { - idx=codegen.constant_map[key]; + idx = codegen.constant_map[key]; } - return idx|(GDFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDFunction::ADDR_BITS); //make it a local constant (faster access) + return idx | (GDFunction::ADDR_TYPE_LOCAL_CONSTANT << GDFunction::ADDR_BITS); //make it a local constant (faster access) } - } - owner=owner->_owner; + owner = owner->_owner; } /* @@ -242,58 +233,55 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier]; - return idx|(GDFunction::ADDR_TYPE_GLOBAL<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_GLOBAL << GDFunction::ADDR_BITS); //argument (stack root) } //not found, error - _set_error("Identifier not found: "+String(identifier),p_expression); + _set_error("Identifier not found: " + String(identifier), p_expression); return -1; - } break; case GDParser::Node::TYPE_CONSTANT: { //return constant - const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode*>(p_expression); - + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(p_expression); int idx; if (!codegen.constant_map.has(cn->value)) { - idx=codegen.constant_map.size(); - codegen.constant_map[cn->value]=idx; + idx = codegen.constant_map.size(); + codegen.constant_map[cn->value] = idx; } else { - idx=codegen.constant_map[cn->value]; + idx = codegen.constant_map[cn->value]; } - - return idx|(GDFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_LOCAL_CONSTANT << GDFunction::ADDR_BITS); //argument (stack root) } break; case GDParser::Node::TYPE_SELF: { //return constant if (codegen.function_node && codegen.function_node->_static) { - _set_error("'self' not present in static function!",p_expression); + _set_error("'self' not present in static function!", p_expression); return -1; } - return (GDFunction::ADDR_TYPE_SELF<<GDFunction::ADDR_BITS); + return (GDFunction::ADDR_TYPE_SELF << GDFunction::ADDR_BITS); } break; case GDParser::Node::TYPE_ARRAY: { - const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode*>(p_expression); + const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_expression); Vector<int> values; - int slevel=p_stack_level; + int slevel = p_stack_level; - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { - int ret = _parse_expression(codegen,an->elements[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, an->elements[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -303,10 +291,10 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(GDFunction::OPCODE_CONSTRUCT_ARRAY); codegen.opcodes.push_back(values.size()); - for(int i=0;i<values.size();i++) + for (int i = 0; i < values.size(); i++) codegen.opcodes.push_back(values[i]); - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -314,27 +302,27 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre } break; case GDParser::Node::TYPE_DICTIONARY: { - const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode*>(p_expression); + const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(p_expression); Vector<int> values; - int slevel=p_stack_level; + int slevel = p_stack_level; - for(int i=0;i<dn->elements.size();i++) { + for (int i = 0; i < dn->elements.size(); i++) { - int ret = _parse_expression(codegen,dn->elements[i].key,slevel); - if (ret<0) + int ret = _parse_expression(codegen, dn->elements[i].key, slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } values.push_back(ret); - ret = _parse_expression(codegen,dn->elements[i].value,slevel); - if (ret<0) + ret = _parse_expression(codegen, dn->elements[i].value, slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -344,10 +332,10 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(GDFunction::OPCODE_CONSTRUCT_DICTIONARY); codegen.opcodes.push_back(dn->elements.size()); - for(int i=0;i<values.size();i++) + for (int i = 0; i < values.size(); i++) codegen.opcodes.push_back(values[i]); - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -356,27 +344,24 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre case GDParser::Node::TYPE_OPERATOR: { //hell breaks loose - const GDParser::OperatorNode *on = static_cast<const GDParser::OperatorNode*>(p_expression); - switch(on->op) { - + const GDParser::OperatorNode *on = static_cast<const GDParser::OperatorNode *>(p_expression); + switch (on->op) { //call/constructor operator case GDParser::OperatorNode::OP_PARENT_CALL: { - - ERR_FAIL_COND_V(on->arguments.size()<1,-1); + ERR_FAIL_COND_V(on->arguments.size() < 1, -1); const GDParser::IdentifierNode *in = (const GDParser::IdentifierNode *)on->arguments[0]; - Vector<int> arguments; int slevel = p_stack_level; - for(int i=1;i<on->arguments.size();i++) { + for (int i = 1; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -389,27 +374,27 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(codegen.get_name_map_pos(in->name)); //instance codegen.opcodes.push_back(arguments.size()); //argument count codegen.alloc_call(arguments.size()); - for(int i=0;i<arguments.size();i++) + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); //arguments } break; case GDParser::OperatorNode::OP_CALL: { - if (on->arguments[0]->type==GDParser::Node::TYPE_TYPE) { + if (on->arguments[0]->type == GDParser::Node::TYPE_TYPE) { //construct a basic type - ERR_FAIL_COND_V(on->arguments.size()<1,-1); + ERR_FAIL_COND_V(on->arguments.size() < 1, -1); const GDParser::TypeNode *tn = (const GDParser::TypeNode *)on->arguments[0]; int vtype = tn->vtype; Vector<int> arguments; int slevel = p_stack_level; - for(int i=1;i<on->arguments.size();i++) { + for (int i = 1; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -421,24 +406,23 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(vtype); //instance codegen.opcodes.push_back(arguments.size()); //argument count codegen.alloc_call(arguments.size()); - for(int i=0;i<arguments.size();i++) + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); //arguments - } else if (on->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { + } else if (on->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { //built in function - ERR_FAIL_COND_V(on->arguments.size()<1,-1); - + ERR_FAIL_COND_V(on->arguments.size() < 1, -1); Vector<int> arguments; int slevel = p_stack_level; - for(int i=1;i<on->arguments.size();i++) { + for (int i = 1; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -446,79 +430,74 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre arguments.push_back(ret); } - codegen.opcodes.push_back(GDFunction::OPCODE_CALL_BUILT_IN); - codegen.opcodes.push_back(static_cast<const GDParser::BuiltInFunctionNode*>(on->arguments[0])->function); - codegen.opcodes.push_back(on->arguments.size()-1); - codegen.alloc_call(on->arguments.size()-1); - for(int i=0;i<arguments.size();i++) + codegen.opcodes.push_back(static_cast<const GDParser::BuiltInFunctionNode *>(on->arguments[0])->function); + codegen.opcodes.push_back(on->arguments.size() - 1); + codegen.alloc_call(on->arguments.size() - 1); + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); } else { //regular function - ERR_FAIL_COND_V(on->arguments.size()<2,-1); + ERR_FAIL_COND_V(on->arguments.size() < 2, -1); const GDParser::Node *instance = on->arguments[0]; - if (instance->type==GDParser::Node::TYPE_SELF) { + if (instance->type == GDParser::Node::TYPE_SELF) { //room for optimization - } - Vector<int> arguments; int slevel = p_stack_level; - for(int i=0;i<on->arguments.size();i++) { + for (int i = 0; i < on->arguments.size(); i++) { int ret; - if (i==0 && on->arguments[i]->type==GDParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) { + if (i == 0 && on->arguments[i]->type == GDParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) { //static call to self - ret=(GDFunction::ADDR_TYPE_CLASS<<GDFunction::ADDR_BITS); - } else if (i==1) { + ret = (GDFunction::ADDR_TYPE_CLASS << GDFunction::ADDR_BITS); + } else if (i == 1) { - if (on->arguments[i]->type!=GDParser::Node::TYPE_IDENTIFIER) { - _set_error("Attempt to call a non-identifier.",on); + if (on->arguments[i]->type != GDParser::Node::TYPE_IDENTIFIER) { + _set_error("Attempt to call a non-identifier.", on); return -1; } - GDParser::IdentifierNode *id = static_cast<GDParser::IdentifierNode*>(on->arguments[i]); - ret=codegen.get_name_map_pos(id->name); + GDParser::IdentifierNode *id = static_cast<GDParser::IdentifierNode *>(on->arguments[i]); + ret = codegen.get_name_map_pos(id->name); } else { - ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } } arguments.push_back(ret); - } - codegen.opcodes.push_back(p_root?GDFunction::OPCODE_CALL:GDFunction::OPCODE_CALL_RETURN); // perform operator - codegen.opcodes.push_back(on->arguments.size()-2); - codegen.alloc_call(on->arguments.size()-2); - for(int i=0;i<arguments.size();i++) + codegen.opcodes.push_back(p_root ? GDFunction::OPCODE_CALL : GDFunction::OPCODE_CALL_RETURN); // perform operator + codegen.opcodes.push_back(on->arguments.size() - 2); + codegen.alloc_call(on->arguments.size() - 2); + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); } } break; case GDParser::OperatorNode::OP_YIELD: { - - ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size()!=2,-1); + ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size() != 2, -1); Vector<int> arguments; int slevel = p_stack_level; - for(int i=0;i<on->arguments.size();i++) { + for (int i = 0; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)) { + if (ret & (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)) { slevel++; codegen.alloc_stack(slevel); } @@ -526,8 +505,8 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre } //push call bytecode - codegen.opcodes.push_back(arguments.size()==0?GDFunction::OPCODE_YIELD:GDFunction::OPCODE_YIELD_SIGNAL); // basic type constructor - for(int i=0;i<arguments.size();i++) + codegen.opcodes.push_back(arguments.size() == 0 ? GDFunction::OPCODE_YIELD : GDFunction::OPCODE_YIELD_SIGNAL); // basic type constructor + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); //arguments codegen.opcodes.push_back(GDFunction::OPCODE_YIELD_RESUME); //next will be where to place the result :) @@ -538,60 +517,60 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre case GDParser::OperatorNode::OP_INDEX: case GDParser::OperatorNode::OP_INDEX_NAMED: { - ERR_FAIL_COND_V(on->arguments.size()!=2,-1); + ERR_FAIL_COND_V(on->arguments.size() != 2, -1); int slevel = p_stack_level; - bool named=(on->op==GDParser::OperatorNode::OP_INDEX_NAMED); + bool named = (on->op == GDParser::OperatorNode::OP_INDEX_NAMED); - int from = _parse_expression(codegen,on->arguments[0],slevel); - if (from<0) + int from = _parse_expression(codegen, on->arguments[0], slevel); + if (from < 0) return from; int index; if (named) { - if (on->arguments[0]->type==GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { + if (on->arguments[0]->type == GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { - GDParser::IdentifierNode* identifier = static_cast<GDParser::IdentifierNode*>(on->arguments[1]); - const Map<StringName,GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name); + GDParser::IdentifierNode *identifier = static_cast<GDParser::IdentifierNode *>(on->arguments[1]); + const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name); #ifdef DEBUG_ENABLED - if (MI && MI->get().getter==codegen.function_node->name) { - String n = static_cast<GDParser::IdentifierNode*>(on->arguments[1])->name; - _set_error("Must use '"+n+"' instead of 'self."+n+"' in getter.",on); + if (MI && MI->get().getter == codegen.function_node->name) { + String n = static_cast<GDParser::IdentifierNode *>(on->arguments[1])->name; + _set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", on); return -1; } #endif - if (MI && MI->get().getter=="") { + if (MI && MI->get().getter == "") { // Faster than indexing self (as if no self. had been used) - return (MI->get().index)|(GDFunction::ADDR_TYPE_MEMBER<<GDFunction::ADDR_BITS); + return (MI->get().index) | (GDFunction::ADDR_TYPE_MEMBER << GDFunction::ADDR_BITS); } } - index=codegen.get_name_map_pos(static_cast<GDParser::IdentifierNode*>(on->arguments[1])->name); + index = codegen.get_name_map_pos(static_cast<GDParser::IdentifierNode *>(on->arguments[1])->name); } else { - if (on->arguments[1]->type==GDParser::Node::TYPE_CONSTANT && static_cast<const GDParser::ConstantNode*>(on->arguments[1])->value.get_type()==Variant::STRING) { + if (on->arguments[1]->type == GDParser::Node::TYPE_CONSTANT && static_cast<const GDParser::ConstantNode *>(on->arguments[1])->value.get_type() == Variant::STRING) { //also, somehow, named (speed up anyway) - StringName name = static_cast<const GDParser::ConstantNode*>(on->arguments[1])->value; - index=codegen.get_name_map_pos(name); - named=true; + StringName name = static_cast<const GDParser::ConstantNode *>(on->arguments[1])->value; + index = codegen.get_name_map_pos(name); + named = true; } else { //regular indexing - if (from&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (from & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - index = _parse_expression(codegen,on->arguments[1],slevel); - if (index<0) + index = _parse_expression(codegen, on->arguments[1], slevel); + if (index < 0) return index; } } - codegen.opcodes.push_back(named?GDFunction::OPCODE_GET_NAMED:GDFunction::OPCODE_GET); // perform operator + codegen.opcodes.push_back(named ? GDFunction::OPCODE_GET_NAMED : GDFunction::OPCODE_GET); // perform operator codegen.opcodes.push_back(from); // argument 1 codegen.opcodes.push_back(index); // argument 2 (unary only takes one parameter) @@ -600,66 +579,66 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre // AND operator with early out on failure - int res = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (res<0) + int res = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(res); - int jump_fail_pos=codegen.opcodes.size(); + int jump_fail_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - res = _parse_expression(codegen,on->arguments[1],p_stack_level); - if (res<0) + res = _parse_expression(codegen, on->arguments[1], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(res); - int jump_fail_pos2=codegen.opcodes.size(); + int jump_fail_pos2 = codegen.opcodes.size(); codegen.opcodes.push_back(0); codegen.alloc_stack(p_stack_level); //it will be used.. codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_TRUE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - codegen.opcodes.push_back(codegen.opcodes.size()+3); - codegen.opcodes[jump_fail_pos]=codegen.opcodes.size(); - codegen.opcodes[jump_fail_pos2]=codegen.opcodes.size(); + codegen.opcodes.push_back(codegen.opcodes.size() + 3); + codegen.opcodes[jump_fail_pos] = codegen.opcodes.size(); + codegen.opcodes[jump_fail_pos2] = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_FALSE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS; + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS; } break; case GDParser::OperatorNode::OP_OR: { // OR operator with early out on success - int res = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (res<0) + int res = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF); codegen.opcodes.push_back(res); - int jump_success_pos=codegen.opcodes.size(); + int jump_success_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - res = _parse_expression(codegen,on->arguments[1],p_stack_level); - if (res<0) + res = _parse_expression(codegen, on->arguments[1], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF); codegen.opcodes.push_back(res); - int jump_success_pos2=codegen.opcodes.size(); + int jump_success_pos2 = codegen.opcodes.size(); codegen.opcodes.push_back(0); codegen.alloc_stack(p_stack_level); //it will be used.. codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_FALSE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - codegen.opcodes.push_back(codegen.opcodes.size()+3); - codegen.opcodes[jump_success_pos]=codegen.opcodes.size(); - codegen.opcodes[jump_success_pos2]=codegen.opcodes.size(); + codegen.opcodes.push_back(codegen.opcodes.size() + 3); + codegen.opcodes[jump_success_pos] = codegen.opcodes.size(); + codegen.opcodes[jump_success_pos2] = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_TRUE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS; + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS; } break; // ternary operators @@ -667,70 +646,113 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre // x IF a ELSE y operator with early out on failure - int res = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (res<0) + int res = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(res); - int jump_fail_pos=codegen.opcodes.size(); + int jump_fail_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - - res = _parse_expression(codegen,on->arguments[1],p_stack_level); - if (res<0) + res = _parse_expression(codegen, on->arguments[1], p_stack_level); + if (res < 0) return res; - + codegen.alloc_stack(p_stack_level); //it will be used.. codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(res); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - int jump_past_pos=codegen.opcodes.size(); + int jump_past_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - - codegen.opcodes[jump_fail_pos]=codegen.opcodes.size(); - res = _parse_expression(codegen,on->arguments[2],p_stack_level); - if (res<0) + + codegen.opcodes[jump_fail_pos] = codegen.opcodes.size(); + res = _parse_expression(codegen, on->arguments[2], p_stack_level); + if (res < 0) return res; - + codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(res); - - codegen.opcodes[jump_past_pos]=codegen.opcodes.size(); - - return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS; + + codegen.opcodes[jump_past_pos] = codegen.opcodes.size(); + + return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS; } break; //unary operators - case GDParser::OperatorNode::OP_NEG: { if (!_create_unary_operator(codegen,on,Variant::OP_NEGATE,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_NOT: { if (!_create_unary_operator(codegen,on,Variant::OP_NOT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_INVERT: { if (!_create_unary_operator(codegen,on,Variant::OP_BIT_NEGATE,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_PREINC: { } break; //? - case GDParser::OperatorNode::OP_PREDEC: { } break; - case GDParser::OperatorNode::OP_INC: { } break; - case GDParser::OperatorNode::OP_DEC: { } break; + case GDParser::OperatorNode::OP_NEG: { + if (!_create_unary_operator(codegen, on, Variant::OP_NEGATE, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_NOT: { + if (!_create_unary_operator(codegen, on, Variant::OP_NOT, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_BIT_INVERT: { + if (!_create_unary_operator(codegen, on, Variant::OP_BIT_NEGATE, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_PREINC: { + } break; //? + case GDParser::OperatorNode::OP_PREDEC: { + } break; + case GDParser::OperatorNode::OP_INC: { + } break; + case GDParser::OperatorNode::OP_DEC: { + } break; //binary operators (in precedence order) - case GDParser::OperatorNode::OP_IN: { if (!_create_binary_operator(codegen,on,Variant::OP_IN,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_NOT_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_NOT_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_LESS: { if (!_create_binary_operator(codegen,on,Variant::OP_LESS,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_LESS_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_LESS_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_GREATER: { if (!_create_binary_operator(codegen,on,Variant::OP_GREATER,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_GREATER_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_GREATER_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_ADD: { if (!_create_binary_operator(codegen,on,Variant::OP_ADD,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_SUB: { if (!_create_binary_operator(codegen,on,Variant::OP_SUBSTRACT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_MUL: { if (!_create_binary_operator(codegen,on,Variant::OP_MULTIPLY,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_DIV: { if (!_create_binary_operator(codegen,on,Variant::OP_DIVIDE,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_MOD: { if (!_create_binary_operator(codegen,on,Variant::OP_MODULE,p_stack_level)) return -1;} break; + case GDParser::OperatorNode::OP_IN: { + if (!_create_binary_operator(codegen, on, Variant::OP_IN, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_NOT_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_NOT_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_LESS: { + if (!_create_binary_operator(codegen, on, Variant::OP_LESS, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_LESS_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_LESS_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_GREATER: { + if (!_create_binary_operator(codegen, on, Variant::OP_GREATER, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_GREATER_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_GREATER_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_ADD: { + if (!_create_binary_operator(codegen, on, Variant::OP_ADD, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_SUB: { + if (!_create_binary_operator(codegen, on, Variant::OP_SUBSTRACT, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_MUL: { + if (!_create_binary_operator(codegen, on, Variant::OP_MULTIPLY, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_DIV: { + if (!_create_binary_operator(codegen, on, Variant::OP_DIVIDE, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_MOD: { + if (!_create_binary_operator(codegen, on, Variant::OP_MODULE, p_stack_level)) return -1; + } break; //case GDParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break; //case GDParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_AND: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_AND,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_OR: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_OR,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_XOR: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_XOR,p_stack_level)) return -1;} break; - //shift - case GDParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break; + case GDParser::OperatorNode::OP_BIT_AND: { + if (!_create_binary_operator(codegen, on, Variant::OP_BIT_AND, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_BIT_OR: { + if (!_create_binary_operator(codegen, on, Variant::OP_BIT_OR, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_BIT_XOR: { + if (!_create_binary_operator(codegen, on, Variant::OP_BIT_XOR, p_stack_level)) return -1; + } break; + //shift + case GDParser::OperatorNode::OP_SHIFT_LEFT: { + if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_LEFT, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_SHIFT_RIGHT: { + if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_RIGHT, p_stack_level)) return -1; + } break; //assignment operators case GDParser::OperatorNode::OP_ASSIGN_ADD: case GDParser::OperatorNode::OP_ASSIGN_SUB: @@ -745,49 +767,45 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre case GDParser::OperatorNode::OP_INIT_ASSIGN: case GDParser::OperatorNode::OP_ASSIGN: { - ERR_FAIL_COND_V(on->arguments.size()!=2,-1); - - - if (on->arguments[0]->type==GDParser::Node::TYPE_OPERATOR && (static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX || static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX_NAMED)) { - //SET (chained) MODE!! + ERR_FAIL_COND_V(on->arguments.size() != 2, -1); + if (on->arguments[0]->type == GDParser::Node::TYPE_OPERATOR && (static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX || static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX_NAMED)) { +//SET (chained) MODE!! #ifdef DEBUG_ENABLED - if (static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX_NAMED) { - const GDParser::OperatorNode* inon = static_cast<GDParser::OperatorNode*>(on->arguments[0]); - + if (static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX_NAMED) { + const GDParser::OperatorNode *inon = static_cast<GDParser::OperatorNode *>(on->arguments[0]); - if (inon->arguments[0]->type==GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { + if (inon->arguments[0]->type == GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { - const Map<StringName,GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(static_cast<GDParser::IdentifierNode*>(inon->arguments[1])->name); - if (MI && MI->get().setter==codegen.function_node->name) { - String n = static_cast<GDParser::IdentifierNode*>(inon->arguments[1])->name; - _set_error("Must use '"+n+"' instead of 'self."+n+"' in setter.",inon); + const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(static_cast<GDParser::IdentifierNode *>(inon->arguments[1])->name); + if (MI && MI->get().setter == codegen.function_node->name) { + String n = static_cast<GDParser::IdentifierNode *>(inon->arguments[1])->name; + _set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", inon); return -1; } } } #endif + int slevel = p_stack_level; - int slevel=p_stack_level; - - GDParser::OperatorNode* op = static_cast<GDParser::OperatorNode*>(on->arguments[0]); + GDParser::OperatorNode *op = static_cast<GDParser::OperatorNode *>(on->arguments[0]); /* Find chain of sets */ - List<GDParser::OperatorNode*> chain; + List<GDParser::OperatorNode *> chain; { //create get/set chain - GDParser::OperatorNode* n=op; - while(true) { + GDParser::OperatorNode *n = op; + while (true) { chain.push_back(n); - if (n->arguments[0]->type!=GDParser::Node::TYPE_OPERATOR) + if (n->arguments[0]->type != GDParser::Node::TYPE_OPERATOR) break; - n = static_cast<GDParser::OperatorNode*>(n->arguments[0]); - if (n->op!=GDParser::OperatorNode::OP_INDEX && n->op!=GDParser::OperatorNode::OP_INDEX_NAMED) + n = static_cast<GDParser::OperatorNode *>(n->arguments[0]); + if (n->op != GDParser::OperatorNode::OP_INDEX && n->op != GDParser::OperatorNode::OP_INDEX_NAMED) break; } } @@ -795,52 +813,48 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre /* Chain of gets */ //get at (potential) root stack pos, so it can be returned - int prev_pos = _parse_expression(codegen,chain.back()->get()->arguments[0],slevel); - if (prev_pos<0) + int prev_pos = _parse_expression(codegen, chain.back()->get()->arguments[0], slevel); + if (prev_pos < 0) return prev_pos; - int retval=prev_pos; + int retval = prev_pos; //print_line("retval: "+itos(retval)); - if (retval&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (retval & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - Vector<int> setchain; - for(List<GDParser::OperatorNode*>::Element *E=chain.back();E;E=E->prev()) { - + for (List<GDParser::OperatorNode *>::Element *E = chain.back(); E; E = E->prev()) { - if (E==chain.front()) //ignore first + if (E == chain.front()) //ignore first break; - bool named = E->get()->op==GDParser::OperatorNode::OP_INDEX_NAMED; + bool named = E->get()->op == GDParser::OperatorNode::OP_INDEX_NAMED; int key_idx; if (named) { - key_idx = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode*>(E->get()->arguments[1])->name); + key_idx = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode *>(E->get()->arguments[1])->name); //printf("named key %x\n",key_idx); } else { - if (prev_pos&(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)) { + if (prev_pos & (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)) { slevel++; codegen.alloc_stack(slevel); } GDParser::Node *key = E->get()->arguments[1]; - key_idx = _parse_expression(codegen,key,slevel); + key_idx = _parse_expression(codegen, key, slevel); //printf("expr key %x\n",key_idx); - //stack was raised here if retval was stack but.. - } - if (key_idx<0) + if (key_idx < 0) return key_idx; codegen.opcodes.push_back(named ? GDFunction::OPCODE_GET_NAMED : GDFunction::OPCODE_GET); @@ -848,7 +862,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(key_idx); slevel++; codegen.alloc_stack(slevel); - int dst_pos = (GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)|slevel; + int dst_pos = (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) | slevel; codegen.opcodes.push_back(dst_pos); @@ -858,105 +872,91 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre setchain.push_back(prev_pos); setchain.push_back(named ? GDFunction::OPCODE_SET_NAMED : GDFunction::OPCODE_SET); - prev_pos=dst_pos; - + prev_pos = dst_pos; } setchain.invert(); - int set_index; - bool named=false; + bool named = false; + if (static_cast<const GDParser::OperatorNode *>(op)->op == GDParser::OperatorNode::OP_INDEX_NAMED) { - if (static_cast<const GDParser::OperatorNode*>(op)->op==GDParser::OperatorNode::OP_INDEX_NAMED) { - - - set_index=codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name); - named=true; + set_index = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name); + named = true; } else { - set_index = _parse_expression(codegen,op->arguments[1],slevel+1); - named=false; + set_index = _parse_expression(codegen, op->arguments[1], slevel + 1); + named = false; } - - if (set_index<0) + if (set_index < 0) return set_index; - if (set_index&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (set_index & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - - int set_value = _parse_assign_right_expression(codegen,on,slevel+1); - if (set_value<0) + int set_value = _parse_assign_right_expression(codegen, on, slevel + 1); + if (set_value < 0) return set_value; - codegen.opcodes.push_back(named?GDFunction::OPCODE_SET_NAMED:GDFunction::OPCODE_SET); + codegen.opcodes.push_back(named ? GDFunction::OPCODE_SET_NAMED : GDFunction::OPCODE_SET); codegen.opcodes.push_back(prev_pos); codegen.opcodes.push_back(set_index); codegen.opcodes.push_back(set_value); - for(int i=0;i<setchain.size();i+=4) { + for (int i = 0; i < setchain.size(); i += 4) { - - codegen.opcodes.push_back(setchain[i+0]); - codegen.opcodes.push_back(setchain[i+1]); - codegen.opcodes.push_back(setchain[i+2]); - codegen.opcodes.push_back(setchain[i+3]); + codegen.opcodes.push_back(setchain[i + 0]); + codegen.opcodes.push_back(setchain[i + 1]); + codegen.opcodes.push_back(setchain[i + 2]); + codegen.opcodes.push_back(setchain[i + 3]); } return retval; - } else { //ASSIGNMENT MODE!! int slevel = p_stack_level; - int dst_address_a = _parse_expression(codegen,on->arguments[0],slevel,false,on->op==GDParser::OperatorNode::OP_INIT_ASSIGN); - if (dst_address_a<0) + int dst_address_a = _parse_expression(codegen, on->arguments[0], slevel, false, on->op == GDParser::OperatorNode::OP_INIT_ASSIGN); + if (dst_address_a < 0) return -1; - if (dst_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (dst_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - int src_address_b = _parse_assign_right_expression(codegen,on,slevel); - if (src_address_b<0) + int src_address_b = _parse_assign_right_expression(codegen, on, slevel); + if (src_address_b < 0) return -1; - - - codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN); // perform operator codegen.opcodes.push_back(dst_address_a); // argument 1 codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter) return dst_address_a; //if anything, returns wathever was assigned or correct stack position - } - } break; case GDParser::OperatorNode::OP_EXTENDS: { - ERR_FAIL_COND_V(on->arguments.size()!=2,false); - + ERR_FAIL_COND_V(on->arguments.size() != 2, false); int slevel = p_stack_level; - int src_address_a = _parse_expression(codegen,on->arguments[0],slevel); - if (src_address_a<0) + int src_address_a = _parse_expression(codegen, on->arguments[0], slevel); + if (src_address_a < 0) return -1; - if (src_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) + if (src_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) slevel++; //uses stack for return, increase stack - int src_address_b = _parse_expression(codegen,on->arguments[1],slevel); - if (src_address_b<0) + int src_address_b = _parse_expression(codegen, on->arguments[1], slevel); + if (src_address_b < 0) return -1; codegen.opcodes.push_back(GDFunction::OPCODE_EXTENDS_TEST); // perform operator @@ -966,14 +966,13 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre } break; default: { - - ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #"+itos(on->op)+" in parse tree while parsing expression."); + ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #" + itos(on->op) + " in parse tree while parsing expression."); ERR_FAIL_V(0); //unreachable code } break; } - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -984,97 +983,89 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre ERR_EXPLAIN("Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); ERR_FAIL_V(-1); //unreachable code } break; - - } ERR_FAIL_V(-1); //unreachable code } - -Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_block,int p_stack_level,int p_break_addr,int p_continue_addr) { +Error GDCompiler::_parse_block(CodeGen &codegen, const GDParser::BlockNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) { codegen.push_stack_identifiers(); - int new_identifiers=0; - codegen.current_line=p_block->line; + int new_identifiers = 0; + codegen.current_line = p_block->line; - for(int i=0;i<p_block->statements.size();i++) { + for (int i = 0; i < p_block->statements.size(); i++) { const GDParser::Node *s = p_block->statements[i]; - - switch(s->type) { + switch (s->type) { case GDParser::Node::TYPE_NEWLINE: { #ifdef DEBUG_ENABLED - const GDParser::NewLineNode *nl = static_cast<const GDParser::NewLineNode*>(s); + const GDParser::NewLineNode *nl = static_cast<const GDParser::NewLineNode *>(s); codegen.opcodes.push_back(GDFunction::OPCODE_LINE); codegen.opcodes.push_back(nl->line); - codegen.current_line=nl->line; + codegen.current_line = nl->line; #endif } break; case GDParser::Node::TYPE_CONTROL_FLOW: { // try subblocks - const GDParser::ControlFlowNode *cf = static_cast<const GDParser::ControlFlowNode*>(s); - - switch(cf->cf_type) { + const GDParser::ControlFlowNode *cf = static_cast<const GDParser::ControlFlowNode *>(s); + switch (cf->cf_type) { case GDParser::ControlFlowNode::CF_IF: { #ifdef DEBUG_ENABLED codegen.opcodes.push_back(GDFunction::OPCODE_LINE); codegen.opcodes.push_back(cf->line); - codegen.current_line=cf->line; + codegen.current_line = cf->line; #endif - int ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false); - if (ret<0) + int ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(ret); - int else_addr=codegen.opcodes.size(); + int else_addr = codegen.opcodes.size(); codegen.opcodes.push_back(0); //temporary - Error err = _parse_block(codegen,cf->body,p_stack_level,p_break_addr,p_continue_addr); + Error err = _parse_block(codegen, cf->body, p_stack_level, p_break_addr, p_continue_addr); if (err) return err; if (cf->body_else) { codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - int end_addr=codegen.opcodes.size(); + int end_addr = codegen.opcodes.size(); codegen.opcodes.push_back(0); - codegen.opcodes[else_addr]=codegen.opcodes.size(); + codegen.opcodes[else_addr] = codegen.opcodes.size(); - Error err = _parse_block(codegen,cf->body_else,p_stack_level,p_break_addr,p_continue_addr); + Error err = _parse_block(codegen, cf->body_else, p_stack_level, p_break_addr, p_continue_addr); if (err) return err; - codegen.opcodes[end_addr]=codegen.opcodes.size(); + codegen.opcodes[end_addr] = codegen.opcodes.size(); } else { //end without else - codegen.opcodes[else_addr]=codegen.opcodes.size(); - + codegen.opcodes[else_addr] = codegen.opcodes.size(); } } break; case GDParser::ControlFlowNode::CF_FOR: { - - - int slevel=p_stack_level; - int iter_stack_pos=slevel; - int iterator_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - int counter_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - int container_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int slevel = p_stack_level; + int iter_stack_pos = slevel; + int iterator_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + int counter_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + int container_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.alloc_stack(slevel); - codegen.push_stack_identifiers(); - codegen.add_stack_identifier(static_cast<const GDParser::IdentifierNode*>(cf->arguments[0])->name,iter_stack_pos); + codegen.push_stack_identifiers(); + codegen.add_stack_identifier(static_cast<const GDParser::IdentifierNode *>(cf->arguments[0])->name, iter_stack_pos); - int ret = _parse_expression(codegen,cf->arguments[1],slevel,false); - if (ret<0) + int ret = _parse_expression(codegen, cf->arguments[1], slevel, false); + if (ret < 0) return ERR_COMPILATION_FAILED; //assign container @@ -1086,32 +1077,29 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo codegen.opcodes.push_back(GDFunction::OPCODE_ITERATE_BEGIN); codegen.opcodes.push_back(counter_pos); codegen.opcodes.push_back(container_pos); - codegen.opcodes.push_back(codegen.opcodes.size()+4); + codegen.opcodes.push_back(codegen.opcodes.size() + 4); codegen.opcodes.push_back(iterator_pos); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); //skip code for next - codegen.opcodes.push_back(codegen.opcodes.size()+8); + codegen.opcodes.push_back(codegen.opcodes.size() + 8); //break loop - int break_pos=codegen.opcodes.size(); + int break_pos = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); //skip code for next codegen.opcodes.push_back(0); //skip code for next //next loop - int continue_pos=codegen.opcodes.size(); + int continue_pos = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_ITERATE); codegen.opcodes.push_back(counter_pos); codegen.opcodes.push_back(container_pos); codegen.opcodes.push_back(break_pos); codegen.opcodes.push_back(iterator_pos); - - Error err = _parse_block(codegen,cf->body,slevel,break_pos,continue_pos); + Error err = _parse_block(codegen, cf->body, slevel, break_pos, continue_pos); if (err) return err; - codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(continue_pos); - codegen.opcodes[break_pos+1]=codegen.opcodes.size(); - + codegen.opcodes[break_pos + 1] = codegen.opcodes.size(); codegen.pop_stack_identifiers(); @@ -1119,25 +1107,25 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo case GDParser::ControlFlowNode::CF_WHILE: { codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - codegen.opcodes.push_back(codegen.opcodes.size()+3); - int break_addr=codegen.opcodes.size(); + codegen.opcodes.push_back(codegen.opcodes.size() + 3); + int break_addr = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(0); - int continue_addr=codegen.opcodes.size(); + int continue_addr = codegen.opcodes.size(); - int ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false); - if (ret<0) + int ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(ret); codegen.opcodes.push_back(break_addr); - Error err = _parse_block(codegen,cf->body,p_stack_level,break_addr,continue_addr); + Error err = _parse_block(codegen, cf->body, p_stack_level, break_addr, continue_addr); if (err) return err; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(continue_addr); - codegen.opcodes[break_addr+1]=codegen.opcodes.size(); + codegen.opcodes[break_addr + 1] = codegen.opcodes.size(); } break; case GDParser::ControlFlowNode::CF_SWITCH: { @@ -1145,9 +1133,9 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo } break; case GDParser::ControlFlowNode::CF_BREAK: { - if (p_break_addr<0) { + if (p_break_addr < 0) { - _set_error("'break'' not within loop",cf); + _set_error("'break'' not within loop", cf); return ERR_COMPILATION_FAILED; } codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); @@ -1156,9 +1144,9 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo } break; case GDParser::ControlFlowNode::CF_CONTINUE: { - if (p_continue_addr<0) { + if (p_continue_addr < 0) { - _set_error("'continue' not within loop",cf); + _set_error("'continue' not within loop", cf); return ERR_COMPILATION_FAILED; } @@ -1172,30 +1160,29 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo if (cf->arguments.size()) { - ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false); - if (ret<0) + ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; } else { - ret=GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS; + ret = GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS; } codegen.opcodes.push_back(GDFunction::OPCODE_RETURN); codegen.opcodes.push_back(ret); } break; - } } break; case GDParser::Node::TYPE_ASSERT: { #ifdef DEBUG_ENABLED // try subblocks - const GDParser::AssertNode *as = static_cast<const GDParser::AssertNode*>(s); + const GDParser::AssertNode *as = static_cast<const GDParser::AssertNode *>(s); - int ret = _parse_expression(codegen,as->condition,p_stack_level,false); - if (ret<0) + int ret = _parse_expression(codegen, as->condition, p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; codegen.opcodes.push_back(GDFunction::OPCODE_ASSERT); @@ -1210,90 +1197,82 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo } break; case GDParser::Node::TYPE_LOCAL_VAR: { + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(s); - const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode*>(s); - - codegen.add_stack_identifier(lv->name,p_stack_level++); + codegen.add_stack_identifier(lv->name, p_stack_level++); codegen.alloc_stack(p_stack_level); new_identifiers++; } break; default: { //expression - int ret = _parse_expression(codegen,s,p_stack_level,true); - if (ret<0) + int ret = _parse_expression(codegen, s, p_stack_level, true); + if (ret < 0) return ERR_PARSE_ERROR; } break; - } - } codegen.pop_stack_identifiers(); return OK; } - -Error GDCompiler::_parse_function(GDScript *p_script,const GDParser::ClassNode *p_class,const GDParser::FunctionNode *p_func,bool p_for_ready) { +Error GDCompiler::_parse_function(GDScript *p_script, const GDParser::ClassNode *p_class, const GDParser::FunctionNode *p_func, bool p_for_ready) { Vector<int> bytecode; CodeGen codegen; - codegen.class_node=p_class; - codegen.script=p_script; - codegen.function_node=p_func; - codegen.stack_max=0; - codegen.current_line=0; - codegen.call_max=0; - codegen.debug_stack=ScriptDebugger::get_singleton()!=NULL; + codegen.class_node = p_class; + codegen.script = p_script; + codegen.function_node = p_func; + codegen.stack_max = 0; + codegen.current_line = 0; + codegen.call_max = 0; + codegen.debug_stack = ScriptDebugger::get_singleton() != NULL; Vector<StringName> argnames; - int stack_level=0; + int stack_level = 0; if (p_func) { - for(int i=0;i<p_func->arguments.size();i++) { - codegen.add_stack_identifier(p_func->arguments[i],i); + for (int i = 0; i < p_func->arguments.size(); i++) { + codegen.add_stack_identifier(p_func->arguments[i], i); #ifdef TOOLS_ENABLED argnames.push_back(p_func->arguments[i]); #endif } - stack_level=p_func->arguments.size(); + stack_level = p_func->arguments.size(); } codegen.alloc_stack(stack_level); /* Parse initializer -if applies- */ - bool is_initializer=!p_for_ready && !p_func; + bool is_initializer = !p_for_ready && !p_func; - if (is_initializer || (p_func && String(p_func->name)=="_init")) { + if (is_initializer || (p_func && String(p_func->name) == "_init")) { //parse initializer for class members - if (!p_func && p_class->extends_used && p_script->native.is_null()){ + if (!p_func && p_class->extends_used && p_script->native.is_null()) { //call implicit parent constructor codegen.opcodes.push_back(GDFunction::OPCODE_CALL_SELF_BASE); codegen.opcodes.push_back(codegen.get_name_map_pos("_init")); codegen.opcodes.push_back(0); - codegen.opcodes.push_back((GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)|0); - + codegen.opcodes.push_back((GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) | 0); } - Error err = _parse_block(codegen,p_class->initializer,stack_level); + Error err = _parse_block(codegen, p_class->initializer, stack_level); if (err) return err; - is_initializer=true; - + is_initializer = true; } - if (p_for_ready || (p_func && String(p_func->name)=="_ready")) { + if (p_for_ready || (p_func && String(p_func->name) == "_ready")) { //parse initializer for class members if (p_class->ready->statements.size()) { - Error err = _parse_block(codegen,p_class->ready,stack_level); + Error err = _parse_block(codegen, p_class->ready, stack_level); if (err) return err; } - } - /* Parse default argument code -if applies- */ Vector<int> defarg_addr; @@ -1305,189 +1284,178 @@ Error GDCompiler::_parse_function(GDScript *p_script,const GDParser::ClassNode * codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_TO_DEF_ARGUMENT); defarg_addr.push_back(codegen.opcodes.size()); - for(int i=0;i<p_func->default_values.size();i++) { + for (int i = 0; i < p_func->default_values.size(); i++) { - _parse_expression(codegen,p_func->default_values[i],stack_level,true); + _parse_expression(codegen, p_func->default_values[i], stack_level, true); defarg_addr.push_back(codegen.opcodes.size()); } - defarg_addr.invert(); } - - - Error err = _parse_block(codegen,p_func->body,stack_level); + Error err = _parse_block(codegen, p_func->body, stack_level); if (err) return err; - func_name=p_func->name; + func_name = p_func->name; } else { if (p_for_ready) - func_name="_ready"; + func_name = "_ready"; else - func_name="_init"; + func_name = "_init"; } codegen.opcodes.push_back(GDFunction::OPCODE_END); - GDFunction *gdfunc=NULL; + GDFunction *gdfunc = NULL; //if (String(p_func->name)=="") { //initializer func // gdfunc = &p_script->initializer; //} else { //regular func - p_script->member_functions[func_name]=memnew(GDFunction); - gdfunc = p_script->member_functions[func_name]; + p_script->member_functions[func_name] = memnew(GDFunction); + gdfunc = p_script->member_functions[func_name]; //} if (p_func) - gdfunc->_static=p_func->_static; + gdfunc->_static = p_func->_static; #ifdef TOOLS_ENABLED - gdfunc->arg_names=argnames; + gdfunc->arg_names = argnames; #endif //constants if (codegen.constant_map.size()) { - gdfunc->_constant_count=codegen.constant_map.size(); + gdfunc->_constant_count = codegen.constant_map.size(); gdfunc->constants.resize(codegen.constant_map.size()); - gdfunc->_constants_ptr=&gdfunc->constants[0]; - const Variant *K=NULL; - while((K=codegen.constant_map.next(K))) { + gdfunc->_constants_ptr = &gdfunc->constants[0]; + const Variant *K = NULL; + while ((K = codegen.constant_map.next(K))) { int idx = codegen.constant_map[*K]; - gdfunc->constants[idx]=*K; + gdfunc->constants[idx] = *K; } } else { - gdfunc->_constants_ptr=NULL; - gdfunc->_constant_count=0; + gdfunc->_constants_ptr = NULL; + gdfunc->_constant_count = 0; } //global names if (codegen.name_map.size()) { gdfunc->global_names.resize(codegen.name_map.size()); gdfunc->_global_names_ptr = &gdfunc->global_names[0]; - for(Map<StringName,int>::Element *E=codegen.name_map.front();E;E=E->next()) { + for (Map<StringName, int>::Element *E = codegen.name_map.front(); E; E = E->next()) { - gdfunc->global_names[E->get()]=E->key(); + gdfunc->global_names[E->get()] = E->key(); } - gdfunc->_global_names_count=gdfunc->global_names.size(); + gdfunc->_global_names_count = gdfunc->global_names.size(); } else { gdfunc->_global_names_ptr = NULL; - gdfunc->_global_names_count =0; + gdfunc->_global_names_count = 0; } - if (codegen.opcodes.size()) { - gdfunc->code=codegen.opcodes; - gdfunc->_code_ptr=&gdfunc->code[0]; - gdfunc->_code_size=codegen.opcodes.size(); + gdfunc->code = codegen.opcodes; + gdfunc->_code_ptr = &gdfunc->code[0]; + gdfunc->_code_size = codegen.opcodes.size(); } else { - gdfunc->_code_ptr=NULL; - gdfunc->_code_size=0; + gdfunc->_code_ptr = NULL; + gdfunc->_code_size = 0; } if (defarg_addr.size()) { - gdfunc->default_arguments=defarg_addr; - gdfunc->_default_arg_count=defarg_addr.size()-1; - gdfunc->_default_arg_ptr=&gdfunc->default_arguments[0]; + gdfunc->default_arguments = defarg_addr; + gdfunc->_default_arg_count = defarg_addr.size() - 1; + gdfunc->_default_arg_ptr = &gdfunc->default_arguments[0]; } else { - gdfunc->_default_arg_count=0; - gdfunc->_default_arg_ptr=NULL; + gdfunc->_default_arg_count = 0; + gdfunc->_default_arg_ptr = NULL; } - gdfunc->_argument_count=p_func ? p_func->arguments.size() : 0; - gdfunc->_stack_size=codegen.stack_max; - gdfunc->_call_size=codegen.call_max; - gdfunc->name=func_name; + gdfunc->_argument_count = p_func ? p_func->arguments.size() : 0; + gdfunc->_stack_size = codegen.stack_max; + gdfunc->_call_size = codegen.call_max; + gdfunc->name = func_name; #ifdef DEBUG_ENABLED - if (ScriptDebugger::get_singleton()){ + if (ScriptDebugger::get_singleton()) { String signature; //path - if (p_script->get_path()!=String()) - signature+=p_script->get_path(); + if (p_script->get_path() != String()) + signature += p_script->get_path(); //loc if (p_func) { - signature+="::"+itos(p_func->body->line); + signature += "::" + itos(p_func->body->line); } else { - signature+="::0"; + signature += "::0"; } //funciton and class if (p_class->name) { - signature+="::"+String(p_class->name)+"."+String(func_name); + signature += "::" + String(p_class->name) + "." + String(func_name); } else { - signature+="::"+String(func_name); + signature += "::" + String(func_name); } - - - gdfunc->profile.signature=signature; + gdfunc->profile.signature = signature; } #endif - gdfunc->_script=p_script; - gdfunc->source=source; + gdfunc->_script = p_script; + gdfunc->source = source; #ifdef DEBUG_ENABLED { - gdfunc->func_cname=(String(source)+" - "+String(func_name)).utf8(); - gdfunc->_func_cname=gdfunc->func_cname.get_data(); - + gdfunc->func_cname = (String(source) + " - " + String(func_name)).utf8(); + gdfunc->_func_cname = gdfunc->func_cname.get_data(); } #endif if (p_func) { - gdfunc->_initial_line=p_func->line; + gdfunc->_initial_line = p_func->line; } else { - gdfunc->_initial_line=0; + gdfunc->_initial_line = 0; } if (codegen.debug_stack) - gdfunc->stack_debug=codegen.stack_debug; + gdfunc->stack_debug = codegen.stack_debug; if (is_initializer) - p_script->initializer=gdfunc; - + p_script->initializer = gdfunc; return OK; } - - Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDParser::ClassNode *p_class, bool p_keep_state) { - Map<StringName,Ref<GDScript> > old_subclasses; + Map<StringName, Ref<GDScript> > old_subclasses; if (p_keep_state) { - old_subclasses=p_script->subclasses; + old_subclasses = p_script->subclasses; } - p_script->native=Ref<GDNativeClass>(); - p_script->base=Ref<GDScript>(); - p_script->_base=NULL; + p_script->native = Ref<GDNativeClass>(); + p_script->base = Ref<GDScript>(); + p_script->_base = NULL; p_script->members.clear(); p_script->constants.clear(); - for (Map<StringName,GDFunction*>::Element *E=p_script->member_functions.front();E;E=E->next()) { + for (Map<StringName, GDFunction *>::Element *E = p_script->member_functions.front(); E; E = E->next()) { memdelete(E->get()); } p_script->member_functions.clear(); p_script->member_indices.clear(); p_script->member_info.clear(); p_script->_signals.clear(); - p_script->initializer=NULL; + p_script->initializer = NULL; p_script->subclasses.clear(); - p_script->_owner=p_owner; - p_script->tool=p_class->tool; - p_script->name=p_class->name; - + p_script->_owner = p_owner; + p_script->tool = p_class->tool; + p_script->name = p_class->name; Ref<GDNativeClass> native; @@ -1497,8 +1465,7 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa Ref<GDScript> script; - - if (path!="") { + if (path != "") { //path (and optionally subclasses) if (path.is_rel_path()) { @@ -1508,47 +1475,46 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa if (p_owner) { GDScript *current_class = p_owner; while (current_class != NULL) { - base=current_class->get_path(); - if (base=="") + base = current_class->get_path(); + if (base == "") current_class = current_class->_owner; else break; } - } - else { + } else { base = p_script->get_path(); } - if (base=="" || base.is_rel_path()) { - _set_error("Could not resolve relative path for parent class: "+path,p_class); + if (base == "" || base.is_rel_path()) { + _set_error("Could not resolve relative path for parent class: " + path, p_class); return ERR_FILE_NOT_FOUND; } - path=base.get_base_dir().plus_file(path).simplify_path(); + path = base.get_base_dir().plus_file(path).simplify_path(); } script = ResourceLoader::load(path); if (script.is_null()) { - _set_error("Could not load base class: "+path,p_class); + _set_error("Could not load base class: " + path, p_class); return ERR_FILE_NOT_FOUND; } if (!script->valid) { - _set_error("Script not fully loaded (cyclic preload?): "+path,p_class); + _set_error("Script not fully loaded (cyclic preload?): " + path, p_class); return ERR_BUSY; } //print_line("EXTENDS PATH: "+path+" script is "+itos(script.is_valid())+" indices is "+itos(script->member_indices.size())+" valid? "+itos(script->valid)); if (p_class->extends_class.size()) { - for(int i=0;i<p_class->extends_class.size();i++) { + for (int i = 0; i < p_class->extends_class.size(); i++) { String sub = p_class->extends_class[i]; if (script->subclasses.has(sub)) { Ref<Script> subclass = script->subclasses[sub]; //avoid reference from dissapearing - script=subclass; + script = subclass; } else { - _set_error("Could not find subclass: "+sub,p_class); + _set_error("Could not find subclass: " + sub, p_class); return ERR_FILE_NOT_FOUND; } } @@ -1556,54 +1522,52 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa } else { - ERR_FAIL_COND_V(p_class->extends_class.size()==0,ERR_BUG); + ERR_FAIL_COND_V(p_class->extends_class.size() == 0, ERR_BUG); //look around for the subclasses - String base=p_class->extends_class[0]; + String base = p_class->extends_class[0]; GDScript *p = p_owner; Ref<GDScript> base_class; - while(p) { + while (p) { if (p->subclasses.has(base)) { - base_class=p->subclasses[base]; + base_class = p->subclasses[base]; break; } - p=p->_owner; + p = p->_owner; } if (base_class.is_valid()) { - for(int i=1;i<p_class->extends_class.size();i++) { + for (int i = 1; i < p_class->extends_class.size(); i++) { - String subclass=p_class->extends_class[i]; + String subclass = p_class->extends_class[i]; if (base_class->subclasses.has(subclass)) { - base_class=base_class->subclasses[subclass]; + base_class = base_class->subclasses[subclass]; } else { - _set_error("Could not find subclass: "+subclass,p_class); + _set_error("Could not find subclass: " + subclass, p_class); return ERR_FILE_NOT_FOUND; } } - script=base_class; - + script = base_class; } else { - if (p_class->extends_class.size()>1) { + if (p_class->extends_class.size() > 1) { - _set_error("Invalid inheritance (unknown class+subclasses)",p_class); + _set_error("Invalid inheritance (unknown class+subclasses)", p_class); return ERR_FILE_NOT_FOUND; - } //if not found, try engine classes if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { - _set_error("Unknown class: '"+base+"'",p_class); + _set_error("Unknown class: '" + base + "'", p_class); return ERR_FILE_NOT_FOUND; } @@ -1611,57 +1575,51 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx]; if (!native.is_valid()) { - _set_error("Global not a class: '"+base+"'",p_class); + _set_error("Global not a class: '" + base + "'", p_class); return ERR_FILE_NOT_FOUND; } } - - } if (script.is_valid()) { - p_script->base=script; - p_script->_base=p_script->base.ptr(); - p_script->member_indices=script->member_indices; + p_script->base = script; + p_script->_base = p_script->base.ptr(); + p_script->member_indices = script->member_indices; } else if (native.is_valid()) { - p_script->native=native; + p_script->native = native; } else { - _set_error("Could not determine inheritance",p_class); + _set_error("Could not determine inheritance", p_class); return ERR_FILE_NOT_FOUND; } - - } - //print_line("Script: "+p_script->get_path()+" indices: "+itos(p_script->member_indices.size())); - - for(int i=0;i<p_class->variables.size();i++) { + for (int i = 0; i < p_class->variables.size(); i++) { StringName name = p_class->variables[i].identifier; if (p_script->member_indices.has(name)) { - _set_error("Member '"+name+"' already exists (in current or parent class)",p_class); + _set_error("Member '" + name + "' already exists (in current or parent class)", p_class); return ERR_ALREADY_EXISTS; } - if (p_class->variables[i]._export.type!=Variant::NIL) { + if (p_class->variables[i]._export.type != Variant::NIL) { - p_script->member_info[name]=p_class->variables[i]._export; + p_script->member_info[name] = p_class->variables[i]._export; #ifdef TOOLS_ENABLED - if (p_class->variables[i].default_value.get_type()!=Variant::NIL) { + if (p_class->variables[i].default_value.get_type() != Variant::NIL) { - p_script->member_default_values[name]=p_class->variables[i].default_value; + p_script->member_default_values[name] = p_class->variables[i].default_value; } #endif } else { - p_script->member_info[name]=PropertyInfo(Variant::NIL,name,PROPERTY_HINT_NONE,"",PROPERTY_USAGE_SCRIPT_VARIABLE); + p_script->member_info[name] = PropertyInfo(Variant::NIL, name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE); } //int new_idx = p_script->member_indices.size(); @@ -1669,154 +1627,147 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa minfo.index = p_script->member_indices.size(); minfo.setter = p_class->variables[i].setter; minfo.getter = p_class->variables[i].getter; - p_script->member_indices[name]=minfo; + p_script->member_indices[name] = minfo; p_script->members.insert(name); - } - for(int i=0;i<p_class->constant_expressions.size();i++) { + for (int i = 0; i < p_class->constant_expressions.size(); i++) { StringName name = p_class->constant_expressions[i].identifier; - ERR_CONTINUE( p_class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT ); + ERR_CONTINUE(p_class->constant_expressions[i].expression->type != GDParser::Node::TYPE_CONSTANT); - GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode*>(p_class->constant_expressions[i].expression); + GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode *>(p_class->constant_expressions[i].expression); - p_script->constants.insert(name,constant->value); + p_script->constants.insert(name, constant->value); //p_script->constants[constant->value].make_const(); } - for(int i=0;i<p_class->_signals.size();i++) { + for (int i = 0; i < p_class->_signals.size(); i++) { StringName name = p_class->_signals[i].name; GDScript *c = p_script; - while(c) { + while (c) { if (c->_signals.has(name)) { - _set_error("Signal '"+name+"' redefined (in current or parent class)",p_class); + _set_error("Signal '" + name + "' redefined (in current or parent class)", p_class); return ERR_ALREADY_EXISTS; } if (c->base.is_valid()) { - c=c->base.ptr(); + c = c->base.ptr(); } else { - c=NULL; + c = NULL; } } if (native.is_valid()) { - if (ObjectTypeDB::has_signal(native->get_name(),name)) { - _set_error("Signal '"+name+"' redefined (original in native class '"+String(native->get_name())+"')",p_class); + if (ObjectTypeDB::has_signal(native->get_name(), name)) { + _set_error("Signal '" + name + "' redefined (original in native class '" + String(native->get_name()) + "')", p_class); return ERR_ALREADY_EXISTS; } } - p_script->_signals[name]=p_class->_signals[i].arguments; + p_script->_signals[name] = p_class->_signals[i].arguments; } //parse sub-classes - for(int i=0;i<p_class->subclasses.size();i++) { + for (int i = 0; i < p_class->subclasses.size(); i++) { StringName name = p_class->subclasses[i]->name; Ref<GDScript> subclass; if (old_subclasses.has(name)) { - subclass=old_subclasses[name]; + subclass = old_subclasses[name]; } else { subclass.instance(); } - Error err = _parse_class(subclass.ptr(),p_script,p_class->subclasses[i],p_keep_state); + Error err = _parse_class(subclass.ptr(), p_script, p_class->subclasses[i], p_keep_state); if (err) return err; - - p_script->constants.insert(name,subclass); //once parsed, goes to the list of constants - p_script->subclasses.insert(name,subclass); - + p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants + p_script->subclasses.insert(name, subclass); } - //parse methods - bool has_initializer=false; - bool has_ready=false; + bool has_initializer = false; + bool has_ready = false; - for(int i=0;i<p_class->functions.size();i++) { + for (int i = 0; i < p_class->functions.size(); i++) { - if (!has_initializer && p_class->functions[i]->name=="_init") - has_initializer=true; - if (!has_ready && p_class->functions[i]->name=="_ready") - has_ready=true; - Error err = _parse_function(p_script,p_class,p_class->functions[i]); + if (!has_initializer && p_class->functions[i]->name == "_init") + has_initializer = true; + if (!has_ready && p_class->functions[i]->name == "_ready") + has_ready = true; + Error err = _parse_function(p_script, p_class, p_class->functions[i]); if (err) return err; } //parse static methods - for(int i=0;i<p_class->static_functions.size();i++) { + for (int i = 0; i < p_class->static_functions.size(); i++) { - Error err = _parse_function(p_script,p_class,p_class->static_functions[i]); + Error err = _parse_function(p_script, p_class, p_class->static_functions[i]); if (err) return err; } - if (!has_initializer) { //create a constructor - Error err = _parse_function(p_script,p_class,NULL); + Error err = _parse_function(p_script, p_class, NULL); if (err) return err; } if (!has_ready && p_class->ready->statements.size()) { //create a constructor - Error err = _parse_function(p_script,p_class,NULL,true); + Error err = _parse_function(p_script, p_class, NULL, true); if (err) return err; } #ifdef DEBUG_ENABLED //validate setters/getters if debug is enabled - for(int i=0;i<p_class->variables.size();i++) { + for (int i = 0; i < p_class->variables.size(); i++) { if (p_class->variables[i].setter) { - const Map<StringName,GDFunction*>::Element *E=p_script->get_member_functions().find(p_class->variables[i].setter); + const Map<StringName, GDFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].setter); if (!E) { - _set_error("Setter function '"+String(p_class->variables[i].setter)+"' not found in class.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Setter function '" + String(p_class->variables[i].setter) + "' not found in class.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } if (E->get()->is_static()) { - _set_error("Setter function '"+String(p_class->variables[i].setter)+"' is static.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Setter function '" + String(p_class->variables[i].setter) + "' is static.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } - } if (p_class->variables[i].getter) { - const Map<StringName,GDFunction*>::Element *E=p_script->get_member_functions().find(p_class->variables[i].getter); + const Map<StringName, GDFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].getter); if (!E) { - _set_error("Getter function '"+String(p_class->variables[i].getter)+"' not found in class.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Getter function '" + String(p_class->variables[i].getter) + "' not found in class.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } if (E->get()->is_static()) { - _set_error("Getter function '"+String(p_class->variables[i].getter)+"' is static.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Getter function '" + String(p_class->variables[i].getter) + "' is static.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } - } } @@ -1824,96 +1775,88 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa if (p_keep_state) { - print_line("RELOAD KEEP "+p_script->path); - for (Set<Object*>::Element *E=p_script->instances.front();E;) { + print_line("RELOAD KEEP " + p_script->path); + for (Set<Object *>::Element *E = p_script->instances.front(); E;) { - Set<Object*>::Element *N = E->next(); + Set<Object *>::Element *N = E->next(); ScriptInstance *si = E->get()->get_script_instance(); if (si->is_placeholder()) { #ifdef TOOLS_ENABLED - PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance*>(si); + PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si); if (p_script->is_tool()) { //re-create as an instance p_script->placeholders.erase(psi); //remove placeholder - GDInstance* instance = memnew( GDInstance ); - instance->base_ref=E->get()->cast_to<Reference>(); + GDInstance *instance = memnew(GDInstance); + instance->base_ref = E->get()->cast_to<Reference>(); instance->members.resize(p_script->member_indices.size()); - instance->script=Ref<GDScript>(p_script); - instance->owner=E->get(); + instance->script = Ref<GDScript>(p_script); + instance->owner = E->get(); //needed for hot reloading - for(Map<StringName,GDScript::MemberInfo>::Element *E=p_script->member_indices.front();E;E=E->next()) { - instance->member_indices_cache[E->key()]=E->get().index; + for (Map<StringName, GDScript::MemberInfo>::Element *E = p_script->member_indices.front(); E; E = E->next()) { + instance->member_indices_cache[E->key()] = E->get().index; } instance->owner->set_script_instance(instance); - /* STEP 2, INITIALIZE AND CONSRTUCT */ Variant::CallError ce; - p_script->initializer->call(instance,NULL,0,ce); + p_script->initializer->call(instance, NULL, 0, ce); - if (ce.error!=Variant::CallError::CALL_OK) { + if (ce.error != Variant::CallError::CALL_OK) { //well, tough luck, not goinna do anything here } } #endif } else { - GDInstance *gi = static_cast<GDInstance*>(si); + GDInstance *gi = static_cast<GDInstance *>(si); gi->reload_members(); } - E=N; - + E = N; } - - } #endif - p_script->valid=true; + p_script->valid = true; return OK; } -Error GDCompiler::compile(const GDParser *p_parser,GDScript *p_script,bool p_keep_state) { +Error GDCompiler::compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state) { - err_line=-1; - err_column=-1; - error=""; - parser=p_parser; - const GDParser::Node* root = parser->get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,ERR_INVALID_DATA); + err_line = -1; + err_column = -1; + error = ""; + parser = p_parser; + const GDParser::Node *root = parser->get_parse_tree(); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, ERR_INVALID_DATA); - source=p_script->get_path(); + source = p_script->get_path(); - Error err = _parse_class(p_script,NULL,static_cast<const GDParser::ClassNode*>(root),p_keep_state); + Error err = _parse_class(p_script, NULL, static_cast<const GDParser::ClassNode *>(root), p_keep_state); if (err) return err; return OK; - } String GDCompiler::get_error() const { return error; } -int GDCompiler::get_error_line() const{ +int GDCompiler::get_error_line() const { return err_line; } -int GDCompiler::get_error_column() const{ +int GDCompiler::get_error_column() const { return err_column; } -GDCompiler::GDCompiler() -{ +GDCompiler::GDCompiler() { } - - diff --git a/modules/gdscript/gd_compiler.h b/modules/gdscript/gd_compiler.h index eefd6de3e..f4d49b3b8 100644 --- a/modules/gdscript/gd_compiler.h +++ b/modules/gdscript/gd_compiler.h @@ -32,7 +32,6 @@ #include "gd_parser.h" #include "gd_script.h" - class GDCompiler { const GDParser *parser; @@ -42,83 +41,86 @@ class GDCompiler { const GDParser::FunctionNode *function_node; bool debug_stack; - List< Map<StringName,int> > stack_id_stack; - Map<StringName,int> stack_identifiers; - - List<GDFunction::StackDebug> stack_debug; - List< Map<StringName,int> > block_identifier_stack; - Map<StringName,int> block_identifiers; + List<Map<StringName, int> > stack_id_stack; + Map<StringName, int> stack_identifiers; - void add_stack_identifier(const StringName& p_id,int p_stackpos) { - stack_identifiers[p_id]=p_stackpos; - if (debug_stack) { - block_identifiers[p_id]=p_stackpos; - GDFunction::StackDebug sd; - sd.added=true; - sd.line=current_line; - sd.identifier=p_id; - sd.pos=p_stackpos; - stack_debug.push_back(sd); - } - } + List<GDFunction::StackDebug> stack_debug; + List<Map<StringName, int> > block_identifier_stack; + Map<StringName, int> block_identifiers; - void push_stack_identifiers() { - stack_id_stack.push_back( stack_identifiers ); - if (debug_stack) { + void add_stack_identifier(const StringName &p_id, int p_stackpos) { + stack_identifiers[p_id] = p_stackpos; + if (debug_stack) { + block_identifiers[p_id] = p_stackpos; + GDFunction::StackDebug sd; + sd.added = true; + sd.line = current_line; + sd.identifier = p_id; + sd.pos = p_stackpos; + stack_debug.push_back(sd); + } + } - block_identifier_stack.push_back(block_identifiers); - block_identifiers.clear(); - } - } + void push_stack_identifiers() { + stack_id_stack.push_back(stack_identifiers); + if (debug_stack) { - void pop_stack_identifiers() { - stack_identifiers = stack_id_stack.back()->get(); - stack_id_stack.pop_back(); + block_identifier_stack.push_back(block_identifiers); + block_identifiers.clear(); + } + } - if (debug_stack) { - for (Map<StringName,int>::Element *E=block_identifiers.front();E;E=E->next()) { + void pop_stack_identifiers() { + stack_identifiers = stack_id_stack.back()->get(); + stack_id_stack.pop_back(); - GDFunction::StackDebug sd; - sd.added=false; - sd.identifier=E->key(); - sd.line=current_line; - sd.pos=E->get(); - stack_debug.push_back(sd); - } - block_identifiers=block_identifier_stack.back()->get(); - block_identifier_stack.pop_back(); - } - } + if (debug_stack) { + for (Map<StringName, int>::Element *E = block_identifiers.front(); E; E = E->next()) { + GDFunction::StackDebug sd; + sd.added = false; + sd.identifier = E->key(); + sd.line = current_line; + sd.pos = E->get(); + stack_debug.push_back(sd); + } + block_identifiers = block_identifier_stack.back()->get(); + block_identifier_stack.pop_back(); + } + } //int get_identifier_pos(const StringName& p_dentifier) const; - HashMap<Variant,int,VariantHasher> constant_map; - Map<StringName,int> name_map; + HashMap<Variant, int, VariantHasher> constant_map; + Map<StringName, int> name_map; - int get_name_map_pos(const StringName& p_identifier) { + int get_name_map_pos(const StringName &p_identifier) { int ret; if (!name_map.has(p_identifier)) { - ret=name_map.size(); - name_map[p_identifier]=ret; + ret = name_map.size(); + name_map[p_identifier] = ret; } else { - ret=name_map[p_identifier]; + ret = name_map[p_identifier]; } return ret; } - int get_constant_pos(const Variant& p_constant) { + int get_constant_pos(const Variant &p_constant) { if (constant_map.has(p_constant)) return constant_map[p_constant]; int pos = constant_map.size(); - constant_map[p_constant]=pos; + constant_map[p_constant] = pos; return pos; } Vector<int> opcodes; - void alloc_stack(int p_level) { if (p_level >= stack_max) stack_max=p_level+1; } - void alloc_call(int p_params) { if (p_params >= call_max) call_max=p_params; } + void alloc_stack(int p_level) { + if (p_level >= stack_max) stack_max = p_level + 1; + } + void alloc_call(int p_params) { + if (p_params >= call_max) call_max = p_params; + } - int current_line; + int current_line; int stack_max; int call_max; }; @@ -134,25 +136,24 @@ class GDCompiler { Ref<GDScript> _parse_class(GDParser::ClassNode *p_class); #endif - void _set_error(const String& p_error,const GDParser::Node *p_node); + void _set_error(const String &p_error, const GDParser::Node *p_node); - bool _create_unary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level); - bool _create_binary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level,bool p_initializer=false); + bool _create_unary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level); + bool _create_binary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer = false); //int _parse_subexpression(CodeGen& codegen,const GDParser::BlockNode *p_block,const GDParser::Node *p_expression); - int _parse_assign_right_expression(CodeGen& codegen,const GDParser::OperatorNode *p_expression, int p_stack_level); - int _parse_expression(CodeGen& codegen,const GDParser::Node *p_expression, int p_stack_level,bool p_root=false,bool p_initializer=false); - Error _parse_block(CodeGen& codegen,const GDParser::BlockNode *p_block,int p_stack_level=0,int p_break_addr=-1,int p_continue_addr=-1); - Error _parse_function(GDScript *p_script,const GDParser::ClassNode *p_class,const GDParser::FunctionNode *p_func,bool p_for_ready=false); - Error _parse_class(GDScript *p_script,GDScript *p_owner,const GDParser::ClassNode *p_class,bool p_keep_state); + int _parse_assign_right_expression(CodeGen &codegen, const GDParser::OperatorNode *p_expression, int p_stack_level); + int _parse_expression(CodeGen &codegen, const GDParser::Node *p_expression, int p_stack_level, bool p_root = false, bool p_initializer = false); + Error _parse_block(CodeGen &codegen, const GDParser::BlockNode *p_block, int p_stack_level = 0, int p_break_addr = -1, int p_continue_addr = -1); + Error _parse_function(GDScript *p_script, const GDParser::ClassNode *p_class, const GDParser::FunctionNode *p_func, bool p_for_ready = false); + Error _parse_class(GDScript *p_script, GDScript *p_owner, const GDParser::ClassNode *p_class, bool p_keep_state); int err_line; int err_column; StringName source; String error; public: - - Error compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state=false); + Error compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state = false); String get_error() const; int get_error_line() const; @@ -161,5 +162,4 @@ public: GDCompiler(); }; - #endif // COMPILER_H diff --git a/modules/gdscript/gd_editor.cpp b/modules/gdscript/gd_editor.cpp index 694a51770..b36a20752 100644 --- a/modules/gdscript/gd_editor.cpp +++ b/modules/gdscript/gd_editor.cpp @@ -26,8 +26,8 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gd_script.h" #include "gd_compiler.h" +#include "gd_script.h" #include "globals.h" #include "os/file_access.h" @@ -35,66 +35,58 @@ void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const p_delimiters->push_back("#"); p_delimiters->push_back("\"\"\" \"\"\""); - } void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { p_delimiters->push_back("\" \""); p_delimiters->push_back("' '"); - - } -String GDScriptLanguage::get_template(const String& p_class_name, const String& p_base_class_name) const { +String GDScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { - String _template = String()+ - "extends %BASE%\n\n"+ - "# class member variables go here, for example:\n"+ - "# var a = 2\n"+ - "# var b = \"textvar\"\n\n"+ - "func _ready():\n"+ - "\t# Called every time the node is added to the scene.\n"+ - "\t# Initialization here\n"+ - "\tpass\n"; + String _template = String() + + "extends %BASE%\n\n" + + "# class member variables go here, for example:\n" + + "# var a = 2\n" + + "# var b = \"textvar\"\n\n" + + "func _ready():\n" + + "\t# Called every time the node is added to the scene.\n" + + "\t# Initialization here\n" + + "\tpass\n"; - return _template.replace("%BASE%",p_base_class_name); + return _template.replace("%BASE%", p_base_class_name); } - - - -bool GDScriptLanguage::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) const { +bool GDScriptLanguage::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) const { GDParser parser; - Error err = parser.parse(p_script,p_path.get_base_dir(),true,p_path); + Error err = parser.parse(p_script, p_path.get_base_dir(), true, p_path); if (err) { - r_line_error=parser.get_error_line(); - r_col_error=parser.get_error_column(); - r_test_error=parser.get_error(); + r_line_error = parser.get_error_line(); + r_col_error = parser.get_error_column(); + r_test_error = parser.get_error(); return false; } else { const GDParser::Node *root = parser.get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false); - const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root); - Map<int,String> funcs; - for(int i=0;i<cl->functions.size();i++) { + const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root); + Map<int, String> funcs; + for (int i = 0; i < cl->functions.size(); i++) { - funcs[cl->functions[i]->line]=cl->functions[i]->name; + funcs[cl->functions[i]->line] = cl->functions[i]->name; } - for(int i=0;i<cl->static_functions.size();i++) { + for (int i = 0; i < cl->static_functions.size(); i++) { - funcs[cl->static_functions[i]->line]=cl->static_functions[i]->name; + funcs[cl->static_functions[i]->line] = cl->static_functions[i]->name; } - for (Map<int,String>::Element *E=funcs.front();E;E=E->next()) { + for (Map<int, String>::Element *E = funcs.front(); E; E = E->next()) { - r_functions->push_back(E->get()+":"+itos(E->key())); + r_functions->push_back(E->get() + ":" + itos(E->key())); } - - } return true; @@ -105,142 +97,133 @@ bool GDScriptLanguage::has_named_classes() const { return false; } -int GDScriptLanguage::find_function(const String& p_function,const String& p_code) const { +int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const { GDTokenizerText tokenizer; tokenizer.set_code(p_code); - int indent=0; - while(tokenizer.get_token()!=GDTokenizer::TK_EOF && tokenizer.get_token()!=GDTokenizer::TK_ERROR) { + int indent = 0; + while (tokenizer.get_token() != GDTokenizer::TK_EOF && tokenizer.get_token() != GDTokenizer::TK_ERROR) { - if (tokenizer.get_token()==GDTokenizer::TK_NEWLINE) { - indent=tokenizer.get_token_line_indent(); + if (tokenizer.get_token() == GDTokenizer::TK_NEWLINE) { + indent = tokenizer.get_token_line_indent(); } //print_line("TOKEN: "+String(GDTokenizer::get_token_name(tokenizer.get_token()))); - if (indent==0 && tokenizer.get_token()==GDTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1)==GDTokenizer::TK_IDENTIFIER) { + if (indent == 0 && tokenizer.get_token() == GDTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1) == GDTokenizer::TK_IDENTIFIER) { String identifier = tokenizer.get_token_identifier(1); - if (identifier==p_function) { + if (identifier == p_function) { return tokenizer.get_token_line(); } } tokenizer.advance(); //print_line("NEXT: "+String(GDTokenizer::get_token_name(tokenizer.get_token()))); - } return -1; } Script *GDScriptLanguage::create_script() const { - return memnew( GDScript ); + return memnew(GDScript); } /* DEBUGGER FUNCTIONS */ - -bool GDScriptLanguage::debug_break_parse(const String& p_file, int p_line,const String& p_error) { +bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) { //break because of parse error - if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) { - - _debug_parse_err_line=p_line; - _debug_parse_err_file=p_file; - _debug_error=p_error; - ScriptDebugger::get_singleton()->debug(this,false); - return true; - } else { - return false; - } + if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) { + _debug_parse_err_line = p_line; + _debug_parse_err_file = p_file; + _debug_error = p_error; + ScriptDebugger::get_singleton()->debug(this, false); + return true; + } else { + return false; + } } -bool GDScriptLanguage::debug_break(const String& p_error,bool p_allow_continue) { - - if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) { +bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) { - _debug_parse_err_line=-1; - _debug_parse_err_file=""; - _debug_error=p_error; - ScriptDebugger::get_singleton()->debug(this,p_allow_continue); - return true; - } else { - return false; - } + if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) { + _debug_parse_err_line = -1; + _debug_parse_err_file = ""; + _debug_error = p_error; + ScriptDebugger::get_singleton()->debug(this, p_allow_continue); + return true; + } else { + return false; + } } String GDScriptLanguage::debug_get_error() const { - return _debug_error; + return _debug_error; } int GDScriptLanguage::debug_get_stack_level_count() const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return 1; - return _debug_call_stack_pos; } int GDScriptLanguage::debug_get_stack_level_line(int p_level) const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return _debug_parse_err_line; - ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,-1); + ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1); - int l = _debug_call_stack_pos - p_level -1; - - return *(_call_stack[l].line); + int l = _debug_call_stack_pos - p_level - 1; + return *(_call_stack[l].line); } String GDScriptLanguage::debug_get_stack_level_function(int p_level) const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return ""; - ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,""); - int l = _debug_call_stack_pos - p_level -1; - return _call_stack[l].function->get_name(); + ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, ""); + int l = _debug_call_stack_pos - p_level - 1; + return _call_stack[l].function->get_name(); } String GDScriptLanguage::debug_get_stack_level_source(int p_level) const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return _debug_parse_err_file; - ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,""); - int l = _debug_call_stack_pos - p_level -1; - return _call_stack[l].function->get_source(); - + ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, ""); + int l = _debug_call_stack_pos - p_level - 1; + return _call_stack[l].function->get_source(); } -void GDScriptLanguage::debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems,int p_max_depth) { +void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return; - ERR_FAIL_INDEX(p_level,_debug_call_stack_pos); - int l = _debug_call_stack_pos - p_level -1; - - GDFunction *f = _call_stack[l].function; + ERR_FAIL_INDEX(p_level, _debug_call_stack_pos); + int l = _debug_call_stack_pos - p_level - 1; - List<Pair<StringName,int> > locals; + GDFunction *f = _call_stack[l].function; - f->debug_get_stack_member_state(*_call_stack[l].line,&locals); - for( List<Pair<StringName,int> >::Element *E = locals.front();E;E=E->next() ) { + List<Pair<StringName, int> > locals; - p_locals->push_back(E->get().first); - p_values->push_back(_call_stack[l].stack[E->get().second]); - } + f->debug_get_stack_member_state(*_call_stack[l].line, &locals); + for (List<Pair<StringName, int> >::Element *E = locals.front(); E; E = E->next()) { + p_locals->push_back(E->get().first); + p_values->push_back(_call_stack[l].stack[E->get().second]); + } } -void GDScriptLanguage::debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems,int p_max_depth) { +void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return; - ERR_FAIL_INDEX(p_level,_debug_call_stack_pos); - int l = _debug_call_stack_pos - p_level -1; - + ERR_FAIL_INDEX(p_level, _debug_call_stack_pos); + int l = _debug_call_stack_pos - p_level - 1; GDInstance *instance = _call_stack[l].instance; @@ -248,25 +231,23 @@ void GDScriptLanguage::debug_get_stack_level_members(int p_level,List<String> *p return; Ref<GDScript> script = instance->get_script(); - ERR_FAIL_COND( script.is_null() ); - + ERR_FAIL_COND(script.is_null()); - const Map<StringName,GDScript::MemberInfo>& mi = script->debug_get_member_indices(); + const Map<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices(); - for(const Map<StringName,GDScript::MemberInfo>::Element *E=mi.front();E;E=E->next()) { + for (const Map<StringName, GDScript::MemberInfo>::Element *E = mi.front(); E; E = E->next()) { p_members->push_back(E->key()); - p_values->push_back( instance->debug_get_member_by_index(E->get().index)); + p_values->push_back(instance->debug_get_member_by_index(E->get().index)); } - } -void GDScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems,int p_max_depth) { +void GDScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - //no globals are really reachable in gdscript + //no globals are really reachable in gdscript } -String GDScriptLanguage::debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems,int p_max_depth) { +String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return ""; return ""; } @@ -276,11 +257,9 @@ void GDScriptLanguage::get_recognized_extensions(List<String> *p_extensions) con p_extensions->push_back("gd"); } - void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const { - - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { p_functions->push_back(GDFunctions::get_info(GDFunctions::Function(i))); } @@ -288,52 +267,51 @@ void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const //not really "functions", but.. { MethodInfo mi; - mi.name="preload:Resource"; - mi.arguments.push_back(PropertyInfo(Variant::STRING,"path")); - mi.return_val=PropertyInfo(Variant::OBJECT,"",PROPERTY_HINT_RESOURCE_TYPE,"Resource"); + mi.name = "preload:Resource"; + mi.arguments.push_back(PropertyInfo(Variant::STRING, "path")); + mi.return_val = PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_RESOURCE_TYPE, "Resource"); p_functions->push_back(mi); } { MethodInfo mi; - mi.name="yield:GDFunctionState"; - mi.arguments.push_back(PropertyInfo(Variant::OBJECT,"object")); - mi.arguments.push_back(PropertyInfo(Variant::STRING,"signal")); + mi.name = "yield:GDFunctionState"; + mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object")); + mi.arguments.push_back(PropertyInfo(Variant::STRING, "signal")); mi.default_arguments.push_back(Variant::NIL); mi.default_arguments.push_back(Variant::STRING); p_functions->push_back(mi); } { MethodInfo mi; - mi.name="assert"; - mi.arguments.push_back(PropertyInfo(Variant::BOOL,"condition")); + mi.name = "assert"; + mi.arguments.push_back(PropertyInfo(Variant::BOOL, "condition")); p_functions->push_back(mi); } } -void GDScriptLanguage::get_public_constants(List<Pair<String,Variant> > *p_constants) const { +void GDScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_constants) const { - Pair<String,Variant> pi; - pi.first="PI"; - pi.second=Math_PI; + Pair<String, Variant> pi; + pi.first = "PI"; + pi.second = Math_PI; p_constants->push_back(pi); } -String GDScriptLanguage::make_function(const String& p_class,const String& p_name,const StringArray& p_args) const { +String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const StringArray &p_args) const { - String s="func "+p_name+"("; + String s = "func " + p_name + "("; if (p_args.size()) { - s+=" "; - for(int i=0;i<p_args.size();i++) { - if (i>0) - s+=", "; - s+=p_args[i]; + s += " "; + for (int i = 0; i < p_args.size(); i++) { + if (i > 0) + s += ", "; + s += p_args[i]; } - s+=" "; + s += " "; } - s+="):\n\tpass # replace with function body\n"; + s += "):\n\tpass # replace with function body\n"; return s; - } #if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) @@ -346,33 +324,31 @@ struct GDCompletionIdentifier { Variant value; //im case there is a value, also return it }; - - -static GDCompletionIdentifier _get_type_from_variant(const Variant& p_variant) { +static GDCompletionIdentifier _get_type_from_variant(const Variant &p_variant) { GDCompletionIdentifier t; - t.type=p_variant.get_type(); - t.value=p_variant; - if (p_variant.get_type()==Variant::OBJECT) { + t.type = p_variant.get_type(); + t.value = p_variant; + if (p_variant.get_type() == Variant::OBJECT) { Object *obj = p_variant; if (obj) { //if (obj->cast_to<GDNativeClass>()) { // t.obj_type=obj->cast_to<GDNativeClass>()->get_name(); // t.value=Variant(); //} else { - t.obj_type=obj->get_type(); + t.obj_type = obj->get_type(); //} } } return t; } -static GDCompletionIdentifier _get_type_from_pinfo(const PropertyInfo& p_info) { +static GDCompletionIdentifier _get_type_from_pinfo(const PropertyInfo &p_info) { GDCompletionIdentifier t; - t.type=p_info.type; - if (p_info.hint==PROPERTY_HINT_RESOURCE_TYPE) { - t.obj_type=p_info.hint_string; + t.type = p_info.type; + if (p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) { + t.obj_type = p_info.hint_string; } return t; } @@ -382,15 +358,11 @@ struct GDCompletionContext { const GDParser::ClassNode *_class; const GDParser::FunctionNode *function; const GDParser::BlockNode *block; - Object* base; + Object *base; String base_path; - }; - -static Ref<Reference> _get_parent_class(GDCompletionContext& context) { - - +static Ref<Reference> _get_parent_class(GDCompletionContext &context) { if (context._class->extends_used) { //do inheritance @@ -399,12 +371,12 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { Ref<GDScript> script; Ref<GDNativeClass> native; - if (path!="") { + if (path != "") { //path (and optionally subclasses) if (path.is_rel_path()) { - path=context.base_path.plus_file(path); + path = context.base_path.plus_file(path); } if (ScriptCodeCompletionCache::get_sigleton()) @@ -423,12 +395,12 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { if (context._class->extends_class.size()) { - for(int i=0;i<context._class->extends_class.size();i++) { + for (int i = 0; i < context._class->extends_class.size(); i++) { String sub = context._class->extends_class[i]; if (script->get_subclasses().has(sub)) { - script=script->get_subclasses()[sub]; + script = script->get_subclasses()[sub]; } else { return REF(); @@ -441,17 +413,16 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { } else { - if (context._class->extends_class.size()==0) { + if (context._class->extends_class.size() == 0) { ERR_PRINT("BUG"); return REF(); } - String base=context._class->extends_class[0]; + String base = context._class->extends_class[0]; - if (context._class->extends_class.size()>1) { + if (context._class->extends_class.size() > 1) { return REF(); - } //if not found, try engine classes if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { @@ -462,22 +433,19 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base]; native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx]; return native; - } - } return Ref<Reference>(); } - -static GDCompletionIdentifier _get_native_class(GDCompletionContext& context) { +static GDCompletionIdentifier _get_native_class(GDCompletionContext &context) { //eeh... GDCompletionIdentifier id; - id.type=Variant::NIL; + id.type = Variant::NIL; - REF pc = _get_parent_class(context); + REF pc = _get_parent_class(context); if (!pc.is_valid()) { return id; } @@ -487,204 +455,191 @@ static GDCompletionIdentifier _get_native_class(GDCompletionContext& context) { if (s.is_null() && nc.is_null()) { return id; } - while(!s.is_null()) { - nc=s->get_native(); - s=s->get_base(); + while (!s.is_null()) { + nc = s->get_native(); + s = s->get_base(); } if (nc.is_null()) { return id; } - - - id.type=Variant::OBJECT; + id.type = Variant::OBJECT; if (context.base) - id.value=context.base; - id.obj_type=nc->get_name(); + id.value = context.base; + id.obj_type = nc->get_name(); return id; } -static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type); - +static bool _guess_identifier_type(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type); -static bool _guess_expression_type(GDCompletionContext& context,const GDParser::Node* p_node,int p_line,GDCompletionIdentifier &r_type) { +static bool _guess_expression_type(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, GDCompletionIdentifier &r_type) { + if (p_node->type == GDParser::Node::TYPE_CONSTANT) { - if (p_node->type==GDParser::Node::TYPE_CONSTANT) { + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(p_node); - const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(p_node); - - r_type=_get_type_from_variant(cn->value); + r_type = _get_type_from_variant(cn->value); return true; - } else if (p_node->type==GDParser::Node::TYPE_DICTIONARY) { - - r_type.type=Variant::DICTIONARY; + } else if (p_node->type == GDParser::Node::TYPE_DICTIONARY) { + r_type.type = Variant::DICTIONARY; //what the heck, fill it anyway const GDParser::DictionaryNode *an = static_cast<const GDParser::DictionaryNode *>(p_node); Dictionary d; - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { GDCompletionIdentifier k; - if (_guess_expression_type(context,an->elements[i].key,p_line,k) && k.value.get_type()!=Variant::NIL) { + if (_guess_expression_type(context, an->elements[i].key, p_line, k) && k.value.get_type() != Variant::NIL) { GDCompletionIdentifier v; - if (_guess_expression_type(context,an->elements[i].value,p_line,v)) { - d[k.value]=v.value; + if (_guess_expression_type(context, an->elements[i].value, p_line, v)) { + d[k.value] = v.value; } - } } - r_type.value=d; + r_type.value = d; return true; - } else if (p_node->type==GDParser::Node::TYPE_ARRAY) { + } else if (p_node->type == GDParser::Node::TYPE_ARRAY) { - r_type.type=Variant::ARRAY; + r_type.type = Variant::ARRAY; //what the heck, fill it anyway const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_node); Array arr; arr.resize(an->elements.size()); - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { GDCompletionIdentifier ci; - if (_guess_expression_type(context,an->elements[i],p_line,ci)) { - arr[i]=ci.value; + if (_guess_expression_type(context, an->elements[i], p_line, ci)) { + arr[i] = ci.value; } } - r_type.value=arr; + r_type.value = arr; return true; - } else if (p_node->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { + } else if (p_node->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { - MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode*>(p_node)->function); - r_type=_get_type_from_pinfo(mi.return_val); + MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode *>(p_node)->function); + r_type = _get_type_from_pinfo(mi.return_val); return true; - } else if (p_node->type==GDParser::Node::TYPE_IDENTIFIER) { + } else if (p_node->type == GDParser::Node::TYPE_IDENTIFIER) { - return _guess_identifier_type(context,p_line-1,static_cast<const GDParser::IdentifierNode *>(p_node)->name,r_type); - } else if (p_node->type==GDParser::Node::TYPE_SELF) { + return _guess_identifier_type(context, p_line - 1, static_cast<const GDParser::IdentifierNode *>(p_node)->name, r_type); + } else if (p_node->type == GDParser::Node::TYPE_SELF) { //eeh... - r_type=_get_native_class(context); - return r_type.type!=Variant::NIL; - - } else if (p_node->type==GDParser::Node::TYPE_OPERATOR) { + r_type = _get_native_class(context); + return r_type.type != Variant::NIL; + } else if (p_node->type == GDParser::Node::TYPE_OPERATOR) { const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node); - if (op->op==GDParser::OperatorNode::OP_CALL) { - if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) { + if (op->op == GDParser::OperatorNode::OP_CALL) { + if (op->arguments[0]->type == GDParser::Node::TYPE_TYPE) { const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]); - r_type.type=tn->vtype; + r_type.type = tn->vtype; return true; - } else if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { - + } else if (op->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { const GDParser::BuiltInFunctionNode *bin = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]); - return _guess_expression_type(context,bin,p_line,r_type); - - } else if (op->arguments.size()>1 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) { + return _guess_expression_type(context, bin, p_line, r_type); + } else if (op->arguments.size() > 1 && op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) { GDCompletionIdentifier base; - if (!_guess_expression_type(context,op->arguments[0],p_line,base)) + if (!_guess_expression_type(context, op->arguments[0], p_line, base)) return false; StringName id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name; - if (base.type==Variant::OBJECT) { + if (base.type == Variant::OBJECT) { - if (id.operator String()=="new" && base.value.get_type()==Variant::OBJECT) { + if (id.operator String() == "new" && base.value.get_type() == Variant::OBJECT) { Object *obj = base.value; if (obj && obj->cast_to<GDNativeClass>()) { GDNativeClass *gdnc = obj->cast_to<GDNativeClass>(); - r_type.type=Variant::OBJECT; - r_type.value=Variant(); - r_type.obj_type=gdnc->get_name(); + r_type.type = Variant::OBJECT; + r_type.value = Variant(); + r_type.obj_type = gdnc->get_name(); return true; } } - if (ObjectTypeDB::has_method(base.obj_type,id)) { + if (ObjectTypeDB::has_method(base.obj_type, id)) { #ifdef TOOLS_ENABLED - MethodBind *mb = ObjectTypeDB::get_method(base.obj_type,id); + MethodBind *mb = ObjectTypeDB::get_method(base.obj_type, id); PropertyInfo pi = mb->get_argument_info(-1); //try calling the function if constant and all args are constant, should not crash.. Object *baseptr = base.value; + if (mb->is_const() && pi.type == Variant::OBJECT) { - if (mb->is_const() && pi.type==Variant::OBJECT) { - - bool all_valid=true; + bool all_valid = true; Vector<Variant> args; - for(int i=2;i<op->arguments.size();i++) { + for (int i = 2; i < op->arguments.size(); i++) { GDCompletionIdentifier arg; - if (_guess_expression_type(context,op->arguments[i],p_line,arg)) { - if (arg.value.get_type()!=Variant::NIL && arg.value.get_type()!=Variant::OBJECT) { // calling with object seems dangerous, i don' t know + if (_guess_expression_type(context, op->arguments[i], p_line, arg)) { + if (arg.value.get_type() != Variant::NIL && arg.value.get_type() != Variant::OBJECT) { // calling with object seems dangerous, i don' t know args.push_back(arg.value); } else { - all_valid=false; + all_valid = false; break; } } else { - all_valid=false; + all_valid = false; } } - if (all_valid && String(id)=="get_node" && ObjectTypeDB::is_type(base.obj_type,"Node") && args.size()) { + if (all_valid && String(id) == "get_node" && ObjectTypeDB::is_type(base.obj_type, "Node") && args.size()) { - String arg1=args[0]; + String arg1 = args[0]; if (arg1.begins_with("/root/")) { - String which = arg1.get_slice("/",2); - if (which!="") { + String which = arg1.get_slice("/", 2); + if (which != "") { List<PropertyInfo> props; Globals::get_singleton()->get_property_list(&props); //print_line("find singleton"); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; //print_line("found "+s); - String name = s.get_slice("/",1); + String name = s.get_slice("/", 1); //print_line("name: "+name+", which: "+which); - if (name==which) { + if (name == which) { String script = Globals::get_singleton()->get(s); if (!script.begins_with("res://")) { - script="res://"+script; + script = "res://" + script; } if (!script.ends_with(".gd")) { //not a script, try find the script anyway, //may have some success - script=script.basename()+".gd"; + script = script.basename() + ".gd"; } if (FileAccess::exists(script)) { //print_line("is a script"); - Ref<Script> scr; if (ScriptCodeCompletionCache::get_sigleton()) scr = ScriptCodeCompletionCache::get_sigleton()->get_cached_resource(script); else scr = ResourceLoader::load(script); - - r_type.obj_type="Node"; - r_type.type=Variant::OBJECT; - r_type.script=scr; - r_type.value=Variant(); + r_type.obj_type = "Node"; + r_type.type = Variant::OBJECT; + r_type.script = scr; + r_type.value = Variant(); return true; - } } } @@ -692,40 +647,34 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser:: } } - - if (baseptr) { if (all_valid) { - Vector<const Variant*> argptr; - for(int i=0;i<args.size();i++) { + Vector<const Variant *> argptr; + for (int i = 0; i < args.size(); i++) { argptr.push_back(&args[i]); } Variant::CallError ce; - Variant ret=mb->call(baseptr,argptr.ptr(),argptr.size(),ce); + Variant ret = mb->call(baseptr, argptr.ptr(), argptr.size(), ce); + if (ce.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) { - if (ce.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) { + if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != NULL) { - if (ret.get_type()!=Variant::OBJECT || ret.operator Object*()!=NULL) { - - r_type=_get_type_from_variant(ret); + r_type = _get_type_from_variant(ret); return true; } } - } } } - r_type.type=pi.type; - if (pi.hint==PROPERTY_HINT_RESOURCE_TYPE) { - r_type.obj_type=pi.hint_string; + r_type.type = pi.type; + if (pi.hint == PROPERTY_HINT_RESOURCE_TYPE) { + r_type.obj_type = pi.hint_string; } - - return true; #else return false; @@ -736,115 +685,108 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser:: } else { //method for some variant.. Variant::CallError ce; - Variant v = Variant::construct(base.type,NULL,0,ce); + Variant v = Variant::construct(base.type, NULL, 0, ce); List<MethodInfo> mi; v.get_method_list(&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { - - if (!E->get().name.begins_with("_") && E->get().name==id.operator String()) { + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { + if (!E->get().name.begins_with("_") && E->get().name == id.operator String()) { MethodInfo mi = E->get(); - r_type.type=mi.return_val.type; - if (mi.return_val.hint==PROPERTY_HINT_RESOURCE_TYPE) { - r_type.obj_type=mi.return_val.hint_string; + r_type.type = mi.return_val.type; + if (mi.return_val.hint == PROPERTY_HINT_RESOURCE_TYPE) { + r_type.obj_type = mi.return_val.hint_string; } return true; } } - } - - } - } else if (op->op==GDParser::OperatorNode::OP_INDEX || op->op==GDParser::OperatorNode::OP_INDEX_NAMED) { + } else if (op->op == GDParser::OperatorNode::OP_INDEX || op->op == GDParser::OperatorNode::OP_INDEX_NAMED) { GDCompletionIdentifier p1; GDCompletionIdentifier p2; + if (op->op == GDParser::OperatorNode::OP_INDEX_NAMED) { - - if (op->op==GDParser::OperatorNode::OP_INDEX_NAMED) { - - if (op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) { - String id = static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name; - p2.type=Variant::STRING; - p2.value=id; + if (op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) { + String id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name; + p2.type = Variant::STRING; + p2.value = id; } } else { if (op->arguments[1]) { - if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) { + if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) { return false; } } } - if (op->arguments[0]->type==GDParser::Node::TYPE_ARRAY) { + if (op->arguments[0]->type == GDParser::Node::TYPE_ARRAY) { const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(op->arguments[0]); if (p2.value.is_num()) { int index = p2.value; - if (index<0 || index>=an->elements.size()) + if (index < 0 || index >= an->elements.size()) return false; - return _guess_expression_type(context,an->elements[index],p_line,r_type); + return _guess_expression_type(context, an->elements[index], p_line, r_type); } - } else if (op->arguments[0]->type==GDParser::Node::TYPE_DICTIONARY) { + } else if (op->arguments[0]->type == GDParser::Node::TYPE_DICTIONARY) { const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(op->arguments[0]); - if (p2.value.get_type()==Variant::NIL) + if (p2.value.get_type() == Variant::NIL) return false; - for(int i=0;i<dn->elements.size();i++) { + for (int i = 0; i < dn->elements.size(); i++) { GDCompletionIdentifier k; - if (!_guess_expression_type(context,dn->elements[i].key,p_line,k)) { + if (!_guess_expression_type(context, dn->elements[i].key, p_line, k)) { return false; } - if (k.value.get_type()==Variant::NIL) + if (k.value.get_type() == Variant::NIL) return false; - if (k.value==p2.value) { + if (k.value == p2.value) { - return _guess_expression_type(context,dn->elements[i].value,p_line,r_type); + return _guess_expression_type(context, dn->elements[i].value, p_line, r_type); } } } else { if (op->arguments[0]) { - if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) { + if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) { return false; } - } - if (p1.value.get_type()==Variant::OBJECT) { + if (p1.value.get_type() == Variant::OBJECT) { //?? - } else if (p1.value.get_type()!=Variant::NIL) { + } else if (p1.value.get_type() != Variant::NIL) { bool valid; - Variant ret = p1.value.get(p2.value,&valid); + Variant ret = p1.value.get(p2.value, &valid); if (valid) { - r_type=_get_type_from_variant(ret); + r_type = _get_type_from_variant(ret); return true; } } else { - if (p1.type!=Variant::NIL) { + if (p1.type != Variant::NIL) { Variant::CallError ce; - Variant base = Variant::construct(p1.type,NULL,0,ce); + Variant base = Variant::construct(p1.type, NULL, 0, ce); bool valid; - Variant ret = base.get(p2.value,&valid); + Variant ret = base.get(p2.value, &valid); if (valid) { - r_type=_get_type_from_variant(ret); + r_type = _get_type_from_variant(ret); return true; } } @@ -853,117 +795,105 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser:: } else { - Variant::Operator vop = Variant::OP_MAX; - switch(op->op) { - case GDParser::OperatorNode::OP_ADD: vop=Variant::OP_ADD; break; - case GDParser::OperatorNode::OP_SUB: vop=Variant::OP_SUBSTRACT; break; - case GDParser::OperatorNode::OP_MUL: vop=Variant::OP_MULTIPLY; break; - case GDParser::OperatorNode::OP_DIV: vop=Variant::OP_DIVIDE; break; - case GDParser::OperatorNode::OP_MOD: vop=Variant::OP_MODULE; break; - case GDParser::OperatorNode::OP_SHIFT_LEFT: vop=Variant::OP_SHIFT_LEFT; break; - case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop=Variant::OP_SHIFT_RIGHT; break; - case GDParser::OperatorNode::OP_BIT_AND: vop=Variant::OP_BIT_AND; break; - case GDParser::OperatorNode::OP_BIT_OR: vop=Variant::OP_BIT_OR; break; - case GDParser::OperatorNode::OP_BIT_XOR: vop=Variant::OP_BIT_XOR; break; - default:{} - + switch (op->op) { + case GDParser::OperatorNode::OP_ADD: vop = Variant::OP_ADD; break; + case GDParser::OperatorNode::OP_SUB: vop = Variant::OP_SUBSTRACT; break; + case GDParser::OperatorNode::OP_MUL: vop = Variant::OP_MULTIPLY; break; + case GDParser::OperatorNode::OP_DIV: vop = Variant::OP_DIVIDE; break; + case GDParser::OperatorNode::OP_MOD: vop = Variant::OP_MODULE; break; + case GDParser::OperatorNode::OP_SHIFT_LEFT: vop = Variant::OP_SHIFT_LEFT; break; + case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop = Variant::OP_SHIFT_RIGHT; break; + case GDParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break; + case GDParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break; + case GDParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break; + default: {} } - - - if (vop==Variant::OP_MAX) + if (vop == Variant::OP_MAX) return false; - - GDCompletionIdentifier p1; GDCompletionIdentifier p2; if (op->arguments[0]) { - if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) { + if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) { return false; } - } - if (op->arguments.size()>1) { - if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) { + if (op->arguments.size() > 1) { + if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) { return false; } } Variant::CallError ce; - bool v1_use_value = p1.value.get_type()!=Variant::NIL && p1.value.get_type()!=Variant::OBJECT; - Variant v1 = (v1_use_value)?p1.value:Variant::construct(p1.type,NULL,0,ce); - bool v2_use_value = p2.value.get_type()!=Variant::NIL && p2.value.get_type()!=Variant::OBJECT; - Variant v2 = (v2_use_value)?p2.value:Variant::construct(p2.type,NULL,0,ce); + bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT; + Variant v1 = (v1_use_value) ? p1.value : Variant::construct(p1.type, NULL, 0, ce); + bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT; + Variant v2 = (v2_use_value) ? p2.value : Variant::construct(p2.type, NULL, 0, ce); // avoid potential invalid ops - if ((vop==Variant::OP_DIVIDE || vop==Variant::OP_MODULE) && v2.get_type()==Variant::INT) { - v2=1; - v2_use_value=false; + if ((vop == Variant::OP_DIVIDE || vop == Variant::OP_MODULE) && v2.get_type() == Variant::INT) { + v2 = 1; + v2_use_value = false; } - if (vop==Variant::OP_DIVIDE && v2.get_type()==Variant::REAL) { - v2=1.0; - v2_use_value=false; + if (vop == Variant::OP_DIVIDE && v2.get_type() == Variant::REAL) { + v2 = 1.0; + v2_use_value = false; } Variant r; bool valid; - Variant::evaluate(vop,v1,v2,r,valid); + Variant::evaluate(vop, v1, v2, r, valid); if (!valid) return false; - r_type.type=r.get_type(); + r_type.type = r.get_type(); if (v1_use_value && v2_use_value) - r_type.value=r; + r_type.value = r; return true; - } - } return false; } -static bool _guess_identifier_type_in_block(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type) { - +static bool _guess_identifier_type_in_block(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type) { + const GDParser::Node *last_assign = NULL; + int last_assign_line = -1; - const GDParser::Node *last_assign=NULL; - int last_assign_line=-1; + for (int i = 0; i < context.block->statements.size(); i++) { - for (int i=0;i<context.block->statements.size();i++) { - - if (context.block->statements[i]->line>p_line) + if (context.block->statements[i]->line > p_line) continue; + if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) { - if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) { - - const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); - if (lv->assign && lv->name==p_identifier) { + if (lv->assign && lv->name == p_identifier) { - last_assign=lv->assign; - last_assign_line=context.block->statements[i]->line; + last_assign = lv->assign; + last_assign_line = context.block->statements[i]->line; } } - if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_OPERATOR) { + if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_OPERATOR) { const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(context.block->statements[i]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { - if (op->arguments.size() && op->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) { + if (op->arguments.size() && op->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) { const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[0]); - if (id->name==p_identifier) { + if (id->name == p_identifier) { - last_assign=op->arguments[1]; - last_assign_line=context.block->statements[i]->line; + last_assign = op->arguments[1]; + last_assign_line = context.block->statements[i]->line; } } } @@ -973,20 +903,18 @@ static bool _guess_identifier_type_in_block(GDCompletionContext& context,int p_l //use the last assignment, (then backwards?) if (last_assign) { - return _guess_expression_type(context,last_assign,last_assign_line,r_type); + return _guess_expression_type(context, last_assign, last_assign_line, r_type); } - return false; } +static bool _guess_identifier_from_assignment_in_function(GDCompletionContext &context, int p_src_line, const StringName &p_identifier, const StringName &p_function, GDCompletionIdentifier &r_type) { -static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& context, int p_src_line, const StringName& p_identifier, const StringName& p_function,GDCompletionIdentifier &r_type) { - - const GDParser::FunctionNode* func=NULL; - for(int i=0;i<context._class->functions.size();i++) { - if (context._class->functions[i]->name==p_function) { - func=context._class->functions[i]; + const GDParser::FunctionNode *func = NULL; + for (int i = 0; i < context._class->functions.size(); i++) { + if (context._class->functions[i]->name == p_function) { + func = context._class->functions[i]; break; } } @@ -994,23 +922,23 @@ static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& c if (!func) return false; - for(int i=0;i<func->body->statements.size();i++) { + for (int i = 0; i < func->body->statements.size(); i++) { if (func->body->statements[i]->line == p_src_line) { break; } - if (func->body->statements[i]->type==GDParser::BlockNode::TYPE_OPERATOR) { + if (func->body->statements[i]->type == GDParser::BlockNode::TYPE_OPERATOR) { const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(func->body->statements[i]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { - if (op->arguments.size() && op->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) { + if (op->arguments.size() && op->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) { const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[0]); - if (id->name==p_identifier) { + if (id->name == p_identifier) { - return _guess_expression_type(context,op->arguments[1],func->body->statements[i]->line,r_type); + return _guess_expression_type(context, op->arguments[1], func->body->statements[i]->line, r_type); } } } @@ -1020,66 +948,62 @@ static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& c return false; } -static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type) { +static bool _guess_identifier_type(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type) { //go to block first + const GDParser::BlockNode *block = context.block; - const GDParser::BlockNode *block=context.block; - - while(block) { + while (block) { GDCompletionContext c = context; - c.block=block; + c.block = block; - if (_guess_identifier_type_in_block(c,p_line,p_identifier,r_type)) { + if (_guess_identifier_type_in_block(c, p_line, p_identifier, r_type)) { return true; } - block=block->parent_block; + block = block->parent_block; } //guess from argument if virtual - if (context.function && context.function->name!=StringName()) { + if (context.function && context.function->name != StringName()) { int argindex = -1; - for(int i=0;i<context.function->arguments.size();i++) { + for (int i = 0; i < context.function->arguments.size(); i++) { - if (context.function->arguments[i]==p_identifier) { - argindex=i; + if (context.function->arguments[i] == p_identifier) { + argindex = i; break; } - } - if (argindex!=-1) { - GDCompletionIdentifier id =_get_native_class(context); - if (id.type==Variant::OBJECT && id.obj_type!=StringName()) { + if (argindex != -1) { + GDCompletionIdentifier id = _get_native_class(context); + if (id.type == Variant::OBJECT && id.obj_type != StringName()) { //this kinda sucks but meh List<MethodInfo> vmethods; - ObjectTypeDB::get_virtual_methods(id.obj_type,&vmethods); - for (List<MethodInfo>::Element *E=vmethods.front();E;E=E->next()) { + ObjectTypeDB::get_virtual_methods(id.obj_type, &vmethods); + for (List<MethodInfo>::Element *E = vmethods.front(); E; E = E->next()) { + if (E->get().name == context.function->name && argindex < E->get().arguments.size()) { - if (E->get().name==context.function->name && argindex<E->get().arguments.size()) { - - PropertyInfo arg=E->get().arguments[argindex]; + PropertyInfo arg = E->get().arguments[argindex]; int scp = arg.name.find(":"); - if (scp!=-1) { - + if (scp != -1) { - r_type.type=Variant::OBJECT; - r_type.obj_type=arg.name.substr(scp+1,arg.name.length()); + r_type.type = Variant::OBJECT; + r_type.obj_type = arg.name.substr(scp + 1, arg.name.length()); return true; } else { - r_type.type=arg.type; - if (arg.hint==PROPERTY_HINT_RESOURCE_TYPE) - r_type.obj_type=arg.hint_string; + r_type.type = arg.type; + if (arg.hint == PROPERTY_HINT_RESOURCE_TYPE) + r_type.obj_type = arg.hint_string; return true; } } @@ -1090,40 +1014,40 @@ static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const //guess type in constant - for(int i=0;i<context._class->constant_expressions.size();i++) { + for (int i = 0; i < context._class->constant_expressions.size(); i++) { - if (context._class->constant_expressions[i].identifier==p_identifier) { + if (context._class->constant_expressions[i].identifier == p_identifier) { - ERR_FAIL_COND_V( context._class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT, false ); - r_type=_get_type_from_variant(static_cast<const GDParser::ConstantNode*>(context._class->constant_expressions[i].expression)->value ); + ERR_FAIL_COND_V(context._class->constant_expressions[i].expression->type != GDParser::Node::TYPE_CONSTANT, false); + r_type = _get_type_from_variant(static_cast<const GDParser::ConstantNode *>(context._class->constant_expressions[i].expression)->value); return true; } } if (!(context.function && context.function->_static)) { - for(int i=0;i<context._class->variables.size();i++) { + for (int i = 0; i < context._class->variables.size(); i++) { - if (context._class->variables[i].identifier==p_identifier) { + if (context._class->variables[i].identifier == p_identifier) { - if (context._class->variables[i]._export.type!=Variant::NIL) { + if (context._class->variables[i]._export.type != Variant::NIL) { - r_type=_get_type_from_pinfo(context._class->variables[i]._export); + r_type = _get_type_from_pinfo(context._class->variables[i]._export); return true; } else if (context._class->variables[i].expression) { - bool rtype = _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type); - if (rtype && r_type.type!=Variant::NIL) + bool rtype = _guess_expression_type(context, context._class->variables[i].expression, context._class->variables[i].line, r_type); + if (rtype && r_type.type != Variant::NIL) return true; //return _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type); } //try to guess from assignment in construtor or _ready - if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_ready",r_type)) + if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_ready", r_type)) return true; - if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_enter_tree",r_type)) + if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_enter_tree", r_type)) return true; - if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_init",r_type)) + if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_init", r_type)) return true; return false; @@ -1135,115 +1059,107 @@ static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const List<PropertyInfo> props; Globals::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; - String name = s.get_slice("/",1); - if (name==String(p_identifier)) { + String name = s.get_slice("/", 1); + if (name == String(p_identifier)) { String path = Globals::get_singleton()->get(s); if (path.begins_with("*")) { - String script =path.substr(1,path.length()); + String script = path.substr(1, path.length()); if (!script.ends_with(".gd")) { //not a script, try find the script anyway, //may have some success - script=script.basename()+".gd"; + script = script.basename() + ".gd"; } if (FileAccess::exists(script)) { //print_line("is a script"); - Ref<Script> scr; if (ScriptCodeCompletionCache::get_sigleton()) scr = ScriptCodeCompletionCache::get_sigleton()->get_cached_resource(script); else scr = ResourceLoader::load(script); - - r_type.obj_type="Node"; - r_type.type=Variant::OBJECT; - r_type.script=scr; - r_type.value=Variant(); + r_type.obj_type = "Node"; + r_type.type = Variant::OBJECT; + r_type.script = scr; + r_type.value = Variant(); return true; - } } } - } //global - for(Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) { - if (E->key()==p_identifier) { + for (Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { + if (E->key() == p_identifier) { - r_type=_get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()]); + r_type = _get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()]); return true; } - } return false; } - -static void _find_identifiers_in_block(GDCompletionContext& context,int p_line,bool p_only_functions,Set<String>& result) { +static void _find_identifiers_in_block(GDCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) { if (p_only_functions) return; - for (int i=0;i<context.block->statements.size();i++) { + for (int i = 0; i < context.block->statements.size(); i++) { - if (context.block->statements[i]->line>p_line) + if (context.block->statements[i]->line > p_line) continue; + if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) { - if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) { - - const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); result.insert(lv->name.operator String()); } } } -static void _find_identifiers_in_class(GDCompletionContext& context,bool p_static,bool p_only_functions,Set<String>& result) { +static void _find_identifiers_in_class(GDCompletionContext &context, bool p_static, bool p_only_functions, Set<String> &result) { if (!p_static && !p_only_functions) { - for(int i=0;i<context._class->variables.size();i++) { + for (int i = 0; i < context._class->variables.size(); i++) { result.insert(context._class->variables[i].identifier); } } if (!p_only_functions) { - for(int i=0;i<context._class->constant_expressions.size();i++) { + for (int i = 0; i < context._class->constant_expressions.size(); i++) { result.insert(context._class->constant_expressions[i].identifier); } - for(int i=0;i<context._class->subclasses.size();i++) { + for (int i = 0; i < context._class->subclasses.size(); i++) { result.insert(context._class->subclasses[i]->name); } - } - for(int i=0;i<context._class->static_functions.size();i++) { + for (int i = 0; i < context._class->static_functions.size(); i++) { if (context._class->static_functions[i]->arguments.size()) - result.insert(context._class->static_functions[i]->name.operator String()+"("); + result.insert(context._class->static_functions[i]->name.operator String() + "("); else - result.insert(context._class->static_functions[i]->name.operator String()+"()"); + result.insert(context._class->static_functions[i]->name.operator String() + "()"); } if (!p_static) { - for(int i=0;i<context._class->functions.size();i++) { + for (int i = 0; i < context._class->functions.size(); i++) { if (context._class->functions[i]->arguments.size()) - result.insert(context._class->functions[i]->name.operator String()+"("); + result.insert(context._class->functions[i]->name.operator String() + "("); else - result.insert(context._class->functions[i]->name.operator String()+"()"); + result.insert(context._class->functions[i]->name.operator String() + "()"); } } @@ -1251,118 +1167,117 @@ static void _find_identifiers_in_class(GDCompletionContext& context,bool p_stati Ref<Reference> base = _get_parent_class(context); - while(true) { + while (true) { Ref<GDScript> script = base; Ref<GDNativeClass> nc = base; if (script.is_valid()) { if (!p_static && !p_only_functions) { - for (const Set<StringName>::Element *E=script->get_members().front();E;E=E->next()) { + for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) { result.insert(E->get().operator String()); } } if (!p_only_functions) { - for (const Map<StringName,Variant>::Element *E=script->get_constants().front();E;E=E->next()) { + for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) { result.insert(E->key().operator String()); } } - for (const Map<StringName,GDFunction*>::Element *E=script->get_member_functions().front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { if (!p_static || E->get()->is_static()) { if (E->get()->get_argument_count()) - result.insert(E->key().operator String()+"("); + result.insert(E->key().operator String() + "("); else - result.insert(E->key().operator String()+"()"); + result.insert(E->key().operator String() + "()"); } } - if (!p_only_functions) { - for (const Map<StringName,Ref<GDScript> >::Element *E=script->get_subclasses().front();E;E=E->next()) { + if (!p_only_functions) { + for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) { result.insert(E->key().operator String()); } } - base=script->get_base(); + base = script->get_base(); if (base.is_null()) - base=script->get_native(); + base = script->get_native(); } else if (nc.is_valid()) { if (!p_only_functions) { StringName type = nc->get_name(); List<String> constants; - ObjectTypeDB::get_integer_constant_list(type,&constants); - for(List<String>::Element *E=constants.front();E;E=E->next()) { + ObjectTypeDB::get_integer_constant_list(type, &constants); + for (List<String>::Element *E = constants.front(); E; E = E->next()) { result.insert(E->get()); } List<MethodInfo> methods; - ObjectTypeDB::get_method_list(type,&methods); - for(List<MethodInfo>::Element *E=methods.front();E;E=E->next()) { + ObjectTypeDB::get_method_list(type, &methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { if (E->get().name.begins_with("_")) continue; if (E->get().arguments.size()) - result.insert(E->get().name+"("); + result.insert(E->get().name + "("); else - result.insert(E->get().name+"()"); + result.insert(E->get().name + "()"); } } break; } else break; - } - } -static void _find_identifiers(GDCompletionContext& context,int p_line,bool p_only_functions,Set<String>& result) { +static void _find_identifiers(GDCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) { - const GDParser::BlockNode *block=context.block; + const GDParser::BlockNode *block = context.block; if (context.function) { - const GDParser::FunctionNode* f = context.function; + const GDParser::FunctionNode *f = context.function; - for (int i=0;i<f->arguments.size();i++) { + for (int i = 0; i < f->arguments.size(); i++) { result.insert(f->arguments[i].operator String()); } } - while(block) { + while (block) { GDCompletionContext c = context; - c.block=block; + c.block = block; - _find_identifiers_in_block(c,p_line,p_only_functions,result); - block=block->parent_block; + _find_identifiers_in_block(c, p_line, p_only_functions, result); + block = block->parent_block; } - const GDParser::ClassNode *clss=context._class; + const GDParser::ClassNode *clss = context._class; - bool _static=context.function && context.function->_static; + bool _static = context.function && context.function->_static; - while(clss) { + while (clss) { GDCompletionContext c = context; - c._class=clss; - c.block=NULL; - c.function=NULL; - _find_identifiers_in_class(c,_static,p_only_functions,result); - clss=clss->owner; + c._class = clss; + c.block = NULL; + c.function = NULL; + _find_identifiers_in_class(c, _static, p_only_functions, result); + clss = clss->owner; } - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { result.insert(GDFunctions::get_func_name(GDFunctions::Function(i))); } - static const char*_type_names[Variant::VARIANT_MAX]={ - "null","bool","int","float","String","Vector2","Rect2","Vector3","Matrix32","Plane","Quat","AABB","Matrix3","Transform", - "Color","Image","NodePath","RID","Object","InputEvent","Dictionary","Array","RawArray","IntArray","FloatArray","StringArray", - "Vector2Array","Vector3Array","ColorArray"}; + static const char *_type_names[Variant::VARIANT_MAX] = { + "null", "bool", "int", "float", "String", "Vector2", "Rect2", "Vector3", "Matrix32", "Plane", "Quat", "AABB", "Matrix3", "Transform", + "Color", "Image", "NodePath", "RID", "Object", "InputEvent", "Dictionary", "Array", "RawArray", "IntArray", "FloatArray", "StringArray", + "Vector2Array", "Vector3Array", "ColorArray" + }; - for(int i=0;i<Variant::VARIANT_MAX;i++) { + for (int i = 0; i < Variant::VARIANT_MAX; i++) { result.insert(_type_names[i]); } @@ -1370,37 +1285,34 @@ static void _find_identifiers(GDCompletionContext& context,int p_line,bool p_onl List<PropertyInfo> props; Globals::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; - String name = s.get_slice("/",1); + String name = s.get_slice("/", 1); String path = Globals::get_singleton()->get(s); if (path.begins_with("*")) { result.insert(name); } - } - - for(const Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) { + for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { result.insert(E->key().operator String()); } } - -static String _get_visual_datatype(const PropertyInfo& p_info,bool p_isarg=true) { +static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = true) { String n = p_info.name; int idx = n.find(":"); - if (idx!=-1) { - return n.substr(idx+1,n.length()); + if (idx != -1) { + return n.substr(idx + 1, n.length()); } - if (p_info.type==Variant::OBJECT && p_info.hint==PROPERTY_HINT_RESOURCE_TYPE) + if (p_info.type == Variant::OBJECT && p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) return p_info.hint_string; - if (p_info.type==Variant::NIL) { + if (p_info.type == Variant::NIL) { if (p_isarg) return "var"; else @@ -1410,74 +1322,68 @@ static String _get_visual_datatype(const PropertyInfo& p_info,bool p_isarg=true) return Variant::get_type_name(p_info.type); } -static void _make_function_hint(const GDParser::FunctionNode* p_func,int p_argidx,String& arghint) { +static void _make_function_hint(const GDParser::FunctionNode *p_func, int p_argidx, String &arghint) { - arghint="func "+p_func->name+"("; - for (int i=0;i<p_func->arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint = "func " + p_func->name + "("; + for (int i = 0; i < p_func->arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; + arghint += " "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=p_func->arguments[i].operator String(); - int deffrom = p_func->arguments.size()-p_func->default_values.size(); + arghint += p_func->arguments[i].operator String(); + int deffrom = p_func->arguments.size() - p_func->default_values.size(); - if (i>=deffrom) { - int defidx = deffrom-i; + if (i >= deffrom) { + int defidx = deffrom - i; - if (defidx>=0 && defidx<p_func->default_values.size()) { + if (defidx >= 0 && defidx < p_func->default_values.size()) { - if (p_func->default_values[defidx]->type==GDParser::Node::TYPE_OPERATOR) { - - const GDParser::OperatorNode *op=static_cast<const GDParser::OperatorNode *>(p_func->default_values[defidx]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { - const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(op->arguments[1]); - arghint+="="+cn->value.get_construct_string(); + if (p_func->default_values[defidx]->type == GDParser::Node::TYPE_OPERATOR) { + const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_func->default_values[defidx]); + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(op->arguments[1]); + arghint += "=" + cn->value.get_construct_string(); } } else { - } } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - if (p_func->arguments.size()>0) - arghint+=" "; - arghint+=")"; + if (p_func->arguments.size() > 0) + arghint += " "; + arghint += ")"; } - -static void _find_type_arguments(const GDParser::Node*p_node,int p_line,const StringName& p_method,const GDCompletionIdentifier& id, int p_argidx, Set<String>& result, String& arghint) { - +static void _find_type_arguments(const GDParser::Node *p_node, int p_line, const StringName &p_method, const GDCompletionIdentifier &id, int p_argidx, Set<String> &result, String &arghint) { //print_line("find type arguments?"); - if (id.type==Variant::INPUT_EVENT && String(p_method)=="is_action" && p_argidx==0) { + if (id.type == Variant::INPUT_EVENT && String(p_method) == "is_action" && p_argidx == 0) { List<PropertyInfo> pinfo; Globals::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()); - result.insert("\""+name+"\""); + String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length()); + result.insert("\"" + name + "\""); } + } else if (id.type == Variant::OBJECT && id.obj_type != StringName()) { - } else if (id.type==Variant::OBJECT && id.obj_type!=StringName()) { - - - MethodBind *m = ObjectTypeDB::get_method(id.obj_type,p_method); + MethodBind *m = ObjectTypeDB::get_method(id.obj_type, p_method); if (!m) { //not in static method, see script @@ -1485,51 +1391,49 @@ static void _find_type_arguments(const GDParser::Node*p_node,int p_line,const St Ref<GDScript> on_script; if (id.value.get_type()) { - Object *obj=id.value; - + Object *obj = id.value; if (obj) { - GDScript *scr = obj->cast_to<GDScript>(); if (scr) { while (scr) { - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { - if (E->get()->is_static() && p_method==E->get()->get_name()) { - arghint="static func "+String(p_method)+"("; - for(int i=0;i<E->get()->get_argument_count();i++) { - if (i>0) - arghint+=", "; + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { + if (E->get()->is_static() && p_method == E->get()->get_name()) { + arghint = "static func " + String(p_method) + "("; + for (int i = 0; i < E->get()->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+="var "+E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count(); - if (i>=deffrom) { - int defidx = deffrom-i; - if (defidx>=0 && defidx<E->get()->get_default_argument_count()) { - arghint+="="+E->get()->get_default_argument(defidx).get_construct_string(); + arghint += "var " + E->get()->get_argument_name(i); + int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); + if (i >= deffrom) { + int defidx = deffrom - i; + if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { + arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - arghint+=")"; + arghint += ")"; return; //found } } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } else { - on_script=obj->get_script(); + on_script = obj->get_script(); } } } @@ -1537,7 +1441,7 @@ static void _find_type_arguments(const GDParser::Node*p_node,int p_line,const St //print_line("but it has a script?"); if (!on_script.is_valid() && id.script.is_valid()) { //print_line("yes"); - on_script=id.script; + on_script = id.script; } if (on_script.is_valid()) { @@ -1549,110 +1453,108 @@ static void _find_type_arguments(const GDParser::Node*p_node,int p_line,const St String code = scr->get_source_code(); //print_line("has source code!"); - if (code!="") { + if (code != "") { //if there is code, parse it. This way is slower but updates in real-time GDParser p; //Error parse(const String& p_code, const String& p_base_path="", bool p_just_validate=false,const String& p_self_path="",bool p_for_completion=false); - Error err = p.parse(scr->get_source_code(),scr->get_path().get_base_dir(),true,"",false); + Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false); - if (err==OK) { + if (err == OK) { //print_line("checking the functions..."); //only if ok, otherwise use what is cached on the script //GDParser::ClassNode *base = p. const GDParser::Node *root = p.get_parse_tree(); - ERR_FAIL_COND(root->type!=GDParser::Node::TYPE_CLASS); + ERR_FAIL_COND(root->type != GDParser::Node::TYPE_CLASS); - const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root); + const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root); - const GDParser::FunctionNode* func=NULL; - bool st=false; + const GDParser::FunctionNode *func = NULL; + bool st = false; - for(int i=0;i<cl->functions.size();i++) { + for (int i = 0; i < cl->functions.size(); i++) { //print_line(String(cl->functions[i]->name)+" vs "+String(p_method)); - if (cl->functions[i]->name==p_method) { - func=cl->functions[i]; + if (cl->functions[i]->name == p_method) { + func = cl->functions[i]; } } - for(int i=0;i<cl->static_functions.size();i++) { + for (int i = 0; i < cl->static_functions.size(); i++) { //print_line(String(cl->static_functions[i]->name)+" vs "+String(p_method)); - if (cl->static_functions[i]->name==p_method) { - func=cl->static_functions[i]; - st=true; + if (cl->static_functions[i]->name == p_method) { + func = cl->static_functions[i]; + st = true; } - } if (func) { - arghint="func "+String(p_method)+"("; + arghint = "func " + String(p_method) + "("; if (st) - arghint="static "+arghint; - for(int i=0;i<func->arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint = "static " + arghint; + for (int i = 0; i < func->arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+="var "+String(func->arguments[i]); - int deffrom = func->arguments.size()-func->default_values.size(); - if (i>=deffrom) { + arghint += "var " + String(func->arguments[i]); + int deffrom = func->arguments.size() - func->default_values.size(); + if (i >= deffrom) { - int defidx = deffrom-i; + int defidx = deffrom - i; - if (defidx>=0 && defidx<func->default_values.size() && func->default_values[defidx]->type==GDParser::Node::TYPE_OPERATOR) { - const GDParser::OperatorNode *op=static_cast<const GDParser::OperatorNode *>(func->default_values[defidx]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { - const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(op->arguments[1]); - arghint+="="+cn->value.get_construct_string(); + if (defidx >= 0 && defidx < func->default_values.size() && func->default_values[defidx]->type == GDParser::Node::TYPE_OPERATOR) { + const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(func->default_values[defidx]); + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(op->arguments[1]); + arghint += "=" + cn->value.get_construct_string(); } } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - arghint+=" )"; + arghint += " )"; return; } } else { //print_line("failed parsing?"); - code=""; + code = ""; } - } - if (code=="") { + if (code == "") { - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { - if (p_method==E->get()->get_name()) { - arghint="func "+String(p_method)+"("; - for(int i=0;i<E->get()->get_argument_count();i++) { - if (i>0) - arghint+=", "; + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { + if (p_method == E->get()->get_name()) { + arghint = "func " + String(p_method) + "("; + for (int i = 0; i < E->get()->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+="var "+E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count(); - if (i>=deffrom) { - int defidx = deffrom-i; - if (defidx>=0 && defidx<E->get()->get_default_argument_count()) { - arghint+="="+E->get()->get_default_argument(defidx).get_construct_string(); + arghint += "var " + E->get()->get_argument_name(i); + int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); + if (i >= deffrom) { + int defidx = deffrom - i; + if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { + arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - arghint+=")"; + arghint += ")"; return; //found } } @@ -1674,25 +1576,23 @@ static void _find_type_arguments(const GDParser::Node*p_node,int p_line,const St } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } } - } else { //regular method - if (p_method.operator String()=="connect") { - + if (p_method.operator String() == "connect") { - if (p_argidx==0) { + if (p_argidx == 0) { List<MethodInfo> sigs; - ObjectTypeDB::get_signal_list(id.obj_type,&sigs); - for (List<MethodInfo>::Element *E=sigs.front();E;E=E->next()) { - result.insert("\""+E->get().name+"\""); + ObjectTypeDB::get_signal_list(id.obj_type, &sigs); + for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) { + result.insert("\"" + E->get().name + "\""); } } /*if (p_argidx==2) { @@ -1704,173 +1604,163 @@ static void _find_type_arguments(const GDParser::Node*p_node,int p_line,const St }*/ } else { - if (p_argidx==0 && (String(p_method)=="get_node" || String(p_method)=="has_node") && ObjectTypeDB::is_type(id.obj_type,"Node")) { + if (p_argidx == 0 && (String(p_method) == "get_node" || String(p_method) == "has_node") && ObjectTypeDB::is_type(id.obj_type, "Node")) { List<PropertyInfo> props; Globals::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; - // print_line("found "+s); - String name = s.get_slice("/",1); - result.insert("\"/root/"+name+"\""); + // print_line("found "+s); + String name = s.get_slice("/", 1); + result.insert("\"/root/" + name + "\""); } } - Object *obj=id.value; + Object *obj = id.value; if (obj) { List<String> options; - obj->get_argument_options(p_method,p_argidx,&options); + obj->get_argument_options(p_method, p_argidx, &options); - for(List<String>::Element *E=options.front();E;E=E->next()) { + for (List<String>::Element *E = options.front(); E; E = E->next()) { result.insert(E->get()); } } - } - arghint = _get_visual_datatype(m->get_argument_info(-1),false)+" "+p_method.operator String()+String("("); + arghint = _get_visual_datatype(m->get_argument_info(-1), false) + " " + p_method.operator String() + String("("); - for(int i=0;i<m->get_argument_count();i++) { - if (i>0) - arghint+=", "; + for (int i = 0; i < m->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; + arghint += " "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } String n = m->get_argument_info(i).name; int dp = n.find(":"); - if (dp!=-1) - n=n.substr(0,dp); - arghint+=_get_visual_datatype(m->get_argument_info(i))+" "+n; - int deffrom = m->get_argument_count()-m->get_default_argument_count(); - + if (dp != -1) + n = n.substr(0, dp); + arghint += _get_visual_datatype(m->get_argument_info(i)) + " " + n; + int deffrom = m->get_argument_count() - m->get_default_argument_count(); - if (i>=deffrom) { - int defidx = i-deffrom; + if (i >= deffrom) { + int defidx = i - deffrom; - if (defidx>=0 && defidx<m->get_default_argument_count()) { - Variant v= m->get_default_argument(i); - arghint+="="+v.get_construct_string(); + if (defidx >= 0 && defidx < m->get_default_argument_count()) { + Variant v = m->get_default_argument(i); + arghint += "=" + v.get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (m->get_argument_count()>0) - arghint+=" "; - + if (m->get_argument_count() > 0) + arghint += " "; - arghint+=")"; + arghint += ")"; } - } } +static void _find_call_arguments(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, int p_argidx, Set<String> &result, String &arghint) { -static void _find_call_arguments(GDCompletionContext& context,const GDParser::Node* p_node, int p_line,int p_argidx, Set<String>& result, String& arghint) { - - - - if (!p_node || p_node->type!=GDParser::Node::TYPE_OPERATOR) { + if (!p_node || p_node->type != GDParser::Node::TYPE_OPERATOR) { return; } const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node); - if (op->op!=GDParser::OperatorNode::OP_CALL) { + if (op->op != GDParser::OperatorNode::OP_CALL) { return; } - if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { + if (op->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { //complete built-in function - const GDParser::BuiltInFunctionNode *fn = static_cast<const GDParser::BuiltInFunctionNode*>(op->arguments[0]); + const GDParser::BuiltInFunctionNode *fn = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]); MethodInfo mi = GDFunctions::get_info(fn->function); - arghint = _get_visual_datatype(mi.return_val,false)+" "+GDFunctions::get_func_name(fn->function)+String("("); - for(int i=0;i<mi.arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint = _get_visual_datatype(mi.return_val, false) + " " + GDFunctions::get_func_name(fn->function) + String("("); + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=_get_visual_datatype(mi.arguments[i])+" "+mi.arguments[i].name; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (mi.arguments.size()>0) - arghint+=" "; - arghint+=")"; + if (mi.arguments.size() > 0) + arghint += " "; + arghint += ")"; - } else if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) { + } else if (op->arguments[0]->type == GDParser::Node::TYPE_TYPE) { //complete constructor - const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode*>(op->arguments[0]); + const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]); List<MethodInfo> mil; - Variant::get_constructor_list(tn->vtype,&mil); + Variant::get_constructor_list(tn->vtype, &mil); - for(List<MethodInfo>::Element *E=mil.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = mil.front(); E; E = E->next()) { MethodInfo mi = E->get(); - if (mi.arguments.size()==0) + if (mi.arguments.size() == 0) continue; if (E->prev()) - arghint+="\n"; - arghint += Variant::get_type_name(tn->vtype)+" "+Variant::get_type_name(tn->vtype)+String("("); - for(int i=0;i<mi.arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint += "\n"; + arghint += Variant::get_type_name(tn->vtype) + " " + Variant::get_type_name(tn->vtype) + String("("); + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=_get_visual_datatype(mi.arguments[i])+" "+mi.arguments[i].name; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (mi.arguments.size()>0) - arghint+=" "; - arghint+=")"; + if (mi.arguments.size() > 0) + arghint += " "; + arghint += ")"; } - } else if (op->arguments.size()>=2 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) { + } else if (op->arguments.size() >= 2 && op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) { //make sure identifier exists... - const GDParser::IdentifierNode *id=static_cast<const GDParser::IdentifierNode *>(op->arguments[1]); + const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1]); - if (op->arguments[0]->type==GDParser::Node::TYPE_SELF) { + if (op->arguments[0]->type == GDParser::Node::TYPE_SELF) { //self, look up - for(int i=0;i<context._class->static_functions.size();i++) { - if (context._class->static_functions[i]->name==id->name) { - _make_function_hint(context._class->static_functions[i],p_argidx,arghint); + for (int i = 0; i < context._class->static_functions.size(); i++) { + if (context._class->static_functions[i]->name == id->name) { + _make_function_hint(context._class->static_functions[i], p_argidx, arghint); return; } } if (context.function && !context.function->_static) { - for(int i=0;i<context._class->functions.size();i++) { - if (context._class->functions[i]->name==id->name) { - _make_function_hint(context._class->functions[i],p_argidx,arghint); + for (int i = 0; i < context._class->functions.size(); i++) { + if (context._class->functions[i]->name == id->name) { + _make_function_hint(context._class->functions[i], p_argidx, arghint); return; } } @@ -1878,64 +1768,61 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No Ref<Reference> base = _get_parent_class(context); - while(true) { + while (true) { Ref<GDScript> script = base; Ref<GDNativeClass> nc = base; if (script.is_valid()) { + for (const Map<StringName, GDFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { - for (const Map<StringName,GDFunction*>::Element *E=script->get_member_functions().front();E;E=E->next()) { - - if (E->key()==id->name) { + if (E->key() == id->name) { if (context.function && context.function->_static && !E->get()->is_static()) continue; - - arghint = "func "+id->name.operator String()+String("("); - for(int i=0;i<E->get()->get_argument_count();i++) { - if (i>0) - arghint+=", "; + arghint = "func " + id->name.operator String() + String("("); + for (int i = 0; i < E->get()->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count(); - if (i>=deffrom) { - int defidx = deffrom-i; - if (defidx>=0 && defidx<E->get()->get_default_argument_count()) { - arghint+="="+E->get()->get_default_argument(defidx).get_construct_string(); + arghint += E->get()->get_argument_name(i); + int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); + if (i >= deffrom) { + int defidx = deffrom - i; + if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { + arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (E->get()->get_argument_count()>0) - arghint+=" "; - arghint+=")"; + if (E->get()->get_argument_count() > 0) + arghint += " "; + arghint += ")"; return; } } - base=script->get_base(); + base = script->get_base(); if (base.is_null()) - base=script->get_native(); + base = script->get_native(); } else if (nc.is_valid()) { if (context.function && !context.function->_static) { GDCompletionIdentifier ci; - ci.type=Variant::OBJECT; - ci.obj_type=nc->get_name(); + ci.type = Variant::OBJECT; + ci.obj_type = nc->get_name(); if (!context._class->owner) - ci.value=context.base; + ci.value = context.base; - _find_type_arguments(p_node,p_line,id->name,ci,p_argidx,result,arghint); + _find_type_arguments(p_node, p_line, id->name, ci, p_argidx, result, arghint); //guess type.. /* List<MethodInfo> methods; @@ -1950,20 +1837,17 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No break; } else break; - } } else { //indexed lookup GDCompletionIdentifier ci; - if (_guess_expression_type(context,op->arguments[0],p_line,ci)) { + if (_guess_expression_type(context, op->arguments[0], p_line, ci)) { - _find_type_arguments(p_node,p_line,id->name,ci,p_argidx,result,arghint); + _find_type_arguments(p_node, p_line, id->name, ci, p_argidx, result, arghint); return; } - } - } #if 0 bool _static=context.function->_static; @@ -2058,110 +1942,102 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No } #endif - } -Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base_path, Object*p_owner, List<String>* r_options, String &r_call_hint) { +Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { GDParser p; - Error err = p.parse(p_code,p_base_path,false,"",true); - bool isfunction=false; + Error err = p.parse(p_code, p_base_path, false, "", true); + bool isfunction = false; Set<String> options; GDCompletionContext context; - context._class=p.get_completion_class(); - context.block=p.get_completion_block(); - context.function=p.get_completion_function(); - context.base=p_owner; - context.base_path=p_base_path; + context._class = p.get_completion_class(); + context.block = p.get_completion_block(); + context.function = p.get_completion_function(); + context.base = p_owner; + context.base_path = p_base_path; - switch(p.get_completion_type()) { + switch (p.get_completion_type()) { case GDParser::COMPLETION_NONE: { } break; case GDParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: { List<StringName> constants; - Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(),&constants); - for(List<StringName>::Element *E=constants.front();E;E=E->next()) { + Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(), &constants); + for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { options.insert(E->get().operator String()); } - } break; case GDParser::COMPLETION_FUNCTION: - isfunction=true; + isfunction = true; case GDParser::COMPLETION_IDENTIFIER: { - _find_identifiers(context,p.get_completion_line(),isfunction,options); + _find_identifiers(context, p.get_completion_line(), isfunction, options); } break; case GDParser::COMPLETION_PARENT_FUNCTION: { } break; case GDParser::COMPLETION_METHOD: - isfunction=true; + isfunction = true; case GDParser::COMPLETION_INDEX: { const GDParser::Node *node = p.get_completion_node(); - if (node->type!=GDParser::Node::TYPE_OPERATOR) + if (node->type != GDParser::Node::TYPE_OPERATOR) break; - - - GDCompletionIdentifier t; - if (_guess_expression_type(context,static_cast<const GDParser::OperatorNode *>(node)->arguments[0],p.get_completion_line(),t)) { + if (_guess_expression_type(context, static_cast<const GDParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t)) { - if (t.type==Variant::OBJECT && t.obj_type=="GDNativeClass") { + if (t.type == Variant::OBJECT && t.obj_type == "GDNativeClass") { //native enum Ref<GDNativeClass> gdn = t.value; if (gdn.is_valid()) { StringName cn = gdn->get_name(); List<String> cnames; - ObjectTypeDB::get_integer_constant_list(cn,&cnames); - for (List<String>::Element *E=cnames.front();E;E=E->next()) { + ObjectTypeDB::get_integer_constant_list(cn, &cnames); + for (List<String>::Element *E = cnames.front(); E; E = E->next()) { options.insert(E->get()); } } - } else if (t.type==Variant::OBJECT && t.obj_type!=StringName()) { + } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) { Ref<GDScript> on_script; if (t.value.get_type()) { - Object *obj=t.value; - + Object *obj = t.value; if (obj) { - GDScript *scr = obj->cast_to<GDScript>(); if (scr) { while (scr) { if (!isfunction) { - for (const Map<StringName,Variant>::Element *E=scr->get_constants().front();E;E=E->next()) { + for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) { options.insert(E->key()); } } - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { if (E->get()->is_static()) options.insert(E->key()); } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } else { - on_script=obj->get_script(); + on_script = obj->get_script(); } } } - if (!on_script.is_valid() && t.script.is_valid()) { - on_script=t.script; + on_script = t.script; } if (on_script.is_valid()) { @@ -2172,119 +2048,107 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base String code = scr->get_source_code(); - if (code!="") { + if (code != "") { //if there is code, parse it. This way is slower but updates in real-time GDParser p; - Error err = p.parse(scr->get_source_code(),scr->get_path().get_base_dir(),true,"",false); + Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false); - if (err==OK) { + if (err == OK) { //only if ok, otherwise use what is cached on the script //GDParser::ClassNode *base = p. const GDParser::Node *root = p.get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,ERR_PARSE_ERROR); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, ERR_PARSE_ERROR); - const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root); + const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root); - for(int i=0;i<cl->functions.size();i++) { + for (int i = 0; i < cl->functions.size(); i++) { if (cl->functions[i]->arguments.size()) - options.insert(String(cl->functions[i]->name)+"("); + options.insert(String(cl->functions[i]->name) + "("); else - options.insert(String(cl->functions[i]->name)+"()"); + options.insert(String(cl->functions[i]->name) + "()"); } - for(int i=0;i<cl->static_functions.size();i++) { + for (int i = 0; i < cl->static_functions.size(); i++) { if (cl->static_functions[i]->arguments.size()) - options.insert(String(cl->static_functions[i]->name)+"("); + options.insert(String(cl->static_functions[i]->name) + "("); else - options.insert(String(cl->static_functions[i]->name)+"()"); - + options.insert(String(cl->static_functions[i]->name) + "()"); } if (!isfunction) { - for(int i=0;i<cl->variables.size();i++) { + for (int i = 0; i < cl->variables.size(); i++) { options.insert(String(cl->variables[i].identifier)); } - for(int i=0;i<cl->constant_expressions.size();i++) { + for (int i = 0; i < cl->constant_expressions.size(); i++) { options.insert(String(cl->constant_expressions[i].identifier)); } - } - } else { - code=""; //well, then no code + code = ""; //well, then no code } - } - if (code=="") { + if (code == "") { //use class directly, no code was found if (!isfunction) { - for (const Map<StringName,Variant>::Element *E=scr->get_constants().front();E;E=E->next()) { + for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) { options.insert(E->key()); } } - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { if (E->get()->get_argument_count()) - options.insert(String(E->key())+"()"); + options.insert(String(E->key()) + "()"); else - options.insert(String(E->key())+"("); - + options.insert(String(E->key()) + "("); } - for (const Set<StringName>::Element *E=scr->get_members().front();E;E=E->next()) { + for (const Set<StringName>::Element *E = scr->get_members().front(); E; E = E->next()) { options.insert(E->get()); } } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } } - - - - - if (!isfunction) { - ObjectTypeDB::get_integer_constant_list(t.obj_type,r_options); + ObjectTypeDB::get_integer_constant_list(t.obj_type, r_options); } List<MethodInfo> mi; - ObjectTypeDB::get_method_list(t.obj_type,&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { + ObjectTypeDB::get_method_list(t.obj_type, &mi); + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { if (E->get().name.begins_with("_")) continue; if (E->get().arguments.size()) - options.insert(E->get().name+"("); + options.insert(E->get().name + "("); else - options.insert(E->get().name+"()"); - + options.insert(E->get().name + "()"); } } else { - - if (t.type==Variant::INPUT_EVENT) { + if (t.type == Variant::INPUT_EVENT) { //this is hardcoded otherwise it's not obvious Set<String> exclude; - for(int i=0;i<InputEvent::TYPE_MAX;i++) { + for (int i = 0; i < InputEvent::TYPE_MAX; i++) { InputEvent ie; - ie.type=InputEvent::Type(i); - static const char*evnames[]={ + ie.type = InputEvent::Type(i); + static const char *evnames[] = { "# Common", "# Key", "# MouseMotion", @@ -2300,22 +2164,20 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base Variant v = ie; - if (i==0) { + if (i == 0) { List<MethodInfo> mi; v.get_method_list(&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { - r_options->push_back(E->get().name+"("); - + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { + r_options->push_back(E->get().name + "("); } - } List<PropertyInfo> pi; v.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 (i==0) + if (i == 0) exclude.insert(E->get().name); else if (exclude.has(E->get().name)) continue; @@ -2325,78 +2187,72 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base } return OK; } else { - if (t.value.get_type()==Variant::NIL) { + if (t.value.get_type() == Variant::NIL) { Variant::CallError ce; - t.value=Variant::construct(t.type,NULL,0,ce); + t.value = Variant::construct(t.type, NULL, 0, ce); } - if (!isfunction) { List<PropertyInfo> pl; t.value.get_property_list(&pl); - for (List<PropertyInfo>::Element *E=pl.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pl.front(); E; E = E->next()) { - if (E->get().name.find("/")==-1) + if (E->get().name.find("/") == -1) options.insert(E->get().name); } } List<MethodInfo> mi; t.value.get_method_list(&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { if (E->get().arguments.size()) - options.insert(E->get().name+"("); + options.insert(E->get().name + "("); else - options.insert(E->get().name+"()"); - + options.insert(E->get().name + "()"); } } } } - } break; case GDParser::COMPLETION_CALL_ARGUMENTS: { - _find_call_arguments(context,p.get_completion_node(),p.get_completion_line(),p.get_completion_argument_index(),options,r_call_hint); + _find_call_arguments(context, p.get_completion_node(), p.get_completion_line(), p.get_completion_argument_index(), options, r_call_hint); } break; case GDParser::COMPLETION_VIRTUAL_FUNC: { GDCompletionIdentifier cid = _get_native_class(context); - if (cid.obj_type!=StringName()) { + if (cid.obj_type != StringName()) { List<MethodInfo> vm; - ObjectTypeDB::get_virtual_methods(cid.obj_type,&vm); - for(List<MethodInfo>::Element *E=vm.front();E;E=E->next()) { + ObjectTypeDB::get_virtual_methods(cid.obj_type, &vm); + for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) { - MethodInfo &mi=E->get(); + MethodInfo &mi = E->get(); String m = mi.name; - if (m.find(":")!=-1) - m=m.substr(0,m.find(":")); - m+="("; + if (m.find(":") != -1) + m = m.substr(0, m.find(":")); + m += "("; if (mi.arguments.size()) { - for(int i=0;i<mi.arguments.size();i++) { - if (i>0) - m+=", "; - String n =mi.arguments[i].name; - if (n.find(":")!=-1) - n=n.substr(0,n.find(":")); - m+=n; + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) + m += ", "; + String n = mi.arguments[i].name; + if (n.find(":") != -1) + n = n.substr(0, n.find(":")); + m += n; } } - m+="):"; + m += "):"; options.insert(m); } } } break; - - } - - for(Set<String>::Element *E=options.front();E;E=E->next()) { + for (Set<String>::Element *E = options.front(); E; E = E->next()) { r_options->push_back(E->get()); } @@ -2405,25 +2261,23 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base #else -Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base_path, Object*p_owner, List<String>* r_options, String &r_call_hint) { +Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return OK; } #endif - -void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_line) const { - +void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const { Vector<String> lines = p_code.split("\n"); List<int> indent_stack; - for(int i=0;i<lines.size();i++) { + for (int i = 0; i < lines.size(); i++) { String l = lines[i]; - int tc=0; - for(int j=0;j<l.length();j++) { - if (l[j]==' ' || l[j]=='\t') { + int tc = 0; + for (int j = 0; j < l.length(); j++) { + if (l[j] == ' ' || l[j] == '\t') { tc++; } else { @@ -2431,48 +2285,45 @@ void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_ } } - - String st = l.substr(tc,l.length()).strip_edges(); - if (st=="" || st.begins_with("#")) + String st = l.substr(tc, l.length()).strip_edges(); + if (st == "" || st.begins_with("#")) continue; //ignore! - int ilevel=0; + int ilevel = 0; if (indent_stack.size()) { - ilevel=indent_stack.back()->get(); + ilevel = indent_stack.back()->get(); } - if (tc>ilevel) { + if (tc > ilevel) { indent_stack.push_back(tc); - } else if (tc<ilevel) { - while(indent_stack.size() && indent_stack.back()->get()>tc) { + } else if (tc < ilevel) { + while (indent_stack.size() && indent_stack.back()->get() > tc) { indent_stack.pop_back(); } - if (indent_stack.size() && indent_stack.back()->get()!=tc) + if (indent_stack.size() && indent_stack.back()->get() != tc) indent_stack.push_back(tc); //this is not right but gets the job done } - if (i>=p_from_line) { + if (i >= p_from_line) { - l=""; - for(int j=0;j<indent_stack.size();j++) - l+="\t"; - l+=st; + l = ""; + for (int j = 0; j < indent_stack.size(); j++) + l += "\t"; + l += st; - - } else if (i>p_to_line) { + } else if (i > p_to_line) { break; } //print_line(itos(indent_stack.size())+","+itos(tc)+": "+l); - lines[i]=l; + lines[i] = l; } - p_code=""; - for(int i=0;i<lines.size();i++) { - if (i>0) - p_code+="\n"; - p_code+=lines[i]; + p_code = ""; + for (int i = 0; i < lines.size(); i++) { + if (i > 0) + p_code += "\n"; + p_code += lines[i]; } - } diff --git a/modules/gdscript/gd_function.cpp b/modules/gdscript/gd_function.cpp index 3a615ee55..638c28c4e 100644 --- a/modules/gdscript/gd_function.cpp +++ b/modules/gdscript/gd_function.cpp @@ -1,19 +1,19 @@ #include "gd_function.h" +#include "gd_functions.h" #include "gd_script.h" #include "os/os.h" -#include "gd_functions.h" -Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self, Variant *p_stack,String& r_error) const{ +Variant *GDFunction::_get_variant(int p_address, GDInstance *p_instance, GDScript *p_script, Variant &self, Variant *p_stack, String &r_error) const { - int address = p_address&ADDR_MASK; + int address = p_address & ADDR_MASK; //sequential table (jump table generated by compiler) - switch((p_address&ADDR_TYPE_MASK)>>ADDR_BITS) { + switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) { case ADDR_TYPE_SELF: { if (!p_instance) { - r_error="Cannot access self without instance."; + r_error = "Cannot access self without instance."; return NULL; } return &self; @@ -25,7 +25,7 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript case ADDR_TYPE_MEMBER: { //member indexing is O(1) if (!p_instance) { - r_error="Cannot access member without instance."; + r_error = "Cannot access member without instance."; return NULL; } return &p_instance->members[address]; @@ -33,41 +33,38 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript case ADDR_TYPE_CLASS_CONSTANT: { //todo change to index! - GDScript *o=p_script; - ERR_FAIL_INDEX_V(address,_global_names_count,NULL); + GDScript *o = p_script; + ERR_FAIL_INDEX_V(address, _global_names_count, NULL); const StringName *sn = &_global_names_ptr[address]; - while(o) { - GDScript *s=o; - while(s) { + while (o) { + GDScript *s = o; + while (s) { - Map<StringName,Variant>::Element *E=s->constants.find(*sn); + Map<StringName, Variant>::Element *E = s->constants.find(*sn); if (E) { return &E->get(); } - s=s->_base; + s = s->_base; } - o=o->_owner; + o = o->_owner; } - ERR_EXPLAIN("GDCompiler bug.."); ERR_FAIL_V(NULL); } break; case ADDR_TYPE_LOCAL_CONSTANT: { - ERR_FAIL_INDEX_V(address,_constant_count,NULL); + ERR_FAIL_INDEX_V(address, _constant_count, NULL); return &_constants_ptr[address]; } break; case ADDR_TYPE_STACK: case ADDR_TYPE_STACK_VARIABLE: { - ERR_FAIL_INDEX_V(address,_stack_size,NULL); + ERR_FAIL_INDEX_V(address, _stack_size, NULL); return &p_stack[address]; } break; case ADDR_TYPE_GLOBAL: { - - ERR_FAIL_INDEX_V(address,GDScriptLanguage::get_singleton()->get_global_array_size(),NULL); - + ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), NULL); return &GDScriptLanguage::get_singleton()->get_global_array()[address]; } break; @@ -81,37 +78,33 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript return NULL; } - -String GDFunction::_get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const { - - +String GDFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const { String err_text; - if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { - int errorarg=p_err.argument; - err_text="Invalid type in "+p_where+". Cannot convert argument "+itos(errorarg+1)+" from "+Variant::get_type_name(argptrs[errorarg]->get_type())+" to "+Variant::get_type_name(p_err.expected)+"."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { - err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { - err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) { - err_text="Invalid call. Nonexistent "+p_where+"."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { - err_text="Attempt to call "+p_where+" on a null instance."; + if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { + int errorarg = p_err.argument; + err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + "."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { + err_text = "Invalid call. Nonexistent " + p_where + "."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { + err_text = "Attempt to call " + p_where + " on a null instance."; } else { - err_text="Bug, call error: #"+itos(p_err.error); + err_text = "Bug, call error: #" + itos(p_err.error); } return err_text; - } -static String _get_var_type(const Variant* p_type) { +static String _get_var_type(const Variant *p_type) { String basestr; - if (p_type->get_type()==Variant::OBJECT) { + if (p_type->get_type() == Variant::OBJECT) { Object *bobj = *p_type; if (!bobj) { basestr = "null instance"; @@ -119,15 +112,15 @@ static String _get_var_type(const Variant* p_type) { #ifdef DEBUG_ENABLED if (ObjectDB::instance_validate(bobj)) { if (bobj->get_script_instance()) - basestr= bobj->get_type()+" ("+bobj->get_script_instance()->get_script()->get_path().get_file()+")"; + basestr = bobj->get_type() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")"; else basestr = bobj->get_type(); } else { - basestr="previously freed instance"; + basestr = "previously freed instance"; } #else - basestr="Object"; + basestr = "Object"; #endif } @@ -136,114 +129,108 @@ static String _get_var_type(const Variant* p_type) { } return basestr; - } -Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError& r_err, CallState *p_state) { - +Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError &r_err, CallState *p_state) { if (!_code_ptr) { return Variant(); } - r_err.error=Variant::CallError::CALL_OK; + r_err.error = Variant::CallError::CALL_OK; Variant self; Variant retvalue; Variant *stack = NULL; Variant **call_args; - int defarg=0; + int defarg = 0; #ifdef DEBUG_ENABLED - //GDScriptLanguage::get_singleton()->calls++; +//GDScriptLanguage::get_singleton()->calls++; #endif - uint32_t alloca_size=0; + uint32_t alloca_size = 0; GDScript *_class; - int ip=0; - int line=_initial_line; - - + int ip = 0; + int line = _initial_line; if (p_state) { //use existing (supplied) state (yielded) - stack=(Variant*)p_state->stack.ptr(); - call_args=(Variant**)stack + sizeof(Variant)*p_state->stack_size; - line=p_state->line; - ip=p_state->ip; - alloca_size=p_state->stack.size(); - _class=p_state->_class; - p_instance=p_state->instance; - defarg=p_state->defarg; - self=p_state->self; + stack = (Variant *)p_state->stack.ptr(); + call_args = (Variant **)stack + sizeof(Variant) * p_state->stack_size; + line = p_state->line; + ip = p_state->ip; + alloca_size = p_state->stack.size(); + _class = p_state->_class; + p_instance = p_state->instance; + defarg = p_state->defarg; + self = p_state->self; //stack[p_state->result_pos]=p_state->result; //assign stack with result } else { - if (p_argcount!=_argument_count) { + if (p_argcount != _argument_count) { - if (p_argcount>_argument_count) { - - r_err.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_err.argument=_argument_count; + if (p_argcount > _argument_count) { + r_err.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_err.argument = _argument_count; return Variant(); } else if (p_argcount < _argument_count - _default_arg_count) { - r_err.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_err.argument=_argument_count - _default_arg_count; + r_err.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_err.argument = _argument_count - _default_arg_count; return Variant(); } else { - defarg=_argument_count-p_argcount; + defarg = _argument_count - p_argcount; } } - alloca_size = sizeof(Variant*)*_call_size + sizeof(Variant)*_stack_size; + alloca_size = sizeof(Variant *) * _call_size + sizeof(Variant) * _stack_size; if (alloca_size) { - uint8_t *aptr = (uint8_t*)alloca(alloca_size); + uint8_t *aptr = (uint8_t *)alloca(alloca_size); if (_stack_size) { - stack=(Variant*)aptr; - for(int i=0;i<p_argcount;i++) - memnew_placement(&stack[i],Variant(*p_args[i])); - for(int i=p_argcount;i<_stack_size;i++) - memnew_placement(&stack[i],Variant); + stack = (Variant *)aptr; + for (int i = 0; i < p_argcount; i++) + memnew_placement(&stack[i], Variant(*p_args[i])); + for (int i = p_argcount; i < _stack_size; i++) + memnew_placement(&stack[i], Variant); } else { - stack=NULL; + stack = NULL; } if (_call_size) { - call_args = (Variant**)&aptr[sizeof(Variant)*_stack_size]; + call_args = (Variant **)&aptr[sizeof(Variant) * _stack_size]; } else { - call_args=NULL; + call_args = NULL; } - } else { - stack=NULL; - call_args=NULL; + stack = NULL; + call_args = NULL; } if (p_instance) { - if (p_instance->base_ref && static_cast<Reference*>(p_instance->owner)->is_referenced()) { + if (p_instance->base_ref && static_cast<Reference *>(p_instance->owner)->is_referenced()) { - self=REF(static_cast<Reference*>(p_instance->owner)); + self = REF(static_cast<Reference *>(p_instance->owner)); } else { - self=p_instance->owner; + self = p_instance->owner; } - _class=p_instance->script.ptr(); + _class = p_instance->script.ptr(); } else { - _class=_script; + _class = _script; } } @@ -252,529 +239,518 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton()) - GDScriptLanguage::get_singleton()->enter_function(p_instance,this,stack,&ip,&line); + GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line); -#define CHECK_SPACE(m_space)\ - ERR_BREAK((ip+m_space)>_code_size) - -#define GET_VARIANT_PTR(m_v,m_code_ofs) \ - Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);\ - if (!m_v)\ - break; +#define CHECK_SPACE(m_space) \ + ERR_BREAK((ip + m_space) > _code_size) +#define GET_VARIANT_PTR(m_v, m_code_ofs) \ + Variant *m_v; \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text); \ + if (!m_v) \ + break; #else #define CHECK_SPACE(m_space) -#define GET_VARIANT_PTR(m_v,m_code_ofs) \ - Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text); +#define GET_VARIANT_PTR(m_v, m_code_ofs) \ + Variant *m_v; \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text); #endif - #ifdef DEBUG_ENABLED uint64_t function_start_time; uint64_t function_call_time; if (GDScriptLanguage::get_singleton()->profiling) { - function_start_time=OS::get_singleton()->get_ticks_usec(); - function_call_time=0; + function_start_time = OS::get_singleton()->get_ticks_usec(); + function_call_time = 0; profile.call_count++; profile.frame_call_count++; } #endif - bool exit_ok=false; - - while(ip<_code_size) { + bool exit_ok = false; + while (ip < _code_size) { - int last_opcode=_code_ptr[ip]; - switch(_code_ptr[ip]) { + int last_opcode = _code_ptr[ip]; + switch (_code_ptr[ip]) { case OPCODE_OPERATOR: { CHECK_SPACE(5); bool valid; - Variant::Operator op = (Variant::Operator)_code_ptr[ip+1]; - ERR_BREAK(op>=Variant::OP_MAX); + Variant::Operator op = (Variant::Operator)_code_ptr[ip + 1]; + ERR_BREAK(op >= Variant::OP_MAX); - GET_VARIANT_PTR(a,2); - GET_VARIANT_PTR(b,3); - GET_VARIANT_PTR(dst,4); + GET_VARIANT_PTR(a, 2); + GET_VARIANT_PTR(b, 3); + GET_VARIANT_PTR(dst, 4); #ifdef DEBUG_ENABLED Variant ret; - Variant::evaluate(op,*a,*b,ret,valid); + Variant::evaluate(op, *a, *b, ret, valid); #else - Variant::evaluate(op,*a,*b,*dst,valid); + Variant::evaluate(op, *a, *b, *dst, valid); #endif if (!valid) { #ifdef DEBUG_ENABLED - if (ret.get_type()==Variant::STRING) { + if (ret.get_type() == Variant::STRING) { //return a string when invalid with the error - err_text=ret; - err_text += " in operator '"+Variant::get_operator_name(op)+"'."; + err_text = ret; + err_text += " in operator '" + Variant::get_operator_name(op) + "'."; } else { - err_text="Invalid operands '"+Variant::get_type_name(a->get_type())+"' and '"+Variant::get_type_name(b->get_type())+"' in operator '"+Variant::get_operator_name(op)+"'."; + err_text = "Invalid operands '" + Variant::get_type_name(a->get_type()) + "' and '" + Variant::get_type_name(b->get_type()) + "' in operator '" + Variant::get_operator_name(op) + "'."; } #endif break; - } #ifdef DEBUG_ENABLED - *dst=ret; + *dst = ret; #endif - ip+=5; - - } continue; + ip += 5; + } + continue; case OPCODE_EXTENDS_TEST: { CHECK_SPACE(4); - GET_VARIANT_PTR(a,1); - GET_VARIANT_PTR(b,2); - GET_VARIANT_PTR(dst,3); + GET_VARIANT_PTR(a, 1); + GET_VARIANT_PTR(b, 2); + GET_VARIANT_PTR(dst, 3); #ifdef DEBUG_ENABLED - if (a->get_type()!=Variant::OBJECT || a->operator Object*()==NULL) { + if (a->get_type() != Variant::OBJECT || a->operator Object *() == NULL) { - err_text="Left operand of 'extends' is not an instance of anything."; + err_text = "Left operand of 'extends' is not an instance of anything."; break; - } - if (b->get_type()!=Variant::OBJECT || b->operator Object*()==NULL) { + if (b->get_type() != Variant::OBJECT || b->operator Object *() == NULL) { - err_text="Right operand of 'extends' is not a class."; + err_text = "Right operand of 'extends' is not a class."; break; - } #endif - Object *obj_A = *a; Object *obj_B = *b; - GDScript *scr_B = obj_B->cast_to<GDScript>(); - bool extends_ok=false; + bool extends_ok = false; if (scr_B) { //if B is a script, the only valid condition is that A has an instance which inherits from the script //in other situation, this shoul return false. - if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language()==GDScriptLanguage::get_singleton()) { + if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language() == GDScriptLanguage::get_singleton()) { - GDScript *cmp = static_cast<GDScript*>(obj_A->get_script_instance()->get_script().ptr()); + GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr()); //bool found=false; - while(cmp) { + while (cmp) { - if (cmp==scr_B) { + if (cmp == scr_B) { //inherits from script, all ok - extends_ok=true; + extends_ok = true; break; - } - cmp=cmp->_base; + cmp = cmp->_base; } - } - } else { - GDNativeClass *nc= obj_B->cast_to<GDNativeClass>(); + GDNativeClass *nc = obj_B->cast_to<GDNativeClass>(); if (!nc) { - err_text="Right operand of 'extends' is not a class (type: '"+obj_B->get_type()+"')."; + err_text = "Right operand of 'extends' is not a class (type: '" + obj_B->get_type() + "')."; break; } - extends_ok=ObjectTypeDB::is_type(obj_A->get_type_name(),nc->get_name()); + extends_ok = ObjectTypeDB::is_type(obj_A->get_type_name(), nc->get_name()); } - *dst=extends_ok; - ip+=4; - - } continue; + *dst = extends_ok; + ip += 4; + } + continue; case OPCODE_SET: { CHECK_SPACE(3); - GET_VARIANT_PTR(dst,1); - GET_VARIANT_PTR(index,2); - GET_VARIANT_PTR(value,3); + GET_VARIANT_PTR(dst, 1); + GET_VARIANT_PTR(index, 2); + GET_VARIANT_PTR(value, 3); bool valid; - dst->set(*index,*value,&valid); + dst->set(*index, *value, &valid); if (!valid) { String v = index->operator String(); - if (v!="") { - v="'"+v+"'"; + if (v != "") { + v = "'" + v + "'"; } else { - v="of type '"+_get_var_type(index)+"'"; + v = "of type '" + _get_var_type(index) + "'"; } - err_text="Invalid set index "+v+" (on base: '"+_get_var_type(dst)+"')."; + err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "')."; break; } - ip+=4; - } continue; + ip += 4; + } + continue; case OPCODE_GET: { CHECK_SPACE(3); - GET_VARIANT_PTR(src,1); - GET_VARIANT_PTR(index,2); - GET_VARIANT_PTR(dst,3); + GET_VARIANT_PTR(src, 1); + GET_VARIANT_PTR(index, 2); + GET_VARIANT_PTR(dst, 3); bool valid; #ifdef DEBUG_ENABLED //allow better error message in cases where src and dst are the same stack position - Variant ret = src->get(*index,&valid); + Variant ret = src->get(*index, &valid); #else - *dst = src->get(*index,&valid); + *dst = src->get(*index, &valid); #endif if (!valid) { String v = index->operator String(); - if (v!="") { - v="'"+v+"'"; + if (v != "") { + v = "'" + v + "'"; } else { - v="of type '"+_get_var_type(index)+"'"; + v = "of type '" + _get_var_type(index) + "'"; } - err_text="Invalid get index "+v+" (on base: '"+_get_var_type(src)+"')."; + err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "')."; break; } #ifdef DEBUG_ENABLED - *dst=ret; + *dst = ret; #endif - ip+=4; - } continue; + ip += 4; + } + continue; case OPCODE_SET_NAMED: { CHECK_SPACE(3); - GET_VARIANT_PTR(dst,1); - GET_VARIANT_PTR(value,3); + GET_VARIANT_PTR(dst, 1); + GET_VARIANT_PTR(value, 3); - int indexname = _code_ptr[ip+2]; + int indexname = _code_ptr[ip + 2]; - ERR_BREAK(indexname<0 || indexname>=_global_names_count); + ERR_BREAK(indexname < 0 || indexname >= _global_names_count); const StringName *index = &_global_names_ptr[indexname]; bool valid; - dst->set_named(*index,*value,&valid); + dst->set_named(*index, *value, &valid); if (!valid) { String err_type; - err_text="Invalid set index '"+String(*index)+"' (on base: '"+_get_var_type(dst)+"')."; + err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "')."; break; } - ip+=4; - } continue; + ip += 4; + } + continue; case OPCODE_GET_NAMED: { - CHECK_SPACE(3); - GET_VARIANT_PTR(src,1); - GET_VARIANT_PTR(dst,3); + GET_VARIANT_PTR(src, 1); + GET_VARIANT_PTR(dst, 3); - int indexname = _code_ptr[ip+2]; + int indexname = _code_ptr[ip + 2]; - ERR_BREAK(indexname<0 || indexname>=_global_names_count); + ERR_BREAK(indexname < 0 || indexname >= _global_names_count); const StringName *index = &_global_names_ptr[indexname]; bool valid; #ifdef DEBUG_ENABLED //allow better error message in cases where src and dst are the same stack position - Variant ret = src->get_named(*index,&valid); + Variant ret = src->get_named(*index, &valid); #else - *dst = src->get_named(*index,&valid); + *dst = src->get_named(*index, &valid); #endif if (!valid) { if (src->has_method(*index)) { - err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"'). Did you mean '."+index->operator String()+"()' ?"; + err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' ?"; } else { - err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"')."; + err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "')."; } break; } #ifdef DEBUG_ENABLED - *dst=ret; + *dst = ret; #endif - ip+=4; - } continue; + ip += 4; + } + continue; case OPCODE_ASSIGN: { CHECK_SPACE(3); - GET_VARIANT_PTR(dst,1); - GET_VARIANT_PTR(src,2); + GET_VARIANT_PTR(dst, 1); + GET_VARIANT_PTR(src, 2); *dst = *src; - ip+=3; - - } continue; + ip += 3; + } + continue; case OPCODE_ASSIGN_TRUE: { CHECK_SPACE(2); - GET_VARIANT_PTR(dst,1); + GET_VARIANT_PTR(dst, 1); *dst = true; - ip+=2; - } continue; + ip += 2; + } + continue; case OPCODE_ASSIGN_FALSE: { CHECK_SPACE(2); - GET_VARIANT_PTR(dst,1); + GET_VARIANT_PTR(dst, 1); *dst = false; - ip+=2; - } continue; + ip += 2; + } + continue; case OPCODE_CONSTRUCT: { CHECK_SPACE(2); - Variant::Type t=Variant::Type(_code_ptr[ip+1]); - int argc=_code_ptr[ip+2]; - CHECK_SPACE(argc+2); + Variant::Type t = Variant::Type(_code_ptr[ip + 1]); + int argc = _code_ptr[ip + 2]; + CHECK_SPACE(argc + 2); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,3+i); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, 3 + i); + argptrs[i] = v; } - GET_VARIANT_PTR(dst,3+argc); + GET_VARIANT_PTR(dst, 3 + argc); Variant::CallError err; - *dst = Variant::construct(t,(const Variant**)argptrs,argc,err); + *dst = Variant::construct(t, (const Variant **)argptrs, argc, err); - if (err.error!=Variant::CallError::CALL_OK) { + if (err.error != Variant::CallError::CALL_OK) { - err_text=_get_call_error(err,"'"+Variant::get_type_name(t)+"' constructor",(const Variant**)argptrs); + err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs); break; } - ip+=4+argc; + ip += 4 + argc; //construct a basic type - } continue; + } + continue; case OPCODE_CONSTRUCT_ARRAY: { CHECK_SPACE(1); - int argc=_code_ptr[ip+1]; + int argc = _code_ptr[ip + 1]; Array array(true); //arrays are always shared array.resize(argc); - CHECK_SPACE(argc+2); - - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,2+i); - array[i]=*v; + CHECK_SPACE(argc + 2); + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, 2 + i); + array[i] = *v; } - GET_VARIANT_PTR(dst,2+argc); + GET_VARIANT_PTR(dst, 2 + argc); - *dst=array; + *dst = array; - ip+=3+argc; - - } continue; + ip += 3 + argc; + } + continue; case OPCODE_CONSTRUCT_DICTIONARY: { CHECK_SPACE(1); - int argc=_code_ptr[ip+1]; + int argc = _code_ptr[ip + 1]; Dictionary dict(true); //arrays are always shared - CHECK_SPACE(argc*2+2); - - for(int i=0;i<argc;i++) { + CHECK_SPACE(argc * 2 + 2); - GET_VARIANT_PTR(k,2+i*2+0); - GET_VARIANT_PTR(v,2+i*2+1); - dict[*k]=*v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(k, 2 + i * 2 + 0); + GET_VARIANT_PTR(v, 2 + i * 2 + 1); + dict[*k] = *v; } - GET_VARIANT_PTR(dst,2+argc*2); + GET_VARIANT_PTR(dst, 2 + argc * 2); - *dst=dict; + *dst = dict; - ip+=3+argc*2; - - } continue; + ip += 3 + argc * 2; + } + continue; case OPCODE_CALL_RETURN: case OPCODE_CALL: { - CHECK_SPACE(4); - bool call_ret = _code_ptr[ip]==OPCODE_CALL_RETURN; + bool call_ret = _code_ptr[ip] == OPCODE_CALL_RETURN; - int argc=_code_ptr[ip+1]; - GET_VARIANT_PTR(base,2); - int nameg=_code_ptr[ip+3]; + int argc = _code_ptr[ip + 1]; + GET_VARIANT_PTR(base, 2); + int nameg = _code_ptr[ip + 3]; - ERR_BREAK(nameg<0 || nameg>=_global_names_count); + ERR_BREAK(nameg < 0 || nameg >= _global_names_count); const StringName *methodname = &_global_names_ptr[nameg]; - ERR_BREAK(argc<0); - ip+=4; - CHECK_SPACE(argc+1); + ERR_BREAK(argc < 0); + ip += 4; + CHECK_SPACE(argc + 1); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,i); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, i); + argptrs[i] = v; } #ifdef DEBUG_ENABLED uint64_t call_time; if (GDScriptLanguage::get_singleton()->profiling) { - call_time=OS::get_singleton()->get_ticks_usec(); + call_time = OS::get_singleton()->get_ticks_usec(); } #endif Variant::CallError err; if (call_ret) { - GET_VARIANT_PTR(ret,argc); - base->call_ptr(*methodname,(const Variant**)argptrs,argc,ret,err); + GET_VARIANT_PTR(ret, argc); + base->call_ptr(*methodname, (const Variant **)argptrs, argc, ret, err); } else { - base->call_ptr(*methodname,(const Variant**)argptrs,argc,NULL,err); + base->call_ptr(*methodname, (const Variant **)argptrs, argc, NULL, err); } #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->profiling) { - function_call_time+=OS::get_singleton()->get_ticks_usec() - call_time; + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; } #endif - if (err.error!=Variant::CallError::CALL_OK) { - + if (err.error != Variant::CallError::CALL_OK) { String methodstr = *methodname; String basestr = _get_var_type(base); - if (methodstr=="call") { - if (argc>=1) { - methodstr=String(*argptrs[0])+" (via call)"; - if (err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { - err.argument-=1; + if (methodstr == "call") { + if (argc >= 1) { + methodstr = String(*argptrs[0]) + " (via call)"; + if (err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { + err.argument -= 1; } } - } if (methodstr=="free") { + } + if (methodstr == "free") { - if (err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) { + if (err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { if (base->is_ref()) { - err_text="Attempted to free a reference."; + err_text = "Attempted to free a reference."; break; - } else if (base->get_type()==Variant::OBJECT) { + } else if (base->get_type() == Variant::OBJECT) { - err_text="Attempted to free a locked object (calling or emitting)."; + err_text = "Attempted to free a locked object (calling or emitting)."; break; } } } - err_text=_get_call_error(err,"function '"+methodstr+"' in base '"+basestr+"'",(const Variant**)argptrs); + err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs); break; } //_call_func(NULL,base,*methodname,ip,argc,p_instance,stack); - ip+=argc+1; - - } continue; + ip += argc + 1; + } + continue; case OPCODE_CALL_BUILT_IN: { CHECK_SPACE(4); - GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip+1]); - int argc=_code_ptr[ip+2]; - ERR_BREAK(argc<0); + GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip + 1]); + int argc = _code_ptr[ip + 2]; + ERR_BREAK(argc < 0); - ip+=3; - CHECK_SPACE(argc+1); + ip += 3; + CHECK_SPACE(argc + 1); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,i); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, i); + argptrs[i] = v; } - GET_VARIANT_PTR(dst,argc); + GET_VARIANT_PTR(dst, argc); Variant::CallError err; - GDFunctions::call(func,(const Variant**)argptrs,argc,*dst,err); - - if (err.error!=Variant::CallError::CALL_OK) { + GDFunctions::call(func, (const Variant **)argptrs, argc, *dst, err); + if (err.error != Variant::CallError::CALL_OK) { String methodstr = GDFunctions::get_func_name(func); - if (dst->get_type()==Variant::STRING) { + if (dst->get_type() == Variant::STRING) { //call provided error string - err_text="Error calling built-in function '"+methodstr+"': "+String(*dst); + err_text = "Error calling built-in function '" + methodstr + "': " + String(*dst); } else { - err_text=_get_call_error(err,"built-in function '"+methodstr+"'",(const Variant**)argptrs); + err_text = _get_call_error(err, "built-in function '" + methodstr + "'", (const Variant **)argptrs); } break; } - ip+=argc+1; - - } continue; + ip += argc + 1; + } + continue; case OPCODE_CALL_SELF: { - } break; case OPCODE_CALL_SELF_BASE: { CHECK_SPACE(2); - int self_fun = _code_ptr[ip+1]; + int self_fun = _code_ptr[ip + 1]; #ifdef DEBUG_ENABLED - if (self_fun<0 || self_fun>=_global_names_count) { + if (self_fun < 0 || self_fun >= _global_names_count) { - err_text="compiler bug, function name not found"; + err_text = "compiler bug, function name not found"; break; } #endif const StringName *methodname = &_global_names_ptr[self_fun]; - int argc=_code_ptr[ip+2]; + int argc = _code_ptr[ip + 2]; - CHECK_SPACE(2+argc+1); + CHECK_SPACE(2 + argc + 1); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,i+3); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, i + 3); + argptrs[i] = v; } - GET_VARIANT_PTR(dst,argc+3); + GET_VARIANT_PTR(dst, argc + 3); const GDScript *gds = _script; - - const Map<StringName,GDFunction*>::Element *E=NULL; + const Map<StringName, GDFunction *>::Element *E = NULL; while (gds->base.ptr()) { - gds=gds->base.ptr(); - E=gds->member_functions.find(*methodname); + gds = gds->base.ptr(); + E = gds->member_functions.find(*methodname); if (E) break; } @@ -783,337 +759,332 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a if (E) { - *dst=E->get()->call(p_instance,(const Variant**)argptrs,argc,err); + *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err); } else if (gds->native.ptr()) { - if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) { + if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { - MethodBind *mb = ObjectTypeDB::get_method(gds->native->get_name(),*methodname); + MethodBind *mb = ObjectTypeDB::get_method(gds->native->get_name(), *methodname); if (!mb) { - err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + err.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; } else { - *dst=mb->call(p_instance->owner,(const Variant**)argptrs,argc,err); + *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err); } } else { - err.error=Variant::CallError::CALL_OK; + err.error = Variant::CallError::CALL_OK; } } else { - if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) { - err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { + err.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; } else { - err.error=Variant::CallError::CALL_OK; + err.error = Variant::CallError::CALL_OK; } } - - if (err.error!=Variant::CallError::CALL_OK) { - + if (err.error != Variant::CallError::CALL_OK) { String methodstr = *methodname; - err_text=_get_call_error(err,"function '"+methodstr+"'",(const Variant**)argptrs); + err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs); break; } - ip+=4+argc; - - } continue; + ip += 4 + argc; + } + continue; case OPCODE_YIELD: case OPCODE_YIELD_SIGNAL: { - int ipofs=1; - if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) { + int ipofs = 1; + if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) { CHECK_SPACE(4); - ipofs+=2; + ipofs += 2; } else { CHECK_SPACE(2); - } - Ref<GDFunctionState> gdfs = memnew( GDFunctionState ); - gdfs->function=this; + Ref<GDFunctionState> gdfs = memnew(GDFunctionState); + gdfs->function = this; gdfs->state.stack.resize(alloca_size); //copy variant stack - for(int i=0;i<_stack_size;i++) { - memnew_placement(&gdfs->state.stack[sizeof(Variant)*i],Variant(stack[i])); + for (int i = 0; i < _stack_size; i++) { + memnew_placement(&gdfs->state.stack[sizeof(Variant) * i], Variant(stack[i])); } - gdfs->state.stack_size=_stack_size; - gdfs->state.self=self; - gdfs->state.alloca_size=alloca_size; - gdfs->state._class=_class; - gdfs->state.ip=ip+ipofs; - gdfs->state.line=line; - gdfs->state.instance_id=(p_instance && p_instance->get_owner())?p_instance->get_owner()->get_instance_ID():0; - gdfs->state.script_id=_class->get_instance_ID(); + gdfs->state.stack_size = _stack_size; + gdfs->state.self = self; + gdfs->state.alloca_size = alloca_size; + gdfs->state._class = _class; + gdfs->state.ip = ip + ipofs; + gdfs->state.line = line; + gdfs->state.instance_id = (p_instance && p_instance->get_owner()) ? p_instance->get_owner()->get_instance_ID() : 0; + gdfs->state.script_id = _class->get_instance_ID(); //gdfs->state.result_pos=ip+ipofs-1; - gdfs->state.defarg=defarg; - gdfs->state.instance=p_instance; - gdfs->function=this; + gdfs->state.defarg = defarg; + gdfs->state.instance = p_instance; + gdfs->function = this; - retvalue=gdfs; + retvalue = gdfs; - if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) { - GET_VARIANT_PTR(argobj,1); - GET_VARIANT_PTR(argname,2); + if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) { + GET_VARIANT_PTR(argobj, 1); + GET_VARIANT_PTR(argname, 2); //do the oneshot connect - if (argobj->get_type()!=Variant::OBJECT) { - err_text="First argument of yield() not of type object."; + if (argobj->get_type() != Variant::OBJECT) { + err_text = "First argument of yield() not of type object."; break; } - if (argname->get_type()!=Variant::STRING) { - err_text="Second argument of yield() not a string (for signal name)."; + if (argname->get_type() != Variant::STRING) { + err_text = "Second argument of yield() not a string (for signal name)."; break; } - Object *obj=argobj->operator Object *(); + Object *obj = argobj->operator Object *(); String signal = argname->operator String(); #ifdef DEBUG_ENABLED if (!obj) { - err_text="First argument of yield() is null."; + err_text = "First argument of yield() is null."; break; } if (ScriptDebugger::get_singleton()) { if (!ObjectDB::instance_validate(obj)) { - err_text="First argument of yield() is a previously freed instance."; + err_text = "First argument of yield() is a previously freed instance."; break; } } - if (signal.length()==0) { + if (signal.length() == 0) { - err_text="Second argument of yield() is an empty string (for signal name)."; + err_text = "Second argument of yield() is an empty string (for signal name)."; break; } #endif - Error err = obj->connect(signal,gdfs.ptr(),"_signal_callback",varray(gdfs),Object::CONNECT_ONESHOT); - if (err!=OK) { - err_text="Error connecting to signal: "+signal+" during yield()."; + Error err = obj->connect(signal, gdfs.ptr(), "_signal_callback", varray(gdfs), Object::CONNECT_ONESHOT); + if (err != OK) { + err_text = "Error connecting to signal: " + signal + " during yield()."; break; } - - } - exit_ok=true; + exit_ok = true; } break; case OPCODE_YIELD_RESUME: { CHECK_SPACE(2); if (!p_state) { - err_text=("Invalid Resume (bug?)"); + err_text = ("Invalid Resume (bug?)"); break; } - GET_VARIANT_PTR(result,1); - *result=p_state->result; - ip+=2; - - } continue; + GET_VARIANT_PTR(result, 1); + *result = p_state->result; + ip += 2; + } + continue; case OPCODE_JUMP: { CHECK_SPACE(2); - int to = _code_ptr[ip+1]; - - ERR_BREAK(to<0 || to>_code_size); - ip=to; + int to = _code_ptr[ip + 1]; - } continue; + ERR_BREAK(to < 0 || to > _code_size); + ip = to; + } + continue; case OPCODE_JUMP_IF: { CHECK_SPACE(3); - GET_VARIANT_PTR(test,1); + GET_VARIANT_PTR(test, 1); bool valid; bool result = test->booleanize(valid); #ifdef DEBUG_ENABLED if (!valid) { - err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type()); + err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type()); break; } #endif if (result) { - int to = _code_ptr[ip+2]; - ERR_BREAK(to<0 || to>_code_size); - ip=to; + int to = _code_ptr[ip + 2]; + ERR_BREAK(to < 0 || to > _code_size); + ip = to; continue; } - ip+=3; - } continue; + ip += 3; + } + continue; case OPCODE_JUMP_IF_NOT: { CHECK_SPACE(3); - GET_VARIANT_PTR(test,1); + GET_VARIANT_PTR(test, 1); bool valid; bool result = test->booleanize(valid); #ifdef DEBUG_ENABLED if (!valid) { - err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type()); + err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type()); break; } #endif if (!result) { - int to = _code_ptr[ip+2]; - ERR_BREAK(to<0 || to>_code_size); - ip=to; + int to = _code_ptr[ip + 2]; + ERR_BREAK(to < 0 || to > _code_size); + ip = to; continue; } - ip+=3; - } continue; + ip += 3; + } + continue; case OPCODE_JUMP_TO_DEF_ARGUMENT: { CHECK_SPACE(2); - ip=_default_arg_ptr[defarg]; - - } continue; + ip = _default_arg_ptr[defarg]; + } + continue; case OPCODE_RETURN: { CHECK_SPACE(2); - GET_VARIANT_PTR(r,1); - retvalue=*r; - exit_ok=true; + GET_VARIANT_PTR(r, 1); + retvalue = *r; + exit_ok = true; } break; case OPCODE_ITERATE_BEGIN: { CHECK_SPACE(8); //space for this an regular iterate - GET_VARIANT_PTR(counter,1); - GET_VARIANT_PTR(container,2); + GET_VARIANT_PTR(counter, 1); + GET_VARIANT_PTR(container, 2); bool valid; - if (!container->iter_init(*counter,valid)) { + if (!container->iter_init(*counter, valid)) { if (!valid) { - err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"'."; + err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "'."; break; } - int jumpto=_code_ptr[ip+3]; - ERR_BREAK(jumpto<0 || jumpto>_code_size); - ip=jumpto; + int jumpto = _code_ptr[ip + 3]; + ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; continue; } - GET_VARIANT_PTR(iterator,4); - + GET_VARIANT_PTR(iterator, 4); - *iterator=container->iter_get(*counter,valid); + *iterator = container->iter_get(*counter, valid); if (!valid) { - err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"'."; + err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "'."; break; } - - ip+=5; //skip regular iterate which is always next - - } continue; + ip += 5; //skip regular iterate which is always next + } + continue; case OPCODE_ITERATE: { CHECK_SPACE(4); - GET_VARIANT_PTR(counter,1); - GET_VARIANT_PTR(container,2); + GET_VARIANT_PTR(counter, 1); + GET_VARIANT_PTR(container, 2); bool valid; - if (!container->iter_next(*counter,valid)) { + if (!container->iter_next(*counter, valid)) { if (!valid) { - err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"' (type changed since first iteration?)."; + err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?)."; break; } - int jumpto=_code_ptr[ip+3]; - ERR_BREAK(jumpto<0 || jumpto>_code_size); - ip=jumpto; + int jumpto = _code_ptr[ip + 3]; + ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; continue; } - GET_VARIANT_PTR(iterator,4); + GET_VARIANT_PTR(iterator, 4); - *iterator=container->iter_get(*counter,valid); + *iterator = container->iter_get(*counter, valid); if (!valid) { - err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"' (but was obtained on first iteration?)."; + err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?)."; break; } - ip+=5; //loop again - } continue; + ip += 5; //loop again + } + continue; case OPCODE_ASSERT: { CHECK_SPACE(2); - GET_VARIANT_PTR(test,1); + GET_VARIANT_PTR(test, 1); #ifdef DEBUG_ENABLED bool valid; bool result = test->booleanize(valid); - if (!valid) { - err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type()); + err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type()); break; } - if (!result) { - err_text="Assertion failed."; + err_text = "Assertion failed."; break; } #endif - ip+=2; - } continue; + ip += 2; + } + continue; case OPCODE_BREAKPOINT: { #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement",true); + GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true); } #endif - ip+=1; - } continue; + ip += 1; + } + continue; case OPCODE_LINE: { CHECK_SPACE(2); - line=_code_ptr[ip+1]; - ip+=2; + line = _code_ptr[ip + 1]; + ip += 2; if (ScriptDebugger::get_singleton()) { // line - bool do_break=false; + bool do_break = false; - if (ScriptDebugger::get_singleton()->get_lines_left()>0) { + if (ScriptDebugger::get_singleton()->get_lines_left() > 0) { - if (ScriptDebugger::get_singleton()->get_depth()<=0) - ScriptDebugger::get_singleton()->set_lines_left( ScriptDebugger::get_singleton()->get_lines_left() -1 ); - if (ScriptDebugger::get_singleton()->get_lines_left()<=0) - do_break=true; + if (ScriptDebugger::get_singleton()->get_depth() <= 0) + ScriptDebugger::get_singleton()->set_lines_left(ScriptDebugger::get_singleton()->get_lines_left() - 1); + if (ScriptDebugger::get_singleton()->get_lines_left() <= 0) + do_break = true; } - if (ScriptDebugger::get_singleton()->is_breakpoint(line,source)) - do_break=true; + if (ScriptDebugger::get_singleton()->is_breakpoint(line, source)) + do_break = true; if (do_break) { - GDScriptLanguage::get_singleton()->debug_break("Breakpoint",true); + GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true); } ScriptDebugger::get_singleton()->line_poll(); - } - } continue; + } + continue; case OPCODE_END: { - exit_ok=true; + exit_ok = true; break; } break; default: { - err_text="Illegal opcode "+itos(_code_ptr[ip])+" at address "+itos(ip); + err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip); } break; - } if (exit_ok) @@ -1122,73 +1093,69 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a // function, file, line, error, explanation String err_file; if (p_instance) - err_file=p_instance->script->path; + err_file = p_instance->script->path; else if (_class) - err_file=_class->path; - if (err_file=="") - err_file="<built-in>"; + err_file = _class->path; + if (err_file == "") + err_file = "<built-in>"; String err_func = name; - if (p_instance && p_instance->script->name!="") - err_func=p_instance->script->name+"."+err_func; - int err_line=line; - if (err_text=="") { - err_text="Internal Script Error! - opcode #"+itos(last_opcode)+" (report please)."; + if (p_instance && p_instance->script->name != "") + err_func = p_instance->script->name + "." + err_func; + int err_line = line; + if (err_text == "") { + err_text = "Internal Script Error! - opcode #" + itos(last_opcode) + " (report please)."; } - if (!GDScriptLanguage::get_singleton()->debug_break(err_text,false)) { + if (!GDScriptLanguage::get_singleton()->debug_break(err_text, false)) { // debugger break did not happen - _err_print_error(err_func.utf8().get_data(),err_file.utf8().get_data(),err_line,err_text.utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT); } - break; } #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->profiling) { uint64_t time_taken = OS::get_singleton()->get_ticks_usec() - function_start_time; - profile.total_time+=time_taken; - profile.self_time+=time_taken-function_call_time; - profile.frame_total_time+=time_taken; - profile.frame_self_time+=time_taken-function_call_time; - GDScriptLanguage::get_singleton()->script_frame_time+=time_taken-function_call_time; - + profile.total_time += time_taken; + profile.self_time += time_taken - function_call_time; + profile.frame_total_time += time_taken; + profile.frame_self_time += time_taken - function_call_time; + GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time; } #endif if (ScriptDebugger::get_singleton()) GDScriptLanguage::get_singleton()->exit_function(); - if (_stack_size) { //free stack - for(int i=0;i<_stack_size;i++) + for (int i = 0; i < _stack_size; i++) stack[i].~Variant(); } return retvalue; - } -const int* GDFunction::get_code() const { +const int *GDFunction::get_code() const { return _code_ptr; } -int GDFunction::get_code_size() const{ +int GDFunction::get_code_size() const { return _code_size; } Variant GDFunction::get_constant(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,constants.size(),"<errconst>"); + ERR_FAIL_INDEX_V(p_idx, constants.size(), "<errconst>"); return constants[p_idx]; } StringName GDFunction::get_global_name(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,global_names.size(),"<errgname>"); + ERR_FAIL_INDEX_V(p_idx, global_names.size(), "<errgname>"); return global_names[p_idx]; } @@ -1196,13 +1163,12 @@ int GDFunction::get_default_argument_count() const { return default_arguments.size(); } -int GDFunction::get_default_argument_addr(int p_arg) const{ +int GDFunction::get_default_argument_addr(int p_arg) const { - ERR_FAIL_INDEX_V(p_arg,default_arguments.size(),-1); + ERR_FAIL_INDEX_V(p_arg, default_arguments.size(), -1); return default_arguments[p_arg]; } - StringName GDFunction::get_name() const { return name; @@ -1227,66 +1193,60 @@ struct _GDFKCS { bool operator<(const _GDFKCS &p_r) const { - return order<p_r.order; + return order < p_r.order; } }; -void GDFunction::debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const { +void GDFunction::debug_get_stack_member_state(int p_line, List<Pair<StringName, int> > *r_stackvars) const { + int oc = 0; + Map<StringName, _GDFKC> sdmap; + for (const List<StackDebug>::Element *E = stack_debug.front(); E; E = E->next()) { - int oc=0; - Map<StringName,_GDFKC> sdmap; - for( const List<StackDebug>::Element *E=stack_debug.front();E;E=E->next()) { - - const StackDebug &sd=E->get(); - if (sd.line>p_line) + const StackDebug &sd = E->get(); + if (sd.line > p_line) break; if (sd.added) { if (!sdmap.has(sd.identifier)) { _GDFKC d; - d.order=oc++; + d.order = oc++; d.pos.push_back(sd.pos); - sdmap[sd.identifier]=d; + sdmap[sd.identifier] = d; } else { sdmap[sd.identifier].pos.push_back(sd.pos); } } else { - ERR_CONTINUE(!sdmap.has(sd.identifier)); sdmap[sd.identifier].pos.pop_back(); if (sdmap[sd.identifier].pos.empty()) sdmap.erase(sd.identifier); } - } - List<_GDFKCS> stackpositions; - for(Map<StringName,_GDFKC>::Element *E=sdmap.front();E;E=E->next() ) { + for (Map<StringName, _GDFKC>::Element *E = sdmap.front(); E; E = E->next()) { _GDFKCS spp; - spp.id=E->key(); - spp.order=E->get().order; - spp.pos=E->get().pos.back()->get(); + spp.id = E->key(); + spp.order = E->get().order; + spp.pos = E->get().pos.back()->get(); stackpositions.push_back(spp); } stackpositions.sort(); - for(List<_GDFKCS>::Element *E=stackpositions.front();E;E=E->next()) { + for (List<_GDFKCS>::Element *E = stackpositions.front(); E; E = E->next()) { - Pair<StringName,int> p; - p.first=E->get().id; - p.second=E->get().pos; + Pair<StringName, int> p; + p.first = E->get().id; + p.second = E->get().pos; r_stackvars->push_back(p); } - - } #if 0 @@ -1305,13 +1265,14 @@ void GDFunction::clear() { } #endif -GDFunction::GDFunction() : function_list(this) { +GDFunction::GDFunction() + : function_list(this) { - _stack_size=0; - _call_size=0; - name="<anonymous>"; + _stack_size = 0; + _call_size = 0; + name = "<anonymous>"; #ifdef DEBUG_ENABLED - _func_cname=NULL; + _func_cname = NULL; if (GDScriptLanguage::get_singleton()->lock) { GDScriptLanguage::get_singleton()->lock->lock(); @@ -1322,20 +1283,20 @@ GDFunction::GDFunction() : function_list(this) { GDScriptLanguage::get_singleton()->lock->unlock(); } - profile.call_count=0; - profile.self_time=0; - profile.total_time=0; - profile.frame_call_count=0; - profile.frame_self_time=0; - profile.frame_total_time=0; - profile.last_frame_call_count=0; - profile.last_frame_self_time=0; - profile.last_frame_total_time=0; + profile.call_count = 0; + profile.self_time = 0; + profile.total_time = 0; + profile.frame_call_count = 0; + profile.frame_self_time = 0; + profile.frame_total_time = 0; + profile.last_frame_call_count = 0; + profile.last_frame_self_time = 0; + profile.last_frame_total_time = 0; #endif } -GDFunction::~GDFunction() { +GDFunction::~GDFunction() { #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->lock) { GDScriptLanguage::get_singleton()->lock->lock(); @@ -1350,8 +1311,7 @@ GDFunction::~GDFunction() { ///////////////////// - -Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { +Variant GDFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { #ifdef DEBUG_ENABLED if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { @@ -1366,51 +1326,50 @@ Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount #endif Variant arg; - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; - ERR_FAIL_COND_V(!function,Variant()); + ERR_FAIL_COND_V(!function, Variant()); - if (p_argcount==0) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=1; + if (p_argcount == 0) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; return Variant(); - } else if (p_argcount==1) { + } else if (p_argcount == 1) { //noooneee - } else if (p_argcount==2) { - arg=*p_args[0]; + } else if (p_argcount == 2) { + arg = *p_args[0]; } else { Array extra_args; - for(int i=0;i<p_argcount-1;i++) { + for (int i = 0; i < p_argcount - 1; i++) { extra_args.push_back(*p_args[i]); } - arg=extra_args; + arg = extra_args; } - Ref<GDFunctionState> self = *p_args[p_argcount-1]; + Ref<GDFunctionState> self = *p_args[p_argcount - 1]; if (self.is_null()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=p_argcount-1; - r_error.expected=Variant::OBJECT; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = p_argcount - 1; + r_error.expected = Variant::OBJECT; return Variant(); } - state.result=arg; - Variant ret = function->call(NULL,NULL,0,r_error,&state); - function=NULL; //cleaned up; - state.result=Variant(); + state.result = arg; + Variant ret = function->call(NULL, NULL, 0, r_error, &state); + function = NULL; //cleaned up; + state.result = Variant(); return ret; } - bool GDFunctionState::is_valid() const { - return function!=NULL; + return function != NULL; } -Variant GDFunctionState::resume(const Variant& p_arg) { +Variant GDFunctionState::resume(const Variant &p_arg) { - ERR_FAIL_COND_V(!function,Variant()); + ERR_FAIL_COND_V(!function, Variant()); #ifdef DEBUG_ENABLED if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { ERR_EXPLAIN("Resumed after yield, but class instance is gone"); @@ -1423,36 +1382,33 @@ Variant GDFunctionState::resume(const Variant& p_arg) { } #endif - state.result=p_arg; + state.result = p_arg; Variant::CallError err; - Variant ret = function->call(NULL,NULL,0,err,&state); - function=NULL; //cleaned up; - state.result=Variant(); + Variant ret = function->call(NULL, NULL, 0, err, &state); + function = NULL; //cleaned up; + state.result = Variant(); return ret; } - void GDFunctionState::_bind_methods() { - ObjectTypeDB::bind_method(_MD("resume:Variant","arg"),&GDFunctionState::resume,DEFVAL(Variant())); - ObjectTypeDB::bind_method(_MD("is_valid"),&GDFunctionState::is_valid); - ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"_signal_callback",&GDFunctionState::_signal_callback,MethodInfo("_signal_callback")); - + ObjectTypeDB::bind_method(_MD("resume:Variant", "arg"), &GDFunctionState::resume, DEFVAL(Variant())); + ObjectTypeDB::bind_method(_MD("is_valid"), &GDFunctionState::is_valid); + ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &GDFunctionState::_signal_callback, MethodInfo("_signal_callback")); } GDFunctionState::GDFunctionState() { - function=NULL; + function = NULL; } GDFunctionState::~GDFunctionState() { - if (function!=NULL) { + if (function != NULL) { //never called, deinitialize stack - for(int i=0;i<state.stack_size;i++) { - Variant *v=(Variant*)&state.stack[sizeof(Variant)*i]; + for (int i = 0; i < state.stack_size; i++) { + Variant *v = (Variant *)&state.stack[sizeof(Variant) * i]; v->~Variant(); } } } - diff --git a/modules/gdscript/gd_function.h b/modules/gdscript/gd_function.h index e09c6509d..5f143cce8 100644 --- a/modules/gdscript/gd_function.h +++ b/modules/gdscript/gd_function.h @@ -1,20 +1,18 @@ #ifndef GD_FUNCTION_H #define GD_FUNCTION_H -#include "self_list.h" #include "os/thread.h" #include "pair.h" -#include "variant.h" -#include "string_db.h" #include "reference.h" +#include "self_list.h" +#include "string_db.h" +#include "variant.h" class GDInstance; class GDScript; - class GDFunction { public: - enum Opcode { OPCODE_OPERATOR, OPCODE_EXTENDS_TEST, @@ -50,30 +48,30 @@ public: }; enum Address { - ADDR_BITS=24, - ADDR_MASK=((1<<ADDR_BITS)-1), - ADDR_TYPE_MASK=~ADDR_MASK, - ADDR_TYPE_SELF=0, - ADDR_TYPE_CLASS=1, - ADDR_TYPE_MEMBER=2, - ADDR_TYPE_CLASS_CONSTANT=3, - ADDR_TYPE_LOCAL_CONSTANT=4, - ADDR_TYPE_STACK=5, - ADDR_TYPE_STACK_VARIABLE=6, - ADDR_TYPE_GLOBAL=7, - ADDR_TYPE_NIL=8 + ADDR_BITS = 24, + ADDR_MASK = ((1 << ADDR_BITS) - 1), + ADDR_TYPE_MASK = ~ADDR_MASK, + ADDR_TYPE_SELF = 0, + ADDR_TYPE_CLASS = 1, + ADDR_TYPE_MEMBER = 2, + ADDR_TYPE_CLASS_CONSTANT = 3, + ADDR_TYPE_LOCAL_CONSTANT = 4, + ADDR_TYPE_STACK = 5, + ADDR_TYPE_STACK_VARIABLE = 6, + ADDR_TYPE_GLOBAL = 7, + ADDR_TYPE_NIL = 8 }; - struct StackDebug { + struct StackDebug { - int line; - int pos; - bool added; - StringName identifier; - }; + int line; + int pos; + bool added; + StringName identifier; + }; private: -friend class GDCompiler; + friend class GDCompiler; StringName source; @@ -105,15 +103,15 @@ friend class GDCompiler; List<StackDebug> stack_debug; - _FORCE_INLINE_ Variant *_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self,Variant *p_stack,String& r_error) const; - _FORCE_INLINE_ String _get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const; + _FORCE_INLINE_ Variant *_get_variant(int p_address, GDInstance *p_instance, GDScript *p_script, Variant &self, Variant *p_stack, String &r_error) const; + _FORCE_INLINE_ String _get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const; -friend class GDScriptLanguage; + friend class GDScriptLanguage; SelfList<GDFunction> function_list; #ifdef DEBUG_ENABLED CharString func_cname; - const char*_func_cname; + const char *_func_cname; struct Profile { StringName signature; @@ -131,9 +129,6 @@ friend class GDScriptLanguage; #endif public: - - - struct CallState { ObjectID instance_id; //by debug only @@ -149,12 +144,11 @@ public: int line; int defarg; Variant result; - }; _FORCE_INLINE_ bool is_static() const { return _static; } - const int* get_code() const; //used for debug + const int *get_code() const; //used for debug int get_code_size() const; Variant get_constant(int p_idx) const; StringName get_global_name(int p_idx) const; @@ -165,47 +159,45 @@ public: GDScript *get_script() const { return _script; } StringName get_source() const { return source; } - void debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const; + void debug_get_stack_member_state(int p_line, List<Pair<StringName, int> > *r_stackvars) const; - _FORCE_INLINE_ bool is_empty() const { return _code_size==0; } + _FORCE_INLINE_ bool is_empty() const { return _code_size == 0; } int get_argument_count() const { return _argument_count; } StringName get_argument_name(int p_idx) const { #ifdef TOOLS_ENABLED - ERR_FAIL_INDEX_V(p_idx,arg_names.size(),StringName()); + ERR_FAIL_INDEX_V(p_idx, arg_names.size(), StringName()); return arg_names[p_idx]; #endif return StringName(); - } Variant get_default_argument(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,default_arguments.size(),Variant()); + ERR_FAIL_INDEX_V(p_idx, default_arguments.size(), Variant()); return default_arguments[p_idx]; } - Variant call(GDInstance *p_instance,const Variant **p_args, int p_argcount,Variant::CallError& r_err,CallState *p_state=NULL); + Variant call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError &r_err, CallState *p_state = NULL); GDFunction(); ~GDFunction(); }; - class GDFunctionState : public Reference { - OBJ_TYPE(GDFunctionState,Reference); -friend class GDFunction; + OBJ_TYPE(GDFunctionState, Reference); + friend class GDFunction; GDFunction *function; GDFunction::CallState state; - Variant _signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error); + Variant _signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error); + protected: static void _bind_methods(); -public: +public: bool is_valid() const; - Variant resume(const Variant& p_arg=Variant()); + Variant resume(const Variant &p_arg = Variant()); GDFunctionState(); ~GDFunctionState(); }; - #endif // GD_FUNCTION_H diff --git a/modules/gdscript/gd_functions.cpp b/modules/gdscript/gd_functions.cpp index 9d3a84d02..c4e569420 100644 --- a/modules/gdscript/gd_functions.cpp +++ b/modules/gdscript/gd_functions.cpp @@ -27,20 +27,20 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_functions.h" +#include "func_ref.h" +#include "gd_script.h" +#include "io/marshalls.h" #include "math_funcs.h" #include "object_type_db.h" -#include "reference.h" -#include "gd_script.h" -#include "func_ref.h" #include "os/os.h" +#include "reference.h" #include "variant_parser.h" -#include "io/marshalls.h" const char *GDFunctions::get_func_name(Function p_func) { - ERR_FAIL_INDEX_V(p_func,FUNC_MAX,""); + ERR_FAIL_INDEX_V(p_func, FUNC_MAX, ""); - static const char *_names[FUNC_MAX]={ + static const char *_names[FUNC_MAX] = { "sin", "cos", "tan", @@ -110,35 +110,34 @@ const char *GDFunctions::get_func_name(Function p_func) { }; return _names[p_func]; - } -void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Variant &r_ret,Variant::CallError &r_error) { +void GDFunctions::call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Variant::CallError &r_error) { - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; #ifdef DEBUG_ENABLED -#define VALIDATE_ARG_COUNT(m_count) \ - if (p_arg_count<m_count) {\ - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;\ - r_error.argument=m_count;\ - r_ret=Variant();\ - return;\ - }\ - if (p_arg_count>m_count) {\ - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;\ - r_error.argument=m_count;\ - r_ret=Variant();\ - return;\ +#define VALIDATE_ARG_COUNT(m_count) \ + if (p_arg_count < m_count) { \ + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; \ + r_error.argument = m_count; \ + r_ret = Variant(); \ + return; \ + } \ + if (p_arg_count > m_count) { \ + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; \ + r_error.argument = m_count; \ + r_ret = Variant(); \ + return; \ } -#define VALIDATE_ARG_NUM(m_arg) \ - if (!p_args[m_arg]->is_num()) {\ - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;\ - r_error.argument=m_arg;\ - r_error.expected=Variant::REAL;\ - r_ret=Variant();\ - return;\ +#define VALIDATE_ARG_NUM(m_arg) \ + if (!p_args[m_arg]->is_num()) { \ + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; \ + r_error.argument = m_arg; \ + r_error.expected = Variant::REAL; \ + r_ret = Variant(); \ + return; \ } #else @@ -149,245 +148,245 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va //using a switch, so the compiler generates a jumptable - switch(p_func) { + switch (p_func) { case MATH_SIN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::sin(*p_args[0]); + r_ret = Math::sin(*p_args[0]); } break; case MATH_COS: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::cos(*p_args[0]); + r_ret = Math::cos(*p_args[0]); } break; case MATH_TAN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::tan(*p_args[0]); + r_ret = Math::tan(*p_args[0]); } break; case MATH_SINH: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::sinh(*p_args[0]); + r_ret = Math::sinh(*p_args[0]); } break; case MATH_COSH: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::cosh(*p_args[0]); + r_ret = Math::cosh(*p_args[0]); } break; case MATH_TANH: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::tanh(*p_args[0]); + r_ret = Math::tanh(*p_args[0]); } break; case MATH_ASIN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::asin(*p_args[0]); + r_ret = Math::asin(*p_args[0]); } break; case MATH_ACOS: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::acos(*p_args[0]); + r_ret = Math::acos(*p_args[0]); } break; case MATH_ATAN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::atan(*p_args[0]); + r_ret = Math::atan(*p_args[0]); } break; case MATH_ATAN2: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::atan2(*p_args[0],*p_args[1]); + r_ret = Math::atan2(*p_args[0], *p_args[1]); } break; case MATH_SQRT: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::sqrt(*p_args[0]); + r_ret = Math::sqrt(*p_args[0]); } break; case MATH_FMOD: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::fmod(*p_args[0],*p_args[1]); + r_ret = Math::fmod(*p_args[0], *p_args[1]); } break; case MATH_FPOSMOD: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::fposmod(*p_args[0],*p_args[1]); + r_ret = Math::fposmod(*p_args[0], *p_args[1]); } break; case MATH_FLOOR: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::floor(*p_args[0]); - } break; + r_ret = Math::floor(*p_args[0]); + } break; case MATH_CEIL: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::ceil(*p_args[0]); + r_ret = Math::ceil(*p_args[0]); } break; case MATH_ROUND: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::round(*p_args[0]); + r_ret = Math::round(*p_args[0]); } break; case MATH_ABS: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT) { int64_t i = *p_args[0]; - r_ret=ABS(i); - } else if (p_args[0]->get_type()==Variant::REAL) { + r_ret = ABS(i); + } else if (p_args[0]->get_type() == Variant::REAL) { real_t r = *p_args[0]; - r_ret=Math::abs(r); + r_ret = Math::abs(r); } else { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::REAL; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::REAL; + r_ret = Variant(); } } break; case MATH_SIGN: { - VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()==Variant::INT) { + VALIDATE_ARG_COUNT(1); + if (p_args[0]->get_type() == Variant::INT) { - int64_t i = *p_args[0]; - r_ret= i < 0 ? -1 : ( i > 0 ? +1 : 0); - } else if (p_args[0]->get_type()==Variant::REAL) { + int64_t i = *p_args[0]; + r_ret = i < 0 ? -1 : (i > 0 ? +1 : 0); + } else if (p_args[0]->get_type() == Variant::REAL) { - real_t r = *p_args[0]; - r_ret= r < 0.0 ? -1.0 : ( r > 0.0 ? +1.0 : 0.0); - } else { + real_t r = *p_args[0]; + r_ret = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0); + } else { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::REAL; - r_ret=Variant(); - } + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::REAL; + r_ret = Variant(); + } } break; case MATH_POW: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::pow(*p_args[0],*p_args[1]); + r_ret = Math::pow(*p_args[0], *p_args[1]); } break; case MATH_LOG: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::log(*p_args[0]); + r_ret = Math::log(*p_args[0]); } break; case MATH_EXP: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::exp(*p_args[0]); + r_ret = Math::exp(*p_args[0]); } break; case MATH_ISNAN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::is_nan(*p_args[0]); + r_ret = Math::is_nan(*p_args[0]); } break; case MATH_ISINF: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::is_inf(*p_args[0]); + r_ret = Math::is_inf(*p_args[0]); } break; case MATH_EASE: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::ease(*p_args[0],*p_args[1]); + r_ret = Math::ease(*p_args[0], *p_args[1]); } break; case MATH_DECIMALS: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::step_decimals(*p_args[0]); + r_ret = Math::step_decimals(*p_args[0]); } break; case MATH_STEPIFY: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::stepify(*p_args[0],*p_args[1]); + r_ret = Math::stepify(*p_args[0], *p_args[1]); } break; case MATH_LERP: { VALIDATE_ARG_COUNT(3); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - r_ret=Math::lerp(*p_args[0],*p_args[1],*p_args[2]); + r_ret = Math::lerp(*p_args[0], *p_args[1], *p_args[2]); } break; case MATH_DECTIME: { VALIDATE_ARG_COUNT(3); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - r_ret=Math::dectime(*p_args[0],*p_args[1],*p_args[2]); + r_ret = Math::dectime(*p_args[0], *p_args[1], *p_args[2]); } break; case MATH_RANDOMIZE: { Math::randomize(); - r_ret=Variant(); + r_ret = Variant(); } break; case MATH_RAND: { - r_ret=Math::rand(); + r_ret = Math::rand(); } break; case MATH_RANDF: { - r_ret=Math::randf(); + r_ret = Math::randf(); } break; case MATH_RANDOM: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::random(*p_args[0],*p_args[1]); + r_ret = Math::random(*p_args[0], *p_args[1]); } break; case MATH_SEED: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - uint32_t seed=*p_args[0]; + uint32_t seed = *p_args[0]; Math::seed(seed); - r_ret=Variant(); + r_ret = Variant(); } break; case MATH_RANDSEED: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - uint32_t seed=*p_args[0]; + uint32_t seed = *p_args[0]; int ret = Math::rand_from_seed(&seed); Array reta; reta.push_back(ret); reta.push_back(seed); - r_ret=reta; + r_ret = reta; } break; case MATH_DEG2RAD: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::deg2rad(*p_args[0]); + r_ret = Math::deg2rad(*p_args[0]); } break; case MATH_RAD2DEG: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::rad2deg(*p_args[0]); + r_ret = Math::rad2deg(*p_args[0]); } break; case MATH_LINEAR2DB: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::linear2db(*p_args[0]); + r_ret = Math::linear2db(*p_args[0]); } break; case MATH_DB2LINEAR: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::db2linear(*p_args[0]); + r_ret = Math::db2linear(*p_args[0]); } break; case LOGIC_MAX: { VALIDATE_ARG_COUNT(2); - if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT) { int64_t a = *p_args[0]; int64_t b = *p_args[1]; - r_ret=MAX(a,b); + r_ret = MAX(a, b); } else { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -395,17 +394,17 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va real_t a = *p_args[0]; real_t b = *p_args[1]; - r_ret=MAX(a,b); + r_ret = MAX(a, b); } } break; case LOGIC_MIN: { VALIDATE_ARG_COUNT(2); - if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT) { int64_t a = *p_args[0]; int64_t b = *p_args[1]; - r_ret=MIN(a,b); + r_ret = MIN(a, b); } else { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -413,17 +412,17 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va real_t a = *p_args[0]; real_t b = *p_args[1]; - r_ret=MIN(a,b); + r_ret = MIN(a, b); } } break; case LOGIC_CLAMP: { VALIDATE_ARG_COUNT(3); - if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT && p_args[2]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT && p_args[2]->get_type() == Variant::INT) { int64_t a = *p_args[0]; int64_t b = *p_args[1]; int64_t c = *p_args[2]; - r_ret=CLAMP(a,b,c); + r_ret = CLAMP(a, b, c); } else { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -433,7 +432,7 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va real_t b = *p_args[1]; real_t c = *p_args[2]; - r_ret=CLAMP(a,b,c); + r_ret = CLAMP(a, b, c); } } break; case LOGIC_NEAREST_PO2: { @@ -444,87 +443,80 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va } break; case OBJ_WEAKREF: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=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; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); return; - } if (p_args[0]->is_ref()) { REF r = *p_args[0]; if (!r.is_valid()) { - r_ret=Variant(); + r_ret = Variant(); return; } - Ref<WeakRef> wref = memnew( WeakRef ); + Ref<WeakRef> wref = memnew(WeakRef); wref->set_ref(r); - r_ret=wref; + r_ret = wref; } else { Object *obj = *p_args[0]; if (!obj) { - r_ret=Variant(); + r_ret = Variant(); return; } - Ref<WeakRef> wref = memnew( WeakRef ); + Ref<WeakRef> wref = memnew(WeakRef); wref->set_obj(obj); - r_ret=wref; + r_ret = wref; } - - - } break; case FUNC_FUNCREF: { VALIDATE_ARG_COUNT(2); - if (p_args[0]->get_type()!=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; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); return; - } - if (p_args[1]->get_type()!=Variant::STRING && p_args[1]->get_type()!=Variant::NODE_PATH) { + if (p_args[1]->get_type() != Variant::STRING && p_args[1]->get_type() != Variant::NODE_PATH) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=1; - r_error.expected=Variant::STRING; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 1; + r_error.expected = Variant::STRING; + r_ret = Variant(); return; - } - Ref<FuncRef> fr = memnew( FuncRef); + Ref<FuncRef> fr = memnew(FuncRef); fr->set_instance(*p_args[0]); fr->set_function(*p_args[1]); - r_ret=fr; + r_ret = fr; } break; case TYPE_CONVERT: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(1); - int type=*p_args[1]; - if (type<0 || type>=Variant::VARIANT_MAX) { + int type = *p_args[1]; + if (type < 0 || type >= Variant::VARIANT_MAX) { - r_ret=RTR("Invalid type argument to convert(), use TYPE_* constants."); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::INT; + r_ret = RTR("Invalid type argument to convert(), use TYPE_* constants."); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::INT; return; } else { - - r_ret=Variant::construct(Variant::Type(type),p_args,1,r_error); + r_ret = Variant::construct(Variant::Type(type), p_args, 1, r_error); } } break; case TYPE_OF: { @@ -542,119 +534,116 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va case TEXT_STR: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); - if (i==0) - str=os; + if (i == 0) + str = os; else - str+=os; + str += os; } - r_ret=str; + r_ret = str; } break; case TEXT_PRINT: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { - str+=p_args[i]->operator String(); + str += p_args[i]->operator String(); } //str+="\n"; print_line(str); - r_ret=Variant(); - + r_ret = Variant(); } break; case TEXT_PRINT_TABBED: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { if (i) - str+="\t"; - str+=p_args[i]->operator String(); + str += "\t"; + str += p_args[i]->operator String(); } //str+="\n"; print_line(str); - r_ret=Variant(); - + r_ret = Variant(); } break; case TEXT_PRINT_SPACED: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { if (i) - str+=" "; - str+=p_args[i]->operator String(); + str += " "; + str += p_args[i]->operator String(); } //str+="\n"; print_line(str); - r_ret=Variant(); - + r_ret = Variant(); } break; case TEXT_PRINTERR: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { - str+=p_args[i]->operator String(); + str += p_args[i]->operator String(); } //str+="\n"; - OS::get_singleton()->printerr("%s\n",str.utf8().get_data()); - r_ret=Variant(); + OS::get_singleton()->printerr("%s\n", str.utf8().get_data()); + r_ret = Variant(); } break; case TEXT_PRINTRAW: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { - str+=p_args[i]->operator String(); + str += p_args[i]->operator String(); } //str+="\n"; - OS::get_singleton()->print("%s",str.utf8().get_data()); - r_ret=Variant(); + OS::get_singleton()->print("%s", str.utf8().get_data()); + r_ret = Variant(); } break; case VAR_TO_STR: { VALIDATE_ARG_COUNT(1); String vars; - VariantWriter::write_to_string(*p_args[0],vars); - r_ret=vars; + VariantWriter::write_to_string(*p_args[0], vars); + r_ret = vars; } break; case STR_TO_VAR: { VALIDATE_ARG_COUNT(1); - 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; - r_ret=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; + r_ret = Variant(); return; } VariantParser::StreamString ss; - ss.s=*p_args[0]; + ss.s = *p_args[0]; String errs; int line; - Error err = VariantParser::parse(&ss,r_ret,errs,line); + Error err = VariantParser::parse(&ss, r_ret, errs, line); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; - r_ret="Parse error at line "+itos(line)+": "+errs; + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = "Parse error at line " + itos(line) + ": " + errs; return; } @@ -664,106 +653,104 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va ByteArray barr; int len; - Error err = encode_variant(*p_args[0],NULL,len); + Error err = encode_variant(*p_args[0], NULL, len); if (err) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::NIL; - r_ret="Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::NIL; + r_ret = "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."; return; } barr.resize(len); { ByteArray::Write w = barr.write(); - encode_variant(*p_args[0],w.ptr(),len); - + encode_variant(*p_args[0], w.ptr(), len); } - r_ret=barr; + r_ret = barr; } break; case BYTES_TO_VAR: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::RAW_ARRAY) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::RAW_ARRAY; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::RAW_ARRAY) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::RAW_ARRAY; + r_ret = Variant(); return; } - ByteArray varr=*p_args[0]; + ByteArray varr = *p_args[0]; Variant ret; { - ByteArray::Read r=varr.read(); - Error err = decode_variant(ret,r.ptr(),varr.size(),NULL); - if (err!=OK) { - r_ret=RTR("Not enough bytes for decoding bytes, or invalid format."); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::RAW_ARRAY; + ByteArray::Read r = varr.read(); + Error err = decode_variant(ret, r.ptr(), varr.size(), NULL); + if (err != OK) { + r_ret = RTR("Not enough bytes for decoding bytes, or invalid format."); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::RAW_ARRAY; return; } - } - r_ret=ret; + r_ret = ret; } break; case GEN_RANGE: { - switch(p_arg_count) { + switch (p_arg_count) { case 0: { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=1; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; + r_ret = Variant(); } break; case 1: { VALIDATE_ARG_NUM(0); - int count=*p_args[0]; + int count = *p_args[0]; Array arr(true); - if (count<=0) { - r_ret=arr; + if (count <= 0) { + r_ret = arr; return; } Error err = arr.resize(count); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - r_ret=Variant(); + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = Variant(); return; } - for(int i=0;i<count;i++) { - arr[i]=i; + for (int i = 0; i < count; i++) { + arr[i] = i; } - r_ret=arr; + r_ret = arr; } break; case 2: { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - int from=*p_args[0]; - int to=*p_args[1]; + int from = *p_args[0]; + int to = *p_args[1]; Array arr(true); - if (from>=to) { - r_ret=arr; + if (from >= to) { + r_ret = arr; return; } - Error err = arr.resize(to-from); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - r_ret=Variant(); + Error err = arr.resize(to - from); + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = Variant(); return; } - for(int i=from;i<to;i++) - arr[i-from]=i; - r_ret=arr; + for (int i = from; i < to; i++) + arr[i - from] = i; + r_ret = arr; } break; case 3: { @@ -771,65 +758,64 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - int from=*p_args[0]; - int to=*p_args[1]; - int incr=*p_args[2]; - if (incr==0) { + int from = *p_args[0]; + int to = *p_args[1]; + int incr = *p_args[2]; + if (incr == 0) { - r_ret=RTR("step argument is zero!"); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = RTR("step argument is zero!"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return; } Array arr(true); - if (from>=to && incr>0) { - r_ret=arr; + if (from >= to && incr > 0) { + r_ret = arr; return; } - if (from<=to && incr<0) { - r_ret=arr; + if (from <= to && incr < 0) { + r_ret = arr; return; } //calculate how many - int count=0; - if (incr>0) { + int count = 0; + if (incr > 0) { - count=((to-from-1)/incr)+1; + count = ((to - from - 1) / incr) + 1; } else { - count=((from-to-1)/-incr)+1; + count = ((from - to - 1) / -incr) + 1; } - Error err = arr.resize(count); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - r_ret=Variant(); + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = Variant(); return; } - if (incr>0) { - int idx=0; - for(int i=from;i<to;i+=incr) { - arr[idx++]=i; + if (incr > 0) { + int idx = 0; + for (int i = from; i < to; i += incr) { + arr[idx++] = i; } } else { - int idx=0; - for(int i=from;i>to;i+=incr) { - arr[idx++]=i; + int idx = 0; + for (int i = from; i > to; i += incr) { + arr[idx++] = i; } } - r_ret=arr; + r_ret = arr; } break; default: { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=3; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = 3; + r_ret = Variant(); } break; } @@ -837,12 +823,12 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va } break; case RESOURCE_LOAD: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_ret = Variant(); } else { - r_ret=ResourceLoader::load(*p_args[0]); + r_ret = ResourceLoader::load(*p_args[0]); } } break; @@ -850,91 +836,85 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()==Variant::NIL) { - r_ret=Variant(); - } else if (p_args[0]->get_type()!=Variant::OBJECT) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_ret=Variant(); + if (p_args[0]->get_type() == Variant::NIL) { + r_ret = Variant(); + } else if (p_args[0]->get_type() != Variant::OBJECT) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_ret = Variant(); } else { Object *obj = *p_args[0]; if (!obj) { - r_ret=Variant(); + r_ret = Variant(); - } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language()!=GDScriptLanguage::get_singleton()) { + } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=RTR("Not a script with an instance"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = RTR("Not a script with an instance"); return; } else { - GDInstance *ins = static_cast<GDInstance*>(obj->get_script_instance()); + GDInstance *ins = static_cast<GDInstance *>(obj->get_script_instance()); Ref<GDScript> base = ins->get_script(); if (base.is_null()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=RTR("Not based on a script"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = RTR("Not based on a script"); return; - } - GDScript *p = base.ptr(); Vector<StringName> sname; - while(p->_owner) { + while (p->_owner) { sname.push_back(p->name); - p=p->_owner; + p = p->_owner; } sname.invert(); - if (!p->path.is_resource_file()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = Variant(); - - r_ret=RTR("Not based on a resource file"); + r_ret = RTR("Not based on a resource file"); return; } - NodePath cp(sname,Vector<StringName>(),false); + NodePath cp(sname, Vector<StringName>(), false); Dictionary d(true); - d["@subpath"]=cp; - d["@path"]=p->path; - + d["@subpath"] = cp; + d["@path"] = p->path; p = base.ptr(); - while(p) { + while (p) { - for(Set<StringName>::Element *E=p->members.front();E;E=E->next()) { + for (Set<StringName>::Element *E = p->members.front(); E; E = E->next()) { Variant value; - if (ins->get(E->get(),value)) { + if (ins->get(E->get(), value)) { String k = E->get(); if (!d.has(k)) { - d[k]=value; + d[k] = value; } } } - p=p->_base; + p = p->_base; } - r_ret=d; - + r_ret = d; } } @@ -943,12 +923,12 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::DICTIONARY) { + if (p_args[0]->get_type() != Variant::DICTIONARY) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = Variant(); return; } @@ -957,10 +937,10 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va if (!d.has("@path")) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=RTR("Invalid instance dictionary format (missing @path)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = RTR("Invalid instance dictionary format (missing @path)"); return; } @@ -968,10 +948,10 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va Ref<Script> scr = ResourceLoader::load(d["@path"]); if (!scr.is_valid()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=RTR("Invalid instance dictionary format (can't load script at @path)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = RTR("Invalid instance dictionary format (can't load script at @path)"); return; } @@ -979,40 +959,40 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va if (!gdscr.is_valid()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=Variant(); - r_ret=RTR("Invalid instance dictionary format (invalid script at @path)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); + r_ret = RTR("Invalid instance dictionary format (invalid script at @path)"); return; } NodePath sub; if (d.has("@subpath")) { - sub=d["@subpath"]; + sub = d["@subpath"]; } - for(int i=0;i<sub.get_name_count();i++) { + for (int i = 0; i < sub.get_name_count(); i++) { - gdscr = gdscr->subclasses[ sub.get_name(i)]; + gdscr = gdscr->subclasses[sub.get_name(i)]; if (!gdscr.is_valid()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=Variant(); - r_ret=RTR("Invalid instance dictionary (invalid subclasses)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); + r_ret = RTR("Invalid instance dictionary (invalid subclasses)"); return; } } - r_ret = gdscr->_new(NULL,0,r_error); + r_ret = gdscr->_new(NULL, 0, r_error); - GDInstance *ins = static_cast<GDInstance*>(static_cast<Object*>(r_ret)->get_script_instance()); + GDInstance *ins = static_cast<GDInstance *>(static_cast<Object *>(r_ret)->get_script_instance()); Ref<GDScript> gd_ref = ins->get_script(); - for(Map<StringName,GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) { - if(d.has(E->key())) { + for (Map<StringName, GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) { + if (d.has(E->key())) { ins->members[E->get().index] = d[E->key()]; } } @@ -1021,22 +1001,22 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va case HASH: { VALIDATE_ARG_COUNT(1); - r_ret=p_args[0]->hash(); + r_ret = p_args[0]->hash(); } break; case COLOR8: { - if (p_arg_count<3) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=3; - r_ret=Variant(); + if (p_arg_count < 3) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 3; + r_ret = Variant(); return; } - if (p_arg_count>4) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=4; - r_ret=Variant(); + if (p_arg_count > 4) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = 4; + r_ret = Variant(); return; } @@ -1045,78 +1025,76 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - Color color((float)*p_args[0]/255.0f,(float)*p_args[1]/255.0f,(float)*p_args[2]/255.0f); + Color color((float)*p_args[0] / 255.0f, (float)*p_args[1] / 255.0f, (float)*p_args[2] / 255.0f); - if (p_arg_count==4) { + if (p_arg_count == 4) { VALIDATE_ARG_NUM(3); - color.a=(float)*p_args[3]/255.0f; + color.a = (float)*p_args[3] / 255.0f; } - r_ret=color; + r_ret = color; } break; case COLORN: { - if (p_arg_count<1) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=1; - r_ret=Variant(); + if (p_arg_count < 1) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; + r_ret = Variant(); return; } - if (p_arg_count>2) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=2; - r_ret=Variant(); + if (p_arg_count > 2) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = 2; + r_ret = Variant(); return; } - - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_ret=Variant(); + + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_ret = Variant(); } else { Color color = Color::named(*p_args[0]); - if (p_arg_count==2) { + if (p_arg_count == 2) { VALIDATE_ARG_NUM(1); - color.a=*p_args[1]; + color.a = *p_args[1]; } - r_ret=color; + r_ret = color; } } break; case PRINT_STACK: { - ScriptLanguage* script = GDScriptLanguage::get_singleton(); - for (int i=0; i < script->debug_get_stack_level_count(); i++) { + ScriptLanguage *script = GDScriptLanguage::get_singleton(); + for (int i = 0; i < script->debug_get_stack_level_count(); i++) { - print_line("Frame "+itos(i)+" - "+script->debug_get_stack_level_source(i)+":"+itos(script->debug_get_stack_level_line(i))+" in function '"+script->debug_get_stack_level_function(i)+"'"); + print_line("Frame " + itos(i) + " - " + script->debug_get_stack_level_source(i) + ":" + itos(script->debug_get_stack_level_line(i)) + " in function '" + script->debug_get_stack_level_function(i) + "'"); }; } break; case INSTANCE_FROM_ID: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::INT && p_args[0]->get_type()!=Variant::REAL) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::INT; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::INT && p_args[0]->get_type() != Variant::REAL) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::INT; + r_ret = Variant(); break; } - uint32_t id=*p_args[0]; - r_ret=ObjectDB::get_instance(id); + uint32_t id = *p_args[0]; + r_ret = ObjectDB::get_instance(id); } break; case FUNC_MAX: { ERR_FAIL(); } break; - } - } bool GDFunctions::is_deterministic(Function p_func) { @@ -1124,7 +1102,7 @@ bool GDFunctions::is_deterministic(Function p_func) { //man i couldn't have chosen a worse function name, //way too controversial.. - switch(p_func) { + switch (p_func) { case MATH_SIN: case MATH_COS: @@ -1167,16 +1145,13 @@ bool GDFunctions::is_deterministic(Function p_func) { case TYPE_EXISTS: case TEXT_STR: case COLOR8: -// enable for debug only, otherwise not desirable - case GEN_RANGE: + // enable for debug only, otherwise not desirable - case GEN_RANGE: return true; default: return false; - } return false; - - } MethodInfo GDFunctions::get_info(Function p_func) { @@ -1184,376 +1159,376 @@ MethodInfo GDFunctions::get_info(Function p_func) { #ifdef TOOLS_ENABLED //using a switch, so the compiler generates a jumptable - switch(p_func) { + switch (p_func) { case MATH_SIN: { - MethodInfo mi("sin",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sin", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_COS: { - MethodInfo mi("cos",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("cos", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_TAN: { - MethodInfo mi("tan",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("tan", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SINH: { - MethodInfo mi("sinh",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sinh", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_COSH: { - MethodInfo mi("cosh",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("cosh", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_TANH: { - MethodInfo mi("tanh",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("tanh", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ASIN: { - MethodInfo mi("asin",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("asin", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ACOS: { - MethodInfo mi("acos",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("acos", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ATAN: { - MethodInfo mi("atan",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("atan", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ATAN2: { - MethodInfo mi("atan2",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("atan2", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SQRT: { - MethodInfo mi("sqrt",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sqrt", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FMOD: { - MethodInfo mi("fmod",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FPOSMOD: { - MethodInfo mi("fposmod",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FLOOR: { - MethodInfo mi("floor",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("floor", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; - } break; + } break; case MATH_CEIL: { - MethodInfo mi("ceil",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("ceil", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ROUND: { - MethodInfo mi("round",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("round", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ABS: { - MethodInfo mi("abs",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("abs", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SIGN: { - MethodInfo mi("sign",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sign", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_POW: { - MethodInfo mi("pow",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("pow", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_LOG: { - MethodInfo mi("log",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("log", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_EXP: { - MethodInfo mi("exp",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("exp", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ISNAN: { - MethodInfo mi("is_nan",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("is_nan", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ISINF: { - MethodInfo mi("is_inf",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("is_inf", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_EASE: { - MethodInfo mi("ease",PropertyInfo(Variant::REAL,"s"),PropertyInfo(Variant::REAL,"curve")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("ease", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "curve")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_DECIMALS: { - MethodInfo mi("decimals",PropertyInfo(Variant::REAL,"step")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("decimals", PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_STEPIFY: { - MethodInfo mi("stepify",PropertyInfo(Variant::REAL,"s"),PropertyInfo(Variant::REAL,"step")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("stepify", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_LERP: { - MethodInfo mi("lerp",PropertyInfo(Variant::REAL,"from"),PropertyInfo(Variant::REAL,"to"), PropertyInfo(Variant::REAL,"weight")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("lerp", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "weight")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_DECTIME: { - MethodInfo mi("dectime",PropertyInfo(Variant::REAL,"value"),PropertyInfo(Variant::REAL,"amount"),PropertyInfo(Variant::REAL,"step")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("dectime", PropertyInfo(Variant::REAL, "value"), PropertyInfo(Variant::REAL, "amount"), PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_RANDOMIZE: { MethodInfo mi("randomize"); - mi.return_val.type=Variant::NIL; + mi.return_val.type = Variant::NIL; return mi; } break; case MATH_RAND: { MethodInfo mi("randi"); - mi.return_val.type=Variant::INT; + mi.return_val.type = Variant::INT; return mi; } break; case MATH_RANDF: { MethodInfo mi("randf"); - mi.return_val.type=Variant::REAL; + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_RANDOM: { - MethodInfo mi("rand_range",PropertyInfo(Variant::REAL,"from"),PropertyInfo(Variant::REAL,"to")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("rand_range", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SEED: { - MethodInfo mi("seed",PropertyInfo(Variant::INT,"seed")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("seed", PropertyInfo(Variant::INT, "seed")); + mi.return_val.type = Variant::NIL; return mi; } break; case MATH_RANDSEED: { - MethodInfo mi("rand_seed",PropertyInfo(Variant::INT,"seed")); - mi.return_val.type=Variant::ARRAY; + MethodInfo mi("rand_seed", PropertyInfo(Variant::INT, "seed")); + mi.return_val.type = Variant::ARRAY; return mi; } break; case MATH_DEG2RAD: { - MethodInfo mi("deg2rad",PropertyInfo(Variant::REAL,"deg")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("deg2rad", PropertyInfo(Variant::REAL, "deg")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_RAD2DEG: { - MethodInfo mi("rad2deg",PropertyInfo(Variant::REAL,"rad")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("rad2deg", PropertyInfo(Variant::REAL, "rad")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_LINEAR2DB: { - MethodInfo mi("linear2db",PropertyInfo(Variant::REAL,"nrg")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("linear2db", PropertyInfo(Variant::REAL, "nrg")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_DB2LINEAR: { - MethodInfo mi("db2linear",PropertyInfo(Variant::REAL,"db")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("db2linear", PropertyInfo(Variant::REAL, "db")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_MAX: { - MethodInfo mi("max",PropertyInfo(Variant::REAL,"a"),PropertyInfo(Variant::REAL,"b")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("max", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_MIN: { - MethodInfo mi("min",PropertyInfo(Variant::REAL,"a"),PropertyInfo(Variant::REAL,"b")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("min", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_CLAMP: { - MethodInfo mi("clamp",PropertyInfo(Variant::REAL,"val"),PropertyInfo(Variant::REAL,"min"),PropertyInfo(Variant::REAL,"max")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("clamp", PropertyInfo(Variant::REAL, "val"), PropertyInfo(Variant::REAL, "min"), PropertyInfo(Variant::REAL, "max")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_NEAREST_PO2: { - MethodInfo mi("nearest_po2",PropertyInfo(Variant::INT,"val")); - mi.return_val.type=Variant::INT; + MethodInfo mi("nearest_po2", PropertyInfo(Variant::INT, "val")); + mi.return_val.type = Variant::INT; return mi; } break; case OBJ_WEAKREF: { - MethodInfo mi("weakref",PropertyInfo(Variant::OBJECT,"obj")); - mi.return_val.type=Variant::OBJECT; - mi.return_val.name="WeakRef"; + MethodInfo mi("weakref", PropertyInfo(Variant::OBJECT, "obj")); + mi.return_val.type = Variant::OBJECT; + mi.return_val.name = "WeakRef"; return mi; } break; case FUNC_FUNCREF: { - MethodInfo mi("funcref",PropertyInfo(Variant::OBJECT,"instance"),PropertyInfo(Variant::STRING,"funcname")); - mi.return_val.type=Variant::OBJECT; - mi.return_val.name="FuncRef"; + MethodInfo mi("funcref", PropertyInfo(Variant::OBJECT, "instance"), PropertyInfo(Variant::STRING, "funcname")); + mi.return_val.type = Variant::OBJECT; + mi.return_val.name = "FuncRef"; return mi; } break; case TYPE_CONVERT: { - MethodInfo mi("convert",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::INT,"type")); - mi.return_val.type=Variant::OBJECT; + MethodInfo mi("convert", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::INT, "type")); + mi.return_val.type = Variant::OBJECT; return mi; } break; case TYPE_OF: { - MethodInfo mi("typeof",PropertyInfo(Variant::NIL,"what")); - mi.return_val.type=Variant::INT; + MethodInfo mi("typeof", PropertyInfo(Variant::NIL, "what")); + mi.return_val.type = Variant::INT; return mi; } break; case TYPE_EXISTS: { - MethodInfo mi("type_exists",PropertyInfo(Variant::STRING,"type")); - mi.return_val.type=Variant::BOOL; + MethodInfo mi("type_exists", PropertyInfo(Variant::STRING, "type")); + mi.return_val.type = Variant::BOOL; return mi; } break; case TEXT_STR: { - MethodInfo mi("str",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("str", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::STRING; return mi; } break; case TEXT_PRINT: { - MethodInfo mi("print",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("print", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINT_TABBED: { - MethodInfo mi("printt",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("printt", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINT_SPACED: { - MethodInfo mi("prints",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("prints", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINTERR: { - MethodInfo mi("printerr",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("printerr", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINTRAW: { - MethodInfo mi("printraw",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("printraw", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case VAR_TO_STR: { - MethodInfo mi("var2str",PropertyInfo(Variant::NIL,"var")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("var2str", PropertyInfo(Variant::NIL, "var")); + mi.return_val.type = Variant::STRING; return mi; } break; case STR_TO_VAR: { - MethodInfo mi("str2var:Variant",PropertyInfo(Variant::STRING,"string")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("str2var:Variant", PropertyInfo(Variant::STRING, "string")); + mi.return_val.type = Variant::NIL; return mi; } break; case VAR_TO_BYTES: { - MethodInfo mi("var2bytes",PropertyInfo(Variant::NIL,"var")); - mi.return_val.type=Variant::RAW_ARRAY; + MethodInfo mi("var2bytes", PropertyInfo(Variant::NIL, "var")); + mi.return_val.type = Variant::RAW_ARRAY; return mi; } break; case BYTES_TO_VAR: { - MethodInfo mi("bytes2var:Variant",PropertyInfo(Variant::RAW_ARRAY,"bytes")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("bytes2var:Variant", PropertyInfo(Variant::RAW_ARRAY, "bytes")); + mi.return_val.type = Variant::NIL; return mi; } break; case GEN_RANGE: { - MethodInfo mi("range",PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::ARRAY; + MethodInfo mi("range", PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::ARRAY; return mi; } break; case RESOURCE_LOAD: { - MethodInfo mi("load",PropertyInfo(Variant::STRING,"path")); - mi.return_val.type=Variant::OBJECT; - mi.return_val.name="Resource"; + MethodInfo mi("load", PropertyInfo(Variant::STRING, "path")); + mi.return_val.type = Variant::OBJECT; + mi.return_val.name = "Resource"; return mi; } break; case INST2DICT: { - MethodInfo mi("inst2dict",PropertyInfo(Variant::OBJECT,"inst")); - mi.return_val.type=Variant::DICTIONARY; + MethodInfo mi("inst2dict", PropertyInfo(Variant::OBJECT, "inst")); + mi.return_val.type = Variant::DICTIONARY; return mi; } break; case DICT2INST: { - MethodInfo mi("dict2inst",PropertyInfo(Variant::DICTIONARY,"dict")); - mi.return_val.type=Variant::OBJECT; + MethodInfo mi("dict2inst", PropertyInfo(Variant::DICTIONARY, "dict")); + mi.return_val.type = Variant::OBJECT; return mi; } break; case HASH: { - MethodInfo mi("hash",PropertyInfo(Variant::NIL,"var:Variant")); - mi.return_val.type=Variant::INT; + MethodInfo mi("hash", PropertyInfo(Variant::NIL, "var:Variant")); + mi.return_val.type = Variant::INT; return mi; } break; case COLOR8: { - MethodInfo mi("Color8",PropertyInfo(Variant::INT,"r8"),PropertyInfo(Variant::INT,"g8"),PropertyInfo(Variant::INT,"b8"),PropertyInfo(Variant::INT,"a8")); - mi.return_val.type=Variant::COLOR; + MethodInfo mi("Color8", PropertyInfo(Variant::INT, "r8"), PropertyInfo(Variant::INT, "g8"), PropertyInfo(Variant::INT, "b8"), PropertyInfo(Variant::INT, "a8")); + mi.return_val.type = Variant::COLOR; return mi; } break; case COLORN: { - MethodInfo mi("ColorN",PropertyInfo(Variant::STRING,"name"),PropertyInfo(Variant::REAL,"alpha")); - mi.return_val.type=Variant::COLOR; + MethodInfo mi("ColorN", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::REAL, "alpha")); + mi.return_val.type = Variant::COLOR; return mi; } break; case PRINT_STACK: { MethodInfo mi("print_stack"); - mi.return_val.type=Variant::NIL; + mi.return_val.type = Variant::NIL; return mi; } break; case INSTANCE_FROM_ID: { - MethodInfo mi("instance_from_id",PropertyInfo(Variant::INT,"instance_id")); - mi.return_val.type=Variant::OBJECT; + MethodInfo mi("instance_from_id", PropertyInfo(Variant::INT, "instance_id")); + mi.return_val.type = Variant::OBJECT; return mi; } break; @@ -1561,7 +1536,6 @@ MethodInfo GDFunctions::get_info(Function p_func) { ERR_FAIL_V(MethodInfo()); } break; - } #endif diff --git a/modules/gdscript/gd_functions.h b/modules/gdscript/gd_functions.h index 74c119918..66dae42d4 100644 --- a/modules/gdscript/gd_functions.h +++ b/modules/gdscript/gd_functions.h @@ -33,7 +33,6 @@ class GDFunctions { public: - enum Function { MATH_SIN, MATH_COS, @@ -106,10 +105,9 @@ public: }; static const char *get_func_name(Function p_func); - static void call(Function p_func,const Variant **p_args,int p_arg_count,Variant &r_ret,Variant::CallError &r_error); + static void call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Variant::CallError &r_error); static bool is_deterministic(Function p_func); static MethodInfo get_info(Function p_func); - }; #endif // GD_FUNCTIONS_H diff --git a/modules/gdscript/gd_parser.cpp b/modules/gdscript/gd_parser.cpp index 96c279e4f..38b1fc4df 100644 --- a/modules/gdscript/gd_parser.cpp +++ b/modules/gdscript/gd_parser.cpp @@ -27,74 +27,72 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_parser.h" -#include "print_string.h" +#include "gd_script.h" #include "io/resource_loader.h" #include "os/file_access.h" +#include "print_string.h" #include "script_language.h" -#include "gd_script.h" -template<class T> -T* GDParser::alloc_node() { +template <class T> +T *GDParser::alloc_node() { - T *t = memnew( T); + T *t = memnew(T); - t->next=list; - list=t; + t->next = list; + list = t; if (!head) - head=t; + head = t; - t->line=tokenizer->get_token_line(); - t->column=tokenizer->get_token_column(); + t->line = tokenizer->get_token_line(); + t->column = tokenizer->get_token_column(); return t; - } bool GDParser::_end_statement() { - if (tokenizer->get_token()==GDTokenizer::TK_SEMICOLON) { + if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON) { tokenizer->advance(); return true; //handle next - } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE || tokenizer->get_token()==GDTokenizer::TK_EOF) { + } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE || tokenizer->get_token() == GDTokenizer::TK_EOF) { return true; //will be handled properly } return false; } -bool GDParser::_enter_indent_block(BlockNode* p_block) { - +bool GDParser::_enter_indent_block(BlockNode *p_block) { - if (tokenizer->get_token()!=GDTokenizer::TK_COLON) { + if (tokenizer->get_token() != GDTokenizer::TK_COLON) { // report location at the previous token (on the previous line) int error_line = tokenizer->get_token_line(-1); int error_column = tokenizer->get_token_column(-1); - _set_error("':' expected at end of line.",error_line,error_column); + _set_error("':' expected at end of line.", error_line, error_column); return false; } tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token() != GDTokenizer::TK_NEWLINE) { // be more python-like int current = tab_level.back()->get(); - tab_level.push_back(current+1); + tab_level.push_back(current + 1); return true; //_set_error("newline expected after ':'."); //return false; } - while(true) { + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token() != GDTokenizer::TK_NEWLINE) { return false; //wtf - } else if (tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE) { + } else if (tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE) { int indent = tokenizer->get_token_line_indent(); int current = tab_level.back()->get(); - if (indent<=current) { - print_line("current: "+itos(current)+" indent: "+itos(indent)); + if (indent <= current) { + print_line("current: " + itos(current) + " indent: " + itos(indent)); print_line("less than current"); return false; } @@ -106,52 +104,51 @@ bool GDParser::_enter_indent_block(BlockNode* p_block) { } else if (p_block) { NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=tokenizer->get_token_line(); + nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); - } tokenizer->advance(); // go to next newline } } -bool GDParser::_parse_arguments(Node* p_parent,Vector<Node*>& p_args,bool p_static,bool p_can_codecomplete) { +bool GDParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete) { - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); } else { - parenthesis ++; - int argidx=0; + parenthesis++; + int argidx = 0; - while(true) { + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { _make_completable_call(argidx); - completion_node=p_parent; - } else if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING && tokenizer->get_token(1)==GDTokenizer::TK_CURSOR) { + completion_node = p_parent; + } else if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING && tokenizer->get_token(1) == GDTokenizer::TK_CURSOR) { //completing a string argument.. - completion_cursor=tokenizer->get_token_constant(); + completion_cursor = tokenizer->get_token_constant(); _make_completable_call(argidx); - completion_node=p_parent; + completion_node = p_parent; tokenizer->advance(1); return false; } - Node*arg = _parse_expression(p_parent,p_static); + Node *arg = _parse_expression(p_parent, p_static); if (!arg) return false; p_args.push_back(arg); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); break; - } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { - if (tokenizer->get_token(1)==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token(1) == GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expression expected"); return false; @@ -164,51 +161,46 @@ bool GDParser::_parse_arguments(Node* p_parent,Vector<Node*>& p_args,bool p_stat _set_error("Expected ',' or ')'"); return false; } - } - parenthesis --; + parenthesis--; } return true; - } - void GDParser::_make_completable_call(int p_arg) { - completion_cursor=StringName(); - completion_type=COMPLETION_CALL_ARGUMENTS; - completion_class=current_class; - completion_function=current_function; - completion_line=tokenizer->get_token_line(); - completion_argument=p_arg; - completion_block=current_block; - completion_found=true; + completion_cursor = StringName(); + completion_type = COMPLETION_CALL_ARGUMENTS; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_argument = p_arg; + completion_block = current_block; + completion_found = true; tokenizer->advance(); - } +bool GDParser::_get_completable_identifier(CompletionType p_type, StringName &identifier) { -bool GDParser::_get_completable_identifier(CompletionType p_type,StringName& identifier) { - - identifier=StringName(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { - identifier=tokenizer->get_token_identifier(); + identifier = StringName(); + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { + identifier = tokenizer->get_token_identifier(); tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { - completion_cursor=identifier; - completion_type=p_type; - completion_class=current_class; - completion_function=current_function; - completion_line=tokenizer->get_token_line(); - completion_block=current_block; - completion_found=true; + completion_cursor = identifier; + completion_type = p_type; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_block = current_block; + completion_found = true; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { - identifier=identifier.operator String() + tokenizer->get_token_identifier().operator String(); + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { + identifier = identifier.operator String() + tokenizer->get_token_identifier().operator String(); tokenizer->advance(); } @@ -218,72 +210,70 @@ bool GDParser::_get_completable_identifier(CompletionType p_type,StringName& ide return false; } +GDParser::Node *GDParser::_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign, bool p_parsing_constant) { -GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_allow_assign,bool p_parsing_constant) { - -// Vector<Node*> expressions; -// Vector<OperatorNode::Operator> operators; + // Vector<Node*> expressions; + // Vector<OperatorNode::Operator> operators; Vector<Expression> expression; - Node *expr=NULL; + Node *expr = NULL; int op_line = tokenizer->get_token_line(); // when operators are created at the bottom, the line might have been changed (\n found) - while(true) { - + while (true) { /*****************/ /* Parse Operand */ /*****************/ - if (parenthesis>0) { + if (parenthesis > 0) { //remove empty space (only allowed if inside parenthesis - while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } } - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { //subexpression () tokenizer->advance(); parenthesis++; - Node* subexpr = _parse_expression(p_parent,p_static,p_allow_assign,p_parsing_constant); + Node *subexpr = _parse_expression(p_parent, p_static, p_allow_assign, p_parsing_constant); parenthesis--; if (!subexpr) return NULL; - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in expression"); return NULL; } tokenizer->advance(); - expr=subexpr; - } else if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + expr = subexpr; + } else if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { tokenizer->advance(); continue; //no point in cursor in the middle of expression - } else if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value=tokenizer->get_token_constant(); + constant->value = tokenizer->get_token_constant(); tokenizer->advance(); - expr=constant; - } else if (tokenizer->get_token()==GDTokenizer::TK_CONST_PI) { + expr = constant; + } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_PI) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value=Math_PI; + constant->value = Math_PI; tokenizer->advance(); - expr=constant; - } else if (tokenizer->get_token()==GDTokenizer::TK_PR_PRELOAD) { + expr = constant; + } else if (tokenizer->get_token() == GDTokenizer::TK_PR_PRELOAD) { //constant defined by tokenizer tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after 'preload'"); return NULL; } @@ -297,18 +287,18 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ Node *subexpr = _parse_and_reduce_expression(p_parent, p_static); if (subexpr) { if (subexpr->type == Node::TYPE_CONSTANT) { - cn = static_cast<ConstantNode*>(subexpr); + cn = static_cast<ConstantNode *>(subexpr); found_constant = true; } if (subexpr->type == Node::TYPE_IDENTIFIER) { - IdentifierNode *in = static_cast<IdentifierNode*>(subexpr); + IdentifierNode *in = static_cast<IdentifierNode *>(subexpr); Vector<ClassNode::Constant> ce = current_class->constant_expressions; // Try to find the constant expression by the identifier - for(int i=0; i < ce.size(); ++i){ - if(ce[i].identifier == in->name) { - if(ce[i].expression->type == Node::TYPE_CONSTANT) { - cn = static_cast<ConstantNode*>(ce[i].expression); + for (int i = 0; i < ce.size(); ++i) { + if (ce[i].identifier == in->name) { + if (ce[i].expression->type == Node::TYPE_CONSTANT) { + cn = static_cast<ConstantNode *>(ce[i].expression); found_constant = true; } } @@ -317,7 +307,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ if (found_constant && cn->value.get_type() == Variant::STRING) { valid = true; - path = (String) cn->value; + path = (String)cn->value; } } @@ -326,17 +316,15 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - if (!path.is_abs_path() && base_path!="") - path=base_path+"/"+path; - path = path.replace("///","//").simplify_path(); - if (path==self_path) { + if (!path.is_abs_path() && base_path != "") + path = base_path + "/" + path; + path = path.replace("///", "//").simplify_path(); + if (path == self_path) { _set_error("Can't preload itself (use 'get_script()')."); return NULL; - } - Ref<Resource> res; if (!validating) { @@ -347,33 +335,33 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ res = ResourceLoader::load(path); } if (!res.is_valid()) { - _set_error("Can't preload resource at path: "+path); + _set_error("Can't preload resource at path: " + path); return NULL; } } else { if (!FileAccess::exists(path)) { - _set_error("Can't preload resource at path: "+path); + _set_error("Can't preload resource at path: " + path); return NULL; } } - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' after 'preload' path"); return NULL; } ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value=res; + constant->value = res; tokenizer->advance(); - expr=constant; - } else if (tokenizer->get_token()==GDTokenizer::TK_PR_YIELD) { + expr = constant; + } else if (tokenizer->get_token() == GDTokenizer::TK_PR_YIELD) { //constant defined by tokenizer tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after 'yield'"); return NULL; } @@ -381,50 +369,49 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ tokenizer->advance(); OperatorNode *yield = alloc_node<OperatorNode>(); - yield->op=OperatorNode::OP_YIELD; + yield->op = OperatorNode::OP_YIELD; - while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { - expr=yield; + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { + expr = yield; tokenizer->advance(); } else { - parenthesis ++; + parenthesis++; - Node *object = _parse_and_reduce_expression(p_parent,p_static); + Node *object = _parse_and_reduce_expression(p_parent, p_static); if (!object) return NULL; yield->arguments.push_back(object); - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { _set_error("Expected ',' after first argument of 'yield'"); return NULL; } tokenizer->advance(); - Node *signal = _parse_and_reduce_expression(p_parent,p_static); + Node *signal = _parse_and_reduce_expression(p_parent, p_static); if (!signal) return NULL; yield->arguments.push_back(signal); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' after second argument of 'yield'"); return NULL; } - parenthesis --; + parenthesis--; tokenizer->advance(); - expr=yield; + expr = yield; } - - } else if (tokenizer->get_token()==GDTokenizer::TK_SELF) { + } else if (tokenizer->get_token() == GDTokenizer::TK_SELF) { if (p_static) { _set_error("'self'' not allowed in static function or constant expression"); @@ -433,51 +420,50 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ //constant defined by tokenizer SelfNode *self = alloc_node<SelfNode>(); tokenizer->advance(); - expr=self; - } else if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1)==GDTokenizer::TK_PERIOD) { + expr = self; + } else if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1) == GDTokenizer::TK_PERIOD) { Variant::Type bi_type = tokenizer->get_token_type(); tokenizer->advance(2); StringName identifier; - if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT,identifier)) { + if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT, identifier)) { - completion_built_in_constant=bi_type; + completion_built_in_constant = bi_type; } - if (identifier==StringName()) { + if (identifier == StringName()) { _set_error("Built-in type constant expected after '.'"); return NULL; } - if (!Variant::has_numeric_constant(bi_type,identifier)) { + if (!Variant::has_numeric_constant(bi_type, identifier)) { - _set_error("Static constant '"+identifier.operator String()+"' not present in built-in type "+Variant::get_type_name(bi_type)+"."); + _set_error("Static constant '" + identifier.operator String() + "' not present in built-in type " + Variant::get_type_name(bi_type) + "."); return NULL; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=Variant::get_numeric_constant_value(bi_type,identifier); - expr=cn; + cn->value = Variant::get_numeric_constant_value(bi_type, identifier); + expr = cn; - - } else if (tokenizer->get_token(1)==GDTokenizer::TK_PARENTHESIS_OPEN && (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE || tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER || tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC)) { + } else if (tokenizer->get_token(1) == GDTokenizer::TK_PARENTHESIS_OPEN && (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE || tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER || tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC)) { //function or constructor OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_CALL; + op->op = OperatorNode::OP_CALL; - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) { + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) { TypeNode *tn = alloc_node<TypeNode>(); - tn->vtype=tokenizer->get_token_type(); + tn->vtype = tokenizer->get_token_type(); op->arguments.push_back(tn); tokenizer->advance(2); - } else if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC) { BuiltInFunctionNode *bn = alloc_node<BuiltInFunctionNode>(); - bn->function=tokenizer->get_token_built_in_func(); + bn->function = tokenizer->get_token_built_in_func(); op->arguments.push_back(bn); tokenizer->advance(2); } else { @@ -486,43 +472,40 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ op->arguments.push_back(self); StringName identifier; - if (_get_completable_identifier(COMPLETION_FUNCTION,identifier)) { - + if (_get_completable_identifier(COMPLETION_FUNCTION, identifier)) { } - IdentifierNode* id = alloc_node<IdentifierNode>(); - id->name=identifier; + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->name = identifier; op->arguments.push_back(id); tokenizer->advance(1); } - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { _make_completable_call(0); - completion_node=op; - + completion_node = op; } - if (!_parse_arguments(op,op->arguments,p_static,true)) + if (!_parse_arguments(op, op->arguments, p_static, true)) return NULL; - expr=op; + expr = op; - } else if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { + } else if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { //identifier (reference) - const ClassNode* cln = current_class; - bool bfn = false; - StringName identifier; - if (_get_completable_identifier(COMPLETION_IDENTIFIER,identifier)) { - + const ClassNode *cln = current_class; + bool bfn = false; + StringName identifier; + if (_get_completable_identifier(COMPLETION_IDENTIFIER, identifier)) { } if (p_parsing_constant) { - for( int i=0; i<cln->constant_expressions.size(); ++i ) { + for (int i = 0; i < cln->constant_expressions.size(); ++i) { - if( cln->constant_expressions[i].identifier == identifier ) { + if (cln->constant_expressions[i].identifier == identifier) { expr = cln->constant_expressions[i].expression; - bfn = true; + bfn = true; break; } } @@ -530,36 +513,35 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { //check from constants ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value = GDScriptLanguage::get_singleton()->get_global_array()[ GDScriptLanguage::get_singleton()->get_global_map()[identifier] ]; - expr=constant; + constant->value = GDScriptLanguage::get_singleton()->get_global_array()[GDScriptLanguage::get_singleton()->get_global_map()[identifier]]; + expr = constant; bfn = true; } } - if ( !bfn ) { + if (!bfn) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; expr = id; } - } else if (/*tokenizer->get_token()==GDTokenizer::TK_OP_ADD ||*/ tokenizer->get_token()==GDTokenizer::TK_OP_SUB || tokenizer->get_token()==GDTokenizer::TK_OP_NOT || tokenizer->get_token()==GDTokenizer::TK_OP_BIT_INVERT) { + } else if (/*tokenizer->get_token()==GDTokenizer::TK_OP_ADD ||*/ tokenizer->get_token() == GDTokenizer::TK_OP_SUB || tokenizer->get_token() == GDTokenizer::TK_OP_NOT || tokenizer->get_token() == GDTokenizer::TK_OP_BIT_INVERT) { //single prefix operators like !expr -expr ++expr --expr alloc_node<OperatorNode>(); Expression e; - e.is_op=true; + e.is_op = true; - switch(tokenizer->get_token()) { - case GDTokenizer::TK_OP_SUB: e.op=OperatorNode::OP_NEG; break; - case GDTokenizer::TK_OP_NOT: e.op=OperatorNode::OP_NOT; break; - case GDTokenizer::TK_OP_BIT_INVERT: e.op=OperatorNode::OP_BIT_INVERT; break; + switch (tokenizer->get_token()) { + case GDTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break; + case GDTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break; + case GDTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break; default: {} } - tokenizer->advance(); - if (e.op!=OperatorNode::OP_NOT && tokenizer->get_token()==GDTokenizer::TK_OP_NOT) { + if (e.op != OperatorNode::OP_NOT && tokenizer->get_token() == GDTokenizer::TK_OP_NOT) { _set_error("Misplaced 'not'."); return NULL; } @@ -574,33 +556,33 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ op->arguments.push_back(subexpr); expr=op;*/ - } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_OPEN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_OPEN) { // array tokenizer->advance(); ArrayNode *arr = alloc_node<ArrayNode>(); - bool expecting_comma=false; + bool expecting_comma = false; - while(true) { + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_EOF) { + if (tokenizer->get_token() == GDTokenizer::TK_EOF) { _set_error("Unterminated array"); return NULL; - } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_CLOSE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(); break; - } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); //ignore newline - } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { if (!expecting_comma) { _set_error("expression or ']' expected"); return NULL; } - expecting_comma=false; + expecting_comma = false; tokenizer->advance(); //ignore newline } else { //parse expression @@ -608,16 +590,16 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ _set_error("',' or ']' expected"); return NULL; } - Node *n = _parse_expression(arr,p_static,p_allow_assign,p_parsing_constant); + Node *n = _parse_expression(arr, p_static, p_allow_assign, p_parsing_constant); if (!n) return NULL; arr->elements.push_back(n); - expecting_comma=true; + expecting_comma = true; } } - expr=arr; - } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_OPEN) { + expr = arr; + } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_OPEN) { // array tokenizer->advance(); @@ -632,140 +614,137 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ }; - Node *key=NULL; + Node *key = NULL; - DictExpect expecting=DICT_EXPECT_KEY; + DictExpect expecting = DICT_EXPECT_KEY; - while(true) { + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_EOF) { + if (tokenizer->get_token() == GDTokenizer::TK_EOF) { _set_error("Unterminated dictionary"); return NULL; - } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_CLOSE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) { - if (expecting==DICT_EXPECT_COLON) { + if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return NULL; } - if (expecting==DICT_EXPECT_VALUE) { + if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return NULL; } tokenizer->advance(); break; - } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); //ignore newline - } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { - if (expecting==DICT_EXPECT_KEY) { + if (expecting == DICT_EXPECT_KEY) { _set_error("key or '}' expected"); return NULL; } - if (expecting==DICT_EXPECT_VALUE) { + if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return NULL; } - if (expecting==DICT_EXPECT_COLON) { + if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return NULL; } - expecting=DICT_EXPECT_KEY; + expecting = DICT_EXPECT_KEY; tokenizer->advance(); //ignore newline - } else if (tokenizer->get_token()==GDTokenizer::TK_COLON) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COLON) { - if (expecting==DICT_EXPECT_KEY) { + if (expecting == DICT_EXPECT_KEY) { _set_error("key or '}' expected"); return NULL; } - if (expecting==DICT_EXPECT_VALUE) { + if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return NULL; } - if (expecting==DICT_EXPECT_COMMA) { + if (expecting == DICT_EXPECT_COMMA) { _set_error("',' or '}' expected"); return NULL; } - expecting=DICT_EXPECT_VALUE; + expecting = DICT_EXPECT_VALUE; tokenizer->advance(); //ignore newline } else { - if (expecting==DICT_EXPECT_COMMA) { + if (expecting == DICT_EXPECT_COMMA) { _set_error("',' or '}' expected"); return NULL; } - if (expecting==DICT_EXPECT_COLON) { + if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return NULL; } - if (expecting==DICT_EXPECT_KEY) { + if (expecting == DICT_EXPECT_KEY) { - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1)==GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1) == GDTokenizer::TK_OP_ASSIGN) { //lua style identifier, easier to write ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = tokenizer->get_token_identifier(); key = cn; tokenizer->advance(2); - expecting=DICT_EXPECT_VALUE; + expecting = DICT_EXPECT_VALUE; } else { //python/js style more flexible - key = _parse_expression(dict,p_static,p_allow_assign,p_parsing_constant); + key = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant); if (!key) return NULL; - expecting=DICT_EXPECT_COLON; + expecting = DICT_EXPECT_COLON; } } - if (expecting==DICT_EXPECT_VALUE) { - Node *value = _parse_expression(dict,p_static,p_allow_assign,p_parsing_constant); + if (expecting == DICT_EXPECT_VALUE) { + Node *value = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant); if (!value) return NULL; - expecting=DICT_EXPECT_COMMA; + expecting = DICT_EXPECT_COMMA; DictionaryNode::Pair pair; - pair.key=key; - pair.value=value; + pair.key = key; + pair.value = value; dict->elements.push_back(pair); - key=NULL; - + key = NULL; } - } } - expr=dict; + expr = dict; - } else if (tokenizer->get_token()==GDTokenizer::TK_PERIOD && (tokenizer->get_token(1)==GDTokenizer::TK_IDENTIFIER || tokenizer->get_token(1)==GDTokenizer::TK_CURSOR) && tokenizer->get_token(2)==GDTokenizer::TK_PARENTHESIS_OPEN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && (tokenizer->get_token(1) == GDTokenizer::TK_IDENTIFIER || tokenizer->get_token(1) == GDTokenizer::TK_CURSOR) && tokenizer->get_token(2) == GDTokenizer::TK_PARENTHESIS_OPEN) { // parent call tokenizer->advance(); //goto identifier OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_PARENT_CALL; - + op->op = OperatorNode::OP_PARENT_CALL; /*SelfNode *self = alloc_node<SelfNode>(); op->arguments.push_back(self); forbidden for now */ StringName identifier; - if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION,identifier)) { + if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier)) { //indexing stuff } IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=identifier; + id->name = identifier; op->arguments.push_back(id); tokenizer->advance(1); - if (!_parse_arguments(op,op->arguments,p_static)) + if (!_parse_arguments(op, op->arguments, p_static)) return NULL; - expr=op; + expr = op; } else { @@ -773,113 +752,106 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ //print_line("found bug?"); - _set_error("Error parsing expression, misplaced: "+String(tokenizer->get_token_name(tokenizer->get_token()))); - return NULL; //nothing + _set_error("Error parsing expression, misplaced: " + String(tokenizer->get_token_name(tokenizer->get_token()))); + return NULL; //nothing } if (!expr) { ERR_EXPLAIN("GDParser bug, couldn't figure out what expression is.."); - ERR_FAIL_COND_V(!expr,NULL); + ERR_FAIL_COND_V(!expr, NULL); } - /******************/ /* Parse Indexing */ /******************/ - while (true) { //expressions can be indexed any number of times - if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) { //indexing using "." - if (tokenizer->get_token(1)!=GDTokenizer::TK_CURSOR && tokenizer->get_token(1)!=GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1)!=GDTokenizer::TK_BUILT_IN_FUNC ) { + if (tokenizer->get_token(1) != GDTokenizer::TK_CURSOR && tokenizer->get_token(1) != GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1) != GDTokenizer::TK_BUILT_IN_FUNC) { _set_error("Expected identifier as member"); return NULL; - } else if (tokenizer->get_token(2)==GDTokenizer::TK_PARENTHESIS_OPEN) { + } else if (tokenizer->get_token(2) == GDTokenizer::TK_PARENTHESIS_OPEN) { //call!! - OperatorNode * op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_CALL; + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_CALL; tokenizer->advance(); - IdentifierNode * id = alloc_node<IdentifierNode>(); - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC ) { + IdentifierNode *id = alloc_node<IdentifierNode>(); + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC) { //small hack so built in funcs don't obfuscate methods - id->name=GDFunctions::get_func_name(tokenizer->get_token_built_in_func()); + id->name = GDFunctions::get_func_name(tokenizer->get_token_built_in_func()); tokenizer->advance(); } else { StringName identifier; - if (_get_completable_identifier(COMPLETION_METHOD,identifier)) { - completion_node=op; + if (_get_completable_identifier(COMPLETION_METHOD, identifier)) { + completion_node = op; //indexing stuff } - id->name=identifier; + id->name = identifier; } op->arguments.push_back(expr); // call what op->arguments.push_back(id); // call func //get arguments tokenizer->advance(1); - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { _make_completable_call(0); - completion_node=op; - + completion_node = op; } - if (!_parse_arguments(op,op->arguments,p_static,true)) + if (!_parse_arguments(op, op->arguments, p_static, true)) return NULL; - expr=op; + expr = op; } else { //simple indexing! - - OperatorNode * op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_INDEX_NAMED; + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_INDEX_NAMED; tokenizer->advance(); - StringName identifier; - if (_get_completable_identifier(COMPLETION_INDEX,identifier)) { + if (_get_completable_identifier(COMPLETION_INDEX, identifier)) { - if (identifier==StringName()) { - identifier="@temp"; //so it parses allright + if (identifier == StringName()) { + identifier = "@temp"; //so it parses allright } - completion_node=op; + completion_node = op; //indexing stuff } - IdentifierNode * id = alloc_node<IdentifierNode>(); - id->name=identifier; + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->name = identifier; op->arguments.push_back(expr); op->arguments.push_back(id); - expr=op; - - + expr = op; } - } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_OPEN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_OPEN) { //indexing using "[]" - OperatorNode * op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_INDEX; + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_INDEX; tokenizer->advance(1); - Node *subexpr = _parse_expression(op,p_static,p_allow_assign,p_parsing_constant); + Node *subexpr = _parse_expression(op, p_static, p_allow_assign, p_parsing_constant); if (!subexpr) { return NULL; } - if (tokenizer->get_token()!=GDTokenizer::TK_BRACKET_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_BRACKET_CLOSE) { _set_error("Expected ']'"); return NULL; } @@ -887,7 +859,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ op->arguments.push_back(expr); op->arguments.push_back(subexpr); tokenizer->advance(1); - expr=op; + expr = op; } else break; @@ -897,88 +869,97 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ /* Parse Operator */ /******************/ - if (parenthesis>0) { + if (parenthesis > 0) { //remove empty space (only allowed if inside parenthesis - while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } } Expression e; - e.is_op=false; - e.node=expr; + e.is_op = false; + e.node = expr; expression.push_back(e); // determine which operator is next OperatorNode::Operator op; - bool valid=true; + bool valid = true; //assign, if allowed is only alowed on the first operator -#define _VALIDATE_ASSIGN if (!p_allow_assign) { _set_error("Unexpected assign."); return NULL; } p_allow_assign=false; - switch(tokenizer->get_token()) { //see operator +#define _VALIDATE_ASSIGN \ + if (!p_allow_assign) { \ + _set_error("Unexpected assign."); \ + return NULL; \ + } \ + p_allow_assign = false; + switch (tokenizer->get_token()) { //see operator - case GDTokenizer::TK_OP_IN: op=OperatorNode::OP_IN; break; - case GDTokenizer::TK_OP_EQUAL: op=OperatorNode::OP_EQUAL ; break; - case GDTokenizer::TK_OP_NOT_EQUAL: op=OperatorNode::OP_NOT_EQUAL ; break; - case GDTokenizer::TK_OP_LESS: op=OperatorNode::OP_LESS ; break; - case GDTokenizer::TK_OP_LESS_EQUAL: op=OperatorNode::OP_LESS_EQUAL ; break; - case GDTokenizer::TK_OP_GREATER: op=OperatorNode::OP_GREATER ; break; - case GDTokenizer::TK_OP_GREATER_EQUAL: op=OperatorNode::OP_GREATER_EQUAL ; break; - case GDTokenizer::TK_OP_AND: op=OperatorNode::OP_AND ; break; - case GDTokenizer::TK_OP_OR: op=OperatorNode::OP_OR ; break; - case GDTokenizer::TK_OP_ADD: op=OperatorNode::OP_ADD ; break; - case GDTokenizer::TK_OP_SUB: op=OperatorNode::OP_SUB ; break; - case GDTokenizer::TK_OP_MUL: op=OperatorNode::OP_MUL ; break; - case GDTokenizer::TK_OP_DIV: op=OperatorNode::OP_DIV ; break; - case GDTokenizer::TK_OP_MOD: op=OperatorNode::OP_MOD ; break; + case GDTokenizer::TK_OP_IN: op = OperatorNode::OP_IN; break; + case GDTokenizer::TK_OP_EQUAL: op = OperatorNode::OP_EQUAL; break; + case GDTokenizer::TK_OP_NOT_EQUAL: op = OperatorNode::OP_NOT_EQUAL; break; + case GDTokenizer::TK_OP_LESS: op = OperatorNode::OP_LESS; break; + case GDTokenizer::TK_OP_LESS_EQUAL: op = OperatorNode::OP_LESS_EQUAL; break; + case GDTokenizer::TK_OP_GREATER: op = OperatorNode::OP_GREATER; break; + case GDTokenizer::TK_OP_GREATER_EQUAL: op = OperatorNode::OP_GREATER_EQUAL; break; + case GDTokenizer::TK_OP_AND: op = OperatorNode::OP_AND; break; + case GDTokenizer::TK_OP_OR: op = OperatorNode::OP_OR; break; + case GDTokenizer::TK_OP_ADD: op = OperatorNode::OP_ADD; break; + case GDTokenizer::TK_OP_SUB: op = OperatorNode::OP_SUB; break; + case GDTokenizer::TK_OP_MUL: op = OperatorNode::OP_MUL; break; + case GDTokenizer::TK_OP_DIV: op = OperatorNode::OP_DIV; break; + case GDTokenizer::TK_OP_MOD: + op = OperatorNode::OP_MOD; + break; //case GDTokenizer::TK_OP_NEG: op=OperatorNode::OP_NEG ; break; - case GDTokenizer::TK_OP_SHIFT_LEFT: op=OperatorNode::OP_SHIFT_LEFT ; break; - case GDTokenizer::TK_OP_SHIFT_RIGHT: op=OperatorNode::OP_SHIFT_RIGHT ; break; - case GDTokenizer::TK_OP_ASSIGN: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN ; break; - case GDTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_ADD ; break; - case GDTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SUB ; break; - case GDTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_MUL ; break; - case GDTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_DIV ; break; - case GDTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_MOD ; break; - case GDTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SHIFT_LEFT; ; break; - case GDTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SHIFT_RIGHT; ; break; - case GDTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_AND ; break; - case GDTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_OR ; break; - case GDTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_XOR ; break; - case GDTokenizer::TK_OP_BIT_AND: op=OperatorNode::OP_BIT_AND ; break; - case GDTokenizer::TK_OP_BIT_OR: op=OperatorNode::OP_BIT_OR ; break; - case GDTokenizer::TK_OP_BIT_XOR: op=OperatorNode::OP_BIT_XOR ; break; - case GDTokenizer::TK_PR_EXTENDS: op=OperatorNode::OP_EXTENDS; break; - case GDTokenizer::TK_CF_IF: op=OperatorNode::OP_TERNARY_IF; break; - case GDTokenizer::TK_CF_ELSE: op=OperatorNode::OP_TERNARY_ELSE; break; - default: valid=false; break; + case GDTokenizer::TK_OP_SHIFT_LEFT: op = OperatorNode::OP_SHIFT_LEFT; break; + case GDTokenizer::TK_OP_SHIFT_RIGHT: op = OperatorNode::OP_SHIFT_RIGHT; break; + case GDTokenizer::TK_OP_ASSIGN: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN; break; + case GDTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_ADD; break; + case GDTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SUB; break; + case GDTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MUL; break; + case GDTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_DIV; break; + case GDTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MOD; break; + case GDTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: + _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_LEFT; + ; + break; + case GDTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: + _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_RIGHT; + ; + break; + case GDTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_AND; break; + case GDTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_OR; break; + case GDTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_XOR; break; + case GDTokenizer::TK_OP_BIT_AND: op = OperatorNode::OP_BIT_AND; break; + case GDTokenizer::TK_OP_BIT_OR: op = OperatorNode::OP_BIT_OR; break; + case GDTokenizer::TK_OP_BIT_XOR: op = OperatorNode::OP_BIT_XOR; break; + case GDTokenizer::TK_PR_EXTENDS: op = OperatorNode::OP_EXTENDS; break; + case GDTokenizer::TK_CF_IF: op = OperatorNode::OP_TERNARY_IF; break; + case GDTokenizer::TK_CF_ELSE: op = OperatorNode::OP_TERNARY_ELSE; break; + default: valid = false; break; } if (valid) { - e.is_op=true; - e.op=op; + e.is_op = true; + e.op = op; expression.push_back(e); tokenizer->advance(); } else { break; } - } /* Reduce the set set of expressions and place them in an operator tree, respecting precedence */ + while (expression.size() > 1) { - while(expression.size()>1) { - - int next_op=-1; - int min_priority=0xFFFFF; - bool is_unary=false; - bool is_ternary=false; - - for(int i=0;i<expression.size();i++) { - + int next_op = -1; + int min_priority = 0xFFFFF; + bool is_unary = false; + bool is_ternary = false; + for (int i = 0; i < expression.size(); i++) { if (!expression[i].is_op) { @@ -987,101 +968,111 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ int priority; - bool unary=false; - bool ternary=false; - bool error=false; + bool unary = false; + bool ternary = false; + bool error = false; - switch(expression[i].op) { + switch (expression[i].op) { - case OperatorNode::OP_EXTENDS: priority=-1; break; //before anything + case OperatorNode::OP_EXTENDS: + priority = -1; + break; //before anything - case OperatorNode::OP_BIT_INVERT: priority=0; unary=true; break; - case OperatorNode::OP_NEG: priority=1; unary=true; break; + case OperatorNode::OP_BIT_INVERT: + priority = 0; + unary = true; + break; + case OperatorNode::OP_NEG: + priority = 1; + unary = true; + break; + + case OperatorNode::OP_MUL: priority = 2; break; + case OperatorNode::OP_DIV: priority = 2; break; + case OperatorNode::OP_MOD: priority = 2; break; - case OperatorNode::OP_MUL: priority=2; break; - case OperatorNode::OP_DIV: priority=2; break; - case OperatorNode::OP_MOD: priority=2; break; + case OperatorNode::OP_ADD: priority = 3; break; + case OperatorNode::OP_SUB: priority = 3; break; - case OperatorNode::OP_ADD: priority=3; break; - case OperatorNode::OP_SUB: priority=3; break; + case OperatorNode::OP_SHIFT_LEFT: priority = 4; break; + case OperatorNode::OP_SHIFT_RIGHT: priority = 4; break; - case OperatorNode::OP_SHIFT_LEFT: priority=4; break; - case OperatorNode::OP_SHIFT_RIGHT: priority=4; break; + case OperatorNode::OP_BIT_AND: priority = 5; break; + case OperatorNode::OP_BIT_XOR: priority = 6; break; + case OperatorNode::OP_BIT_OR: priority = 7; break; - case OperatorNode::OP_BIT_AND: priority=5; break; - case OperatorNode::OP_BIT_XOR: priority=6; break; - case OperatorNode::OP_BIT_OR: priority=7; break; + case OperatorNode::OP_LESS: priority = 8; break; + case OperatorNode::OP_LESS_EQUAL: priority = 8; break; + case OperatorNode::OP_GREATER: priority = 8; break; + case OperatorNode::OP_GREATER_EQUAL: priority = 8; break; - case OperatorNode::OP_LESS: priority=8; break; - case OperatorNode::OP_LESS_EQUAL: priority=8; break; - case OperatorNode::OP_GREATER: priority=8; break; - case OperatorNode::OP_GREATER_EQUAL: priority=8; break; + case OperatorNode::OP_EQUAL: priority = 8; break; + case OperatorNode::OP_NOT_EQUAL: priority = 8; break; - case OperatorNode::OP_EQUAL: priority=8; break; - case OperatorNode::OP_NOT_EQUAL: priority=8; break; + case OperatorNode::OP_IN: priority = 10; break; - - case OperatorNode::OP_IN: priority=10; break; - - case OperatorNode::OP_NOT: priority=11; unary=true; break; - case OperatorNode::OP_AND: priority=12; break; - case OperatorNode::OP_OR: priority=13; break; - - case OperatorNode::OP_TERNARY_IF: priority=14; ternary=true; break; - case OperatorNode::OP_TERNARY_ELSE: priority=14; error=true; break; // Errors out when found without IF (since IF would consume it) + case OperatorNode::OP_NOT: + priority = 11; + unary = true; + break; + case OperatorNode::OP_AND: priority = 12; break; + case OperatorNode::OP_OR: priority = 13; break; - case OperatorNode::OP_ASSIGN: priority=15; break; - case OperatorNode::OP_ASSIGN_ADD: priority=15; break; - case OperatorNode::OP_ASSIGN_SUB: priority=15; break; - case OperatorNode::OP_ASSIGN_MUL: priority=15; break; - case OperatorNode::OP_ASSIGN_DIV: priority=15; break; - case OperatorNode::OP_ASSIGN_MOD: priority=15; break; - case OperatorNode::OP_ASSIGN_SHIFT_LEFT: priority=15; break; - case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: priority=15; break; - case OperatorNode::OP_ASSIGN_BIT_AND: priority=15; break; - case OperatorNode::OP_ASSIGN_BIT_OR: priority=15; break; - case OperatorNode::OP_ASSIGN_BIT_XOR: priority=15; break; + case OperatorNode::OP_TERNARY_IF: + priority = 14; + ternary = true; + break; + case OperatorNode::OP_TERNARY_ELSE: + priority = 14; + error = true; + break; // Errors out when found without IF (since IF would consume it) + case OperatorNode::OP_ASSIGN: priority = 15; break; + case OperatorNode::OP_ASSIGN_ADD: priority = 15; break; + case OperatorNode::OP_ASSIGN_SUB: priority = 15; break; + case OperatorNode::OP_ASSIGN_MUL: priority = 15; break; + case OperatorNode::OP_ASSIGN_DIV: priority = 15; break; + case OperatorNode::OP_ASSIGN_MOD: priority = 15; break; + case OperatorNode::OP_ASSIGN_SHIFT_LEFT: priority = 15; break; + case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: priority = 15; break; + case OperatorNode::OP_ASSIGN_BIT_AND: priority = 15; break; + case OperatorNode::OP_ASSIGN_BIT_OR: priority = 15; break; + case OperatorNode::OP_ASSIGN_BIT_XOR: priority = 15; break; default: { - _set_error("GDParser bug, invalid operator in expression: "+itos(expression[i].op)); + _set_error("GDParser bug, invalid operator in expression: " + itos(expression[i].op)); return NULL; } - } - if (priority<min_priority) { - if(error) { + if (priority < min_priority) { + if (error) { _set_error("Unexpected operator"); return NULL; } // < is used for left to right (default) // <= is used for right to left - next_op=i; - min_priority=priority; - is_unary=unary; - is_ternary=ternary; + next_op = i; + min_priority = priority; + is_unary = unary; + is_ternary = ternary; } - } - - if (next_op==-1) { - + if (next_op == -1) { _set_error("Yet another parser bug...."); - ERR_FAIL_COND_V(next_op==-1,NULL); + ERR_FAIL_COND_V(next_op == -1, NULL); } - // OK! create operator.. if (is_unary) { - int expr_pos=next_op; - while(expression[expr_pos].is_op) { + int expr_pos = next_op; + while (expression[expr_pos].is_op) { expr_pos++; - if (expr_pos==expression.size()) { + if (expr_pos == expression.size()) { //can happen.. _set_error("Unexpected end of expression.."); return NULL; @@ -1089,44 +1080,43 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ } //consecutively do unary opeators - for(int i=expr_pos-1;i>=next_op;i--) { + for (int i = expr_pos - 1; i >= next_op; i--) { OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[i].op; - op->arguments.push_back(expression[i+1].node); - op->line=op_line; //line might have been changed from a \n - expression[i].is_op=false; - expression[i].node=op; - expression.remove(i+1); + op->op = expression[i].op; + op->arguments.push_back(expression[i + 1].node); + op->line = op_line; //line might have been changed from a \n + expression[i].is_op = false; + expression[i].node = op; + expression.remove(i + 1); } - - } else if(is_ternary) { - if (next_op <1 || next_op>=(expression.size()-1)) { + } else if (is_ternary) { + if (next_op < 1 || next_op >= (expression.size() - 1)) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } - - if(next_op>=(expression.size()-2) || expression[next_op+2].op != OperatorNode::OP_TERNARY_ELSE) { + + if (next_op >= (expression.size() - 2) || expression[next_op + 2].op != OperatorNode::OP_TERNARY_ELSE) { _set_error("Expected else after ternary if."); ERR_FAIL_V(NULL); } - if(next_op>=(expression.size()-3)) { + if (next_op >= (expression.size() - 3)) { _set_error("Expected value after ternary else."); ERR_FAIL_V(NULL); } OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[next_op].op; - op->line=op_line; //line might have been changed from a \n + op->op = expression[next_op].op; + op->line = op_line; //line might have been changed from a \n - if (expression[next_op-1].is_op) { + if (expression[next_op - 1].is_op) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } - if (expression[next_op+1].is_op) { + if (expression[next_op + 1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, @@ -1136,7 +1126,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - if (expression[next_op+3].is_op) { + if (expression[next_op + 3].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, @@ -1146,35 +1136,34 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - - op->arguments.push_back(expression[next_op+1].node); //next expression goes as first - op->arguments.push_back(expression[next_op-1].node); //left expression goes as when-true - op->arguments.push_back(expression[next_op+3].node); //expression after next goes as when-false + op->arguments.push_back(expression[next_op + 1].node); //next expression goes as first + op->arguments.push_back(expression[next_op - 1].node); //left expression goes as when-true + op->arguments.push_back(expression[next_op + 3].node); //expression after next goes as when-false //replace all 3 nodes by this operator and make it an expression - expression[next_op-1].node=op; + expression[next_op - 1].node = op; expression.remove(next_op); expression.remove(next_op); expression.remove(next_op); expression.remove(next_op); } else { - if (next_op <1 || next_op>=(expression.size()-1)) { + if (next_op < 1 || next_op >= (expression.size() - 1)) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[next_op].op; - op->line=op_line; //line might have been changed from a \n + op->op = expression[next_op].op; + op->line = op_line; //line might have been changed from a \n - if (expression[next_op-1].is_op) { + if (expression[next_op - 1].is_op) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } - if (expression[next_op+1].is_op) { + if (expression[next_op + 1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, @@ -1184,26 +1173,22 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - - op->arguments.push_back(expression[next_op-1].node); //expression goes as left - op->arguments.push_back(expression[next_op+1].node); //next expression goes as right + op->arguments.push_back(expression[next_op - 1].node); //expression goes as left + op->arguments.push_back(expression[next_op + 1].node); //next expression goes as right //replace all 3 nodes by this operator and make it an expression - expression[next_op-1].node=op; + expression[next_op - 1].node = op; expression.remove(next_op); expression.remove(next_op); } - } return expression[0].node; - } +GDParser::Node *GDParser::_reduce_expression(Node *p_node, bool p_to_const) { -GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { - - switch(p_node->type) { + switch (p_node->type) { case Node::TYPE_BUILT_IN_FUNCTION: { //many may probably be optimizable @@ -1211,14 +1196,14 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { } break; case Node::TYPE_ARRAY: { - ArrayNode *an = static_cast<ArrayNode*>(p_node); - bool all_constants=true; + ArrayNode *an = static_cast<ArrayNode *>(p_node); + bool all_constants = true; - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { - an->elements[i]=_reduce_expression(an->elements[i],p_to_const); - if (an->elements[i]->type!=Node::TYPE_CONSTANT) - all_constants=false; + an->elements[i] = _reduce_expression(an->elements[i], p_to_const); + if (an->elements[i]->type != Node::TYPE_CONSTANT) + all_constants = false; } if (all_constants && p_to_const) { @@ -1228,12 +1213,11 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { Array arr(!p_to_const); //print_line("mk array "+itos(!p_to_const)); arr.resize(an->elements.size()); - for(int i=0;i<an->elements.size();i++) { - ConstantNode *acn = static_cast<ConstantNode*>(an->elements[i]); - arr[i]=acn->value; - + for (int i = 0; i < an->elements.size(); i++) { + ConstantNode *acn = static_cast<ConstantNode *>(an->elements[i]); + arr[i] = acn->value; } - cn->value=arr; + cn->value = arr; return cn; } @@ -1242,18 +1226,17 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { } break; case Node::TYPE_DICTIONARY: { - DictionaryNode *dn = static_cast<DictionaryNode*>(p_node); - bool all_constants=true; + DictionaryNode *dn = static_cast<DictionaryNode *>(p_node); + bool all_constants = true; - for(int i=0;i<dn->elements.size();i++) { - - dn->elements[i].key=_reduce_expression(dn->elements[i].key,p_to_const); - if (dn->elements[i].key->type!=Node::TYPE_CONSTANT) - all_constants=false; - dn->elements[i].value=_reduce_expression(dn->elements[i].value,p_to_const); - if (dn->elements[i].value->type!=Node::TYPE_CONSTANT) - all_constants=false; + for (int i = 0; i < dn->elements.size(); i++) { + dn->elements[i].key = _reduce_expression(dn->elements[i].key, p_to_const); + if (dn->elements[i].key->type != Node::TYPE_CONSTANT) + all_constants = false; + dn->elements[i].value = _reduce_expression(dn->elements[i].value, p_to_const); + if (dn->elements[i].value->type != Node::TYPE_CONSTANT) + all_constants = false; } if (all_constants && p_to_const) { @@ -1261,157 +1244,143 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { ConstantNode *cn = alloc_node<ConstantNode>(); Dictionary dict(!p_to_const); - for(int i=0;i<dn->elements.size();i++) { - ConstantNode *key_c = static_cast<ConstantNode*>(dn->elements[i].key); - ConstantNode *value_c = static_cast<ConstantNode*>(dn->elements[i].value); - - dict[key_c->value]=value_c->value; + for (int i = 0; i < dn->elements.size(); i++) { + ConstantNode *key_c = static_cast<ConstantNode *>(dn->elements[i].key); + ConstantNode *value_c = static_cast<ConstantNode *>(dn->elements[i].value); + dict[key_c->value] = value_c->value; } - cn->value=dict; + cn->value = dict; return cn; } return dn; - } break; case Node::TYPE_OPERATOR: { - OperatorNode *op=static_cast<OperatorNode*>(p_node); + OperatorNode *op = static_cast<OperatorNode *>(p_node); - bool all_constants=true; - int last_not_constant=-1; + bool all_constants = true; + int last_not_constant = -1; - for(int i=0;i<op->arguments.size();i++) { + for (int i = 0; i < op->arguments.size(); i++) { - op->arguments[i]=_reduce_expression(op->arguments[i],p_to_const); - if (op->arguments[i]->type!=Node::TYPE_CONSTANT) { - all_constants=false; - last_not_constant=i; + op->arguments[i] = _reduce_expression(op->arguments[i], p_to_const); + if (op->arguments[i]->type != Node::TYPE_CONSTANT) { + all_constants = false; + last_not_constant = i; } } - if (op->op==OperatorNode::OP_EXTENDS) { + if (op->op == OperatorNode::OP_EXTENDS) { //nothing much return op; - - } if (op->op==OperatorNode::OP_PARENT_CALL) { + } + if (op->op == OperatorNode::OP_PARENT_CALL) { //nothing much return op; - } else if (op->op==OperatorNode::OP_CALL) { + } else if (op->op == OperatorNode::OP_CALL) { //can reduce base type constructors - if ((op->arguments[0]->type==Node::TYPE_TYPE || (op->arguments[0]->type==Node::TYPE_BUILT_IN_FUNCTION && GDFunctions::is_deterministic( static_cast<BuiltInFunctionNode*>(op->arguments[0])->function))) && last_not_constant==0) { + if ((op->arguments[0]->type == Node::TYPE_TYPE || (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && GDFunctions::is_deterministic(static_cast<BuiltInFunctionNode *>(op->arguments[0])->function))) && last_not_constant == 0) { //native type constructor or intrinsic function - const Variant **vptr=NULL; - Vector<Variant*> ptrs; - if (op->arguments.size()>1) { - - ptrs.resize(op->arguments.size()-1); - for(int i=0;i<ptrs.size();i++) { + const Variant **vptr = NULL; + Vector<Variant *> ptrs; + if (op->arguments.size() > 1) { + ptrs.resize(op->arguments.size() - 1); + for (int i = 0; i < ptrs.size(); i++) { - ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[i+1]); - ptrs[i]=&cn->value; + ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i + 1]); + ptrs[i] = &cn->value; } - vptr=(const Variant**)&ptrs[0]; - - + vptr = (const Variant **)&ptrs[0]; } Variant::CallError ce; Variant v; - if (op->arguments[0]->type==Node::TYPE_TYPE) { - TypeNode *tn = static_cast<TypeNode*>(op->arguments[0]); - v = Variant::construct(tn->vtype,vptr,ptrs.size(),ce); + if (op->arguments[0]->type == Node::TYPE_TYPE) { + TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]); + v = Variant::construct(tn->vtype, vptr, ptrs.size(), ce); } else { - GDFunctions::Function func = static_cast<BuiltInFunctionNode*>(op->arguments[0])->function; - GDFunctions::call(func,vptr,ptrs.size(),v,ce); + GDFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function; + GDFunctions::call(func, vptr, ptrs.size(), v, ce); } - - if (ce.error!=Variant::CallError::CALL_OK) { + if (ce.error != Variant::CallError::CALL_OK) { String errwhere; - if (op->arguments[0]->type==Node::TYPE_TYPE) { - TypeNode *tn = static_cast<TypeNode*>(op->arguments[0]); - errwhere="'"+Variant::get_type_name(tn->vtype)+"'' constructor"; + if (op->arguments[0]->type == Node::TYPE_TYPE) { + TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]); + errwhere = "'" + Variant::get_type_name(tn->vtype) + "'' constructor"; } else { - GDFunctions::Function func = static_cast<BuiltInFunctionNode*>(op->arguments[0])->function; - errwhere=String("'")+GDFunctions::get_func_name(func)+"'' intrinsic function"; - + GDFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function; + errwhere = String("'") + GDFunctions::get_func_name(func) + "'' intrinsic function"; } - switch(ce.error) { + switch (ce.error) { case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: { - _set_error("Invalid argument (#"+itos(ce.argument+1)+") for "+errwhere+"."); + _set_error("Invalid argument (#" + itos(ce.argument + 1) + ") for " + errwhere + "."); } break; case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { - _set_error("Too many arguments for "+errwhere+"."); + _set_error("Too many arguments for " + errwhere + "."); } break; case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: { - _set_error("Too few arguments for "+errwhere+"."); + _set_error("Too few arguments for " + errwhere + "."); } break; default: { - _set_error("Invalid arguments for "+errwhere+"."); + _set_error("Invalid arguments for " + errwhere + "."); } break; } - error_line=op->line; + error_line = op->line; return p_node; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; + cn->value = v; return cn; - } else if (op->arguments[0]->type==Node::TYPE_BUILT_IN_FUNCTION && last_not_constant==0) { - - - - - + } else if (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && last_not_constant == 0) { } return op; //don't reduce yet - } else if (op->op==OperatorNode::OP_YIELD) { + } else if (op->op == OperatorNode::OP_YIELD) { return op; - } else if (op->op==OperatorNode::OP_INDEX) { + } else if (op->op == OperatorNode::OP_INDEX) { //can reduce indices into constant arrays or dictionaries if (all_constants) { - ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]); - ConstantNode *cb = static_cast<ConstantNode*>(op->arguments[1]); - - + ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]); + ConstantNode *cb = static_cast<ConstantNode *>(op->arguments[1]); bool valid; - Variant v = ca->value.get(cb->value,&valid); + Variant v = ca->value.get(cb->value, &valid); if (!valid) { _set_error("invalid index in constant expression"); - error_line=op->line; + error_line = op->line; return op; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; + cn->value = v; return cn; } /*else if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { @@ -1433,32 +1402,31 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { return op; - } else if (op->op==OperatorNode::OP_INDEX_NAMED) { + } else if (op->op == OperatorNode::OP_INDEX_NAMED) { - if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { + if (op->arguments[0]->type == Node::TYPE_CONSTANT && op->arguments[1]->type == Node::TYPE_IDENTIFIER) { - ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]); - IdentifierNode *ib = static_cast<IdentifierNode*>(op->arguments[1]); + ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]); + IdentifierNode *ib = static_cast<IdentifierNode *>(op->arguments[1]); bool valid; - Variant v = ca->value.get_named(ib->name,&valid); + Variant v = ca->value.get_named(ib->name, &valid); if (!valid) { - _set_error("invalid index '"+String(ib->name)+"' in constant expression"); - error_line=op->line; + _set_error("invalid index '" + String(ib->name) + "' in constant expression"); + error_line = op->line; return op; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; + cn->value = v; return cn; } return op; - } //validate assignment (don't assign to cosntant expression - switch(op->op) { + switch (op->op) { case OperatorNode::OP_ASSIGN: case OperatorNode::OP_ASSIGN_ADD: @@ -1472,17 +1440,17 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { case OperatorNode::OP_ASSIGN_BIT_OR: case OperatorNode::OP_ASSIGN_BIT_XOR: { - if (op->arguments[0]->type==Node::TYPE_CONSTANT) { - _set_error("Can't assign to constant",tokenizer->get_token_line()-1); - error_line=op->line; + if (op->arguments[0]->type == Node::TYPE_CONSTANT) { + _set_error("Can't assign to constant", tokenizer->get_token_line() - 1); + error_line = op->line; return op; } - if (op->arguments[0]->type==Node::TYPE_OPERATOR) { - OperatorNode *on = static_cast<OperatorNode*>(op->arguments[0]); + if (op->arguments[0]->type == Node::TYPE_OPERATOR) { + OperatorNode *on = static_cast<OperatorNode *>(op->arguments[0]); if (on->op != OperatorNode::OP_INDEX && on->op != OperatorNode::OP_INDEX_NAMED) { - _set_error("Can't assign to an expression",tokenizer->get_token_line()-1); - error_line=op->line; + _set_error("Can't assign to an expression", tokenizer->get_token_line() - 1); + error_line = op->line; return op; } } @@ -1493,58 +1461,102 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { //now se if all are constants if (!all_constants) return op; //nothing to reduce from here on -#define _REDUCE_UNARY(m_vop)\ - bool valid=false;\ - Variant res;\ - Variant::evaluate(m_vop,static_cast<ConstantNode*>(op->arguments[0])->value,Variant(),res,valid);\ - if (!valid) {\ - _set_error("Invalid operand for unary operator");\ - error_line=op->line;\ - return p_node;\ - }\ - ConstantNode *cn = alloc_node<ConstantNode>();\ - cn->value=res;\ +#define _REDUCE_UNARY(m_vop) \ + bool valid = false; \ + Variant res; \ + Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, Variant(), res, valid); \ + if (!valid) { \ + _set_error("Invalid operand for unary operator"); \ + error_line = op->line; \ + return p_node; \ + } \ + ConstantNode *cn = alloc_node<ConstantNode>(); \ + cn->value = res; \ return cn; -#define _REDUCE_BINARY(m_vop)\ - bool valid=false;\ - Variant res;\ - Variant::evaluate(m_vop,static_cast<ConstantNode*>(op->arguments[0])->value,static_cast<ConstantNode*>(op->arguments[1])->value,res,valid);\ - if (!valid) {\ - _set_error("Invalid operands for operator");\ - error_line=op->line;\ - return p_node;\ - }\ - ConstantNode *cn = alloc_node<ConstantNode>();\ - cn->value=res;\ +#define _REDUCE_BINARY(m_vop) \ + bool valid = false; \ + Variant res; \ + Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, static_cast<ConstantNode *>(op->arguments[1])->value, res, valid); \ + if (!valid) { \ + _set_error("Invalid operands for operator"); \ + error_line = op->line; \ + return p_node; \ + } \ + ConstantNode *cn = alloc_node<ConstantNode>(); \ + cn->value = res; \ return cn; - switch(op->op) { + switch (op->op) { //unary operators - case OperatorNode::OP_NEG: { _REDUCE_UNARY(Variant::OP_NEGATE); } break; - case OperatorNode::OP_NOT: { _REDUCE_UNARY(Variant::OP_NOT); } break; - case OperatorNode::OP_BIT_INVERT: { _REDUCE_UNARY(Variant::OP_BIT_NEGATE); } break; + case OperatorNode::OP_NEG: { + _REDUCE_UNARY(Variant::OP_NEGATE); + } break; + case OperatorNode::OP_NOT: { + _REDUCE_UNARY(Variant::OP_NOT); + } break; + case OperatorNode::OP_BIT_INVERT: { + _REDUCE_UNARY(Variant::OP_BIT_NEGATE); + } break; //binary operators (in precedence order) - case OperatorNode::OP_IN: { _REDUCE_BINARY(Variant::OP_IN); } break; - case OperatorNode::OP_EQUAL: { _REDUCE_BINARY(Variant::OP_EQUAL); } break; - case OperatorNode::OP_NOT_EQUAL: { _REDUCE_BINARY(Variant::OP_NOT_EQUAL); } break; - case OperatorNode::OP_LESS: { _REDUCE_BINARY(Variant::OP_LESS); } break; - case OperatorNode::OP_LESS_EQUAL: { _REDUCE_BINARY(Variant::OP_LESS_EQUAL); } break; - case OperatorNode::OP_GREATER: { _REDUCE_BINARY(Variant::OP_GREATER); } break; - case OperatorNode::OP_GREATER_EQUAL: { _REDUCE_BINARY(Variant::OP_GREATER_EQUAL); } break; - case OperatorNode::OP_AND: { _REDUCE_BINARY(Variant::OP_AND); } break; - case OperatorNode::OP_OR: { _REDUCE_BINARY(Variant::OP_OR); } break; - case OperatorNode::OP_ADD: { _REDUCE_BINARY(Variant::OP_ADD); } break; - case OperatorNode::OP_SUB: { _REDUCE_BINARY(Variant::OP_SUBSTRACT); } break; - case OperatorNode::OP_MUL: { _REDUCE_BINARY(Variant::OP_MULTIPLY); } break; - case OperatorNode::OP_DIV: { _REDUCE_BINARY(Variant::OP_DIVIDE); } break; - case OperatorNode::OP_MOD: { _REDUCE_BINARY(Variant::OP_MODULE); } break; - case OperatorNode::OP_SHIFT_LEFT: { _REDUCE_BINARY(Variant::OP_SHIFT_LEFT); } break; - case OperatorNode::OP_SHIFT_RIGHT: { _REDUCE_BINARY(Variant::OP_SHIFT_RIGHT); } break; - case OperatorNode::OP_BIT_AND: { _REDUCE_BINARY(Variant::OP_BIT_AND); } break; - case OperatorNode::OP_BIT_OR: { _REDUCE_BINARY(Variant::OP_BIT_OR); } break; - case OperatorNode::OP_BIT_XOR: { _REDUCE_BINARY(Variant::OP_BIT_XOR); } break; + case OperatorNode::OP_IN: { + _REDUCE_BINARY(Variant::OP_IN); + } break; + case OperatorNode::OP_EQUAL: { + _REDUCE_BINARY(Variant::OP_EQUAL); + } break; + case OperatorNode::OP_NOT_EQUAL: { + _REDUCE_BINARY(Variant::OP_NOT_EQUAL); + } break; + case OperatorNode::OP_LESS: { + _REDUCE_BINARY(Variant::OP_LESS); + } break; + case OperatorNode::OP_LESS_EQUAL: { + _REDUCE_BINARY(Variant::OP_LESS_EQUAL); + } break; + case OperatorNode::OP_GREATER: { + _REDUCE_BINARY(Variant::OP_GREATER); + } break; + case OperatorNode::OP_GREATER_EQUAL: { + _REDUCE_BINARY(Variant::OP_GREATER_EQUAL); + } break; + case OperatorNode::OP_AND: { + _REDUCE_BINARY(Variant::OP_AND); + } break; + case OperatorNode::OP_OR: { + _REDUCE_BINARY(Variant::OP_OR); + } break; + case OperatorNode::OP_ADD: { + _REDUCE_BINARY(Variant::OP_ADD); + } break; + case OperatorNode::OP_SUB: { + _REDUCE_BINARY(Variant::OP_SUBSTRACT); + } break; + case OperatorNode::OP_MUL: { + _REDUCE_BINARY(Variant::OP_MULTIPLY); + } break; + case OperatorNode::OP_DIV: { + _REDUCE_BINARY(Variant::OP_DIVIDE); + } break; + case OperatorNode::OP_MOD: { + _REDUCE_BINARY(Variant::OP_MODULE); + } break; + case OperatorNode::OP_SHIFT_LEFT: { + _REDUCE_BINARY(Variant::OP_SHIFT_LEFT); + } break; + case OperatorNode::OP_SHIFT_RIGHT: { + _REDUCE_BINARY(Variant::OP_SHIFT_RIGHT); + } break; + case OperatorNode::OP_BIT_AND: { + _REDUCE_BINARY(Variant::OP_BIT_AND); + } break; + case OperatorNode::OP_BIT_OR: { + _REDUCE_BINARY(Variant::OP_BIT_OR); + } break; + case OperatorNode::OP_BIT_XOR: { + _REDUCE_BINARY(Variant::OP_BIT_XOR); + } break; default: { ERR_FAIL_V(op); } } @@ -1553,16 +1565,15 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { default: { return p_node; } break; - } } -GDParser::Node* GDParser::_parse_and_reduce_expression(Node *p_parent,bool p_static,bool p_reduce_const,bool p_allow_assign) { +GDParser::Node *GDParser::_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const, bool p_allow_assign) { - Node* expr=_parse_expression(p_parent,p_static,p_allow_assign,p_reduce_const); + Node *expr = _parse_expression(p_parent, p_static, p_allow_assign, p_reduce_const); if (!expr || error_set) return NULL; - expr = _reduce_expression(expr,p_reduce_const); + expr = _reduce_expression(expr, p_reduce_const); if (!expr || error_set) return NULL; return expr; @@ -1574,56 +1585,53 @@ bool GDParser::_recover_from_completion() { return false; //can't recover if no completion } //skip stuff until newline - while(tokenizer->get_token()!=GDTokenizer::TK_NEWLINE && tokenizer->get_token()!=GDTokenizer::TK_EOF && tokenizer->get_token()!=GDTokenizer::TK_ERROR) { + while (tokenizer->get_token() != GDTokenizer::TK_NEWLINE && tokenizer->get_token() != GDTokenizer::TK_EOF && tokenizer->get_token() != GDTokenizer::TK_ERROR) { tokenizer->advance(); } - completion_found=false; - error_set=false; - if(tokenizer->get_token() == GDTokenizer::TK_ERROR){ + completion_found = false; + error_set = false; + if (tokenizer->get_token() == GDTokenizer::TK_ERROR) { error_set = true; } return true; } -void GDParser::_parse_block(BlockNode *p_block,bool p_static) { +void GDParser::_parse_block(BlockNode *p_block, bool p_static) { int indent_level = tab_level.back()->get(); - #ifdef DEBUG_ENABLED NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=tokenizer->get_token_line(); + nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); #endif - while(true) { + while (true) { GDTokenizer::Token token = tokenizer->get_token(); if (error_set) return; - if (indent_level>tab_level.back()->get()) { - p_block->end_line=tokenizer->get_token_line(); + if (indent_level > tab_level.back()->get()) { + p_block->end_line = tokenizer->get_token_line(); return; //go back a level } - if (pending_newline!=-1) { + if (pending_newline != -1) { NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=pending_newline; + nl->line = pending_newline; p_block->statements.push_back(nl); - pending_newline=-1; - + pending_newline = -1; } - switch(token) { - + switch (token) { case GDTokenizer::TK_EOF: - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); case GDTokenizer::TK_ERROR: { return; //go back @@ -1634,26 +1642,25 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { if (!_parse_newline()) { if (!error_set) { - p_block->end_line=tokenizer->get_token_line(); - pending_newline=p_block->end_line; - + p_block->end_line = tokenizer->get_token_line(); + pending_newline = p_block->end_line; } return; } NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=tokenizer->get_token_line(); + nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); } break; case GDTokenizer::TK_CF_PASS: { - if (tokenizer->get_token(1)!=GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE && tokenizer->get_token(1)!=GDTokenizer::TK_EOF) { + if (tokenizer->get_token(1) != GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDTokenizer::TK_EOF) { _set_error("Expected ';' or <NewLine>."); return; } tokenizer->advance(); - if(tokenizer->get_token()==GDTokenizer::TK_SEMICOLON) { + if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON) { // Ignore semicolon after 'pass' tokenizer->advance(); } @@ -1662,7 +1669,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { //variale declaration and (eventual) initialization tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for local variable name."); return; @@ -1673,20 +1680,19 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { p_block->variables.push_back(n); //line? p_block->variable_lines.push_back(tokenizer->get_token_line()); - //must know when the local variable is declared LocalVarNode *lv = alloc_node<LocalVarNode>(); - lv->name=n; + lv->name = n; p_block->statements.push_back(lv); - Node *assigned=NULL; + Node *assigned = NULL; - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_block,p_static); + subexpr = _parse_and_reduce_expression(p_block, p_static); if (!subexpr) { if (_recover_from_completion()) { break; @@ -1694,23 +1700,19 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } - - - lv->assign=subexpr; - assigned=subexpr; + lv->assign = subexpr; + assigned = subexpr; } else { ConstantNode *c = alloc_node<ConstantNode>(); - c->value=Variant(); + c->value = Variant(); assigned = c; - } IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=n; - + id->name = n; OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_ASSIGN; + op->op = OperatorNode::OP_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(assigned); p_block->statements.push_back(op); @@ -1724,8 +1726,8 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { case GDTokenizer::TK_CF_IF: { tokenizer->advance(); - - Node *condition = _parse_and_reduce_expression(p_block,p_static); + + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -1735,39 +1737,39 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { ControlFlowNode *cf_if = alloc_node<ControlFlowNode>(); - cf_if->cf_type=ControlFlowNode::CF_IF; + cf_if->cf_type = ControlFlowNode::CF_IF; cf_if->arguments.push_back(condition); cf_if->body = alloc_node<BlockNode>(); - cf_if->body->parent_block=p_block; + cf_if->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body); if (!_enter_indent_block(cf_if->body)) { _set_error("Expected intended block after 'if'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_if->body; - _parse_block(cf_if->body,p_static); - current_block=p_block; + current_block = cf_if->body; + _parse_block(cf_if->body, p_static); + current_block = p_block; if (error_set) return; p_block->statements.push_back(cf_if); - while(true) { + while (true) { - while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } if (tab_level.back()->get() < indent_level) { //not at current indent level - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - if (tokenizer->get_token()==GDTokenizer::TK_CF_ELIF) { + if (tokenizer->get_token() == GDTokenizer::TK_CF_ELIF) { if (tab_level.back()->get() > indent_level) { @@ -1777,15 +1779,15 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); - cf_if->body_else=alloc_node<BlockNode>(); - cf_if->body_else->parent_block=p_block; + cf_if->body_else = alloc_node<BlockNode>(); + cf_if->body_else->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body_else); ControlFlowNode *cf_else = alloc_node<ControlFlowNode>(); - cf_else->cf_type=ControlFlowNode::CF_IF; + cf_else->cf_type = ControlFlowNode::CF_IF; //condition - Node *condition = _parse_and_reduce_expression(p_block,p_static); + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -1793,66 +1795,60 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } cf_else->arguments.push_back(condition); - cf_else->cf_type=ControlFlowNode::CF_IF; + cf_else->cf_type = ControlFlowNode::CF_IF; cf_if->body_else->statements.push_back(cf_else); - cf_if=cf_else; - cf_if->body=alloc_node<BlockNode>(); - cf_if->body->parent_block=p_block; + cf_if = cf_else; + cf_if->body = alloc_node<BlockNode>(); + cf_if->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body); - if (!_enter_indent_block(cf_if->body)) { _set_error("Expected indented block after 'elif'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_else->body; - _parse_block(cf_else->body,p_static); - current_block=p_block; + current_block = cf_else->body; + _parse_block(cf_else->body, p_static); + current_block = p_block; if (error_set) return; - - } else if (tokenizer->get_token()==GDTokenizer::TK_CF_ELSE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CF_ELSE) { if (tab_level.back()->get() > indent_level) { _set_error("Invalid indent"); return; } - tokenizer->advance(); - cf_if->body_else=alloc_node<BlockNode>(); - cf_if->body_else->parent_block=p_block; + cf_if->body_else = alloc_node<BlockNode>(); + cf_if->body_else->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body_else); if (!_enter_indent_block(cf_if->body_else)) { _set_error("Expected indented block after 'else'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_if->body_else; - _parse_block(cf_if->body_else,p_static); - current_block=p_block; + current_block = cf_if->body_else; + _parse_block(cf_if->body_else, p_static); + current_block = p_block; if (error_set) return; - break; //after else, exit } else break; - } - } break; case GDTokenizer::TK_CF_WHILE: { tokenizer->advance(); - Node *condition = _parse_and_reduce_expression(p_block,p_static); + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -1862,22 +1858,22 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { ControlFlowNode *cf_while = alloc_node<ControlFlowNode>(); - cf_while->cf_type=ControlFlowNode::CF_WHILE; + cf_while->cf_type = ControlFlowNode::CF_WHILE; cf_while->arguments.push_back(condition); cf_while->body = alloc_node<BlockNode>(); - cf_while->body->parent_block=p_block; + cf_while->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_while->body); if (!_enter_indent_block(cf_while->body)) { _set_error("Expected indented block after 'while'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_while->body; - _parse_block(cf_while->body,p_static); - current_block=p_block; + current_block = cf_while->body; + _parse_block(cf_while->body, p_static); + current_block = p_block; if (error_set) return; p_block->statements.push_back(cf_while); @@ -1886,24 +1882,24 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("identifier expected after 'for'"); } IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=tokenizer->get_token_identifier(); + id->name = tokenizer->get_token_identifier(); tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_OP_IN) { + if (tokenizer->get_token() != GDTokenizer::TK_OP_IN) { _set_error("'in' expected after identifier"); return; } tokenizer->advance(); - Node *container = _parse_and_reduce_expression(p_block,p_static); + Node *container = _parse_and_reduce_expression(p_block, p_static); if (!container) { if (_recover_from_completion()) { break; @@ -1913,23 +1909,23 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { ControlFlowNode *cf_for = alloc_node<ControlFlowNode>(); - cf_for->cf_type=ControlFlowNode::CF_FOR; + cf_for->cf_type = ControlFlowNode::CF_FOR; cf_for->arguments.push_back(id); cf_for->arguments.push_back(container); cf_for->body = alloc_node<BlockNode>(); - cf_for->body->parent_block=p_block; + cf_for->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_for->body); if (!_enter_indent_block(cf_for->body)) { _set_error("Expected indented block after 'for'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_for->body; - _parse_block(cf_for->body,p_static); - current_block=p_block; + current_block = cf_for->body; + _parse_block(cf_for->body, p_static); + current_block = p_block; if (error_set) return; @@ -1939,7 +1935,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>(); - cf_continue->cf_type=ControlFlowNode::CF_CONTINUE; + cf_continue->cf_type = ControlFlowNode::CF_CONTINUE; p_block->statements.push_back(cf_continue); if (!_end_statement()) { _set_error("Expected end of statement (continue)"); @@ -1950,7 +1946,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); ControlFlowNode *cf_break = alloc_node<ControlFlowNode>(); - cf_break->cf_type=ControlFlowNode::CF_BREAK; + cf_break->cf_type = ControlFlowNode::CF_BREAK; p_block->statements.push_back(cf_break); if (!_end_statement()) { _set_error("Expected end of statement (break)"); @@ -1961,11 +1957,9 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); ControlFlowNode *cf_return = alloc_node<ControlFlowNode>(); - cf_return->cf_type=ControlFlowNode::CF_RETURN; - + cf_return->cf_type = ControlFlowNode::CF_RETURN; - - if (tokenizer->get_token()==GDTokenizer::TK_SEMICOLON || tokenizer->get_token()==GDTokenizer::TK_NEWLINE || tokenizer->get_token()==GDTokenizer::TK_EOF) { + if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON || tokenizer->get_token() == GDTokenizer::TK_NEWLINE || tokenizer->get_token() == GDTokenizer::TK_EOF) { //expect end of statement p_block->statements.push_back(cf_return); if (!_end_statement()) { @@ -1973,7 +1967,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } } else { //expect expression - Node *retexpr = _parse_and_reduce_expression(p_block,p_static); + Node *retexpr = _parse_and_reduce_expression(p_block, p_static); if (!retexpr) { if (_recover_from_completion()) { break; @@ -1988,12 +1982,11 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } } - } break; case GDTokenizer::TK_PR_ASSERT: { tokenizer->advance(); - Node *condition = _parse_and_reduce_expression(p_block,p_static); + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -2001,7 +1994,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } AssertNode *an = alloc_node<AssertNode>(); - an->condition=condition; + an->condition = condition; p_block->statements.push_back(an); if (!_end_statement()) { @@ -2022,7 +2015,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } break; default: { - Node *expression = _parse_and_reduce_expression(p_block,p_static,false,true); + Node *expression = _parse_and_reduce_expression(p_block, p_static, false, true); if (!expression) { if (_recover_from_completion()) { break; @@ -2036,7 +2029,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } } break; - /* + /* case GDTokenizer::TK_CF_LOCAL: { if (tokenizer->get_token(1)!=GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE ) { @@ -2046,37 +2039,35 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); } break; */ - } } - } bool GDParser::_parse_newline() { - if (tokenizer->get_token(1)!=GDTokenizer::TK_EOF && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token(1) != GDTokenizer::TK_EOF && tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE) { int indent = tokenizer->get_token_line_indent(); int current_indent = tab_level.back()->get(); - if (indent>current_indent) { + if (indent > current_indent) { _set_error("Unexpected indent."); return false; } - if (indent<current_indent) { + if (indent < current_indent) { - while(indent<current_indent) { + while (indent < current_indent) { //exit block - if (tab_level.size()==1) { + if (tab_level.size() == 1) { _set_error("Invalid indent. BUG?"); return false; } tab_level.pop_back(); - if (tab_level.back()->get()<indent) { + if (tab_level.back()->get() < indent) { _set_error("Unindent does not match any outer indentation level."); return false; @@ -2091,13 +2082,10 @@ bool GDParser::_parse_newline() { tokenizer->advance(); return true; - } - void GDParser::_parse_extends(ClassNode *p_class) { - if (p_class->extends_used) { _set_error("'extends' already used for this class."); @@ -2110,72 +2098,70 @@ void GDParser::_parse_extends(ClassNode *p_class) { return; } - p_class->extends_used=true; + p_class->extends_used = true; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type()==Variant::OBJECT) { + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type() == Variant::OBJECT) { p_class->extends_class.push_back(Variant::get_type_name(Variant::OBJECT)); tokenizer->advance(); return; } // see if inheritance happens from a file - if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT) { + if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT) { Variant constant = tokenizer->get_token_constant(); - if (constant.get_type()!=Variant::STRING) { + if (constant.get_type() != Variant::STRING) { _set_error("'extends' constant must be a string."); return; } - p_class->extends_file=constant; + p_class->extends_file = constant; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() != GDTokenizer::TK_PERIOD) { return; } else tokenizer->advance(); - } - while(true) { - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + while (true) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Invalid 'extends' syntax, expected string constant (path) and/or identifier (parent class)."); return; } - StringName identifier=tokenizer->get_token_identifier(); + StringName identifier = tokenizer->get_token_identifier(); p_class->extends_class.push_back(identifier); tokenizer->advance(1); - if (tokenizer->get_token()!=GDTokenizer::TK_PERIOD) + if (tokenizer->get_token() != GDTokenizer::TK_PERIOD) return; } - } void GDParser::_parse_class(ClassNode *p_class) { int indent_level = tab_level.back()->get(); - while(true) { + while (true) { GDTokenizer::Token token = tokenizer->get_token(); if (error_set) return; - if (indent_level>tab_level.back()->get()) { - p_class->end_line=tokenizer->get_token_line(); + if (indent_level > tab_level.back()->get()) { + p_class->end_line = tokenizer->get_token_line(); return; //go back a level } - switch(token) { + switch (token) { case GDTokenizer::TK_EOF: - p_class->end_line=tokenizer->get_token_line(); + p_class->end_line = tokenizer->get_token_line(); case GDTokenizer::TK_ERROR: { return; //go back //end of file! @@ -2183,7 +2169,7 @@ void GDParser::_parse_class(ClassNode *p_class) { case GDTokenizer::TK_NEWLINE: { if (!_parse_newline()) { if (!error_set) { - p_class->end_line=tokenizer->get_token_line(); + p_class->end_line = tokenizer->get_token_line(); } return; } @@ -2207,7 +2193,7 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - p_class->tool=true; + p_class->tool = true; tokenizer->advance(); } break; @@ -2217,7 +2203,7 @@ void GDParser::_parse_class(ClassNode *p_class) { StringName name; StringName extends; - if (tokenizer->get_token(1)!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token(1) != GDTokenizer::TK_IDENTIFIER) { _set_error("'class' syntax: 'class <Name>:' or 'class <Name> extends <BaseClass>:'"); return; @@ -2227,16 +2213,15 @@ void GDParser::_parse_class(ClassNode *p_class) { ClassNode *newclass = alloc_node<ClassNode>(); newclass->initializer = alloc_node<BlockNode>(); - newclass->initializer->parent_class=newclass; + newclass->initializer->parent_class = newclass; newclass->ready = alloc_node<BlockNode>(); - newclass->ready->parent_class=newclass; - newclass->name=name; - newclass->owner=p_class; + newclass->ready->parent_class = newclass; + newclass->name = name; + newclass->owner = p_class; p_class->subclasses.push_back(newclass); - - if (tokenizer->get_token()==GDTokenizer::TK_PR_EXTENDS) { + if (tokenizer->get_token() == GDTokenizer::TK_PR_EXTENDS) { _parse_extends(newclass); if (error_set) @@ -2248,9 +2233,9 @@ void GDParser::_parse_class(ClassNode *p_class) { _set_error("Indented block expected."); return; } - current_class=newclass; + current_class = newclass; _parse_class(newclass); - current_class=p_class; + current_class = p_class; } break; /* this is for functions.... @@ -2261,7 +2246,7 @@ void GDParser::_parse_class(ClassNode *p_class) { */ case GDTokenizer::TK_PR_STATIC: { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) { _set_error("Expected 'func'."); return; @@ -2270,42 +2255,38 @@ void GDParser::_parse_class(ClassNode *p_class) { }; //fallthrough to function case GDTokenizer::TK_PR_FUNCTION: { - bool _static=false; - pending_newline=-1; + bool _static = false; + pending_newline = -1; - if (tokenizer->get_token(-1)==GDTokenizer::TK_PR_STATIC) { + if (tokenizer->get_token(-1) == GDTokenizer::TK_PR_STATIC) { - _static=true; + _static = true; } - tokenizer->advance(); StringName name; - if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC,name)) { - + if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC, name)) { } - - if (name==StringName()) { + if (name == StringName()) { _set_error("Expected identifier after 'func' (syntax: 'func <identifier>([arguments]):' )."); return; } - for(int i=0;i<p_class->functions.size();i++) { - if (p_class->functions[i]->name==name) { - _set_error("Function '"+String(name)+"' already exists in this class (at line: "+itos(p_class->functions[i]->line)+")."); + for (int i = 0; i < p_class->functions.size(); i++) { + if (p_class->functions[i]->name == name) { + _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->functions[i]->line) + ")."); } } - for(int i=0;i<p_class->static_functions.size();i++) { - if (p_class->static_functions[i]->name==name) { - _set_error("Function '"+String(name)+"' already exists in this class (at line: "+itos(p_class->static_functions[i]->line)+")."); + for (int i = 0; i < p_class->static_functions.size(); i++) { + if (p_class->static_functions[i]->name == name) { + _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->static_functions[i]->line) + ")."); } } - - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after identifier (syntax: 'func <identifier>([arguments]):' )."); return; @@ -2314,39 +2295,37 @@ void GDParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); Vector<StringName> arguments; - Vector<Node*> default_values; + Vector<Node *> default_values; int fnline = tokenizer->get_token_line(); - - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { //has arguments - bool defaulting=false; - while(true) { + bool defaulting = false; + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); continue; } - if (tokenizer->get_token()==GDTokenizer::TK_PR_VAR) { + if (tokenizer->get_token() == GDTokenizer::TK_PR_VAR) { tokenizer->advance(); //var before the identifier is allowed } - - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for argument."); return; } - StringName argname=tokenizer->get_token_identifier(); + StringName argname = tokenizer->get_token_identifier(); arguments.push_back(argname); tokenizer->advance(); - if (defaulting && tokenizer->get_token()!=GDTokenizer::TK_OP_ASSIGN) { + if (defaulting && tokenizer->get_token() != GDTokenizer::TK_OP_ASSIGN) { _set_error("Default parameter expected."); return; @@ -2354,21 +2333,20 @@ void GDParser::_parse_class(ClassNode *p_class) { //tokenizer->advance(); - - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { - defaulting=true; + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { + defaulting = true; tokenizer->advance(1); - Node *defval=NULL; + Node *defval = NULL; - defval=_parse_and_reduce_expression(p_class,_static); + defval = _parse_and_reduce_expression(p_class, _static); if (!defval || error_set) return; OperatorNode *on = alloc_node<OperatorNode>(); - on->op=OperatorNode::OP_ASSIGN; + on->op = OperatorNode::OP_ASSIGN; IdentifierNode *in = alloc_node<IdentifierNode>(); - in->name=argname; + in->name = argname; on->arguments.push_back(in); on->arguments.push_back(defval); @@ -2381,14 +2359,14 @@ void GDParser::_parse_class(ClassNode *p_class) { default_values.push_back(on); } - while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); continue; - } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')'."); return; @@ -2396,68 +2374,63 @@ void GDParser::_parse_class(ClassNode *p_class) { break; } - - } tokenizer->advance(); BlockNode *block = alloc_node<BlockNode>(); - block->parent_class=p_class; + block->parent_class = p_class; - if (name=="_init") { + if (name == "_init") { if (p_class->extends_used) { OperatorNode *cparent = alloc_node<OperatorNode>(); - cparent->op=OperatorNode::OP_PARENT_CALL; + cparent->op = OperatorNode::OP_PARENT_CALL; block->statements.push_back(cparent); IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name="_init"; + id->name = "_init"; cparent->arguments.push_back(id); - if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("expected '(' for parent constructor arguments."); } tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { //has arguments - parenthesis ++; - while(true) { + parenthesis++; + while (true) { - Node *arg = _parse_and_reduce_expression(p_class,_static); + Node *arg = _parse_and_reduce_expression(p_class, _static); cparent->arguments.push_back(arg); - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); continue; - } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')'."); return; } break; - } - parenthesis --; + parenthesis--; } tokenizer->advance(); } } else { - - if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) { _set_error("Parent constructor call found for a class without inheritance."); return; } - } } @@ -2468,31 +2441,29 @@ void GDParser::_parse_class(ClassNode *p_class) { } FunctionNode *function = alloc_node<FunctionNode>(); - function->name=name; - function->arguments=arguments; - function->default_values=default_values; - function->_static=_static; - function->line=fnline; - + function->name = name; + function->arguments = arguments; + function->default_values = default_values; + function->_static = _static; + function->line = fnline; if (_static) p_class->static_functions.push_back(function); else p_class->functions.push_back(function); - - current_function=function; - function->body=block; - current_block=block; - _parse_block(block,_static); - current_block=NULL; + current_function = function; + function->body = block; + current_block = block; + _parse_block(block, _static); + current_block = NULL; //arguments } break; case GDTokenizer::TK_PR_SIGNAL: { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier after 'signal'."); return; } @@ -2501,22 +2472,20 @@ void GDParser::_parse_class(ClassNode *p_class) { sig.name = tokenizer->get_token_identifier(); tokenizer->advance(); - - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { tokenizer->advance(); - while(true) { - if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (true) { + if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); continue; } - - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); break; } - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier in signal argument."); return; } @@ -2524,13 +2493,13 @@ void GDParser::_parse_class(ClassNode *p_class) { sig.arguments.push_back(tokenizer->get_token_identifier()); tokenizer->advance(); - while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')' after signal parameter identifier."); return; } @@ -2548,67 +2517,65 @@ void GDParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) { + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) { Variant::Type type = tokenizer->get_token_type(); - if (type==Variant::NIL) { + if (type == Variant::NIL) { _set_error("Can't export null type."); return; } - current_export.type=type; - current_export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE; + current_export.type = type; + current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { // hint expected next! tokenizer->advance(); - switch(current_export.type) { - + switch (current_export.type) { case Variant::INT: { - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="FLAGS") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") { - current_export.hint=PROPERTY_HINT_ALL_FLAGS; + current_export.hint = PROPERTY_HINT_ALL_FLAGS; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { break; } - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) - { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { _set_error("Expected ')' or ',' in bit flags hint."); return; } - current_export.hint=PROPERTY_HINT_FLAGS; + current_export.hint = PROPERTY_HINT_FLAGS; tokenizer->advance(); bool first = true; - while(true) { + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { + current_export = PropertyInfo(); _set_error("Expected a string constant in named bit flags hint."); return; } String c = tokenizer->get_token_constant(); if (!first) - current_export.hint_string+=","; + current_export.hint_string += ","; else - first=false; + first = false; - current_export.hint_string+=c.xml_escape(); + current_export.hint_string += c.xml_escape(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { + current_export = PropertyInfo(); _set_error("Expected ')' or ',' in named bit flags hint."); return; } @@ -2618,39 +2585,38 @@ void GDParser::_parse_class(ClassNode *p_class) { break; } - if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING) { + if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration - current_export.hint=PROPERTY_HINT_ENUM; - bool first=true; - while(true) { + current_export.hint = PROPERTY_HINT_ENUM; + bool first = true; + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a string constant in enumeration hint."); return; } String c = tokenizer->get_token_constant(); if (!first) - current_export.hint_string+=","; + current_export.hint_string += ","; else - first=false; + first = false; - current_export.hint_string+=c.xml_escape(); + current_export.hint_string += c.xml_escape(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { + current_export = PropertyInfo(); _set_error("Expected ')' or ',' in enumeration hint."); return; } tokenizer->advance(); - } break; @@ -2659,10 +2625,10 @@ void GDParser::_parse_class(ClassNode *p_class) { }; //fallthrough to use the same case Variant::REAL: { - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="EASE") { - current_export.hint=PROPERTY_HINT_EXP_EASING; + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EASE") { + current_export.hint = PROPERTY_HINT_EXP_EASING; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } @@ -2670,146 +2636,143 @@ void GDParser::_parse_class(ClassNode *p_class) { } // range - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="EXP") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EXP") { - current_export.hint=PROPERTY_HINT_EXP_RANGE; + current_export.hint = PROPERTY_HINT_EXP_RANGE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - else if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + else if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { _set_error("Expected ')' or ',' in exponential range hint."); return; } tokenizer->advance(); - } - else - current_export.hint=PROPERTY_HINT_RANGE; + } else + current_export.hint = PROPERTY_HINT_RANGE; - float sign=1.0; + float sign = 1.0; - if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) { - sign=-1; + if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) { + sign = -1; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a range in numeric hint."); return; - } - current_export.hint_string=rtos(sign*double(tokenizer->get_token_constant())); + current_export.hint_string = rtos(sign * double(tokenizer->get_token_constant())); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { - current_export.hint_string="0,"+current_export.hint_string; + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { + current_export.hint_string = "0," + current_export.hint_string; break; } - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected ',' or ')' in numeric range hint."); return; } tokenizer->advance(); - sign=1.0; - if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) { - sign=-1; + sign = 1.0; + if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) { + sign = -1; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a number as upper bound in numeric range hint."); return; } - current_export.hint_string+=","+rtos(sign*double(tokenizer->get_token_constant())); + current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant())); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected ',' or ')' in numeric range hint."); return; } tokenizer->advance(); - sign=1.0; - if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) { - sign=-1; + sign = 1.0; + if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) { + sign = -1; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a number as step in numeric range hint."); return; } - current_export.hint_string+=","+rtos(sign*double(tokenizer->get_token_constant())); + current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant())); tokenizer->advance(); } break; case Variant::STRING: { - if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING) { + if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration - current_export.hint=PROPERTY_HINT_ENUM; - bool first=true; - while(true) { + current_export.hint = PROPERTY_HINT_ENUM; + bool first = true; + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a string constant in enumeration hint."); return; } String c = tokenizer->get_token_constant(); if (!first) - current_export.hint_string+=","; + current_export.hint_string += ","; else - first=false; + first = false; - current_export.hint_string+=c.xml_escape(); + current_export.hint_string += c.xml_escape(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { + current_export = PropertyInfo(); _set_error("Expected ')' or ',' in enumeration hint."); return; } tokenizer->advance(); - } break; } - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="DIR") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "DIR") { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) - current_export.hint=PROPERTY_HINT_DIR; - else if (tokenizer->get_token()==GDTokenizer::TK_COMMA ) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) + current_export.hint = PROPERTY_HINT_DIR; + else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier()=="GLOBAL")) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) { _set_error("Expected 'GLOBAL' after comma in directory hint."); return; } @@ -2817,42 +2780,41 @@ void GDParser::_parse_class(ClassNode *p_class) { _set_error("Global filesystem hints may only be used in tool scripts."); return; } - current_export.hint=PROPERTY_HINT_GLOBAL_DIR; + current_export.hint = PROPERTY_HINT_GLOBAL_DIR; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } - } - else { + } else { _set_error("Expected ')' or ',' in hint."); return; } break; } - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="FILE") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FILE") { - current_export.hint=PROPERTY_HINT_FILE; + current_export.hint = PROPERTY_HINT_FILE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="GLOBAL") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "GLOBAL") { if (!p_class->tool) { _set_error("Global filesystem hints may only be used in tool scripts."); return; } - current_export.hint=PROPERTY_HINT_GLOBAL_FILE; + current_export.hint = PROPERTY_HINT_GLOBAL_FILE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) + else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) tokenizer->advance(); else { _set_error("Expected ')' or ',' in hint."); @@ -2860,31 +2822,30 @@ void GDParser::_parse_class(ClassNode *p_class) { } } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { - if (current_export.hint==PROPERTY_HINT_GLOBAL_FILE) + if (current_export.hint == PROPERTY_HINT_GLOBAL_FILE) _set_error("Expected string constant with filter"); else _set_error("Expected 'GLOBAL' or string constant with filter"); return; } - current_export.hint_string=tokenizer->get_token_constant(); + current_export.hint_string = tokenizer->get_token_constant(); tokenizer->advance(); - } - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } break; } - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="MULTILINE") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "MULTILINE") { - current_export.hint=PROPERTY_HINT_MULTILINE_TEXT; + current_export.hint = PROPERTY_HINT_MULTILINE_TEXT; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } @@ -2893,20 +2854,20 @@ void GDParser::_parse_class(ClassNode *p_class) { } break; case Variant::COLOR: { - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER ) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Color type hint expects RGB or RGBA as hints"); return; } String identifier = tokenizer->get_token_identifier(); - if (identifier=="RGB") { - current_export.hint=PROPERTY_HINT_COLOR_NO_ALPHA; - } else if (identifier=="RGBA") { + if (identifier == "RGB") { + current_export.hint = PROPERTY_HINT_COLOR_NO_ALPHA; + } else if (identifier == "RGBA") { //none } else { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Color type hint expects RGB or RGBA as hints"); return; } @@ -2915,47 +2876,44 @@ void GDParser::_parse_class(ClassNode *p_class) { } break; default: { - current_export=PropertyInfo(); - _set_error("Type '"+Variant::get_type_name(type)+"' can't take hints."); + current_export = PropertyInfo(); + _set_error("Type '" + Variant::get_type_name(type) + "' can't take hints."); return; } break; } - } - } else if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { + } else if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { String identifier = tokenizer->get_token_identifier(); - if (!ObjectTypeDB::is_type(identifier,"Resource")) { + if (!ObjectTypeDB::is_type(identifier, "Resource")) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Export hint not a type or resource."); } - current_export.type=Variant::OBJECT; - current_export.hint=PROPERTY_HINT_RESOURCE_TYPE; - current_export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE; + current_export.type = Variant::OBJECT; + current_export.hint = PROPERTY_HINT_RESOURCE_TYPE; + current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; - current_export.hint_string=identifier; + current_export.hint_string = identifier; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected ')' or ',' after export hint."); return; - } tokenizer->advance(); - } - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected 'var'."); return; } @@ -2963,10 +2921,10 @@ void GDParser::_parse_class(ClassNode *p_class) { }; //fallthrough to var case GDTokenizer::TK_PR_ONREADY: { - if (token==GDTokenizer::TK_PR_ONREADY) { + if (token == GDTokenizer::TK_PR_ONREADY) { //may be fallthrough from export, ignore if so tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) { _set_error("Expected 'var'."); return; } @@ -2976,37 +2934,37 @@ void GDParser::_parse_class(ClassNode *p_class) { //variale declaration and (eventual) initialization ClassNode::Member member; - bool autoexport = tokenizer->get_token(-1)==GDTokenizer::TK_PR_EXPORT; - if (current_export.type!=Variant::NIL) { - member._export=current_export; - current_export=PropertyInfo(); + bool autoexport = tokenizer->get_token(-1) == GDTokenizer::TK_PR_EXPORT; + if (current_export.type != Variant::NIL) { + member._export = current_export; + current_export = PropertyInfo(); } - bool onready = tokenizer->get_token(-1)==GDTokenizer::TK_PR_ONREADY; + bool onready = tokenizer->get_token(-1) == GDTokenizer::TK_PR_ONREADY; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for member variable name."); return; } - member.identifier=tokenizer->get_token_identifier(); - member.expression=NULL; - member._export.name=member.identifier; - member.line=tokenizer->get_token_line(); + member.identifier = tokenizer->get_token_identifier(); + member.expression = NULL; + member._export.name = member.identifier; + member.line = tokenizer->get_token_line(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { #ifdef DEBUG_ENABLED int line = tokenizer->get_token_line(); #endif tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_class,false,autoexport); + subexpr = _parse_and_reduce_expression(p_class, false, autoexport); if (!subexpr) { if (_recover_from_completion()) { break; @@ -3015,24 +2973,23 @@ void GDParser::_parse_class(ClassNode *p_class) { } //discourage common error - if (!onready && subexpr->type==Node::TYPE_OPERATOR) { + if (!onready && subexpr->type == Node::TYPE_OPERATOR) { - OperatorNode *op=static_cast<OperatorNode*>(subexpr); - if (op->op==OperatorNode::OP_CALL && op->arguments[0]->type==Node::TYPE_SELF && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { - IdentifierNode *id=static_cast<IdentifierNode*>(op->arguments[1]); - if (id->name=="get_node") { + OperatorNode *op = static_cast<OperatorNode *>(subexpr); + if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_SELF && op->arguments[1]->type == Node::TYPE_IDENTIFIER) { + IdentifierNode *id = static_cast<IdentifierNode *>(op->arguments[1]); + if (id->name == "get_node") { - _set_error("Use 'onready var "+String(member.identifier)+" = get_node(..)' instead"); + _set_error("Use 'onready var " + String(member.identifier) + " = get_node(..)' instead"); return; - } } } - member.expression=subexpr; + member.expression = subexpr; if (autoexport) { - if (1)/*(subexpr->type==Node::TYPE_ARRAY) { + if (1) /*(subexpr->type==Node::TYPE_ARRAY) { member._export.type=Variant::ARRAY; @@ -3042,54 +2999,53 @@ void GDParser::_parse_class(ClassNode *p_class) { } else*/ { - if (subexpr->type!=Node::TYPE_CONSTANT) { + if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } - ConstantNode *cn = static_cast<ConstantNode*>(subexpr); - if (cn->value.get_type()==Variant::NIL) { + ConstantNode *cn = static_cast<ConstantNode *>(subexpr); + if (cn->value.get_type() == Variant::NIL) { _set_error("Can't accept a null constant expression for infering export type."); return; } - member._export.type=cn->value.get_type(); - member._export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE; - if (cn->value.get_type()==Variant::OBJECT) { + member._export.type = cn->value.get_type(); + member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; + if (cn->value.get_type() == Variant::OBJECT) { Object *obj = cn->value; Resource *res = obj->cast_to<Resource>(); - if(res==NULL) { + if (res == NULL) { _set_error("Exported constant not a type or resource."); return; } - member._export.hint=PROPERTY_HINT_RESOURCE_TYPE; - member._export.hint_string=res->get_type(); + member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; + member._export.hint_string = res->get_type(); } } } #ifdef TOOLS_ENABLED - if (subexpr->type==Node::TYPE_CONSTANT && member._export.type!=Variant::NIL) { + if (subexpr->type == Node::TYPE_CONSTANT && member._export.type != Variant::NIL) { - ConstantNode *cn = static_cast<ConstantNode*>(subexpr); - if (cn->value.get_type()!=Variant::NIL) { - member.default_value=cn->value; + ConstantNode *cn = static_cast<ConstantNode *>(subexpr); + if (cn->value.get_type() != Variant::NIL) { + member.default_value = cn->value; } } #endif IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=member.identifier; + id->name = member.identifier; OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_INIT_ASSIGN; + op->op = OperatorNode::OP_INIT_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(subexpr); - #ifdef DEBUG_ENABLED NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=line; + nl->line = line; if (onready) p_class->ready->statements.push_back(nl); else @@ -3100,8 +3056,6 @@ void GDParser::_parse_class(ClassNode *p_class) { else p_class->initializer->statements.push_back(op); - - } else { if (autoexport) { @@ -3109,36 +3063,33 @@ void GDParser::_parse_class(ClassNode *p_class) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } - } - if (tokenizer->get_token()==GDTokenizer::TK_PR_SETGET) { - + if (tokenizer->get_token() == GDTokenizer::TK_PR_SETGET) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { //just comma means using only getter - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for setter function after 'notify'."); } - member.setter=tokenizer->get_token_identifier(); + member.setter = tokenizer->get_token_identifier(); tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { //there is a getter tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for getter function after ','."); } - member.getter=tokenizer->get_token_identifier(); + member.getter = tokenizer->get_token_identifier(); tokenizer->advance(); - } } @@ -3155,25 +3106,25 @@ void GDParser::_parse_class(ClassNode *p_class) { ClassNode::Constant constant; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected name (identifier) for constant."); return; } - constant.identifier=tokenizer->get_token_identifier(); + constant.identifier = tokenizer->get_token_identifier(); tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() != GDTokenizer::TK_OP_ASSIGN) { _set_error("Constant expects assignment."); return; } tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_class,true,true); + subexpr = _parse_and_reduce_expression(p_class, true, true); if (!subexpr) { if (_recover_from_completion()) { break; @@ -3181,10 +3132,10 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - if (subexpr->type!=Node::TYPE_CONSTANT) { + if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Expected constant expression"); } - constant.expression=subexpr; + constant.expression = subexpr; p_class->constant_expressions.push_back(constant); @@ -3195,32 +3146,25 @@ void GDParser::_parse_class(ClassNode *p_class) { } break; - default: { - _set_error(String()+"Unexpected token: "+tokenizer->get_token_name(tokenizer->get_token())+":"+tokenizer->get_token_identifier()); + _set_error(String() + "Unexpected token: " + tokenizer->get_token_name(tokenizer->get_token()) + ":" + tokenizer->get_token_identifier()); return; } break; - } - } - - } - -void GDParser::_set_error(const String& p_error, int p_line, int p_column) { - +void GDParser::_set_error(const String &p_error, int p_line, int p_column) { if (error_set) return; //allow no further errors - error=p_error; - error_line=p_line<0?tokenizer->get_token_line():p_line; - error_column=p_column<0?tokenizer->get_token_column():p_column; - error_set=true; + error = p_error; + error_line = p_line < 0 ? tokenizer->get_token_line() : p_line; + error_column = p_column < 0 ? tokenizer->get_token_column() : p_column; + error_set = true; } String GDParser::get_error() const { @@ -3237,27 +3181,25 @@ int GDParser::get_error_column() const { return error_column; } +Error GDParser::_parse(const String &p_base_path) { -Error GDParser::_parse(const String& p_base_path) { - - - base_path=p_base_path; + base_path = p_base_path; clear(); //assume class ClassNode *main_class = alloc_node<ClassNode>(); main_class->initializer = alloc_node<BlockNode>(); - main_class->initializer->parent_class=main_class; + main_class->initializer->parent_class = main_class; main_class->ready = alloc_node<BlockNode>(); - main_class->ready->parent_class=main_class; - current_class=main_class; + main_class->ready->parent_class = main_class; + current_class = main_class; _parse_class(main_class); - if (tokenizer->get_token()==GDTokenizer::TK_ERROR) { - error_set=false; - _set_error("Parse Error: "+tokenizer->get_token_error()); + if (tokenizer->get_token() == GDTokenizer::TK_ERROR) { + error_set = false; + _set_error("Parse Error: " + tokenizer->get_token_error()); } if (error_set) { @@ -3267,60 +3209,59 @@ Error GDParser::_parse(const String& p_base_path) { return OK; } -Error GDParser::parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path, const String &p_self_path) { +Error GDParser::parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path, const String &p_self_path) { - for_completion=false; - validating=false; - completion_type=COMPLETION_NONE; - completion_node=NULL; - completion_class=NULL; - completion_function=NULL; - completion_block=NULL; - completion_found=false; - current_block=NULL; - current_class=NULL; - current_function=NULL; + for_completion = false; + validating = false; + completion_type = COMPLETION_NONE; + completion_node = NULL; + completion_class = NULL; + completion_function = NULL; + completion_block = NULL; + completion_found = false; + current_block = NULL; + current_class = NULL; + current_function = NULL; - self_path=p_self_path; - GDTokenizerBuffer *tb = memnew( GDTokenizerBuffer ); + self_path = p_self_path; + GDTokenizerBuffer *tb = memnew(GDTokenizerBuffer); tb->set_code_buffer(p_bytecode); - tokenizer=tb; + tokenizer = tb; Error ret = _parse(p_base_path); memdelete(tb); - tokenizer=NULL; + tokenizer = NULL; return ret; } +Error GDParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion) { -Error GDParser::parse(const String& p_code, const String& p_base_path, bool p_just_validate, const String &p_self_path,bool p_for_completion) { - - completion_type=COMPLETION_NONE; - completion_node=NULL; - completion_class=NULL; - completion_function=NULL; - completion_block=NULL; - completion_found=false; - current_block=NULL; - current_class=NULL; + completion_type = COMPLETION_NONE; + completion_node = NULL; + completion_class = NULL; + completion_function = NULL; + completion_block = NULL; + completion_found = false; + current_block = NULL; + current_class = NULL; - current_function=NULL; + current_function = NULL; - self_path=p_self_path; - GDTokenizerText *tt = memnew( GDTokenizerText ); + self_path = p_self_path; + GDTokenizerText *tt = memnew(GDTokenizerText); tt->set_code(p_code); - validating=p_just_validate; - for_completion=p_for_completion; - tokenizer=tt; + validating = p_just_validate; + for_completion = p_for_completion; + tokenizer = tt; Error ret = _parse(p_base_path); memdelete(tt); - tokenizer=NULL; + tokenizer = NULL; return ret; } bool GDParser::is_tool_script() const { - return (head && head->type==Node::TYPE_CLASS && static_cast<const ClassNode*>(head)->tool); + return (head && head->type == Node::TYPE_CLASS && static_cast<const ClassNode *>(head)->tool); } const GDParser::Node *GDParser::get_parse_tree() const { @@ -3330,43 +3271,41 @@ const GDParser::Node *GDParser::get_parse_tree() const { void GDParser::clear() { - while(list) { + while (list) { - Node *l=list; - list=list->next; + Node *l = list; + list = list->next; memdelete(l); } - head=NULL; - list=NULL; + head = NULL; + list = NULL; - completion_type=COMPLETION_NONE; - completion_node=NULL; - completion_class=NULL; - completion_function=NULL; - completion_block=NULL; - current_block=NULL; - current_class=NULL; + completion_type = COMPLETION_NONE; + completion_node = NULL; + completion_class = NULL; + completion_function = NULL; + completion_block = NULL; + current_block = NULL; + current_class = NULL; - completion_found=false; + completion_found = false; - current_function=NULL; + current_function = NULL; - validating=false; - for_completion=false; - error_set=false; + validating = false; + for_completion = false; + error_set = false; tab_level.clear(); tab_level.push_back(0); - error_line=0; - error_column=0; - pending_newline=-1; - parenthesis=0; - current_export.type=Variant::NIL; - error=""; - + error_line = 0; + error_column = 0; + pending_newline = -1; + parenthesis = 0; + current_export.type = Variant::NIL; + error = ""; } - GDParser::CompletionType GDParser::get_completion_type() { return completion_type; @@ -3382,12 +3321,12 @@ int GDParser::get_completion_line() { return completion_line; } -Variant::Type GDParser::get_completion_built_in_constant(){ +Variant::Type GDParser::get_completion_built_in_constant() { return completion_built_in_constant; } -GDParser::Node *GDParser::get_completion_node(){ +GDParser::Node *GDParser::get_completion_node() { return completion_node; } @@ -3397,12 +3336,12 @@ GDParser::BlockNode *GDParser::get_completion_block() { return completion_block; } -GDParser::ClassNode *GDParser::get_completion_class(){ +GDParser::ClassNode *GDParser::get_completion_class() { return completion_class; } -GDParser::FunctionNode *GDParser::get_completion_function(){ +GDParser::FunctionNode *GDParser::get_completion_function() { return completion_function; } @@ -3414,12 +3353,11 @@ int GDParser::get_completion_argument_index() { GDParser::GDParser() { - head=NULL; - list=NULL; - tokenizer=NULL; - pending_newline=-1; + head = NULL; + list = NULL; + tokenizer = NULL; + pending_newline = -1; clear(); - } GDParser::~GDParser() { diff --git a/modules/gdscript/gd_parser.h b/modules/gdscript/gd_parser.h index 8173cc348..9ee7c531f 100644 --- a/modules/gdscript/gd_parser.h +++ b/modules/gdscript/gd_parser.h @@ -29,14 +29,13 @@ #ifndef GD_PARSER_H #define GD_PARSER_H -#include "gd_tokenizer.h" #include "gd_functions.h" +#include "gd_tokenizer.h" #include "map.h" #include "object.h" class GDParser { public: - struct Node { enum Type { @@ -58,7 +57,7 @@ public: TYPE_NEWLINE, }; - Node * next; + Node *next; int line; int column; Type type; @@ -77,7 +76,6 @@ public: StringName extends_file; Vector<StringName> extends_class; - struct Member { PropertyInfo _export; #ifdef TOOLS_ENABLED @@ -99,11 +97,11 @@ public: Vector<StringName> arguments; }; - Vector<ClassNode*> subclasses; + Vector<ClassNode *> subclasses; Vector<Member> variables; Vector<Constant> constant_expressions; - Vector<FunctionNode*> functions; - Vector<FunctionNode*> static_functions; + Vector<FunctionNode *> functions; + Vector<FunctionNode *> static_functions; Vector<Signal> _signals; BlockNode *initializer; BlockNode *ready; @@ -111,73 +109,86 @@ public: //Vector<Node*> initializers; int end_line; - ClassNode() { tool=false; type=TYPE_CLASS; extends_used=false; end_line=-1; owner=NULL;} + ClassNode() { + tool = false; + type = TYPE_CLASS; + extends_used = false; + end_line = -1; + owner = NULL; + } }; - - struct FunctionNode : public Node { bool _static; StringName name; Vector<StringName> arguments; - Vector<Node*> default_values; + Vector<Node *> default_values; BlockNode *body; - FunctionNode() { type=TYPE_FUNCTION; _static=false; } - + FunctionNode() { + type = TYPE_FUNCTION; + _static = false; + } }; struct BlockNode : public Node { ClassNode *parent_class; BlockNode *parent_block; - Map<StringName,int> locals; - List<Node*> statements; + Map<StringName, int> locals; + List<Node *> statements; Vector<StringName> variables; Vector<int> variable_lines; //the following is useful for code completion - List<BlockNode*> sub_blocks; + List<BlockNode *> sub_blocks; int end_line; - BlockNode() { type=TYPE_BLOCK; end_line=-1; parent_block=NULL; parent_class=NULL; } + BlockNode() { + type = TYPE_BLOCK; + end_line = -1; + parent_block = NULL; + parent_class = NULL; + } }; struct TypeNode : public Node { Variant::Type vtype; - TypeNode() { type=TYPE_TYPE; } + TypeNode() { type = TYPE_TYPE; } }; struct BuiltInFunctionNode : public Node { GDFunctions::Function function; - BuiltInFunctionNode() { type=TYPE_BUILT_IN_FUNCTION; } + BuiltInFunctionNode() { type = TYPE_BUILT_IN_FUNCTION; } }; struct IdentifierNode : public Node { StringName name; - IdentifierNode() { type=TYPE_IDENTIFIER; } + IdentifierNode() { type = TYPE_IDENTIFIER; } }; struct LocalVarNode : public Node { StringName name; Node *assign; - LocalVarNode() { type=TYPE_LOCAL_VAR; assign=NULL;} + LocalVarNode() { + type = TYPE_LOCAL_VAR; + assign = NULL; + } }; struct ConstantNode : public Node { Variant value; - ConstantNode() { type=TYPE_CONSTANT; } + ConstantNode() { type = TYPE_CONSTANT; } }; struct ArrayNode : public Node { - Vector<Node*> elements; - ArrayNode() { type=TYPE_ARRAY; } + Vector<Node *> elements; + ArrayNode() { type = TYPE_ARRAY; } }; - struct DictionaryNode : public Node { struct Pair { @@ -187,11 +198,11 @@ public: }; Vector<Pair> elements; - DictionaryNode() { type=TYPE_DICTIONARY; } + DictionaryNode() { type = TYPE_DICTIONARY; } }; struct SelfNode : public Node { - SelfNode() { type=TYPE_SELF; } + SelfNode() { type = TYPE_SELF; } }; struct OperatorNode : public Node { @@ -251,8 +262,8 @@ public: Operator op; - Vector<Node*> arguments; - OperatorNode() { type=TYPE_OPERATOR; } + Vector<Node *> arguments; + OperatorNode() { type = TYPE_OPERATOR; } }; struct ControlFlowNode : public Node { @@ -267,28 +278,32 @@ public: }; CFType cf_type; - Vector<Node*> arguments; + Vector<Node *> arguments; BlockNode *body; BlockNode *body_else; ControlFlowNode *_else; //used for if - ControlFlowNode() { type=TYPE_CONTROL_FLOW; cf_type=CF_IF; body=NULL; body_else=NULL;} + ControlFlowNode() { + type = TYPE_CONTROL_FLOW; + cf_type = CF_IF; + body = NULL; + body_else = NULL; + } }; struct AssertNode : public Node { - Node* condition; - AssertNode() { type=TYPE_ASSERT; } + Node *condition; + AssertNode() { type = TYPE_ASSERT; } }; struct BreakpointNode : public Node { - BreakpointNode() { type=TYPE_BREAKPOINT; } + BreakpointNode() { type = TYPE_BREAKPOINT; } }; struct NewLineNode : public Node { - NewLineNode() { type=TYPE_NEWLINE; } + NewLineNode() { type = TYPE_NEWLINE; } }; - struct Expression { bool is_op; @@ -298,8 +313,7 @@ public: }; }; - -/* + /* struct OperatorNode : public Node { DataType return_cache; @@ -381,18 +395,13 @@ public: COMPLETION_VIRTUAL_FUNC }; - - private: - - GDTokenizer *tokenizer; - Node *head; Node *list; - template<class T> - T* alloc_node(); + template <class T> + T *alloc_node(); bool validating; bool for_completion; @@ -409,12 +418,11 @@ private: String base_path; String self_path; - ClassNode *current_class; FunctionNode *current_function; BlockNode *current_block; - bool _get_completable_identifier(CompletionType p_type,StringName& identifier); + bool _get_completable_identifier(CompletionType p_type, StringName &identifier); void _make_completable_call(int p_arg); CompletionType completion_type; @@ -431,31 +439,29 @@ private: PropertyInfo current_export; - void _set_error(const String& p_error, int p_line=-1, int p_column=-1); + void _set_error(const String &p_error, int p_line = -1, int p_column = -1); bool _recover_from_completion(); - - bool _parse_arguments(Node* p_parent, Vector<Node*>& p_args, bool p_static, bool p_can_codecomplete=false); - bool _enter_indent_block(BlockNode *p_block=NULL); + bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false); + bool _enter_indent_block(BlockNode *p_block = NULL); bool _parse_newline(); - Node* _parse_expression(Node *p_parent, bool p_static, bool p_allow_assign=false, bool p_parsing_constant=false); - Node* _reduce_expression(Node *p_node,bool p_to_const=false); - Node* _parse_and_reduce_expression(Node *p_parent,bool p_static,bool p_reduce_const=false,bool p_allow_assign=false); + Node *_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign = false, bool p_parsing_constant = false); + Node *_reduce_expression(Node *p_node, bool p_to_const = false); + Node *_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const = false, bool p_allow_assign = false); - void _parse_block(BlockNode *p_block,bool p_static); + void _parse_block(BlockNode *p_block, bool p_static); void _parse_extends(ClassNode *p_class); void _parse_class(ClassNode *p_class); bool _end_statement(); - Error _parse(const String& p_base_path); + Error _parse(const String &p_base_path); public: - String get_error() const; int get_error_line() const; int get_error_column() const; - Error parse(const String& p_code, const String& p_base_path="", bool p_just_validate=false,const String& p_self_path="",bool p_for_completion=false); - Error parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path="",const String& p_self_path=""); + Error parse(const String &p_code, const String &p_base_path = "", bool p_just_validate = false, const String &p_self_path = "", bool p_for_completion = false); + Error parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path = "", const String &p_self_path = ""); bool is_tool_script() const; const Node *get_parse_tree() const; @@ -472,7 +478,6 @@ public: FunctionNode *get_completion_function(); int get_completion_argument_index(); - void clear(); GDParser(); ~GDParser(); diff --git a/modules/gdscript/gd_script.cpp b/modules/gdscript/gd_script.cpp index 6301a0a1b..d0341bf46 100644 --- a/modules/gdscript/gd_script.cpp +++ b/modules/gdscript/gd_script.cpp @@ -27,18 +27,18 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_script.h" -#include "globals.h" -#include "global_constants.h" #include "gd_compiler.h" -#include "os/file_access.h" +#include "global_constants.h" +#include "globals.h" #include "io/file_access_encrypted.h" +#include "os/file_access.h" #include "os/os.h" /////////////////////////// -GDNativeClass::GDNativeClass(const StringName& p_name) { +GDNativeClass::GDNativeClass(const StringName &p_name) { - name=p_name; + name = p_name; } /*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){ @@ -46,33 +46,30 @@ GDNativeClass::GDNativeClass(const StringName& p_name) { }*/ - -bool GDNativeClass::_get(const StringName& p_name,Variant &r_ret) const { +bool GDNativeClass::_get(const StringName &p_name, Variant &r_ret) const { bool ok; int v = ObjectTypeDB::get_integer_constant(name, p_name, &ok); if (ok) { - r_ret=v; + r_ret = v; return true; } else { return false; } } - void GDNativeClass::_bind_methods() { - ObjectTypeDB::bind_method(_MD("new"),&GDNativeClass::_new); - + ObjectTypeDB::bind_method(_MD("new"), &GDNativeClass::_new); } Variant GDNativeClass::_new() { Object *o = instance(); if (!o) { - ERR_EXPLAIN("Class type: '"+String(name)+"' is not instantiable."); - ERR_FAIL_COND_V(!o,Variant()); + ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable."); + ERR_FAIL_COND_V(!o, Variant()); } Reference *ref = o->cast_to<Reference>(); @@ -81,7 +78,6 @@ Variant GDNativeClass::_new() { } else { return o; } - } Object *GDNativeClass::instance() { @@ -89,22 +85,19 @@ Object *GDNativeClass::instance() { return ObjectTypeDB::instance(name); } - - -GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError& r_error) { - +GDInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) { /* STEP 1, CREATE */ - GDInstance* instance = memnew( GDInstance ); - instance->base_ref=p_isref; + GDInstance *instance = memnew(GDInstance); + instance->base_ref = p_isref; instance->members.resize(member_indices.size()); - instance->script=Ref<GDScript>(this); - instance->owner=p_owner; + instance->script = Ref<GDScript>(this); + instance->owner = p_owner; #ifdef DEBUG_ENABLED //needed for hot reloading - for(Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) { - instance->member_indices_cache[E->key()]=E->get().index; + for (Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) { + instance->member_indices_cache[E->key()] = E->get().index; } #endif instance->owner->set_script_instance(instance); @@ -113,51 +106,49 @@ GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Obj instances.insert(instance->owner); - initializer->call(instance,p_args,p_argcount,r_error); + initializer->call(instance, p_args, p_argcount, r_error); - if (r_error.error!=Variant::CallError::CALL_OK) { - instance->script=Ref<GDScript>(); + if (r_error.error != Variant::CallError::CALL_OK) { + instance->script = Ref<GDScript>(); instance->owner->set_script_instance(NULL); instances.erase(p_owner); - ERR_FAIL_COND_V(r_error.error!=Variant::CallError::CALL_OK, NULL); //error constructing + ERR_FAIL_COND_V(r_error.error != Variant::CallError::CALL_OK, NULL); //error constructing } //@TODO make thread safe return instance; - } -Variant GDScript::_new(const Variant** p_args,int p_argcount,Variant::CallError& r_error) { +Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { /* STEP 1, CREATE */ if (!valid) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; REF ref; - Object *owner=NULL; + Object *owner = NULL; - GDScript *_baseptr=this; + GDScript *_baseptr = this; while (_baseptr->_base) { - _baseptr=_baseptr->_base; + _baseptr = _baseptr->_base; } if (_baseptr->native.ptr()) { - owner=_baseptr->native->instance(); + owner = _baseptr->native->instance(); } else { - owner=memnew( Reference ); //by default, no base means use reference + owner = memnew(Reference); //by default, no base means use reference } - Reference *r=owner->cast_to<Reference>(); + Reference *r = owner->cast_to<Reference>(); if (r) { - ref=REF(r); + ref = REF(r); } - - GDInstance* instance = _create_instance(p_args,p_argcount,owner,r!=NULL,r_error); + GDInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error); if (!instance) { if (ref.is_null()) { memdelete(owner); //no owner, sorry @@ -176,7 +167,6 @@ bool GDScript::can_instance() const { //return valid; //any script in GDscript can instance return valid || (!tool && !ScriptServer::is_scripting_enabled()); - } StringName GDScript::get_instance_base_type() const { @@ -192,14 +182,11 @@ struct _GDScriptMemberSort { int index; StringName name; - _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort& p_member) const { return index < p_member.index; } - + _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; } }; - #ifdef TOOLS_ENABLED - void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) { placeholders.erase(p_placeholder); @@ -249,33 +236,30 @@ void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) { }*/ #endif -bool GDScript::get_property_default_value(const StringName& p_property, Variant &r_value) const { +bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const { #ifdef TOOLS_ENABLED //for (const Map<StringName,Variant>::Element *I=member_default_values.front();I;I=I->next()) { // print_line("\t"+String(String(I->key())+":"+String(I->get()))); //} - const Map<StringName,Variant>::Element *E=member_default_values_cache.find(p_property); + const Map<StringName, Variant>::Element *E = member_default_values_cache.find(p_property); if (E) { - r_value=E->get(); + r_value = E->get(); return true; } if (base_cache.is_valid()) { - return base_cache->get_property_default_value(p_property,r_value); + return base_cache->get_property_default_value(p_property, r_value); } #endif return false; - } -ScriptInstance* GDScript::instance_create(Object *p_this) { - +ScriptInstance *GDScript::instance_create(Object *p_this) { if (!tool && !ScriptServer::is_scripting_enabled()) { - #ifdef TOOLS_ENABLED //instance a fake script for editing the values @@ -285,7 +269,7 @@ ScriptInstance* GDScript::instance_create(Object *p_this) { for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { print_line(E->get().name); }*/ - PlaceHolderScriptInstance *si = memnew( PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(),Ref<Script>(this),p_this) ); + PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this)); placeholders.insert(si); //_update_placeholder(si); _update_exports(); @@ -295,66 +279,62 @@ ScriptInstance* GDScript::instance_create(Object *p_this) { #endif } - GDScript *top=this; - while(top->_base) - top=top->_base; + GDScript *top = this; + while (top->_base) + top = top->_base; if (top->native.is_valid()) { - if (!ObjectTypeDB::is_type(p_this->get_type_name(),top->native->get_name())) { + if (!ObjectTypeDB::is_type(p_this->get_type_name(), top->native->get_name())) { if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),0,"Script inherits from native type '"+String(top->native->get_name())+"', so it can't be instanced in object of type: '"+p_this->get_type()+"'"); + GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_type() + "'"); } - ERR_EXPLAIN("Script inherits from native type '"+String(top->native->get_name())+"', so it can't be instanced in object of type: '"+p_this->get_type()+"'"); + ERR_EXPLAIN("Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_type() + "'"); ERR_FAIL_V(NULL); - } } Variant::CallError unchecked_error; - return _create_instance(NULL,0,p_this,p_this->cast_to<Reference>(),unchecked_error); - + return _create_instance(NULL, 0, p_this, p_this->cast_to<Reference>(), unchecked_error); } bool GDScript::instance_has(const Object *p_this) const { - return instances.has((Object*)p_this); + return instances.has((Object *)p_this); } bool GDScript::has_source_code() const { - return source!=""; + return source != ""; } String GDScript::get_source_code() const { return source; } -void GDScript::set_source_code(const String& p_code) { +void GDScript::set_source_code(const String &p_code) { - if (source==p_code) + if (source == p_code) return; - source=p_code; + source = p_code; #ifdef TOOLS_ENABLED - source_changed_cache=true; - //print_line("SC CHANGED "+get_path()); + source_changed_cache = true; +//print_line("SC CHANGED "+get_path()); #endif - } #ifdef TOOLS_ENABLED -void GDScript::_update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames) { +void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) { if (base_cache.is_valid()) { - base_cache->_update_exports_values(values,propnames); + base_cache->_update_exports_values(values, propnames); } - for(Map<StringName,Variant>::Element *E=member_default_values_cache.front();E;E=E->next()) { - values[E->key()]=E->get(); + for (Map<StringName, Variant>::Element *E = member_default_values_cache.front(); E; E = E->next()) { + values[E->key()] = E->get(); } - for (List<PropertyInfo>::Element *E=members_cache.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = members_cache.front(); E; E = E->next()) { propnames.push_back(E->get()); } - } #endif @@ -362,90 +342,87 @@ bool GDScript::_update_exports() { #ifdef TOOLS_ENABLED - bool changed=false; + bool changed = false; if (source_changed_cache) { //print_line("updating source for "+get_path()); - source_changed_cache=false; - changed=true; + source_changed_cache = false; + changed = true; - String basedir=path; + String basedir = path; - if (basedir=="") - basedir=get_path(); + if (basedir == "") + basedir = get_path(); - if (basedir!="") - basedir=basedir.get_base_dir(); + if (basedir != "") + basedir = basedir.get_base_dir(); GDParser parser; - Error err = parser.parse(source,basedir,true,path); + Error err = parser.parse(source, basedir, true, path); - if (err==OK) { + if (err == OK) { - const GDParser::Node* root = parser.get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false); + const GDParser::Node *root = parser.get_parse_tree(); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false); - const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode*>(root); + const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode *>(root); if (base_cache.is_valid()) { base_cache->inheriters_cache.erase(get_instance_ID()); - base_cache=Ref<GDScript>(); + base_cache = Ref<GDScript>(); } - - if (c->extends_used && String(c->extends_file)!="" && String(c->extends_file) != get_path()) { + if (c->extends_used && String(c->extends_file) != "" && String(c->extends_file) != get_path()) { String path = c->extends_file; if (path.is_rel_path()) { String base = get_path(); - if (base=="" || base.is_rel_path()) { + if (base == "" || base.is_rel_path()) { - ERR_PRINT(("Could not resolve relative path for parent class: "+path).utf8().get_data()); + ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data()); } else { - path=base.get_base_dir().plus_file(path); + path = base.get_base_dir().plus_file(path); } } - if (path!=get_path()) { + if (path != get_path()) { Ref<GDScript> bf = ResourceLoader::load(path); if (bf.is_valid()) { //print_line("parent is: "+bf->get_path()); - base_cache=bf; + base_cache = bf; bf->inheriters_cache.insert(get_instance_ID()); //bf->_update_exports(p_instances,true,false); - } } else { - ERR_PRINT(("Path extending itself in "+path).utf8().get_data()); + ERR_PRINT(("Path extending itself in " + path).utf8().get_data()); } } members_cache.clear(); member_default_values_cache.clear(); - for(int i=0;i<c->variables.size();i++) { - if (c->variables[i]._export.type==Variant::NIL) + for (int i = 0; i < c->variables.size(); i++) { + if (c->variables[i]._export.type == Variant::NIL) continue; members_cache.push_back(c->variables[i]._export); //print_line("found "+c->variables[i]._export.name); - member_default_values_cache[c->variables[i].identifier]=c->variables[i].default_value; + member_default_values_cache[c->variables[i].identifier] = c->variables[i].default_value; } _signals.clear(); - for(int i=0;i<c->_signals.size();i++) { - _signals[c->_signals[i].name]=c->_signals[i].arguments; + for (int i = 0; i < c->_signals.size(); i++) { + _signals[c->_signals[i].name] = c->_signals[i].arguments; } } } else { //print_line("unchaged is "+get_path()); - } if (base_cache.is_valid()) { @@ -459,13 +436,13 @@ bool GDScript::_update_exports() { //print_line("updating placeholders for "+get_path()); //update placeholders if any - Map<StringName,Variant> values; + Map<StringName, Variant> values; List<PropertyInfo> propnames; - _update_exports_values(values,propnames); + _update_exports_values(values, propnames); - for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { + for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { - E->get()->update(propnames,values); + E->get()->update(propnames, values); } } @@ -481,14 +458,14 @@ void GDScript::update_exports() { _update_exports(); - Set<ObjectID> copy=inheriters_cache; //might get modified + Set<ObjectID> copy = inheriters_cache; //might get modified //print_line("update exports for "+get_path()+" ic: "+itos(copy.size())); - for(Set<ObjectID>::Element *E=copy.front();E;E=E->next()) { - Object *id=ObjectDB::get_instance(E->get()); + for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) { + Object *id = ObjectDB::get_instance(E->get()); if (!id) continue; - GDScript *s=id->cast_to<GDScript>(); + GDScript *s = id->cast_to<GDScript>(); if (!s) continue; s->update_exports(); @@ -497,70 +474,65 @@ void GDScript::update_exports() { #endif } -void GDScript::_set_subclass_path(Ref<GDScript>& p_sc,const String& p_path) { +void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) { - p_sc->path=p_path; - for(Map<StringName,Ref<GDScript> >::Element *E=p_sc->subclasses.front();E;E=E->next()) { + p_sc->path = p_path; + for (Map<StringName, Ref<GDScript> >::Element *E = p_sc->subclasses.front(); E; E = E->next()) { - _set_subclass_path(E->get(),p_path); + _set_subclass_path(E->get(), p_path); } } Error GDScript::reload(bool p_keep_state) { + ERR_FAIL_COND_V(!p_keep_state && instances.size(), ERR_ALREADY_IN_USE); - ERR_FAIL_COND_V(!p_keep_state && instances.size(),ERR_ALREADY_IN_USE); - - String basedir=path; + String basedir = path; - if (basedir=="") - basedir=get_path(); + if (basedir == "") + basedir = get_path(); - if (basedir!="") - basedir=basedir.get_base_dir(); + if (basedir != "") + basedir = basedir.get_base_dir(); - - - - valid=false; + valid = false; GDParser parser; - Error err = parser.parse(source,basedir,false,path); + Error err = parser.parse(source, basedir, false, path); if (err) { if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),parser.get_error_line(),"Parser Error: "+parser.get_error()); + GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error()); } - _err_print_error("GDScript::reload",path.empty()?"built-in":(const char*)path.utf8().get_data(),parser.get_error_line(),("Parse Error: "+parser.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_PARSE_ERROR); } - bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script(); GDCompiler compiler; - err = compiler.compile(&parser,this,p_keep_state); + err = compiler.compile(&parser, this, p_keep_state); if (err) { if (can_run) { if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),compiler.get_error_line(),"Parser Error: "+compiler.get_error()); + GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error()); } - _err_print_error("GDScript::reload",path.empty()?"built-in":(const char*)path.utf8().get_data(),compiler.get_error_line(),("Compile Error: "+compiler.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_COMPILATION_FAILED); } else { return err; } } - valid=true; + valid = true; - for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) { + for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) { - _set_subclass_path(E->get(),path); + _set_subclass_path(E->get(), path); } #ifdef TOOLS_ENABLED - /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { +/*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { _update_placeholder(E->get()); }*/ @@ -578,74 +550,67 @@ ScriptLanguage *GDScript::get_language() const { return GDScriptLanguage::get_singleton(); } +Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { -Variant GDScript::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { + GDScript *top = this; + while (top) { - - GDScript *top=this; - while(top) { - - Map<StringName,GDFunction*>::Element *E=top->member_functions.find(p_method); + Map<StringName, GDFunction *>::Element *E = top->member_functions.find(p_method); if (E) { if (!E->get()->is_static()) { - WARN_PRINT(String("Can't call non-static function: '"+String(p_method)+"' in script.").utf8().get_data()); + WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data()); } - return E->get()->call(NULL,p_args,p_argcount,r_error); + return E->get()->call(NULL, p_args, p_argcount, r_error); } - top=top->_base; + top = top->_base; } //none found, regular - return Script::call(p_method,p_args,p_argcount,r_error); - + return Script::call(p_method, p_args, p_argcount, r_error); } -bool GDScript::_get(const StringName& p_name,Variant &r_ret) const { +bool GDScript::_get(const StringName &p_name, Variant &r_ret) const { { - - const GDScript *top=this; - while(top) { + const GDScript *top = this; + while (top) { { - const Map<StringName,Variant>::Element *E=top->constants.find(p_name); + const Map<StringName, Variant>::Element *E = top->constants.find(p_name); if (E) { - r_ret= E->get(); + r_ret = E->get(); return true; } } { - const Map<StringName,Ref<GDScript> >::Element *E=subclasses.find(p_name); + const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name); if (E) { - r_ret=E->get(); + r_ret = E->get(); return true; } } - top=top->_base; + top = top->_base; } - if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) { + if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) { - r_ret=get_source_code(); + r_ret = get_source_code(); return true; } } - - return false; - } -bool GDScript::_set(const StringName& p_name, const Variant& p_value) { +bool GDScript::_set(const StringName &p_name, const Variant &p_value) { - if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) { + if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) { set_source_code(p_value); reload(); @@ -657,159 +622,147 @@ bool GDScript::_set(const StringName& p_name, const Variant& p_value) { void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const { - p_properties->push_back( PropertyInfo(Variant::STRING,"script/source",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); + p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } - void GDScript::_bind_methods() { - ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"new",&GDScript::_new,MethodInfo("new")); - - ObjectTypeDB::bind_method(_MD("get_as_byte_code"),&GDScript::get_as_byte_code); + ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new")); + ObjectTypeDB::bind_method(_MD("get_as_byte_code"), &GDScript::get_as_byte_code); } - Vector<uint8_t> GDScript::get_as_byte_code() const { GDTokenizerBuffer tokenizer; return tokenizer.parse_code_string(source); }; - -Error GDScript::load_byte_code(const String& p_path) { +Error GDScript::load_byte_code(const String &p_path) { Vector<uint8_t> bytecode; if (p_path.ends_with("gde")) { - FileAccess *fa = FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!fa,ERR_CANT_OPEN); - FileAccessEncrypted *fae = memnew( FileAccessEncrypted ); - ERR_FAIL_COND_V(!fae,ERR_CANT_OPEN); + FileAccess *fa = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN); + FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN); Vector<uint8_t> key; key.resize(32); - for(int i=0;i<key.size();i++) { - key[i]=script_encryption_key[i]; + for (int i = 0; i < key.size(); i++) { + key[i] = script_encryption_key[i]; } - Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_READ); - ERR_FAIL_COND_V(err,err); + Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ); + ERR_FAIL_COND_V(err, err); bytecode.resize(fae->get_len()); - fae->get_buffer(bytecode.ptr(),bytecode.size()); + fae->get_buffer(bytecode.ptr(), bytecode.size()); memdelete(fae); } else { bytecode = FileAccess::get_file_as_array(p_path); } - ERR_FAIL_COND_V(bytecode.size()==0,ERR_PARSE_ERROR); - path=p_path; + ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR); + path = p_path; - String basedir=path; + String basedir = path; - if (basedir=="") - basedir=get_path(); + if (basedir == "") + basedir = get_path(); - if (basedir!="") - basedir=basedir.get_base_dir(); + if (basedir != "") + basedir = basedir.get_base_dir(); - valid=false; + valid = false; GDParser parser; - Error err = parser.parse_bytecode(bytecode,basedir,get_path()); + Error err = parser.parse_bytecode(bytecode, basedir, get_path()); if (err) { - _err_print_error("GDScript::load_byte_code",path.empty()?"built-in":(const char*)path.utf8().get_data(),parser.get_error_line(),("Parse Error: "+parser.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_PARSE_ERROR); } GDCompiler compiler; - err = compiler.compile(&parser,this); + err = compiler.compile(&parser, this); if (err) { - _err_print_error("GDScript::load_byte_code",path.empty()?"built-in":(const char*)path.utf8().get_data(),compiler.get_error_line(),("Compile Error: "+compiler.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_COMPILATION_FAILED); } - valid=true; + valid = true; - for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) { + for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) { - _set_subclass_path(E->get(),path); + _set_subclass_path(E->get(), path); } return OK; } - -Error GDScript::load_source_code(const String& p_path) { - +Error GDScript::load_source_code(const String &p_path) { DVector<uint8_t> sourcef; Error err; - FileAccess *f=FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); } int len = f->get_len(); - sourcef.resize(len+1); + sourcef.resize(len + 1); DVector<uint8_t>::Write w = sourcef.write(); - int r = f->get_buffer(w.ptr(),len); + int r = f->get_buffer(w.ptr(), len); f->close(); memdelete(f); - ERR_FAIL_COND_V(r!=len,ERR_CANT_OPEN); - w[len]=0; + ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); + w[len] = 0; String s; - if (s.parse_utf8((const char*)w.ptr())) { + if (s.parse_utf8((const char *)w.ptr())) { - ERR_EXPLAIN("Script '"+p_path+"' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); + ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); ERR_FAIL_V(ERR_INVALID_DATA); } - source=s; + source = s; #ifdef TOOLS_ENABLED - source_changed_cache=true; + source_changed_cache = true; #endif //print_line("LSC :"+get_path()); - path=p_path; + path = p_path; return OK; - } - -const Map<StringName,GDFunction*>& GDScript::debug_get_member_functions() const { +const Map<StringName, GDFunction *> &GDScript::debug_get_member_functions() const { return member_functions; } - - StringName GDScript::debug_get_member_by_index(int p_idx) const { + for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) { - for(const Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) { - - if (E->get().index==p_idx) + if (E->get().index == p_idx) return E->key(); } return "<error>"; } - Ref<GDScript> GDScript::get_base() const { return base; } -bool GDScript::has_script_signal(const StringName& p_signal) const { +bool GDScript::has_script_signal(const StringName &p_signal) const { if (_signals.has(p_signal)) return true; if (base.is_valid()) { return base->has_script_signal(p_signal); } #ifdef TOOLS_ENABLED - else if (base_cache.is_valid()){ + else if (base_cache.is_valid()) { return base_cache->has_script_signal(p_signal); } @@ -818,13 +771,13 @@ bool GDScript::has_script_signal(const StringName& p_signal) const { } void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const { - for(const Map<StringName,Vector<StringName> >::Element *E=_signals.front();E;E=E->next()) { + for (const Map<StringName, Vector<StringName> >::Element *E = _signals.front(); E; E = E->next()) { MethodInfo mi; - mi.name=E->key(); - for(int i=0;i<E->get().size();i++) { + mi.name = E->key(); + for (int i = 0; i < E->get().size(); i++) { PropertyInfo arg; - arg.name=E->get()[i]; + arg.name = E->get()[i]; mi.arguments.push_back(arg); } r_signals->push_back(mi); @@ -834,27 +787,25 @@ void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const { base->get_script_signal_list(r_signals); } #ifdef TOOLS_ENABLED - else if (base_cache.is_valid()){ + else if (base_cache.is_valid()) { base_cache->get_script_signal_list(r_signals); } #endif - } +GDScript::GDScript() + : script_list(this) { -GDScript::GDScript() : script_list(this) { - - - _static_ref=this; - valid=false; - subclass_count=0; - initializer=NULL; - _base=NULL; - _owner=NULL; - tool=false; + _static_ref = this; + valid = false; + subclass_count = 0; + initializer = NULL; + _base = NULL; + _owner = NULL; + tool = false; #ifdef TOOLS_ENABLED - source_changed_cache=false; + source_changed_cache = false; #endif #ifdef DEBUG_ENABLED @@ -870,12 +821,12 @@ GDScript::GDScript() : script_list(this) { } GDScript::~GDScript() { - for (Map<StringName,GDFunction*>::Element *E=member_functions.front();E;E=E->next()) { - memdelete( E->get() ); + for (Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) { + memdelete(E->get()); } - for (Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) { - E->get()->_owner=NULL; //bye, you are no longer owned cause I died + for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) { + E->get()->_owner = NULL; //bye, you are no longer owned cause I died } #ifdef DEBUG_ENABLED @@ -890,48 +841,41 @@ GDScript::~GDScript() { #endif } - - - - ////////////////////////////// // INSTANCE // ////////////////////////////// - -bool GDInstance::set(const StringName& p_name, const Variant& p_value) { +bool GDInstance::set(const StringName &p_name, const Variant &p_value) { //member { - const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); + const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); if (E) { if (E->get().setter) { - const Variant *val=&p_value; + const Variant *val = &p_value; Variant::CallError err; - call(E->get().setter,&val,1,err); - if (err.error==Variant::CallError::CALL_OK) { + call(E->get().setter, &val, 1, err); + if (err.error == Variant::CallError::CALL_OK) { return true; //function exists, call was successful } - } - else + } else members[E->get().index] = p_value; return true; } } - GDScript *sptr=script.ptr(); - while(sptr) { + GDScript *sptr = script.ptr(); + while (sptr) { - - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set); + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set); if (E) { - Variant name=p_name; - const Variant *args[2]={&name,&p_value}; + Variant name = p_name; + const Variant *args[2] = { &name, &p_value }; Variant::CallError err; - Variant ret = E->get()->call(this,(const Variant**)args,2,err); - if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool()) + Variant ret = E->get()->call(this, (const Variant **)args, 2, err); + if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) return true; } sptr = sptr->_base; @@ -940,54 +884,50 @@ bool GDInstance::set(const StringName& p_name, const Variant& p_value) { return false; } -bool GDInstance::get(const StringName& p_name, Variant &r_ret) const { - +bool GDInstance::get(const StringName &p_name, Variant &r_ret) const { - - const GDScript *sptr=script.ptr(); - while(sptr) { + const GDScript *sptr = script.ptr(); + while (sptr) { { - const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); + const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); if (E) { if (E->get().getter) { Variant::CallError err; - r_ret=const_cast<GDInstance*>(this)->call(E->get().getter,NULL,0,err); - if (err.error==Variant::CallError::CALL_OK) { + r_ret = const_cast<GDInstance *>(this)->call(E->get().getter, NULL, 0, err); + if (err.error == Variant::CallError::CALL_OK) { return true; } } - r_ret=members[E->get().index]; + r_ret = members[E->get().index]; return true; //index found - } } { const GDScript *sl = sptr; - while(sl) { - const Map<StringName,Variant>::Element *E = sl->constants.find(p_name); + while (sl) { + const Map<StringName, Variant>::Element *E = sl->constants.find(p_name); if (E) { - r_ret=E->get(); + r_ret = E->get(); return true; //index found - } - sl=sl->_base; + sl = sl->_base; } } { - const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get); + const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get); if (E) { - Variant name=p_name; - const Variant *args[1]={&name}; + Variant name = p_name; + const Variant *args[1] = { &name }; Variant::CallError err; - Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err); - if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) { - r_ret=ret; + Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), (const Variant **)args, 1, err); + if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) { + r_ret = ret; return true; } } @@ -996,94 +936,86 @@ bool GDInstance::get(const StringName& p_name, Variant &r_ret) const { } return false; - } -Variant::Type GDInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const { +Variant::Type GDInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { - - const GDScript *sptr=script.ptr(); - while(sptr) { + const GDScript *sptr = script.ptr(); + while (sptr) { if (sptr->member_info.has(p_name)) { if (r_is_valid) - *r_is_valid=true; + *r_is_valid = true; return sptr->member_info[p_name].type; } sptr = sptr->_base; } if (r_is_valid) - *r_is_valid=false; + *r_is_valid = false; return Variant::NIL; } void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const { // exported members, not doen yet! - const GDScript *sptr=script.ptr(); + const GDScript *sptr = script.ptr(); List<PropertyInfo> props; - while(sptr) { - + while (sptr) { - const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list); + const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list); if (E) { - Variant::CallError err; - Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),NULL,0,err); - if (err.error==Variant::CallError::CALL_OK) { + Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), NULL, 0, err); + if (err.error == Variant::CallError::CALL_OK) { - if (ret.get_type()!=Variant::ARRAY) { + if (ret.get_type() != Variant::ARRAY) { ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries."); ERR_FAIL(); } Array arr = ret; - for(int i=0;i<arr.size();i++) { + for (int i = 0; i < arr.size(); i++) { Dictionary d = arr[i]; ERR_CONTINUE(!d.has("name")); ERR_CONTINUE(!d.has("type")); PropertyInfo pinfo; - pinfo.type = Variant::Type( d["type"].operator int()); - ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX ); + pinfo.type = Variant::Type(d["type"].operator int()); + ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX); pinfo.name = d["name"]; - ERR_CONTINUE(pinfo.name==""); + ERR_CONTINUE(pinfo.name == ""); if (d.has("hint")) - pinfo.hint=PropertyHint(d["hint"].operator int()); + pinfo.hint = PropertyHint(d["hint"].operator int()); if (d.has("hint_string")) - pinfo.hint_string=d["hint_string"]; + pinfo.hint_string = d["hint_string"]; if (d.has("usage")) - pinfo.usage=d["usage"]; + pinfo.usage = d["usage"]; props.push_back(pinfo); - } - } } //instance a fake script for editing the values Vector<_GDScriptMemberSort> msort; - for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) { + for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) { _GDScriptMemberSort ms; ERR_CONTINUE(!sptr->member_indices.has(E->key())); - ms.index=sptr->member_indices[E->key()].index; - ms.name=E->key(); + ms.index = sptr->member_indices[E->key()].index; + ms.name = E->key(); msort.push_back(ms); - } msort.sort(); msort.invert(); - for(int i=0;i<msort.size();i++) { + for (int i = 0; i < msort.size(); i++) { props.push_front(sptr->member_info[msort[i].name]); - } #if 0 if (sptr->member_functions.has("_get_property_list")) { @@ -1132,7 +1064,7 @@ void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const { //props.invert(); - for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { p_properties->push_back(E->get()); } @@ -1140,28 +1072,27 @@ void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const { void GDInstance::get_method_list(List<MethodInfo> *p_list) const { - const GDScript *sptr=script.ptr(); - while(sptr) { + const GDScript *sptr = script.ptr(); + while (sptr) { - for (Map<StringName,GDFunction*>::Element *E = sptr->member_functions.front();E;E=E->next()) { + for (Map<StringName, GDFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) { MethodInfo mi; - mi.name=E->key(); - mi.flags|=METHOD_FLAG_FROM_SCRIPT; - for(int i=0;i<E->get()->get_argument_count();i++) - mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i))); + mi.name = E->key(); + mi.flags |= METHOD_FLAG_FROM_SCRIPT; + for (int i = 0; i < E->get()->get_argument_count(); i++) + mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i))); p_list->push_back(mi); } sptr = sptr->_base; } - } -bool GDInstance::has_method(const StringName& p_method) const { +bool GDInstance::has_method(const StringName &p_method) const { - const GDScript *sptr=script.ptr(); - while(sptr) { - const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + const GDScript *sptr = script.ptr(); + while (sptr) { + const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) return true; sptr = sptr->_base; @@ -1169,79 +1100,74 @@ bool GDInstance::has_method(const StringName& p_method) const { return false; } -Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { +Variant GDInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str()); - GDScript *sptr=script.ptr(); - while(sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + GDScript *sptr = script.ptr(); + while (sptr) { + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) { - return E->get()->call(this,p_args,p_argcount,r_error); + return E->get()->call(this, p_args, p_argcount, r_error); } sptr = sptr->_base; } - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } -void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) { +void GDInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) { - GDScript *sptr=script.ptr(); + GDScript *sptr = script.ptr(); Variant::CallError ce; - while(sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + while (sptr) { + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) { - E->get()->call(this,p_args,p_argcount,ce); + E->get()->call(this, p_args, p_argcount, ce); } sptr = sptr->_base; } - } - -void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) { +void GDInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) { if (sptr->_base) - _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount); + _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount); Variant::CallError ce; - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) { - E->get()->call(this,p_args,p_argcount,ce); + E->get()->call(this, p_args, p_argcount, ce); } - } -void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) { +void GDInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) { if (script.ptr()) { - _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount); + _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount); } } void GDInstance::notification(int p_notification) { //notification is not virutal, it gets called at ALL levels just like in C. - Variant value=p_notification; - const Variant *args[1]={&value }; + Variant value = p_notification; + const Variant *args[1] = { &value }; - GDScript *sptr=script.ptr(); - while(sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification); + GDScript *sptr = script.ptr(); + while (sptr) { + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification); if (E) { Variant::CallError err; - E->get()->call(this,args,1,err); - if (err.error!=Variant::CallError::CALL_OK) { + E->get()->call(this, args, 1, err); + if (err.error != Variant::CallError::CALL_OK) { //print error about notification call - } } sptr = sptr->_base; } - } Ref<Script> GDInstance::get_script() const { @@ -1264,31 +1190,30 @@ void GDInstance::reload_members() { new_members.resize(script->member_indices.size()); //pass the values to the new indices - for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) { + for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) { if (member_indices_cache.has(E->key())) { Variant value = members[member_indices_cache[E->key()]]; - new_members[E->get().index]=value; + new_members[E->get().index] = value; } - } //apply - members=new_members; + members = new_members; //pass the values to the new indices member_indices_cache.clear(); - for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) { + for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) { - member_indices_cache[E->key()]=E->get().index; + member_indices_cache[E->key()] = E->get().index; } #endif } GDInstance::GDInstance() { - owner=NULL; - base_ref=false; + owner = NULL; + base_ref = false; } GDInstance::~GDInstance() { @@ -1303,8 +1228,7 @@ GDInstance::~GDInstance() { /************* SCRIPT LANGUAGE **************/ /************* SCRIPT LANGUAGE **************/ -GDScriptLanguage *GDScriptLanguage::singleton=NULL; - +GDScriptLanguage *GDScriptLanguage::singleton = NULL; String GDScriptLanguage::get_name() const { @@ -1313,61 +1237,58 @@ String GDScriptLanguage::get_name() const { /* LANGUAGE FUNCTIONS */ -void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) { - +void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) { if (globals.has(p_name)) { //overwrite existing - global_array[globals[p_name]]=p_value; + global_array[globals[p_name]] = p_value; return; } - globals[p_name]=global_array.size(); + globals[p_name] = global_array.size(); global_array.push_back(p_value); - _global_array=global_array.ptr(); + _global_array = global_array.ptr(); } -void GDScriptLanguage::add_global_constant(const StringName& p_variable,const Variant& p_value) { +void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) { - _add_global(p_variable,p_value); + _add_global(p_variable, p_value); } - void GDScriptLanguage::init() { - //populate global constants - int gcc=GlobalConstants::get_global_constant_count(); - for(int i=0;i<gcc;i++) { + int gcc = GlobalConstants::get_global_constant_count(); + for (int i = 0; i < gcc; i++) { - _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)),GlobalConstants::get_global_constant_value(i)); + _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i)); } - _add_global(StaticCString::create("PI"),Math_PI); + _add_global(StaticCString::create("PI"), Math_PI); //populate native classes List<StringName> class_list; ObjectTypeDB::get_type_list(&class_list); - for(List<StringName>::Element *E=class_list.front();E;E=E->next()) { + for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) { StringName n = E->get(); String s = String(n); if (s.begins_with("_")) - n=s.substr(1,s.length()); + n = s.substr(1, s.length()); if (globals.has(n)) continue; - Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) ); - _add_global(n,nc); + Ref<GDNativeClass> nc = memnew(GDNativeClass(E->get())); + _add_global(n, nc); } //populate singletons List<Globals::Singleton> singletons; Globals::get_singleton()->get_singletons(&singletons); - for(List<Globals::Singleton>::Element *E=singletons.front();E;E=E->next()) { + for (List<Globals::Singleton>::Element *E = singletons.front(); E; E = E->next()) { - _add_global(E->get().name,E->get().ptr); + _add_global(E->get().name, E->get().ptr); } } @@ -1379,14 +1300,12 @@ String GDScriptLanguage::get_extension() const { return "gd"; } -Error GDScriptLanguage::execute_file(const String& p_path) { +Error GDScriptLanguage::execute_file(const String &p_path) { // ?? return OK; } -void GDScriptLanguage::finish() { - - +void GDScriptLanguage::finish() { } void GDScriptLanguage::profiling_start() { @@ -1396,27 +1315,26 @@ void GDScriptLanguage::profiling_start() { lock->lock(); } - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - elem->self()->profile.call_count=0; - elem->self()->profile.self_time=0; - elem->self()->profile.total_time=0; - elem->self()->profile.frame_call_count=0; - elem->self()->profile.frame_self_time=0; - elem->self()->profile.frame_total_time=0; - elem->self()->profile.last_frame_call_count=0; - elem->self()->profile.last_frame_self_time=0; - elem->self()->profile.last_frame_total_time=0; - elem=elem->next(); + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + elem->self()->profile.call_count = 0; + elem->self()->profile.self_time = 0; + elem->self()->profile.total_time = 0; + elem->self()->profile.frame_call_count = 0; + elem->self()->profile.frame_self_time = 0; + elem->self()->profile.frame_total_time = 0; + elem->self()->profile.last_frame_call_count = 0; + elem->self()->profile.last_frame_self_time = 0; + elem->self()->profile.last_frame_total_time = 0; + elem = elem->next(); } - profiling=true; + profiling = true; if (lock) { lock->unlock(); } #endif - } void GDScriptLanguage::profiling_stop() { @@ -1426,7 +1344,7 @@ void GDScriptLanguage::profiling_stop() { lock->lock(); } - profiling=false; + profiling = false; if (lock) { lock->unlock(); } @@ -1434,95 +1352,83 @@ void GDScriptLanguage::profiling_stop() { #endif } -int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max) { +int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) { - int current=0; + int current = 0; #ifdef DEBUG_ENABLED if (lock) { lock->lock(); } - - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - if (current>=p_info_max) + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + if (current >= p_info_max) break; - p_info_arr[current].call_count=elem->self()->profile.call_count; - p_info_arr[current].self_time=elem->self()->profile.self_time; - p_info_arr[current].total_time=elem->self()->profile.total_time; - p_info_arr[current].signature=elem->self()->profile.signature; - elem=elem->next(); + p_info_arr[current].call_count = elem->self()->profile.call_count; + p_info_arr[current].self_time = elem->self()->profile.self_time; + p_info_arr[current].total_time = elem->self()->profile.total_time; + p_info_arr[current].signature = elem->self()->profile.signature; + elem = elem->next(); current++; } - - if (lock) { lock->unlock(); } - #endif return current; - - } -int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max) { +int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) { - int current=0; + int current = 0; #ifdef DEBUG_ENABLED if (lock) { lock->lock(); } - - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - if (current>=p_info_max) + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + if (current >= p_info_max) break; - if (elem->self()->profile.last_frame_call_count>0) { - p_info_arr[current].call_count=elem->self()->profile.last_frame_call_count; - p_info_arr[current].self_time=elem->self()->profile.last_frame_self_time; - p_info_arr[current].total_time=elem->self()->profile.last_frame_total_time; - p_info_arr[current].signature=elem->self()->profile.signature; + if (elem->self()->profile.last_frame_call_count > 0) { + p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count; + p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time; + p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time; + p_info_arr[current].signature = elem->self()->profile.signature; //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count)); current++; } - elem=elem->next(); - + elem = elem->next(); } - if (lock) { lock->unlock(); } - #endif return current; - } - struct GDScriptDepSort { //must support sorting so inheritance works properly (parent must be reloaded first) - bool operator()(const Ref<GDScript> &A, const Ref<GDScript>& B) const { + bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const { - if (A==B) + if (A == B) return false; //shouldn't happen but.. - const GDScript *I=B->get_base().ptr(); - while(I) { - if (I==A.ptr()) { + const GDScript *I = B->get_base().ptr(); + while (I) { + if (I == A.ptr()) { // A is a base of B return true; } - I=I->get_base().ptr(); + I = I->get_base().ptr(); } return false; //not a base @@ -1531,8 +1437,6 @@ struct GDScriptDepSort { void GDScriptLanguage::reload_all_scripts() { - - #ifdef DEBUG_ENABLED print_line("RELOAD ALL SCRIPTS"); if (lock) { @@ -1541,13 +1445,13 @@ void GDScriptLanguage::reload_all_scripts() { List<Ref<GDScript> > scripts; - SelfList<GDScript> *elem=script_list.first(); - while(elem) { + SelfList<GDScript> *elem = script_list.first(); + while (elem) { if (elem->self()->get_path().is_resource_file()) { - print_line("FOUND: "+elem->self()->get_path()); + print_line("FOUND: " + elem->self()->get_path()); scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident } - elem=elem->next(); + elem = elem->next(); } if (lock) { @@ -1558,18 +1462,16 @@ void GDScriptLanguage::reload_all_scripts() { scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) { + for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) { - print_line("RELOADING: "+E->get()->get_path()); + print_line("RELOADING: " + E->get()->get_path()); E->get()->load_source_code(E->get()->get_path()); E->get()->reload(true); } #endif } - -void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload) { - +void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) { #ifdef DEBUG_ENABLED @@ -1579,13 +1481,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof List<Ref<GDScript> > scripts; - SelfList<GDScript> *elem=script_list.first(); - while(elem) { + SelfList<GDScript> *elem = script_list.first(); + while (elem) { if (elem->self()->get_path().is_resource_file()) { scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident } - elem=elem->next(); + elem = elem->next(); } if (lock) { @@ -1594,68 +1496,68 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof //when someone asks you why dynamically typed languages are easier to write.... - Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > > to_reload; + Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload; //as scripts are going to be reloaded, must proceed without locking here scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) { + for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) { - bool reload = E->get()==p_script || to_reload.has(E->get()->get_base()); + bool reload = E->get() == p_script || to_reload.has(E->get()->get_base()); if (!reload) continue; - to_reload.insert(E->get(),Map<ObjectID,List<Pair<StringName,Variant> > >()); + to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >()); if (!p_soft_reload) { //save state and remove script from instances - Map<ObjectID,List<Pair<StringName,Variant> > >& map = to_reload[E->get()]; + Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()]; - while(E->get()->instances.front()) { + while (E->get()->instances.front()) { Object *obj = E->get()->instances.front()->get(); //save instance info - List<Pair<StringName,Variant> > state; + List<Pair<StringName, Variant> > state; if (obj->get_script_instance()) { obj->get_script_instance()->get_property_state(state); - map[obj->get_instance_ID()]=state; + map[obj->get_instance_ID()] = state; obj->set_script(RefPtr()); } } - //same thing for placeholders +//same thing for placeholders #ifdef TOOLS_ENABLED - while(E->get()->placeholders.size()) { + while (E->get()->placeholders.size()) { Object *obj = E->get()->placeholders.front()->get()->get_owner(); //save instance info - List<Pair<StringName,Variant> > state; + List<Pair<StringName, Variant> > state; if (obj->get_script_instance()) { obj->get_script_instance()->get_property_state(state); - map[obj->get_instance_ID()]=state; + map[obj->get_instance_ID()] = state; obj->set_script(RefPtr()); } } #endif - for(Map<ObjectID,List<Pair<StringName,Variant> > >::Element *F=E->get()->pending_reload_state.front();F;F=F->next()) { - map[F->key()]=F->get(); //pending to reload, use this one instead + for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) { + map[F->key()] = F->get(); //pending to reload, use this one instead } } } - for(Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > >::Element *E=to_reload.front();E;E=E->next()) { + for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) { Ref<GDScript> scr = E->key(); scr->reload(p_soft_reload); //restore state if saved - for (Map<ObjectID,List<Pair<StringName,Variant> > >::Element *F=E->get().front();F;F=F->next()) { + for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) { Object *obj = ObjectDB::get_instance(F->key()); if (!obj) @@ -1669,13 +1571,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof if (!obj->get_script_instance()) { //failed, save reload state for next time if not saved if (!scr->pending_reload_state.has(obj->get_instance_ID())) { - scr->pending_reload_state[obj->get_instance_ID()]=F->get(); + scr->pending_reload_state[obj->get_instance_ID()] = F->get(); } continue; } - for (List<Pair<StringName,Variant> >::Element *G=F->get().front();G;G=G->next()) { - obj->get_script_instance()->set(G->get().first,G->get().second); + for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) { + obj->get_script_instance()->set(G->get().first, G->get().second); } scr->pending_reload_state.erase(obj->get_instance_ID()); //as it reloaded, remove pending state @@ -1684,14 +1586,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof //if instance states were saved, set them! } - #endif } void GDScriptLanguage::frame() { // print_line("calls: "+itos(calls)); - calls=0; + calls = 0; #ifdef DEBUG_ENABLED if (profiling) { @@ -1699,18 +1600,17 @@ void GDScriptLanguage::frame() { lock->lock(); } - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - elem->self()->profile.last_frame_call_count=elem->self()->profile.frame_call_count; - elem->self()->profile.last_frame_self_time=elem->self()->profile.frame_self_time; - elem->self()->profile.last_frame_total_time=elem->self()->profile.frame_total_time; - elem->self()->profile.frame_call_count=0; - elem->self()->profile.frame_self_time=0; - elem->self()->profile.frame_total_time=0; - elem=elem->next(); + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count; + elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time; + elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time; + elem->self()->profile.frame_call_count = 0; + elem->self()->profile.frame_self_time = 0; + elem->self()->profile.frame_total_time = 0; + elem = elem->next(); } - if (lock) { lock->unlock(); } @@ -1720,9 +1620,9 @@ void GDScriptLanguage::frame() { } /* EDITOR FUNCTIONS */ -void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { +void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { - static const char *_reserved_words[]={ + static const char *_reserved_words[] = { // operators "and", "in", @@ -1765,11 +1665,10 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { "pass", "return", "while", - 0}; - - - const char **w=_reserved_words; + 0 + }; + const char **w = _reserved_words; while (*w) { @@ -1777,73 +1676,69 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { w++; } - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i))); } - } GDScriptLanguage::GDScriptLanguage() { - calls=0; + calls = 0; ERR_FAIL_COND(singleton); - singleton=this; + singleton = this; strings._init = StaticCString::create("_init"); strings._notification = StaticCString::create("_notification"); - strings._set= StaticCString::create("_set"); - strings._get= StaticCString::create("_get"); - strings._get_property_list= StaticCString::create("_get_property_list"); - strings._script_source=StaticCString::create("script/source"); - _debug_parse_err_line=-1; - _debug_parse_err_file=""; + strings._set = StaticCString::create("_set"); + strings._get = StaticCString::create("_get"); + strings._get_property_list = StaticCString::create("_get_property_list"); + strings._script_source = StaticCString::create("script/source"); + _debug_parse_err_line = -1; + _debug_parse_err_file = ""; #ifdef NO_THREADS - lock=NULL; + lock = NULL; #else lock = Mutex::create(); #endif - profiling=false; - script_frame_time=0; + profiling = false; + script_frame_time = 0; - _debug_call_stack_pos=0; - int dmcs=GLOBAL_DEF("debug/script_max_call_stack",1024); + _debug_call_stack_pos = 0; + int dmcs = GLOBAL_DEF("debug/script_max_call_stack", 1024); if (ScriptDebugger::get_singleton()) { //debugging enabled! _debug_max_call_stack = dmcs; - if (_debug_max_call_stack<1024) - _debug_max_call_stack=1024; - _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 ); + if (_debug_max_call_stack < 1024) + _debug_max_call_stack = 1024; + _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1); } else { - _debug_max_call_stack=0; - _call_stack=NULL; + _debug_max_call_stack = 0; + _call_stack = NULL; } - } - GDScriptLanguage::~GDScriptLanguage() { - if (lock) { memdelete(lock); - lock=NULL; + lock = NULL; } - if (_call_stack) { + if (_call_stack) { memdelete_arr(_call_stack); } - singleton=NULL; + singleton = NULL; } /*************** RESOURCE ***************/ -RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; - GDScript *script = memnew( GDScript ); + GDScript *script = memnew(GDScript); Ref<GDScript> scriptres(script); @@ -1853,18 +1748,17 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_ori script->set_path(p_original_path); Error err = script->load_byte_code(p_path); + if (err != OK) { - if (err!=OK) { - - ERR_FAIL_COND_V(err!=OK, RES()); + ERR_FAIL_COND_V(err != OK, RES()); } } else { Error err = script->load_source_code(p_path); - if (err!=OK) { + if (err != OK) { - ERR_FAIL_COND_V(err!=OK, RES()); + ERR_FAIL_COND_V(err != OK, RES()); } script->set_script_path(p_original_path); // script needs this. @@ -1874,7 +1768,7 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_ori script->reload(); } if (r_error) - *r_error=OK; + *r_error = OK; return scriptres; } @@ -1885,38 +1779,36 @@ void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_ext p_extensions->push_back("gde"); } -bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const { +bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const { - return (p_type=="Script" || p_type=="GDScript"); + return (p_type == "Script" || p_type == "GDScript"); } String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const { String el = p_path.extension().to_lower(); - if (el=="gd" || el=="gdc" || el=="gde") + if (el == "gd" || el == "gdc" || el == "gde") return "GDScript"; return ""; } - -Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Ref<GDScript> sqscr = p_resource; - ERR_FAIL_COND_V(sqscr.is_null(),ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER); String source = sqscr->get_source_code(); Error err; - FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err); - + FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); } file->store_string(source); - if (file->get_error()!=OK && file->get_error()!=ERR_FILE_EOF) { + if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { memdelete(file); return ERR_CANT_CREATE; } @@ -1924,20 +1816,19 @@ Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resour memdelete(file); if (ScriptServer::is_reload_scripts_on_save_enabled()) { - GDScriptLanguage::get_singleton()->reload_tool_script(p_resource,false); + GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false); } return OK; } -void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { +void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { if (p_resource->cast_to<GDScript>()) { p_extensions->push_back("gd"); } - } -bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const { +bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const { - return p_resource->cast_to<GDScript>()!=NULL; + return p_resource->cast_to<GDScript>() != NULL; } diff --git a/modules/gdscript/gd_script.h b/modules/gdscript/gd_script.h index b6aaa0670..7dd876ed8 100644 --- a/modules/gdscript/gd_script.h +++ b/modules/gdscript/gd_script.h @@ -29,48 +29,44 @@ #ifndef GD_SCRIPT_H #define GD_SCRIPT_H -#include "script_language.h" +#include "gd_function.h" #include "io/resource_loader.h" #include "io/resource_saver.h" -#include "gd_function.h" +#include "script_language.h" class GDNativeClass : public Reference { - OBJ_TYPE(GDNativeClass,Reference); + OBJ_TYPE(GDNativeClass, Reference); StringName name; -protected: - bool _get(const StringName& p_name,Variant &r_ret) const; +protected: + bool _get(const StringName &p_name, Variant &r_ret) const; static void _bind_methods(); public: - - _FORCE_INLINE_ const StringName& get_name() const { return name; } + _FORCE_INLINE_ const StringName &get_name() const { return name; } Variant _new(); Object *instance(); - GDNativeClass(const StringName& p_name); + GDNativeClass(const StringName &p_name); }; - class GDScript : public Script { - - OBJ_TYPE(GDScript,Script); + OBJ_TYPE(GDScript, Script); bool tool; bool valid; - struct MemberInfo { int index; StringName setter; StringName getter; }; -friend class GDInstance; -friend class GDFunction; -friend class GDCompiler; -friend class GDFunctions; -friend class GDScriptLanguage; + friend class GDInstance; + friend class GDFunction; + friend class GDCompiler; + friend class GDFunctions; + friend class GDScriptLanguage; Variant _static_ref; //used for static call Ref<GDNativeClass> native; @@ -79,107 +75,105 @@ friend class GDScriptLanguage; GDScript *_owner; //for subclasses Set<StringName> members; //members are just indices to the instanced script. - Map<StringName,Variant> constants; - Map<StringName,GDFunction*> member_functions; - Map<StringName,MemberInfo> member_indices; //members are just indices to the instanced script. - Map<StringName,Ref<GDScript> > subclasses; - Map<StringName,Vector<StringName> > _signals; + Map<StringName, Variant> constants; + Map<StringName, GDFunction *> member_functions; + Map<StringName, MemberInfo> member_indices; //members are just indices to the instanced script. + Map<StringName, Ref<GDScript> > subclasses; + Map<StringName, Vector<StringName> > _signals; #ifdef TOOLS_ENABLED - Map<StringName,Variant> member_default_values; + Map<StringName, Variant> member_default_values; List<PropertyInfo> members_cache; - Map<StringName,Variant> member_default_values_cache; + Map<StringName, Variant> member_default_values_cache; Ref<GDScript> base_cache; Set<ObjectID> inheriters_cache; bool source_changed_cache; - void _update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames); + void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames); #endif - Map<StringName,PropertyInfo> member_info; + Map<StringName, PropertyInfo> member_info; GDFunction *initializer; //direct pointer to _init , faster to locate int subclass_count; - Set<Object*> instances; + Set<Object *> instances; //exported members String source; String path; String name; SelfList<GDScript> script_list; + GDInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error); - GDInstance* _create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError &r_error); - - void _set_subclass_path(Ref<GDScript>& p_sc,const String& p_path); + void _set_subclass_path(Ref<GDScript> &p_sc, const String &p_path); #ifdef TOOLS_ENABLED - Set<PlaceHolderScriptInstance*> placeholders; + Set<PlaceHolderScriptInstance *> placeholders; //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder); #endif #ifdef DEBUG_ENABLED - Map<ObjectID,List<Pair<StringName,Variant> > > pending_reload_state; + Map<ObjectID, List<Pair<StringName, Variant> > > pending_reload_state; #endif bool _update_exports(); protected: - 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; + bool _set(const StringName &p_name, const Variant &p_value); void _get_property_list(List<PropertyInfo> *p_properties) const; - Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error); -// void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); + Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); + // void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); static void _bind_methods(); -public: +public: bool is_valid() const { return valid; } - const Map<StringName,Ref<GDScript> >& get_subclasses() const { return subclasses; } - const Map<StringName,Variant >& get_constants() const { return constants; } - const Set<StringName>& get_members() const { return members; } - const Map<StringName,GDFunction*>& get_member_functions() const { return member_functions; } - const Ref<GDNativeClass>& get_native() const { return native; } + const Map<StringName, Ref<GDScript> > &get_subclasses() const { return subclasses; } + const Map<StringName, Variant> &get_constants() const { return constants; } + const Set<StringName> &get_members() const { return members; } + const Map<StringName, GDFunction *> &get_member_functions() const { return member_functions; } + const Ref<GDNativeClass> &get_native() const { return native; } - virtual bool has_script_signal(const StringName& p_signal) const; + virtual bool has_script_signal(const StringName &p_signal) const; virtual void get_script_signal_list(List<MethodInfo> *r_signals) const; - bool is_tool() const { return tool; } Ref<GDScript> get_base() const; - const Map<StringName,MemberInfo>& debug_get_member_indices() const { return member_indices; } - const Map<StringName,GDFunction*>& debug_get_member_functions() const; //this is debug only + const Map<StringName, MemberInfo> &debug_get_member_indices() const { return member_indices; } + const Map<StringName, GDFunction *> &debug_get_member_functions() const; //this is debug only StringName debug_get_member_by_index(int p_idx) const; - Variant _new(const Variant** p_args,int p_argcount,Variant::CallError& r_error); + Variant _new(const Variant **p_args, int p_argcount, Variant::CallError &r_error); virtual bool can_instance() const; virtual StringName get_instance_base_type() const; // this may not work in all scripts, will return empty if so - virtual ScriptInstance* instance_create(Object *p_this); + virtual ScriptInstance *instance_create(Object *p_this); virtual bool instance_has(const Object *p_this) const; virtual bool has_source_code() const; virtual String get_source_code() const; - virtual void set_source_code(const String& p_code); + virtual void set_source_code(const String &p_code); virtual void update_exports(); - virtual Error reload(bool p_keep_state=false); + virtual Error reload(bool p_keep_state = false); virtual String get_node_type() const; - void set_script_path(const String& p_path) { path=p_path; } //because subclasses need a path too... - Error load_source_code(const String& p_path); - Error load_byte_code(const String& p_path); + void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too... + Error load_source_code(const String &p_path); + Error load_byte_code(const String &p_path); Vector<uint8_t> get_as_byte_code() const; - bool get_property_default_value(const StringName& p_property,Variant& r_value) const; + bool get_property_default_value(const StringName &p_property, Variant &r_value) const; virtual ScriptLanguage *get_language() const; @@ -188,37 +182,34 @@ public: }; class GDInstance : public ScriptInstance { -friend class GDScript; -friend class GDFunction; -friend class GDFunctions; -friend class GDCompiler; + friend class GDScript; + friend class GDFunction; + friend class GDFunctions; + friend class GDCompiler; Object *owner; Ref<GDScript> script; #ifdef DEBUG_ENABLED - Map<StringName,int> member_indices_cache; //used only for hot script reloading + Map<StringName, int> member_indices_cache; //used only for hot script reloading #endif Vector<Variant> members; bool base_ref; - - void _ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount); + void _ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount); public: + _FORCE_INLINE_ Object *get_owner() { return owner; } - _FORCE_INLINE_ Object* get_owner() { return owner; } - - 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; - 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); + virtual bool has_method(const StringName &p_method) const; + 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 debug_get_member_by_index(int p_idx) const { return members[p_idx]; } @@ -228,116 +219,107 @@ public: virtual ScriptLanguage *get_language(); - void set_path(const String& p_path); + void set_path(const String &p_path); void reload_members(); GDInstance(); ~GDInstance(); - }; class GDScriptLanguage : public ScriptLanguage { static GDScriptLanguage *singleton; - Variant* _global_array; + Variant *_global_array; Vector<Variant> global_array; - Map<StringName,int> globals; - - - struct CallLevel { - - Variant *stack; - GDFunction *function; - GDInstance *instance; - int *ip; - int *line; + Map<StringName, int> globals; - }; + struct CallLevel { + Variant *stack; + GDFunction *function; + GDInstance *instance; + int *ip; + int *line; + }; - int _debug_parse_err_line; - String _debug_parse_err_file; - String _debug_error; - int _debug_call_stack_pos; - int _debug_max_call_stack; - CallLevel *_call_stack; - - void _add_global(const StringName& p_name,const Variant& p_value); + int _debug_parse_err_line; + String _debug_parse_err_file; + String _debug_error; + int _debug_call_stack_pos; + int _debug_max_call_stack; + CallLevel *_call_stack; + void _add_global(const StringName &p_name, const Variant &p_value); Mutex *lock; - - -friend class GDScript; + friend class GDScript; SelfList<GDScript>::List script_list; -friend class GDFunction; + friend class GDFunction; SelfList<GDFunction>::List function_list; bool profiling; uint64_t script_frame_time; -public: - +public: int calls; - bool debug_break(const String& p_error,bool p_allow_continue=true); - bool debug_break_parse(const String& p_file, int p_line,const String& p_error); + bool debug_break(const String &p_error, bool p_allow_continue = true); + bool debug_break_parse(const String &p_file, int p_line, const String &p_error); - _FORCE_INLINE_ void enter_function(GDInstance *p_instance,GDFunction *p_function, Variant *p_stack, int *p_ip, int *p_line) { + _FORCE_INLINE_ void enter_function(GDInstance *p_instance, GDFunction *p_function, Variant *p_stack, int *p_ip, int *p_line) { - if (Thread::get_main_ID()!=Thread::get_caller_ID()) - return; //no support for other threads than main for now + if (Thread::get_main_ID() != Thread::get_caller_ID()) + return; //no support for other threads than main for now - if (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0) - ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() +1 ); + if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0) + ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() + 1); - if (_debug_call_stack_pos >= _debug_max_call_stack) { - //stack overflow - _debug_error="Stack Overflow (Stack Size: "+itos(_debug_max_call_stack)+")"; - ScriptDebugger::get_singleton()->debug(this); - return; - } - - _call_stack[_debug_call_stack_pos].stack=p_stack; - _call_stack[_debug_call_stack_pos].instance=p_instance; - _call_stack[_debug_call_stack_pos].function=p_function; - _call_stack[_debug_call_stack_pos].ip=p_ip; - _call_stack[_debug_call_stack_pos].line=p_line; - _debug_call_stack_pos++; - } + if (_debug_call_stack_pos >= _debug_max_call_stack) { + //stack overflow + _debug_error = "Stack Overflow (Stack Size: " + itos(_debug_max_call_stack) + ")"; + ScriptDebugger::get_singleton()->debug(this); + return; + } - _FORCE_INLINE_ void exit_function() { + _call_stack[_debug_call_stack_pos].stack = p_stack; + _call_stack[_debug_call_stack_pos].instance = p_instance; + _call_stack[_debug_call_stack_pos].function = p_function; + _call_stack[_debug_call_stack_pos].ip = p_ip; + _call_stack[_debug_call_stack_pos].line = p_line; + _debug_call_stack_pos++; + } - if (Thread::get_main_ID()!=Thread::get_caller_ID()) - return; //no support for other threads than main for now + _FORCE_INLINE_ void exit_function() { - if (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0) - ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() -1 ); + if (Thread::get_main_ID() != Thread::get_caller_ID()) + return; //no support for other threads than main for now - if (_debug_call_stack_pos==0) { + if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0) + ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() - 1); - _debug_error="Stack Underflow (Engine Bug)"; - ScriptDebugger::get_singleton()->debug(this); - return; - } + if (_debug_call_stack_pos == 0) { - _debug_call_stack_pos--; - } + _debug_error = "Stack Underflow (Engine Bug)"; + ScriptDebugger::get_singleton()->debug(this); + return; + } + _debug_call_stack_pos--; + } virtual Vector<StackInfo> debug_get_current_stack_info() { - if (Thread::get_main_ID()!=Thread::get_caller_ID()) - return Vector<StackInfo>(); + if (Thread::get_main_ID() != Thread::get_caller_ID()) + return Vector<StackInfo>(); Vector<StackInfo> csi; csi.resize(_debug_call_stack_pos); - for(int i=0;i<_debug_call_stack_pos;i++) { - csi[_debug_call_stack_pos-i-1].line=_call_stack[i].line?*_call_stack[i].line:0; - csi[_debug_call_stack_pos-i-1].script=Ref<GDScript>(_call_stack[i].function->get_script()); + for (int i = 0; i < _debug_call_stack_pos; i++) { + csi[_debug_call_stack_pos - i - 1].line = _call_stack[i].line ? *_call_stack[i].line : 0; + csi[_debug_call_stack_pos - i - 1].script = Ref<GDScript>(_call_stack[i].function->get_script()); } return csi; } @@ -353,10 +335,9 @@ public: } strings; - _FORCE_INLINE_ int get_global_array_size() const { return global_array.size(); } - _FORCE_INLINE_ Variant* get_global_array() { return _global_array; } - _FORCE_INLINE_ const Map<StringName,int>& get_global_map() { return globals; } + _FORCE_INLINE_ Variant *get_global_array() { return _global_array; } + _FORCE_INLINE_ const Map<StringName, int> &get_global_map() { return globals; } _FORCE_INLINE_ static GDScriptLanguage *get_singleton() { return singleton; } @@ -366,23 +347,22 @@ public: virtual void init(); virtual String get_type() const; virtual String get_extension() const; - virtual Error execute_file(const String& p_path) ; + virtual Error execute_file(const String &p_path); virtual void finish(); /* EDITOR FUNCTIONS */ virtual void get_reserved_words(List<String> *p_words) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; - virtual String get_template(const String& p_class_name, const String& p_base_class_name) const; - 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; + virtual String get_template(const String &p_class_name, const String &p_base_class_name) const; + 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; virtual Script *create_script() const; virtual bool has_named_classes() const; - virtual int find_function(const String& p_function,const String& p_code) const; - virtual String make_function(const String& p_class,const String& p_name,const StringArray& p_args) const; - virtual Error complete_code(const String& p_code, const String& p_base_path, Object*p_owner,List<String>* r_options,String& r_call_hint); - virtual void auto_indent_code(String& p_code,int p_from_line,int p_to_line) const; - virtual void add_global_constant(const StringName& p_variable,const Variant& p_value); - + virtual int find_function(const String &p_function, const String &p_code) const; + virtual String make_function(const String &p_class, const String &p_name, const StringArray &p_args) const; + virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint); + virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; + virtual void add_global_constant(const StringName &p_variable, const Variant &p_value); /* DEBUGGER FUNCTIONS */ @@ -391,24 +371,24 @@ public: virtual int debug_get_stack_level_line(int p_level) const; virtual String debug_get_stack_level_function(int p_level) const; virtual String debug_get_stack_level_source(int p_level) const; - 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); - 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); - virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1); - virtual String debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems=-1,int p_max_depth=-1); + 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); + 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); + virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1); virtual void reload_all_scripts(); - virtual void reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload); + virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload); virtual void frame(); virtual void get_public_functions(List<MethodInfo> *p_functions) const; - virtual void get_public_constants(List<Pair<String,Variant> > *p_constants) const; + virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const; virtual void profiling_start(); virtual void profiling_stop(); - virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max); - virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max); + virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max); + virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max); /* LOADER FUNCTIONS */ @@ -418,24 +398,19 @@ public: ~GDScriptLanguage(); }; - class ResourceFormatLoaderGDScript : public ResourceFormatLoader { public: - - 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 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; - }; class ResourceFormatSaverGDScript : public ResourceFormatSaver { public: - - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const; - virtual bool recognize(const RES& p_resource) const; - + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; + virtual bool recognize(const RES &p_resource) const; }; #endif // GD_SCRIPT_H diff --git a/modules/gdscript/gd_tokenizer.cpp b/modules/gdscript/gd_tokenizer.cpp index 6b19d5fc3..3d9d49303 100644 --- a/modules/gdscript/gd_tokenizer.cpp +++ b/modules/gdscript/gd_tokenizer.cpp @@ -27,203 +27,196 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_tokenizer.h" -#include "print_string.h" #include "gd_functions.h" #include "io/marshalls.h" #include "map.h" +#include "print_string.h" -const char* GDTokenizer::token_names[TK_MAX]={ -"Empty", -"Identifier", -"Constant", -"Self", -"Built-In Type", -"Built-In Func", -"In", -"'=='", -"'!='", -"'<'", -"'<='", -"'>'", -"'>='", -"'and'", -"'or'", -"'not'", -"'+'", -"'-'", -"'*'", -"'/'", -"'%'", -"'<<'", -"'>>'", -"'='", -"'+='", -"'-='", -"'*='", -"'/='", -"'%='", -"'<<='", -"'>>='", -"'&='", -"'|='", -"'^='", -"'&'", -"'|'", -"'^'", -"'~'", -//"Plus Plus", -//"Minus Minus", -"if", -"elif", -"else", -"for", -"do", -"while", -"switch (reserved)", -"case (reserved)", -"break", -"continue", -"pass", -"return", -"func", -"class", -"extends", -"onready", -"tool", -"static", -"export", -"setget", -"const", -"var", -"preload", -"assert", -"yield", -"signal", -"breakpoint", -"'['", -"']'", -"'{'", -"'}'", -"'('", -"')'", -"','", -"';'", -"'.'", -"'?'", -"':'", -"'\\n'", -"PI", -"Error", -"EOF", -"Cursor"}; +const char *GDTokenizer::token_names[TK_MAX] = { + "Empty", + "Identifier", + "Constant", + "Self", + "Built-In Type", + "Built-In Func", + "In", + "'=='", + "'!='", + "'<'", + "'<='", + "'>'", + "'>='", + "'and'", + "'or'", + "'not'", + "'+'", + "'-'", + "'*'", + "'/'", + "'%'", + "'<<'", + "'>>'", + "'='", + "'+='", + "'-='", + "'*='", + "'/='", + "'%='", + "'<<='", + "'>>='", + "'&='", + "'|='", + "'^='", + "'&'", + "'|'", + "'^'", + "'~'", + //"Plus Plus", + //"Minus Minus", + "if", + "elif", + "else", + "for", + "do", + "while", + "switch (reserved)", + "case (reserved)", + "break", + "continue", + "pass", + "return", + "func", + "class", + "extends", + "onready", + "tool", + "static", + "export", + "setget", + "const", + "var", + "preload", + "assert", + "yield", + "signal", + "breakpoint", + "'['", + "']'", + "'{'", + "'}'", + "'('", + "')'", + "','", + "';'", + "'.'", + "'?'", + "':'", + "'\\n'", + "PI", + "Error", + "EOF", + "Cursor" +}; const char *GDTokenizer::get_token_name(Token p_token) { - ERR_FAIL_INDEX_V(p_token,TK_MAX,"<error>"); + ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>"); return token_names[p_token]; } static bool _is_text_char(CharType c) { - return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_'; + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; } static bool _is_number(CharType c) { - return (c>='0' && c<='9'); + return (c >= '0' && c <= '9'); } static bool _is_hex(CharType c) { - return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'); + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } -void GDTokenizerText::_make_token(Token p_type) { +void GDTokenizerText::_make_token(Token p_type) { - TokenData &tk=tk_rb[tk_rb_pos]; + TokenData &tk = tk_rb[tk_rb_pos]; - tk.type=p_type; - tk.line=line; - tk.col=column; + tk.type = p_type; + tk.line = line; + tk.col = column; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_identifier(const StringName& p_identifier) { +void GDTokenizerText::_make_identifier(const StringName &p_identifier) { - TokenData &tk=tk_rb[tk_rb_pos]; + TokenData &tk = tk_rb[tk_rb_pos]; - tk.type=TK_IDENTIFIER; - tk.identifier=p_identifier; - tk.line=line; - tk.col=column; - - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_IDENTIFIER; + tk.identifier = p_identifier; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_built_in_func(GDFunctions::Function p_func) { - - TokenData &tk=tk_rb[tk_rb_pos]; +void GDTokenizerText::_make_built_in_func(GDFunctions::Function p_func) { - tk.type=TK_BUILT_IN_FUNC; - tk.func=p_func; - tk.line=line; - tk.col=column; + TokenData &tk = tk_rb[tk_rb_pos]; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_BUILT_IN_FUNC; + tk.func = p_func; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_constant(const Variant& p_constant) { +void GDTokenizerText::_make_constant(const Variant &p_constant) { - TokenData &tk=tk_rb[tk_rb_pos]; + TokenData &tk = tk_rb[tk_rb_pos]; - tk.type=TK_CONSTANT; - tk.constant=p_constant; - tk.line=line; - tk.col=column; - - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_CONSTANT; + tk.constant = p_constant; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_type(const Variant::Type& p_type) { - - - TokenData &tk=tk_rb[tk_rb_pos]; +void GDTokenizerText::_make_type(const Variant::Type &p_type) { - tk.type=TK_BUILT_IN_TYPE; - tk.vtype=p_type; - tk.line=line; - tk.col=column; + TokenData &tk = tk_rb[tk_rb_pos]; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_BUILT_IN_TYPE; + tk.vtype = p_type; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } +void GDTokenizerText::_make_error(const String &p_error) { -void GDTokenizerText::_make_error(const String& p_error) { - - error_flag=true; - last_error=p_error; - - TokenData &tk=tk_rb[tk_rb_pos]; - tk.type=TK_ERROR; - tk.constant=p_error; - tk.line=line; - tk.col=column; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + error_flag = true; + last_error = p_error; + TokenData &tk = tk_rb[tk_rb_pos]; + tk.type = TK_ERROR; + tk.constant = p_error; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } - void GDTokenizerText::_make_newline(int p_spaces) { - TokenData &tk=tk_rb[tk_rb_pos]; - tk.type=TK_NEWLINE; - tk.constant=p_spaces; - tk.line=line; - tk.col=column; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + TokenData &tk = tk_rb[tk_rb_pos]; + tk.type = TK_NEWLINE; + tk.constant = p_spaces; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } void GDTokenizerText::_advance() { @@ -234,29 +227,32 @@ void GDTokenizerText::_advance() { return; } - if (code_pos>=len) { + if (code_pos >= len) { _make_token(TK_EOF); return; } -#define GETCHAR(m_ofs) ((m_ofs+code_pos)>=len?0:_code[m_ofs+code_pos]) -#define INCPOS(m_amount) { code_pos+=m_amount; column+=m_amount; } +#define GETCHAR(m_ofs) ((m_ofs + code_pos) >= len ? 0 : _code[m_ofs + code_pos]) +#define INCPOS(m_amount) \ + { \ + code_pos += m_amount; \ + column += m_amount; \ + } while (true) { + bool is_node_path = false; + StringMode string_mode = STRING_DOUBLE_QUOTE; - bool is_node_path = false; - StringMode string_mode=STRING_DOUBLE_QUOTE; - - switch(GETCHAR(0)) { + switch (GETCHAR(0)) { case 0: _make_token(TK_EOF); break; case '\\': INCPOS(1); - if (GETCHAR(0)=='\r') { + if (GETCHAR(0) == '\r') { INCPOS(1); } - if (GETCHAR(0)!='\n') { + if (GETCHAR(0) != '\n') { _make_error("Expected newline after '\\'."); return; } @@ -264,7 +260,7 @@ void GDTokenizerText::_advance() { INCPOS(1); line++; - while(GETCHAR(0)==' ' || GETCHAR(0)=='\t') { + while (GETCHAR(0) == ' ' || GETCHAR(0) == '\t') { INCPOS(1); } @@ -277,9 +273,9 @@ void GDTokenizerText::_advance() { case '\n': { line++; INCPOS(1); - column=1; - int i=0; - while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') { + column = 1; + int i = 0; + while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') { i++; } @@ -289,19 +285,19 @@ void GDTokenizerText::_advance() { #if 1 //py style tokenizer case '#': { // line comment skip - while(GETCHAR(0)!='\n') { + while (GETCHAR(0) != '\n') { code_pos++; - if (GETCHAR(0)==0) { //end of file + if (GETCHAR(0) == 0) { //end of file //_make_error("Unterminated Comment"); _make_token(TK_EOF); return; } } INCPOS(1); - column=1; + column = 1; line++; - int i=0; - while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') { + int i = 0; + while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') { i++; } _make_newline(i); @@ -311,7 +307,7 @@ void GDTokenizerText::_advance() { #endif case '/': { - switch(GETCHAR(1)) { + switch (GETCHAR(1)) { #if 0 // c style tokenizer case '*': { // block comment int pos = code_pos+2; @@ -367,11 +363,10 @@ void GDTokenizerText::_advance() { } break; default: _make_token(TK_OP_DIV); - } } break; case '=': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_EQUAL); INCPOS(1); @@ -380,12 +375,12 @@ void GDTokenizerText::_advance() { } break; case '<': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_LESS_EQUAL); INCPOS(1); - } else if (GETCHAR(1)=='<') { - if (GETCHAR(2)=='=') { + } else if (GETCHAR(1) == '<') { + if (GETCHAR(2) == '=') { _make_token(TK_OP_ASSIGN_SHIFT_LEFT); INCPOS(1); } else { @@ -397,11 +392,11 @@ void GDTokenizerText::_advance() { } break; case '>': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_GREATER_EQUAL); INCPOS(1); - } else if (GETCHAR(1)=='>') { - if (GETCHAR(2)=='=') { + } else if (GETCHAR(1) == '>') { + if (GETCHAR(2) == '=') { _make_token(TK_OP_ASSIGN_SHIFT_RIGHT); INCPOS(1); @@ -415,7 +410,7 @@ void GDTokenizerText::_advance() { } break; case '!': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_NOT_EQUAL); INCPOS(1); } else { @@ -456,7 +451,7 @@ void GDTokenizerText::_advance() { _make_token(TK_COLON); //for methods maybe but now useless. break; case '^': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_BIT_XOR); INCPOS(1); } else { @@ -468,11 +463,11 @@ void GDTokenizerText::_advance() { _make_token(TK_OP_BIT_INVERT); break; case '&': { - if (GETCHAR(1)=='&') { + if (GETCHAR(1) == '&') { _make_token(TK_OP_AND); INCPOS(1); - } else if (GETCHAR(1)=='=') { + } else if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_BIT_AND); INCPOS(1); } else { @@ -480,11 +475,11 @@ void GDTokenizerText::_advance() { } } break; case '|': { - if (GETCHAR(1)=='|') { + if (GETCHAR(1) == '|') { _make_token(TK_OP_OR); INCPOS(1); - } else if (GETCHAR(1)=='=') { + } else if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_BIT_OR); INCPOS(1); } else { @@ -493,7 +488,7 @@ void GDTokenizerText::_advance() { } break; case '*': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_MUL); INCPOS(1); } else { @@ -502,12 +497,12 @@ void GDTokenizerText::_advance() { } break; case '+': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_ADD); INCPOS(1); - //} else if (GETCHAR(1)=='+') { - // _make_token(TK_OP_PLUS_PLUS); - // INCPOS(1); + //} else if (GETCHAR(1)=='+') { + // _make_token(TK_OP_PLUS_PLUS); + // INCPOS(1); } else { _make_token(TK_OP_ADD); } @@ -515,19 +510,19 @@ void GDTokenizerText::_advance() { } break; case '-': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_SUB); INCPOS(1); - //} else if (GETCHAR(1)=='-') { - // _make_token(TK_OP_MINUS_MINUS); - // INCPOS(1); + //} else if (GETCHAR(1)=='-') { + // _make_token(TK_OP_MINUS_MINUS); + // INCPOS(1); } else { _make_token(TK_OP_SUB); } } break; case '%': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_MOD); INCPOS(1); } else { @@ -535,106 +530,103 @@ void GDTokenizerText::_advance() { } } break; case '@': - if( CharType(GETCHAR(1))!='"' && CharType(GETCHAR(1))!='\'' ) { + if (CharType(GETCHAR(1)) != '"' && CharType(GETCHAR(1)) != '\'') { _make_error("Unexpected '@'"); return; } INCPOS(1); - is_node_path=true; + is_node_path = true; case '\'': case '"': { - if (GETCHAR(0)=='\'') - string_mode=STRING_SINGLE_QUOTE; - - - int i=1; - if (string_mode==STRING_DOUBLE_QUOTE && GETCHAR(i)=='"' && GETCHAR(i+1)=='"') { - i+=2; - string_mode=STRING_MULTILINE; + if (GETCHAR(0) == '\'') + string_mode = STRING_SINGLE_QUOTE; + int i = 1; + if (string_mode == STRING_DOUBLE_QUOTE && GETCHAR(i) == '"' && GETCHAR(i + 1) == '"') { + i += 2; + string_mode = STRING_MULTILINE; } - String str; - while(true) { - if (CharType(GETCHAR(i))==0) { + while (true) { + if (CharType(GETCHAR(i)) == 0) { _make_error("Unterminated String"); return; - } else if( string_mode==STRING_DOUBLE_QUOTE && CharType(GETCHAR(i))=='"' ) { + } else if (string_mode == STRING_DOUBLE_QUOTE && CharType(GETCHAR(i)) == '"') { break; - } else if( string_mode==STRING_SINGLE_QUOTE && CharType(GETCHAR(i))=='\'' ) { + } else if (string_mode == STRING_SINGLE_QUOTE && CharType(GETCHAR(i)) == '\'') { break; - } else if( string_mode==STRING_MULTILINE && CharType(GETCHAR(i))=='\"' && CharType(GETCHAR(i+1))=='\"' && CharType(GETCHAR(i+2))=='\"') { - i+=2; + } else if (string_mode == STRING_MULTILINE && CharType(GETCHAR(i)) == '\"' && CharType(GETCHAR(i + 1)) == '\"' && CharType(GETCHAR(i + 2)) == '\"') { + i += 2; break; - } else if( string_mode!=STRING_MULTILINE && CharType(GETCHAR(i))=='\n') { + } else if (string_mode != STRING_MULTILINE && CharType(GETCHAR(i)) == '\n') { _make_error("Unexpected EOL at String."); return; - } else if( CharType(GETCHAR(i))==0xFFFF) { + } else if (CharType(GETCHAR(i)) == 0xFFFF) { //string ends here, next will be TK i--; break; - } else if (CharType(GETCHAR(i))=='\\') { + } else if (CharType(GETCHAR(i)) == '\\') { //escaped characters... i++; CharType next = GETCHAR(i); - if (next==0) { + if (next == 0) { _make_error("Unterminated String"); return; } - CharType res=0; + CharType res = 0; - switch(next) { + switch (next) { - case 'a': res=7; break; - case 'b': res=8; break; - case 't': res=9; break; - case 'n': res=10; break; - case 'v': res=11; break; - case 'f': res=12; break; - case 'r': res=13; break; - case '\'': res='\''; break; - case '\"': res='\"'; break; - case '\\': res='\\'; break; - case '/': res='/'; break; //wtf + case 'a': res = 7; break; + case 'b': res = 8; break; + case 't': res = 9; break; + case 'n': res = 10; break; + case 'v': res = 11; break; + case 'f': res = 12; break; + case 'r': res = 13; break; + case '\'': res = '\''; break; + case '\"': res = '\"'; break; + case '\\': res = '\\'; break; + case '/': + res = '/'; + break; //wtf case 'u': { //hexnumbarh - oct is deprecated - i+=1; - for(int j=0;j<4;j++) { - CharType c = GETCHAR(i+j); - if (c==0) { + i += 1; + for (int j = 0; j < 4; j++) { + CharType c = GETCHAR(i + j); + if (c == 0) { _make_error("Unterminated String"); return; } - 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'))) { _make_error("Malformed hex constant in string"); return; } 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; } - i+=3; + i += 3; } break; default: { @@ -644,15 +636,15 @@ void GDTokenizerText::_advance() { } break; } - str+=res; + str += res; } else { - if (CharType(GETCHAR(i))=='\n') { + if (CharType(GETCHAR(i)) == '\n') { line++; - column=1; + column = 1; } - str+=CharType(GETCHAR(i)); + str += CharType(GETCHAR(i)); } i++; } @@ -670,54 +662,54 @@ void GDTokenizerText::_advance() { } break; default: { - if (_is_number(GETCHAR(0)) || (GETCHAR(0)=='.' && _is_number(GETCHAR(1)))) { + if (_is_number(GETCHAR(0)) || (GETCHAR(0) == '.' && _is_number(GETCHAR(1)))) { // parse number - bool period_found=false; - bool exponent_found=false; - bool hexa_found=false; - bool sign_found=false; + bool period_found = false; + bool exponent_found = false; + bool hexa_found = false; + bool sign_found = false; String str; - int i=0; + int i = 0; - while(true) { - if (GETCHAR(i)=='.') { + while (true) { + if (GETCHAR(i) == '.') { if (period_found || exponent_found) { _make_error("Invalid numeric constant at '.'"); return; } - period_found=true; - } else if (GETCHAR(i)=='x') { - if (hexa_found || str.length()!=1 || !( (i==1 && str[0]=='0') || (i==2 && str[1]=='0' && str[0]=='-') ) ) { + period_found = true; + } else if (GETCHAR(i) == 'x') { + if (hexa_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) { _make_error("Invalid numeric constant at 'x'"); return; } - hexa_found=true; - } else if (!hexa_found && GETCHAR(i)=='e') { + hexa_found = true; + } else if (!hexa_found && GETCHAR(i) == 'e') { if (hexa_found || exponent_found) { _make_error("Invalid numeric constant at 'e'"); return; } - exponent_found=true; + exponent_found = true; } else if (_is_number(GETCHAR(i))) { //all ok } else if (hexa_found && _is_hex(GETCHAR(i))) { - } else if ((GETCHAR(i)=='-' || GETCHAR(i)=='+') && exponent_found) { + } else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) { if (sign_found) { _make_error("Invalid numeric constant at '-'"); return; } - sign_found=true; + sign_found = true; } else break; - str+=CharType(GETCHAR(i)); + str += CharType(GETCHAR(i)); i++; } - if (!( _is_number(str[str.length()-1]) || (hexa_found && _is_hex(str[str.length()-1])))) { - _make_error("Invalid numeric constant: "+str); + if (!(_is_number(str[str.length() - 1]) || (hexa_found && _is_hex(str[str.length() - 1])))) { + _make_error("Invalid numeric constant: " + str); return; } @@ -732,13 +724,12 @@ void GDTokenizerText::_advance() { } else { int val = str.to_int(); _make_constant(val); - } return; } - if (GETCHAR(0)=='.') { + if (GETCHAR(0) == '.') { //parse period _make_token(TK_PERIOD); break; @@ -747,75 +738,77 @@ void GDTokenizerText::_advance() { if (_is_text_char(GETCHAR(0))) { // parse identifier String str; - str+=CharType(GETCHAR(0)); + str += CharType(GETCHAR(0)); - int i=1; - while(_is_text_char(GETCHAR(i))) { - str+=CharType(GETCHAR(i)); + int i = 1; + while (_is_text_char(GETCHAR(i))) { + str += CharType(GETCHAR(i)); i++; } - bool identifier=false; + bool identifier = false; - if (str=="null") { + if (str == "null") { _make_constant(Variant()); - } else if (str=="true") { + } else if (str == "true") { _make_constant(true); - } else if (str=="false") { + } else if (str == "false") { _make_constant(false); } else { - bool found=false; + bool found = false; - struct _bit { Variant::Type type; const char *text;}; + struct _bit { + Variant::Type type; + const char *text; + }; //built in types - static const _bit type_list[]={ + static const _bit type_list[] = { //types - {Variant::BOOL,"bool"}, - {Variant::INT,"int"}, - {Variant::REAL,"float"}, - {Variant::STRING,"String"}, - {Variant::VECTOR2,"Vector2"}, - {Variant::RECT2,"Rect2"}, - {Variant::MATRIX32,"Matrix32"}, - {Variant::VECTOR3,"Vector3"}, - {Variant::_AABB,"AABB"}, - {Variant::_AABB,"Rect3"}, - {Variant::PLANE,"Plane"}, - {Variant::QUAT,"Quat"}, - {Variant::MATRIX3,"Matrix3"}, - {Variant::TRANSFORM,"Transform"}, - {Variant::COLOR,"Color"}, - {Variant::IMAGE,"Image"}, - {Variant::_RID,"RID"}, - {Variant::OBJECT,"Object"}, - {Variant::INPUT_EVENT,"InputEvent"}, - {Variant::NODE_PATH,"NodePath"}, - {Variant::DICTIONARY,"Dictionary"}, - {Variant::ARRAY,"Array"}, - {Variant::RAW_ARRAY,"RawArray"}, - {Variant::INT_ARRAY,"IntArray"}, - {Variant::REAL_ARRAY,"FloatArray"}, - {Variant::STRING_ARRAY,"StringArray"}, - {Variant::VECTOR2_ARRAY,"Vector2Array"}, - {Variant::VECTOR3_ARRAY,"Vector3Array"}, - {Variant::COLOR_ARRAY,"ColorArray"}, - {Variant::VARIANT_MAX,NULL}, + { Variant::BOOL, "bool" }, + { Variant::INT, "int" }, + { Variant::REAL, "float" }, + { Variant::STRING, "String" }, + { Variant::VECTOR2, "Vector2" }, + { Variant::RECT2, "Rect2" }, + { Variant::MATRIX32, "Matrix32" }, + { Variant::VECTOR3, "Vector3" }, + { Variant::_AABB, "AABB" }, + { Variant::_AABB, "Rect3" }, + { Variant::PLANE, "Plane" }, + { Variant::QUAT, "Quat" }, + { Variant::MATRIX3, "Matrix3" }, + { Variant::TRANSFORM, "Transform" }, + { Variant::COLOR, "Color" }, + { Variant::IMAGE, "Image" }, + { Variant::_RID, "RID" }, + { Variant::OBJECT, "Object" }, + { Variant::INPUT_EVENT, "InputEvent" }, + { Variant::NODE_PATH, "NodePath" }, + { Variant::DICTIONARY, "Dictionary" }, + { Variant::ARRAY, "Array" }, + { Variant::RAW_ARRAY, "RawArray" }, + { Variant::INT_ARRAY, "IntArray" }, + { Variant::REAL_ARRAY, "FloatArray" }, + { Variant::STRING_ARRAY, "StringArray" }, + { Variant::VECTOR2_ARRAY, "Vector2Array" }, + { Variant::VECTOR3_ARRAY, "Vector3Array" }, + { Variant::COLOR_ARRAY, "ColorArray" }, + { Variant::VARIANT_MAX, NULL }, }; { + int idx = 0; - int idx=0; - - while(type_list[idx].text) { + while (type_list[idx].text) { - if (str==type_list[idx].text) { + if (str == type_list[idx].text) { _make_type(type_list[idx].type); - found=true; + found = true; break; } idx++; @@ -826,12 +819,12 @@ void GDTokenizerText::_advance() { //built in func? - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { - if (str==GDFunctions::get_func_name(GDFunctions::Function(i))) { + if (str == GDFunctions::get_func_name(GDFunctions::Function(i))) { _make_built_in_func(GDFunctions::Function(i)); - found=true; + found = true; break; } } @@ -841,57 +834,59 @@ void GDTokenizerText::_advance() { if (!found) { + struct _kws { + Token token; + const char *text; + }; - struct _kws { Token token; const char *text;}; - - static const _kws keyword_list[]={ + static const _kws keyword_list[] = { //ops - {TK_OP_IN,"in"}, - {TK_OP_NOT,"not"}, - {TK_OP_OR,"or"}, - {TK_OP_AND,"and"}, + { TK_OP_IN, "in" }, + { TK_OP_NOT, "not" }, + { TK_OP_OR, "or" }, + { TK_OP_AND, "and" }, //func - {TK_PR_FUNCTION,"func"}, - {TK_PR_CLASS,"class"}, - {TK_PR_EXTENDS,"extends"}, - {TK_PR_ONREADY,"onready"}, - {TK_PR_TOOL,"tool"}, - {TK_PR_STATIC,"static"}, - {TK_PR_EXPORT,"export"}, - {TK_PR_SETGET,"setget"}, - {TK_PR_VAR,"var"}, - {TK_PR_PRELOAD,"preload"}, - {TK_PR_ASSERT,"assert"}, - {TK_PR_YIELD,"yield"}, - {TK_PR_SIGNAL,"signal"}, - {TK_PR_BREAKPOINT,"breakpoint"}, - {TK_PR_CONST,"const"}, + { TK_PR_FUNCTION, "func" }, + { TK_PR_CLASS, "class" }, + { TK_PR_EXTENDS, "extends" }, + { TK_PR_ONREADY, "onready" }, + { TK_PR_TOOL, "tool" }, + { TK_PR_STATIC, "static" }, + { TK_PR_EXPORT, "export" }, + { TK_PR_SETGET, "setget" }, + { TK_PR_VAR, "var" }, + { TK_PR_PRELOAD, "preload" }, + { TK_PR_ASSERT, "assert" }, + { TK_PR_YIELD, "yield" }, + { TK_PR_SIGNAL, "signal" }, + { TK_PR_BREAKPOINT, "breakpoint" }, + { TK_PR_CONST, "const" }, //controlflow - {TK_CF_IF,"if"}, - {TK_CF_ELIF,"elif"}, - {TK_CF_ELSE,"else"}, - {TK_CF_FOR,"for"}, - {TK_CF_WHILE,"while"}, - {TK_CF_DO,"do"}, - {TK_CF_SWITCH,"switch"}, - {TK_CF_CASE,"case"}, - {TK_CF_BREAK,"break"}, - {TK_CF_CONTINUE,"continue"}, - {TK_CF_RETURN,"return"}, - {TK_CF_PASS,"pass"}, - {TK_SELF,"self"}, - {TK_CONST_PI,"PI"}, - {TK_ERROR,NULL} + { TK_CF_IF, "if" }, + { TK_CF_ELIF, "elif" }, + { TK_CF_ELSE, "else" }, + { TK_CF_FOR, "for" }, + { TK_CF_WHILE, "while" }, + { TK_CF_DO, "do" }, + { TK_CF_SWITCH, "switch" }, + { TK_CF_CASE, "case" }, + { TK_CF_BREAK, "break" }, + { TK_CF_CONTINUE, "continue" }, + { TK_CF_RETURN, "return" }, + { TK_CF_PASS, "pass" }, + { TK_SELF, "self" }, + { TK_CONST_PI, "PI" }, + { TK_ERROR, NULL } }; - int idx=0; - found=false; + int idx = 0; + found = false; - while(keyword_list[idx].text) { + while (keyword_list[idx].text) { - if (str==keyword_list[idx].text) { + if (str == keyword_list[idx].text) { _make_token(keyword_list[idx].token); - found=true; + found = true; break; } idx++; @@ -899,10 +894,9 @@ void GDTokenizerText::_advance() { } if (!found) - identifier=true; + identifier = true; } - if (identifier) { _make_identifier(str); } @@ -919,381 +913,358 @@ void GDTokenizerText::_advance() { INCPOS(1); break; } - } -void GDTokenizerText::set_code(const String& p_code) { +void GDTokenizerText::set_code(const String &p_code) { - code=p_code; + code = p_code; len = p_code.length(); if (len) { - _code=&code[0]; + _code = &code[0]; } else { - _code=NULL; + _code = NULL; } - code_pos=0; - line=1; //it is stand-ar-ized that lines begin in 1 in code.. - column=1; //the same holds for columns - tk_rb_pos=0; - error_flag=false; - last_error=""; - for(int i=0;i<MAX_LOOKAHEAD+1;i++) + code_pos = 0; + line = 1; //it is stand-ar-ized that lines begin in 1 in code.. + column = 1; //the same holds for columns + tk_rb_pos = 0; + error_flag = false; + last_error = ""; + for (int i = 0; i < MAX_LOOKAHEAD + 1; i++) _advance(); } GDTokenizerText::Token GDTokenizerText::get_token(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, TK_ERROR); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, TK_ERROR); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, TK_ERROR); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, TK_ERROR); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; return tk_rb[ofs].type; } int GDTokenizerText::get_token_line(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, -1); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; return tk_rb[ofs].line; } int GDTokenizerText::get_token_column(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, -1); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; return tk_rb[ofs].col; } -const Variant& GDTokenizerText::get_token_constant(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, tk_rb[0].constant); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, tk_rb[0].constant); +const Variant &GDTokenizerText::get_token_constant(int p_offset) const { + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, tk_rb[0].constant); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, tk_rb[0].constant); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_CONSTANT,tk_rb[0].constant); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_CONSTANT, tk_rb[0].constant); return tk_rb[ofs].constant; } StringName GDTokenizerText::get_token_identifier(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, StringName()); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, StringName()); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, StringName()); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, StringName()); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_IDENTIFIER,StringName()); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_IDENTIFIER, StringName()); return tk_rb[ofs].identifier; - } GDFunctions::Function GDTokenizerText::get_token_built_in_func(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_BUILT_IN_FUNC,GDFunctions::FUNC_MAX); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_FUNC, GDFunctions::FUNC_MAX); return tk_rb[ofs].func; - } Variant::Type GDTokenizerText::get_token_type(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, Variant::NIL); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, Variant::NIL); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, Variant::NIL); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, Variant::NIL); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_BUILT_IN_TYPE,Variant::NIL); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_TYPE, Variant::NIL); return tk_rb[ofs].vtype; - } - int GDTokenizerText::get_token_line_indent(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, 0); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, 0); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_NEWLINE,0); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0); return tk_rb[ofs].constant; - } String GDTokenizerText::get_token_error(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, String()); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, String()); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, String()); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, String()); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_ERROR,String()); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_ERROR, String()); return tk_rb[ofs].constant; } void GDTokenizerText::advance(int p_amount) { - ERR_FAIL_COND( p_amount <=0 ); - for(int i=0;i<p_amount;i++) + ERR_FAIL_COND(p_amount <= 0); + for (int i = 0; i < p_amount; i++) _advance(); } - - - - - - - - - - ////////////////////////////////////////////////////////////////////////////////////////////////////// #define BYTECODE_VERSION 10 -Error GDTokenizerBuffer::set_code_buffer(const Vector<uint8_t> & p_buffer) { - +Error GDTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) { - const uint8_t *buf=p_buffer.ptr(); - int total_len=p_buffer.size(); - ERR_FAIL_COND_V( p_buffer.size()<24 || p_buffer[0]!='G' || p_buffer[1]!='D' || p_buffer[2]!='S' || p_buffer[3]!='C',ERR_INVALID_DATA); + const uint8_t *buf = p_buffer.ptr(); + int total_len = p_buffer.size(); + ERR_FAIL_COND_V(p_buffer.size() < 24 || p_buffer[0] != 'G' || p_buffer[1] != 'D' || p_buffer[2] != 'S' || p_buffer[3] != 'C', ERR_INVALID_DATA); int version = decode_uint32(&buf[4]); - if (version>BYTECODE_VERSION) { + if (version > BYTECODE_VERSION) { ERR_EXPLAIN("Bytecode is too New! Please use a newer engine version."); - ERR_FAIL_COND_V(version>BYTECODE_VERSION,ERR_INVALID_DATA); + ERR_FAIL_COND_V(version > BYTECODE_VERSION, ERR_INVALID_DATA); } int identifier_count = decode_uint32(&buf[8]); int constant_count = decode_uint32(&buf[12]); int line_count = decode_uint32(&buf[16]); int token_count = decode_uint32(&buf[20]); - const uint8_t *b=buf; + const uint8_t *b = buf; - b=&buf[24]; - total_len-=24; + b = &buf[24]; + total_len -= 24; identifiers.resize(identifier_count); - for(int i=0;i<identifier_count;i++) { + for (int i = 0; i < identifier_count; i++) { int len = decode_uint32(b); - ERR_FAIL_COND_V(len>total_len,ERR_INVALID_DATA); - b+=4; + ERR_FAIL_COND_V(len > total_len, ERR_INVALID_DATA); + b += 4; Vector<uint8_t> cs; cs.resize(len); - for(int j=0;j<len;j++) { - cs[j]=b[j]^0xb6; + for (int j = 0; j < len; j++) { + cs[j] = b[j] ^ 0xb6; } - cs[cs.size()-1]=0; + cs[cs.size() - 1] = 0; String s; - s.parse_utf8((const char*)cs.ptr()); - b+=len; - total_len-=len+4; - identifiers[i]=s; + s.parse_utf8((const char *)cs.ptr()); + b += len; + total_len -= len + 4; + identifiers[i] = s; } constants.resize(constant_count); - for(int i=0;i<constant_count;i++) { + for (int i = 0; i < constant_count; i++) { Variant v; int len; - Error err = decode_variant(v,b,total_len,&len); + Error err = decode_variant(v, b, total_len, &len); if (err) return err; - b+=len; - total_len-=len; - constants[i]=v; - + b += len; + total_len -= len; + constants[i] = v; } - ERR_FAIL_COND_V(line_count*8>total_len,ERR_INVALID_DATA); + ERR_FAIL_COND_V(line_count * 8 > total_len, ERR_INVALID_DATA); - for(int i=0;i<line_count;i++) { + for (int i = 0; i < line_count; i++) { - uint32_t token=decode_uint32(b); - b+=4; - uint32_t linecol=decode_uint32(b); - b+=4; + uint32_t token = decode_uint32(b); + b += 4; + uint32_t linecol = decode_uint32(b); + b += 4; - lines.insert(token,linecol); - total_len-=8; + lines.insert(token, linecol); + total_len -= 8; } tokens.resize(token_count); - for(int i=0;i<token_count;i++) { + for (int i = 0; i < token_count; i++) { - ERR_FAIL_COND_V( total_len < 1, ERR_INVALID_DATA); + ERR_FAIL_COND_V(total_len < 1, ERR_INVALID_DATA); - if ((*b)&TOKEN_BYTE_MASK) { //little endian always - ERR_FAIL_COND_V( total_len < 4, ERR_INVALID_DATA); + if ((*b) & TOKEN_BYTE_MASK) { //little endian always + ERR_FAIL_COND_V(total_len < 4, ERR_INVALID_DATA); - tokens[i]=decode_uint32(b)&~TOKEN_BYTE_MASK; - b+=4; + tokens[i] = decode_uint32(b) & ~TOKEN_BYTE_MASK; + b += 4; } else { - tokens[i]=*b; - b+=1; + tokens[i] = *b; + b += 1; total_len--; } } - token=0; + token = 0; return OK; - } - -Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) { +Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String &p_code) { Vector<uint8_t> buf; - - Map<StringName,int> identifier_map; - HashMap<Variant,int,VariantHasher> constant_map; - Map<uint32_t,int> line_map; + Map<StringName, int> identifier_map; + HashMap<Variant, int, VariantHasher> constant_map; + Map<uint32_t, int> line_map; Vector<uint32_t> token_array; GDTokenizerText tt; tt.set_code(p_code); - int line=-1; + int line = -1; - while(true) { + while (true) { - if (tt.get_token_line()!=line) { + if (tt.get_token_line() != line) { - line=tt.get_token_line(); - line_map[line]=token_array.size(); + line = tt.get_token_line(); + line_map[line] = token_array.size(); } - uint32_t token=tt.get_token(); - switch(tt.get_token()) { + uint32_t token = tt.get_token(); + switch (tt.get_token()) { case TK_IDENTIFIER: { StringName id = tt.get_token_identifier(); if (!identifier_map.has(id)) { int idx = identifier_map.size(); - identifier_map[id]=idx; + identifier_map[id] = idx; } - token|=identifier_map[id]<<TOKEN_BITS; + token |= identifier_map[id] << TOKEN_BITS; } break; case TK_CONSTANT: { Variant c = tt.get_token_constant(); if (!constant_map.has(c)) { int idx = constant_map.size(); - constant_map[c]=idx; + constant_map[c] = idx; } - token|=constant_map[c]<<TOKEN_BITS; + token |= constant_map[c] << TOKEN_BITS; } break; case TK_BUILT_IN_TYPE: { - token|=tt.get_token_type()<<TOKEN_BITS; + token |= tt.get_token_type() << TOKEN_BITS; } break; case TK_BUILT_IN_FUNC: { - token|=tt.get_token_built_in_func()<<TOKEN_BITS; + token |= tt.get_token_built_in_func() << TOKEN_BITS; } break; case TK_NEWLINE: { - token|=tt.get_token_line_indent()<<TOKEN_BITS; + token |= tt.get_token_line_indent() << TOKEN_BITS; } break; case TK_ERROR: { ERR_FAIL_V(Vector<uint8_t>()); } break; default: {} - }; token_array.push_back(token); - if (tt.get_token()==TK_EOF) + if (tt.get_token() == TK_EOF) break; tt.advance(); - } //reverse maps - Map<int,StringName> rev_identifier_map; - for(Map<StringName,int>::Element *E=identifier_map.front();E;E=E->next()) { - rev_identifier_map[E->get()]=E->key(); + Map<int, StringName> rev_identifier_map; + for (Map<StringName, int>::Element *E = identifier_map.front(); E; E = E->next()) { + rev_identifier_map[E->get()] = E->key(); } - Map<int,Variant> rev_constant_map; - const Variant *K =NULL; - while((K=constant_map.next(K))) { - rev_constant_map[constant_map[*K]]=*K; + Map<int, Variant> rev_constant_map; + const Variant *K = NULL; + while ((K = constant_map.next(K))) { + rev_constant_map[constant_map[*K]] = *K; } - Map<int,uint32_t> rev_line_map; - for(Map<uint32_t,int>::Element *E=line_map.front();E;E=E->next()) { - rev_line_map[E->get()]=E->key(); + Map<int, uint32_t> rev_line_map; + for (Map<uint32_t, int>::Element *E = line_map.front(); E; E = E->next()) { + rev_line_map[E->get()] = E->key(); } //save header buf.resize(24); - buf[0]='G'; - buf[1]='D'; - buf[2]='S'; - buf[3]='C'; - encode_uint32(BYTECODE_VERSION,&buf[4]); - encode_uint32(identifier_map.size(),&buf[8]); - encode_uint32(constant_map.size(),&buf[12]); - encode_uint32(line_map.size(),&buf[16]); - encode_uint32(token_array.size(),&buf[20]); + buf[0] = 'G'; + buf[1] = 'D'; + buf[2] = 'S'; + buf[3] = 'C'; + encode_uint32(BYTECODE_VERSION, &buf[4]); + encode_uint32(identifier_map.size(), &buf[8]); + encode_uint32(constant_map.size(), &buf[12]); + encode_uint32(line_map.size(), &buf[16]); + encode_uint32(token_array.size(), &buf[20]); //save identifiers - for(Map<int,StringName>::Element *E=rev_identifier_map.front();E;E=E->next()) { + for (Map<int, StringName>::Element *E = rev_identifier_map.front(); E; E = E->next()) { CharString cs = String(E->get()).utf8(); - int len = cs.length()+1; - int extra = 4-(len%4); - if (extra==4) - extra=0; + int len = cs.length() + 1; + int extra = 4 - (len % 4); + if (extra == 4) + extra = 0; uint8_t ibuf[4]; - encode_uint32(len+extra,ibuf); - for(int i=0;i<4;i++) { + encode_uint32(len + extra, ibuf); + for (int i = 0; i < 4; i++) { buf.push_back(ibuf[i]); } - for(int i=0;i<len;i++) { - buf.push_back(cs[i]^0xb6); + for (int i = 0; i < len; i++) { + buf.push_back(cs[i] ^ 0xb6); } - for(int i=0;i<extra;i++) { - buf.push_back(0^0xb6); + for (int i = 0; i < extra; i++) { + buf.push_back(0 ^ 0xb6); } } - for(Map<int,Variant>::Element *E=rev_constant_map.front();E;E=E->next()) { + for (Map<int, Variant>::Element *E = rev_constant_map.front(); E; E = E->next()) { int len; - Error err = encode_variant(E->get(),NULL,len); - ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>()); - int pos=buf.size(); - buf.resize(pos+len); - encode_variant(E->get(),&buf[pos],len); + Error err = encode_variant(E->get(), NULL, len); + ERR_FAIL_COND_V(err != OK, Vector<uint8_t>()); + int pos = buf.size(); + buf.resize(pos + len); + encode_variant(E->get(), &buf[pos], len); } - for(Map<int,uint32_t>::Element *E=rev_line_map.front();E;E=E->next()) { + for (Map<int, uint32_t>::Element *E = rev_line_map.front(); E; E = E->next()) { uint8_t ibuf[8]; - encode_uint32(E->key(),&ibuf[0]); - encode_uint32(E->get(),&ibuf[4]); - for(int i=0;i<8;i++) + encode_uint32(E->key(), &ibuf[0]); + encode_uint32(E->get(), &ibuf[4]); + for (int i = 0; i < 8; i++) buf.push_back(ibuf[i]); } - for(int i=0;i<token_array.size();i++) { + for (int i = 0; i < token_array.size(); i++) { uint32_t token = token_array[i]; - if (token&~TOKEN_MASK) { + if (token & ~TOKEN_MASK) { uint8_t buf4[4]; - encode_uint32(token_array[i]|TOKEN_BYTE_MASK,&buf4[0]); - for(int j=0;j<4;j++) { + encode_uint32(token_array[i] | TOKEN_BYTE_MASK, &buf4[0]); + for (int j = 0; j < 4; j++) { buf.push_back(buf4[j]); } } else { @@ -1302,102 +1273,94 @@ Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) { } return buf; - } GDTokenizerBuffer::Token GDTokenizerBuffer::get_token(int p_offset) const { - int offset = token+p_offset; + int offset = token + p_offset; - if (offset<0 || offset>=tokens.size()) + if (offset < 0 || offset >= tokens.size()) return TK_EOF; - return GDTokenizerBuffer::Token(tokens[offset]&TOKEN_MASK); + return GDTokenizerBuffer::Token(tokens[offset] & TOKEN_MASK); } +StringName GDTokenizerBuffer::get_token_identifier(int p_offset) const { -StringName GDTokenizerBuffer::get_token_identifier(int p_offset) const{ + int offset = token + p_offset; - int offset = token+p_offset; - - ERR_FAIL_INDEX_V(offset,tokens.size(),StringName()); - uint32_t identifier = tokens[offset]>>TOKEN_BITS; - ERR_FAIL_INDEX_V(identifier,identifiers.size(),StringName()); + ERR_FAIL_INDEX_V(offset, tokens.size(), StringName()); + uint32_t identifier = tokens[offset] >> TOKEN_BITS; + ERR_FAIL_INDEX_V(identifier, identifiers.size(), StringName()); return identifiers[identifier]; } -GDFunctions::Function GDTokenizerBuffer::get_token_built_in_func(int p_offset) const{ +GDFunctions::Function GDTokenizerBuffer::get_token_built_in_func(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),GDFunctions::FUNC_MAX); - return GDFunctions::Function(tokens[offset]>>TOKEN_BITS); + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), GDFunctions::FUNC_MAX); + return GDFunctions::Function(tokens[offset] >> TOKEN_BITS); } -Variant::Type GDTokenizerBuffer::get_token_type(int p_offset) const{ +Variant::Type GDTokenizerBuffer::get_token_type(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),Variant::NIL); + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), Variant::NIL); - return Variant::Type(tokens[offset]>>TOKEN_BITS); + return Variant::Type(tokens[offset] >> TOKEN_BITS); } -int GDTokenizerBuffer::get_token_line(int p_offset) const{ +int GDTokenizerBuffer::get_token_line(int p_offset) const { - int offset = token+p_offset; + int offset = token + p_offset; int pos = lines.find_nearest(offset); - if (pos<0) + if (pos < 0) return -1; - if (pos>=lines.size()) - pos=lines.size()-1; + if (pos >= lines.size()) + pos = lines.size() - 1; uint32_t l = lines.getv(pos); - return l&TOKEN_LINE_MASK; - + return l & TOKEN_LINE_MASK; } -int GDTokenizerBuffer::get_token_column(int p_offset) const{ +int GDTokenizerBuffer::get_token_column(int p_offset) const { - int offset = token+p_offset; + int offset = token + p_offset; int pos = lines.find_nearest(offset); - if (pos<0) + if (pos < 0) return -1; - if (pos>=lines.size()) - pos=lines.size()-1; + if (pos >= lines.size()) + pos = lines.size() - 1; uint32_t l = lines.getv(pos); - return l>>TOKEN_LINE_BITS; - + return l >> TOKEN_LINE_BITS; } -int GDTokenizerBuffer::get_token_line_indent(int p_offset) const{ +int GDTokenizerBuffer::get_token_line_indent(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),0); - return tokens[offset]>>TOKEN_BITS; + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), 0); + return tokens[offset] >> TOKEN_BITS; } -const Variant& GDTokenizerBuffer::get_token_constant(int p_offset) const{ - +const Variant &GDTokenizerBuffer::get_token_constant(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),nil); - uint32_t constant = tokens[offset]>>TOKEN_BITS; - ERR_FAIL_INDEX_V(constant,constants.size(),nil); + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), nil); + uint32_t constant = tokens[offset] >> TOKEN_BITS; + ERR_FAIL_INDEX_V(constant, constants.size(), nil); return constants[constant]; - } -String GDTokenizerBuffer::get_token_error(int p_offset) const{ +String GDTokenizerBuffer::get_token_error(int p_offset) const { ERR_FAIL_V(String()); } -void GDTokenizerBuffer::advance(int p_amount){ +void GDTokenizerBuffer::advance(int p_amount) { - ERR_FAIL_INDEX(p_amount+token,tokens.size()); - token+=p_amount; + ERR_FAIL_INDEX(p_amount + token, tokens.size()); + token += p_amount; } -GDTokenizerBuffer::GDTokenizerBuffer(){ - - token=0; +GDTokenizerBuffer::GDTokenizerBuffer() { + token = 0; } - diff --git a/modules/gdscript/gd_tokenizer.h b/modules/gdscript/gd_tokenizer.h index b26cdd916..1fe0910c3 100644 --- a/modules/gdscript/gd_tokenizer.h +++ b/modules/gdscript/gd_tokenizer.h @@ -29,15 +29,14 @@ #ifndef GD_TOKENIZER_H #define GD_TOKENIZER_H +#include "gd_functions.h" +#include "string_db.h" #include "ustring.h" #include "variant.h" -#include "string_db.h" -#include "gd_functions.h" #include "vmap.h" class GDTokenizer { public: - enum Token { TK_EMPTY, @@ -127,37 +126,36 @@ public: }; protected: - enum StringMode { STRING_SINGLE_QUOTE, STRING_DOUBLE_QUOTE, STRING_MULTILINE }; - static const char* token_names[TK_MAX]; + static const char *token_names[TK_MAX]; + public: static const char *get_token_name(Token p_token); - virtual const Variant& get_token_constant(int p_offset=0) const=0; - virtual Token get_token(int p_offset=0) const=0; - virtual StringName get_token_identifier(int p_offset=0) const=0; - virtual GDFunctions::Function get_token_built_in_func(int p_offset=0) const=0; - virtual Variant::Type get_token_type(int p_offset=0) const=0; - virtual int get_token_line(int p_offset=0) const=0; - virtual int get_token_column(int p_offset=0) const=0; - virtual int get_token_line_indent(int p_offset=0) const=0; - virtual String get_token_error(int p_offset=0) const=0; - virtual void advance(int p_amount=1)=0; + virtual const Variant &get_token_constant(int p_offset = 0) const = 0; + virtual Token get_token(int p_offset = 0) const = 0; + virtual StringName get_token_identifier(int p_offset = 0) const = 0; + virtual GDFunctions::Function get_token_built_in_func(int p_offset = 0) const = 0; + virtual Variant::Type get_token_type(int p_offset = 0) const = 0; + virtual int get_token_line(int p_offset = 0) const = 0; + virtual int get_token_column(int p_offset = 0) const = 0; + virtual int get_token_line_indent(int p_offset = 0) const = 0; + virtual String get_token_error(int p_offset = 0) const = 0; + virtual void advance(int p_amount = 1) = 0; virtual ~GDTokenizer(){}; - }; class GDTokenizerText : public GDTokenizer { enum { - MAX_LOOKAHEAD=4, - TK_RB_SIZE=MAX_LOOKAHEAD*2+1 + MAX_LOOKAHEAD = 4, + TK_RB_SIZE = MAX_LOOKAHEAD * 2 + 1 }; @@ -169,17 +167,21 @@ class GDTokenizerText : public GDTokenizer { Variant::Type vtype; //for type types GDFunctions::Function func; //function for built in functions }; - int line,col; - TokenData() { type = TK_EMPTY; line=col=0; vtype=Variant::NIL; } + int line, col; + TokenData() { + type = TK_EMPTY; + line = col = 0; + vtype = Variant::NIL; + } }; void _make_token(Token p_type); - void _make_newline(int p_spaces=0); - void _make_identifier(const StringName& p_identifier); + void _make_newline(int p_spaces = 0); + void _make_identifier(const StringName &p_identifier); void _make_built_in_func(GDFunctions::Function p_func); - void _make_constant(const Variant& p_constant); - void _make_type(const Variant::Type& p_type); - void _make_error(const String& p_error); + void _make_constant(const Variant &p_constant); + void _make_type(const Variant::Type &p_type); + void _make_error(const String &p_error); String code; int len; @@ -187,66 +189,58 @@ class GDTokenizerText : public GDTokenizer { const CharType *_code; int line; int column; - TokenData tk_rb[TK_RB_SIZE*2+1]; + TokenData tk_rb[TK_RB_SIZE * 2 + 1]; int tk_rb_pos; String last_error; bool error_flag; void _advance(); -public: - - void set_code(const String& p_code); - virtual Token get_token(int p_offset=0) const; - virtual StringName get_token_identifier(int p_offset=0) const; - virtual GDFunctions::Function get_token_built_in_func(int p_offset=0) const; - virtual Variant::Type get_token_type(int p_offset=0) const; - virtual int get_token_line(int p_offset=0) const; - virtual int get_token_column(int p_offset=0) const; - virtual int get_token_line_indent(int p_offset=0) const; - virtual const Variant& get_token_constant(int p_offset=0) const; - virtual String get_token_error(int p_offset=0) const; - virtual void advance(int p_amount=1); +public: + void set_code(const String &p_code); + virtual Token get_token(int p_offset = 0) const; + virtual StringName get_token_identifier(int p_offset = 0) const; + virtual GDFunctions::Function get_token_built_in_func(int p_offset = 0) const; + virtual Variant::Type get_token_type(int p_offset = 0) const; + virtual int get_token_line(int p_offset = 0) const; + virtual int get_token_column(int p_offset = 0) const; + virtual int get_token_line_indent(int p_offset = 0) const; + virtual const Variant &get_token_constant(int p_offset = 0) const; + virtual String get_token_error(int p_offset = 0) const; + virtual void advance(int p_amount = 1); }; - - - class GDTokenizerBuffer : public GDTokenizer { - enum { - TOKEN_BYTE_MASK=0x80, - TOKEN_BITS=8, - TOKEN_MASK=(1<<TOKEN_BITS)-1, - TOKEN_LINE_BITS=24, - TOKEN_LINE_MASK=(1<<TOKEN_LINE_BITS)-1, + TOKEN_BYTE_MASK = 0x80, + TOKEN_BITS = 8, + TOKEN_MASK = (1 << TOKEN_BITS) - 1, + TOKEN_LINE_BITS = 24, + TOKEN_LINE_MASK = (1 << TOKEN_LINE_BITS) - 1, }; - Vector<StringName> identifiers; Vector<Variant> constants; - VMap<uint32_t,uint32_t> lines; + VMap<uint32_t, uint32_t> lines; Vector<uint32_t> tokens; Variant nil; int token; public: - - - Error set_code_buffer(const Vector<uint8_t> & p_buffer); - static Vector<uint8_t> parse_code_string(const String& p_code); - virtual Token get_token(int p_offset=0) const; - virtual StringName get_token_identifier(int p_offset=0) const; - virtual GDFunctions::Function get_token_built_in_func(int p_offset=0) const; - virtual Variant::Type get_token_type(int p_offset=0) const; - virtual int get_token_line(int p_offset=0) const; - virtual int get_token_column(int p_offset=0) const; - virtual int get_token_line_indent(int p_offset=0) const; - virtual const Variant& get_token_constant(int p_offset=0) const; - virtual String get_token_error(int p_offset=0) const; - virtual void advance(int p_amount=1); + Error set_code_buffer(const Vector<uint8_t> &p_buffer); + static Vector<uint8_t> parse_code_string(const String &p_code); + virtual Token get_token(int p_offset = 0) const; + virtual StringName get_token_identifier(int p_offset = 0) const; + virtual GDFunctions::Function get_token_built_in_func(int p_offset = 0) const; + virtual Variant::Type get_token_type(int p_offset = 0) const; + virtual int get_token_line(int p_offset = 0) const; + virtual int get_token_column(int p_offset = 0) const; + virtual int get_token_line_indent(int p_offset = 0) const; + virtual const Variant &get_token_constant(int p_offset = 0) const; + virtual String get_token_error(int p_offset = 0) const; + virtual void advance(int p_amount = 1); GDTokenizerBuffer(); }; diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index 2fc663c85..1711f2ba8 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -29,111 +29,103 @@ #include "register_types.h" #include "gd_script.h" +#include "io/file_access_encrypted.h" #include "io/resource_loader.h" #include "os/file_access.h" -#include "io/file_access_encrypted.h" - - -GDScriptLanguage *script_language_gd=NULL; -ResourceFormatLoaderGDScript *resource_loader_gd=NULL; -ResourceFormatSaverGDScript *resource_saver_gd=NULL; +GDScriptLanguage *script_language_gd = NULL; +ResourceFormatLoaderGDScript *resource_loader_gd = NULL; +ResourceFormatSaverGDScript *resource_saver_gd = NULL; #ifdef TOOLS_ENABLED #include "editor/editor_import_export.h" -#include "gd_tokenizer.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" +#include "gd_tokenizer.h" class EditorExportGDScript : public EditorExportPlugin { - OBJ_TYPE(EditorExportGDScript,EditorExportPlugin); + OBJ_TYPE(EditorExportGDScript, EditorExportPlugin); public: - - virtual Vector<uint8_t> custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform) { + virtual Vector<uint8_t> custom_export(String &p_path, const Ref<EditorExportPlatform> &p_platform) { //compile gdscript to bytecode - if (EditorImportExport::get_singleton()->script_get_action()!=EditorImportExport::SCRIPT_ACTION_NONE) { + if (EditorImportExport::get_singleton()->script_get_action() != EditorImportExport::SCRIPT_ACTION_NONE) { if (p_path.ends_with(".gd")) { Vector<uint8_t> file = FileAccess::get_file_as_array(p_path); if (file.empty()) return file; String txt; - txt.parse_utf8((const char*)file.ptr(),file.size()); + txt.parse_utf8((const char *)file.ptr(), file.size()); file = GDTokenizerBuffer::parse_code_string(txt); if (!file.empty()) { - if (EditorImportExport::get_singleton()->script_get_action()==EditorImportExport::SCRIPT_ACTION_ENCRYPT) { + if (EditorImportExport::get_singleton()->script_get_action() == EditorImportExport::SCRIPT_ACTION_ENCRYPT) { - String tmp_path=EditorSettings::get_singleton()->get_settings_path().plus_file("tmp/script.gde"); - FileAccess *fa = FileAccess::open(tmp_path,FileAccess::WRITE); - String skey=EditorImportExport::get_singleton()->script_get_encryption_key().to_lower(); + String tmp_path = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp/script.gde"); + FileAccess *fa = FileAccess::open(tmp_path, FileAccess::WRITE); + String skey = EditorImportExport::get_singleton()->script_get_encryption_key().to_lower(); Vector<uint8_t> key; key.resize(32); - for(int i=0;i<32;i++) { - int v=0; - if (i*2<skey.length()) { - CharType ct = skey[i*2]; - if (ct>='0' && ct<='9') - ct=ct-'0'; - else if (ct>='a' && ct<='f') - ct=10+ct-'a'; - v|=ct<<4; + for (int i = 0; i < 32; i++) { + int v = 0; + if (i * 2 < skey.length()) { + CharType ct = skey[i * 2]; + if (ct >= '0' && ct <= '9') + ct = ct - '0'; + else if (ct >= 'a' && ct <= 'f') + ct = 10 + ct - 'a'; + v |= ct << 4; } - if (i*2+1<skey.length()) { - CharType ct = skey[i*2+1]; - if (ct>='0' && ct<='9') - ct=ct-'0'; - else if (ct>='a' && ct<='f') - ct=10+ct-'a'; - v|=ct; + if (i * 2 + 1 < skey.length()) { + CharType ct = skey[i * 2 + 1]; + if (ct >= '0' && ct <= '9') + ct = ct - '0'; + else if (ct >= 'a' && ct <= 'f') + ct = 10 + ct - 'a'; + v |= ct; } - key[i]=v; + key[i] = v; } - FileAccessEncrypted *fae=memnew(FileAccessEncrypted); - Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_WRITE_AES256); - if (err==OK) { + FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_WRITE_AES256); + if (err == OK) { - fae->store_buffer(file.ptr(),file.size()); - p_path=p_path.basename()+".gde"; + fae->store_buffer(file.ptr(), file.size()); + p_path = p_path.basename() + ".gde"; } memdelete(fae); - file=FileAccess::get_file_as_array(tmp_path); + file = FileAccess::get_file_as_array(tmp_path); return file; - } else { - p_path=p_path.basename()+".gdc"; + p_path = p_path.basename() + ".gdc"; return file; } } - } } return Vector<uint8_t>(); } - - EditorExportGDScript(){} - + EditorExportGDScript() {} }; static void register_editor_plugin() { - Ref<EditorExportGDScript> egd = memnew( EditorExportGDScript ); + Ref<EditorExportGDScript> egd = memnew(EditorExportGDScript); EditorImportExport::get_singleton()->add_export_plugin(egd); } - #endif void register_gdscript_types() { @@ -141,30 +133,27 @@ void register_gdscript_types() { ObjectTypeDB::register_type<GDScript>(); ObjectTypeDB::register_virtual_type<GDFunctionState>(); - script_language_gd=memnew( GDScriptLanguage ); + script_language_gd = memnew(GDScriptLanguage); //script_language_gd->init(); ScriptServer::register_language(script_language_gd); - resource_loader_gd=memnew( ResourceFormatLoaderGDScript ); + resource_loader_gd = memnew(ResourceFormatLoaderGDScript); ResourceLoader::add_resource_format_loader(resource_loader_gd); - resource_saver_gd=memnew( ResourceFormatSaverGDScript ); + resource_saver_gd = memnew(ResourceFormatSaverGDScript); ResourceSaver::add_resource_format_saver(resource_saver_gd); #ifdef TOOLS_ENABLED EditorNode::add_init_callback(register_editor_plugin); #endif - } void unregister_gdscript_types() { - ScriptServer::unregister_language(script_language_gd); if (script_language_gd) - memdelete( script_language_gd ); + memdelete(script_language_gd); if (resource_loader_gd) - memdelete( resource_loader_gd ); + memdelete(resource_loader_gd); if (resource_saver_gd) - memdelete( resource_saver_gd ); - + memdelete(resource_saver_gd); } diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 22e79f7fc..7c2452bc0 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -27,40 +27,40 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "grid_map.h" -#include "servers/visual_server.h" -#include "scene/resources/surface_tool.h" -#include "message_queue.h" -#include "scene/3d/light.h" -#include "scene/3d/baked_light_instance.h" #include "io/marshalls.h" -#include "scene/scene_string_names.h" +#include "message_queue.h" #include "os/os.h" +#include "scene/3d/baked_light_instance.h" +#include "scene/3d/light.h" #include "scene/resources/mesh_library.h" +#include "scene/resources/surface_tool.h" +#include "scene/scene_string_names.h" +#include "servers/visual_server.h" -bool GridMap::_set(const StringName& p_name, const Variant& p_value) { +bool GridMap::_set(const StringName &p_name, const Variant &p_value) { - String name=p_name; + String name = p_name; - if (name=="theme/theme") { + if (name == "theme/theme") { set_theme(p_value); - } else if (name=="cell/size") { + } else if (name == "cell/size") { set_cell_size(p_value); - } else if (name=="cell/octant_size") { + } else if (name == "cell/octant_size") { set_octant_size(p_value); - } else if (name=="cell/center_x") { + } else if (name == "cell/center_x") { set_center_x(p_value); - } else if (name=="cell/center_y") { + } else if (name == "cell/center_y") { set_center_y(p_value); - } else if (name=="cell/center_z") { + } else if (name == "cell/center_z") { set_center_z(p_value); - } else if (name=="cell/scale") { + } else if (name == "cell/scale") { set_cell_scale(p_value); - } else if (name=="lighting/bake") { + } else if (name == "lighting/bake") { set_use_baked_light(p_value); - } else if (name=="theme/bake") { + } else if (name == "theme/bake") { set_bake(p_value); -/* } else if (name=="cells") { + /* } else if (name=="cells") { DVector<int> cells = p_value; int amount=cells.size(); DVector<int>::Read r = cells.read(); @@ -77,195 +77,187 @@ bool GridMap::_set(const StringName& p_name, const Variant& p_value) { } _recreate_octant_data();*/ - } else if (name=="data") { + } else if (name == "data") { Dictionary d = p_value; Dictionary baked; if (d.has("baked")) - baked=d["baked"]; + baked = d["baked"]; if (d.has("cells")) { DVector<int> cells = d["cells"]; - int amount=cells.size(); + int amount = cells.size(); DVector<int>::Read r = cells.read(); - ERR_FAIL_COND_V(amount%3,false); // not even + ERR_FAIL_COND_V(amount % 3, false); // not even cell_map.clear(); - for(int i=0;i<amount/3;i++) { + for (int i = 0; i < amount / 3; i++) { IndexKey ik; - ik.key=decode_uint64((const uint8_t*)&r[i*3]); + ik.key = decode_uint64((const uint8_t *)&r[i * 3]); Cell cell; - cell.cell=decode_uint32((const uint8_t*)&r[i*3+2]); - cell_map[ik]=cell; - + cell.cell = decode_uint32((const uint8_t *)&r[i * 3 + 2]); + cell_map[ik] = cell; } } - baked_lock=baked.size()!=0; + baked_lock = baked.size() != 0; _recreate_octant_data(); - baked_lock=false; + baked_lock = false; if (!baked.empty()) { List<Variant> kl; baked.get_key_list(&kl); - for (List<Variant>::Element *E=kl.front();E;E=E->next()) { + for (List<Variant>::Element *E = kl.front(); E; E = E->next()) { Plane ikv = E->get(); - Ref<Mesh> b=baked[ikv]; + Ref<Mesh> b = baked[ikv]; ERR_CONTINUE(!b.is_valid()); OctantKey ok; - ok.x=ikv.normal.x; - ok.y=ikv.normal.y; - ok.z=ikv.normal.z; - ok.area=ikv.d; + ok.x = ikv.normal.x; + ok.y = ikv.normal.y; + ok.z = ikv.normal.z; + ok.area = ikv.d; ERR_CONTINUE(!octant_map.has(ok)); Octant &g = *octant_map[ok]; - g.baked=b; - g.bake_instance=VS::get_singleton()->instance_create(); - VS::get_singleton()->instance_set_base(g.bake_instance,g.baked->get_rid()); - VS::get_singleton()->instance_geometry_set_baked_light(g.bake_instance,baked_light_instance?baked_light_instance->get_baked_light_instance():RID()); + g.baked = b; + g.bake_instance = VS::get_singleton()->instance_create(); + VS::get_singleton()->instance_set_base(g.bake_instance, g.baked->get_rid()); + VS::get_singleton()->instance_geometry_set_baked_light(g.bake_instance, baked_light_instance ? baked_light_instance->get_baked_light_instance() : RID()); } } - } else if (name.begins_with("areas/")) { - int which = name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - if (what=="bounds") { - ERR_FAIL_COND_V(area_map.has(which),false); - create_area(which,p_value); + int which = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + if (what == "bounds") { + ERR_FAIL_COND_V(area_map.has(which), false); + create_area(which, p_value); return true; } - ERR_FAIL_COND_V(!area_map.has(which),false); + ERR_FAIL_COND_V(!area_map.has(which), false); - if (what=="name") - area_set_name(which,p_value); - else if (what=="disable_distance") - area_set_portal_disable_distance(which,p_value); - else if (what=="exterior_portal") - area_set_portal_disable_color(which,p_value); + if (what == "name") + area_set_name(which, p_value); + else if (what == "disable_distance") + area_set_portal_disable_distance(which, p_value); + else if (what == "exterior_portal") + area_set_portal_disable_color(which, p_value); else return false; } else return false; return true; - - } -bool GridMap::_get(const StringName& p_name,Variant &r_ret) const { +bool GridMap::_get(const StringName &p_name, Variant &r_ret) const { - String name=p_name; + String name = p_name; - if (name=="theme/theme") { - r_ret= get_theme(); - } else if (name=="cell/size") { - r_ret= get_cell_size(); - } else if (name=="cell/octant_size") { - r_ret= get_octant_size(); - } else if (name=="cell/center_x") { - r_ret= get_center_x(); - } else if (name=="cell/center_y") { - r_ret= get_center_y(); - } else if (name=="cell/center_z") { - r_ret= get_center_z(); - } else if (name=="cell/scale") { - r_ret= cell_scale; - } else if (name=="lighting/bake") { - r_ret=is_using_baked_light(); - } else if (name=="theme/bake") { - r_ret= bake; - } else if (name=="data") { + if (name == "theme/theme") { + r_ret = get_theme(); + } else if (name == "cell/size") { + r_ret = get_cell_size(); + } else if (name == "cell/octant_size") { + r_ret = get_octant_size(); + } else if (name == "cell/center_x") { + r_ret = get_center_x(); + } else if (name == "cell/center_y") { + r_ret = get_center_y(); + } else if (name == "cell/center_z") { + r_ret = get_center_z(); + } else if (name == "cell/scale") { + r_ret = cell_scale; + } else if (name == "lighting/bake") { + r_ret = is_using_baked_light(); + } else if (name == "theme/bake") { + r_ret = bake; + } else if (name == "data") { Dictionary d; DVector<int> cells; - cells.resize(cell_map.size()*3); + cells.resize(cell_map.size() * 3); { DVector<int>::Write w = cells.write(); - int i=0; - for (Map<IndexKey,Cell>::Element *E=cell_map.front();E;E=E->next(),i++) { + int i = 0; + for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next(), i++) { - encode_uint64(E->key().key,(uint8_t*)&w[i*3]); - encode_uint32(E->get().cell,(uint8_t*)&w[i*3+2]); + encode_uint64(E->key().key, (uint8_t *)&w[i * 3]); + encode_uint32(E->get().cell, (uint8_t *)&w[i * 3 + 2]); } } - d["cells"]=cells; + d["cells"] = cells; Dictionary baked; - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { - Octant &g=*E->get(); + Octant &g = *E->get(); if (g.baked.is_valid()) { - baked[Plane(E->key().x,E->key().y,E->key().z,E->key().area)]=g.baked; + baked[Plane(E->key().x, E->key().y, E->key().z, E->key().area)] = g.baked; } - - } if (baked.size()) { - d["baked"]=baked; + d["baked"] = baked; } - r_ret= d; + r_ret = d; } else if (name.begins_with("areas/")) { - int which = name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - if (what=="bounds") - r_ret= area_get_bounds(which); - else if (what=="name") - r_ret= area_get_name(which); - else if (what=="disable_distance") - r_ret= area_get_portal_disable_distance(which); - else if (what=="exterior_portal") - r_ret= area_is_exterior_portal(which); + int which = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + if (what == "bounds") + r_ret = area_get_bounds(which); + else if (what == "name") + r_ret = area_get_name(which); + else if (what == "disable_distance") + r_ret = area_get_portal_disable_distance(which); + else if (what == "exterior_portal") + r_ret = area_is_exterior_portal(which); else return false; } else return false; return true; - } -void GridMap::_get_property_list( List<PropertyInfo> *p_list) const { +void GridMap::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back( PropertyInfo( Variant::OBJECT, "theme/theme", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary")); - p_list->push_back( PropertyInfo( Variant::BOOL, "theme/bake")); - p_list->push_back( PropertyInfo( Variant::BOOL, "lighting/bake")); - p_list->push_back( PropertyInfo( Variant::REAL, "cell/size",PROPERTY_HINT_RANGE,"0.01,16384,0.01") ); - p_list->push_back( PropertyInfo( Variant::INT, "cell/octant_size",PROPERTY_HINT_RANGE,"1,1024,1") ); - p_list->push_back( PropertyInfo( Variant::BOOL, "cell/center_x") ); - p_list->push_back( PropertyInfo( Variant::BOOL, "cell/center_y") ); - p_list->push_back( PropertyInfo( Variant::BOOL, "cell/center_z") ); - p_list->push_back( PropertyInfo( Variant::REAL, "cell/scale") ); + p_list->push_back(PropertyInfo(Variant::OBJECT, "theme/theme", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary")); + p_list->push_back(PropertyInfo(Variant::BOOL, "theme/bake")); + p_list->push_back(PropertyInfo(Variant::BOOL, "lighting/bake")); + p_list->push_back(PropertyInfo(Variant::REAL, "cell/size", PROPERTY_HINT_RANGE, "0.01,16384,0.01")); + p_list->push_back(PropertyInfo(Variant::INT, "cell/octant_size", PROPERTY_HINT_RANGE, "1,1024,1")); + p_list->push_back(PropertyInfo(Variant::BOOL, "cell/center_x")); + p_list->push_back(PropertyInfo(Variant::BOOL, "cell/center_y")); + p_list->push_back(PropertyInfo(Variant::BOOL, "cell/center_z")); + p_list->push_back(PropertyInfo(Variant::REAL, "cell/scale")); - p_list->push_back( PropertyInfo( Variant::DICTIONARY, "data", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) ); + p_list->push_back(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); - for(const Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { + for (const Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { - String base="areas/"+itos(E->key())+"/"; - p_list->push_back( PropertyInfo( Variant::_AABB, base+"bounds", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) ); - p_list->push_back( PropertyInfo( Variant::STRING, base+"name", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) ); - p_list->push_back( PropertyInfo( Variant::REAL, base+"disable_distance", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) ); - p_list->push_back( PropertyInfo( Variant::COLOR, base+"disable_color", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) ); - p_list->push_back( PropertyInfo( Variant::BOOL, base+"exterior_portal", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) ); + String base = "areas/" + itos(E->key()) + "/"; + p_list->push_back(PropertyInfo(Variant::_AABB, base + "bounds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); + p_list->push_back(PropertyInfo(Variant::STRING, base + "name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); + p_list->push_back(PropertyInfo(Variant::REAL, base + "disable_distance", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); + p_list->push_back(PropertyInfo(Variant::COLOR, base + "disable_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); + p_list->push_back(PropertyInfo(Variant::BOOL, base + "exterior_portal", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); } } - -void GridMap::set_theme(const Ref<MeshLibrary>& p_theme) { +void GridMap::set_theme(const Ref<MeshLibrary> &p_theme) { if (!theme.is_null()) theme->unregister_owner(this); - theme=p_theme; + theme = p_theme; if (!theme.is_null()) theme->register_owner(this); @@ -273,35 +265,34 @@ void GridMap::set_theme(const Ref<MeshLibrary>& p_theme) { _change_notify("theme"); } -Ref<MeshLibrary> GridMap::get_theme() const{ +Ref<MeshLibrary> GridMap::get_theme() const { return theme; } -void GridMap::set_cell_size(float p_size){ +void GridMap::set_cell_size(float p_size) { - cell_size=p_size; + cell_size = p_size; _recreate_octant_data(); - } -float GridMap::get_cell_size() const{ +float GridMap::get_cell_size() const { return cell_size; } -void GridMap::set_octant_size(int p_size){ +void GridMap::set_octant_size(int p_size) { - octant_size=p_size; + octant_size = p_size; _recreate_octant_data(); } -int GridMap::get_octant_size() const{ +int GridMap::get_octant_size() const { return octant_size; } void GridMap::set_center_x(bool p_enable) { - center_x=p_enable; + center_x = p_enable; _recreate_octant_data(); } @@ -311,7 +302,7 @@ bool GridMap::get_center_x() const { void GridMap::set_center_y(bool p_enable) { - center_y=p_enable; + center_y = p_enable; _recreate_octant_data(); } @@ -321,7 +312,7 @@ bool GridMap::get_center_y() const { void GridMap::set_center_z(bool p_enable) { - center_z=p_enable; + center_z = p_enable; _recreate_octant_data(); } @@ -329,67 +320,61 @@ bool GridMap::get_center_z() const { return center_z; } +int GridMap::_find_area(const IndexKey &p_pos) const { -int GridMap::_find_area(const IndexKey& p_pos) const { - - for(const Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { - //this should somehow be faster... - const Area& a=*E->get(); - if ( p_pos.x>=a.from.x && p_pos.x<a.to.x && - p_pos.y>=a.from.y && p_pos.y<a.to.y && - p_pos.z>=a.from.z && p_pos.z<a.to.z ) { + for (const Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { + //this should somehow be faster... + const Area &a = *E->get(); + if (p_pos.x >= a.from.x && p_pos.x < a.to.x && + p_pos.y >= a.from.y && p_pos.y < a.to.y && + p_pos.z >= a.from.z && p_pos.z < a.to.z) { return E->key(); } } return 0; } -void GridMap::set_cell_item(int p_x,int p_y,int p_z, int p_item,int p_rot){ +void GridMap::set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot) { - ERR_FAIL_INDEX(ABS(p_x),1<<20); - ERR_FAIL_INDEX(ABS(p_y),1<<20); - ERR_FAIL_INDEX(ABS(p_z),1<<20); + ERR_FAIL_INDEX(ABS(p_x), 1 << 20); + ERR_FAIL_INDEX(ABS(p_y), 1 << 20); + ERR_FAIL_INDEX(ABS(p_z), 1 << 20); IndexKey key; - key.x=p_x; - key.y=p_y; - key.z=p_z; + key.x = p_x; + key.y = p_y; + key.z = p_z; OctantKey ok; - ok.x=p_x/octant_size; - ok.y=p_y/octant_size; - ok.z=p_z/octant_size; + ok.x = p_x / octant_size; + ok.y = p_y / octant_size; + ok.z = p_z / octant_size; ok.area = _find_area(key); - if (cell_map.has(key)) { - int prev_item=cell_map[key].item; + int prev_item = cell_map[key].item; - OctantKey octantkey=ok; + OctantKey octantkey = ok; ERR_FAIL_COND(!octant_map.has(octantkey)); - Octant& g = *octant_map[octantkey]; + Octant &g = *octant_map[octantkey]; ERR_FAIL_COND(!g.items.has(prev_item)); ERR_FAIL_COND(!g.items[prev_item].cells.has(key)); - g.items[prev_item].cells.erase(key); - if (g.items[prev_item].cells.size()==0) { + if (g.items[prev_item].cells.size() == 0) { VS::get_singleton()->free(g.items[prev_item].multimesh_instance); g.items.erase(prev_item); - } if (g.items.empty() || !baked_lock) { //unbake just in case if (g.baked.is_valid()) { VS::get_singleton()->free(g.bake_instance); - g.bake_instance=RID(); - g.baked=Ref<Mesh>(); + g.bake_instance = RID(); + g.baked = Ref<Mesh>(); } - - } if (g.items.empty()) { @@ -403,148 +388,141 @@ void GridMap::set_cell_item(int p_x,int p_y,int p_z, int p_item,int p_rot){ octant_map.erase(octantkey); } else { - - g.dirty=true; + g.dirty = true; } cell_map.erase(key); _queue_dirty_map(); } - if (p_item<0) + if (p_item < 0) return; - OctantKey octantkey=ok; + OctantKey octantkey = ok; //add later if (!octant_map.has(octantkey)) { - - Octant *g = memnew( Octant ); - g->dirty=true; + Octant *g = memnew(Octant); + g->dirty = true; g->static_body = PhysicsServer::get_singleton()->body_create(PhysicsServer::BODY_MODE_STATIC); - PhysicsServer::get_singleton()->body_attach_object_instance_ID(g->static_body,get_instance_ID()); + PhysicsServer::get_singleton()->body_attach_object_instance_ID(g->static_body, get_instance_ID()); if (is_inside_world()) - PhysicsServer::get_singleton()->body_set_space(g->static_body,get_world()->get_space()); + PhysicsServer::get_singleton()->body_set_space(g->static_body, get_world()->get_space()); - SceneTree *st=SceneTree::get_singleton(); + SceneTree *st = SceneTree::get_singleton(); if (st && st->is_debugging_collisions_hint()) { - g->collision_debug=VisualServer::get_singleton()->mesh_create(); - g->collision_debug_instance=VisualServer::get_singleton()->instance_create(); - VisualServer::get_singleton()->instance_set_base(g->collision_debug_instance,g->collision_debug); + g->collision_debug = VisualServer::get_singleton()->mesh_create(); + g->collision_debug_instance = VisualServer::get_singleton()->instance_create(); + VisualServer::get_singleton()->instance_set_base(g->collision_debug_instance, g->collision_debug); if (is_inside_world()) { - VisualServer::get_singleton()->instance_set_scenario(g->collision_debug_instance,get_world()->get_scenario()); - VisualServer::get_singleton()->instance_set_transform(g->collision_debug_instance,get_global_transform()); + VisualServer::get_singleton()->instance_set_scenario(g->collision_debug_instance, get_world()->get_scenario()); + VisualServer::get_singleton()->instance_set_transform(g->collision_debug_instance, get_global_transform()); } - } - octant_map[octantkey]=g; + octant_map[octantkey] = g; } - Octant& g = *octant_map[octantkey]; + Octant &g = *octant_map[octantkey]; if (!g.items.has(p_item)) { Octant::ItemInstances ii; if (theme.is_valid() && theme->has_item(p_item)) { - ii.mesh=theme->get_item_mesh(p_item); - ii.shape=theme->get_item_shape(p_item); - ii.navmesh=theme->get_item_navmesh(p_item); + ii.mesh = theme->get_item_mesh(p_item); + ii.shape = theme->get_item_shape(p_item); + ii.navmesh = theme->get_item_navmesh(p_item); } - ii.multimesh = Ref<MultiMesh>( memnew( MultiMesh ) ); + ii.multimesh = Ref<MultiMesh>(memnew(MultiMesh)); ii.multimesh->set_mesh(ii.mesh); ii.multimesh_instance = VS::get_singleton()->instance_create(); - VS::get_singleton()->instance_set_base(ii.multimesh_instance,ii.multimesh->get_rid()); - VS::get_singleton()->instance_geometry_set_baked_light(ii.multimesh_instance,baked_light_instance?baked_light_instance->get_baked_light_instance():RID()); + VS::get_singleton()->instance_set_base(ii.multimesh_instance, ii.multimesh->get_rid()); + VS::get_singleton()->instance_geometry_set_baked_light(ii.multimesh_instance, baked_light_instance ? baked_light_instance->get_baked_light_instance() : RID()); if (!baked_lock) { //unbake just in case if (g.bake_instance.is_valid()) VS::get_singleton()->free(g.bake_instance); - g.baked=Ref<Mesh>(); + g.baked = Ref<Mesh>(); if (is_inside_world()) { - VS::get_singleton()->instance_set_scenario(ii.multimesh_instance,get_world()->get_scenario()); + VS::get_singleton()->instance_set_scenario(ii.multimesh_instance, get_world()->get_scenario()); if (ok.area) { - VS::get_singleton()->instance_set_room( ii.multimesh_instance,area_map[ok.area]->instance); + VS::get_singleton()->instance_set_room(ii.multimesh_instance, area_map[ok.area]->instance); } } } - g.items[p_item]=ii; + g.items[p_item] = ii; } Octant::ItemInstances &ii = g.items[p_item]; ii.cells.insert(key); - g.dirty=true; + g.dirty = true; _queue_dirty_map(); - cell_map[key]=Cell(); - Cell &c=cell_map[key]; - c.item=p_item; - c.rot=p_rot; - + cell_map[key] = Cell(); + Cell &c = cell_map[key]; + c.item = p_item; + c.rot = p_rot; } -int GridMap::get_cell_item(int p_x,int p_y,int p_z) const{ - - ERR_FAIL_INDEX_V(ABS(p_x),1<<20,INVALID_CELL_ITEM); - ERR_FAIL_INDEX_V(ABS(p_y),1<<20,INVALID_CELL_ITEM); - ERR_FAIL_INDEX_V(ABS(p_z),1<<20,INVALID_CELL_ITEM); +int GridMap::get_cell_item(int p_x, int p_y, int p_z) const { + ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, INVALID_CELL_ITEM); + ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, INVALID_CELL_ITEM); + ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, INVALID_CELL_ITEM); IndexKey key; - key.x=p_x; - key.y=p_y; - key.z=p_z; + key.x = p_x; + key.y = p_y; + key.z = p_z; if (!cell_map.has(key)) return INVALID_CELL_ITEM; return cell_map[key].item; - } -int GridMap::get_cell_item_orientation(int p_x,int p_y,int p_z) const{ +int GridMap::get_cell_item_orientation(int p_x, int p_y, int p_z) const { - ERR_FAIL_INDEX_V(ABS(p_x),1<<20,-1); - ERR_FAIL_INDEX_V(ABS(p_y),1<<20,-1); - ERR_FAIL_INDEX_V(ABS(p_z),1<<20,-1); + ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, -1); + ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, -1); + ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, -1); IndexKey key; - key.x=p_x; - key.y=p_y; - key.z=p_z; + key.x = p_x; + key.y = p_y; + key.z = p_z; if (!cell_map.has(key)) return -1; return cell_map[key].rot; - } -void GridMap::_octant_enter_tree(const OctantKey &p_key){ +void GridMap::_octant_enter_tree(const OctantKey &p_key) { ERR_FAIL_COND(!octant_map.has(p_key)); - if(navigation){ - Octant&g = *octant_map[p_key]; + if (navigation) { + Octant &g = *octant_map[p_key]; - Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z)); + Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z)); _octant_clear_navmesh(p_key); - for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) { - Octant::ItemInstances &ii=E->get(); + for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) { + Octant::ItemInstances &ii = E->get(); - for(Set<IndexKey>::Element *F=ii.cells.front();F;F=F->next()) { + for (Set<IndexKey>::Element *F = ii.cells.front(); F; F = F->next()) { - IndexKey ik=F->get(); - Map<IndexKey,Cell>::Element *C=cell_map.find(ik); + IndexKey ik = F->get(); + Map<IndexKey, Cell>::Element *C = cell_map.find(ik); ERR_CONTINUE(!C); - Vector3 cellpos = Vector3(ik.x,ik.y,ik.z ); + Vector3 cellpos = Vector3(ik.x, ik.y, ik.z); Transform xform; - if (clip && ( (clip_above && cellpos[clip_axis]>clip_floor) || (!clip_above && cellpos[clip_axis]<clip_floor))) { + if (clip && ((clip_above && cellpos[clip_axis] > clip_floor) || (!clip_above && cellpos[clip_axis] < clip_floor))) { xform.basis.set_zero(); @@ -553,16 +531,15 @@ void GridMap::_octant_enter_tree(const OctantKey &p_key){ xform.basis.set_orthogonal_index(C->get().rot); } - - xform.set_origin( cellpos*cell_size+ofs); - xform.basis.scale(Vector3(cell_scale,cell_scale,cell_scale)); + xform.set_origin(cellpos * cell_size + ofs); + xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); // add the item's navmesh at given xform to GridMap's Navigation ancestor - if(ii.navmesh.is_valid()){ - int nm_id = navigation->navmesh_create(ii.navmesh,xform,this); + if (ii.navmesh.is_valid()) { + int nm_id = navigation->navmesh_create(ii.navmesh, xform, this); Octant::NavMesh nm; - nm.id=nm_id; - nm.xform=xform; - g.navmesh_ids[ik]=nm; + nm.id = nm_id; + nm.xform = xform; + g.navmesh_ids[ik] = nm; } } } @@ -572,17 +549,16 @@ void GridMap::_octant_enter_tree(const OctantKey &p_key){ void GridMap::_octant_enter_world(const OctantKey &p_key) { ERR_FAIL_COND(!octant_map.has(p_key)); - Octant&g = *octant_map[p_key]; - PhysicsServer::get_singleton()->body_set_state(g.static_body,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform()); - PhysicsServer::get_singleton()->body_set_space(g.static_body,get_world()->get_space()); + Octant &g = *octant_map[p_key]; + PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); + PhysicsServer::get_singleton()->body_set_space(g.static_body, get_world()->get_space()); //print_line("BODYPOS: "+get_global_transform()); - if (g.collision_debug_instance.is_valid()) { - VS::get_singleton()->instance_set_scenario(g.collision_debug_instance,get_world()->get_scenario()); - VS::get_singleton()->instance_set_transform(g.collision_debug_instance,get_global_transform()); + VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform()); if (area_map.has(p_key.area)) { - VS::get_singleton()->instance_set_room(g.collision_debug_instance,area_map[p_key.area]->instance); + VS::get_singleton()->instance_set_room(g.collision_debug_instance, area_map[p_key.area]->instance); } } if (g.baked.is_valid()) { @@ -590,58 +566,55 @@ void GridMap::_octant_enter_world(const OctantKey &p_key) { Transform xf = get_global_transform(); xf.translate(_octant_get_offset(p_key)); - VS::get_singleton()->instance_set_transform(g.bake_instance,xf); - VS::get_singleton()->instance_set_scenario(g.bake_instance,get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(g.bake_instance, xf); + VS::get_singleton()->instance_set_scenario(g.bake_instance, get_world()->get_scenario()); if (area_map.has(p_key.area)) { - VS::get_singleton()->instance_set_room(g.bake_instance,area_map[p_key.area]->instance); - + VS::get_singleton()->instance_set_room(g.bake_instance, area_map[p_key.area]->instance); } } else { - for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) { + for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) { - VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance,get_world()->get_scenario()); - VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform()); + VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(E->get().multimesh_instance, get_global_transform()); //print_line("INSTANCEPOS: "+get_global_transform()); if (area_map.has(p_key.area)) { - VS::get_singleton()->instance_set_room(E->get().multimesh_instance,area_map[p_key.area]->instance); + VS::get_singleton()->instance_set_room(E->get().multimesh_instance, area_map[p_key.area]->instance); } } } } - void GridMap::_octant_transform(const OctantKey &p_key) { ERR_FAIL_COND(!octant_map.has(p_key)); - Octant&g = *octant_map[p_key]; - PhysicsServer::get_singleton()->body_set_state(g.static_body,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform()); + Octant &g = *octant_map[p_key]; + PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); if (g.collision_debug_instance.is_valid()) { - VS::get_singleton()->instance_set_transform(g.collision_debug_instance,get_global_transform()); + VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform()); } if (g.baked.is_valid()) { Transform xf = get_global_transform(); - xf.origin+=_octant_get_offset(p_key); - VS::get_singleton()->instance_set_transform(g.bake_instance,xf); + xf.origin += _octant_get_offset(p_key); + VS::get_singleton()->instance_set_transform(g.bake_instance, xf); } else { - for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) { + for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) { - VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform()); + VS::get_singleton()->instance_set_transform(E->get().multimesh_instance, get_global_transform()); //print_line("UPDATEPOS: "+get_global_transform()); } } - } -void GridMap::_octant_clear_navmesh(const OctantKey &p_key){ - Octant&g = *octant_map[p_key]; +void GridMap::_octant_clear_navmesh(const OctantKey &p_key) { + Octant &g = *octant_map[p_key]; if (navigation) { - for(Map<IndexKey,Octant::NavMesh>::Element *E=g.navmesh_ids.front();E;E=E->next()) { + for (Map<IndexKey, Octant::NavMesh>::Element *E = g.navmesh_ids.front(); E; E = E->next()) { Octant::NavMesh *nvm = &E->get(); - if(nvm && nvm->id){ + if (nvm && nvm->id) { navigation->navmesh_remove(E->get().id); } } @@ -651,7 +624,7 @@ void GridMap::_octant_clear_navmesh(const OctantKey &p_key){ void GridMap::_octant_update(const OctantKey &p_key) { ERR_FAIL_COND(!octant_map.has(p_key)); - Octant&g = *octant_map[p_key]; + Octant &g = *octant_map[p_key]; if (!g.dirty) return; @@ -672,31 +645,30 @@ void GridMap::_octant_update(const OctantKey &p_key) { * set item's multimesh's instance count to number of cells which have this item * and set said multimesh bounding box to one containing all cells which have this item */ - for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) { + for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) { - Octant::ItemInstances &ii=E->get(); + Octant::ItemInstances &ii = E->get(); ii.multimesh->set_instance_count(ii.cells.size()); AABB aabb; - AABB mesh_aabb = ii.mesh.is_null()?AABB():ii.mesh->get_aabb(); - - Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z)); + AABB mesh_aabb = ii.mesh.is_null() ? AABB() : ii.mesh->get_aabb(); + Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z)); //print_line("OCTANT, CELLS: "+itos(ii.cells.size())); - int idx=0; + int idx = 0; // foreach cell containing this item type - for(Set<IndexKey>::Element *F=ii.cells.front();F;F=F->next()) { - IndexKey ik=F->get(); - Map<IndexKey,Cell>::Element *C=cell_map.find(ik); + for (Set<IndexKey>::Element *F = ii.cells.front(); F; F = F->next()) { + IndexKey ik = F->get(); + Map<IndexKey, Cell>::Element *C = cell_map.find(ik); ERR_CONTINUE(!C); - Vector3 cellpos = Vector3(ik.x,ik.y,ik.z ); + Vector3 cellpos = Vector3(ik.x, ik.y, ik.z); Transform xform; - if (clip && ( (clip_above && cellpos[clip_axis]>clip_floor) || (!clip_above && cellpos[clip_axis]<clip_floor))) { + if (clip && ((clip_above && cellpos[clip_axis] > clip_floor) || (!clip_above && cellpos[clip_axis] < clip_floor))) { xform.basis.set_zero(); @@ -705,19 +677,17 @@ void GridMap::_octant_update(const OctantKey &p_key) { xform.basis.set_orthogonal_index(C->get().rot); } + xform.set_origin(cellpos * cell_size + ofs); + xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); - xform.set_origin( cellpos*cell_size+ofs); - xform.basis.scale(Vector3(cell_scale,cell_scale,cell_scale)); - - ii.multimesh->set_instance_transform(idx,xform); + ii.multimesh->set_instance_transform(idx, xform); //ii.multimesh->set_instance_transform(idx,Transform() ); - ii.multimesh->set_instance_color(idx,Color(1,1,1,1)); + ii.multimesh->set_instance_color(idx, Color(1, 1, 1, 1)); //print_line("MMINST: "+xform); + if (idx == 0) { - if(idx==0) { - - aabb=xform.xform(mesh_aabb); + aabb = xform.xform(mesh_aabb); } else { aabb.merge_with(xform.xform(mesh_aabb)); @@ -726,22 +696,22 @@ void GridMap::_octant_update(const OctantKey &p_key) { // add the item's shape at given xform to octant's static_body if (ii.shape.is_valid()) { // add the item's shape - PhysicsServer::get_singleton()->body_add_shape(g.static_body,ii.shape->get_rid(),xform); + PhysicsServer::get_singleton()->body_add_shape(g.static_body, ii.shape->get_rid(), xform); if (g.collision_debug.is_valid()) { - ii.shape->add_vertices_to_array(col_debug,xform); + ii.shape->add_vertices_to_array(col_debug, xform); } - // print_line("PHIS x: "+xform); + // print_line("PHIS x: "+xform); } // add the item's navmesh at given xform to GridMap's Navigation ancestor - if(navigation){ - if(ii.navmesh.is_valid()){ - int nm_id = navigation->navmesh_create(ii.navmesh,xform,this); + if (navigation) { + if (ii.navmesh.is_valid()) { + int nm_id = navigation->navmesh_create(ii.navmesh, xform, this); Octant::NavMesh nm; - nm.id=nm_id; - nm.xform=xform; - g.navmesh_ids[ik]=nm; + nm.id = nm_id; + nm.xform = xform; + g.navmesh_ids[ik] = nm; } } @@ -749,130 +719,119 @@ void GridMap::_octant_update(const OctantKey &p_key) { } ii.multimesh->set_aabb(aabb); - - } if (col_debug.size()) { - Array arr; arr.resize(VS::ARRAY_MAX); - arr[VS::ARRAY_VERTEX]=col_debug; + arr[VS::ARRAY_VERTEX] = col_debug; - VS::get_singleton()->mesh_add_surface(g.collision_debug,VS::PRIMITIVE_LINES,arr); - SceneTree *st=SceneTree::get_singleton(); + VS::get_singleton()->mesh_add_surface(g.collision_debug, VS::PRIMITIVE_LINES, arr); + SceneTree *st = SceneTree::get_singleton(); if (st) { - VS::get_singleton()->mesh_surface_set_material( g.collision_debug, 0,st->get_debug_collision_material()->get_rid() ); + VS::get_singleton()->mesh_surface_set_material(g.collision_debug, 0, st->get_debug_collision_material()->get_rid()); } } - g.dirty=false; - + g.dirty = false; } - void GridMap::_octant_exit_world(const OctantKey &p_key) { ERR_FAIL_COND(!octant_map.has(p_key)); - Octant&g = *octant_map[p_key]; - PhysicsServer::get_singleton()->body_set_state(g.static_body,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform()); - PhysicsServer::get_singleton()->body_set_space(g.static_body,RID()); - + Octant &g = *octant_map[p_key]; + PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); + PhysicsServer::get_singleton()->body_set_space(g.static_body, RID()); if (g.baked.is_valid()) { - VS::get_singleton()->instance_set_room(g.bake_instance,RID()); - VS::get_singleton()->instance_set_scenario(g.bake_instance,RID()); - + VS::get_singleton()->instance_set_room(g.bake_instance, RID()); + VS::get_singleton()->instance_set_scenario(g.bake_instance, RID()); } if (g.collision_debug_instance.is_valid()) { - VS::get_singleton()->instance_set_room(g.collision_debug_instance,RID()); - VS::get_singleton()->instance_set_scenario(g.collision_debug_instance,RID()); + VS::get_singleton()->instance_set_room(g.collision_debug_instance, RID()); + VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, RID()); } - for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) { + for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) { - VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance,RID()); - // VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform()); - VS::get_singleton()->instance_set_room(E->get().multimesh_instance,RID()); + VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance, RID()); + // VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform()); + VS::get_singleton()->instance_set_room(E->get().multimesh_instance, RID()); } - } void GridMap::_octant_clear_baked(const OctantKey &p_key) { - ERR_FAIL_COND(!octant_map.has(p_key)); - Octant&g = *octant_map[p_key]; + Octant &g = *octant_map[p_key]; if (!g.baked.is_valid()) return; VS::get_singleton()->free(g.bake_instance); - g.bake_instance=RID(); - g.baked=Ref<Mesh>(); + g.bake_instance = RID(); + g.baked = Ref<Mesh>(); if (is_inside_tree()) _octant_enter_world(p_key); - g.dirty=true; + g.dirty = true; _queue_dirty_map(); } -void GridMap::_octant_bake(const OctantKey &p_key, const Ref<TriangleMesh>& p_tmesh,const Vector<BakeLight> &p_lights,List<Vector3> *p_prebake) { - +void GridMap::_octant_bake(const OctantKey &p_key, const Ref<TriangleMesh> &p_tmesh, const Vector<BakeLight> &p_lights, List<Vector3> *p_prebake) { ERR_FAIL_COND(!octant_map.has(p_key)); - Octant&g = *octant_map[p_key]; + Octant &g = *octant_map[p_key]; - Ref<TriangleMesh> tm=p_tmesh; + Ref<TriangleMesh> tm = p_tmesh; if (!p_prebake && is_inside_world()) _octant_exit_world(p_key); - Map< Ref<Material>, Ref<SurfaceTool> > surfaces; - Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z)); - Vector3 octant_ofs=_octant_get_offset(p_key); + Map<Ref<Material>, Ref<SurfaceTool> > surfaces; + Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z)); + Vector3 octant_ofs = _octant_get_offset(p_key); - for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) { + for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) { - Octant::ItemInstances &ii=E->get(); + Octant::ItemInstances &ii = E->get(); if (ii.mesh.is_null()) continue; - for(Set<IndexKey>::Element *F=ii.cells.front();F;F=F->next()) { + for (Set<IndexKey>::Element *F = ii.cells.front(); F; F = F->next()) { - IndexKey ik=F->get(); - Map<IndexKey,Cell>::Element *C=cell_map.find(ik); + IndexKey ik = F->get(); + Map<IndexKey, Cell>::Element *C = cell_map.find(ik); ERR_CONTINUE(!C); - Vector3 cellpos = Vector3(ik.x,ik.y,ik.z ); + Vector3 cellpos = Vector3(ik.x, ik.y, ik.z); Transform xform; xform.basis.set_orthogonal_index(C->get().rot); - xform.set_origin( cellpos*cell_size+ofs); + xform.set_origin(cellpos * cell_size + ofs); if (!p_prebake) - xform.origin-=octant_ofs; + xform.origin -= octant_ofs; - - for(int i=0;i<ii.mesh->get_surface_count();i++) { + for (int i = 0; i < ii.mesh->get_surface_count(); i++) { if (p_prebake) { - if (ii.mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) + if (ii.mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) continue; Array a = ii.mesh->surface_get_arrays(i); - DVector<Vector3> av=a[VS::ARRAY_VERTEX]; + DVector<Vector3> av = a[VS::ARRAY_VERTEX]; int avs = av.size(); DVector<Vector3>::Read vr = av.read(); - DVector<int> ai=a[VS::ARRAY_INDEX]; - int ais=ai.size(); + DVector<int> ai = a[VS::ARRAY_INDEX]; + int ais = ai.size(); if (ais) { - DVector<int>::Read ir=ai.read(); - for(int j=0;j<ais;j++) { + DVector<int>::Read ir = ai.read(); + for (int j = 0; j < ais; j++) { p_prebake->push_back(xform.xform(vr[ir[j]])); //print_line("V SET: "+xform.xform(vr[ir[j]])); @@ -880,7 +839,7 @@ void GridMap::_octant_bake(const OctantKey &p_key, const Ref<TriangleMesh>& p_tm } else { - for(int j=0;j<avs;j++) { + for (int j = 0; j < avs; j++) { p_prebake->push_back(xform.xform(vr[j])); } @@ -890,79 +849,75 @@ void GridMap::_octant_bake(const OctantKey &p_key, const Ref<TriangleMesh>& p_tm Ref<Material> m = ii.mesh->surface_get_material(i); - Map< Ref<Material>, Ref<SurfaceTool> >::Element *S=surfaces.find(m); + Map<Ref<Material>, Ref<SurfaceTool> >::Element *S = surfaces.find(m); if (!S) { - S=surfaces.insert(m,Ref<SurfaceTool>( memnew( SurfaceTool ))); + S = surfaces.insert(m, Ref<SurfaceTool>(memnew(SurfaceTool))); } Ref<SurfaceTool> st = S->get(); - List<SurfaceTool::Vertex>::Element *V=st->get_vertex_array().back(); - st->append_from(ii.mesh,i,xform); + List<SurfaceTool::Vertex>::Element *V = st->get_vertex_array().back(); + st->append_from(ii.mesh, i, xform); st->set_material(m); - if (tm.is_valid()) { if (V) - V=V->next(); + V = V->next(); else - V=st->get_vertex_array().front(); + V = st->get_vertex_array().front(); int lc = p_lights.size(); - const BakeLight* bl = p_lights.ptr(); - float ofs = cell_size*0.02; + const BakeLight *bl = p_lights.ptr(); + float ofs = cell_size * 0.02; + for (; V; V = V->next()) { - for(;V;V=V->next()) { - - SurfaceTool::Vertex &v=V->get(); + SurfaceTool::Vertex &v = V->get(); Vector3 vertex = v.vertex + octant_ofs; //print_line("V GET: "+vertex); - Vector3 normal = tm->get_area_normal( AABB( Vector3(-ofs,-ofs,-ofs)+vertex,Vector3(ofs,ofs,ofs)*2.0)); - if (normal==Vector3()) { - print_line("couldn't find for vertex: "+vertex); + Vector3 normal = tm->get_area_normal(AABB(Vector3(-ofs, -ofs, -ofs) + vertex, Vector3(ofs, ofs, ofs) * 2.0)); + if (normal == Vector3()) { + print_line("couldn't find for vertex: " + vertex); } - ERR_CONTINUE( normal== Vector3()); + ERR_CONTINUE(normal == Vector3()); - float max_l=1.0; - float max_dist=1.0; + float max_l = 1.0; + float max_dist = 1.0; if (lc) { - for(int j=0;j<lc;j++) { - const BakeLight &l=bl[j]; - switch(l.type) { + for (int j = 0; j < lc; j++) { + const BakeLight &l = bl[j]; + switch (l.type) { case VS::LIGHT_DIRECTIONAL: { - Vector3 ray_from=vertex + normal *ofs; - Vector3 ray_to=l.dir*5000; + Vector3 ray_from = vertex + normal * ofs; + Vector3 ray_to = l.dir * 5000; Vector3 n; Vector3 p; - if (tm->intersect_segment(ray_from,ray_to,p,n)) { + if (tm->intersect_segment(ray_from, ray_to, p, n)) { - float dist = 1.0-l.param[VS::LIGHT_PARAM_SHADOW_DARKENING]; - if (dist<=max_dist) { - max_dist=dist; - max_l=1.0-dist; + float dist = 1.0 - l.param[VS::LIGHT_PARAM_SHADOW_DARKENING]; + if (dist <= max_dist) { + max_dist = dist; + max_l = 1.0 - dist; } } } break; } - } } - v.color=Color(max_l,max_l,max_l,1.0); - + v.color = Color(max_l, max_l, max_l, 1.0); } st->add_to_format(VS::ARRAY_FORMAT_COLOR); if (m.is_valid()) { Ref<FixedMaterial> fm = m; if (fm.is_valid()) - fm->set_fixed_flag(FixedMaterial::FLAG_USE_COLOR_ARRAY,true); + fm->set_fixed_flag(FixedMaterial::FLAG_USE_COLOR_ARRAY, true); } } } @@ -973,43 +928,42 @@ void GridMap::_octant_bake(const OctantKey &p_key, const Ref<TriangleMesh>& p_tm if (p_prebake) return; - g.baked = Ref<Mesh>( memnew( Mesh )); + g.baked = Ref<Mesh>(memnew(Mesh)); - for(Map< Ref<Material>, Ref<SurfaceTool> >::Element *E=surfaces.front();E;E=E->next()) { + for (Map<Ref<Material>, Ref<SurfaceTool> >::Element *E = surfaces.front(); E; E = E->next()) { Ref<SurfaceTool> st = E->get(); st->commit(g.baked); } g.bake_instance = VS::get_singleton()->instance_create(); - VS::get_singleton()->instance_set_base(g.bake_instance,g.baked->get_rid()); + VS::get_singleton()->instance_set_base(g.bake_instance, g.baked->get_rid()); if (is_inside_world()) _octant_enter_world(p_key); - g.dirty=true; + g.dirty = true; _queue_dirty_map(); } void GridMap::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { _update_area_instances(); - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { -// IndexKey ik; -// ik.key = E->key().indexkey; + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { + // IndexKey ik; + // ik.key = E->key().indexkey; _octant_enter_world(E->key()); _octant_update(E->key()); } - awaiting_update=false; + awaiting_update = false; - last_transform=get_global_transform(); + last_transform = get_global_transform(); if (use_baked_light) { @@ -1020,30 +974,29 @@ void GridMap::_notification(int p_what) { case NOTIFICATION_TRANSFORM_CHANGED: { Transform new_xform = get_global_transform(); - if (new_xform==last_transform) + if (new_xform == last_transform) break; //update run - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { _octant_transform(E->key()); } - last_transform=new_xform; + last_transform = new_xform; } break; case NOTIFICATION_EXIT_WORLD: { - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { _octant_exit_world(E->key()); } if (use_baked_light) { if (baked_light_instance) { - baked_light_instance->disconnect(SceneStringNames::get_singleton()->baked_light_changed,this,SceneStringNames::get_singleton()->_baked_light_changed); - baked_light_instance=NULL; + baked_light_instance->disconnect(SceneStringNames::get_singleton()->baked_light_changed, this, SceneStringNames::get_singleton()->_baked_light_changed); + baked_light_instance = NULL; } _baked_light_changed(); - } //_queue_dirty_map(MAP_DIRTY_INSTANCES|MAP_DIRTY_TRANSFORMS); @@ -1053,41 +1006,39 @@ void GridMap::_notification(int p_what) { } break; case NOTIFICATION_ENTER_TREE: { - Spatial *c=this; - while(c) { - navigation=c->cast_to<Navigation>(); + Spatial *c = this; + while (c) { + navigation = c->cast_to<Navigation>(); if (navigation) { break; } - c=c->get_parent()->cast_to<Spatial>(); + c = c->get_parent()->cast_to<Spatial>(); } - if(navigation){ - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + if (navigation) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { if (navigation) { _octant_enter_tree(E->key()); } } } - _queue_dirty_map(); + _queue_dirty_map(); } break; case NOTIFICATION_EXIT_TREE: { - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { if (navigation) { _octant_clear_navmesh(E->key()); } } - navigation=NULL; + navigation = NULL; } break; } } - - void GridMap::_queue_dirty_map() { if (awaiting_update) @@ -1095,29 +1046,28 @@ void GridMap::_queue_dirty_map() { if (is_inside_world()) { - MessageQueue::get_singleton()->push_call(this,"_update_dirty_map_callback"); - awaiting_update=true; + MessageQueue::get_singleton()->push_call(this, "_update_dirty_map_callback"); + awaiting_update = true; } } void GridMap::_recreate_octant_data() { - Map<IndexKey,Cell> cell_copy=cell_map; + Map<IndexKey, Cell> cell_copy = cell_map; _clear_internal(true); - for (Map<IndexKey,Cell>::Element *E=cell_copy.front();E;E=E->next()) { + for (Map<IndexKey, Cell>::Element *E = cell_copy.front(); E; E = E->next()) { - set_cell_item(E->key().x,E->key().y,E->key().z,E->get().item,E->get().rot); + set_cell_item(E->key().x, E->key().y, E->key().z, E->get().item, E->get().rot); } - } void GridMap::_clear_internal(bool p_keep_areas) { - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { if (is_inside_world()) _octant_exit_world(E->key()); - for (Map<int,Octant::ItemInstances>::Element *F=E->get()->items.front();F;F=F->next()) { + for (Map<int, Octant::ItemInstances>::Element *F = E->get()->items.front(); F; F = F->next()) { VS::get_singleton()->free(F->get().multimesh_instance); } @@ -1133,7 +1083,6 @@ void GridMap::_clear_internal(bool p_keep_areas) { PhysicsServer::get_singleton()->free(E->get()->static_body); memdelete(E->get()); - } octant_map.clear(); @@ -1142,265 +1091,241 @@ void GridMap::_clear_internal(bool p_keep_areas) { if (p_keep_areas) return; - for (Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { - + for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { VS::get_singleton()->free(E->get()->base_portal); VS::get_singleton()->free(E->get()->instance); - for(int i=0;i<E->get()->portals.size();i++) { + for (int i = 0; i < E->get()->portals.size(); i++) { VS::get_singleton()->free(E->get()->portals[i].instance); } memdelete(E->get()); } - } void GridMap::clear() { _clear_internal(); - } -void GridMap::resource_changed(const RES& p_res) { +void GridMap::resource_changed(const RES &p_res) { _recreate_octant_data(); } - void GridMap::_update_dirty_map_callback() { if (!awaiting_update) return; - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { _octant_update(E->key()); } - - awaiting_update=false; - + awaiting_update = false; } - void GridMap::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_theme","theme:MeshLibrary"),&GridMap::set_theme); - ObjectTypeDB::bind_method(_MD("get_theme:MeshLibrary"),&GridMap::get_theme); - - ObjectTypeDB::bind_method(_MD("set_bake","enable"),&GridMap::set_bake); - ObjectTypeDB::bind_method(_MD("is_baking_enabled"),&GridMap::is_baking_enabled); + ObjectTypeDB::bind_method(_MD("set_theme", "theme:MeshLibrary"), &GridMap::set_theme); + ObjectTypeDB::bind_method(_MD("get_theme:MeshLibrary"), &GridMap::get_theme); - ObjectTypeDB::bind_method(_MD("set_cell_size","size"),&GridMap::set_cell_size); - ObjectTypeDB::bind_method(_MD("get_cell_size"),&GridMap::get_cell_size); + ObjectTypeDB::bind_method(_MD("set_bake", "enable"), &GridMap::set_bake); + ObjectTypeDB::bind_method(_MD("is_baking_enabled"), &GridMap::is_baking_enabled); - ObjectTypeDB::bind_method(_MD("set_octant_size","size"),&GridMap::set_octant_size); - ObjectTypeDB::bind_method(_MD("get_octant_size"),&GridMap::get_octant_size); + ObjectTypeDB::bind_method(_MD("set_cell_size", "size"), &GridMap::set_cell_size); + ObjectTypeDB::bind_method(_MD("get_cell_size"), &GridMap::get_cell_size); - ObjectTypeDB::bind_method(_MD("set_cell_item","x","y","z","item","orientation"),&GridMap::set_cell_item,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_cell_item","x","y","z"),&GridMap::get_cell_item); - ObjectTypeDB::bind_method(_MD("get_cell_item_orientation","x","y","z"),&GridMap::get_cell_item_orientation); + ObjectTypeDB::bind_method(_MD("set_octant_size", "size"), &GridMap::set_octant_size); + ObjectTypeDB::bind_method(_MD("get_octant_size"), &GridMap::get_octant_size); -// ObjectTypeDB::bind_method(_MD("_recreate_octants"),&GridMap::_recreate_octants); - ObjectTypeDB::bind_method(_MD("_update_dirty_map_callback"),&GridMap::_update_dirty_map_callback); - ObjectTypeDB::bind_method(_MD("resource_changed","resource"),&GridMap::resource_changed); + ObjectTypeDB::bind_method(_MD("set_cell_item", "x", "y", "z", "item", "orientation"), &GridMap::set_cell_item, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_cell_item", "x", "y", "z"), &GridMap::get_cell_item); + ObjectTypeDB::bind_method(_MD("get_cell_item_orientation", "x", "y", "z"), &GridMap::get_cell_item_orientation); - ObjectTypeDB::bind_method(_MD("set_center_x","enable"),&GridMap::set_center_x); - ObjectTypeDB::bind_method(_MD("get_center_x"),&GridMap::get_center_x); - ObjectTypeDB::bind_method(_MD("set_center_y","enable"),&GridMap::set_center_y); - ObjectTypeDB::bind_method(_MD("get_center_y"),&GridMap::get_center_y); - ObjectTypeDB::bind_method(_MD("set_center_z","enable"),&GridMap::set_center_z); - ObjectTypeDB::bind_method(_MD("get_center_z"),&GridMap::get_center_z); + // ObjectTypeDB::bind_method(_MD("_recreate_octants"),&GridMap::_recreate_octants); + ObjectTypeDB::bind_method(_MD("_update_dirty_map_callback"), &GridMap::_update_dirty_map_callback); + ObjectTypeDB::bind_method(_MD("resource_changed", "resource"), &GridMap::resource_changed); - ObjectTypeDB::bind_method(_MD("set_clip","enabled","clipabove","floor","axis"),&GridMap::set_clip,DEFVAL(true),DEFVAL(0),DEFVAL(Vector3::AXIS_X)); + ObjectTypeDB::bind_method(_MD("set_center_x", "enable"), &GridMap::set_center_x); + ObjectTypeDB::bind_method(_MD("get_center_x"), &GridMap::get_center_x); + ObjectTypeDB::bind_method(_MD("set_center_y", "enable"), &GridMap::set_center_y); + ObjectTypeDB::bind_method(_MD("get_center_y"), &GridMap::get_center_y); + ObjectTypeDB::bind_method(_MD("set_center_z", "enable"), &GridMap::set_center_z); + ObjectTypeDB::bind_method(_MD("get_center_z"), &GridMap::get_center_z); - ObjectTypeDB::bind_method(_MD("create_area","id","area"),&GridMap::create_area); - ObjectTypeDB::bind_method(_MD("area_get_bounds","area","bounds"),&GridMap::area_get_bounds); - ObjectTypeDB::bind_method(_MD("area_set_exterior_portal","area","enable"),&GridMap::area_set_exterior_portal); - ObjectTypeDB::bind_method(_MD("area_set_name","area","name"),&GridMap::area_set_name); - ObjectTypeDB::bind_method(_MD("area_get_name","area"),&GridMap::area_get_name); - ObjectTypeDB::bind_method(_MD("area_is_exterior_portal","area"),&GridMap::area_is_exterior_portal); - ObjectTypeDB::bind_method(_MD("area_set_portal_disable_distance","area","distance"),&GridMap::area_set_portal_disable_distance); - ObjectTypeDB::bind_method(_MD("area_get_portal_disable_distance","area"),&GridMap::area_get_portal_disable_distance); - ObjectTypeDB::bind_method(_MD("area_set_portal_disable_color","area","color"),&GridMap::area_set_portal_disable_color); - ObjectTypeDB::bind_method(_MD("area_get_portal_disable_color","area"),&GridMap::area_get_portal_disable_color); - ObjectTypeDB::bind_method(_MD("erase_area","area"),&GridMap::erase_area); - ObjectTypeDB::bind_method(_MD("get_unused_area_id","area"),&GridMap::get_unused_area_id); - ObjectTypeDB::bind_method(_MD("bake_geometry"),&GridMap::bake_geometry); + ObjectTypeDB::bind_method(_MD("set_clip", "enabled", "clipabove", "floor", "axis"), &GridMap::set_clip, DEFVAL(true), DEFVAL(0), DEFVAL(Vector3::AXIS_X)); - ObjectTypeDB::bind_method(_MD("_baked_light_changed"),&GridMap::_baked_light_changed); - ObjectTypeDB::bind_method(_MD("set_use_baked_light","use"),&GridMap::set_use_baked_light); - ObjectTypeDB::bind_method(_MD("is_using_baked_light","use"),&GridMap::is_using_baked_light); + ObjectTypeDB::bind_method(_MD("create_area", "id", "area"), &GridMap::create_area); + ObjectTypeDB::bind_method(_MD("area_get_bounds", "area", "bounds"), &GridMap::area_get_bounds); + ObjectTypeDB::bind_method(_MD("area_set_exterior_portal", "area", "enable"), &GridMap::area_set_exterior_portal); + ObjectTypeDB::bind_method(_MD("area_set_name", "area", "name"), &GridMap::area_set_name); + ObjectTypeDB::bind_method(_MD("area_get_name", "area"), &GridMap::area_get_name); + ObjectTypeDB::bind_method(_MD("area_is_exterior_portal", "area"), &GridMap::area_is_exterior_portal); + ObjectTypeDB::bind_method(_MD("area_set_portal_disable_distance", "area", "distance"), &GridMap::area_set_portal_disable_distance); + ObjectTypeDB::bind_method(_MD("area_get_portal_disable_distance", "area"), &GridMap::area_get_portal_disable_distance); + ObjectTypeDB::bind_method(_MD("area_set_portal_disable_color", "area", "color"), &GridMap::area_set_portal_disable_color); + ObjectTypeDB::bind_method(_MD("area_get_portal_disable_color", "area"), &GridMap::area_get_portal_disable_color); + ObjectTypeDB::bind_method(_MD("erase_area", "area"), &GridMap::erase_area); + ObjectTypeDB::bind_method(_MD("get_unused_area_id", "area"), &GridMap::get_unused_area_id); + ObjectTypeDB::bind_method(_MD("bake_geometry"), &GridMap::bake_geometry); - ObjectTypeDB::bind_method(_MD("_get_baked_light_meshes"),&GridMap::_get_baked_light_meshes); + ObjectTypeDB::bind_method(_MD("_baked_light_changed"), &GridMap::_baked_light_changed); + ObjectTypeDB::bind_method(_MD("set_use_baked_light", "use"), &GridMap::set_use_baked_light); + ObjectTypeDB::bind_method(_MD("is_using_baked_light", "use"), &GridMap::is_using_baked_light); + ObjectTypeDB::bind_method(_MD("_get_baked_light_meshes"), &GridMap::_get_baked_light_meshes); + ObjectTypeDB::set_method_flags("GridMap", "bake_geometry", METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); - ObjectTypeDB::set_method_flags("GridMap","bake_geometry",METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - - ObjectTypeDB::bind_method(_MD("clear"),&GridMap::clear); - - BIND_CONSTANT( INVALID_CELL_ITEM ); + ObjectTypeDB::bind_method(_MD("clear"), &GridMap::clear); + BIND_CONSTANT(INVALID_CELL_ITEM); } void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::Axis p_axis) { if (!p_enabled && !clip) return; - if (clip && p_enabled && clip_floor==p_floor && p_clip_above==clip_above && p_axis==clip_axis) + if (clip && p_enabled && clip_floor == p_floor && p_clip_above == clip_above && p_axis == clip_axis) return; - clip=p_enabled; - clip_floor=p_floor; - clip_axis=p_axis; - clip_above=p_clip_above; + clip = p_enabled; + clip_floor = p_floor; + clip_axis = p_axis; + clip_above = p_clip_above; //make it all update - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { - - Octant *g=E->get(); - g->dirty=true; + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { + Octant *g = E->get(); + g->dirty = true; } - awaiting_update=true; + awaiting_update = true; _update_dirty_map_callback(); } - void GridMap::_update_areas() { //clear the portals - for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { + for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { //this should somehow be faster... - Area& a=*E->get(); + Area &a = *E->get(); a.portals.clear(); if (a.instance.is_valid()) { VisualServer::get_singleton()->free(a.instance); - a.instance=RID(); + a.instance = RID(); } } //test all areas against all areas and create portals - this sucks (slow :( ) - for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { - Area& a=*E->get(); + for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { + Area &a = *E->get(); if (a.exterior_portal) //that's pretty much all it does... yes it is continue; - Vector3 from_a(a.from.x,a.from.y,a.from.z); - Vector3 to_a(a.to.x,a.to.y,a.to.z); + Vector3 from_a(a.from.x, a.from.y, a.from.z); + Vector3 to_a(a.to.x, a.to.y, a.to.z); - for(Map<int,Area*>::Element *F=area_map.front();F;F=F->next()) { + for (Map<int, Area *>::Element *F = area_map.front(); F; F = F->next()) { - Area& b=*F->get(); - Vector3 from_b(b.from.x,b.from.y,b.from.z); - Vector3 to_b(b.to.x,b.to.y,b.to.z); + Area &b = *F->get(); + Vector3 from_b(b.from.x, b.from.y, b.from.z); + Vector3 to_b(b.to.x, b.to.y, b.to.z); // initially test intersection and discards - int axis=-1; - float sign=0; - bool valid=true; - Vector3 axmin,axmax; + int axis = -1; + float sign = 0; + bool valid = true; + Vector3 axmin, axmax; + for (int i = 0; i < 3; i++) { - for(int i=0;i<3;i++) { + if (from_a[i] == to_b[i]) { - if (from_a[i]==to_b[i]) { - - if (axis!=-1) { - valid=false; + if (axis != -1) { + valid = false; break; } - axis=i; - sign=-1; - } else if (from_b[i]==to_a[i]) { + axis = i; + sign = -1; + } else if (from_b[i] == to_a[i]) { - if (axis!=-1) { - valid=false; + if (axis != -1) { + valid = false; break; } - axis=i; - sign=+1; + axis = i; + sign = +1; } - - if (from_a[i] > to_b[i] || to_a[i] < from_b[i] ) { - valid=false; + if (from_a[i] > to_b[i] || to_a[i] < from_b[i]) { + valid = false; break; } else { - axmin[i]= ( from_a[i] > from_b[i] ) ? from_a[i] :from_b[i]; - axmax[i]= ( to_a[i] < to_b[i] ) ? to_a[i] :to_b[i]; - + axmin[i] = (from_a[i] > from_b[i]) ? from_a[i] : from_b[i]; + axmax[i] = (to_a[i] < to_b[i]) ? to_a[i] : to_b[i]; } - - } - if (axis==-1 || !valid) + if (axis == -1 || !valid) continue; Transform xf; + for (int i = 0; i < 3; i++) { - for(int i=0;i<3;i++) { - - - - int ax=(axis+i)%3; + int ax = (axis + i) % 3; Vector3 axis_vec; - float scale = (i==0)?sign:((axmax[ax]-axmin[ax])*cell_size); - axis_vec[ax]=scale; - xf.basis.set_axis((2+i)%3,axis_vec); - xf.origin[i]=axmin[i]*cell_size; - + float scale = (i == 0) ? sign : ((axmax[ax] - axmin[ax]) * cell_size); + axis_vec[ax] = scale; + xf.basis.set_axis((2 + i) % 3, axis_vec); + xf.origin[i] = axmin[i] * cell_size; } - - Area::Portal portal; - portal.xform=xf; + portal.xform = xf; a.portals.push_back(portal); } } _update_area_instances(); - } void GridMap::_update_area_instances() { Transform base_xform; if (_in_tree) - base_xform=get_global_transform(); + base_xform = get_global_transform(); - for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { + for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { //this should somehow be faster... - Area& a=*E->get(); - if (a.instance.is_valid()!=_in_tree) { + Area &a = *E->get(); + if (a.instance.is_valid() != _in_tree) { if (!_in_tree) { - for(int i=0;i<a.portals.size();i++) { + for (int i = 0; i < a.portals.size(); i++) { - Area::Portal&p=a.portals[i]; + Area::Portal &p = a.portals[i]; ERR_CONTINUE(!p.instance.is_valid()); VisualServer::get_singleton()->free(p.instance); - p.instance=RID(); + p.instance = RID(); } VisualServer::get_singleton()->free(a.instance); - a.instance=RID(); + a.instance = RID(); } else { //a.instance = VisualServer::get_singleton()->instance_create2(base_room,get_world()->get_scenario()); - for(int i=0;i<a.portals.size();i++) { + for (int i = 0; i < a.portals.size(); i++) { - Area::Portal&p=a.portals[i]; + Area::Portal &p = a.portals[i]; ERR_CONTINUE(p.instance.is_valid()); - p.instance=VisualServer::get_singleton()->instance_create2(a.base_portal,get_world()->get_scenario()); - VisualServer::get_singleton()->instance_set_room(p.instance,a.instance); + p.instance = VisualServer::get_singleton()->instance_create2(a.base_portal, get_world()->get_scenario()); + VisualServer::get_singleton()->instance_set_room(p.instance, a.instance); } } } @@ -1408,62 +1333,57 @@ void GridMap::_update_area_instances() { if (a.instance.is_valid()) { Transform xform; - Vector3 from_a(a.from.x,a.from.y,a.from.z); - Vector3 to_a(a.to.x,a.to.y,a.to.z); + Vector3 from_a(a.from.x, a.from.y, a.from.z); + Vector3 to_a(a.to.x, a.to.y, a.to.z); - for(int i=0;i<3;i++) { - xform.origin[i]=from_a[i]*cell_size; + for (int i = 0; i < 3; i++) { + xform.origin[i] = from_a[i] * cell_size; Vector3 s; - s[i]=(to_a[i]-from_a[i])*cell_size; - xform.basis.set_axis(i,s); + s[i] = (to_a[i] - from_a[i]) * cell_size; + xform.basis.set_axis(i, s); } + VisualServer::get_singleton()->instance_set_transform(a.instance, base_xform * xform); - VisualServer::get_singleton()->instance_set_transform(a.instance,base_xform * xform); + for (int i = 0; i < a.portals.size(); i++) { - for(int i=0;i<a.portals.size();i++) { - - Area::Portal&p=a.portals[i]; + Area::Portal &p = a.portals[i]; ERR_CONTINUE(!p.instance.is_valid()); - VisualServer::get_singleton()->instance_set_transform(p.instance,base_xform * xform); - + VisualServer::get_singleton()->instance_set_transform(p.instance, base_xform * xform); } - } } - } -Error GridMap::create_area(int p_id,const AABB& p_bounds) { +Error GridMap::create_area(int p_id, const AABB &p_bounds) { - ERR_FAIL_COND_V(area_map.has(p_id),ERR_ALREADY_EXISTS); + ERR_FAIL_COND_V(area_map.has(p_id), ERR_ALREADY_EXISTS); ERR_EXPLAIN("ID 0 is taken as global area, start from 1"); - ERR_FAIL_COND_V(p_id==0,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(p_bounds.has_no_area(),ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_id == 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_bounds.has_no_area(), ERR_INVALID_PARAMETER); // FIRST VALIDATE AREA - IndexKey from,to; - from.x=p_bounds.pos.x; - from.y=p_bounds.pos.y; - from.z=p_bounds.pos.z; - to.x=p_bounds.pos.x+p_bounds.size.x; - to.y=p_bounds.pos.y+p_bounds.size.y; - to.z=p_bounds.pos.z+p_bounds.size.z; - + IndexKey from, to; + from.x = p_bounds.pos.x; + from.y = p_bounds.pos.y; + from.z = p_bounds.pos.z; + to.x = p_bounds.pos.x + p_bounds.size.x; + to.y = p_bounds.pos.y + p_bounds.size.y; + to.z = p_bounds.pos.z + p_bounds.size.z; - for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { + for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { //this should somehow be faster... - Area& a=*E->get(); + Area &a = *E->get(); //does it interset with anything else? - if ( from.x >= a.to.x || - to.x <= a.from.x || - from.y >= a.to.y || - to.y <= a.from.y || - from.z >= a.to.z || - to.z <= a.from.z ) { + if (from.x >= a.to.x || + to.x <= a.from.x || + from.y >= a.to.y || + to.y <= a.from.y || + from.z >= a.to.z || + to.z <= a.from.z) { // all good } else { @@ -1472,62 +1392,60 @@ Error GridMap::create_area(int p_id,const AABB& p_bounds) { } } - - Area *area = memnew( Area ); - area->from=from; - area->to=to; - area->portal_disable_distance=0; - area->exterior_portal=false; - area->name="Area "+itos(p_id); - area_map[p_id]=area; + Area *area = memnew(Area); + area->from = from; + area->to = to; + area->portal_disable_distance = 0; + area->exterior_portal = false; + area->name = "Area " + itos(p_id); + area_map[p_id] = area; _recreate_octant_data(); return OK; } AABB GridMap::area_get_bounds(int p_area) const { - ERR_FAIL_COND_V(!area_map.has(p_area),AABB()); + ERR_FAIL_COND_V(!area_map.has(p_area), AABB()); const Area *a = area_map[p_area]; AABB aabb; - aabb.pos=Vector3(a->from.x,a->from.y,a->from.z); - aabb.size=Vector3(a->to.x,a->to.y,a->to.z)-aabb.pos; + aabb.pos = Vector3(a->from.x, a->from.y, a->from.z); + aabb.size = Vector3(a->to.x, a->to.y, a->to.z) - aabb.pos; return aabb; } -void GridMap::area_set_name(int p_area,const String& p_name) { +void GridMap::area_set_name(int p_area, const String &p_name) { ERR_FAIL_COND(!area_map.has(p_area)); Area *a = area_map[p_area]; - a->name=p_name; + a->name = p_name; } String GridMap::area_get_name(int p_area) const { - ERR_FAIL_COND_V(!area_map.has(p_area),""); + ERR_FAIL_COND_V(!area_map.has(p_area), ""); const Area *a = area_map[p_area]; return a->name; } - -void GridMap::area_set_exterior_portal(int p_area,bool p_enable) { +void GridMap::area_set_exterior_portal(int p_area, bool p_enable) { ERR_FAIL_COND(!area_map.has(p_area)); Area *a = area_map[p_area]; - if (a->exterior_portal==p_enable) + if (a->exterior_portal == p_enable) return; - a->exterior_portal=p_enable; + a->exterior_portal = p_enable; _recreate_octant_data(); } bool GridMap::area_is_exterior_portal(int p_area) const { - ERR_FAIL_COND_V(!area_map.has(p_area),false); + ERR_FAIL_COND_V(!area_map.has(p_area), false); const Area *a = area_map[p_area]; return a->exterior_portal; @@ -1538,13 +1456,12 @@ void GridMap::area_set_portal_disable_distance(int p_area, float p_distance) { ERR_FAIL_COND(!area_map.has(p_area)); Area *a = area_map[p_area]; - a->portal_disable_distance=p_distance; - + a->portal_disable_distance = p_distance; } float GridMap::area_get_portal_disable_distance(int p_area) const { - ERR_FAIL_COND_V(!area_map.has(p_area),0); + ERR_FAIL_COND_V(!area_map.has(p_area), 0); const Area *a = area_map[p_area]; return a->portal_disable_distance; @@ -1555,13 +1472,12 @@ void GridMap::area_set_portal_disable_color(int p_area, Color p_color) { ERR_FAIL_COND(!area_map.has(p_area)); Area *a = area_map[p_area]; - a->portal_disable_color=p_color; - + a->portal_disable_color = p_color; } Color GridMap::area_get_portal_disable_color(int p_area) const { - ERR_FAIL_COND_V(!area_map.has(p_area),Color()); + ERR_FAIL_COND_V(!area_map.has(p_area), Color()); const Area *a = area_map[p_area]; return a->portal_disable_color; @@ -1569,34 +1485,29 @@ Color GridMap::area_get_portal_disable_color(int p_area) const { void GridMap::get_area_list(List<int> *p_areas) const { - for(const Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) { + for (const Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) { p_areas->push_back(E->key()); } - } - GridMap::Area::Portal::~Portal() { if (instance.is_valid()) VisualServer::get_singleton()->free(instance); } - GridMap::Area::Area() { - base_portal=VisualServer::get_singleton()->portal_create(); - Vector< Point2 > points; - points.push_back( Point2( 0, 1 ) ); - points.push_back( Point2( 1, 1 ) ); - points.push_back( Point2( 1, 0 ) ); - points.push_back( Point2( 0, 0 ) ); - VisualServer::get_singleton()->portal_set_shape(base_portal,points); - + base_portal = VisualServer::get_singleton()->portal_create(); + Vector<Point2> points; + points.push_back(Point2(0, 1)); + points.push_back(Point2(1, 1)); + points.push_back(Point2(1, 0)); + points.push_back(Point2(0, 0)); + VisualServer::get_singleton()->portal_set_shape(base_portal, points); } - GridMap::Area::~Area() { if (instance.is_valid()) @@ -1608,7 +1519,7 @@ void GridMap::erase_area(int p_area) { ERR_FAIL_COND(!area_map.has(p_area)); - Area* a=area_map[p_area]; + Area *a = area_map[p_area]; memdelete(a); area_map.erase(p_area); _recreate_octant_data(); @@ -1619,15 +1530,14 @@ int GridMap::get_unused_area_id() const { if (area_map.empty()) return 1; else - return area_map.back()->key()+1; + return area_map.back()->key() + 1; } - void GridMap::set_bake(bool p_bake) { - bake=p_bake; - if (bake==false) { - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + bake = p_bake; + if (bake == false) { + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { _octant_clear_baked(E->key()); } @@ -1641,17 +1551,15 @@ bool GridMap::is_baking_enabled() const { void GridMap::set_cell_scale(float p_scale) { - cell_scale=p_scale; + cell_scale = p_scale; _queue_dirty_map(); } -float GridMap::get_cell_scale() const{ +float GridMap::get_cell_scale() const { return cell_scale; } - - void GridMap::bake_geometry() { //used to compute vertex occlusion @@ -1662,120 +1570,110 @@ void GridMap::bake_geometry() { List<Vector3> vertices; - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { - _octant_bake(E->key(),tmesh,lights,&vertices); - + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { + _octant_bake(E->key(), tmesh, lights, &vertices); } DVector<Vector3> vv; vv.fill_with(vertices); //print_line("TOTAL VERTICES: "+itos(vv.size())); - tmesh = Ref<TriangleMesh>( memnew( TriangleMesh )); + tmesh = Ref<TriangleMesh>(memnew(TriangleMesh)); tmesh->create(vv); - - for(int i=0;i<get_child_count();i++) { + for (int i = 0; i < get_child_count(); i++) { if (get_child(i)->cast_to<Light>()) { Light *l = get_child(i)->cast_to<Light>(); BakeLight bl; - for(int i=0;i<Light::PARAM_MAX;i++) { - bl.param[i]=l->get_parameter(Light::Parameter(i)); + for (int i = 0; i < Light::PARAM_MAX; i++) { + bl.param[i] = l->get_parameter(Light::Parameter(i)); } - Transform t=l->get_global_transform(); - bl.pos=t.origin; - bl.dir=t.basis.get_axis(2); - bl.type=l->get_light_type(); + Transform t = l->get_global_transform(); + bl.pos = t.origin; + bl.dir = t.basis.get_axis(2); + bl.type = l->get_light_type(); lights.push_back(bl); - } } } - int idx=0; - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + int idx = 0; + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { if (E->get()->baked.is_valid()) _octant_clear_baked(E->key()); - _octant_bake(E->key(),tmesh,lights); - print_line("baking "+itos(idx)+"/"+itos(octant_map.size())); + _octant_bake(E->key(), tmesh, lights); + print_line("baking " + itos(idx) + "/" + itos(octant_map.size())); idx++; } - } void GridMap::_baked_light_changed() { -// if (!baked_light_instance) -// VS::get_singleton()->instance_geometry_set_baked_light(get_instance(),RID()); -// else -// VS::get_singleton()->instance_geometry_set_baked_light(get_instance(),baked_light_instance->get_baked_light_instance()); - for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) { + // if (!baked_light_instance) + // VS::get_singleton()->instance_geometry_set_baked_light(get_instance(),RID()); + // else + // VS::get_singleton()->instance_geometry_set_baked_light(get_instance(),baked_light_instance->get_baked_light_instance()); + for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { - for(Map<int,Octant::ItemInstances>::Element *F=E->get()->items.front();F;F=F->next()) { + for (Map<int, Octant::ItemInstances>::Element *F = E->get()->items.front(); F; F = F->next()) { - VS::get_singleton()->instance_geometry_set_baked_light(F->get().multimesh_instance,baked_light_instance?baked_light_instance->get_baked_light_instance():RID()); + VS::get_singleton()->instance_geometry_set_baked_light(F->get().multimesh_instance, baked_light_instance ? baked_light_instance->get_baked_light_instance() : RID()); } - } - } void GridMap::_find_baked_light() { - Node *n=get_parent(); - while(n) { + Node *n = get_parent(); + while (n) { - BakedLightInstance *bl=n->cast_to<BakedLightInstance>(); + BakedLightInstance *bl = n->cast_to<BakedLightInstance>(); if (bl) { - baked_light_instance=bl; - baked_light_instance->connect(SceneStringNames::get_singleton()->baked_light_changed,this,SceneStringNames::get_singleton()->_baked_light_changed); + baked_light_instance = bl; + baked_light_instance->connect(SceneStringNames::get_singleton()->baked_light_changed, this, SceneStringNames::get_singleton()->_baked_light_changed); _baked_light_changed(); return; } - n=n->get_parent(); + n = n->get_parent(); } _baked_light_changed(); } - Array GridMap::_get_baked_light_meshes() { if (theme.is_null()) return Array(); - Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z)); + Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z)); Array meshes; - for (Map<IndexKey,Cell>::Element *E=cell_map.front();E;E=E->next()) { - + for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) { int id = E->get().item; if (!theme->has_item(id)) continue; - Ref<Mesh> mesh=theme->get_item_mesh(id); + Ref<Mesh> mesh = theme->get_item_mesh(id); if (mesh.is_null()) continue; - IndexKey ik=E->key(); + IndexKey ik = E->key(); - Vector3 cellpos = Vector3(ik.x,ik.y,ik.z ); + Vector3 cellpos = Vector3(ik.x, ik.y, ik.z); Transform xform; xform.basis.set_orthogonal_index(E->get().rot); - - xform.set_origin( cellpos*cell_size+ofs); - xform.basis.scale(Vector3(cell_scale,cell_scale,cell_scale)); + xform.set_origin(cellpos * cell_size + ofs); + xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); meshes.push_back(xform); meshes.push_back(mesh); - } return meshes; @@ -1783,62 +1681,57 @@ Array GridMap::_get_baked_light_meshes() { void GridMap::set_use_baked_light(bool p_use) { - if (use_baked_light==p_use) + if (use_baked_light == p_use) return; - use_baked_light=p_use; + use_baked_light = p_use; if (is_inside_world()) { if (!p_use) { if (baked_light_instance) { - baked_light_instance->disconnect(SceneStringNames::get_singleton()->baked_light_changed,this,SceneStringNames::get_singleton()->_baked_light_changed); - baked_light_instance=NULL; + baked_light_instance->disconnect(SceneStringNames::get_singleton()->baked_light_changed, this, SceneStringNames::get_singleton()->_baked_light_changed); + baked_light_instance = NULL; } _baked_light_changed(); } else { _find_baked_light(); } } - } -bool GridMap::is_using_baked_light() const{ +bool GridMap::is_using_baked_light() const { return use_baked_light; } - GridMap::GridMap() { - cell_size=2; - octant_size=4; - awaiting_update=false; - _in_tree=false; - center_x=true; - center_y=true; - center_z=true; + cell_size = 2; + octant_size = 4; + awaiting_update = false; + _in_tree = false; + center_x = true; + center_y = true; + center_z = true; - clip=false; - clip_floor=0; - clip_axis=Vector3::AXIS_Z; - clip_above=true; - baked_lock=false; - bake=false; - cell_scale=1.0; + clip = false; + clip_floor = 0; + clip_axis = Vector3::AXIS_Z; + clip_above = true; + baked_lock = false; + bake = false; + cell_scale = 1.0; - baked_light_instance=NULL; - use_baked_light=false; + baked_light_instance = NULL; + use_baked_light = false; navigation = NULL; } - GridMap::~GridMap() { if (!theme.is_null()) theme->unregister_owner(this); clear(); - } - diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h index 3863c337b..afa827911 100644 --- a/modules/gridmap/grid_map.h +++ b/modules/gridmap/grid_map.h @@ -29,26 +29,23 @@ #ifndef GRID_MAP_H #define GRID_MAP_H - -#include "scene/resources/mesh_library.h" -#include "scene/3d/spatial.h" #include "scene/3d/navigation.h" +#include "scene/3d/spatial.h" +#include "scene/resources/mesh_library.h" #include "scene/resources/multimesh.h" //heh heh, godotsphir!! this shares no code and the design is completely different with previous projects i've done.. //should scale better with hardware that supports instancing - class BakedLightInstance; class GridMap : public Spatial { - - OBJ_TYPE( GridMap, Spatial ); + OBJ_TYPE(GridMap, Spatial); enum { - MAP_DIRTY_TRANSFORMS=1, - MAP_DIRTY_INSTANCES=2, + MAP_DIRTY_TRANSFORMS = 1, + MAP_DIRTY_INSTANCES = 2, }; union IndexKey { @@ -60,12 +57,12 @@ class GridMap : public Spatial { }; uint64_t key; - _FORCE_INLINE_ bool operator<(const IndexKey& p_key) const { + _FORCE_INLINE_ bool operator<(const IndexKey &p_key) const { return key < p_key.key; } - IndexKey() { key=0; } + IndexKey() { key = 0; } }; /** @@ -75,12 +72,16 @@ class GridMap : public Spatial { struct { unsigned int item : 16; - unsigned int rot:5; - unsigned int layer:8; + unsigned int rot : 5; + unsigned int layer : 8; }; uint32_t cell; - Cell() { item=0; rot=0; layer=0; } + Cell() { + item = 0; + rot = 0; + layer = 0; + } }; /** @@ -110,8 +111,8 @@ class GridMap : public Spatial { bool dirty; RID static_body; - Map<int,ItemInstances> items; - Map<IndexKey,NavMesh> navmesh_ids; + Map<int, ItemInstances> items; + Map<IndexKey, NavMesh> navmesh_ids; }; union OctantKey { @@ -125,13 +126,13 @@ class GridMap : public Spatial { uint64_t key; - _FORCE_INLINE_ bool operator<(const OctantKey& p_key) const { + _FORCE_INLINE_ bool operator<(const OctantKey &p_key) const { return key < p_key.key; } //OctantKey(const IndexKey& p_k, int p_item) { indexkey=p_k.key; item=p_item; } - OctantKey() { key=0; } + OctantKey() { key = 0; } }; Transform last_transform; @@ -139,7 +140,7 @@ class GridMap : public Spatial { bool _in_tree; float cell_size; int octant_size; - bool center_x,center_y,center_z; + bool center_x, center_y, center_z; bool bake; float cell_scale; Navigation *navigation; @@ -150,7 +151,6 @@ class GridMap : public Spatial { bool baked_lock; Vector3::Axis clip_axis; - /** * @brief An Area is something like a room: it has doors, and Octants can choose to belong to it. */ @@ -177,11 +177,9 @@ class GridMap : public Spatial { Ref<MeshLibrary> theme; - Map<OctantKey,Octant*> octant_map; - Map<IndexKey,Cell> cell_map; - Map<int,Area*> area_map; - - + Map<OctantKey, Octant *> octant_map; + Map<IndexKey, Cell> cell_map; + Map<int, Area *> area_map; void _recreate_octant_data(); @@ -193,11 +191,11 @@ class GridMap : public Spatial { float param[VS::LIGHT_PARAM_MAX]; }; - _FORCE_INLINE_ int _find_area(const IndexKey& p_pos) const; + _FORCE_INLINE_ int _find_area(const IndexKey &p_pos) const; _FORCE_INLINE_ Vector3 _octant_get_offset(const OctantKey &p_key) const { - return Vector3(p_key.x,p_key.y,p_key.z)*cell_size*octant_size; + return Vector3(p_key.x, p_key.y, p_key.z) * cell_size * octant_size; } void _octant_enter_world(const OctantKey &p_key); @@ -206,46 +204,41 @@ class GridMap : public Spatial { void _octant_update(const OctantKey &p_key); void _octant_transform(const OctantKey &p_key); void _octant_clear_baked(const OctantKey &p_key); - void _octant_clear_navmesh(const GridMap::OctantKey&); - void _octant_bake(const OctantKey &p_key,const Ref<TriangleMesh>& p_tmesh=RES(),const Vector<BakeLight> &p_lights=Vector<BakeLight>(),List<Vector3> *r_prebake=NULL); + void _octant_clear_navmesh(const GridMap::OctantKey &); + void _octant_bake(const OctantKey &p_key, const Ref<TriangleMesh> &p_tmesh = RES(), const Vector<BakeLight> &p_lights = Vector<BakeLight>(), List<Vector3> *r_prebake = NULL); bool awaiting_update; void _queue_dirty_map(); void _update_dirty_map_callback(); - void resource_changed(const RES& p_res); - + void resource_changed(const RES &p_res); void _update_areas(); void _update_area_instances(); - void _clear_internal(bool p_keep_areas=false); + void _clear_internal(bool p_keep_areas = false); BakedLightInstance *baked_light_instance; bool use_baked_light; void _find_baked_light(); void _baked_light_changed(); - Array _get_baked_light_meshes(); 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; + 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; void _notification(int p_what); static void _bind_methods(); - public: - enum { - INVALID_CELL_ITEM=-1 + INVALID_CELL_ITEM = -1 }; - void set_theme(const Ref<MeshLibrary>& p_theme); + void set_theme(const Ref<MeshLibrary> &p_theme); Ref<MeshLibrary> get_theme() const; void set_cell_size(float p_size); @@ -254,7 +247,6 @@ public: void set_octant_size(int p_size); int get_octant_size() const; - void set_center_x(bool p_enable); bool get_center_x() const; void set_center_y(bool p_enable); @@ -262,16 +254,16 @@ public: void set_center_z(bool p_enable); bool get_center_z() const; - void set_cell_item(int p_x,int p_y,int p_z, int p_item,int p_orientation=0); - int get_cell_item(int p_x,int p_y,int p_z) const; - int get_cell_item_orientation(int p_x,int p_y,int p_z) const; + void set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_orientation = 0); + int get_cell_item(int p_x, int p_y, int p_z) const; + int get_cell_item_orientation(int p_x, int p_y, int p_z) const; - void set_clip(bool p_enabled, bool p_clip_above=true, int p_floor=0, Vector3::Axis p_axis=Vector3::AXIS_X); + void set_clip(bool p_enabled, bool p_clip_above = true, int p_floor = 0, Vector3::Axis p_axis = Vector3::AXIS_X); - Error create_area(int p_id,const AABB& p_area); + Error create_area(int p_id, const AABB &p_area); AABB area_get_bounds(int p_area) const; - void area_set_exterior_portal(int p_area,bool p_enable); - void area_set_name(int p_area,const String& p_name); + void area_set_exterior_portal(int p_area, bool p_enable); + void area_set_name(int p_area, const String &p_name); String area_get_name(int p_area) const; bool area_is_exterior_portal(int p_area) const; void area_set_portal_disable_distance(int p_area, float p_distance); diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp index 84861e5d1..cd138ed06 100644 --- a/modules/gridmap/grid_map_editor_plugin.cpp +++ b/modules/gridmap/grid_map_editor_plugin.cpp @@ -27,59 +27,53 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "grid_map_editor_plugin.h" +#include "editor/editor_settings.h" #include "editor/plugins/spatial_editor_plugin.h" #include "scene/3d/camera.h" -#include "editor/editor_settings.h" -#include "os/keyboard.h" #include "geometry.h" +#include "os/keyboard.h" void GridMapEditor::_node_removed(Node *p_node) { - if(p_node==node) { - node=NULL; + if (p_node == node) { + node = NULL; hide(); theme_pallete->hide(); } - } - void GridMapEditor::_configure() { - if(!node) + if (!node) return; update_grid(); - } -void GridMapEditor::_menu_option(int p_option) { - +void GridMapEditor::_menu_option(int p_option) { - switch(p_option) { + switch (p_option) { case MENU_OPTION_CONFIGURE: { - } break; case MENU_OPTION_LOCK_VIEW: { - int index=options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW); - lock_view=!options->get_popup()->is_item_checked(index); + int index = options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW); + lock_view = !options->get_popup()->is_item_checked(index); - options->get_popup()->set_item_checked(index,lock_view); + options->get_popup()->set_item_checked(index, lock_view); } break; case MENU_OPTION_CLIP_DISABLED: case MENU_OPTION_CLIP_ABOVE: case MENU_OPTION_CLIP_BELOW: { - clip_mode=ClipMode(p_option-MENU_OPTION_CLIP_DISABLED); - for(int i=0;i<3;i++) { - - int index=options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED+i); - options->get_popup()->set_item_checked(index,i==clip_mode); + clip_mode = ClipMode(p_option - MENU_OPTION_CLIP_DISABLED); + for (int i = 0; i < 3; i++) { + int index = options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED + i); + options->get_popup()->set_item_checked(index, i == clip_mode); } _update_clip(); @@ -88,102 +82,100 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_Y_AXIS: case MENU_OPTION_Z_AXIS: { - int new_axis = p_option-MENU_OPTION_X_AXIS; - for(int i=0;i<3;i++) { - int idx=options->get_popup()->get_item_index(MENU_OPTION_X_AXIS+i); - options->get_popup()->set_item_checked(idx,i==new_axis); + int new_axis = p_option - MENU_OPTION_X_AXIS; + for (int i = 0; i < 3; i++) { + int idx = options->get_popup()->get_item_index(MENU_OPTION_X_AXIS + i); + options->get_popup()->set_item_checked(idx, i == new_axis); } - edit_axis=Vector3::Axis(new_axis); + edit_axis = Vector3::Axis(new_axis); update_grid(); _update_clip(); } break; case MENU_OPTION_CURSOR_ROTATE_Y: { Matrix3 r; - if (input_action==INPUT_DUPLICATE) { + if (input_action == INPUT_DUPLICATE) { r.set_orthogonal_index(selection.duplicate_rot); - r.rotate(Vector3(0,1,0),Math_PI/2.0); - selection.duplicate_rot=r.get_orthogonal_index(); + r.rotate(Vector3(0, 1, 0), Math_PI / 2.0); + selection.duplicate_rot = r.get_orthogonal_index(); _update_duplicate_indicator(); break; } r.set_orthogonal_index(cursor_rot); - r.rotate(Vector3(0,1,0),Math_PI/2.0); - cursor_rot=r.get_orthogonal_index(); + r.rotate(Vector3(0, 1, 0), Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); _update_cursor_transform(); } break; case MENU_OPTION_CURSOR_ROTATE_X: { Matrix3 r; - if (input_action==INPUT_DUPLICATE) { + if (input_action == INPUT_DUPLICATE) { r.set_orthogonal_index(selection.duplicate_rot); - r.rotate(Vector3(1,0,0),Math_PI/2.0); - selection.duplicate_rot=r.get_orthogonal_index(); + r.rotate(Vector3(1, 0, 0), Math_PI / 2.0); + selection.duplicate_rot = r.get_orthogonal_index(); _update_duplicate_indicator(); break; } r.set_orthogonal_index(cursor_rot); - r.rotate(Vector3(1,0,0),Math_PI/2.0); - cursor_rot=r.get_orthogonal_index(); + r.rotate(Vector3(1, 0, 0), Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); _update_cursor_transform(); } break; case MENU_OPTION_CURSOR_ROTATE_Z: { Matrix3 r; - if (input_action==INPUT_DUPLICATE) { + if (input_action == INPUT_DUPLICATE) { r.set_orthogonal_index(selection.duplicate_rot); - r.rotate(Vector3(0,0,1),Math_PI/2.0); - selection.duplicate_rot=r.get_orthogonal_index(); + r.rotate(Vector3(0, 0, 1), Math_PI / 2.0); + selection.duplicate_rot = r.get_orthogonal_index(); _update_duplicate_indicator(); break; } r.set_orthogonal_index(cursor_rot); - r.rotate(Vector3(0,0,1),Math_PI/2.0); - cursor_rot=r.get_orthogonal_index(); + r.rotate(Vector3(0, 0, 1), Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); _update_cursor_transform(); } break; case MENU_OPTION_CURSOR_BACK_ROTATE_Y: { Matrix3 r; r.set_orthogonal_index(cursor_rot); - r.rotate(Vector3(0,1,0),-Math_PI/2.0); - cursor_rot=r.get_orthogonal_index(); + r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); _update_cursor_transform(); } break; case MENU_OPTION_CURSOR_BACK_ROTATE_X: { Matrix3 r; r.set_orthogonal_index(cursor_rot); - r.rotate(Vector3(1,0,0),-Math_PI/2.0); - cursor_rot=r.get_orthogonal_index(); + r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); _update_cursor_transform(); } break; case MENU_OPTION_CURSOR_BACK_ROTATE_Z: { Matrix3 r; r.set_orthogonal_index(cursor_rot); - r.rotate(Vector3(0,0,1),-Math_PI/2.0); - cursor_rot=r.get_orthogonal_index(); + r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); _update_cursor_transform(); } break; case MENU_OPTION_CURSOR_CLEAR_ROTATION: { - if (input_action==INPUT_DUPLICATE) { + if (input_action == INPUT_DUPLICATE) { - - selection.duplicate_rot=0; + selection.duplicate_rot = 0; _update_duplicate_indicator(); break; } - cursor_rot=0; + cursor_rot = 0; _update_cursor_transform(); } break; - case MENU_OPTION_DUPLICATE_SELECTS: { int idx = options->get_popup()->get_item_index(MENU_OPTION_DUPLICATE_SELECTS); - options->get_popup()->set_item_checked( idx, !options->get_popup()->is_item_checked( idx ) ); + options->get_popup()->set_item_checked(idx, !options->get_popup()->is_item_checked(idx)); } break; case MENU_OPTION_SELECTION_MAKE_AREA: case MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR: { @@ -191,37 +183,34 @@ void GridMapEditor::_menu_option(int p_option) { if (!selection.active) break; int area = node->get_unused_area_id(); - Error err = node->create_area(area,AABB(selection.begin,selection.end-selection.begin+Vector3(1,1,1))); - if (err!=OK) { - - + Error err = node->create_area(area, AABB(selection.begin, selection.end - selection.begin + Vector3(1, 1, 1))); + if (err != OK) { } - if (p_option==MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR) { + if (p_option == MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR) { - node->area_set_exterior_portal(area,true); + node->area_set_exterior_portal(area, true); } _update_areas_display(); update_areas(); - } break; case MENU_OPTION_REMOVE_AREA: { - if (selected_area<1) + if (selected_area < 1) return; node->erase_area(selected_area); _update_areas_display(); update_areas(); } break; case MENU_OPTION_SELECTION_DUPLICATE: - if (!(selection.active && input_action==INPUT_NONE)) + if (!(selection.active && input_action == INPUT_NONE)) return; - if (last_mouseover==Vector3(-1,-1,-1)) //nono mouseovering anythin + if (last_mouseover == Vector3(-1, -1, -1)) //nono mouseovering anythin break; - input_action=INPUT_DUPLICATE; - selection.click=last_mouseover; - selection.current=last_mouseover; - selection.duplicate_rot=0; + input_action = INPUT_DUPLICATE; + selection.click = last_mouseover; + selection.current = last_mouseover; + selection.duplicate_rot = 0; _update_duplicate_indicator(); break; case MENU_OPTION_SELECTION_CLEAR: { @@ -230,28 +219,24 @@ void GridMapEditor::_menu_option(int p_option) { _delete_selection(); - } break; case MENU_OPTION_GRIDMAP_SETTINGS: { settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50)); } break; - } } void GridMapEditor::_update_cursor_transform() { - cursor_transform=Transform(); - cursor_transform.origin=cursor_origin; + cursor_transform = Transform(); + cursor_transform.origin = cursor_origin; cursor_transform.basis.set_orthogonal_index(cursor_rot); cursor_transform = node->get_transform() * cursor_transform; - if (cursor_instance.is_valid()) { - VisualServer::get_singleton()->instance_set_transform(cursor_instance,cursor_transform); - VisualServer::get_singleton()->instance_geometry_set_flag(cursor_instance,VS::INSTANCE_FLAG_VISIBLE,cursor_visible); + VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform); + VisualServer::get_singleton()->instance_geometry_set_flag(cursor_instance, VS::INSTANCE_FLAG_VISIBLE, cursor_visible); } - } void GridMapEditor::_update_selection_transform() { @@ -260,93 +245,87 @@ void GridMapEditor::_update_selection_transform() { Transform xf; xf.basis.set_zero(); - VisualServer::get_singleton()->instance_set_transform(selection_instance,xf); + VisualServer::get_singleton()->instance_set_transform(selection_instance, xf); return; } Transform xf; - xf.scale(Vector3(1,1,1)*(Vector3(1,1,1)+(selection.end-selection.begin))*node->get_cell_size()); - xf.origin=selection.begin*node->get_cell_size(); - - VisualServer::get_singleton()->instance_set_transform(selection_instance,node->get_global_transform() * xf); + xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); + xf.origin = selection.begin * node->get_cell_size(); + VisualServer::get_singleton()->instance_set_transform(selection_instance, node->get_global_transform() * xf); } void GridMapEditor::_validate_selection() { if (!selection.active) return; - selection.begin=selection.click; - selection.end=selection.current; - - if (selection.begin.x>selection.end.x) - SWAP(selection.begin.x,selection.end.x); - if (selection.begin.y>selection.end.y) - SWAP(selection.begin.y,selection.end.y); - if (selection.begin.z>selection.end.z) - SWAP(selection.begin.z,selection.end.z); + selection.begin = selection.click; + selection.end = selection.current; + if (selection.begin.x > selection.end.x) + SWAP(selection.begin.x, selection.end.x); + if (selection.begin.y > selection.end.y) + SWAP(selection.begin.y, selection.end.y); + if (selection.begin.z > selection.end.z) + SWAP(selection.begin.z, selection.end.z); _update_selection_transform(); } -bool GridMapEditor::do_input_action(Camera* p_camera,const Point2& p_point,bool p_click) { +bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click) { if (!spatial_editor) return false; - - if (selected_pallete<0 && input_action!=INPUT_COPY && input_action!=INPUT_SELECT && input_action!=INPUT_DUPLICATE) + if (selected_pallete < 0 && input_action != INPUT_COPY && input_action != INPUT_SELECT && input_action != INPUT_DUPLICATE) return false; Ref<MeshLibrary> theme = node->get_theme(); if (theme.is_null()) return false; - if (input_action!=INPUT_COPY && input_action!=INPUT_SELECT && input_action!=INPUT_DUPLICATE && !theme->has_item(selected_pallete)) + if (input_action != INPUT_COPY && input_action != INPUT_SELECT && input_action != INPUT_DUPLICATE && !theme->has_item(selected_pallete)) return false; Camera *camera = p_camera; Vector3 from = camera->project_ray_origin(p_point); Vector3 normal = camera->project_ray_normal(p_point); Transform local_xform = node->get_global_transform().affine_inverse(); - Vector<Plane> planes=camera->get_frustum(); - from=local_xform.xform(from); - normal=local_xform.basis.xform(normal).normalized(); - + Vector<Plane> planes = camera->get_frustum(); + from = local_xform.xform(from); + normal = local_xform.basis.xform(normal).normalized(); Plane p; - p.normal[edit_axis]=1.0; - p.d=edit_floor[edit_axis]*node->get_cell_size(); + p.normal[edit_axis] = 1.0; + p.d = edit_floor[edit_axis] * node->get_cell_size(); Vector3 inters; if (!p.intersects_segment(from, from + normal * settings_pick_distance->get_val(), &inters)) return false; - //make sure the intersection is inside the frustum planes, to avoid //painting on invisible regions - for(int i=0;i<planes.size();i++) { + for (int i = 0; i < planes.size(); i++) { Plane fp = local_xform.xform(planes[i]); if (fp.is_point_over(inters)) return false; } - int cell[3]; - float cell_size[3]={node->get_cell_size(),node->get_cell_size(),node->get_cell_size()}; + float cell_size[3] = { node->get_cell_size(), node->get_cell_size(), node->get_cell_size() }; - last_mouseover=Vector3(-1,-1,-1); + last_mouseover = Vector3(-1, -1, -1); - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - if (i==edit_axis) - cell[i]=edit_floor[i]; + if (i == edit_axis) + cell[i] = edit_floor[i]; else { - cell[i]=inters[i]/node->get_cell_size(); - if (inters[i]<0) - cell[i]-=1; //compensate negative - grid_ofs[i]=cell[i]*cell_size[i]; + cell[i] = inters[i] / node->get_cell_size(); + if (inters[i] < 0) + cell[i] -= 1; //compensate negative + grid_ofs[i] = cell[i] * cell_size[i]; } /*if (cell[i]<0 || cell[i]>=grid_size[i]) { @@ -357,68 +336,65 @@ bool GridMapEditor::do_input_action(Camera* p_camera,const Point2& p_point,bool }*/ } - last_mouseover=Vector3(cell[0],cell[1],cell[2]); - VS::get_singleton()->instance_set_transform(grid_instance[edit_axis],Transform(Matrix3(),grid_ofs)); - + last_mouseover = Vector3(cell[0], cell[1], cell[2]); + VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], Transform(Matrix3(), grid_ofs)); if (cursor_instance.is_valid()) { - cursor_origin=(Vector3(cell[0],cell[1],cell[2])+Vector3(0.5*node->get_center_x(),0.5*node->get_center_y(),0.5*node->get_center_z()))*node->get_cell_size(); - cursor_visible=true; + cursor_origin = (Vector3(cell[0], cell[1], cell[2]) + Vector3(0.5 * node->get_center_x(), 0.5 * node->get_center_y(), 0.5 * node->get_center_z())) * node->get_cell_size(); + cursor_visible = true; _update_cursor_transform(); - } - if (input_action==INPUT_DUPLICATE) { + if (input_action == INPUT_DUPLICATE) { - selection.current=Vector3(cell[0],cell[1],cell[2]); + selection.current = Vector3(cell[0], cell[1], cell[2]); _update_duplicate_indicator(); - } else if (input_action==INPUT_SELECT) { + } else if (input_action == INPUT_SELECT) { - selection.current=Vector3(cell[0],cell[1],cell[2]); + selection.current = Vector3(cell[0], cell[1], cell[2]); if (p_click) - selection.click=selection.current; - selection.active=true; + selection.click = selection.current; + selection.active = true; _validate_selection(); return true; - } else if (input_action==INPUT_COPY) { + } else if (input_action == INPUT_COPY) { - int item=node->get_cell_item(cell[0],cell[1],cell[2]); - if (item>=0) { - selected_pallete=item; + int item = node->get_cell_item(cell[0], cell[1], cell[2]); + if (item >= 0) { + selected_pallete = item; theme_pallete->set_current(item); update_pallete(); _update_cursor_instance(); } return true; - } if (input_action==INPUT_PAINT) { + } + if (input_action == INPUT_PAINT) { SetItem si; - si.pos=Vector3(cell[0],cell[1],cell[2]); - si.new_value=selected_pallete; - si.new_orientation=cursor_rot; - si.old_value=node->get_cell_item(cell[0],cell[1],cell[2]); - si.old_orientation=node->get_cell_item_orientation(cell[0],cell[1],cell[2]); + si.pos = Vector3(cell[0], cell[1], cell[2]); + si.new_value = selected_pallete; + si.new_orientation = cursor_rot; + si.old_value = node->get_cell_item(cell[0], cell[1], cell[2]); + si.old_orientation = node->get_cell_item_orientation(cell[0], cell[1], cell[2]); set_items.push_back(si); - node->set_cell_item(cell[0],cell[1],cell[2],selected_pallete,cursor_rot); + node->set_cell_item(cell[0], cell[1], cell[2], selected_pallete, cursor_rot); return true; - } else if (input_action==INPUT_ERASE) { + } else if (input_action == INPUT_ERASE) { SetItem si; - si.pos=Vector3(cell[0],cell[1],cell[2]); - si.new_value=-1; - si.new_orientation=0; - si.old_value=node->get_cell_item(cell[0],cell[1],cell[2]); - si.old_orientation=node->get_cell_item_orientation(cell[0],cell[1],cell[2]); + si.pos = Vector3(cell[0], cell[1], cell[2]); + si.new_value = -1; + si.new_orientation = 0; + si.old_value = node->get_cell_item(cell[0], cell[1], cell[2]); + si.old_orientation = node->get_cell_item_orientation(cell[0], cell[1], cell[2]); set_items.push_back(si); - node->set_cell_item(cell[0],cell[1],cell[2],-1); + node->set_cell_item(cell[0], cell[1], cell[2], -1); return true; } - return false; - } void GridMapEditor::_delete_selection() { @@ -427,269 +403,253 @@ void GridMapEditor::_delete_selection() { return; undo_redo->create_action("GridMap Delete Selection"); - for(int i=selection.begin.x;i<=selection.end.x;i++) { + for (int i = selection.begin.x; i <= selection.end.x; i++) { - for(int j=selection.begin.y;j<=selection.end.y;j++) { + for (int j = selection.begin.y; j <= selection.end.y; j++) { - for(int k=selection.begin.z;k<=selection.end.z;k++) { + for (int k = selection.begin.z; k <= selection.end.z; k++) { - undo_redo->add_do_method(node,"set_cell_item",i,j,k,GridMap::INVALID_CELL_ITEM); - undo_redo->add_undo_method(node,"set_cell_item",i,j,k,node->get_cell_item(i,j,k),node->get_cell_item_orientation(i,j,k)); + undo_redo->add_do_method(node, "set_cell_item", i, j, k, GridMap::INVALID_CELL_ITEM); + undo_redo->add_undo_method(node, "set_cell_item", i, j, k, node->get_cell_item(i, j, k), node->get_cell_item_orientation(i, j, k)); } - } } undo_redo->commit_action(); - selection.active=false; + selection.active = false; _validate_selection(); - } void GridMapEditor::_update_duplicate_indicator() { - if (!selection.active || input_action!=INPUT_DUPLICATE) { + if (!selection.active || input_action != INPUT_DUPLICATE) { Transform xf; xf.basis.set_zero(); - VisualServer::get_singleton()->instance_set_transform(duplicate_instance,xf); + VisualServer::get_singleton()->instance_set_transform(duplicate_instance, xf); return; } Transform xf; - xf.scale(Vector3(1,1,1)*(Vector3(1,1,1)+(selection.end-selection.begin))*node->get_cell_size()); - xf.origin=(selection.begin+(selection.current-selection.click))*node->get_cell_size(); + xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); + xf.origin = (selection.begin + (selection.current - selection.click)) * node->get_cell_size(); Matrix3 rot; rot.set_orthogonal_index(selection.duplicate_rot); xf.basis = rot * xf.basis; - VisualServer::get_singleton()->instance_set_transform(duplicate_instance,node->get_global_transform() * xf); - - + VisualServer::get_singleton()->instance_set_transform(duplicate_instance, node->get_global_transform() * xf); } -struct __Item { Vector3 pos; int rot; int item ; }; +struct __Item { + Vector3 pos; + int rot; + int item; +}; void GridMapEditor::_duplicate_paste() { if (!selection.active) return; int idx = options->get_popup()->get_item_index(MENU_OPTION_DUPLICATE_SELECTS); - bool reselect = options->get_popup()->is_item_checked( idx ); - + bool reselect = options->get_popup()->is_item_checked(idx); - - List< __Item > items; + List<__Item> items; Matrix3 rot; rot.set_orthogonal_index(selection.duplicate_rot); - for(int i=selection.begin.x;i<=selection.end.x;i++) { + for (int i = selection.begin.x; i <= selection.end.x; i++) { - for(int j=selection.begin.y;j<=selection.end.y;j++) { + for (int j = selection.begin.y; j <= selection.end.y; j++) { - for(int k=selection.begin.z;k<=selection.end.z;k++) { + for (int k = selection.begin.z; k <= selection.end.z; k++) { - int itm = node->get_cell_item(i,j,k); - if (itm==GridMap::INVALID_CELL_ITEM) + int itm = node->get_cell_item(i, j, k); + if (itm == GridMap::INVALID_CELL_ITEM) continue; - int orientation = node->get_cell_item_orientation(i,j,k); + int orientation = node->get_cell_item_orientation(i, j, k); __Item item; - Vector3 rel=Vector3(i,j,k)-selection.begin; + Vector3 rel = Vector3(i, j, k) - selection.begin; rel = rot.xform(rel); Matrix3 orm; orm.set_orthogonal_index(orientation); orm = rot * orm; - item.pos=selection.begin+rel; - item.item=itm; - item.rot=orm.get_orthogonal_index(); + item.pos = selection.begin + rel; + item.item = itm; + item.rot = orm.get_orthogonal_index(); items.push_back(item); } - } } - Vector3 ofs=selection.current-selection.click; + Vector3 ofs = selection.current - selection.click; if (items.size()) { undo_redo->create_action("GridMap Duplicate Selection"); - for(List< __Item >::Element *E=items.front();E;E=E->next()) { - __Item &it=E->get(); - Vector3 pos = it.pos+ofs; - - undo_redo->add_do_method(node,"set_cell_item",pos.x,pos.y,pos.z,it.item,it.rot); - undo_redo->add_undo_method(node,"set_cell_item",pos.x,pos.y,pos.z,node->get_cell_item(pos.x,pos.y,pos.z),node->get_cell_item_orientation(pos.x,pos.y,pos.z)); + for (List<__Item>::Element *E = items.front(); E; E = E->next()) { + __Item &it = E->get(); + Vector3 pos = it.pos + ofs; + undo_redo->add_do_method(node, "set_cell_item", pos.x, pos.y, pos.z, it.item, it.rot); + undo_redo->add_undo_method(node, "set_cell_item", pos.x, pos.y, pos.z, node->get_cell_item(pos.x, pos.y, pos.z), node->get_cell_item_orientation(pos.x, pos.y, pos.z)); } undo_redo->commit_action(); } - if (reselect) { - selection.begin+=ofs; - selection.end+=ofs; - selection.click=selection.begin; - selection.current=selection.end; + selection.begin += ofs; + selection.end += ofs; + selection.click = selection.begin; + selection.current = selection.end; _validate_selection(); } - } -bool GridMapEditor::forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event) { +bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const InputEvent &p_event) { if (!node) { return false; } - if (edit_mode->get_selected()==0) { // regular click + if (edit_mode->get_selected() == 0) { // regular click switch (p_event.type) { case InputEvent::MOUSE_BUTTON: { - if (p_event.mouse_button.button_index==BUTTON_WHEEL_UP && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) { + if (p_event.mouse_button.button_index == BUTTON_WHEEL_UP && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) { if (p_event.mouse_button.pressed) - floor->set_val( floor->get_val() +1); + floor->set_val(floor->get_val() + 1); return true; //eaten - } else if (p_event.mouse_button.button_index==BUTTON_WHEEL_DOWN && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) { + } else if (p_event.mouse_button.button_index == BUTTON_WHEEL_DOWN && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) { if (p_event.mouse_button.pressed) - floor->set_val( floor->get_val() -1); + floor->set_val(floor->get_val() - 1); return true; } if (p_event.mouse_button.pressed) { - if (p_event.mouse_button.button_index==BUTTON_LEFT) { + if (p_event.mouse_button.button_index == BUTTON_LEFT) { - if (input_action==INPUT_DUPLICATE) { + if (input_action == INPUT_DUPLICATE) { //paste _duplicate_paste(); - input_action=INPUT_NONE; + input_action = INPUT_NONE; _update_duplicate_indicator(); } else if (p_event.mouse_button.mod.shift) { - input_action=INPUT_SELECT; + input_action = INPUT_SELECT; } else if (p_event.mouse_button.mod.command) - input_action=INPUT_COPY; + input_action = INPUT_COPY; else { - input_action=INPUT_PAINT; + input_action = INPUT_PAINT; set_items.clear(); } - } else if (p_event.mouse_button.button_index==BUTTON_RIGHT) - if (input_action==INPUT_DUPLICATE) { + } else if (p_event.mouse_button.button_index == BUTTON_RIGHT) + if (input_action == INPUT_DUPLICATE) { - input_action=INPUT_NONE; + input_action = INPUT_NONE; _update_duplicate_indicator(); } else { - input_action=INPUT_ERASE; + input_action = INPUT_ERASE; set_items.clear(); } else return false; - return do_input_action(p_camera,Point2(p_event.mouse_button.x,p_event.mouse_button.y),true); + return do_input_action(p_camera, Point2(p_event.mouse_button.x, p_event.mouse_button.y), true); } else { - if ( - (p_event.mouse_button.button_index==BUTTON_RIGHT && input_action==INPUT_ERASE) || - (p_event.mouse_button.button_index==BUTTON_LEFT && input_action==INPUT_PAINT) ) { + (p_event.mouse_button.button_index == BUTTON_RIGHT && input_action == INPUT_ERASE) || + (p_event.mouse_button.button_index == BUTTON_LEFT && input_action == INPUT_PAINT)) { if (set_items.size()) { undo_redo->create_action("GridMap Paint"); - for(List<SetItem>::Element *E=set_items.front();E;E=E->next()) { + for (List<SetItem>::Element *E = set_items.front(); E; E = E->next()) { - const SetItem &si=E->get(); - undo_redo->add_do_method(node,"set_cell_item",si.pos.x,si.pos.y,si.pos.z,si.new_value,si.new_orientation); + const SetItem &si = E->get(); + undo_redo->add_do_method(node, "set_cell_item", si.pos.x, si.pos.y, si.pos.z, si.new_value, si.new_orientation); } - for(List<SetItem>::Element *E=set_items.back();E;E=E->prev()) { + for (List<SetItem>::Element *E = set_items.back(); E; E = E->prev()) { - const SetItem &si=E->get(); - undo_redo->add_undo_method(node,"set_cell_item",si.pos.x,si.pos.y,si.pos.z,si.old_value,si.old_orientation); + const SetItem &si = E->get(); + undo_redo->add_undo_method(node, "set_cell_item", si.pos.x, si.pos.y, si.pos.z, si.old_value, si.old_orientation); } - undo_redo->commit_action(); } set_items.clear(); - input_action=INPUT_NONE; + input_action = INPUT_NONE; return true; - } - - - if (p_event.mouse_button.button_index==BUTTON_LEFT && input_action!=INPUT_NONE) { + if (p_event.mouse_button.button_index == BUTTON_LEFT && input_action != INPUT_NONE) { set_items.clear(); - input_action=INPUT_NONE; + input_action = INPUT_NONE; return true; } - if (p_event.mouse_button.button_index==BUTTON_RIGHT && (input_action==INPUT_ERASE || input_action==INPUT_DUPLICATE)) { - input_action=INPUT_NONE; + if (p_event.mouse_button.button_index == BUTTON_RIGHT && (input_action == INPUT_ERASE || input_action == INPUT_DUPLICATE)) { + input_action = INPUT_NONE; return true; } } } break; case InputEvent::MOUSE_MOTION: { - return do_input_action(p_camera,Point2(p_event.mouse_motion.x,p_event.mouse_motion.y),false); + return do_input_action(p_camera, Point2(p_event.mouse_motion.x, p_event.mouse_motion.y), false); } break; } - } else if (edit_mode->get_selected()==1) { + } else if (edit_mode->get_selected() == 1) { //area mode, select an area switch (p_event.type) { case InputEvent::MOUSE_BUTTON: { - if (p_event.mouse_button.button_index==BUTTON_LEFT && p_event.mouse_button.pressed) { + if (p_event.mouse_button.button_index == BUTTON_LEFT && p_event.mouse_button.pressed) { - Point2 point = Point2(p_event.mouse_motion.x,p_event.mouse_motion.y); + Point2 point = Point2(p_event.mouse_motion.x, p_event.mouse_motion.y); Camera *camera = p_camera; Vector3 from = camera->project_ray_origin(point); Vector3 normal = camera->project_ray_normal(point); Transform local_xform = node->get_global_transform().affine_inverse(); - from=local_xform.xform(from); - normal=local_xform.basis.xform(normal).normalized(); + from = local_xform.xform(from); + normal = local_xform.basis.xform(normal).normalized(); List<int> areas; node->get_area_list(&areas); - float min_d=1e10; - int min_area=-1; - + float min_d = 1e10; + int min_area = -1; - for(List<int>::Element *E=areas.front();E;E=E->next()) { + for (List<int>::Element *E = areas.front(); E; E = E->next()) { int area = E->get(); AABB aabb = node->area_get_bounds(area); - aabb.pos*=node->get_cell_size(); - aabb.size*=node->get_cell_size(); + aabb.pos *= node->get_cell_size(); + aabb.size *= node->get_cell_size(); - - Vector3 rclip,rnormal; - if (!aabb.intersects_segment(from,from+normal*10000,&rclip,&rnormal)) + Vector3 rclip, rnormal; + if (!aabb.intersects_segment(from, from + normal * 10000, &rclip, &rnormal)) continue; float d = normal.dot(rclip); - if (d<min_d) { - min_d=d; - min_area=area; + if (d < min_d) { + min_d = d; + min_area = area; } } - selected_area=min_area; + selected_area = min_area; update_areas(); - } } break; } - } - return false; } @@ -697,12 +657,11 @@ struct _CGMEItemSort { String name; int id; - _FORCE_INLINE_ bool operator<(const _CGMEItemSort& r_it) const { return name < r_it.name; } - + _FORCE_INLINE_ bool operator<(const _CGMEItemSort &r_it) const { return name < r_it.name; } }; void GridMapEditor::_set_display_mode(int p_mode) { - if (display_mode==p_mode) { + if (display_mode == p_mode) { return; } @@ -714,32 +673,32 @@ void GridMapEditor::_set_display_mode(int p_mode) { mode_thumbnail->set_pressed(true); } - display_mode=p_mode; + display_mode = p_mode; update_pallete(); } -void GridMapEditor::update_pallete() { +void GridMapEditor::update_pallete() { int selected = theme_pallete->get_current(); theme_pallete->clear(); if (display_mode == DISPLAY_THUMBNAIL) { theme_pallete->set_max_columns(0); theme_pallete->set_icon_mode(ItemList::ICON_MODE_TOP); - } else if (display_mode == DISPLAY_LIST){ + } else if (display_mode == DISPLAY_LIST) { theme_pallete->set_max_columns(1); theme_pallete->set_icon_mode(ItemList::ICON_MODE_LEFT); } - float min_size = EDITOR_DEF("grid_map/preview_size",64); + float min_size = EDITOR_DEF("grid_map/preview_size", 64); theme_pallete->set_fixed_icon_size(Size2(min_size, min_size)); - theme_pallete->set_fixed_column_width(min_size*3/2); + theme_pallete->set_fixed_column_width(min_size * 3 / 2); theme_pallete->set_max_text_lines(2); Ref<MeshLibrary> theme = node->get_theme(); if (theme.is_null()) { - last_theme=NULL; + last_theme = NULL; return; } @@ -747,65 +706,63 @@ void GridMapEditor::update_pallete() { ids = theme->get_item_list(); List<_CGMEItemSort> il; - for(int i=0;i<ids.size();i++) { + for (int i = 0; i < ids.size(); i++) { _CGMEItemSort is; - is.id=ids[i]; - is.name=theme->get_item_name(ids[i]); + is.id = ids[i]; + is.name = theme->get_item_name(ids[i]); il.push_back(is); } il.sort(); int item = 0; - for(List<_CGMEItemSort>::Element *E=il.front();E;E=E->next()) { + for (List<_CGMEItemSort>::Element *E = il.front(); E; E = E->next()) { int id = E->get().id; theme_pallete->add_item(""); - String name=theme->get_item_name(id); + String name = theme->get_item_name(id); Ref<Texture> preview = theme->get_item_preview(id); if (!preview.is_null()) { theme_pallete->set_item_icon(item, preview); theme_pallete->set_item_tooltip(item, name); } - if (name!="") { - theme_pallete->set_item_text(item,name); + if (name != "") { + theme_pallete->set_item_text(item, name); } theme_pallete->set_item_metadata(item, id); item++; } - if (selected!=-1) { + if (selected != -1) { theme_pallete->select(selected); } - last_theme=theme.operator->(); + last_theme = theme.operator->(); } - void GridMapEditor::_area_renamed() { - TreeItem * it = area_list->get_selected(); + TreeItem *it = area_list->get_selected(); int area = it->get_metadata(0); - if (area<1) + if (area < 1) return; - node->area_set_name(area,it->get_text(0)); + node->area_set_name(area, it->get_text(0)); } - void GridMapEditor::_area_selected() { - TreeItem * it = area_list->get_selected(); + TreeItem *it = area_list->get_selected(); int area = it->get_metadata(0); - if (area<1) + if (area < 1) return; - selected_area=area; + selected_area = area; } -void GridMapEditor::update_areas() { +void GridMapEditor::update_areas() { area_list->clear(); @@ -814,248 +771,223 @@ void GridMapEditor::update_areas() { TreeItem *root = area_list->create_item(NULL); area_list->set_hide_root(true); - TreeItem *selected=NULL; + TreeItem *selected = NULL; - - for (List<int>::Element *E=areas.front();E;E=E->next()) { + for (List<int>::Element *E = areas.front(); E; E = E->next()) { int area = E->get(); TreeItem *ti = area_list->create_item(root); - String name=node->area_get_name(area); + String name = node->area_get_name(area); - ti->set_metadata(0,area); - ti->set_text(0,name); - ti->set_editable(0,true); - if (area==selected_area) - selected=ti; + ti->set_metadata(0, area); + ti->set_text(0, name); + ti->set_editable(0, true); + if (area == selected_area) + selected = ti; } - if (selected) selected->select(0); - } void GridMapEditor::edit(GridMap *p_gridmap) { - node=p_gridmap; + node = p_gridmap; VS *vs = VS::get_singleton(); - last_mouseover=Vector3(-1,-1,-1); - input_action=INPUT_NONE; - selection.active=false; + last_mouseover = Vector3(-1, -1, -1); + input_action = INPUT_NONE; + selection.active = false; _update_selection_transform(); _update_duplicate_indicator(); - spatial_editor = editor->get_editor_plugin_screen()->cast_to<SpatialEditorPlugin>(); + spatial_editor = editor->get_editor_plugin_screen()->cast_to<SpatialEditorPlugin>(); if (!node) { set_process(false); - for(int i=0;i<3;i++) { - VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_VISIBLE,false); - + for (int i = 0; i < 3; i++) { + VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i], VS::INSTANCE_FLAG_VISIBLE, false); } - VisualServer::get_singleton()->instance_geometry_set_flag(cursor_instance, VS::INSTANCE_FLAG_VISIBLE,false); + VisualServer::get_singleton()->instance_geometry_set_flag(cursor_instance, VS::INSTANCE_FLAG_VISIBLE, false); _clear_areas(); return; } - update_pallete(); update_areas(); set_process(true); Vector3 edited_floor = p_gridmap->get_meta("_editor_floor_"); - clip_mode=p_gridmap->has_meta("_editor_clip_")?ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()):CLIP_DISABLED; - - - - for(int i=0;i<3;i++) { - if (vs->mesh_get_surface_count(grid[i])>0) - vs->mesh_remove_surface(grid[i],0); - edit_floor[i]=edited_floor[i]; + clip_mode = p_gridmap->has_meta("_editor_clip_") ? ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()) : CLIP_DISABLED; + for (int i = 0; i < 3; i++) { + if (vs->mesh_get_surface_count(grid[i]) > 0) + vs->mesh_remove_surface(grid[i], 0); + edit_floor[i] = edited_floor[i]; } { //update grids indicator_mat = VisualServer::get_singleton()->fixed_material_create(); - VisualServer::get_singleton()->material_set_flag( indicator_mat, VisualServer::MATERIAL_FLAG_UNSHADED, true ); - VisualServer::get_singleton()->material_set_flag( indicator_mat, VisualServer::MATERIAL_FLAG_ONTOP, false ); - - VisualServer::get_singleton()->fixed_material_set_param(indicator_mat,VisualServer::FIXED_MATERIAL_PARAM_DIFFUSE,Color(0.8,0.5,0.1)); - VisualServer::get_singleton()->fixed_material_set_flag( indicator_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true ); - VisualServer::get_singleton()->fixed_material_set_flag( indicator_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY, true ); + VisualServer::get_singleton()->material_set_flag(indicator_mat, VisualServer::MATERIAL_FLAG_UNSHADED, true); + VisualServer::get_singleton()->material_set_flag(indicator_mat, VisualServer::MATERIAL_FLAG_ONTOP, false); + VisualServer::get_singleton()->fixed_material_set_param(indicator_mat, VisualServer::FIXED_MATERIAL_PARAM_DIFFUSE, Color(0.8, 0.5, 0.1)); + VisualServer::get_singleton()->fixed_material_set_flag(indicator_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true); + VisualServer::get_singleton()->fixed_material_set_flag(indicator_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY, true); Vector<Vector3> grid_points[3]; Vector<Color> grid_colors[3]; - float cell_size[3]={p_gridmap->get_cell_size(),p_gridmap->get_cell_size(),p_gridmap->get_cell_size()}; + float cell_size[3] = { p_gridmap->get_cell_size(), p_gridmap->get_cell_size(), p_gridmap->get_cell_size() }; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis; - axis[i]=1; + axis[i] = 1; Vector3 axis_n1; - axis_n1[(i+1)%3]=cell_size[(i+1)%3]; + axis_n1[(i + 1) % 3] = cell_size[(i + 1) % 3]; Vector3 axis_n2; - axis_n2[(i+2)%3]=cell_size[(i+2)%3]; + axis_n2[(i + 2) % 3] = cell_size[(i + 2) % 3]; - for(int j=-GRID_CURSOR_SIZE;j<=GRID_CURSOR_SIZE;j++) { + for (int j = -GRID_CURSOR_SIZE; j <= GRID_CURSOR_SIZE; j++) { - for(int k=-GRID_CURSOR_SIZE;k<=GRID_CURSOR_SIZE;k++) { + for (int k = -GRID_CURSOR_SIZE; k <= GRID_CURSOR_SIZE; k++) { - Vector3 p = axis_n1*j + axis_n2 *k; - float trans = Math::pow(MAX(0,1.0-(Vector2(j,k).length()/GRID_CURSOR_SIZE)),2); + Vector3 p = axis_n1 * j + axis_n2 * k; + float trans = Math::pow(MAX(0, 1.0 - (Vector2(j, k).length() / GRID_CURSOR_SIZE)), 2); - Vector3 pj = axis_n1*(j+1) + axis_n2 *k; - float transj = Math::pow(MAX(0,1.0-(Vector2(j+1,k).length()/GRID_CURSOR_SIZE)),2); + Vector3 pj = axis_n1 * (j + 1) + axis_n2 * k; + float transj = Math::pow(MAX(0, 1.0 - (Vector2(j + 1, k).length() / GRID_CURSOR_SIZE)), 2); - Vector3 pk = axis_n1*j + axis_n2 *(k+1); - float transk = Math::pow(MAX(0,1.0-(Vector2(j,k+1).length()/GRID_CURSOR_SIZE)),2); + Vector3 pk = axis_n1 * j + axis_n2 * (k + 1); + float transk = Math::pow(MAX(0, 1.0 - (Vector2(j, k + 1).length() / GRID_CURSOR_SIZE)), 2); grid_points[i].push_back(p); grid_points[i].push_back(pk); - grid_colors[i].push_back(Color(1,1,1,trans)); - grid_colors[i].push_back(Color(1,1,1,transk)); + grid_colors[i].push_back(Color(1, 1, 1, trans)); + grid_colors[i].push_back(Color(1, 1, 1, transk)); grid_points[i].push_back(p); grid_points[i].push_back(pj); - grid_colors[i].push_back(Color(1,1,1,trans)); - grid_colors[i].push_back(Color(1,1,1,transj)); + grid_colors[i].push_back(Color(1, 1, 1, trans)); + grid_colors[i].push_back(Color(1, 1, 1, transj)); } - } Array d; d.resize(VS::ARRAY_MAX); - d[VS::ARRAY_VERTEX]=grid_points[i]; - d[VS::ARRAY_COLOR]=grid_colors[i]; - VisualServer::get_singleton()->mesh_add_surface(grid[i],VisualServer::PRIMITIVE_LINES,d); - VisualServer::get_singleton()->mesh_surface_set_material(grid[i],0,indicator_mat); - - + d[VS::ARRAY_VERTEX] = grid_points[i]; + d[VS::ARRAY_COLOR] = grid_colors[i]; + VisualServer::get_singleton()->mesh_add_surface(grid[i], VisualServer::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat); } - } update_grid(); _update_clip(); _update_areas_display(); - - } void GridMapEditor::_update_clip() { - - node->set_meta("_editor_clip_",clip_mode); - if (clip_mode==CLIP_DISABLED) + node->set_meta("_editor_clip_", clip_mode); + if (clip_mode == CLIP_DISABLED) node->set_clip(false); else - node->set_clip(true,clip_mode==CLIP_ABOVE,edit_floor[edit_axis],edit_axis); + node->set_clip(true, clip_mode == CLIP_ABOVE, edit_floor[edit_axis], edit_axis); } - void GridMapEditor::update_grid() { - grid_xform.origin.x-=1; //force update in hackish way.. what do i care + grid_xform.origin.x -= 1; //force update in hackish way.. what do i care //VS *vs = VS::get_singleton(); - grid_ofs[edit_axis]=edit_floor[edit_axis]*node->get_cell_size(); + grid_ofs[edit_axis] = edit_floor[edit_axis] * node->get_cell_size(); - edit_grid_xform.origin=grid_ofs; - edit_grid_xform.basis=Matrix3(); - - - for(int i=0;i<3;i++) { - VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_VISIBLE,i==edit_axis); + edit_grid_xform.origin = grid_ofs; + edit_grid_xform.basis = Matrix3(); + for (int i = 0; i < 3; i++) { + VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i], VS::INSTANCE_FLAG_VISIBLE, i == edit_axis); } - updating=true; + updating = true; floor->set_val(edit_floor[edit_axis]); - updating=false; - + updating = false; } - - void GridMapEditor::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { - theme_pallete->connect("item_selected", this,"_item_selected_cbk"); - edit_mode->connect("item_selected", this,"_edit_mode_changed"); - area_list->connect("item_edited", this,"_area_renamed"); - area_list->connect("item_selected", this,"_area_selected"); - for(int i=0;i<3;i++) { + theme_pallete->connect("item_selected", this, "_item_selected_cbk"); + edit_mode->connect("item_selected", this, "_edit_mode_changed"); + area_list->connect("item_edited", this, "_area_renamed"); + area_list->connect("item_selected", this, "_area_selected"); + for (int i = 0; i < 3; i++) { - grid[i]=VS::get_singleton()->mesh_create(); - grid_instance[i]=VS::get_singleton()->instance_create2(grid[i],get_tree()->get_root()->get_world()->get_scenario()); + grid[i] = VS::get_singleton()->mesh_create(); + grid_instance[i] = VS::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world()->get_scenario()); } - selection_instance = VisualServer::get_singleton()->instance_create2(selection_mesh,get_tree()->get_root()->get_world()->get_scenario()); - duplicate_instance = VisualServer::get_singleton()->instance_create2(duplicate_mesh,get_tree()->get_root()->get_world()->get_scenario()); + selection_instance = VisualServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world()->get_scenario()); + duplicate_instance = VisualServer::get_singleton()->instance_create2(duplicate_mesh, get_tree()->get_root()->get_world()->get_scenario()); _update_selection_transform(); _update_duplicate_indicator(); - } else if (p_what==NOTIFICATION_EXIT_TREE) { + } else if (p_what == NOTIFICATION_EXIT_TREE) { - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { VS::get_singleton()->free(grid_instance[i]); VS::get_singleton()->free(grid[i]); - grid_instance[i]=RID(); - grid[i]=RID(); + grid_instance[i] = RID(); + grid[i] = RID(); } VisualServer::get_singleton()->free(selection_instance); VisualServer::get_singleton()->free(duplicate_instance); - selection_instance=RID(); - duplicate_instance=RID(); + selection_instance = RID(); + duplicate_instance = RID(); - } else if (p_what==NOTIFICATION_PROCESS) { + } else if (p_what == NOTIFICATION_PROCESS) { Transform xf = node->get_global_transform(); - if (xf!=grid_xform) { - for(int i=0;i<3;i++) { - + if (xf != grid_xform) { + for (int i = 0; i < 3; i++) { - VS::get_singleton()->instance_set_transform(grid_instance[i],xf * edit_grid_xform); + VS::get_singleton()->instance_set_transform(grid_instance[i], xf * edit_grid_xform); } - grid_xform=xf; + grid_xform = xf; } Ref<MeshLibrary> cgmt = node->get_theme(); - if (cgmt.operator->()!=last_theme) + if (cgmt.operator->() != last_theme) update_pallete(); if (lock_view) { - EditorNode*editor = get_tree()->get_root()->get_child(0)->cast_to<EditorNode>(); + EditorNode *editor = get_tree()->get_root()->get_child(0)->cast_to<EditorNode>(); Plane p; - p.normal[edit_axis]=1.0; - p.d=edit_floor[edit_axis]*node->get_cell_size(); + p.normal[edit_axis] = 1.0; + p.d = edit_floor[edit_axis] * node->get_cell_size(); p = node->get_transform().xform(p); // plane to snap SpatialEditorPlugin *sep = editor->get_editor_plugin_screen()->cast_to<SpatialEditorPlugin>(); if (sep) sep->snap_cursor_to_plane(p); - //editor->get_editor_plugin_screen()->call("snap_cursor_to_plane",p); - + //editor->get_editor_plugin_screen()->call("snap_cursor_to_plane",p); } } - } void GridMapEditor::_update_cursor_instance() { @@ -1065,32 +997,30 @@ void GridMapEditor::_update_cursor_instance() { if (cursor_instance.is_valid()) VisualServer::get_singleton()->free(cursor_instance); - cursor_instance=RID(); + cursor_instance = RID(); - if (selected_pallete>=0) { + if (selected_pallete >= 0) { if (node && !node->get_theme().is_null()) { Ref<Mesh> mesh = node->get_theme()->get_item_mesh(selected_pallete); if (!mesh.is_null() && mesh->get_rid().is_valid()) { - cursor_instance=VisualServer::get_singleton()->instance_create2(mesh->get_rid(),get_tree()->get_root()->get_world()->get_scenario()); - VisualServer::get_singleton()->instance_set_transform(cursor_instance,cursor_transform); + cursor_instance = VisualServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world()->get_scenario()); + VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform); } } } - } void GridMapEditor::_item_selected_cbk(int idx) { - selected_pallete=theme_pallete->get_item_metadata(idx); + selected_pallete = theme_pallete->get_item_metadata(idx); _update_cursor_instance(); - } void GridMapEditor::_clear_areas() { - for(int i=0;i<areas.size();i++) { + for (int i = 0; i < areas.size(); i++) { VisualServer::get_singleton()->free(areas[i].instance); VisualServer::get_singleton()->free(areas[i].mesh); @@ -1110,51 +1040,48 @@ void GridMapEditor::_update_areas_display() { Transform global_xf = node->get_global_transform(); - for(List<int>::Element *E=areas.front();E;E=E->next()) { + for (List<int>::Element *E = areas.front(); E; E = E->next()) { int area = E->get(); Color color; if (node->area_is_exterior_portal(area)) - color=Color(1,1,1,0.2); + color = Color(1, 1, 1, 0.2); else - color.set_hsv(Math::fmod(area*0.37,1),Math::fmod(area*0.75,1),1.0,0.2); + color.set_hsv(Math::fmod(area * 0.37, 1), Math::fmod(area * 0.75, 1), 1.0, 0.2); RID material = VisualServer::get_singleton()->fixed_material_create(); - VisualServer::get_singleton()->fixed_material_set_param( material, VS::FIXED_MATERIAL_PARAM_DIFFUSE,color ); - VisualServer::get_singleton()->fixed_material_set_param( material, VS::FIXED_MATERIAL_PARAM_EMISSION,0.5 ); - VisualServer::get_singleton()->fixed_material_set_flag( material, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true ); - + VisualServer::get_singleton()->fixed_material_set_param(material, VS::FIXED_MATERIAL_PARAM_DIFFUSE, color); + VisualServer::get_singleton()->fixed_material_set_param(material, VS::FIXED_MATERIAL_PARAM_EMISSION, 0.5); + VisualServer::get_singleton()->fixed_material_set_flag(material, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true); RID mesh = VisualServer::get_singleton()->mesh_create(); DVector<Plane> planes; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis; - axis[i]=1.0; - planes.push_back(Plane(axis,1)); - planes.push_back(Plane(-axis,0)); + axis[i] = 1.0; + planes.push_back(Plane(axis, 1)); + planes.push_back(Plane(-axis, 0)); } - VisualServer::get_singleton()->mesh_add_surface_from_planes(mesh,planes); - VisualServer::get_singleton()->mesh_surface_set_material(mesh,0,material,true); + VisualServer::get_singleton()->mesh_add_surface_from_planes(mesh, planes); + VisualServer::get_singleton()->mesh_surface_set_material(mesh, 0, material, true); AreaDisplay ad; - ad.mesh=mesh; - ad.instance = VisualServer::get_singleton()->instance_create2(mesh,node->get_world()->get_scenario()); + ad.mesh = mesh; + ad.instance = VisualServer::get_singleton()->instance_create2(mesh, node->get_world()->get_scenario()); Transform xform; AABB aabb = node->area_get_bounds(area); - xform.origin=aabb.pos * node->get_cell_size(); + xform.origin = aabb.pos * node->get_cell_size(); xform.basis.scale(aabb.size * node->get_cell_size()); - VisualServer::get_singleton()->instance_set_transform(ad.instance,global_xf * xform); + VisualServer::get_singleton()->instance_set_transform(ad.instance, global_xf * xform); this->areas.push_back(ad); - } - } void GridMapEditor::_edit_mode_changed(int p_what) { - if (p_what==0) { + if (p_what == 0) { theme_pallete->show(); area_list->hide(); @@ -1162,89 +1089,82 @@ void GridMapEditor::_edit_mode_changed(int p_what) { theme_pallete->hide(); area_list->show(); - } } void GridMapEditor::_floor_changed(float p_value) { - if (updating) return; - edit_floor[edit_axis]=p_value; - node->set_meta("_editor_floor_",Vector3(edit_floor[0],edit_floor[1],edit_floor[2])); + edit_floor[edit_axis] = p_value; + node->set_meta("_editor_floor_", Vector3(edit_floor[0], edit_floor[1], edit_floor[2])); update_grid(); _update_clip(); - } void GridMapEditor::_bind_methods() { - ObjectTypeDB::bind_method("_menu_option",&GridMapEditor::_menu_option); - ObjectTypeDB::bind_method("_configure",&GridMapEditor::_configure); - ObjectTypeDB::bind_method("_item_selected_cbk",&GridMapEditor::_item_selected_cbk); - ObjectTypeDB::bind_method("_edit_mode_changed",&GridMapEditor::_edit_mode_changed); - ObjectTypeDB::bind_method("_area_renamed",&GridMapEditor::_area_renamed); - ObjectTypeDB::bind_method("_area_selected",&GridMapEditor::_area_selected); - ObjectTypeDB::bind_method("_floor_changed",&GridMapEditor::_floor_changed); + ObjectTypeDB::bind_method("_menu_option", &GridMapEditor::_menu_option); + ObjectTypeDB::bind_method("_configure", &GridMapEditor::_configure); + ObjectTypeDB::bind_method("_item_selected_cbk", &GridMapEditor::_item_selected_cbk); + ObjectTypeDB::bind_method("_edit_mode_changed", &GridMapEditor::_edit_mode_changed); + ObjectTypeDB::bind_method("_area_renamed", &GridMapEditor::_area_renamed); + ObjectTypeDB::bind_method("_area_selected", &GridMapEditor::_area_selected); + ObjectTypeDB::bind_method("_floor_changed", &GridMapEditor::_floor_changed); - ObjectTypeDB::bind_method(_MD("_set_display_mode","mode"), &GridMapEditor::_set_display_mode); + ObjectTypeDB::bind_method(_MD("_set_display_mode", "mode"), &GridMapEditor::_set_display_mode); } - - GridMapEditor::GridMapEditor(EditorNode *p_editor) { + input_action = INPUT_NONE; + editor = p_editor; + undo_redo = p_editor->get_undo_redo(); - input_action=INPUT_NONE; - editor=p_editor; - undo_redo=p_editor->get_undo_redo(); - - int mw = EDITOR_DEF("grid_map/palette_min_width",230); - Control *ec = memnew( Control); - ec->set_custom_minimum_size(Size2(mw,0)); + int mw = EDITOR_DEF("grid_map/palette_min_width", 230); + Control *ec = memnew(Control); + ec->set_custom_minimum_size(Size2(mw, 0)); add_child(ec); - - spatial_editor_hb = memnew( HBoxContainer ); + spatial_editor_hb = memnew(HBoxContainer); SpatialEditor::get_singleton()->add_control_to_menu_panel(spatial_editor_hb); - options = memnew( MenuButton ); + options = memnew(MenuButton); spatial_editor_hb->add_child(options); spatial_editor_hb->hide(); options->set_text("Grid"); - options->get_popup()->add_check_item("Snap View",MENU_OPTION_LOCK_VIEW); + options->get_popup()->add_check_item("Snap View", MENU_OPTION_LOCK_VIEW); options->get_popup()->add_separator(); - options->get_popup()->add_item("Prev Level ("+keycode_get_string(KEY_MASK_CMD)+"Down Wheel)",MENU_OPTION_PREV_LEVEL); - options->get_popup()->add_item("Next Level ("+keycode_get_string(KEY_MASK_CMD)+"Up Wheel)",MENU_OPTION_NEXT_LEVEL); + options->get_popup()->add_item("Prev Level (" + keycode_get_string(KEY_MASK_CMD) + "Down Wheel)", MENU_OPTION_PREV_LEVEL); + options->get_popup()->add_item("Next Level (" + keycode_get_string(KEY_MASK_CMD) + "Up Wheel)", MENU_OPTION_NEXT_LEVEL); options->get_popup()->add_separator(); - options->get_popup()->add_check_item("Clip Disabled",MENU_OPTION_CLIP_DISABLED); - options->get_popup()->set_item_checked( options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true ); - options->get_popup()->add_check_item("Clip Above",MENU_OPTION_CLIP_ABOVE); - options->get_popup()->add_check_item("Clip Below",MENU_OPTION_CLIP_BELOW); + options->get_popup()->add_check_item("Clip Disabled", MENU_OPTION_CLIP_DISABLED); + options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true); + options->get_popup()->add_check_item("Clip Above", MENU_OPTION_CLIP_ABOVE); + options->get_popup()->add_check_item("Clip Below", MENU_OPTION_CLIP_BELOW); options->get_popup()->add_separator(); - options->get_popup()->add_check_item("Edit X Axis",MENU_OPTION_X_AXIS,KEY_Z); - options->get_popup()->add_check_item("Edit Y Axis",MENU_OPTION_Y_AXIS,KEY_X); - options->get_popup()->add_check_item("Edit Z Axis",MENU_OPTION_Z_AXIS,KEY_C); - options->get_popup()->set_item_checked( options->get_popup()->get_item_index(MENU_OPTION_Y_AXIS), true ); + options->get_popup()->add_check_item("Edit X Axis", MENU_OPTION_X_AXIS, KEY_Z); + options->get_popup()->add_check_item("Edit Y Axis", MENU_OPTION_Y_AXIS, KEY_X); + options->get_popup()->add_check_item("Edit Z Axis", MENU_OPTION_Z_AXIS, KEY_C); + options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_Y_AXIS), true); options->get_popup()->add_separator(); - options->get_popup()->add_item("Cursor Rotate X",MENU_OPTION_CURSOR_ROTATE_X,KEY_A); - options->get_popup()->add_item("Cursor Rotate Y",MENU_OPTION_CURSOR_ROTATE_Y,KEY_S); - options->get_popup()->add_item("Cursor Rotate Z",MENU_OPTION_CURSOR_ROTATE_Z,KEY_D); - options->get_popup()->add_item("Cursor Back Rotate X",MENU_OPTION_CURSOR_BACK_ROTATE_X,KEY_MASK_SHIFT+KEY_A); - options->get_popup()->add_item("Cursor Back Rotate Y",MENU_OPTION_CURSOR_BACK_ROTATE_Y,KEY_MASK_SHIFT+KEY_S); - options->get_popup()->add_item("Cursor Back Rotate Z",MENU_OPTION_CURSOR_BACK_ROTATE_Z,KEY_MASK_SHIFT+KEY_D); - options->get_popup()->add_item("Cursor Clear Rotation",MENU_OPTION_CURSOR_CLEAR_ROTATION,KEY_W); + options->get_popup()->add_item("Cursor Rotate X", MENU_OPTION_CURSOR_ROTATE_X, KEY_A); + options->get_popup()->add_item("Cursor Rotate Y", MENU_OPTION_CURSOR_ROTATE_Y, KEY_S); + options->get_popup()->add_item("Cursor Rotate Z", MENU_OPTION_CURSOR_ROTATE_Z, KEY_D); + options->get_popup()->add_item("Cursor Back Rotate X", MENU_OPTION_CURSOR_BACK_ROTATE_X, KEY_MASK_SHIFT + KEY_A); + options->get_popup()->add_item("Cursor Back Rotate Y", MENU_OPTION_CURSOR_BACK_ROTATE_Y, KEY_MASK_SHIFT + KEY_S); + options->get_popup()->add_item("Cursor Back Rotate Z", MENU_OPTION_CURSOR_BACK_ROTATE_Z, KEY_MASK_SHIFT + KEY_D); + options->get_popup()->add_item("Cursor Clear Rotation", MENU_OPTION_CURSOR_CLEAR_ROTATION, KEY_W); options->get_popup()->add_separator(); - options->get_popup()->add_check_item("Duplicate Selects",MENU_OPTION_DUPLICATE_SELECTS); + options->get_popup()->add_check_item("Duplicate Selects", MENU_OPTION_DUPLICATE_SELECTS); options->get_popup()->add_separator(); - options->get_popup()->add_item("Create Area",MENU_OPTION_SELECTION_MAKE_AREA,KEY_CONTROL+KEY_C); - options->get_popup()->add_item("Create Exterior Connector",MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR); - options->get_popup()->add_item("Erase Area",MENU_OPTION_REMOVE_AREA); + options->get_popup()->add_item("Create Area", MENU_OPTION_SELECTION_MAKE_AREA, KEY_CONTROL + KEY_C); + options->get_popup()->add_item("Create Exterior Connector", MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR); + options->get_popup()->add_item("Erase Area", MENU_OPTION_REMOVE_AREA); options->get_popup()->add_separator(); - options->get_popup()->add_item("Selection -> Duplicate",MENU_OPTION_SELECTION_DUPLICATE,KEY_MASK_SHIFT+KEY_INSERT); - options->get_popup()->add_item("Selection -> Clear",MENU_OPTION_SELECTION_CLEAR,KEY_MASK_SHIFT+KEY_DELETE); + options->get_popup()->add_item("Selection -> Duplicate", MENU_OPTION_SELECTION_DUPLICATE, KEY_MASK_SHIFT + KEY_INSERT); + options->get_popup()->add_item("Selection -> Clear", MENU_OPTION_SELECTION_CLEAR, KEY_MASK_SHIFT + KEY_DELETE); //options->get_popup()->add_separator(); //options->get_popup()->add_item("Configure",MENU_OPTION_CONFIGURE); @@ -1266,30 +1186,30 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { settings_pick_distance->set_val(EDITOR_DEF("grid_map/pick_distance", 5000.0)); settings_vbc->add_margin_child("Pick Distance:", settings_pick_distance); - clip_mode=CLIP_DISABLED; - options->get_popup()->connect("item_pressed", this,"_menu_option"); + clip_mode = CLIP_DISABLED; + options->get_popup()->connect("item_pressed", this, "_menu_option"); - HBoxContainer *hb = memnew( HBoxContainer ); + HBoxContainer *hb = memnew(HBoxContainer); add_child(hb); hb->set_h_size_flags(SIZE_EXPAND_FILL); edit_mode = memnew(OptionButton); edit_mode->set_area_as_parent_rect(); - edit_mode->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,24); - edit_mode->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,14); + edit_mode->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_BEGIN, 24); + edit_mode->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 14); edit_mode->add_item("Tiles"); edit_mode->add_item("Areas"); hb->add_child(edit_mode); edit_mode->set_h_size_flags(SIZE_EXPAND_FILL); - mode_thumbnail = memnew( ToolButton ); + mode_thumbnail = memnew(ToolButton); mode_thumbnail->set_toggle_mode(true); mode_thumbnail->set_pressed(true); - mode_thumbnail->set_icon(p_editor->get_gui_base()->get_icon("FileThumbnail","EditorIcons")); + mode_thumbnail->set_icon(p_editor->get_gui_base()->get_icon("FileThumbnail", "EditorIcons")); hb->add_child(mode_thumbnail); mode_thumbnail->connect("pressed", this, "_set_display_mode", varray(DISPLAY_THUMBNAIL)); - mode_list = memnew( ToolButton ); + mode_list = memnew(ToolButton); mode_list->set_toggle_mode(true); mode_list->set_pressed(false); mode_list->set_icon(p_editor->get_gui_base()->get_icon("FileList", "EditorIcons")); @@ -1297,13 +1217,13 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { mode_list->connect("pressed", this, "_set_display_mode", varray(DISPLAY_LIST)); display_mode = DISPLAY_THUMBNAIL; - selected_area=-1; + selected_area = -1; - theme_pallete = memnew( ItemList ); + theme_pallete = memnew(ItemList); add_child(theme_pallete); theme_pallete->set_v_size_flags(SIZE_EXPAND_FILL); - area_list = memnew( Tree ); + area_list = memnew(Tree); add_child(area_list); area_list->set_v_size_flags(SIZE_EXPAND_FILL); area_list->hide(); @@ -1313,26 +1233,25 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { fl->set_text(" Floor: "); spatial_editor_hb->add_child(fl); - floor = memnew( SpinBox ); + floor = memnew(SpinBox); floor->set_min(-32767); floor->set_max(32767); floor->set_step(1); - floor->get_line_edit()->add_constant_override("minimum_spaces",16); + floor->get_line_edit()->add_constant_override("minimum_spaces", 16); spatial_editor_hb->add_child(floor); - floor->connect("value_changed",this,"_floor_changed"); - + floor->connect("value_changed", this, "_floor_changed"); - edit_axis=Vector3::AXIS_Y; - edit_floor[0]=-1; - edit_floor[1]=-1; - edit_floor[2]=-1; + edit_axis = Vector3::AXIS_Y; + edit_floor[0] = -1; + edit_floor[1] = -1; + edit_floor[2] = -1; - cursor_visible=false; - selected_pallete=-1; - lock_view=false; - cursor_rot=0; - last_mouseover=Vector3(-1,-1,-1); + cursor_visible = false; + selected_pallete = -1; + lock_view = false; + cursor_rot = 0; + last_mouseover = Vector3(-1, -1, -1); selection_mesh = VisualServer::get_singleton()->mesh_create(); duplicate_mesh = VisualServer::get_singleton()->mesh_create(); @@ -1340,45 +1259,43 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { { //selection mesh create - DVector<Vector3> lines; DVector<Vector3> triangles; - for (int i=0;i<6;i++) { - + for (int i = 0; i < 6; i++) { Vector3 face_points[4]; - for (int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { float v[3]; - v[0]=1.0; - v[1]=1-2*((j>>1)&1); - v[2]=v[1]*(1-2*(j&1)); + v[0] = 1.0; + v[1] = 1 - 2 * ((j >> 1) & 1); + v[2] = v[1] * (1 - 2 * (j & 1)); - for (int k=0;k<3;k++) { + for (int k = 0; k < 3; k++) { - if (i<3) - face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1); + if (i < 3) + face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1); else - face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1); + face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1); } } - triangles.push_back(face_points[0]*0.5+Vector3(0.5,0.5,0.5)); - triangles.push_back(face_points[1]*0.5+Vector3(0.5,0.5,0.5)); - triangles.push_back(face_points[2]*0.5+Vector3(0.5,0.5,0.5)); + triangles.push_back(face_points[0] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[1] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[2] * 0.5 + Vector3(0.5, 0.5, 0.5)); - triangles.push_back(face_points[2]*0.5+Vector3(0.5,0.5,0.5)); - triangles.push_back(face_points[3]*0.5+Vector3(0.5,0.5,0.5)); - triangles.push_back(face_points[0]*0.5+Vector3(0.5,0.5,0.5)); + triangles.push_back(face_points[2] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[3] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[0] * 0.5 + Vector3(0.5, 0.5, 0.5)); } - for(int i=0;i<12;i++) { + for (int i = 0; i < 12; i++) { - AABB base(Vector3(0,0,0),Vector3(1,1,1)); - Vector3 a,b; - base.get_edge(i,a,b); + AABB base(Vector3(0, 0, 0), Vector3(1, 1, 1)); + Vector3 a, b; + base.get_edge(i, a, b); lines.push_back(a); lines.push_back(b); } @@ -1387,65 +1304,55 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { d.resize(VS::ARRAY_MAX); inner_mat = VisualServer::get_singleton()->fixed_material_create(); - VisualServer::get_singleton()->fixed_material_set_param(inner_mat,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(0.7,0.7,1.0,0.3)); - VisualServer::get_singleton()->material_set_flag(inner_mat,VS::MATERIAL_FLAG_ONTOP,true); - VisualServer::get_singleton()->material_set_flag(inner_mat,VS::MATERIAL_FLAG_UNSHADED,true); - VisualServer::get_singleton()->fixed_material_set_flag( inner_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true ); + VisualServer::get_singleton()->fixed_material_set_param(inner_mat, VS::FIXED_MATERIAL_PARAM_DIFFUSE, Color(0.7, 0.7, 1.0, 0.3)); + VisualServer::get_singleton()->material_set_flag(inner_mat, VS::MATERIAL_FLAG_ONTOP, true); + VisualServer::get_singleton()->material_set_flag(inner_mat, VS::MATERIAL_FLAG_UNSHADED, true); + VisualServer::get_singleton()->fixed_material_set_flag(inner_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true); - - d[VS::ARRAY_VERTEX]=triangles; - VisualServer::get_singleton()->mesh_add_surface(selection_mesh,VS::PRIMITIVE_TRIANGLES,d); - VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh,0,inner_mat); + d[VS::ARRAY_VERTEX] = triangles; + VisualServer::get_singleton()->mesh_add_surface(selection_mesh, VS::PRIMITIVE_TRIANGLES, d); + VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 0, inner_mat); outer_mat = VisualServer::get_singleton()->fixed_material_create(); - VisualServer::get_singleton()->fixed_material_set_param(outer_mat,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(0.7,0.7,1.0,0.8)); - VisualServer::get_singleton()->material_set_line_width(outer_mat,3.0); - VisualServer::get_singleton()->material_set_flag(outer_mat,VS::MATERIAL_FLAG_ONTOP,true); - VisualServer::get_singleton()->material_set_flag(outer_mat,VS::MATERIAL_FLAG_UNSHADED,true); - VisualServer::get_singleton()->fixed_material_set_flag( outer_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true ); - - - d[VS::ARRAY_VERTEX]=lines; - VisualServer::get_singleton()->mesh_add_surface(selection_mesh,VS::PRIMITIVE_LINES,d); - VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh,1,outer_mat); + VisualServer::get_singleton()->fixed_material_set_param(outer_mat, VS::FIXED_MATERIAL_PARAM_DIFFUSE, Color(0.7, 0.7, 1.0, 0.8)); + VisualServer::get_singleton()->material_set_line_width(outer_mat, 3.0); + VisualServer::get_singleton()->material_set_flag(outer_mat, VS::MATERIAL_FLAG_ONTOP, true); + VisualServer::get_singleton()->material_set_flag(outer_mat, VS::MATERIAL_FLAG_UNSHADED, true); + VisualServer::get_singleton()->fixed_material_set_flag(outer_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true); + d[VS::ARRAY_VERTEX] = lines; + VisualServer::get_singleton()->mesh_add_surface(selection_mesh, VS::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 1, outer_mat); inner_mat_dup = VisualServer::get_singleton()->fixed_material_create(); - VisualServer::get_singleton()->fixed_material_set_param(inner_mat_dup,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(1.0,0.7,0.7,0.3)); - VisualServer::get_singleton()->material_set_flag(inner_mat_dup,VS::MATERIAL_FLAG_ONTOP,true); - VisualServer::get_singleton()->material_set_flag(inner_mat_dup,VS::MATERIAL_FLAG_UNSHADED,true); - VisualServer::get_singleton()->fixed_material_set_flag( inner_mat_dup, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true ); - + VisualServer::get_singleton()->fixed_material_set_param(inner_mat_dup, VS::FIXED_MATERIAL_PARAM_DIFFUSE, Color(1.0, 0.7, 0.7, 0.3)); + VisualServer::get_singleton()->material_set_flag(inner_mat_dup, VS::MATERIAL_FLAG_ONTOP, true); + VisualServer::get_singleton()->material_set_flag(inner_mat_dup, VS::MATERIAL_FLAG_UNSHADED, true); + VisualServer::get_singleton()->fixed_material_set_flag(inner_mat_dup, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true); - d[VS::ARRAY_VERTEX]=triangles; - VisualServer::get_singleton()->mesh_add_surface(duplicate_mesh,VS::PRIMITIVE_TRIANGLES,d); - VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh,0,inner_mat_dup); + d[VS::ARRAY_VERTEX] = triangles; + VisualServer::get_singleton()->mesh_add_surface(duplicate_mesh, VS::PRIMITIVE_TRIANGLES, d); + VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh, 0, inner_mat_dup); outer_mat_dup = VisualServer::get_singleton()->fixed_material_create(); - VisualServer::get_singleton()->fixed_material_set_param(outer_mat_dup,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(1.0,0.7,0.7,0.8)); - VisualServer::get_singleton()->material_set_line_width(outer_mat_dup,3.0); - VisualServer::get_singleton()->material_set_flag(outer_mat_dup,VS::MATERIAL_FLAG_ONTOP,true); - VisualServer::get_singleton()->material_set_flag(outer_mat_dup,VS::MATERIAL_FLAG_UNSHADED,true); - VisualServer::get_singleton()->fixed_material_set_flag( outer_mat_dup, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true ); - - - d[VS::ARRAY_VERTEX]=lines; - VisualServer::get_singleton()->mesh_add_surface(duplicate_mesh,VS::PRIMITIVE_LINES,d); - VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh,1,outer_mat_dup); + VisualServer::get_singleton()->fixed_material_set_param(outer_mat_dup, VS::FIXED_MATERIAL_PARAM_DIFFUSE, Color(1.0, 0.7, 0.7, 0.8)); + VisualServer::get_singleton()->material_set_line_width(outer_mat_dup, 3.0); + VisualServer::get_singleton()->material_set_flag(outer_mat_dup, VS::MATERIAL_FLAG_ONTOP, true); + VisualServer::get_singleton()->material_set_flag(outer_mat_dup, VS::MATERIAL_FLAG_UNSHADED, true); + VisualServer::get_singleton()->fixed_material_set_flag(outer_mat_dup, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true); + d[VS::ARRAY_VERTEX] = lines; + VisualServer::get_singleton()->mesh_add_surface(duplicate_mesh, VS::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh, 1, outer_mat_dup); } - selection.active=false; - updating=false; - + selection.active = false; + updating = false; } - - - GridMapEditor::~GridMapEditor() { - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { if (grid[i].is_valid()) VisualServer::get_singleton()->free(grid[i]); @@ -1464,7 +1371,6 @@ GridMapEditor::~GridMapEditor() { if (selection_instance.is_valid()) VisualServer::get_singleton()->free(selection_instance); - VisualServer::get_singleton()->free(duplicate_mesh); if (duplicate_instance.is_valid()) VisualServer::get_singleton()->free(duplicate_instance); @@ -1474,8 +1380,7 @@ GridMapEditor::~GridMapEditor() { void GridMapEditorPlugin::edit(Object *p_object) { - - gridmap_editor->edit(p_object?p_object->cast_to<GridMap>():NULL); + gridmap_editor->edit(p_object ? p_object->cast_to<GridMap>() : NULL); } bool GridMapEditorPlugin::handles(Object *p_object) const { @@ -1496,26 +1401,18 @@ void GridMapEditorPlugin::make_visible(bool p_visible) { gridmap_editor->edit(NULL); gridmap_editor->set_process(false); } - } - GridMapEditorPlugin::GridMapEditorPlugin(EditorNode *p_node) { - editor=p_node; - gridmap_editor = memnew( GridMapEditor(editor) ); + editor = p_node; + gridmap_editor = memnew(GridMapEditor(editor)); SpatialEditor::get_singleton()->get_palette_split()->add_child(gridmap_editor); - SpatialEditor::get_singleton()->get_palette_split()->move_child(gridmap_editor,0); + SpatialEditor::get_singleton()->get_palette_split()->move_child(gridmap_editor, 0); gridmap_editor->hide(); - - - } - -GridMapEditorPlugin::~GridMapEditorPlugin() -{ +GridMapEditorPlugin::~GridMapEditorPlugin() { } - diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h index 23f377c8c..a7d1bfff3 100644 --- a/modules/gridmap/grid_map_editor_plugin.h +++ b/modules/gridmap/grid_map_editor_plugin.h @@ -29,10 +29,10 @@ #ifndef GRID_MAP_EDITOR_PLUGIN_H #define GRID_MAP_EDITOR_PLUGIN_H -#include "editor/editor_plugin.h" #include "editor/editor_node.h" -#include "grid_map.h" +#include "editor/editor_plugin.h" #include "editor/pane_drag.h" +#include "grid_map.h" /** @author Juan Linietsky <reduzio@gmail.com> */ @@ -40,11 +40,11 @@ class SpatialEditorPlugin; class GridMapEditor : public VBoxContainer { - OBJ_TYPE(GridMapEditor, VBoxContainer ); + OBJ_TYPE(GridMapEditor, VBoxContainer); enum { - GRID_CURSOR_SIZE=50 + GRID_CURSOR_SIZE = 50 }; enum InputAction { @@ -65,14 +65,14 @@ class GridMapEditor : public VBoxContainer { }; enum DisplayMode { - DISPLAY_THUMBNAIL, - DISPLAY_LIST + DISPLAY_THUMBNAIL, + DISPLAY_LIST }; UndoRedo *undo_redo; InputAction input_action; Panel *panel; - MenuButton * options; + MenuButton *options; SpinBox *floor; OptionButton *edit_mode; ToolButton *mode_thumbnail; @@ -94,7 +94,7 @@ class GridMapEditor : public VBoxContainer { List<SetItem> set_items; GridMap *node; - MeshLibrary* last_theme; + MeshLibrary *last_theme; ClipMode clip_mode; bool lock_view; @@ -121,10 +121,8 @@ class GridMapEditor : public VBoxContainer { bool updating; - struct Selection { - Vector3 click; Vector3 current; Vector3 begin; @@ -144,7 +142,6 @@ class GridMapEditor : public VBoxContainer { int selected_area; int cursor_rot; - enum Menu { MENU_OPTION_CONFIGURE, @@ -176,7 +173,6 @@ class GridMapEditor : public VBoxContainer { SpatialEditorPlugin *spatial_editor; - struct AreaDisplay { RID mesh; @@ -215,20 +211,18 @@ class GridMapEditor : public VBoxContainer { void update_areas(); EditorNode *editor; - bool do_input_action(Camera* p_camera,const Point2& p_point,bool p_click); + bool do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click); -friend class GridMapEditorPlugin; + friend class GridMapEditorPlugin; Panel *theme_panel; protected: void _notification(int p_what); void _node_removed(Node *p_node); static void _bind_methods(); -public: - - bool forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event); - +public: + bool forward_spatial_input_event(Camera *p_camera, const InputEvent &p_event); void edit(GridMap *p_gridmap); GridMapEditor() {} @@ -238,14 +232,13 @@ public: class GridMapEditorPlugin : public EditorPlugin { - OBJ_TYPE( GridMapEditorPlugin, EditorPlugin ); + OBJ_TYPE(GridMapEditorPlugin, EditorPlugin); GridMapEditor *gridmap_editor; EditorNode *editor; public: - - virtual bool forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event) { return gridmap_editor->forward_spatial_input_event(p_camera,p_event); } + virtual bool forward_spatial_input_event(Camera *p_camera, const InputEvent &p_event) { return gridmap_editor->forward_spatial_input_event(p_camera, p_event); } virtual String get_name() const { return "GridMap"; } bool has_main_screen() const { return false; } virtual void edit(Object *p_node); @@ -254,7 +247,6 @@ public: GridMapEditorPlugin(EditorNode *p_node); ~GridMapEditorPlugin(); - }; #endif // CUBE_GRID_MAP_EDITOR_PLUGIN_H diff --git a/modules/gridmap/register_types.cpp b/modules/gridmap/register_types.cpp index 284d59a68..bc505c67c 100644 --- a/modules/gridmap/register_types.cpp +++ b/modules/gridmap/register_types.cpp @@ -28,9 +28,9 @@ /*************************************************************************/ #include "register_types.h" #ifndef _3D_DISABLED -#include "object_type_db.h" #include "grid_map.h" #include "grid_map_editor_plugin.h" +#include "object_type_db.h" #endif void register_gridmap_types() { @@ -43,9 +43,5 @@ void register_gridmap_types() { #endif } - - void unregister_gridmap_types() { - - } diff --git a/modules/ik/ik.cpp b/modules/ik/ik.cpp index 35b3ba7e8..b0378a899 100644 --- a/modules/ik/ik.cpp +++ b/modules/ik/ik.cpp @@ -30,22 +30,20 @@ #include "ik.h" -bool InverseKinematics::_get(const StringName& p_name,Variant &r_ret) const -{ +bool InverseKinematics::_get(const StringName &p_name, Variant &r_ret) const { - if (String(p_name)=="ik_bone") { + if (String(p_name) == "ik_bone") { - r_ret=get_bone_name(); + r_ret = get_bone_name(); return true; } return false; } -bool InverseKinematics::_set(const StringName& p_name, const Variant& p_value) -{ +bool InverseKinematics::_set(const StringName &p_name, const Variant &p_value) { - if (String(p_name)=="ik_bone") { + if (String(p_name) == "ik_bone") { set_bone_name(p_value); changed = true; @@ -55,109 +53,97 @@ bool InverseKinematics::_set(const StringName& p_name, const Variant& p_value) return false; } -void InverseKinematics::_get_property_list( List<PropertyInfo>* p_list ) const -{ +void InverseKinematics::_get_property_list(List<PropertyInfo> *p_list) const { - Skeleton *parent=NULL; - if(get_parent()) - parent=get_parent()->cast_to<Skeleton>(); + Skeleton *parent = NULL; + if (get_parent()) + parent = get_parent()->cast_to<Skeleton>(); if (parent) { String names; - for(int i=0;i<parent->get_bone_count();i++) { - if(i>0) - names+=","; - names+=parent->get_bone_name(i); + for (int i = 0; i < parent->get_bone_count(); i++) { + if (i > 0) + names += ","; + names += parent->get_bone_name(i); } - p_list->push_back(PropertyInfo(Variant::STRING,"ik_bone",PROPERTY_HINT_ENUM,names)); + p_list->push_back(PropertyInfo(Variant::STRING, "ik_bone", PROPERTY_HINT_ENUM, names)); } else { - p_list->push_back(PropertyInfo(Variant::STRING,"ik_bone")); - + p_list->push_back(PropertyInfo(Variant::STRING, "ik_bone")); } - } -void InverseKinematics::_check_bind() -{ +void InverseKinematics::_check_bind() { if (get_parent() && get_parent()->cast_to<Skeleton>()) { Skeleton *sk = get_parent()->cast_to<Skeleton>(); int idx = sk->find_bone(ik_bone); - if (idx!=-1) { + if (idx != -1) { ik_bone_no = idx; - bound=true; + bound = true; } skel = sk; } } -void InverseKinematics::_check_unbind() -{ +void InverseKinematics::_check_unbind() { if (bound) { if (get_parent() && get_parent()->cast_to<Skeleton>()) { Skeleton *sk = get_parent()->cast_to<Skeleton>(); int idx = sk->find_bone(ik_bone); - if (idx!=-1) + if (idx != -1) ik_bone_no = idx; else ik_bone_no = 0; skel = sk; - } - bound=false; + bound = false; } } - -void InverseKinematics::set_bone_name(const String& p_name) -{ +void InverseKinematics::set_bone_name(const String &p_name) { if (is_inside_tree()) _check_unbind(); - ik_bone=p_name; + ik_bone = p_name; if (is_inside_tree()) _check_bind(); changed = true; } -String InverseKinematics::get_bone_name() const -{ +String InverseKinematics::get_bone_name() const { return ik_bone; } -void InverseKinematics::set_iterations(int itn) -{ +void InverseKinematics::set_iterations(int itn) { if (is_inside_tree()) _check_unbind(); - iterations=itn; + iterations = itn; if (is_inside_tree()) _check_bind(); changed = true; } -int InverseKinematics::get_iterations() const -{ +int InverseKinematics::get_iterations() const { return iterations; } -void InverseKinematics::set_chain_size(int cs) -{ +void InverseKinematics::set_chain_size(int cs) { if (is_inside_tree()) _check_unbind(); - chain_size=cs; + chain_size = cs; chain.clear(); if (bound) update_parameters(); @@ -167,52 +153,46 @@ void InverseKinematics::set_chain_size(int cs) changed = true; } -int InverseKinematics::get_chain_size() const -{ +int InverseKinematics::get_chain_size() const { return chain_size; } -void InverseKinematics::set_precision(float p) -{ +void InverseKinematics::set_precision(float p) { if (is_inside_tree()) _check_unbind(); - precision=p; + precision = p; if (is_inside_tree()) _check_bind(); changed = true; } -float InverseKinematics::get_precision() const -{ +float InverseKinematics::get_precision() const { return precision; } -void InverseKinematics::set_speed(float p) -{ +void InverseKinematics::set_speed(float p) { if (is_inside_tree()) _check_unbind(); - speed=p; + speed = p; if (is_inside_tree()) _check_bind(); changed = true; } -float InverseKinematics::get_speed() const -{ +float InverseKinematics::get_speed() const { return speed; } -void InverseKinematics::update_parameters() -{ +void InverseKinematics::update_parameters() { tail_bone = -1; for (int i = 0; i < skel->get_bone_count(); i++) if (skel->get_bone_parent(i) == ik_bone_no) @@ -226,10 +206,9 @@ void InverseKinematics::update_parameters() } } -void InverseKinematics::_notification(int p_what) -{ +void InverseKinematics::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -267,9 +246,8 @@ void InverseKinematics::_notification(int p_what) if (!reached && err < precision) reached = true; break; - } else - if (reached) - reached = false; + } else if (reached) + reached = false; if (err > olderr) psign = -psign; Transform mod = skel->get_bone_global_pose(cur_bone); @@ -286,10 +264,9 @@ void InverseKinematics::_notification(int p_what) } if (reached) break; - } - } break; + } break; case NOTIFICATION_EXIT_TREE: { set_process(false); @@ -298,29 +275,26 @@ void InverseKinematics::_notification(int p_what) } } void InverseKinematics::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_bone_name","ik_bone"),&InverseKinematics::set_bone_name); - ObjectTypeDB::bind_method(_MD("get_bone_name"),&InverseKinematics::get_bone_name); - ObjectTypeDB::bind_method(_MD("set_iterations","iterations"),&InverseKinematics::set_iterations); - ObjectTypeDB::bind_method(_MD("get_iterations"),&InverseKinematics::get_iterations); - ObjectTypeDB::bind_method(_MD("set_chain_size","chain_size"),&InverseKinematics::set_chain_size); - ObjectTypeDB::bind_method(_MD("get_chain_size"),&InverseKinematics::get_chain_size); - ObjectTypeDB::bind_method(_MD("set_precision","precision"),&InverseKinematics::set_precision); - ObjectTypeDB::bind_method(_MD("get_precision"),&InverseKinematics::get_precision); - ObjectTypeDB::bind_method(_MD("set_speed","speed"),&InverseKinematics::set_speed); - ObjectTypeDB::bind_method(_MD("get_speed"),&InverseKinematics::get_speed); + ObjectTypeDB::bind_method(_MD("set_bone_name", "ik_bone"), &InverseKinematics::set_bone_name); + ObjectTypeDB::bind_method(_MD("get_bone_name"), &InverseKinematics::get_bone_name); + ObjectTypeDB::bind_method(_MD("set_iterations", "iterations"), &InverseKinematics::set_iterations); + ObjectTypeDB::bind_method(_MD("get_iterations"), &InverseKinematics::get_iterations); + ObjectTypeDB::bind_method(_MD("set_chain_size", "chain_size"), &InverseKinematics::set_chain_size); + ObjectTypeDB::bind_method(_MD("get_chain_size"), &InverseKinematics::get_chain_size); + ObjectTypeDB::bind_method(_MD("set_precision", "precision"), &InverseKinematics::set_precision); + ObjectTypeDB::bind_method(_MD("get_precision"), &InverseKinematics::get_precision); + ObjectTypeDB::bind_method(_MD("set_speed", "speed"), &InverseKinematics::set_speed); + ObjectTypeDB::bind_method(_MD("get_speed"), &InverseKinematics::get_speed); ADD_PROPERTY(PropertyInfo(Variant::INT, "iterations"), _SCS("set_iterations"), _SCS("get_iterations")); ADD_PROPERTY(PropertyInfo(Variant::INT, "chain_size"), _SCS("set_chain_size"), _SCS("get_chain_size")); ADD_PROPERTY(PropertyInfo(Variant::REAL, "precision"), _SCS("set_precision"), _SCS("get_precision")); ADD_PROPERTY(PropertyInfo(Variant::REAL, "speed"), _SCS("set_speed"), _SCS("get_speed")); } -InverseKinematics::InverseKinematics() -{ - bound=false; +InverseKinematics::InverseKinematics() { + bound = false; chain_size = 2; iterations = 100; precision = 0.001; speed = 0.2; - } - diff --git a/modules/ik/ik.h b/modules/ik/ik.h index c8b2c3a8b..5a71c2e77 100644 --- a/modules/ik/ik.h +++ b/modules/ik/ik.h @@ -48,16 +48,17 @@ class InverseKinematics : public Spatial { bool changed; 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; + 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; void _notification(int p_what); static void _bind_methods(); void update_parameters(); + public: Skeleton *get_skeleton(); - void set_bone_name(const String& p_name); + void set_bone_name(const String &p_name); String get_bone_name() const; void set_iterations(int itn); int get_iterations() const; @@ -71,4 +72,3 @@ public: }; #endif - diff --git a/modules/ik/register_types.cpp b/modules/ik/register_types.cpp index 46ef53f15..926dc45b0 100644 --- a/modules/ik/register_types.cpp +++ b/modules/ik/register_types.cpp @@ -28,8 +28,8 @@ /*************************************************************************/ #include "register_types.h" #ifndef _3D_DISABLED -#include "object_type_db.h" #include "ik.h" +#include "object_type_db.h" #endif void register_ik_types() { @@ -39,9 +39,5 @@ void register_ik_types() { #endif } - - void unregister_ik_types() { - - } diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index 096e655d7..fc496638a 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -28,16 +28,15 @@ /*************************************************************************/ #include "image_loader_jpegd.h" -#include "print_string.h" #include "os/os.h" +#include "print_string.h" #include <jpgd.h> #include <string.h> +Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p_buffer_len) { -Error jpeg_load_image_from_buffer(Image *p_image,const uint8_t* p_buffer, int p_buffer_len) { - - jpgd::jpeg_decoder_mem_stream mem_stream(p_buffer,p_buffer_len); + jpgd::jpeg_decoder_mem_stream mem_stream(p_buffer, p_buffer_len); jpgd::jpeg_decoder decoder(&mem_stream); @@ -48,8 +47,8 @@ Error jpeg_load_image_from_buffer(Image *p_image,const uint8_t* p_buffer, int p_ const int image_width = decoder.get_width(); const int image_height = decoder.get_height(); int comps = decoder.get_num_components(); - if (comps==3) - comps=4; //weird + if (comps == 3) + comps = 4; //weird if (decoder.begin_decoding() != jpgd::JPGD_SUCCESS) return ERR_FILE_CORRUPT; @@ -62,42 +61,34 @@ Error jpeg_load_image_from_buffer(Image *p_image,const uint8_t* p_buffer, int p_ DVector<uint8_t>::Write dw = data.write(); - jpgd::uint8 *pImage_data = (jpgd::uint8*)dw.ptr(); + jpgd::uint8 *pImage_data = (jpgd::uint8 *)dw.ptr(); - for (int y = 0; y < image_height; y++) - { - const jpgd::uint8* pScan_line; + for (int y = 0; y < image_height; y++) { + const jpgd::uint8 *pScan_line; jpgd::uint scan_line_len; - if (decoder.decode((const void**)&pScan_line, &scan_line_len) != jpgd::JPGD_SUCCESS) - { + if (decoder.decode((const void **)&pScan_line, &scan_line_len) != jpgd::JPGD_SUCCESS) { return ERR_FILE_CORRUPT; } jpgd::uint8 *pDst = pImage_data + y * dst_bpl; memcpy(pDst, pScan_line, dst_bpl); - - } - //all good Image::Format fmt; - if (comps==1) - fmt=Image::FORMAT_GRAYSCALE; + if (comps == 1) + fmt = Image::FORMAT_GRAYSCALE; else - fmt=Image::FORMAT_RGBA; + fmt = Image::FORMAT_RGBA; dw = DVector<uint8_t>::Write(); - p_image->create(image_width,image_height,0,fmt,data); + p_image->create(image_width, image_height, 0, fmt, data); return OK; - } - -Error ImageLoaderJPG::load_image(Image *p_image,FileAccess *f) { - +Error ImageLoaderJPG::load_image(Image *p_image, FileAccess *f) { DVector<uint8_t> src_image; int src_image_len = f->get_len(); @@ -106,30 +97,27 @@ Error ImageLoaderJPG::load_image(Image *p_image,FileAccess *f) { DVector<uint8_t>::Write w = src_image.write(); - f->get_buffer(&w[0],src_image_len); + f->get_buffer(&w[0], src_image_len); f->close(); - - Error err = jpeg_load_image_from_buffer(p_image,w.ptr(),src_image_len); + Error err = jpeg_load_image_from_buffer(p_image, w.ptr(), src_image_len); w = DVector<uint8_t>::Write(); return err; - } void ImageLoaderJPG::get_recognized_extensions(List<String> *p_extensions) const { - + p_extensions->push_back("jpg"); p_extensions->push_back("jpeg"); } - -static Image _jpegd_mem_loader_func(const uint8_t* p_png,int p_size) { +static Image _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) { Image img; - Error err = jpeg_load_image_from_buffer(&img,p_png,p_size); + Error err = jpeg_load_image_from_buffer(&img, p_png, p_size); if (err) ERR_PRINT("Couldn't initialize ImageLoaderJPG with the given resource."); @@ -138,7 +126,5 @@ static Image _jpegd_mem_loader_func(const uint8_t* p_png,int p_size) { ImageLoaderJPG::ImageLoaderJPG() { - Image::_jpg_mem_loader_func=_jpegd_mem_loader_func; + Image::_jpg_mem_loader_func = _jpegd_mem_loader_func; } - - diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h index aeb219aa5..0803cfba1 100644 --- a/modules/jpg/image_loader_jpegd.h +++ b/modules/jpg/image_loader_jpegd.h @@ -36,14 +36,10 @@ */ class ImageLoaderJPG : public ImageFormatLoader { - public: - - virtual Error load_image(Image *p_image,FileAccess *f); - virtual void get_recognized_extensions(List<String> *p_extensions) const; + virtual Error load_image(Image *p_image, FileAccess *f); + virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderJPG(); }; - - #endif diff --git a/modules/jpg/register_types.cpp b/modules/jpg/register_types.cpp index bcd467f5f..ce0330643 100644 --- a/modules/jpg/register_types.cpp +++ b/modules/jpg/register_types.cpp @@ -34,11 +34,11 @@ static ImageLoaderJPG *image_loader_jpg = NULL; void register_jpg_types() { - image_loader_jpg = memnew( ImageLoaderJPG ); + image_loader_jpg = memnew(ImageLoaderJPG); ImageLoader::add_image_format_loader(image_loader_jpg); } void unregister_jpg_types() { - memdelete( image_loader_jpg ); + memdelete(image_loader_jpg); } diff --git a/modules/mpc/audio_stream_mpc.cpp b/modules/mpc/audio_stream_mpc.cpp index befb8ea29..c992af429 100644 --- a/modules/mpc/audio_stream_mpc.cpp +++ b/modules/mpc/audio_stream_mpc.cpp @@ -28,42 +28,40 @@ /*************************************************************************/ #include "audio_stream_mpc.h" - Error AudioStreamPlaybackMPC::_open_file() { if (f) { memdelete(f); - f=NULL; + f = NULL; } Error err; //printf("mpc open file %ls\n", file.c_str()); - f=FileAccess::open(file,FileAccess::READ,&err); + f = FileAccess::open(file, FileAccess::READ, &err); if (err) { - f=NULL; + f = NULL; ERR_FAIL_V(err); return err; } //printf("file size is %i\n", f->get_len()); //f->seek_end(0); - streamlen=f->get_len(); + streamlen = f->get_len(); //f->seek(0); - if (streamlen<=0) { + if (streamlen <= 0) { memdelete(f); - f=NULL; + f = NULL; ERR_FAIL_V(ERR_INVALID_DATA); } - data_ofs=0; + data_ofs = 0; if (preload) { data.resize(streamlen); DVector<uint8_t>::Write w = data.write(); - f->get_buffer(&w[0],streamlen); + f->get_buffer(&w[0], streamlen); memdelete(f); - f=NULL; - + f = NULL; } return OK; @@ -73,32 +71,32 @@ void AudioStreamPlaybackMPC::_close_file() { if (f) { memdelete(f); - f=NULL; + f = NULL; } data.resize(0); - streamlen=0; - data_ofs=0; + streamlen = 0; + data_ofs = 0; } -int AudioStreamPlaybackMPC::_read_file(void *p_dst,int p_bytes) { +int AudioStreamPlaybackMPC::_read_file(void *p_dst, int p_bytes) { if (f) - return f->get_buffer((uint8_t*)p_dst,p_bytes); + return f->get_buffer((uint8_t *)p_dst, p_bytes); DVector<uint8_t>::Read r = data.read(); - if (p_bytes+data_ofs > streamlen) { - p_bytes=streamlen-data_ofs; + if (p_bytes + data_ofs > streamlen) { + p_bytes = streamlen - data_ofs; } - copymem(p_dst,&r[data_ofs],p_bytes); + copymem(p_dst, &r[data_ofs], p_bytes); //print_line("read file: "+itos(p_bytes)); - data_ofs+=p_bytes; + data_ofs += p_bytes; return p_bytes; } -bool AudioStreamPlaybackMPC::_seek_file(int p_pos){ +bool AudioStreamPlaybackMPC::_seek_file(int p_pos) { - if (p_pos<0 || p_pos>streamlen) + if (p_pos < 0 || p_pos > streamlen) return false; if (f) { @@ -107,27 +105,25 @@ bool AudioStreamPlaybackMPC::_seek_file(int p_pos){ } //print_line("read file to: "+itos(p_pos)); - data_ofs=p_pos; + data_ofs = p_pos; return true; - } -int AudioStreamPlaybackMPC::_tell_file() const{ +int AudioStreamPlaybackMPC::_tell_file() const { if (f) return f->get_pos(); //print_line("tell file, get: "+itos(data_ofs)); return data_ofs; - } -int AudioStreamPlaybackMPC::_sizeof_file() const{ +int AudioStreamPlaybackMPC::_sizeof_file() const { //print_line("sizeof file, get: "+itos(streamlen)); return streamlen; } -bool AudioStreamPlaybackMPC::_canseek_file() const{ +bool AudioStreamPlaybackMPC::_canseek_file() const { //print_line("canseek file, get true"); return true; @@ -135,81 +131,73 @@ bool AudioStreamPlaybackMPC::_canseek_file() const{ ///////////////////// -mpc_int32_t AudioStreamPlaybackMPC::_mpc_read(mpc_reader *p_reader,void *p_dst, mpc_int32_t p_bytes) { +mpc_int32_t AudioStreamPlaybackMPC::_mpc_read(mpc_reader *p_reader, void *p_dst, mpc_int32_t p_bytes) { - AudioStreamPlaybackMPC *smpc=(AudioStreamPlaybackMPC *)p_reader->data; - return smpc->_read_file(p_dst,p_bytes); + AudioStreamPlaybackMPC *smpc = (AudioStreamPlaybackMPC *)p_reader->data; + return smpc->_read_file(p_dst, p_bytes); } -mpc_bool_t AudioStreamPlaybackMPC::_mpc_seek(mpc_reader *p_reader,mpc_int32_t p_offset) { +mpc_bool_t AudioStreamPlaybackMPC::_mpc_seek(mpc_reader *p_reader, mpc_int32_t p_offset) { - AudioStreamPlaybackMPC *smpc=(AudioStreamPlaybackMPC *)p_reader->data; + AudioStreamPlaybackMPC *smpc = (AudioStreamPlaybackMPC *)p_reader->data; return smpc->_seek_file(p_offset); - } mpc_int32_t AudioStreamPlaybackMPC::_mpc_tell(mpc_reader *p_reader) { - AudioStreamPlaybackMPC *smpc=(AudioStreamPlaybackMPC *)p_reader->data; + AudioStreamPlaybackMPC *smpc = (AudioStreamPlaybackMPC *)p_reader->data; return smpc->_tell_file(); - } mpc_int32_t AudioStreamPlaybackMPC::_mpc_get_size(mpc_reader *p_reader) { - AudioStreamPlaybackMPC *smpc=(AudioStreamPlaybackMPC *)p_reader->data; + AudioStreamPlaybackMPC *smpc = (AudioStreamPlaybackMPC *)p_reader->data; return smpc->_sizeof_file(); - - } mpc_bool_t AudioStreamPlaybackMPC::_mpc_canseek(mpc_reader *p_reader) { - AudioStreamPlaybackMPC *smpc=(AudioStreamPlaybackMPC *)p_reader->data; + AudioStreamPlaybackMPC *smpc = (AudioStreamPlaybackMPC *)p_reader->data; return smpc->_canseek_file(); } - - - -int AudioStreamPlaybackMPC::mix(int16_t* p_bufer,int p_frames) { +int AudioStreamPlaybackMPC::mix(int16_t *p_bufer, int p_frames) { if (!active || paused) return 0; - int todo=p_frames; + int todo = p_frames; - while(todo>MPC_DECODER_BUFFER_LENGTH/si.channels) { + while (todo > MPC_DECODER_BUFFER_LENGTH / si.channels) { mpc_frame_info frame; - frame.buffer=sample_buffer; + frame.buffer = sample_buffer; mpc_status err = mpc_demux_decode(demux, &frame); - if (frame.bits!=-1) { + if (frame.bits != -1) { int16_t *dst_buff = p_bufer; #ifdef MPC_FIXED_POINT - for( int i = 0; i < frame.samples * si.channels; i++) { + for (int i = 0; i < frame.samples * si.channels; i++) { int tmp = sample_buffer[i] >> MPC_FIXED_POINT_FRACTPART; if (tmp > ((1 << 15) - 1)) tmp = ((1 << 15) - 1); if (tmp < -(1 << 15)) tmp = -(1 << 15); dst_buff[i] = tmp; } #else - for( int i = 0; i < frame.samples * si.channels; i++) { + for (int i = 0; i < frame.samples * si.channels; i++) { - int tmp = Math::fast_ftoi(sample_buffer[i]*32767.0); + int tmp = Math::fast_ftoi(sample_buffer[i] * 32767.0); if (tmp > ((1 << 15) - 1)) tmp = ((1 << 15) - 1); if (tmp < -(1 << 15)) tmp = -(1 << 15); dst_buff[i] = tmp; - } #endif int frames = frame.samples; - p_bufer+=si.channels*frames; - todo-=frames; + p_bufer += si.channels * frames; + todo -= frames; } else { if (err != MPC_STATUS_OK) { @@ -225,101 +213,91 @@ int AudioStreamPlaybackMPC::mix(int16_t* p_bufer,int p_frames) { break; } else { - loops++; mpc_demux_exit(demux); _seek_file(0); demux = mpc_demux_init(&reader); //do loop somehow - } } } } - return p_frames-todo; + return p_frames - todo; } Error AudioStreamPlaybackMPC::_reload() { - ERR_FAIL_COND_V(demux!=NULL, ERR_FILE_ALREADY_IN_USE); + ERR_FAIL_COND_V(demux != NULL, ERR_FILE_ALREADY_IN_USE); Error err = _open_file(); - ERR_FAIL_COND_V(err!=OK,ERR_CANT_OPEN); + ERR_FAIL_COND_V(err != OK, ERR_CANT_OPEN); demux = mpc_demux_init(&reader); - ERR_FAIL_COND_V(!demux,ERR_CANT_CREATE); - mpc_demux_get_info(demux, &si); + ERR_FAIL_COND_V(!demux, ERR_CANT_CREATE); + mpc_demux_get_info(demux, &si); return OK; } -void AudioStreamPlaybackMPC::set_file(const String& p_file) { +void AudioStreamPlaybackMPC::set_file(const String &p_file) { - file=p_file; + file = p_file; Error err = _open_file(); - ERR_FAIL_COND(err!=OK); + ERR_FAIL_COND(err != OK); demux = mpc_demux_init(&reader); ERR_FAIL_COND(!demux); - mpc_demux_get_info(demux, &si); - stream_min_size=MPC_DECODER_BUFFER_LENGTH*2/si.channels; - stream_rate=si.sample_freq; - stream_channels=si.channels; + mpc_demux_get_info(demux, &si); + stream_min_size = MPC_DECODER_BUFFER_LENGTH * 2 / si.channels; + stream_rate = si.sample_freq; + stream_channels = si.channels; mpc_demux_exit(demux); - demux=NULL; + demux = NULL; _close_file(); - } - String AudioStreamPlaybackMPC::get_file() const { return file; } - void AudioStreamPlaybackMPC::play(float p_offset) { - if (active) stop(); - active=false; + active = false; Error err = _open_file(); - ERR_FAIL_COND(err!=OK); - if (_reload()!=OK) + ERR_FAIL_COND(err != OK); + if (_reload() != OK) return; - active=true; - loops=0; - + active = true; + loops = 0; } -void AudioStreamPlaybackMPC::stop() { - +void AudioStreamPlaybackMPC::stop() { if (!active) return; if (demux) { mpc_demux_exit(demux); - demux=NULL; + demux = NULL; } _close_file(); - active=false; - + active = false; } -bool AudioStreamPlaybackMPC::is_playing() const { +bool AudioStreamPlaybackMPC::is_playing() const { return active; } +void AudioStreamPlaybackMPC::set_loop(bool p_enable) { -void AudioStreamPlaybackMPC::set_loop(bool p_enable) { - - loop=p_enable; + loop = p_enable; } -bool AudioStreamPlaybackMPC::has_loop() const { +bool AudioStreamPlaybackMPC::has_loop() const { return loop; } @@ -344,38 +322,33 @@ float AudioStreamPlaybackMPC::get_pos() const { return 0; } void AudioStreamPlaybackMPC::seek_pos(float p_time) { - - } - void AudioStreamPlaybackMPC::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_file","name"),&AudioStreamPlaybackMPC::set_file); - ObjectTypeDB::bind_method(_MD("get_file"),&AudioStreamPlaybackMPC::get_file); - - ADD_PROPERTYNZ( PropertyInfo(Variant::STRING,"file",PROPERTY_HINT_FILE,"mpc"), _SCS("set_file"), _SCS("get_file")); + ObjectTypeDB::bind_method(_MD("set_file", "name"), &AudioStreamPlaybackMPC::set_file); + ObjectTypeDB::bind_method(_MD("get_file"), &AudioStreamPlaybackMPC::get_file); + ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_FILE, "mpc"), _SCS("set_file"), _SCS("get_file")); } AudioStreamPlaybackMPC::AudioStreamPlaybackMPC() { - preload=false; - f=NULL; - streamlen=0; - data_ofs=0; - active=false; - paused=false; - loop=false; - demux=NULL; - reader.data=this; - reader.read=_mpc_read; - reader.seek=_mpc_seek; - reader.tell=_mpc_tell; - reader.get_size=_mpc_get_size; - reader.canseek=_mpc_canseek; - loops=0; - + preload = false; + f = NULL; + streamlen = 0; + data_ofs = 0; + active = false; + paused = false; + loop = false; + demux = NULL; + reader.data = this; + reader.read = _mpc_read; + reader.seek = _mpc_seek; + reader.tell = _mpc_tell; + reader.get_size = _mpc_get_size; + reader.canseek = _mpc_canseek; + loops = 0; } AudioStreamPlaybackMPC::~AudioStreamPlaybackMPC() { @@ -386,11 +359,9 @@ AudioStreamPlaybackMPC::~AudioStreamPlaybackMPC() { memdelete(f); } - - -RES ResourceFormatLoaderAudioStreamMPC::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderAudioStreamMPC::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=OK; //streamed so it will always work.. + *r_error = OK; //streamed so it will always work.. AudioStreamMPC *mpc_stream = memnew(AudioStreamMPC); mpc_stream->set_file(p_path); return Ref<AudioStreamMPC>(mpc_stream); @@ -400,15 +371,14 @@ void ResourceFormatLoaderAudioStreamMPC::get_recognized_extensions(List<String> p_extensions->push_back("mpc"); } -bool ResourceFormatLoaderAudioStreamMPC::handles_type(const String& p_type) const { +bool ResourceFormatLoaderAudioStreamMPC::handles_type(const String &p_type) const { - return (p_type=="AudioStream") || (p_type=="AudioStreamMPC"); + return (p_type == "AudioStream") || (p_type == "AudioStreamMPC"); } String ResourceFormatLoaderAudioStreamMPC::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="mpc") + if (p_path.extension().to_lower() == "mpc") return "AudioStreamMPC"; return ""; } - diff --git a/modules/mpc/audio_stream_mpc.h b/modules/mpc/audio_stream_mpc.h index 9430f752f..1baf498ed 100644 --- a/modules/mpc/audio_stream_mpc.h +++ b/modules/mpc/audio_stream_mpc.h @@ -38,7 +38,7 @@ class AudioStreamPlaybackMPC : public AudioStreamPlayback { - OBJ_TYPE( AudioStreamPlaybackMPC, AudioStreamPlayback ); + OBJ_TYPE(AudioStreamPlaybackMPC, AudioStreamPlayback); bool preload; FileAccess *f; @@ -47,7 +47,6 @@ class AudioStreamPlaybackMPC : public AudioStreamPlayback { int data_ofs; int streamlen; - bool active; bool paused; bool loop; @@ -55,12 +54,12 @@ class AudioStreamPlaybackMPC : public AudioStreamPlayback { // mpc mpc_reader reader; - mpc_demux* demux; + mpc_demux *demux; mpc_streaminfo si; MPC_SAMPLE_FORMAT sample_buffer[MPC_DECODER_BUFFER_LENGTH]; - static mpc_int32_t _mpc_read(mpc_reader *p_reader,void *p_dst, mpc_int32_t p_bytes); - static mpc_bool_t _mpc_seek(mpc_reader *p_reader,mpc_int32_t p_offset); + static mpc_int32_t _mpc_read(mpc_reader *p_reader, void *p_dst, mpc_int32_t p_bytes); + static mpc_bool_t _mpc_seek(mpc_reader *p_reader, mpc_int32_t p_offset); static mpc_int32_t _mpc_tell(mpc_reader *p_reader); static mpc_int32_t _mpc_get_size(mpc_reader *p_reader); static mpc_bool_t _mpc_canseek(mpc_reader *p_reader); @@ -72,26 +71,23 @@ class AudioStreamPlaybackMPC : public AudioStreamPlayback { protected: Error _open_file(); void _close_file(); - int _read_file(void *p_dst,int p_bytes); + int _read_file(void *p_dst, int p_bytes); bool _seek_file(int p_pos); - int _tell_file() const; + int _tell_file() const; int _sizeof_file() const; bool _canseek_file() const; - Error _reload(); static void _bind_methods(); public: - - void set_file(const String& p_file); + void set_file(const String &p_file); String get_file() const; - virtual void play(float p_offset=0); + virtual void play(float p_offset = 0); virtual void stop(); virtual bool is_playing() const; - virtual void set_loop(bool p_enable); virtual bool has_loop() const; @@ -108,9 +104,9 @@ public: virtual int get_mix_rate() const { return stream_rate; } virtual int get_minimum_buffer_size() const { return stream_min_size; } - virtual int mix(int16_t* p_bufer,int p_frames); + virtual int mix(int16_t *p_bufer, int p_frames); - virtual void set_loop_restart_time(float p_time) { } + virtual void set_loop_restart_time(float p_time) {} AudioStreamPlaybackMPC(); ~AudioStreamPlaybackMPC(); @@ -118,29 +114,26 @@ public: class AudioStreamMPC : public AudioStream { - OBJ_TYPE( AudioStreamMPC, AudioStream ); + OBJ_TYPE(AudioStreamMPC, AudioStream); String file; -public: +public: Ref<AudioStreamPlayback> instance_playback() { - Ref<AudioStreamPlaybackMPC> pb = memnew( AudioStreamPlaybackMPC ); + Ref<AudioStreamPlaybackMPC> pb = memnew(AudioStreamPlaybackMPC); pb->set_file(file); return pb; } - void set_file(const String& p_file) { file=p_file; } - - + void set_file(const String &p_file) { file = p_file; } }; class ResourceFormatLoaderAudioStreamMPC : public ResourceFormatLoader { public: - 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 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; - }; #endif // AUDIO_STREAM_MPC_H diff --git a/modules/mpc/register_types.cpp b/modules/mpc/register_types.cpp index 7e962804b..1bc59d1e8 100644 --- a/modules/mpc/register_types.cpp +++ b/modules/mpc/register_types.cpp @@ -30,16 +30,16 @@ #include "audio_stream_mpc.h" -static ResourceFormatLoaderAudioStreamMPC* mpc_stream_loader = NULL; +static ResourceFormatLoaderAudioStreamMPC *mpc_stream_loader = NULL; void register_mpc_types() { - mpc_stream_loader=memnew( ResourceFormatLoaderAudioStreamMPC ); + mpc_stream_loader = memnew(ResourceFormatLoaderAudioStreamMPC); ResourceLoader::add_resource_format_loader(mpc_stream_loader); ObjectTypeDB::register_type<AudioStreamMPC>(); } void unregister_mpc_types() { - memdelete( mpc_stream_loader ); + memdelete(mpc_stream_loader); } diff --git a/modules/openssl/stream_peer_openssl.cpp b/modules/openssl/stream_peer_openssl.cpp index a1d07d911..00db522fa 100644 --- a/modules/openssl/stream_peer_openssl.cpp +++ b/modules/openssl/stream_peer_openssl.cpp @@ -29,14 +29,13 @@ #include "stream_peer_openssl.h" //hostname matching code from curl - //#include <openssl/applink.c> // To prevent crashing (see the OpenSSL FAQ) bool StreamPeerOpenSSL::_match_host_name(const char *name, const char *hostname) { - return Tool_Curl_cert_hostcheck(name,hostname)==CURL_HOST_MATCH; -// print_line("MATCH: "+String(name)+" vs "+String(hostname)); -// return true; + return Tool_Curl_cert_hostcheck(name, hostname) == CURL_HOST_MATCH; + // print_line("MATCH: "+String(name)+" vs "+String(hostname)); + // return true; } Error StreamPeerOpenSSL::_match_common_name(const char *hostname, const X509 *server_cert) { @@ -47,36 +46,32 @@ Error StreamPeerOpenSSL::_match_common_name(const char *hostname, const X509 *se char *common_name_str = NULL; // Find the position of the CN field in the Subject field of the certificate - common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1); + common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *)server_cert), NID_commonName, -1); - ERR_FAIL_COND_V(common_name_loc < 0, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(common_name_loc < 0, ERR_INVALID_PARAMETER); // Extract the CN field - common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc); + common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *)server_cert), common_name_loc); - ERR_FAIL_COND_V(common_name_entry == NULL, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(common_name_entry == NULL, ERR_INVALID_PARAMETER); // Convert the CN field to a C string common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry); - ERR_FAIL_COND_V(common_name_asn1 == NULL, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(common_name_asn1 == NULL, ERR_INVALID_PARAMETER); - common_name_str = (char *) ASN1_STRING_data(common_name_asn1); + common_name_str = (char *)ASN1_STRING_data(common_name_asn1); // Make sure there isn't an embedded NUL character in the CN bool malformed_certificate = (size_t)ASN1_STRING_length(common_name_asn1) != strlen(common_name_str); - ERR_FAIL_COND_V(malformed_certificate, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(malformed_certificate, ERR_INVALID_PARAMETER); // Compare expected hostname with the CN - - return _match_host_name(common_name_str,hostname)?OK:FAILED; - + return _match_host_name(common_name_str, hostname) ? OK : FAILED; } - /** * Tries to find a match for hostname in the certificate's Subject Alternative Name extension. * @@ -90,26 +85,25 @@ Error StreamPeerOpenSSL::_match_subject_alternative_name(const char *hostname, c STACK_OF(GENERAL_NAME) *san_names = NULL; // Try to extract the names within the SAN extension from the certificate - san_names = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, NULL, NULL); + san_names = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i((X509 *)server_cert, NID_subject_alt_name, NULL, NULL); if (san_names == NULL) { return ERR_FILE_NOT_FOUND; } san_names_nb = sk_GENERAL_NAME_num(san_names); // Check each name within the extension - for (i=0; i<san_names_nb; i++) { + for (i = 0; i < san_names_nb; i++) { const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i); if (current_name->type == GEN_DNS) { // Current name is a DNS name, let's check it - char *dns_name = (char *) ASN1_STRING_data(current_name->d.dNSName); + char *dns_name = (char *)ASN1_STRING_data(current_name->d.dNSName); // Make sure there isn't an embedded NUL character in the DNS name if ((size_t)ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) { result = ERR_INVALID_PARAMETER; break; - } - else { // Compare expected hostname with the DNS name + } else { // Compare expected hostname with the DNS name if (_match_host_name(dns_name, hostname)) { result = OK; break; @@ -131,19 +125,19 @@ int StreamPeerOpenSSL::_cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg bool base_cert_valid = X509_verify_cert(x509_ctx); if (!base_cert_valid) { - print_line("Cause: "+String(X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx)))); + print_line("Cause: " + String(X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx)))); ERR_print_errors_fp(stdout); } X509 *server_cert = X509_STORE_CTX_get_current_cert(x509_ctx); - ERR_FAIL_COND_V(!server_cert,0); + ERR_FAIL_COND_V(!server_cert, 0); char cert_str[256]; - X509_NAME_oneline(X509_get_subject_name (server_cert), - cert_str, sizeof (cert_str)); + X509_NAME_oneline(X509_get_subject_name(server_cert), + cert_str, sizeof(cert_str)); - print_line("CERT STR: "+String(cert_str)); - print_line("VALID: "+itos(base_cert_valid)); + print_line("CERT STR: " + String(cert_str)); + print_line("VALID: " + itos(base_cert_valid)); if (!base_cert_valid) return 0; @@ -152,27 +146,24 @@ int StreamPeerOpenSSL::_cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg if (ssl->validate_hostname) { - Error err = _match_subject_alternative_name(ssl->hostname.utf8().get_data(),server_cert); + Error err = _match_subject_alternative_name(ssl->hostname.utf8().get_data(), server_cert); - if (err==ERR_FILE_NOT_FOUND) { + if (err == ERR_FILE_NOT_FOUND) { - err = _match_common_name(ssl->hostname.utf8().get_data(),server_cert); + err = _match_common_name(ssl->hostname.utf8().get_data(), server_cert); } - if (err!=OK) { + if (err != OK) { - ssl->status=STATUS_ERROR_HOSTNAME_MISMATCH; + ssl->status = STATUS_ERROR_HOSTNAME_MISMATCH; return 0; } } return 1; - } - - -int StreamPeerOpenSSL::_bio_create( BIO *b ) { +int StreamPeerOpenSSL::_bio_create(BIO *b) { b->init = 1; b->num = 0; b->ptr = NULL; @@ -180,31 +171,29 @@ int StreamPeerOpenSSL::_bio_create( BIO *b ) { return 1; } -int StreamPeerOpenSSL::_bio_destroy( BIO *b ) -{ - if ( b == NULL ) +int StreamPeerOpenSSL::_bio_destroy(BIO *b) { + if (b == NULL) return 0; - b->ptr = NULL; /* sb_tls_remove() will free it */ + b->ptr = NULL; /* sb_tls_remove() will free it */ b->init = 0; b->flags = 0; return 1; } -int StreamPeerOpenSSL::_bio_read( BIO *b, char *buf, int len ) { +int StreamPeerOpenSSL::_bio_read(BIO *b, char *buf, int len) { - - if ( buf == NULL || len <= 0 ) return 0; + if (buf == NULL || len <= 0) return 0; StreamPeerOpenSSL *sp = (StreamPeerOpenSSL *)b->ptr; - ERR_FAIL_COND_V( sp == NULL, 0); + ERR_FAIL_COND_V(sp == NULL, 0); - BIO_clear_retry_flags( b ); + BIO_clear_retry_flags(b); if (sp->use_blocking) { - Error err = sp->base->get_data((uint8_t*)buf,len); - if (err!=OK) { + Error err = sp->base->get_data((uint8_t *)buf, len); + if (err != OK) { return -1; } @@ -212,12 +201,12 @@ int StreamPeerOpenSSL::_bio_read( BIO *b, char *buf, int len ) { } else { int got; - Error err = sp->base->get_partial_data((uint8_t*)buf,len,got); - if (err!=OK) { + Error err = sp->base->get_partial_data((uint8_t *)buf, len, got); + if (err != OK) { return -1; } - if (got==0) { - BIO_set_retry_read( b ); + if (got == 0) { + BIO_set_retry_read(b); } return got; } @@ -226,19 +215,19 @@ int StreamPeerOpenSSL::_bio_read( BIO *b, char *buf, int len ) { return 0; } -int StreamPeerOpenSSL::_bio_write( BIO *b, const char *buf, int len ) { +int StreamPeerOpenSSL::_bio_write(BIO *b, const char *buf, int len) { - if ( buf == NULL || len <= 0 ) return 0; + if (buf == NULL || len <= 0) return 0; StreamPeerOpenSSL *sp = (StreamPeerOpenSSL *)b->ptr; - ERR_FAIL_COND_V( sp == NULL, 0); + ERR_FAIL_COND_V(sp == NULL, 0); - BIO_clear_retry_flags( b ); + BIO_clear_retry_flags(b); if (sp->use_blocking) { - Error err = sp->base->put_data((const uint8_t*)buf,len); - if (err!=OK) { + Error err = sp->base->put_data((const uint8_t *)buf, len); + if (err != OK) { return -1; } @@ -246,43 +235,39 @@ int StreamPeerOpenSSL::_bio_write( BIO *b, const char *buf, int len ) { } else { int sent; - Error err = sp->base->put_partial_data((const uint8_t*)buf,len,sent); - if (err!=OK) { + Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent); + if (err != OK) { return -1; } - if (sent==0) { - BIO_set_retry_write( b ); + if (sent == 0) { + BIO_set_retry_write(b); } return sent; - } //unreachable return 0; } -long StreamPeerOpenSSL::_bio_ctrl( BIO *b, int cmd, long num, void *ptr ) -{ - if ( cmd == BIO_CTRL_FLUSH ) { +long StreamPeerOpenSSL::_bio_ctrl(BIO *b, int cmd, long num, void *ptr) { + if (cmd == BIO_CTRL_FLUSH) { /* The OpenSSL library needs this */ return 1; } return 0; } -int StreamPeerOpenSSL::_bio_gets( BIO *b, char *buf, int len ) -{ +int StreamPeerOpenSSL::_bio_gets(BIO *b, char *buf, int len) { return -1; } -int StreamPeerOpenSSL::_bio_puts( BIO *b, const char *str ) -{ - return _bio_write( b, str, strlen( str ) ); +int StreamPeerOpenSSL::_bio_puts(BIO *b, const char *str) { + return _bio_write(b, str, strlen(str)); } BIO_METHOD StreamPeerOpenSSL::_bio_method = { /* it's a source/sink BIO */ - ( 100 | 0x400 ), + (100 | 0x400), "streampeer glue", _bio_write, _bio_read, @@ -293,35 +278,29 @@ BIO_METHOD StreamPeerOpenSSL::_bio_method = { _bio_destroy }; -Error StreamPeerOpenSSL::connect(Ref<StreamPeer> p_base, bool p_validate_certs, const String& p_for_hostname) { +Error StreamPeerOpenSSL::connect(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) { if (connected) disconnect(); - - hostname=p_for_hostname; - status=STATUS_DISCONNECTED; + hostname = p_for_hostname; + status = STATUS_DISCONNECTED; // Set up a SSL_CTX object, which will tell our BIO object how to do its work ctx = SSL_CTX_new(SSLv23_client_method()); - base=p_base; - validate_certs=p_validate_certs; - validate_hostname=p_for_hostname!=""; - - - + base = p_base; + validate_certs = p_validate_certs; + validate_hostname = p_for_hostname != ""; if (p_validate_certs) { - if (certs.size()) { //yay for undocumented OpenSSL functions X509_STORE *store = SSL_CTX_get_cert_store(ctx); - for(int i=0;i<certs.size();i++) { - - X509_STORE_add_cert(store,certs[i]); + for (int i = 0; i < certs.size(); i++) { + X509_STORE_add_cert(store, certs[i]); } #if 0 const unsigned char *in=(const unsigned char *)certs.ptr(); @@ -343,7 +322,6 @@ Error StreamPeerOpenSSL::connect(Ref<StreamPeer> p_base, bool p_validate_certs, //int res = SSL_CTX_load_verify_locations(ctx,"/etc/ssl/certs/ca-certificates.crt",NULL); //print_line("verify locations res: "+itos(res)); - /* Ask OpenSSL to verify the server certificate. Note that this * does NOT include verifying that the hostname is correct. * So, by itself, this means anyone with any legitimate @@ -366,183 +344,176 @@ Error StreamPeerOpenSSL::connect(Ref<StreamPeer> p_base, bool p_validate_certs, * OpenSSL's built-in routine which would have been called if * we hadn't set the callback. Therefore, we're just * "wrapping" OpenSSL's routine, not replacing it. */ - SSL_CTX_set_cert_verify_callback (ctx, _cert_verify_callback,this); + SSL_CTX_set_cert_verify_callback(ctx, _cert_verify_callback, this); //Let the verify_callback catch the verify_depth error so that we get an appropriate error in the logfile. (??) - SSL_CTX_set_verify_depth(ctx,max_cert_chain_depth + 1); - + SSL_CTX_set_verify_depth(ctx, max_cert_chain_depth + 1); } - - - - - ssl = SSL_new( ctx ); - bio = BIO_new( &_bio_method ); + ssl = SSL_new(ctx); + bio = BIO_new(&_bio_method); bio->ptr = this; - SSL_set_bio( ssl, bio, bio ); + SSL_set_bio(ssl, bio, bio); - if (p_for_hostname!=String()) { - SSL_set_tlsext_host_name(ssl,p_for_hostname.utf8().get_data()); + if (p_for_hostname != String()) { + SSL_set_tlsext_host_name(ssl, p_for_hostname.utf8().get_data()); } - use_blocking=true; // let handshake use blocking + use_blocking = true; // let handshake use blocking // Set the SSL to automatically retry on failure. SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); // Same as before, try to connect. - int result = SSL_connect( ssl ); + int result = SSL_connect(ssl); - print_line("CONNECTION RESULT: "+itos(result)); - if (result<1) { + print_line("CONNECTION RESULT: " + itos(result)); + if (result < 1) { ERR_print_errors_fp(stdout); _print_error(result); } - X509 * peer = SSL_get_peer_certificate(ssl); + X509 *peer = SSL_get_peer_certificate(ssl); if (peer) { bool cert_ok = SSL_get_verify_result(ssl) == X509_V_OK; - print_line("cert_ok: "+itos(cert_ok)); + print_line("cert_ok: " + itos(cert_ok)); - } else if (validate_certs){ - status=STATUS_ERROR_NO_CERTIFICATE; + } else if (validate_certs) { + status = STATUS_ERROR_NO_CERTIFICATE; } - connected=true; - status=STATUS_CONNECTED; + connected = true; + status = STATUS_CONNECTED; return OK; } Error StreamPeerOpenSSL::accept(Ref<StreamPeer> p_base) { - return ERR_UNAVAILABLE; } void StreamPeerOpenSSL::_print_error(int err) { - err = SSL_get_error(ssl,err); - switch(err) { + err = SSL_get_error(ssl, err); + switch (err) { case SSL_ERROR_NONE: ERR_PRINT("NO ERROR: The TLS/SSL I/O operation completed"); break; case SSL_ERROR_ZERO_RETURN: ERR_PRINT("The TLS/SSL connection has been closed."); case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: - ERR_PRINT("The operation did not complete."); break; + ERR_PRINT("The operation did not complete."); + break; case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: - ERR_PRINT("The connect/accept operation did not complete"); break; + ERR_PRINT("The connect/accept operation did not complete"); + break; case SSL_ERROR_WANT_X509_LOOKUP: - ERR_PRINT("The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again."); break; + ERR_PRINT("The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again."); + break; case SSL_ERROR_SYSCALL: - ERR_PRINT("Some I/O error occurred. The OpenSSL error queue may contain more information on the error."); break; + ERR_PRINT("Some I/O error occurred. The OpenSSL error queue may contain more information on the error."); + break; case SSL_ERROR_SSL: - ERR_PRINT("A failure in the SSL library occurred, usually a protocol error."); break; - + ERR_PRINT("A failure in the SSL library occurred, usually a protocol error."); + break; } } -Error StreamPeerOpenSSL::put_data(const uint8_t* p_data,int p_bytes) { +Error StreamPeerOpenSSL::put_data(const uint8_t *p_data, int p_bytes) { - ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED); - while(p_bytes>0) { - int ret = SSL_write(ssl,p_data,p_bytes); - if (ret<=0) { + while (p_bytes > 0) { + int ret = SSL_write(ssl, p_data, p_bytes); + if (ret <= 0) { _print_error(ret); disconnect(); return ERR_CONNECTION_ERROR; } - p_data+=ret; - p_bytes-=ret; + p_data += ret; + p_bytes -= ret; } return OK; - } -Error StreamPeerOpenSSL::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent){ +Error StreamPeerOpenSSL::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) { - ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED); - if (p_bytes==0) + ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED); + if (p_bytes == 0) return OK; - Error err = put_data(p_data,p_bytes); - if (err!=OK) + Error err = put_data(p_data, p_bytes); + if (err != OK) return err; - r_sent=p_bytes; + r_sent = p_bytes; return OK; - } -Error StreamPeerOpenSSL::get_data(uint8_t* p_buffer, int p_bytes){ +Error StreamPeerOpenSSL::get_data(uint8_t *p_buffer, int p_bytes) { - ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED); - while(p_bytes>0) { + while (p_bytes > 0) { - int ret = SSL_read(ssl,p_buffer,p_bytes); - if (ret<=0) { + int ret = SSL_read(ssl, p_buffer, p_bytes); + if (ret <= 0) { _print_error(ret); disconnect(); return ERR_CONNECTION_ERROR; } - p_buffer+=ret; - p_bytes-=ret; + p_buffer += ret; + p_bytes -= ret; } return OK; } -Error StreamPeerOpenSSL::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received){ +Error StreamPeerOpenSSL::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) { - ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED); - if (p_bytes==0) { - r_received=0; + ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED); + if (p_bytes == 0) { + r_received = 0; return OK; } - Error err = get_data(p_buffer,p_bytes); - if (err!=OK) + Error err = get_data(p_buffer, p_bytes); + if (err != OK) return err; - r_received=p_bytes; + r_received = p_bytes; return OK; } int StreamPeerOpenSSL::get_available_bytes() const { - ERR_FAIL_COND_V(!connected,0); + ERR_FAIL_COND_V(!connected, 0); return SSL_pending(ssl); - } StreamPeerOpenSSL::StreamPeerOpenSSL() { - ctx=NULL; - ssl=NULL; - bio=NULL; - connected=false; - use_blocking=true; //might be improved int the future, but for now it always blocks - max_cert_chain_depth=9; - flags=0; + ctx = NULL; + ssl = NULL; + bio = NULL; + connected = false; + use_blocking = true; //might be improved int the future, but for now it always blocks + max_cert_chain_depth = 9; + flags = 0; } void StreamPeerOpenSSL::disconnect() { if (!connected) return; - SSL_shutdown( ssl ); - SSL_free( ssl ); + SSL_shutdown(ssl); + SSL_free(ssl); SSL_CTX_free(ctx); - base=Ref<StreamPeer>(); - connected=false; - validate_certs=false; - validate_hostname=false; - status=STATUS_DISCONNECTED; - - + base = Ref<StreamPeer>(); + connected = false; + validate_certs = false; + validate_hostname = false; + status = STATUS_DISCONNECTED; } StreamPeerOpenSSL::Status StreamPeerOpenSSL::get_status() const { @@ -550,27 +521,24 @@ StreamPeerOpenSSL::Status StreamPeerOpenSSL::get_status() const { return status; } - StreamPeerOpenSSL::~StreamPeerOpenSSL() { disconnect(); } -StreamPeerSSL* StreamPeerOpenSSL::_create_func() { +StreamPeerSSL *StreamPeerOpenSSL::_create_func() { - return memnew( StreamPeerOpenSSL ); + return memnew(StreamPeerOpenSSL); } +Vector<X509 *> StreamPeerOpenSSL::certs; -Vector<X509*> StreamPeerOpenSSL::certs; - - -void StreamPeerOpenSSL::_load_certs(const ByteArray& p_array) { +void StreamPeerOpenSSL::_load_certs(const ByteArray &p_array) { ByteArray::Read r = p_array.read(); - BIO* mem = BIO_new(BIO_s_mem()); - BIO_puts(mem,(const char*)r.ptr()); - while(true) { - X509*cert = PEM_read_bio_X509(mem, NULL, 0, NULL); + BIO *mem = BIO_new(BIO_s_mem()); + BIO_puts(mem, (const char *)r.ptr()); + while (true) { + X509 *cert = PEM_read_bio_X509(mem, NULL, 0, NULL); if (!cert) break; certs.push_back(cert); @@ -580,66 +548,62 @@ void StreamPeerOpenSSL::_load_certs(const ByteArray& p_array) { void StreamPeerOpenSSL::initialize_ssl() { - available=true; + available = true; - load_certs_func=_load_certs; + load_certs_func = _load_certs; - _create=_create_func; + _create = _create_func; CRYPTO_malloc_init(); // Initialize malloc, free, etc for OpenSSL's use SSL_library_init(); // Initialize OpenSSL's SSL libraries SSL_load_error_strings(); // Load SSL error strings ERR_load_BIO_strings(); // Load BIO error strings OpenSSL_add_all_algorithms(); // Load all available encryption algorithms - String certs_path =GLOBAL_DEF("ssl/certificates",""); - Globals::get_singleton()->set_custom_property_info("ssl/certificates",PropertyInfo(Variant::STRING,"ssl/certificates",PROPERTY_HINT_FILE,"*.crt")); - if (certs_path!="") { - - + String certs_path = GLOBAL_DEF("ssl/certificates", ""); + Globals::get_singleton()->set_custom_property_info("ssl/certificates", PropertyInfo(Variant::STRING, "ssl/certificates", PROPERTY_HINT_FILE, "*.crt")); + if (certs_path != "") { - FileAccess *f=FileAccess::open(certs_path,FileAccess::READ); + FileAccess *f = FileAccess::open(certs_path, FileAccess::READ); if (f) { ByteArray arr; int flen = f->get_len(); - arr.resize(flen+1); + arr.resize(flen + 1); { ByteArray::Write w = arr.write(); - f->get_buffer(w.ptr(),flen); - w[flen]=0; //end f string + f->get_buffer(w.ptr(), flen); + w[flen] = 0; //end f string } memdelete(f); _load_certs(arr); - print_line("Loaded certs from '"+certs_path+"': "+itos(certs.size())); + print_line("Loaded certs from '" + certs_path + "': " + itos(certs.size())); } } - String config_path =GLOBAL_DEF("ssl/config",""); - Globals::get_singleton()->set_custom_property_info("ssl/config",PropertyInfo(Variant::STRING,"ssl/config",PROPERTY_HINT_FILE,"*.cnf")); - if (config_path!="") { + String config_path = GLOBAL_DEF("ssl/config", ""); + Globals::get_singleton()->set_custom_property_info("ssl/config", PropertyInfo(Variant::STRING, "ssl/config", PROPERTY_HINT_FILE, "*.cnf")); + if (config_path != "") { Vector<uint8_t> data = FileAccess::get_file_as_array(config_path); if (data.size()) { data.push_back(0); - BIO* mem = BIO_new(BIO_s_mem()); - BIO_puts(mem,(const char*) data.ptr()); + BIO *mem = BIO_new(BIO_s_mem()); + BIO_puts(mem, (const char *)data.ptr()); - while(true) { - X509*cert = PEM_read_bio_X509(mem, NULL, 0, NULL); + while (true) { + X509 *cert = PEM_read_bio_X509(mem, NULL, 0, NULL); if (!cert) break; certs.push_back(cert); } BIO_free(mem); } - print_line("Loaded certs from '"+certs_path+"': "+itos(certs.size())); - + print_line("Loaded certs from '" + certs_path + "': " + itos(certs.size())); } - } -void StreamPeerOpenSSL::finalize_ssl(){ +void StreamPeerOpenSSL::finalize_ssl() { - for(int i=0;i<certs.size();i++) { + for (int i = 0; i < certs.size(); i++) { X509_free(certs[i]); } certs.clear(); diff --git a/modules/openssl/stream_peer_openssl.h b/modules/openssl/stream_peer_openssl.h index b3777959a..b2abd4b08 100644 --- a/modules/openssl/stream_peer_openssl.h +++ b/modules/openssl/stream_peer_openssl.h @@ -29,26 +29,26 @@ #ifndef STREAM_PEER_OPEN_SSL_H #define STREAM_PEER_OPEN_SSL_H -#include <stdio.h> // If you don't know what this is for stop reading now. -#include "io/stream_peer_ssl.h" +#include "curl_hostcheck.h" #include "globals.h" +#include "io/stream_peer_ssl.h" #include "os/file_access.h" -#include "curl_hostcheck.h" +#include <stdio.h> // If you don't know what this is for stop reading now. #include <openssl/bio.h> // BIO objects for I/O -#include <openssl/ssl.h> // SSL and SSL_CTX for SSL connections #include <openssl/err.h> // Error reporting +#include <openssl/ssl.h> // SSL and SSL_CTX for SSL connections #include <openssl/x509v3.h> class StreamPeerOpenSSL : public StreamPeerSSL { private: - static int _bio_create( BIO *b ); - static int _bio_destroy( BIO *b ); - static int _bio_read( BIO *b, char *buf, int len ); - static int _bio_write( BIO *b, const char *buf, int len ); - static long _bio_ctrl( BIO *b, int cmd, long num, void *ptr ); - static int _bio_gets( BIO *b, char *buf, int len ); - static int _bio_puts( BIO *b, const char *str ); + static int _bio_create(BIO *b); + static int _bio_destroy(BIO *b); + static int _bio_read(BIO *b, char *buf, int len); + static int _bio_write(BIO *b, const char *buf, int len); + static long _bio_ctrl(BIO *b, int cmd, long num, void *ptr); + static int _bio_gets(BIO *b, char *buf, int len); + static int _bio_puts(BIO *b, const char *str); static BIO_METHOD _bio_method; @@ -56,16 +56,14 @@ private: static Error _match_common_name(const char *hostname, const X509 *server_cert); static Error _match_subject_alternative_name(const char *hostname, const X509 *server_cert); - static int _cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg); - Status status; String hostname; int max_cert_chain_depth; - SSL_CTX* ctx; - SSL* ssl; - BIO* bio; + SSL_CTX *ctx; + SSL *ssl; + BIO *bio; bool connected; int flags; bool use_blocking; @@ -74,28 +72,28 @@ private: Ref<StreamPeer> base; - static StreamPeerSSL* _create_func(); + static StreamPeerSSL *_create_func(); void _print_error(int err); - static Vector<X509*> certs; + static Vector<X509 *> certs; + + static void _load_certs(const ByteArray &p_array); - static void _load_certs(const ByteArray& p_array); protected: static void _bind_methods(); -public: - +public: virtual Error accept(Ref<StreamPeer> p_base); - virtual Error connect(Ref<StreamPeer> p_base,bool p_validate_certs=false,const String& p_for_hostname=String()); + virtual Error connect(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()); virtual Status get_status() const; virtual void disconnect(); - virtual Error put_data(const uint8_t* p_data,int p_bytes); - virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent); + virtual Error put_data(const uint8_t *p_data, int p_bytes); + virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent); - virtual Error get_data(uint8_t* p_buffer, int p_bytes); - virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received); + virtual Error get_data(uint8_t *p_buffer, int p_bytes); + virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received); virtual int get_available_bytes() const; diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp index f438dde68..6893be09c 100644 --- a/modules/opus/audio_stream_opus.cpp +++ b/modules/opus/audio_stream_opus.cpp @@ -30,32 +30,32 @@ /*************************************************************************/ #include "audio_stream_opus.h" -const float AudioStreamPlaybackOpus::osrate=48000.0f; +const float AudioStreamPlaybackOpus::osrate = 48000.0f; int AudioStreamPlaybackOpus::_op_read_func(void *_stream, unsigned char *_ptr, int _nbytes) { - FileAccess *fa=(FileAccess*)_stream; + FileAccess *fa = (FileAccess *)_stream; - if(fa->eof_reached()) + if (fa->eof_reached()) return 0; - uint8_t *dst = (uint8_t*)_ptr; + uint8_t *dst = (uint8_t *)_ptr; int read = fa->get_buffer(dst, _nbytes); return read; } -int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, int _whence){ +int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, int _whence) { #ifdef SEEK_SET - FileAccess *fa=(FileAccess*)_stream; + FileAccess *fa = (FileAccess *)_stream; switch (_whence) { case SEEK_SET: { fa->seek(_offset); } break; case SEEK_CUR: { - fa->seek(fa->get_pos()+_offset); + fa->seek(fa->get_pos() + _offset); } break; case SEEK_END: { fa->seek_end(_offset); @@ -64,7 +64,7 @@ int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, in ERR_PRINT("BUG, wtf was whence set to?\n"); } } - int ret=fa->eof_reached()?-1:0; + int ret = fa->eof_reached() ? -1 : 0; return ret; #else return -1; // no seeking @@ -74,97 +74,100 @@ int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, in int AudioStreamPlaybackOpus::_op_close_func(void *_stream) { if (!_stream) return 0; - FileAccess *fa=(FileAccess*)_stream; + FileAccess *fa = (FileAccess *)_stream; if (fa->is_open()) fa->close(); return 0; } opus_int64 AudioStreamPlaybackOpus::_op_tell_func(void *_stream) { - FileAccess *_fa = (FileAccess*)_stream; + FileAccess *_fa = (FileAccess *)_stream; return (opus_int64)_fa->get_pos(); } void AudioStreamPlaybackOpus::_clear_stream() { - if(!stream_loaded) + if (!stream_loaded) return; op_free(opus_file); _close_file(); - stream_loaded=false; - stream_channels=1; - playing=false; + stream_loaded = false; + stream_channels = 1; + playing = false; } void AudioStreamPlaybackOpus::_close_file() { if (f) { memdelete(f); - f=NULL; + f = NULL; } } Error AudioStreamPlaybackOpus::_load_stream() { - ERR_FAIL_COND_V(!stream_valid,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED); _clear_stream(); - if (file=="") + if (file == "") return ERR_INVALID_DATA; Error err; - f=FileAccess::open(file,FileAccess::READ,&err); + f = FileAccess::open(file, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V( err, err ); + ERR_FAIL_COND_V(err, err); } int _err = 0; - opus_file = op_open_callbacks(f,&_op_callbacks,NULL,0,&_err); + opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err); switch (_err) { case OP_EREAD: { // - Can't read the file. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CANT_READ ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CANT_READ); } break; case OP_EVERSION: // - Unrecognized version number. case OP_ENOTFORMAT: // - Stream is not Opus data. - case OP_EIMPL : { // - Stream used non-implemented feature. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_UNRECOGNIZED ); + case OP_EIMPL: { // - Stream used non-implemented feature. + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } break; case OP_EBADLINK: // - Failed to find old data after seeking. case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks. case OP_EBADHEADER: { // - Invalid or mising Opus bitstream header. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CORRUPT ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CORRUPT); } break; case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_BUG ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_BUG); } break; } - repeats=0; - stream_loaded=true; - + repeats = 0; + stream_loaded = true; return OK; } AudioStreamPlaybackOpus::AudioStreamPlaybackOpus() { - loops=false; - playing=false; + loops = false; + playing = false; f = NULL; - stream_loaded=false; - stream_valid=false; - repeats=0; - paused=true; - stream_channels=0; - current_section=0; - length=0; - loop_restart_time=0; - pre_skip=0; + stream_loaded = false; + stream_valid = false; + repeats = 0; + paused = true; + stream_channels = 0; + current_section = 0; + length = 0; + loop_restart_time = 0; + pre_skip = 0; _op_callbacks.read = _op_read_func; _op_callbacks.seek = _op_seek_func; @@ -173,59 +176,62 @@ AudioStreamPlaybackOpus::AudioStreamPlaybackOpus() { } Error AudioStreamPlaybackOpus::set_file(const String &p_file) { - file=p_file; - stream_valid=false; + file = p_file; + stream_valid = false; Error err; - f=FileAccess::open(file,FileAccess::READ,&err); + f = FileAccess::open(file, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V( err, err ); + ERR_FAIL_COND_V(err, err); } int _err; - opus_file = op_open_callbacks(f,&_op_callbacks,NULL,0,&_err); + opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err); switch (_err) { case OP_EREAD: { // - Can't read the file. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CANT_READ ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CANT_READ); } break; case OP_EVERSION: // - Unrecognized version number. case OP_ENOTFORMAT: // - Stream is not Opus data. - case OP_EIMPL : { // - Stream used non-implemented feature. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_UNRECOGNIZED ); + case OP_EIMPL: { // - Stream used non-implemented feature. + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } break; case OP_EBADLINK: // - Failed to find old data after seeking. case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks. case OP_EBADHEADER: { // - Invalid or mising Opus bitstream header. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CORRUPT ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CORRUPT); } break; case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_BUG ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_BUG); } break; } - const OpusHead *oinfo = op_head(opus_file,-1); + const OpusHead *oinfo = op_head(opus_file, -1); - stream_channels=oinfo->channel_count; - pre_skip=oinfo->pre_skip; - frames_mixed=pre_skip; - ogg_int64_t len = op_pcm_total(opus_file,-1); - if(len < 0) { + stream_channels = oinfo->channel_count; + pre_skip = oinfo->pre_skip; + frames_mixed = pre_skip; + ogg_int64_t len = op_pcm_total(opus_file, -1); + if (len < 0) { length = 0; } else { - length=(len/osrate); + length = (len / osrate); } op_free(opus_file); memdelete(f); - f=NULL; - stream_valid=true; - + f = NULL; + stream_valid = true; return OK; } @@ -234,102 +240,100 @@ void AudioStreamPlaybackOpus::play(float p_from) { if (playing) stop(); - if (_load_stream()!=OK) + if (_load_stream() != OK) return; - frames_mixed=pre_skip; - playing=true; - if (p_from>0) { + frames_mixed = pre_skip; + playing = true; + if (p_from > 0) { seek_pos(p_from); } } void AudioStreamPlaybackOpus::stop() { _clear_stream(); - playing=false; + playing = false; } void AudioStreamPlaybackOpus::seek_pos(float p_time) { - if(!playing) return; + if (!playing) return; ogg_int64_t pcm_offset = (ogg_int64_t)(p_time * osrate); - bool ok = op_pcm_seek(opus_file,pcm_offset)==0; - if(!ok) { + bool ok = op_pcm_seek(opus_file, pcm_offset) == 0; + if (!ok) { ERR_PRINT("Seek time over stream size."); return; } - frames_mixed=osrate*p_time; + frames_mixed = osrate * p_time; } -int AudioStreamPlaybackOpus::mix(int16_t* p_bufer,int p_frames) { +int AudioStreamPlaybackOpus::mix(int16_t *p_bufer, int p_frames) { if (!playing) return 0; - int total=p_frames; + int total = p_frames; while (true) { int todo = p_frames; - if (todo==0 || todo<MIN_MIX) { + if (todo == 0 || todo < MIN_MIX) { break; } - int ret=op_read(opus_file,(opus_int16*)p_bufer,todo*stream_channels,¤t_section); - if (ret<0) { + int ret = op_read(opus_file, (opus_int16 *)p_bufer, todo * stream_channels, ¤t_section); + if (ret < 0) { playing = false; - ERR_EXPLAIN("Error reading Opus File: "+file); - ERR_BREAK(ret<0); - } else if (ret==0) { // end of song, reload? + ERR_EXPLAIN("Error reading Opus File: " + file); + ERR_BREAK(ret < 0); + } else if (ret == 0) { // end of song, reload? op_free(opus_file); _close_file(); - f=FileAccess::open(file,FileAccess::READ); + f = FileAccess::open(file, FileAccess::READ); int errv = 0; - opus_file = op_open_callbacks(f,&_op_callbacks,NULL,0,&errv); - if (errv!=0) { - playing=false; + opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &errv); + if (errv != 0) { + playing = false; break; // :( } if (!has_loop()) { - playing=false; - repeats=1; + playing = false; + repeats = 1; break; } if (loop_restart_time) { - bool ok = op_pcm_seek(opus_file, (loop_restart_time*osrate)+pre_skip)==0; + bool ok = op_pcm_seek(opus_file, (loop_restart_time * osrate) + pre_skip) == 0; if (!ok) { - playing=false; + playing = false; ERR_PRINT("loop restart time rejected") } - frames_mixed=(loop_restart_time*osrate)+pre_skip; + frames_mixed = (loop_restart_time * osrate) + pre_skip; } else { - frames_mixed=pre_skip; + frames_mixed = pre_skip; } repeats++; continue; - } - stream_channels=op_head(opus_file,current_section)->channel_count; - - frames_mixed+=ret; + stream_channels = op_head(opus_file, current_section)->channel_count; - p_bufer+=ret*stream_channels; - p_frames-=ret; + frames_mixed += ret; + p_bufer += ret * stream_channels; + p_frames -= ret; } - return total-p_frames; + return total - p_frames; } float AudioStreamPlaybackOpus::get_length() const { - if(!stream_loaded) { - if(const_cast<AudioStreamPlaybackOpus*>(this)->_load_stream() != OK) + if (!stream_loaded) { + if (const_cast<AudioStreamPlaybackOpus *>(this)->_load_stream() != OK) return 0; } return length; @@ -339,7 +343,7 @@ float AudioStreamPlaybackOpus::get_pos() const { int32_t frames = int32_t(frames_mixed); if (frames < 0) - frames=0; + frames = 0; return double(frames) / osrate; } @@ -351,9 +355,9 @@ AudioStreamPlaybackOpus::~AudioStreamPlaybackOpus() { _clear_stream(); } -RES ResourceFormatLoaderAudioStreamOpus::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderAudioStreamOpus::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=OK; + *r_error = OK; AudioStreamOpus *opus_stream = memnew(AudioStreamOpus); opus_stream->set_file(p_path); @@ -366,11 +370,11 @@ void ResourceFormatLoaderAudioStreamOpus::get_recognized_extensions(List<String> } String ResourceFormatLoaderAudioStreamOpus::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="opus") + if (p_path.extension().to_lower() == "opus") return "AudioStreamOpus"; return ""; } -bool ResourceFormatLoaderAudioStreamOpus::handles_type(const String& p_type) const { - return (p_type=="AudioStream" || p_type=="AudioStreamOpus"); +bool ResourceFormatLoaderAudioStreamOpus::handles_type(const String &p_type) const { + return (p_type == "AudioStream" || p_type == "AudioStreamOpus"); } diff --git a/modules/opus/audio_stream_opus.h b/modules/opus/audio_stream_opus.h index 68e15f188..1ae3ead3c 100644 --- a/modules/opus/audio_stream_opus.h +++ b/modules/opus/audio_stream_opus.h @@ -40,10 +40,10 @@ class AudioStreamPlaybackOpus : public AudioStreamPlayback { - OBJ_TYPE(AudioStreamPlaybackOpus,AudioStreamPlayback) + OBJ_TYPE(AudioStreamPlaybackOpus, AudioStreamPlayback) enum { - MIN_MIX=1024 + MIN_MIX = 1024 }; FileAccess *f; @@ -78,19 +78,19 @@ class AudioStreamPlaybackOpus : public AudioStreamPlayback { float loop_restart_time; public: - Error set_file(const String& p_file); + Error set_file(const String &p_file); - virtual void play(float p_from=0); + virtual void play(float p_from = 0); virtual void stop(); virtual bool is_playing() const { return playing; } - virtual void set_loop_restart_time(float p_time) { loop_restart_time=p_time; } + virtual void set_loop_restart_time(float p_time) { loop_restart_time = p_time; } - virtual void set_paused(bool p_paused) { paused=p_paused; } + virtual void set_paused(bool p_paused) { paused = p_paused; } virtual bool is_paused() const { return paused; } - virtual void set_loop(bool p_enable) { loops=p_enable; } - virtual bool has_loop() const {return loops; } + virtual void set_loop(bool p_enable) { loops = p_enable; } + virtual bool has_loop() const { return loops; } virtual float get_length() const; @@ -106,35 +106,33 @@ public: virtual int get_minimum_buffer_size() const; - virtual int mix(int16_t* p_bufer,int p_frames); + virtual int mix(int16_t *p_bufer, int p_frames); AudioStreamPlaybackOpus(); ~AudioStreamPlaybackOpus(); }; +class AudioStreamOpus : public AudioStream { -class AudioStreamOpus: public AudioStream { - - OBJ_TYPE(AudioStreamOpus,AudioStream) + OBJ_TYPE(AudioStreamOpus, AudioStream) String file; -public: +public: Ref<AudioStreamPlayback> instance_playback() { - Ref<AudioStreamPlaybackOpus> pb = memnew( AudioStreamPlaybackOpus ); + Ref<AudioStreamPlaybackOpus> pb = memnew(AudioStreamPlaybackOpus); pb->set_file(file); return pb; } - void set_file(const String& p_file) { file=p_file; } - + void set_file(const String &p_file) { file = p_file; } }; -class ResourceFormatLoaderAudioStreamOpus: public ResourceFormatLoader { +class ResourceFormatLoaderAudioStreamOpus : public ResourceFormatLoader { public: - 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 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; }; diff --git a/modules/opus/register_types.cpp b/modules/opus/register_types.cpp index 9d9a70799..928784e84 100644 --- a/modules/opus/register_types.cpp +++ b/modules/opus/register_types.cpp @@ -34,12 +34,12 @@ static ResourceFormatLoaderAudioStreamOpus *opus_stream_loader = NULL; void register_opus_types() { - opus_stream_loader = memnew( ResourceFormatLoaderAudioStreamOpus ); + opus_stream_loader = memnew(ResourceFormatLoaderAudioStreamOpus); ResourceLoader::add_resource_format_loader(opus_stream_loader); ObjectTypeDB::register_type<AudioStreamOpus>(); } void unregister_opus_types() { - memdelete( opus_stream_loader ); + memdelete(opus_stream_loader); } diff --git a/modules/pbm/bitmap_loader_pbm.cpp b/modules/pbm/bitmap_loader_pbm.cpp index f9fc19b2c..6e7d989fa 100644 --- a/modules/pbm/bitmap_loader_pbm.cpp +++ b/modules/pbm/bitmap_loader_pbm.cpp @@ -30,30 +30,27 @@ #include "os/file_access.h" #include "scene/resources/bit_mask.h" - -static bool _get_token(FileAccessRef& f,uint8_t &saved,DVector<uint8_t>& r_token,bool p_binary=false,bool p_single_chunk=false) { - +static bool _get_token(FileAccessRef &f, uint8_t &saved, DVector<uint8_t> &r_token, bool p_binary = false, bool p_single_chunk = false) { int token_max = r_token.size(); DVector<uint8_t>::Write w; if (token_max) - w=r_token.write(); - int ofs=0; - bool lf=false; - + w = r_token.write(); + int ofs = 0; + bool lf = false; - while(true) { + while (true) { uint8_t b; if (saved) { - b=saved; - saved=0; + b = saved; + saved = 0; } else { b = f->get_8(); } if (f->eof_reached()) { if (ofs) { - w=DVector<uint8_t>::Write(); + w = DVector<uint8_t>::Write(); r_token.resize(ofs); return true; } else { @@ -61,9 +58,9 @@ static bool _get_token(FileAccessRef& f,uint8_t &saved,DVector<uint8_t>& r_token } } - if (!ofs && !p_binary && b=='#') { + if (!ofs && !p_binary && b == '#') { //skip comment - while(b!='\n') { + while (b != '\n') { if (f->eof_reached()) { return false; } @@ -71,182 +68,165 @@ static bool _get_token(FileAccessRef& f,uint8_t &saved,DVector<uint8_t>& r_token b = f->get_8(); } - lf=true; + lf = true; - } else if (b<=32 && !(p_binary && (ofs || lf))) { + } else if (b <= 32 && !(p_binary && (ofs || lf))) { - if (b=='\n') { - lf=true; + if (b == '\n') { + lf = true; } - if (ofs && !p_single_chunk) { - w=DVector<uint8_t>::Write(); + w = DVector<uint8_t>::Write(); r_token.resize(ofs); - saved=b; + saved = b; return true; } } else { - bool resized=false; - while (ofs>=token_max) { + bool resized = false; + while (ofs >= token_max) { if (token_max) - token_max<<=1; + token_max <<= 1; else - token_max=1; - resized=true; + token_max = 1; + resized = true; } if (resized) { - w=DVector<uint8_t>::Write(); + w = DVector<uint8_t>::Write(); r_token.resize(token_max); - w=r_token.write(); + w = r_token.write(); } - w[ofs++]=b; + w[ofs++] = b; } } return false; } -static int _get_number_from_token(DVector<uint8_t>& r_token) { +static int _get_number_from_token(DVector<uint8_t> &r_token) { int len = r_token.size(); DVector<uint8_t>::Read r = r_token.read(); - return String::to_int((const char*)r.ptr(),len); - + return String::to_int((const char *)r.ptr(), len); } +RES ResourceFormatPBM::load(const String &p_path, const String &p_original_path, Error *r_error) { -RES ResourceFormatPBM::load(const String &p_path,const String& p_original_path,Error *r_error) { - -#define _RETURN(m_err)\ -{\ - if (r_error)\ - *r_error=m_err;\ - ERR_FAIL_V(RES());\ -} - +#define _RETURN(m_err) \ + { \ + if (r_error) \ + *r_error = m_err; \ + ERR_FAIL_V(RES()); \ + } - FileAccessRef f=FileAccess::open(p_path,FileAccess::READ); - uint8_t saved=0; + FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); + uint8_t saved = 0; if (!f) _RETURN(ERR_CANT_OPEN); DVector<uint8_t> token; - if (!_get_token(f,saved,token)) { + if (!_get_token(f, saved, token)) { _RETURN(ERR_PARSE_ERROR); } - if (token.size()!=2) { + if (token.size() != 2) { _RETURN(ERR_FILE_CORRUPT); } - if (token[0]!='P') { + if (token[0] != 'P') { _RETURN(ERR_FILE_CORRUPT); } - if (token[1]!='1' && token[1]!='4') { + if (token[1] != '1' && token[1] != '4') { _RETURN(ERR_FILE_CORRUPT); } - bool bits = token[1]=='4'; + bool bits = token[1] == '4'; - if (!_get_token(f,saved,token)) { + if (!_get_token(f, saved, token)) { _RETURN(ERR_PARSE_ERROR); } int width = _get_number_from_token(token); - if (width<=0) { + if (width <= 0) { _RETURN(ERR_FILE_CORRUPT); } - - if (!_get_token(f,saved,token)) { + if (!_get_token(f, saved, token)) { _RETURN(ERR_PARSE_ERROR); } int height = _get_number_from_token(token); - if (height<=0) { + if (height <= 0) { _RETURN(ERR_FILE_CORRUPT); } - Ref<BitMap> bm; bm.instance(); - bm->create(Size2i(width,height)); + bm->create(Size2i(width, height)); if (!bits) { - int required_bytes = width*height; - if (!_get_token(f,saved,token,false,true)) { + int required_bytes = width * height; + if (!_get_token(f, saved, token, false, true)) { _RETURN(ERR_PARSE_ERROR); } - if (token.size()<required_bytes) { + if (token.size() < required_bytes) { _RETURN(ERR_FILE_CORRUPT); } - DVector<uint8_t>::Read r=token.read(); - - for(int i=0;i<height;i++) { - for(int j=0;j<width;j++) { + DVector<uint8_t>::Read r = token.read(); + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { - char num = r[i*width+j]; - bm->set_bit(Point2i(j,i),num=='0'); + char num = r[i * width + j]; + bm->set_bit(Point2i(j, i), num == '0'); } - } - - } else { //a single, entire token of bits! - if (!_get_token(f,saved,token,true)) { + if (!_get_token(f, saved, token, true)) { _RETURN(ERR_PARSE_ERROR); } - int required_bytes = Math::ceil((width*height)/8.0); - if (token.size()<required_bytes) { + int required_bytes = Math::ceil((width * height) / 8.0); + if (token.size() < required_bytes) { _RETURN(ERR_FILE_CORRUPT); } - DVector<uint8_t>::Read r=token.read(); + DVector<uint8_t>::Read r = token.read(); int bitwidth = width; if (bitwidth % 8) - bitwidth+=8-(bitwidth%8); + bitwidth += 8 - (bitwidth % 8); - 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++) { - int ofs = bitwidth*i+j; + int ofs = bitwidth * i + j; - uint8_t byte = r[ofs/8]; - bool bit = (byte>>(7-(ofs%8)))&1; - - bm->set_bit(Point2i(j,i),!bit); + uint8_t byte = r[ofs / 8]; + bool bit = (byte >> (7 - (ofs % 8))) & 1; + bm->set_bit(Point2i(j, i), !bit); } - } - } return bm; - - } void ResourceFormatPBM::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("pbm"); } -bool ResourceFormatPBM::handles_type(const String& p_type) const { - return p_type=="BitMap"; +bool ResourceFormatPBM::handles_type(const String &p_type) const { + return p_type == "BitMap"; } String ResourceFormatPBM::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="pbm") + if (p_path.extension().to_lower() == "pbm") return "BitMap"; return ""; } - - diff --git a/modules/pbm/bitmap_loader_pbm.h b/modules/pbm/bitmap_loader_pbm.h index b60b38fcc..5e5062f43 100644 --- a/modules/pbm/bitmap_loader_pbm.h +++ b/modules/pbm/bitmap_loader_pbm.h @@ -36,15 +36,11 @@ */ class ResourceFormatPBM : public ResourceFormatLoader { - public: - - 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 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; }; - - #endif diff --git a/modules/pbm/register_types.cpp b/modules/pbm/register_types.cpp index 0dd39ce1e..abfc08c90 100644 --- a/modules/pbm/register_types.cpp +++ b/modules/pbm/register_types.cpp @@ -30,15 +30,15 @@ #include "bitmap_loader_pbm.h" -static ResourceFormatPBM * pbm_loader = NULL; +static ResourceFormatPBM *pbm_loader = NULL; void register_pbm_types() { - pbm_loader = memnew( ResourceFormatPBM ); + pbm_loader = memnew(ResourceFormatPBM); ResourceLoader::add_resource_format_loader(pbm_loader); } void unregister_pbm_types() { - memdelete( pbm_loader ); + memdelete(pbm_loader); } diff --git a/modules/pvr/register_types.cpp b/modules/pvr/register_types.cpp index 2464e7898..76fe7970d 100644 --- a/modules/pvr/register_types.cpp +++ b/modules/pvr/register_types.cpp @@ -34,7 +34,7 @@ static ResourceFormatPVR *resource_loader_pvr = NULL; void register_pvr_types() { - resource_loader_pvr = memnew( ResourceFormatPVR ); + resource_loader_pvr = memnew(ResourceFormatPVR); ResourceLoader::add_resource_format_loader(resource_loader_pvr); } diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp index 6201a9235..b1ac913a1 100644 --- a/modules/pvr/texture_loader_pvr.cpp +++ b/modules/pvr/texture_loader_pvr.cpp @@ -27,49 +27,47 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "texture_loader_pvr.h" -#include "os/file_access.h" -#include <string.h> #include "PvrTcEncoder.h" #include "RgbaBitmap.h" +#include "os/file_access.h" +#include <string.h> -static void _pvrtc_decompress(Image* p_img); +static void _pvrtc_decompress(Image *p_img); enum PVRFLags { - PVR_HAS_MIPMAPS=0x00000100, - PVR_TWIDDLED=0x00000200, - PVR_NORMAL_MAP=0x00000400, - PVR_BORDER=0x00000800, - PVR_CUBE_MAP=0x00001000, - PVR_FALSE_MIPMAPS=0x00002000, - PVR_VOLUME_TEXTURES=0x00004000, - PVR_HAS_ALPHA=0x00008000, - PVR_VFLIP=0x00010000 + PVR_HAS_MIPMAPS = 0x00000100, + PVR_TWIDDLED = 0x00000200, + PVR_NORMAL_MAP = 0x00000400, + PVR_BORDER = 0x00000800, + PVR_CUBE_MAP = 0x00001000, + PVR_FALSE_MIPMAPS = 0x00002000, + PVR_VOLUME_TEXTURES = 0x00004000, + PVR_HAS_ALPHA = 0x00008000, + PVR_VFLIP = 0x00010000 }; - - -RES ResourceFormatPVR::load(const String &p_path,const String& p_original_path,Error *r_error) { +RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return RES(); FileAccessRef faref(f); - ERR_FAIL_COND_V(err,RES()); + ERR_FAIL_COND_V(err, RES()); if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; uint32_t hsize = f->get_32(); - ERR_FAIL_COND_V(hsize!=52,RES()); + ERR_FAIL_COND_V(hsize != 52, RES()); uint32_t height = f->get_32(); uint32_t width = f->get_32(); uint32_t mipmaps = f->get_32(); @@ -80,12 +78,12 @@ RES ResourceFormatPVR::load(const String &p_path,const String& p_original_path,E uint32_t gmask = f->get_32(); uint32_t bmask = f->get_32(); uint32_t amask = f->get_32(); - uint8_t pvrid[5]={0,0,0,0,0}; - f->get_buffer(pvrid,4); - ERR_FAIL_COND_V(String((char*)pvrid)!="PVR!",RES()); + uint8_t pvrid[5] = { 0, 0, 0, 0, 0 }; + f->get_buffer(pvrid, 4); + ERR_FAIL_COND_V(String((char *)pvrid) != "PVR!", RES()); uint32_t surfcount = f->get_32(); -/* + /* print_line("height: "+itos(height)); print_line("width: "+itos(width)); print_line("mipmaps: "+itos(mipmaps)); @@ -102,149 +100,144 @@ RES ResourceFormatPVR::load(const String &p_path,const String& p_original_path,E DVector<uint8_t> data; data.resize(surfsize); - ERR_FAIL_COND_V(data.size()==0,RES()); - + ERR_FAIL_COND_V(data.size() == 0, RES()); DVector<uint8_t>::Write w = data.write(); - f->get_buffer(&w[0],surfsize); + f->get_buffer(&w[0], surfsize); err = f->get_error(); - ERR_FAIL_COND_V(err!=OK,RES()); - - Image::Format format=Image::FORMAT_MAX; + ERR_FAIL_COND_V(err != OK, RES()); + Image::Format format = Image::FORMAT_MAX; - switch(flags&0xFF) { + switch (flags & 0xFF) { case 0x18: - case 0xC: format=(flags&PVR_HAS_ALPHA)?Image::FORMAT_PVRTC2_ALPHA:Image::FORMAT_PVRTC2; break; + case 0xC: format = (flags & PVR_HAS_ALPHA) ? Image::FORMAT_PVRTC2_ALPHA : Image::FORMAT_PVRTC2; break; case 0x19: - case 0xD: format=(flags&PVR_HAS_ALPHA)?Image::FORMAT_PVRTC4_ALPHA:Image::FORMAT_PVRTC4; break; + case 0xD: format = (flags & PVR_HAS_ALPHA) ? Image::FORMAT_PVRTC4_ALPHA : Image::FORMAT_PVRTC4; break; case 0x16: - format=Image::FORMAT_GRAYSCALE; break; + format = Image::FORMAT_GRAYSCALE; + break; case 0x17: - format=Image::FORMAT_GRAYSCALE_ALPHA; break; + format = Image::FORMAT_GRAYSCALE_ALPHA; + break; case 0x20: case 0x80: case 0x81: - format=Image::FORMAT_BC1; break; + format = Image::FORMAT_BC1; + break; case 0x21: case 0x22: case 0x82: case 0x83: - format=Image::FORMAT_BC2; break; + format = Image::FORMAT_BC2; + break; case 0x23: case 0x24: case 0x84: case 0x85: - format=Image::FORMAT_BC3; break; + format = Image::FORMAT_BC3; + break; case 0x4: case 0x15: - format=Image::FORMAT_RGB; break; + format = Image::FORMAT_RGB; + break; case 0x5: case 0x12: - format=Image::FORMAT_RGBA; break; + format = Image::FORMAT_RGBA; + break; case 0x36: - format=Image::FORMAT_ETC; break; + format = Image::FORMAT_ETC; + break; default: - ERR_EXPLAIN("Unsupported format in PVR texture: "+itos(flags&0xFF)); + ERR_EXPLAIN("Unsupported format in PVR texture: " + itos(flags & 0xFF)); ERR_FAIL_V(RES()); - } w = DVector<uint8_t>::Write(); - int tex_flags=Texture::FLAG_FILTER|Texture::FLAG_REPEAT; + int tex_flags = Texture::FLAG_FILTER | Texture::FLAG_REPEAT; if (mipmaps) - tex_flags|=Texture::FLAG_MIPMAPS; - + tex_flags |= Texture::FLAG_MIPMAPS; - print_line("flip: "+itos(flags&PVR_VFLIP)); + print_line("flip: " + itos(flags & PVR_VFLIP)); - Image image(width,height,mipmaps,format,data); - ERR_FAIL_COND_V(image.empty(),RES()); + Image image(width, height, mipmaps, format, data); + ERR_FAIL_COND_V(image.empty(), RES()); - Ref<ImageTexture> texture = memnew( ImageTexture ); - texture->create_from_image(image,tex_flags); + Ref<ImageTexture> texture = memnew(ImageTexture); + texture->create_from_image(image, tex_flags); if (r_error) - *r_error=OK; + *r_error = OK; return texture; - } void ResourceFormatPVR::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("pvr"); } -bool ResourceFormatPVR::handles_type(const String& p_type) const { +bool ResourceFormatPVR::handles_type(const String &p_type) const { - return ObjectTypeDB::is_type(p_type,"Texture"); + return ObjectTypeDB::is_type(p_type, "Texture"); } String ResourceFormatPVR::get_resource_type(const String &p_path) const { - - if (p_path.extension().to_lower()=="pvr") + if (p_path.extension().to_lower() == "pvr") return "Texture"; return ""; } - - -static void _compress_pvrtc4(Image * p_img) { +static void _compress_pvrtc4(Image *p_img) { Image img = *p_img; - bool make_mipmaps=false; - if (img.get_width()%8 || img.get_height()%8) { - make_mipmaps=img.get_mipmaps()>0; - img.resize(img.get_width()+(8-(img.get_width()%8)),img.get_height()+(8-(img.get_height()%8))); + bool make_mipmaps = false; + if (img.get_width() % 8 || img.get_height() % 8) { + make_mipmaps = img.get_mipmaps() > 0; + img.resize(img.get_width() + (8 - (img.get_width() % 8)), img.get_height() + (8 - (img.get_height() % 8))); } img.convert(Image::FORMAT_RGBA); - if (img.get_mipmaps()==0 && make_mipmaps) + if (img.get_mipmaps() == 0 && make_mipmaps) img.generate_mipmaps(); - bool use_alpha=img.detect_alpha(); + bool use_alpha = img.detect_alpha(); Image new_img; - new_img.create(img.get_width(),img.get_height(),true,use_alpha?Image::FORMAT_PVRTC4_ALPHA:Image::FORMAT_PVRTC4); - DVector<uint8_t> data=new_img.get_data(); + new_img.create(img.get_width(), img.get_height(), true, use_alpha ? Image::FORMAT_PVRTC4_ALPHA : Image::FORMAT_PVRTC4); + DVector<uint8_t> data = new_img.get_data(); { - DVector<uint8_t>::Write wr=data.write(); - DVector<uint8_t>::Read r=img.get_data().read(); - + DVector<uint8_t>::Write wr = data.write(); + DVector<uint8_t>::Read r = img.get_data().read(); - for(int i=0;i<=new_img.get_mipmaps();i++) { + for (int i = 0; i <= new_img.get_mipmaps(); i++) { - int ofs,size,w,h; - img.get_mipmap_offset_size_and_dimensions(i,ofs,size,w,h); - Javelin::RgbaBitmap bm(w,h); - copymem(bm.GetData(),&r[ofs],size); + int ofs, size, w, h; + img.get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h); + Javelin::RgbaBitmap bm(w, h); + copymem(bm.GetData(), &r[ofs], size); { Javelin::ColorRgba<unsigned char> *dp = bm.GetData(); - for(int j=0;j<size/4;j++) { - SWAP(dp[j].r,dp[j].b); + for (int j = 0; j < size / 4; j++) { + SWAP(dp[j].r, dp[j].b); } } - new_img.get_mipmap_offset_size_and_dimensions(i,ofs,size,w,h); - Javelin::PvrTcEncoder::EncodeRgba4Bpp(&wr[ofs],bm); + new_img.get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h); + Javelin::PvrTcEncoder::EncodeRgba4Bpp(&wr[ofs], bm); } - } - *p_img = Image(new_img.get_width(),new_img.get_height(),new_img.get_mipmaps(),new_img.get_format(),data); - + *p_img = Image(new_img.get_width(), new_img.get_height(), new_img.get_mipmaps(), new_img.get_format(), data); } ResourceFormatPVR::ResourceFormatPVR() { - - Image::_image_decompress_pvrtc=_pvrtc_decompress; - Image::_image_compress_pvrtc4_func=_compress_pvrtc4; - Image::_image_compress_pvrtc2_func=_compress_pvrtc4; - + Image::_image_decompress_pvrtc = _pvrtc_decompress; + Image::_image_compress_pvrtc4_func = _compress_pvrtc4; + Image::_image_compress_pvrtc2_func = _compress_pvrtc4; } ///////////////////////////////////////////////////////// @@ -253,7 +246,6 @@ ResourceFormatPVR::ResourceFormatPVR() { ///////////////////////////////////////////////////////// - #define PT_INDEX 2 #define BLK_Y_SIZE 4 #define BLK_X_MAX 8 @@ -267,52 +259,48 @@ ResourceFormatPVR::ResourceFormatPVR() { legal coordinate range */ #define LIMIT_COORD(Val, Size, p_tiled) \ - ((p_tiled)? WRAP_COORD((Val), (Size)): CLAMP((Val), 0, (Size)-1)) - + ((p_tiled) ? WRAP_COORD((Val), (Size)) : CLAMP((Val), 0, (Size)-1)) struct PVRTCBlock { //blocks are 64 bits uint32_t data[2]; }; +_FORCE_INLINE_ bool is_po2(uint32_t p_input) { - -_FORCE_INLINE_ bool is_po2( uint32_t p_input ) { - - if( p_input==0 ) - return 0; - uint32_t minus1=p_input- 1; - return ((p_input|minus1)==(p_input^minus1))?1:0; + if (p_input == 0) + return 0; + uint32_t minus1 = p_input - 1; + return ((p_input | minus1) == (p_input ^ minus1)) ? 1 : 0; } - -static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) { +static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) { uint32_t raw_bits[2]; raw_bits[0] = p_block->data[1] & (0xFFFE); raw_bits[1] = p_block->data[1] >> 16; - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - if(raw_bits[i] & (1<<15)) { + if (raw_bits[i] & (1 << 15)) { - p_ab_colors[i][0]= (raw_bits[i] >> 10) & 0x1F; - p_ab_colors[i][1]= (raw_bits[i] >> 5) & 0x1F; - p_ab_colors[i][2]= raw_bits[i] & 0x1F; - if(i==0) - p_ab_colors[0][2]|= p_ab_colors[0][2] >> 4; + p_ab_colors[i][0] = (raw_bits[i] >> 10) & 0x1F; + p_ab_colors[i][1] = (raw_bits[i] >> 5) & 0x1F; + p_ab_colors[i][2] = raw_bits[i] & 0x1F; + if (i == 0) + p_ab_colors[0][2] |= p_ab_colors[0][2] >> 4; p_ab_colors[i][3] = 0xF; } else { - p_ab_colors[i][0] = (raw_bits[i] >> (8-1)) & 0x1E; - p_ab_colors[i][1] = (raw_bits[i] >> (4-1)) & 0x1E; + p_ab_colors[i][0] = (raw_bits[i] >> (8 - 1)) & 0x1E; + p_ab_colors[i][1] = (raw_bits[i] >> (4 - 1)) & 0x1E; p_ab_colors[i][0] |= p_ab_colors[i][0] >> 4; p_ab_colors[i][1] |= p_ab_colors[i][1] >> 4; p_ab_colors[i][2] = (raw_bits[i] & 0xF) << 1; - if(i==0) + if (i == 0) p_ab_colors[0][2] |= p_ab_colors[0][2] >> 3; else p_ab_colors[0][2] |= p_ab_colors[0][2] >> 4; @@ -322,55 +310,52 @@ static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) { } } - -static void unpack_modulations(const PVRTCBlock *p_block, const int p_2bit, int p_modulation[8][16], int p_modulation_modes[8][16], int p_x, int p_y) { +static void unpack_modulations(const PVRTCBlock *p_block, const int p_2bit, int p_modulation[8][16], int p_modulation_modes[8][16], int p_x, int p_y) { int block_mod_mode = p_block->data[1] & 1; uint32_t modulation_bits = p_block->data[0]; - if(p_2bit && block_mod_mode) { + if (p_2bit && block_mod_mode) { - for(int y = 0; y < BLK_Y_SIZE; y++) { - for(int x = 0; x < BLK_X_2BPP; x++) { + for (int y = 0; y < BLK_Y_SIZE; y++) { + for (int x = 0; x < BLK_X_2BPP; x++) { - p_modulation_modes[y+p_y][x+p_x] = block_mod_mode; + p_modulation_modes[y + p_y][x + p_x] = block_mod_mode; - if(((x^y)&1) == 0) { - p_modulation[y+p_y][x+p_x] = modulation_bits & 3; + if (((x ^ y) & 1) == 0) { + p_modulation[y + p_y][x + p_x] = modulation_bits & 3; modulation_bits >>= 2; } } } - } else if(p_2bit) { + } else if (p_2bit) { - for(int y = 0; y < BLK_Y_SIZE; y++) { - for(int x = 0; x < BLK_X_2BPP; x++) { - p_modulation_modes[y+p_y][x+p_x] = block_mod_mode; + for (int y = 0; y < BLK_Y_SIZE; y++) { + for (int x = 0; x < BLK_X_2BPP; x++) { + p_modulation_modes[y + p_y][x + p_x] = block_mod_mode; - if(modulation_bits & 1) - p_modulation[y+p_y][x+p_x] = 0x3; + if (modulation_bits & 1) + p_modulation[y + p_y][x + p_x] = 0x3; else - p_modulation[y+p_y][x+p_x] = 0x0; + p_modulation[y + p_y][x + p_x] = 0x0; modulation_bits >>= 1; } } - } else { - for(int y = 0; y < BLK_Y_SIZE; y++) { - for(int x = 0; x < BLK_X_4BPP; x++) { - p_modulation_modes[y+p_y][x+p_x] = block_mod_mode; - p_modulation[y+p_y][x+p_x] = modulation_bits & 3; + } else { + for (int y = 0; y < BLK_Y_SIZE; y++) { + for (int x = 0; x < BLK_X_4BPP; x++) { + p_modulation_modes[y + p_y][x + p_x] = block_mod_mode; + p_modulation[y + p_y][x + p_x] = modulation_bits & 3; modulation_bits >>= 2; } } } - ERR_FAIL_COND(modulation_bits!=0); + ERR_FAIL_COND(modulation_bits != 0); } - - static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], const int p_colorr[4], const int p_colors[4], bool p_2bit, const int x, const int y, int r_result[4]) { int u, v, uscale; int k; @@ -379,7 +364,7 @@ static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], con int P[4], Q[4], R[4], S[4]; - for(k = 0; k < 4; k++) { + for (k = 0; k < 4; k++) { P[k] = p_colorp[k]; Q[k] = p_colorq[k]; R[k] = p_colorr[k]; @@ -388,22 +373,22 @@ static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], con v = (y & 0x3) | ((~y & 0x2) << 1); - if(p_2bit) + if (p_2bit) u = (x & 0x7) | ((~x & 0x4) << 1); else u = (x & 0x3) | ((~x & 0x2) << 1); - v = v - BLK_Y_SIZE/2; + v = v - BLK_Y_SIZE / 2; - if(p_2bit) { - u = u - BLK_X_2BPP/2; + if (p_2bit) { + u = u - BLK_X_2BPP / 2; uscale = 8; } else { - u = u - BLK_X_4BPP/2; + u = u - BLK_X_4BPP / 2; uscale = 4; } - for(k = 0; k < 4; k++) { + for (k = 0; k < 4; k++) { tmp1 = P[k] * uscale + u * (Q[k] - P[k]); tmp2 = R[k] * uscale + u * (S[k] - R[k]); @@ -412,82 +397,77 @@ static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], con r_result[k] = tmp1; } - if(p_2bit) { - for(k = 0; k < 3; k++) { + if (p_2bit) { + for (k = 0; k < 3; k++) { r_result[k] >>= 2; } r_result[3] >>= 1; } else { - for(k = 0; k < 3; k++) { + for (k = 0; k < 3; k++) { r_result[k] >>= 1; } } - for(k = 0; k < 4; k++) { + for (k = 0; k < 4; k++) { ERR_FAIL_COND(r_result[k] >= 256); } - - for(k = 0; k < 3; k++) { + for (k = 0; k < 3; k++) { r_result[k] += r_result[k] >> 5; } r_result[3] += r_result[3] >> 4; - for(k = 0; k < 4; k++) { + for (k = 0; k < 4; k++) { ERR_FAIL_COND(r_result[k] >= 256); } - } - -static void get_modulation_value(int x, int y, const int p_2bit, const int p_modulation[8][16], const int p_modulation_modes[8][16], int *r_mod, int *p_dopt) -{ - static const int rep_vals0[4] = {0, 3, 5, 8}; - static const int rep_vals1[4] = {0, 4, 4, 8}; +static void get_modulation_value(int x, int y, const int p_2bit, const int p_modulation[8][16], const int p_modulation_modes[8][16], int *r_mod, int *p_dopt) { + static const int rep_vals0[4] = { 0, 3, 5, 8 }; + static const int rep_vals1[4] = { 0, 4, 4, 8 }; int mod_val; y = (y & 0x3) | ((~y & 0x2) << 1); - if(p_2bit) + if (p_2bit) x = (x & 0x7) | ((~x & 0x4) << 1); else x = (x & 0x3) | ((~x & 0x2) << 1); *p_dopt = 0; - if(p_modulation_modes[y][x]==0) { + if (p_modulation_modes[y][x] == 0) { mod_val = rep_vals0[p_modulation[y][x]]; - } else if(p_2bit) { - if(((x^y)&1)==0) + } else if (p_2bit) { + if (((x ^ y) & 1) == 0) mod_val = rep_vals0[p_modulation[y][x]]; - else if(p_modulation_modes[y][x] == 1) { - mod_val = ( - rep_vals0[p_modulation[y-1][x]] + - rep_vals0[p_modulation[y+1][x]] + - rep_vals0[p_modulation[y][x-1]] + - rep_vals0[p_modulation[y][x+1]] + 2) / 4; - } else if(p_modulation_modes[y][x] == 2) { - mod_val = ( - rep_vals0[p_modulation[y][x-1]] + - rep_vals0[p_modulation[y][x+1]] + 1) / 2; + else if (p_modulation_modes[y][x] == 1) { + mod_val = (rep_vals0[p_modulation[y - 1][x]] + + rep_vals0[p_modulation[y + 1][x]] + + rep_vals0[p_modulation[y][x - 1]] + + rep_vals0[p_modulation[y][x + 1]] + 2) / + 4; + } else if (p_modulation_modes[y][x] == 2) { + mod_val = (rep_vals0[p_modulation[y][x - 1]] + + rep_vals0[p_modulation[y][x + 1]] + 1) / + 2; } else { - mod_val = ( - rep_vals0[p_modulation[y-1][x]] + - rep_vals0[p_modulation[y+1][x]] + 1) / 2; + mod_val = (rep_vals0[p_modulation[y - 1][x]] + + rep_vals0[p_modulation[y + 1][x]] + 1) / + 2; } - } else { + } else { mod_val = rep_vals1[p_modulation[y][x]]; *p_dopt = p_modulation[y][x] == PT_INDEX; } - *r_mod =mod_val; + *r_mod = mod_val; } - static int disable_twiddling = 0; static uint32_t twiddle_uv(uint32_t p_height, uint32_t p_width, uint32_t p_y, uint32_t p_x) { @@ -502,51 +482,50 @@ static uint32_t twiddle_uv(uint32_t p_height, uint32_t p_width, uint32_t p_y, ui int shift_count; - ERR_FAIL_COND_V(p_y >= p_height,0); - ERR_FAIL_COND_V(p_x >= p_width,0); + ERR_FAIL_COND_V(p_y >= p_height, 0); + ERR_FAIL_COND_V(p_x >= p_width, 0); - ERR_FAIL_COND_V(!is_po2(p_height),0); - ERR_FAIL_COND_V(!is_po2(p_width),0); + ERR_FAIL_COND_V(!is_po2(p_height), 0); + ERR_FAIL_COND_V(!is_po2(p_width), 0); - if(p_height < p_width) { + if (p_height < p_width) { min_dimension = p_height; - max_value = p_x; + max_value = p_x; } else { min_dimension = p_width; - max_value = p_y; + max_value = p_y; } - if(disable_twiddling) - return (p_y* p_width + p_x); + if (disable_twiddling) + return (p_y * p_width + p_x); scr_bit_pos = 1; dst_bit_pos = 1; - twiddled = 0; + twiddled = 0; shift_count = 0; - while(scr_bit_pos < min_dimension) { - if(p_y & scr_bit_pos) { + while (scr_bit_pos < min_dimension) { + if (p_y & scr_bit_pos) { twiddled |= dst_bit_pos; } - if(p_x & scr_bit_pos) { + if (p_x & scr_bit_pos) { twiddled |= (dst_bit_pos << 1); } scr_bit_pos <<= 1; dst_bit_pos <<= 2; shift_count += 1; - } max_value >>= shift_count; - twiddled |= (max_value << (2*shift_count)); + twiddled |= (max_value << (2 * shift_count)); return twiddled; } -static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int p_width, const int p_height, const int p_tiled, unsigned char* p_dst) { +static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int p_width, const int p_height, const int p_tiled, unsigned char *p_dst) { int x, y; int i, j; @@ -567,55 +546,50 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int // local neighbourhood of blocks PVRTCBlock *p_blocks[2][2]; - PVRTCBlock *prev[2][2] = {{NULL, NULL}, {NULL, NULL}}; + PVRTCBlock *prev[2][2] = { { NULL, NULL }, { NULL, NULL } }; struct { int Reps[2][4]; - }colors5554[2][2]; - + } colors5554[2][2]; int ASig[4], BSig[4]; int r_result[4]; - if(p_2bit) + if (p_2bit) x_block_size = BLK_X_2BPP; else x_block_size = BLK_X_4BPP; - block_width = MAX(2, p_width / x_block_size); block_height = MAX(2, p_height / BLK_Y_SIZE); - for(y = 0; y < p_height; y++) - { - for(x = 0; x < p_width; x++) - { + for (y = 0; y < p_height; y++) { + for (x = 0; x < p_width; x++) { - block_x = (x - x_block_size/2); - blk_y = (y - BLK_Y_SIZE/2); + block_x = (x - x_block_size / 2); + blk_y = (y - BLK_Y_SIZE / 2); block_x = LIMIT_COORD(block_x, p_width, p_tiled); blk_y = LIMIT_COORD(blk_y, p_height, p_tiled); - block_x /= x_block_size; blk_y /= BLK_Y_SIZE; - block_xp1 = LIMIT_COORD(block_x+1, block_width, p_tiled); - blk_yp1 = LIMIT_COORD(blk_y+1, block_height, p_tiled); + block_xp1 = LIMIT_COORD(block_x + 1, block_width, p_tiled); + blk_yp1 = LIMIT_COORD(blk_y + 1, block_height, p_tiled); - p_blocks[0][0] = p_comp_img +twiddle_uv(block_height, block_width, blk_y, block_x); - p_blocks[0][1] = p_comp_img +twiddle_uv(block_height, block_width, blk_y, block_xp1); - p_blocks[1][0] = p_comp_img +twiddle_uv(block_height, block_width, blk_yp1, block_x); - p_blocks[1][1] = p_comp_img +twiddle_uv(block_height, block_width, blk_yp1, block_xp1); + p_blocks[0][0] = p_comp_img + twiddle_uv(block_height, block_width, blk_y, block_x); + p_blocks[0][1] = p_comp_img + twiddle_uv(block_height, block_width, blk_y, block_xp1); + p_blocks[1][0] = p_comp_img + twiddle_uv(block_height, block_width, blk_yp1, block_x); + p_blocks[1][1] = p_comp_img + twiddle_uv(block_height, block_width, blk_yp1, block_xp1); - if(memcmp(prev, p_blocks, 4*sizeof(void*)) != 0) { + if (memcmp(prev, p_blocks, 4 * sizeof(void *)) != 0) { p_y = 0; - for(i = 0; i < 2; i++) { + for (i = 0; i < 2; i++) { p_x = 0; - for(j = 0; j < 2; j++) { + for (j = 0; j < 2; j++) { unpack_5554(p_blocks[i][j], colors5554[i][j].Reps); unpack_modulations( @@ -631,11 +605,9 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int p_y += BLK_Y_SIZE; } - - memcpy(prev, p_blocks, 4*sizeof(void*)); + memcpy(prev, p_blocks, 4 * sizeof(void *)); } - interpolate_colors( colors5554[0][0].Reps[0], colors5554[0][1].Reps[0], @@ -652,66 +624,55 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int p_2bit, x, y, BSig); - get_modulation_value(x,y, p_2bit, (const int (*)[16])p_modulation, (const int (*)[16])p_modulation_modes, - &Mod, &DoPT); + get_modulation_value(x, y, p_2bit, (const int(*)[16])p_modulation, (const int(*)[16])p_modulation_modes, + &Mod, &DoPT); - for(i = 0; i < 4; i++) { + for (i = 0; i < 4; i++) { r_result[i] = ASig[i] * 8 + Mod * (BSig[i] - ASig[i]); r_result[i] >>= 3; } - if(DoPT) + if (DoPT) r_result[3] = 0; - - u_pos = (x+y*p_width)<<2; - p_dst[u_pos+0] = (uint8_t)r_result[0]; - p_dst[u_pos+1] = (uint8_t)r_result[1]; - p_dst[u_pos+2] = (uint8_t)r_result[2]; - p_dst[u_pos+3] = (uint8_t)r_result[3]; + u_pos = (x + y * p_width) << 2; + p_dst[u_pos + 0] = (uint8_t)r_result[0]; + p_dst[u_pos + 1] = (uint8_t)r_result[1]; + p_dst[u_pos + 2] = (uint8_t)r_result[2]; + p_dst[u_pos + 3] = (uint8_t)r_result[3]; } } } -static void _pvrtc_decompress(Image* p_img) { +static void _pvrtc_decompress(Image *p_img) { -// static void decompress_pvrtc(const void *p_comp_img, const int p_2bit, const int p_width, const int p_height, unsigned char* p_dst) { -// decompress_pvrtc((PVRTCBlock*)p_comp_img,p_2bit,p_width,p_height,1,p_dst); -// } + // static void decompress_pvrtc(const void *p_comp_img, const int p_2bit, const int p_width, const int p_height, unsigned char* p_dst) { + // decompress_pvrtc((PVRTCBlock*)p_comp_img,p_2bit,p_width,p_height,1,p_dst); + // } - ERR_FAIL_COND( p_img->get_format()!=Image::FORMAT_PVRTC2 && p_img->get_format()!=Image::FORMAT_PVRTC2_ALPHA && p_img->get_format()!=Image::FORMAT_PVRTC4 && p_img->get_format()!=Image::FORMAT_PVRTC4_ALPHA); + ERR_FAIL_COND(p_img->get_format() != Image::FORMAT_PVRTC2 && p_img->get_format() != Image::FORMAT_PVRTC2_ALPHA && p_img->get_format() != Image::FORMAT_PVRTC4 && p_img->get_format() != Image::FORMAT_PVRTC4_ALPHA); - bool _2bit = (p_img->get_format()==Image::FORMAT_PVRTC2 || p_img->get_format()==Image::FORMAT_PVRTC2_ALPHA ); + bool _2bit = (p_img->get_format() == Image::FORMAT_PVRTC2 || p_img->get_format() == Image::FORMAT_PVRTC2_ALPHA); DVector<uint8_t> data = p_img->get_data(); DVector<uint8_t>::Read r = data.read(); - DVector<uint8_t> newdata; - newdata.resize( p_img->get_width() * p_img->get_height() * 4); - DVector<uint8_t>::Write w=newdata.write(); + newdata.resize(p_img->get_width() * p_img->get_height() * 4); + DVector<uint8_t>::Write w = newdata.write(); - decompress_pvrtc((PVRTCBlock*)r.ptr(),_2bit,p_img->get_width(),p_img->get_height(),0,(unsigned char*)w.ptr()); + decompress_pvrtc((PVRTCBlock *)r.ptr(), _2bit, p_img->get_width(), p_img->get_height(), 0, (unsigned char *)w.ptr()); //for(int i=0;i<newdata.size();i++) { // print_line(itos(w[i])); //} - w=DVector<uint8_t>::Write(); - r=DVector<uint8_t>::Read(); + w = DVector<uint8_t>::Write(); + r = DVector<uint8_t>::Read(); - bool make_mipmaps=p_img->get_mipmaps()>0; - Image newimg(p_img->get_width(),p_img->get_height(),0,Image::FORMAT_RGBA,newdata); + bool make_mipmaps = p_img->get_mipmaps() > 0; + Image newimg(p_img->get_width(), p_img->get_height(), 0, Image::FORMAT_RGBA, newdata); if (make_mipmaps) newimg.generate_mipmaps(); - *p_img=newimg; - + *p_img = newimg; } - - - - - - - - diff --git a/modules/pvr/texture_loader_pvr.h b/modules/pvr/texture_loader_pvr.h index bad48b456..768070ee6 100644 --- a/modules/pvr/texture_loader_pvr.h +++ b/modules/pvr/texture_loader_pvr.h @@ -29,22 +29,18 @@ #ifndef TEXTURE_LOADER_PVR_H #define TEXTURE_LOADER_PVR_H - -#include "scene/resources/texture.h" #include "io/resource_loader.h" +#include "scene/resources/texture.h" - -class ResourceFormatPVR : public ResourceFormatLoader{ +class ResourceFormatPVR : public ResourceFormatLoader { public: - - 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 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; ResourceFormatPVR(); virtual ~ResourceFormatPVR() {} }; - #endif // TEXTURE_LOADER_PVR_H diff --git a/modules/speex/audio_stream_speex.cpp b/modules/speex/audio_stream_speex.cpp index 3aa80fd0b..a3c883cd7 100644 --- a/modules/speex/audio_stream_speex.cpp +++ b/modules/speex/audio_stream_speex.cpp @@ -28,24 +28,20 @@ /*************************************************************************/ #include "audio_stream_speex.h" -#include "os_support.h" #include "os/os.h" +#include "os_support.h" #define READ_CHUNK 1024 -static _FORCE_INLINE_ uint16_t le_short(uint16_t s) -{ - uint16_t ret=s; +static _FORCE_INLINE_ uint16_t le_short(uint16_t s) { + uint16_t ret = s; #if 0 //def BIG_ENDIAN_ENABLED ret = s>>8; ret += s<<8; #endif - return ret; + return ret; } - -int AudioStreamPlaybackSpeex::mix(int16_t* p_buffer,int p_frames) { - - +int AudioStreamPlaybackSpeex::mix(int16_t *p_buffer, int p_frames) { //printf("update, loops %i, read ofs %i\n", (int)loops, read_ofs); //printf("playing %i, paused %i\n", (int)playing, (int)paused); @@ -73,54 +69,48 @@ int AudioStreamPlaybackSpeex::mix(int16_t* p_buffer,int p_frames) { while (todo > page_size) { - int ret=0; - while ((todo>page_size && packets_available && !eos) || (ret = ogg_sync_pageout(&oy, &og))==1) { + int ret = 0; + while ((todo > page_size && packets_available && !eos) || (ret = ogg_sync_pageout(&oy, &og)) == 1) { if (!packets_available) { - /*Add page to the bitstream*/ + /*Add page to the bitstream*/ ogg_stream_pagein(&os, &og); page_granule = ogg_page_granulepos(&og); page_nb_packets = ogg_page_packets(&og); - packet_no=0; - if (page_granule>0 && frame_size) - { - skip_samples = page_nb_packets*frame_size*nframes - (page_granule-last_granule); + packet_no = 0; + if (page_granule > 0 && frame_size) { + skip_samples = page_nb_packets * frame_size * nframes - (page_granule - last_granule); if (ogg_page_eos(&og)) skip_samples = -skip_samples; /*else if (!ogg_page_bos(&og)) skip_samples = 0;*/ - } else - { + } else { skip_samples = 0; } - last_granule = page_granule; - packets_available=true; + packets_available = true; } /*Extract all available packets*/ while (todo > page_size && !eos) { - if (ogg_stream_packetout(&os, &op)!=1) { - packets_available=false; + if (ogg_stream_packetout(&os, &op) != 1) { + packets_available = false; break; } packet_no++; - /*End of stream condition*/ if (op.e_o_s) - eos=1; + eos = 1; /*Copy Ogg packet to Speex bitstream*/ - speex_bits_read_from(&bits, (char*)op.packet, op.bytes); - + speex_bits_read_from(&bits, (char *)op.packet, op.bytes); - for (int j=0;j!=nframes;j++) - { + for (int j = 0; j != nframes; j++) { - int16_t* out = p_buffer; + int16_t *out = p_buffer; int ret; /*Decode frame*/ @@ -129,57 +119,49 @@ int AudioStreamPlaybackSpeex::mix(int16_t* p_buffer,int p_frames) { /*for (i=0;i<frame_size*channels;i++) printf ("%d\n", (int)output[i]);*/ - if (ret==-1) { + if (ret == -1) { printf("decode returned -1\n"); break; }; - if (ret==-2) - { - OS::get_singleton()->printerr( "Decoding error: corrupted stream?\n"); + if (ret == -2) { + OS::get_singleton()->printerr("Decoding error: corrupted stream?\n"); break; } - if (speex_bits_remaining(&bits)<0) - { - OS::get_singleton()->printerr( "Decoding overflow: corrupted stream?\n"); + if (speex_bits_remaining(&bits) < 0) { + OS::get_singleton()->printerr("Decoding overflow: corrupted stream?\n"); break; } //if (channels==2) // speex_decode_stereo_int(output, frame_size, &stereo); - /*Convert to short and save to output file*/ - for (int i=0;i<frame_size*stream_channels;i++) { - out[i]=le_short(out[i]); + for (int i = 0; i < frame_size * stream_channels; i++) { + out[i] = le_short(out[i]); } - { int new_frame_size = frame_size; /*printf ("packet %d %d\n", packet_no, skip_samples);*/ - if (packet_no == 1 && j==0 && skip_samples > 0) - { + if (packet_no == 1 && j == 0 && skip_samples > 0) { /*printf ("chopping first packet\n");*/ new_frame_size -= skip_samples; } - if (packet_no == page_nb_packets && skip_samples < 0) - { - int packet_length = nframes*frame_size+skip_samples; - new_frame_size = packet_length - j*frame_size; - if (new_frame_size<0) + if (packet_no == page_nb_packets && skip_samples < 0) { + int packet_length = nframes * frame_size + skip_samples; + new_frame_size = packet_length - j * frame_size; + if (new_frame_size < 0) new_frame_size = 0; - if (new_frame_size>frame_size) + if (new_frame_size > frame_size) new_frame_size = frame_size; /*printf ("chopping end: %d %d %d\n", new_frame_size, packet_length, packet_no);*/ } - - p_buffer+=new_frame_size*stream_channels; - todo-=new_frame_size; + p_buffer += new_frame_size * stream_channels; + todo -= new_frame_size; } } - }; }; //todo = get_todo(); @@ -192,18 +174,18 @@ int AudioStreamPlaybackSpeex::mix(int16_t* p_buffer,int p_frames) { int nb_read = MIN(data.size() - read_ofs, READ_CHUNK); /*Get the ogg buffer for writing*/ - char* ogg_dst = ogg_sync_buffer(&oy, nb_read); + char *ogg_dst = ogg_sync_buffer(&oy, nb_read); /*Read bitstream from input file*/ copymem(ogg_dst, &data[read_ofs], nb_read); read_ofs += nb_read; ogg_sync_wrote(&oy, nb_read); } else { - if (loops) { + if (loops) { reload(); ++loop_count; //break; } else { - playing=false; + playing = false; unload(); break; }; @@ -211,14 +193,11 @@ int AudioStreamPlaybackSpeex::mix(int16_t* p_buffer,int p_frames) { }; }; - return p_frames-todo; + return p_frames - todo; }; - void AudioStreamPlaybackSpeex::unload() { - - if (!active) return; speex_bits_destroy(&bits); @@ -240,44 +219,38 @@ void *AudioStreamPlaybackSpeex::process_header(ogg_packet *op, int *frame_size, SpeexHeader *header; int modeID; - header = speex_packet_to_header((char*)op->packet, op->bytes); - if (!header) - { - OS::get_singleton()->printerr( "Cannot read header\n"); + header = speex_packet_to_header((char *)op->packet, op->bytes); + if (!header) { + OS::get_singleton()->printerr("Cannot read header\n"); return NULL; } - if (header->mode >= SPEEX_NB_MODES) - { - OS::get_singleton()->printerr( "Mode number %d does not (yet/any longer) exist in this version\n", - header->mode); + if (header->mode >= SPEEX_NB_MODES) { + OS::get_singleton()->printerr("Mode number %d does not (yet/any longer) exist in this version\n", + header->mode); return NULL; } modeID = header->mode; - const SpeexMode *mode = speex_lib_get_mode (modeID); + const SpeexMode *mode = speex_lib_get_mode(modeID); - if (header->speex_version_id > 1) - { - OS::get_singleton()->printerr( "This file was encoded with Speex bit-stream version %d, which I don't know how to decode\n", header->speex_version_id); + if (header->speex_version_id > 1) { + OS::get_singleton()->printerr("This file was encoded with Speex bit-stream version %d, which I don't know how to decode\n", header->speex_version_id); return NULL; } - if (mode->bitstream_version < header->mode_bitstream_version) - { - OS::get_singleton()->printerr( "The file was encoded with a newer version of Speex. You need to upgrade in order to play it.\n"); + if (mode->bitstream_version < header->mode_bitstream_version) { + OS::get_singleton()->printerr("The file was encoded with a newer version of Speex. You need to upgrade in order to play it.\n"); return NULL; } - if (mode->bitstream_version > header->mode_bitstream_version) - { - OS::get_singleton()->printerr( "The file was encoded with an older version of Speex. You would need to downgrade the version in order to play it.\n"); + if (mode->bitstream_version > header->mode_bitstream_version) { + OS::get_singleton()->printerr("The file was encoded with an older version of Speex. You would need to downgrade the version in order to play it.\n"); return NULL; } - void* state = speex_decoder_init(mode); - if (!state) - { - OS::get_singleton()->printerr( "Decoder initialization failed.\n"); + void *state = speex_decoder_init(mode); + if (!state) { + OS::get_singleton()->printerr("Decoder initialization failed.\n"); return NULL; } //speex_decoder_ctl(state, SPEEX_SET_ENH, &enh_enabled); @@ -292,7 +265,7 @@ void *AudioStreamPlaybackSpeex::process_header(ogg_packet *op, int *frame_size, *channels = header->nb_channels; - if (*channels!=1) { + if (*channels != 1) { OS::get_singleton()->printerr("Only MONO speex streams supported\n"); return NULL; } @@ -303,12 +276,8 @@ void *AudioStreamPlaybackSpeex::process_header(ogg_packet *op, int *frame_size, return state; } - - void AudioStreamPlaybackSpeex::reload() { - - if (active) unload(); @@ -319,18 +288,18 @@ void AudioStreamPlaybackSpeex::reload() { speex_bits_init(&bits); read_ofs = 0; -// char *buf; + // char *buf; int packet_count = 0; int extra_headers = 0; int stream_init = 0; - page_granule=0; - last_granule=0; - skip_samples=0; - page_nb_packets=0; - packets_available=false; - packet_no=0; + page_granule = 0; + last_granule = 0; + skip_samples = 0; + page_nb_packets = 0; + packets_available = false; + packet_no = 0; int eos = 0; @@ -338,14 +307,14 @@ void AudioStreamPlaybackSpeex::reload() { /*Get the ogg buffer for writing*/ int nb_read = MIN(data.size() - read_ofs, READ_CHUNK); - char* ogg_dst = ogg_sync_buffer(&oy, nb_read); + char *ogg_dst = ogg_sync_buffer(&oy, nb_read); /*Read bitstream from input file*/ copymem(ogg_dst, &data[read_ofs], nb_read); read_ofs += nb_read; ogg_sync_wrote(&oy, nb_read); /*Loop for all complete pages we got (most likely only one)*/ - while (ogg_sync_pageout(&oy, &og)==1) { + while (ogg_sync_pageout(&oy, &og) == 1) { if (stream_init == 0) { ogg_stream_init(&os, ogg_page_serialno(&og)); @@ -355,46 +324,38 @@ void AudioStreamPlaybackSpeex::reload() { ogg_stream_pagein(&os, &og); page_granule = ogg_page_granulepos(&og); page_nb_packets = ogg_page_packets(&og); - if (page_granule>0 && frame_size) - { - skip_samples = page_nb_packets*frame_size*nframes - (page_granule-last_granule); + if (page_granule > 0 && frame_size) { + skip_samples = page_nb_packets * frame_size * nframes - (page_granule - last_granule); if (ogg_page_eos(&og)) skip_samples = -skip_samples; /*else if (!ogg_page_bos(&og)) skip_samples = 0;*/ - } else - { + } else { skip_samples = 0; } - last_granule = page_granule; /*Extract all available packets*/ - while (!eos && ogg_stream_packetout(&os, &op)==1) - { + while (!eos && ogg_stream_packetout(&os, &op) == 1) { /*If first packet, process as Speex header*/ - if (packet_count==0) - { + if (packet_count == 0) { int rate = 0; int channels; st = process_header(&op, &frame_size, &rate, &nframes, &channels, &extra_headers); if (!nframes) - nframes=1; + nframes = 1; if (!st) { unload(); return; }; page_size = nframes * frame_size; - stream_srate=rate; - stream_channels=channels; - stream_minbuff_size=page_size; - + stream_srate = rate; + stream_channels = channels; + stream_minbuff_size = page_size; - } else if (packet_count==1) - { - } else if (packet_count<=1+extra_headers) - { + } else if (packet_count == 1) { + } else if (packet_count <= 1 + extra_headers) { /* Ignore extra headers */ }; }; @@ -403,26 +364,25 @@ void AudioStreamPlaybackSpeex::reload() { } while (packet_count <= extra_headers); - active=true; - + active = true; } void AudioStreamPlaybackSpeex::_bind_methods() { //ObjectTypeDB::bind_method(_MD("set_file","file"),&AudioStreamPlaybackSpeex::set_file); -// ObjectTypeDB::bind_method(_MD("get_file"),&AudioStreamPlaybackSpeex::get_file); + // ObjectTypeDB::bind_method(_MD("get_file"),&AudioStreamPlaybackSpeex::get_file); - ObjectTypeDB::bind_method(_MD("_set_bundled"),&AudioStreamPlaybackSpeex::_set_bundled); - ObjectTypeDB::bind_method(_MD("_get_bundled"),&AudioStreamPlaybackSpeex::_get_bundled); + ObjectTypeDB::bind_method(_MD("_set_bundled"), &AudioStreamPlaybackSpeex::_set_bundled); + ObjectTypeDB::bind_method(_MD("_get_bundled"), &AudioStreamPlaybackSpeex::_get_bundled); - ADD_PROPERTY( PropertyInfo(Variant::DICTIONARY,"_bundled",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_BUNDLE),_SCS("_set_bundled"),_SCS("_get_bundled")); + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_bundled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_BUNDLE), _SCS("_set_bundled"), _SCS("_get_bundled")); //ADD_PROPERTY( PropertyInfo(Variant::STRING,"file",PROPERTY_HINT_FILE,"*.spx"),_SCS("set_file"),_SCS("get_file")); }; -void AudioStreamPlaybackSpeex::_set_bundled(const Dictionary& dict) { +void AudioStreamPlaybackSpeex::_set_bundled(const Dictionary &dict) { - ERR_FAIL_COND( !dict.has("filename")); - ERR_FAIL_COND( !dict.has("data")); + ERR_FAIL_COND(!dict.has("filename")); + ERR_FAIL_COND(!dict.has("data")); filename = dict["filename"]; data = dict["data"]; @@ -436,83 +396,69 @@ Dictionary AudioStreamPlaybackSpeex::_get_bundled() const { return d; }; +void AudioStreamPlaybackSpeex::set_data(const Vector<uint8_t> &p_data) { - -void AudioStreamPlaybackSpeex::set_data(const Vector<uint8_t>& p_data) { - - data=p_data; + data = p_data; reload(); } - void AudioStreamPlaybackSpeex::play(float p_from_pos) { - - reload(); if (!active) return; playing = true; - } -void AudioStreamPlaybackSpeex::stop(){ - +void AudioStreamPlaybackSpeex::stop() { unload(); playing = false; - } -bool AudioStreamPlaybackSpeex::is_playing() const{ +bool AudioStreamPlaybackSpeex::is_playing() const { return playing; } - -void AudioStreamPlaybackSpeex::set_loop(bool p_enable){ +void AudioStreamPlaybackSpeex::set_loop(bool p_enable) { loops = p_enable; } -bool AudioStreamPlaybackSpeex::has_loop() const{ +bool AudioStreamPlaybackSpeex::has_loop() const { return loops; } -float AudioStreamPlaybackSpeex::get_length() const{ +float AudioStreamPlaybackSpeex::get_length() const { return 0; } -String AudioStreamPlaybackSpeex::get_stream_name() const{ +String AudioStreamPlaybackSpeex::get_stream_name() const { return ""; } -int AudioStreamPlaybackSpeex::get_loop_count() const{ +int AudioStreamPlaybackSpeex::get_loop_count() const { return 0; } -float AudioStreamPlaybackSpeex::get_pos() const{ +float AudioStreamPlaybackSpeex::get_pos() const { return 0; } void AudioStreamPlaybackSpeex::seek_pos(float p_time){ - }; - - AudioStreamPlaybackSpeex::AudioStreamPlaybackSpeex() { - active=false; + active = false; st = NULL; - stream_channels=1; - stream_srate=1; - stream_minbuff_size=1; - playing=false; - - + stream_channels = 1; + stream_srate = 1; + stream_minbuff_size = 1; + playing = false; } AudioStreamPlaybackSpeex::~AudioStreamPlaybackSpeex() { @@ -520,20 +466,14 @@ AudioStreamPlaybackSpeex::~AudioStreamPlaybackSpeex() { unload(); } - - - - //////////////////////////////////////// - - -void AudioStreamSpeex::set_file(const String& p_file) { +void AudioStreamSpeex::set_file(const String &p_file) { if (this->file == p_file) return; - this->file=p_file; + this->file = p_file; if (p_file == "") { data.resize(0); @@ -541,7 +481,7 @@ void AudioStreamSpeex::set_file(const String& p_file) { }; Error err; - FileAccess* file = FileAccess::open(p_file, FileAccess::READ,&err); + FileAccess *file = FileAccess::open(p_file, FileAccess::READ, &err); if (err != OK) { data.resize(0); }; @@ -551,13 +491,12 @@ void AudioStreamSpeex::set_file(const String& p_file) { data.resize(file->get_len()); int read = file->get_buffer(&data[0], data.size()); memdelete(file); - } -RES ResourceFormatLoaderAudioStreamSpeex::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderAudioStreamSpeex::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=OK; + *r_error = OK; AudioStreamSpeex *stream = memnew(AudioStreamSpeex); stream->set_file(p_path); @@ -568,14 +507,14 @@ void ResourceFormatLoaderAudioStreamSpeex::get_recognized_extensions(List<String p_extensions->push_back("spx"); } -bool ResourceFormatLoaderAudioStreamSpeex::handles_type(const String& p_type) const { +bool ResourceFormatLoaderAudioStreamSpeex::handles_type(const String &p_type) const { - return (p_type=="AudioStream" || p_type=="AudioStreamSpeex"); + return (p_type == "AudioStream" || p_type == "AudioStreamSpeex"); } String ResourceFormatLoaderAudioStreamSpeex::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="spx") + if (p_path.extension().to_lower() == "spx") return "AudioStreamSpeex"; return ""; } diff --git a/modules/speex/audio_stream_speex.h b/modules/speex/audio_stream_speex.h index e321d7705..70d05b8b4 100644 --- a/modules/speex/audio_stream_speex.h +++ b/modules/speex/audio_stream_speex.h @@ -29,15 +29,15 @@ #ifndef AUDIO_STREAM_SPEEX_H #define AUDIO_STREAM_SPEEX_H -#include "scene/resources/audio_stream.h" -#include "os/file_access.h" #include "io/resource_loader.h" +#include "os/file_access.h" #include "os/thread_safe.h" +#include "scene/resources/audio_stream.h" #include <speex/speex.h> +#include <speex/speex_callbacks.h> #include <speex/speex_header.h> #include <speex/speex_stereo.h> -#include <speex/speex_callbacks.h> // (akien) Prevents unbundling properly, but it's only for 2.1.x as speex // is dropped in 3.0+, so don't want to lose too much time on this. // Needed for speex_free (internal). @@ -49,7 +49,6 @@ class AudioStreamPlaybackSpeex : public AudioStreamPlayback { OBJ_TYPE(AudioStreamPlaybackSpeex, AudioStreamPlayback); - void *st; SpeexBits bits; Vector<uint8_t> data; @@ -66,8 +65,8 @@ class AudioStreamPlaybackSpeex : public AudioStreamPlayback { void reload(); ogg_sync_state oy; - ogg_page og; - ogg_packet op; + ogg_page og; + ogg_packet op; ogg_stream_state os; int nframes; int frame_size; @@ -79,23 +78,20 @@ class AudioStreamPlaybackSpeex : public AudioStreamPlayback { int stream_srate; int stream_minbuff_size; - void* process_header(ogg_packet *op, int *frame_size, int *rate, int *nframes, int *channels, int *extra_headers); + void *process_header(ogg_packet *op, int *frame_size, int *rate, int *nframes, int *channels, int *extra_headers); static void _bind_methods(); protected: - //virtual bool _can_mix() const; Dictionary _get_bundled() const; - void _set_bundled(const Dictionary& dict); + void _set_bundled(const Dictionary &dict); public: + void set_data(const Vector<uint8_t> &p_data); - - void set_data(const Vector<uint8_t>& p_data); - - virtual void play(float p_from_pos=0); + virtual void play(float p_from_pos = 0); virtual void stop(); virtual bool is_playing() const; @@ -115,42 +111,37 @@ public: virtual int get_mix_rate() const { return stream_srate; } virtual int get_minimum_buffer_size() const { return stream_minbuff_size; } - virtual int mix(int16_t* p_bufer,int p_frames); + virtual int mix(int16_t *p_bufer, int p_frames); - virtual void set_loop_restart_time(float p_time) { } //no loop restart, ignore + virtual void set_loop_restart_time(float p_time) {} //no loop restart, ignore AudioStreamPlaybackSpeex(); ~AudioStreamPlaybackSpeex(); }; - - class AudioStreamSpeex : public AudioStream { - OBJ_TYPE(AudioStreamSpeex,AudioStream); + OBJ_TYPE(AudioStreamSpeex, AudioStream); Vector<uint8_t> data; String file; -public: +public: Ref<AudioStreamPlayback> instance_playback() { - Ref<AudioStreamPlaybackSpeex> pb = memnew( AudioStreamPlaybackSpeex ); + Ref<AudioStreamPlaybackSpeex> pb = memnew(AudioStreamPlaybackSpeex); pb->set_data(data); return pb; } - void set_file(const String& p_file); - + void set_file(const String &p_file); }; - class ResourceFormatLoaderAudioStreamSpeex : public ResourceFormatLoader { public: - 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 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; - }; #endif // AUDIO_STREAM_SPEEX_H diff --git a/modules/speex/register_types.cpp b/modules/speex/register_types.cpp index f5b60cf6f..19f17be40 100644 --- a/modules/speex/register_types.cpp +++ b/modules/speex/register_types.cpp @@ -34,12 +34,12 @@ static ResourceFormatLoaderAudioStreamSpeex *speex_stream_loader = NULL; void register_speex_types() { - speex_stream_loader = memnew( ResourceFormatLoaderAudioStreamSpeex ); + speex_stream_loader = memnew(ResourceFormatLoaderAudioStreamSpeex); ResourceLoader::add_resource_format_loader(speex_stream_loader); ObjectTypeDB::register_type<AudioStreamSpeex>(); } void unregister_speex_types() { - memdelete( speex_stream_loader ); + memdelete(speex_stream_loader); } diff --git a/modules/squish/image_compress_squish.cpp b/modules/squish/image_compress_squish.cpp index 27f13f8e8..9d7eeee23 100644 --- a/modules/squish/image_compress_squish.cpp +++ b/modules/squish/image_compress_squish.cpp @@ -34,32 +34,36 @@ void image_compress_squish(Image *p_image) { - int w=p_image->get_width(); - int h=p_image->get_height(); + int w = p_image->get_width(); + int h = p_image->get_height(); if (p_image->get_mipmaps() == 0) { - ERR_FAIL_COND( !w || w % 4 != 0); - ERR_FAIL_COND( !h || h % 4 != 0); + ERR_FAIL_COND(!w || w % 4 != 0); + ERR_FAIL_COND(!h || h % 4 != 0); } else { - ERR_FAIL_COND( !w || w !=nearest_power_of_2(w) ); - ERR_FAIL_COND( !h || h !=nearest_power_of_2(h) ); + ERR_FAIL_COND(!w || w != nearest_power_of_2(w)); + ERR_FAIL_COND(!h || h != nearest_power_of_2(h)); }; - if (p_image->get_format()>=Image::FORMAT_BC1) + if (p_image->get_format() >= Image::FORMAT_BC1) return; //do not compress, already compressed - int shift=0; - int squish_comp=squish::kColourRangeFit; + int shift = 0; + int squish_comp = squish::kColourRangeFit; Image::Format target_format; - if (p_image->get_format()==Image::FORMAT_GRAYSCALE_ALPHA) { + if (p_image->get_format() == Image::FORMAT_GRAYSCALE_ALPHA) { //compressed normalmap - target_format = Image::FORMAT_BC3; squish_comp|=squish::kDxt5; - } else if (p_image->detect_alpha()!=Image::ALPHA_NONE) { + target_format = Image::FORMAT_BC3; + squish_comp |= squish::kDxt5; + } else if (p_image->detect_alpha() != Image::ALPHA_NONE) { - target_format = Image::FORMAT_BC2; squish_comp|=squish::kDxt3; + target_format = Image::FORMAT_BC2; + squish_comp |= squish::kDxt3; } else { - target_format = Image::FORMAT_BC1; shift=1; squish_comp|=squish::kDxt1; + target_format = Image::FORMAT_BC1; + shift = 1; + squish_comp |= squish::kDxt1; } p_image->convert(Image::FORMAT_RGBA); //always expects rgba @@ -67,26 +71,25 @@ void image_compress_squish(Image *p_image) { int mm_count = p_image->get_mipmaps(); DVector<uint8_t> data; - int target_size = Image::get_image_data_size(w,h,target_format,mm_count); + int target_size = Image::get_image_data_size(w, h, target_format, mm_count); data.resize(target_size); DVector<uint8_t>::Read rb = p_image->get_data().read(); DVector<uint8_t>::Write wb = data.write(); - int dst_ofs=0; + int dst_ofs = 0; - for(int i=0;i<=mm_count;i++) { + for (int i = 0; i <= mm_count; i++) { int src_ofs = p_image->get_mipmap_offset(i); - squish::CompressImage( &rb[src_ofs],w,h,&wb[dst_ofs],squish_comp); - dst_ofs+=(MAX(4,w)*MAX(4,h))>>shift; - w>>=1; - h>>=1; + squish::CompressImage(&rb[src_ofs], w, h, &wb[dst_ofs], squish_comp); + dst_ofs += (MAX(4, w) * MAX(4, h)) >> shift; + w >>= 1; + h >>= 1; } rb = DVector<uint8_t>::Read(); wb = DVector<uint8_t>::Write(); - p_image->create(p_image->get_width(),p_image->get_height(),p_image->get_mipmaps(),target_format,data); - + p_image->create(p_image->get_width(), p_image->get_height(), p_image->get_mipmaps(), target_format, data); } diff --git a/modules/theora/register_types.cpp b/modules/theora/register_types.cpp index 043498a23..4671a055f 100644 --- a/modules/theora/register_types.cpp +++ b/modules/theora/register_types.cpp @@ -30,16 +30,16 @@ #include "video_stream_theora.h" -static ResourceFormatLoaderVideoStreamTheora* theora_stream_loader = NULL; +static ResourceFormatLoaderVideoStreamTheora *theora_stream_loader = NULL; void register_theora_types() { - theora_stream_loader = memnew( ResourceFormatLoaderVideoStreamTheora ); + theora_stream_loader = memnew(ResourceFormatLoaderVideoStreamTheora); ResourceLoader::add_resource_format_loader(theora_stream_loader); ObjectTypeDB::register_type<VideoStreamTheora>(); } void unregister_theora_types() { - memdelete( theora_stream_loader ); + memdelete(theora_stream_loader); } diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp index d98ec9ee7..7b77e71cf 100644 --- a/modules/theora/video_stream_theora.cpp +++ b/modules/theora/video_stream_theora.cpp @@ -32,9 +32,9 @@ #include "os/os.h" #include "yuv2rgb.h" -int VideoStreamPlaybackTheora:: buffer_data() { +int VideoStreamPlaybackTheora::buffer_data() { - char *buffer=ogg_sync_buffer(&oy,4096); + char *buffer = ogg_sync_buffer(&oy, 4096); #ifdef THEORA_USE_THREAD_STREAMING @@ -42,44 +42,44 @@ int VideoStreamPlaybackTheora:: buffer_data() { do { thread_sem->post(); - read = MIN(ring_buffer.data_left(),4096); + read = MIN(ring_buffer.data_left(), 4096); if (read) { - ring_buffer.read((uint8_t*)buffer,read); - ogg_sync_wrote(&oy,read); + ring_buffer.read((uint8_t *)buffer, read); + ogg_sync_wrote(&oy, read); } else { OS::get_singleton()->delay_usec(100); } - } while(read==0); + } while (read == 0); return read; #else - int bytes=file->get_buffer((uint8_t*)buffer, 4096); - ogg_sync_wrote(&oy,bytes); - return(bytes); + int bytes = file->get_buffer((uint8_t *)buffer, 4096); + ogg_sync_wrote(&oy, bytes); + return (bytes); #endif } -int VideoStreamPlaybackTheora::queue_page(ogg_page *page){ - if(theora_p) { - ogg_stream_pagein(&to,page); - if (to.e_o_s) - theora_eos=true; - } - if(vorbis_p) { - ogg_stream_pagein(&vo,page); - if (vo.e_o_s) - vorbis_eos=true; - } - return 0; +int VideoStreamPlaybackTheora::queue_page(ogg_page *page) { + if (theora_p) { + ogg_stream_pagein(&to, page); + if (to.e_o_s) + theora_eos = true; + } + if (vorbis_p) { + ogg_stream_pagein(&vo, page); + if (vo.e_o_s) + vorbis_eos = true; + } + return 0; } -void VideoStreamPlaybackTheora::video_write(void){ +void VideoStreamPlaybackTheora::video_write(void) { th_ycbcr_buffer yuv; - th_decode_ycbcr_out(td,yuv); + th_decode_ycbcr_out(td, yuv); /* int y_offset, uv_offset; @@ -113,27 +113,27 @@ void VideoStreamPlaybackTheora::video_write(void){ frame_data.resize(size.x * size.y * pitch); { DVector<uint8_t>::Write w = frame_data.write(); - char* dst = (char*)w.ptr(); + char *dst = (char *)w.ptr(); //uv_offset=(ti.pic_x/2)+(yuv[1].stride)*(ti.pic_y/2); if (px_fmt == TH_PF_444) { - yuv444_2_rgb8888((uint8_t*)dst, (uint8_t*)yuv[0].data, (uint8_t*)yuv[1].data, (uint8_t*)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x<<2, 0); + yuv444_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0); } else if (px_fmt == TH_PF_422) { - yuv422_2_rgb8888((uint8_t*)dst, (uint8_t*)yuv[0].data, (uint8_t*)yuv[1].data, (uint8_t*)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x<<2, 0); + yuv422_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0); } else if (px_fmt == TH_PF_420) { - yuv420_2_rgb8888((uint8_t*)dst, (uint8_t*)yuv[0].data, (uint8_t*)yuv[2].data, (uint8_t*)yuv[1].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x<<2, 0); + yuv420_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[2].data, (uint8_t *)yuv[1].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0); }; format = Image::FORMAT_RGBA; } - Image img(size.x,size.y,0,Image::FORMAT_RGBA,frame_data); //zero copy image creation + Image img(size.x, size.y, 0, Image::FORMAT_RGBA, frame_data); //zero copy image creation texture->set_data(img); //zero copy send to visual server @@ -238,7 +238,7 @@ void VideoStreamPlaybackTheora::clear() { if (!file) return; - if(vorbis_p){ + if (vorbis_p) { ogg_stream_clear(&vo); if (vorbis_p >= 3) { vorbis_block_clear(&vb); @@ -248,7 +248,7 @@ void VideoStreamPlaybackTheora::clear() { vorbis_info_clear(&vi); vorbis_p = 0; } - if(theora_p){ + if (theora_p) { ogg_stream_clear(&to); th_decode_free(td); th_comment_clear(&tc); @@ -258,11 +258,11 @@ void VideoStreamPlaybackTheora::clear() { ogg_sync_clear(&oy); #ifdef THEORA_USE_THREAD_STREAMING - thread_exit=true; + thread_exit = true; thread_sem->post(); //just in case Thread::wait_to_finish(thread); memdelete(thread); - thread=NULL; + thread = NULL; ring_buffer.clear(); #endif //file_name = ""; @@ -272,21 +272,21 @@ void VideoStreamPlaybackTheora::clear() { videobuf_ready = 0; frames_pending = 0; videobuf_time = 0; - theora_eos=false; - vorbis_eos=false; + theora_eos = false; + vorbis_eos = false; if (file) { memdelete(file); } - file=NULL; + file = NULL; playing = false; }; -void VideoStreamPlaybackTheora::set_file(const String& p_file) { +void VideoStreamPlaybackTheora::set_file(const String &p_file) { ERR_FAIL_COND(playing); ogg_packet op; - th_setup_info *ts = NULL; + th_setup_info *ts = NULL; file_name = p_file; if (file) { @@ -296,14 +296,14 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { ERR_FAIL_COND(!file); #ifdef THEORA_USE_THREAD_STREAMING - thread_exit=false; - thread_eof=false; + thread_exit = false; + thread_eof = false; //pre-fill buffer int to_read = ring_buffer.space_left(); - int read = file->get_buffer(read_buffer.ptr(),to_read); - ring_buffer.write(read_buffer.ptr(),read); + int read = file->get_buffer(read_buffer.ptr(), to_read); + ring_buffer.write(read_buffer.ptr(), read); - thread=Thread::create(_streaming_thread,this); + thread = Thread::create(_streaming_thread, this); #endif @@ -317,42 +317,39 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { th_comment_init(&tc); th_info_init(&ti); - theora_eos=false; - vorbis_eos=false; + theora_eos = false; + vorbis_eos = false; /* Ogg file open; parse the headers */ /* Only interested in Vorbis/Theora streams */ int stateflag = 0; - int audio_track_skip=audio_track; - + int audio_track_skip = audio_track; - while(!stateflag){ - int ret=buffer_data(); - if(ret==0)break; - while(ogg_sync_pageout(&oy,&og)>0){ + while (!stateflag) { + int ret = buffer_data(); + if (ret == 0) break; + while (ogg_sync_pageout(&oy, &og) > 0) { ogg_stream_state test; /* is this a mandated initial header? If not, stop parsing */ - if(!ogg_page_bos(&og)){ + if (!ogg_page_bos(&og)) { /* don't leak the page; get it into the appropriate stream */ queue_page(&og); - stateflag=1; + stateflag = 1; break; } - ogg_stream_init(&test,ogg_page_serialno(&og)); - ogg_stream_pagein(&test,&og); - ogg_stream_packetout(&test,&op); - + ogg_stream_init(&test, ogg_page_serialno(&og)); + ogg_stream_pagein(&test, &og); + ogg_stream_packetout(&test, &op); /* identify the codec: try theora */ - if(!theora_p && th_decode_headerin(&ti,&tc,&ts,&op)>=0){ + if (!theora_p && th_decode_headerin(&ti, &tc, &ts, &op) >= 0) { /* it is theora */ - copymem(&to,&test,sizeof(test)); - theora_p=1; - }else if(!vorbis_p && vorbis_synthesis_headerin(&vi,&vc,&op)>=0){ - + copymem(&to, &test, sizeof(test)); + theora_p = 1; + } else if (!vorbis_p && vorbis_synthesis_headerin(&vi, &vc, &op) >= 0) { /* it is vorbis */ if (audio_track_skip) { @@ -364,10 +361,10 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { audio_track_skip--; } else { - copymem(&vo,&test,sizeof(test)); - vorbis_p=1; + copymem(&vo, &test, sizeof(test)); + vorbis_p = 1; } - }else{ + } else { /* whatever it is, we don't care about it */ ogg_stream_clear(&test); } @@ -376,20 +373,20 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { } /* we're expecting more header packets. */ - while((theora_p && theora_p<3) || (vorbis_p && vorbis_p<3)){ + while ((theora_p && theora_p < 3) || (vorbis_p && vorbis_p < 3)) { int ret; /* look for further theora headers */ - while(theora_p && (theora_p<3) && (ret=ogg_stream_packetout(&to,&op))){ - if(ret<0){ - fprintf(stderr,"Error parsing Theora stream headers; " - "corrupt stream?\n"); + while (theora_p && (theora_p < 3) && (ret = ogg_stream_packetout(&to, &op))) { + if (ret < 0) { + fprintf(stderr, "Error parsing Theora stream headers; " + "corrupt stream?\n"); clear(); return; } - if(!th_decode_headerin(&ti,&tc,&ts,&op)){ - fprintf(stderr,"Error parsing Theora stream headers; " - "corrupt stream?\n"); + if (!th_decode_headerin(&ti, &tc, &ts, &op)) { + fprintf(stderr, "Error parsing Theora stream headers; " + "corrupt stream?\n"); clear(); return; } @@ -397,31 +394,31 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { } /* look for more vorbis header packets */ - while(vorbis_p && (vorbis_p<3) && (ret=ogg_stream_packetout(&vo,&op))){ - if(ret<0){ - fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n"); + while (vorbis_p && (vorbis_p < 3) && (ret = ogg_stream_packetout(&vo, &op))) { + if (ret < 0) { + fprintf(stderr, "Error parsing Vorbis stream headers; corrupt stream?\n"); clear(); return; } - ret = vorbis_synthesis_headerin(&vi,&vc,&op); - if(ret){ - fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n"); + ret = vorbis_synthesis_headerin(&vi, &vc, &op); + if (ret) { + fprintf(stderr, "Error parsing Vorbis stream headers; corrupt stream?\n"); clear(); return; } vorbis_p++; - if(vorbis_p==3)break; + if (vorbis_p == 3) break; } /* The header pages/packets will arrive before anything else we care about, or the stream is not obeying spec */ - if(ogg_sync_pageout(&oy,&og)>0){ + if (ogg_sync_pageout(&oy, &og) > 0) { queue_page(&og); /* demux into the appropriate stream */ - }else{ - int ret=buffer_data(); /* someone needs more data */ - if(ret==0){ - fprintf(stderr,"End of file while searching for codec headers.\n"); + } else { + int ret = buffer_data(); /* someone needs more data */ + if (ret == 0) { + fprintf(stderr, "End of file while searching for codec headers.\n"); clear(); return; } @@ -429,30 +426,30 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { } /* and now we have it all. initialize decoders */ - if(theora_p){ - td=th_decode_alloc(&ti,ts); + if (theora_p) { + td = th_decode_alloc(&ti, ts); printf("Ogg logical stream %lx is Theora %dx%d %.02f fps", - to.serialno,ti.pic_width,ti.pic_height, - (double)ti.fps_numerator/ti.fps_denominator); - px_fmt=ti.pixel_fmt; - switch(ti.pixel_fmt){ - case TH_PF_420: printf(" 4:2:0 video\n"); break; - case TH_PF_422: printf(" 4:2:2 video\n"); break; - case TH_PF_444: printf(" 4:4:4 video\n"); break; - case TH_PF_RSVD: - default: - printf(" video\n (UNKNOWN Chroma sampling!)\n"); - break; + to.serialno, ti.pic_width, ti.pic_height, + (double)ti.fps_numerator / ti.fps_denominator); + px_fmt = ti.pixel_fmt; + switch (ti.pixel_fmt) { + case TH_PF_420: printf(" 4:2:0 video\n"); break; + case TH_PF_422: printf(" 4:2:2 video\n"); break; + case TH_PF_444: printf(" 4:4:4 video\n"); break; + case TH_PF_RSVD: + default: + printf(" video\n (UNKNOWN Chroma sampling!)\n"); + break; } - if(ti.pic_width!=ti.frame_width || ti.pic_height!=ti.frame_height) + if (ti.pic_width != ti.frame_width || ti.pic_height != ti.frame_height) printf(" Frame content is %dx%d with offset (%d,%d).\n", - ti.frame_width, ti.frame_height, ti.pic_x, ti.pic_y); - th_decode_ctl(td,TH_DECCTL_GET_PPLEVEL_MAX,&pp_level_max, - sizeof(pp_level_max)); - pp_level=pp_level_max; - pp_level=0; - th_decode_ctl(td,TH_DECCTL_SET_PPLEVEL,&pp_level,sizeof(pp_level)); - pp_inc=0; + ti.frame_width, ti.frame_height, ti.pic_x, ti.pic_y); + th_decode_ctl(td, TH_DECCTL_GET_PPLEVEL_MAX, &pp_level_max, + sizeof(pp_level_max)); + pp_level = pp_level_max; + pp_level = 0; + th_decode_ctl(td, TH_DECCTL_SET_PPLEVEL, &pp_level, sizeof(pp_level)); + pp_inc = 0; /*{ int arg = 0xffff; @@ -465,14 +462,14 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { int w; int h; - w=(ti.pic_x+ti.frame_width+1&~1)-(ti.pic_x&~1); - h=(ti.pic_y+ti.frame_height+1&~1)-(ti.pic_y&~1); + w = (ti.pic_x + ti.frame_width + 1 & ~1) - (ti.pic_x & ~1); + h = (ti.pic_y + ti.frame_height + 1 & ~1) - (ti.pic_y & ~1); size.x = w; size.y = h; - texture->create(w,h,Image::FORMAT_RGBA,Texture::FLAG_FILTER|Texture::FLAG_VIDEO_SURFACE); + texture->create(w, h, Image::FORMAT_RGBA, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE); - }else{ + } else { /* tear down the partial theora setup */ th_info_clear(&ti); th_comment_clear(&tc); @@ -480,32 +477,30 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) { th_setup_free(ts); - if(vorbis_p){ - vorbis_synthesis_init(&vd,&vi); - vorbis_block_init(&vd,&vb); - fprintf(stderr,"Ogg logical stream %lx is Vorbis %d channel %ld Hz audio.\n", - vo.serialno,vi.channels,vi.rate); + if (vorbis_p) { + vorbis_synthesis_init(&vd, &vi); + vorbis_block_init(&vd, &vb); + fprintf(stderr, "Ogg logical stream %lx is Vorbis %d channel %ld Hz audio.\n", + vo.serialno, vi.channels, vi.rate); //_setup(vi.channels, vi.rate); - }else{ + } else { /* tear down the partial vorbis setup */ vorbis_info_clear(&vi); vorbis_comment_clear(&vc); } playing = false; - buffering=true; - time=0; - audio_frames_wrote=0; - - + buffering = true; + time = 0; + audio_frames_wrote = 0; }; float VideoStreamPlaybackTheora::get_time() const { //print_line("total: "+itos(get_total())+" todo: "+itos(get_todo())); //return MAX(0,time-((get_total())/(float)vi.rate)); - return time-AudioServer::get_singleton()->get_output_delay()-delay_compensation;//-((get_total())/(float)vi.rate); + return time - AudioServer::get_singleton()->get_output_delay() - delay_compensation; //-((get_total())/(float)vi.rate); }; Ref<Texture> VideoStreamPlaybackTheora::get_texture() { @@ -523,8 +518,6 @@ void VideoStreamPlaybackTheora::update(float p_delta) { return; }; - - #ifdef THEORA_USE_THREAD_STREAMING thread_sem->post(); #endif @@ -532,112 +525,102 @@ void VideoStreamPlaybackTheora::update(float p_delta) { //double ctime =AudioServer::get_singleton()->get_mix_time(); //print_line("play "+rtos(p_delta)); - time+=p_delta; + time += p_delta; - if (videobuf_time>get_time()) { + if (videobuf_time > get_time()) { return; //no new frames need to be produced } - bool frame_done=false; - bool audio_done=!vorbis_p; + bool frame_done = false; + bool audio_done = !vorbis_p; while (!frame_done || (!audio_done && !vorbis_eos)) { //a frame needs to be produced ogg_packet op; - bool no_theora=false; - + bool no_theora = false; while (vorbis_p) { int ret; float **pcm; - bool buffer_full=false; + bool buffer_full = false; /* if there's pending, decoded audio, grab it */ - if ((ret=vorbis_synthesis_pcmout(&vd,&pcm))>0) { + if ((ret = vorbis_synthesis_pcmout(&vd, &pcm)) > 0) { - - - const int AUXBUF_LEN=4096; + const int AUXBUF_LEN = 4096; int to_read = ret; int16_t aux_buffer[AUXBUF_LEN]; - while(to_read) { + while (to_read) { - int m = MIN(AUXBUF_LEN/vi.channels,to_read); + int m = MIN(AUXBUF_LEN / vi.channels, to_read); int count = 0; - for(int j=0;j<m;j++){ - for(int i=0;i<vi.channels;i++){ + for (int j = 0; j < m; j++) { + for (int i = 0; i < vi.channels; i++) { - int val=Math::fast_ftoi(pcm[i][j]*32767.f); - if(val>32767)val=32767; - if(val<-32768)val=-32768; + int val = Math::fast_ftoi(pcm[i][j] * 32767.f); + if (val > 32767) val = 32767; + if (val < -32768) val = -32768; aux_buffer[count++] = val; } } if (mix_callback) { - int mixed = mix_callback(mix_udata,aux_buffer,m); - to_read-=mixed; - if (mixed!=m) { //could mix no more - buffer_full=true; + int mixed = mix_callback(mix_udata, aux_buffer, m); + to_read -= mixed; + if (mixed != m) { //could mix no more + buffer_full = true; break; } } else { - to_read-=m; //just pretend we sent the audio + to_read -= m; //just pretend we sent the audio } - - } + int tr = vorbis_synthesis_read(&vd, ret - to_read); - int tr = vorbis_synthesis_read(&vd, ret-to_read); - - - if (vd.granulepos>=0) { - // print_line("wrote: "+itos(audio_frames_wrote)+" gpos: "+itos(vd.granulepos)); + if (vd.granulepos >= 0) { + // print_line("wrote: "+itos(audio_frames_wrote)+" gpos: "+itos(vd.granulepos)); } //print_line("mix audio!"); - audio_frames_wrote+=ret-to_read; + audio_frames_wrote += ret - to_read; //print_line("AGP: "+itos(vd.granulepos)+" added "+itos(ret-to_read)); - } else { /* no pending audio; is there a pending packet to decode? */ - if (ogg_stream_packetout(&vo,&op)>0){ - if(vorbis_synthesis(&vb,&op)==0) { /* test for success! */ - vorbis_synthesis_blockin(&vd,&vb); + if (ogg_stream_packetout(&vo, &op) > 0) { + if (vorbis_synthesis(&vb, &op) == 0) { /* test for success! */ + vorbis_synthesis_blockin(&vd, &vb); } - } else { /* we need more data; break out to suck in another page */ + } else { /* we need more data; break out to suck in another page */ //printf("need moar data\n"); break; }; } - - audio_done = videobuf_time < (audio_frames_wrote/float(vi.rate)); + audio_done = videobuf_time < (audio_frames_wrote / float(vi.rate)); if (buffer_full) break; } - while(theora_p && !frame_done){ + while (theora_p && !frame_done) { /* theora is one in, one out... */ - if(ogg_stream_packetout(&to,&op)>0){ + if (ogg_stream_packetout(&to, &op) > 0) { - - if(false && pp_inc){ - pp_level+=pp_inc; - th_decode_ctl(td,TH_DECCTL_SET_PPLEVEL,&pp_level, - sizeof(pp_level)); - pp_inc=0; + if (false && pp_inc) { + pp_level += pp_inc; + th_decode_ctl(td, TH_DECCTL_SET_PPLEVEL, &pp_level, + sizeof(pp_level)); + pp_inc = 0; } /*HACK: This should be set after a seek or a gap, but we might not have a granulepos for the first packet (we only have them for the last @@ -645,13 +628,13 @@ void VideoStreamPlaybackTheora::update(float p_delta) { To do this right, we should back-track from the last packet on the page and compute the correct granulepos for the first packet after a seek or a gap.*/ - if(op.granulepos>=0){ - th_decode_ctl(td,TH_DECCTL_SET_GRANPOS,&op.granulepos, - sizeof(op.granulepos)); + if (op.granulepos >= 0) { + th_decode_ctl(td, TH_DECCTL_SET_GRANPOS, &op.granulepos, + sizeof(op.granulepos)); } ogg_int64_t videobuf_granulepos; - if(th_decode_packetin(td,&op,&videobuf_granulepos)==0){ - videobuf_time=th_granule_time(td,videobuf_granulepos); + if (th_decode_packetin(td, &op, &videobuf_granulepos) == 0) { + videobuf_time = th_granule_time(td, videobuf_granulepos); //printf("frame time %f, play time %f, ready %i\n", (float)videobuf_time, get_time(), videobuf_ready); @@ -661,27 +644,25 @@ void VideoStreamPlaybackTheora::update(float p_delta) { keyframing. Soon enough libtheora will be able to deal with non-keyframe seeks. */ - if(videobuf_time>=get_time()) { - frame_done=true; - } else{ + if (videobuf_time >= get_time()) { + frame_done = true; + } else { /*If we are too slow, reduce the pp level.*/ - pp_inc=pp_level>0?-1:0; + pp_inc = pp_level > 0 ? -1 : 0; } } else { - } } else { - no_theora=true; + no_theora = true; break; } } - - //print_line("no theora: "+itos(no_theora)+" theora eos: "+itos(theora_eos)+" frame done "+itos(frame_done)); +//print_line("no theora: "+itos(no_theora)+" theora eos: "+itos(theora_eos)+" frame done "+itos(frame_done)); #ifdef THEORA_USE_THREAD_STREAMING - if (file && thread_eof && no_theora && theora_eos && ring_buffer.data_left()==0) { + if (file && thread_eof && no_theora && theora_eos && ring_buffer.data_left() == 0) { #else if (file && /*!videobuf_ready && */ no_theora && theora_eos) { #endif @@ -689,7 +670,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) { stop(); return; }; - #if 0 +#if 0 if (!videobuf_ready || audio_todo > 0){ /* no data yet for somebody. Grab another page */ @@ -698,23 +679,22 @@ void VideoStreamPlaybackTheora::update(float p_delta) { queue_page(&og); } } - #else - +#else - if (!frame_done || !audio_done){ + if (!frame_done || !audio_done) { //what's the point of waiting for audio to grab a page? buffer_data(); - while(ogg_sync_pageout(&oy,&og)>0){ + while (ogg_sync_pageout(&oy, &og) > 0) { queue_page(&og); } } - #endif +#endif /* If playback has begun, top audio buffer off immediately. */ //if(stateflag) audio_write_nonblocking(); /* are we at or past time for this video frame? */ - if(videobuf_ready && videobuf_time<=get_time()){ + if (videobuf_ready && videobuf_time <= get_time()) { //video_write(); //videobuf_ready=0; @@ -722,35 +702,29 @@ void VideoStreamPlaybackTheora::update(float p_delta) { //printf("frame at %f not ready (time %f), ready %i\n", (float)videobuf_time, get_time(), videobuf_ready); } - float tdiff=videobuf_time-get_time(); + float tdiff = videobuf_time - get_time(); /*If we have lots of extra time, increase the post-processing level.*/ - if(tdiff>ti.fps_denominator*0.25/ti.fps_numerator){ - pp_inc=pp_level<pp_level_max?1:0; - } - else if(tdiff<ti.fps_denominator*0.05/ti.fps_numerator){ - pp_inc=pp_level>0?-1:0; + if (tdiff > ti.fps_denominator * 0.25 / ti.fps_numerator) { + pp_inc = pp_level < pp_level_max ? 1 : 0; + } else if (tdiff < ti.fps_denominator * 0.05 / ti.fps_numerator) { + pp_inc = pp_level > 0 ? -1 : 0; } - } video_write(); - }; - void VideoStreamPlaybackTheora::play() { if (!playing) - time=0; + time = 0; else { stop(); } playing = true; - delay_compensation=Globals::get_singleton()->get("audio/video_delay_compensation_ms"); - delay_compensation/=1000.0; - - + delay_compensation = Globals::get_singleton()->get("audio/video_delay_compensation_ms"); + delay_compensation /= 1000.0; }; void VideoStreamPlaybackTheora::stop() { @@ -761,7 +735,7 @@ void VideoStreamPlaybackTheora::stop() { set_file(file_name); //reset } playing = false; - time=0; + time = 0; }; bool VideoStreamPlaybackTheora::is_playing() const { @@ -771,7 +745,7 @@ bool VideoStreamPlaybackTheora::is_playing() const { void VideoStreamPlaybackTheora::set_paused(bool p_paused) { - paused=p_paused; + paused = p_paused; //pau = !p_paused; }; @@ -780,7 +754,7 @@ bool VideoStreamPlaybackTheora::is_paused(bool p_paused) const { return paused; }; -void VideoStreamPlaybackTheora::set_loop(bool p_enable) { +void VideoStreamPlaybackTheora::set_loop(bool p_enable){ }; @@ -809,52 +783,49 @@ float VideoStreamPlaybackTheora::get_pos() const { return get_time(); }; -void VideoStreamPlaybackTheora::seek_pos(float p_time) { +void VideoStreamPlaybackTheora::seek_pos(float p_time){ // no }; -void VideoStreamPlaybackTheora::set_mix_callback(AudioMixCallback p_callback,void *p_userdata) { +void VideoStreamPlaybackTheora::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) { - mix_callback=p_callback; - mix_udata=p_userdata; + mix_callback = p_callback; + mix_udata = p_userdata; } -int VideoStreamPlaybackTheora::get_channels() const{ +int VideoStreamPlaybackTheora::get_channels() const { return vi.channels; } void VideoStreamPlaybackTheora::set_audio_track(int p_idx) { - audio_track=p_idx; + audio_track = p_idx; } -int VideoStreamPlaybackTheora::get_mix_rate() const{ +int VideoStreamPlaybackTheora::get_mix_rate() const { return vi.rate; } #ifdef THEORA_USE_THREAD_STREAMING - void VideoStreamPlaybackTheora::_streaming_thread(void *ud) { - VideoStreamPlaybackTheora *vs=(VideoStreamPlaybackTheora*)ud; + VideoStreamPlaybackTheora *vs = (VideoStreamPlaybackTheora *)ud; - while(!vs->thread_exit) { + while (!vs->thread_exit) { //just fill back the buffer if (!vs->thread_eof) { int to_read = vs->ring_buffer.space_left(); if (to_read) { - int read = vs->file->get_buffer(vs->read_buffer.ptr(),to_read); - vs->ring_buffer.write(vs->read_buffer.ptr(),read); - vs->thread_eof=vs->file->eof_reached(); + int read = vs->file->get_buffer(vs->read_buffer.ptr(), to_read); + vs->ring_buffer.write(vs->read_buffer.ptr(), read); + vs->thread_eof = vs->file->eof_reached(); } - - } vs->thread_sem->wait(); @@ -872,24 +843,24 @@ VideoStreamPlaybackTheora::VideoStreamPlaybackTheora() { playing = false; frames_pending = 0; videobuf_time = 0; - paused=false; + paused = false; - buffering=false; - texture = Ref<ImageTexture>( memnew(ImageTexture )); - mix_callback=NULL; - mix_udata=NULL; - audio_track=0; - delay_compensation=0; - audio_frames_wrote=0; + buffering = false; + texture = Ref<ImageTexture>(memnew(ImageTexture)); + mix_callback = NULL; + mix_udata = NULL; + audio_track = 0; + delay_compensation = 0; + audio_frames_wrote = 0; #ifdef THEORA_USE_THREAD_STREAMING - int rb_power = nearest_shift(RB_SIZE_KB*1024); + int rb_power = nearest_shift(RB_SIZE_KB * 1024); ring_buffer.resize(rb_power); - read_buffer.resize(RB_SIZE_KB*1024); - thread_sem=Semaphore::create(); - thread=NULL; - thread_exit=false; - thread_eof=false; + read_buffer.resize(RB_SIZE_KB * 1024); + thread_sem = Semaphore::create(); + thread = NULL; + thread_exit = false; + thread_eof = false; #endif }; @@ -904,20 +875,17 @@ VideoStreamPlaybackTheora::~VideoStreamPlaybackTheora() { if (file) memdelete(file); - - }; - -RES ResourceFormatLoaderVideoStreamTheora::load(const String &p_path,const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderVideoStreamTheora::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; VideoStreamTheora *stream = memnew(VideoStreamTheora); stream->set_file(p_path); if (r_error) - *r_error=OK; + *r_error = OK; return Ref<VideoStreamTheora>(stream); } @@ -927,14 +895,14 @@ void ResourceFormatLoaderVideoStreamTheora::get_recognized_extensions(List<Strin p_extensions->push_back("ogm"); p_extensions->push_back("ogv"); } -bool ResourceFormatLoaderVideoStreamTheora::handles_type(const String& p_type) const { - return (p_type=="VideoStream" || p_type=="VideoStreamTheora"); +bool ResourceFormatLoaderVideoStreamTheora::handles_type(const String &p_type) const { + return (p_type == "VideoStream" || p_type == "VideoStreamTheora"); } String ResourceFormatLoaderVideoStreamTheora::get_resource_type(const String &p_path) const { - String exl=p_path.extension().to_lower(); - if (exl=="ogm" || exl=="ogv") + String exl = p_path.extension().to_lower(); + if (exl == "ogm" || exl == "ogv") return "VideoStreamTheora"; return ""; } diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h index afb8fc986..e42cdfffd 100644 --- a/modules/theora/video_stream_theora.h +++ b/modules/theora/video_stream_theora.h @@ -31,8 +31,8 @@ #include "io/resource_loader.h" #include "os/file_access.h" -#include "os/thread.h" #include "os/semaphore.h" +#include "os/thread.h" #include "ring_buffer.h" #include "scene/resources/video_stream.h" @@ -53,7 +53,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { Image::Format format; DVector<uint8_t> frame_data; int frames_pending; - FileAccess* file; + FileAccess *file; String file_name; int audio_frames_wrote; Point2i size; @@ -66,18 +66,18 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { bool theora_eos; bool vorbis_eos; - ogg_sync_state oy; - ogg_page og; + ogg_sync_state oy; + ogg_page og; ogg_stream_state vo; ogg_stream_state to; - th_info ti; - th_comment tc; - th_dec_ctx *td; - vorbis_info vi; + th_info ti; + th_comment tc; + th_dec_ctx *td; + vorbis_info vi; vorbis_dsp_state vd; - vorbis_block vb; - vorbis_comment vc; - th_pixel_fmt px_fmt; + vorbis_block vb; + vorbis_comment vc; + th_pixel_fmt px_fmt; double videobuf_time; int pp_inc; @@ -97,13 +97,13 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { Ref<ImageTexture> texture; AudioMixCallback mix_callback; - void* mix_udata; + void *mix_udata; bool paused; #ifdef THEORA_USE_THREAD_STREAMING enum { - RB_SIZE_KB=1024 + RB_SIZE_KB = 1024 }; RingBuffer<uint8_t> ring_buffer; @@ -117,15 +117,12 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { #endif - int audio_track; protected: - void clear(); - -public: +public: virtual void play(); virtual void stop(); virtual bool is_playing() const; @@ -145,13 +142,12 @@ public: virtual float get_pos() const; virtual void seek_pos(float p_time); - - void set_file(const String& p_file); + void set_file(const String &p_file); virtual Ref<Texture> get_texture(); virtual void update(float p_delta); - virtual void set_mix_callback(AudioMixCallback p_callback,void *p_userdata); + virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata); virtual int get_channels() const; virtual int get_mix_rate() const; @@ -161,39 +157,33 @@ public: ~VideoStreamPlaybackTheora(); }; - - class VideoStreamTheora : public VideoStream { - OBJ_TYPE(VideoStreamTheora,VideoStream); + OBJ_TYPE(VideoStreamTheora, VideoStream); String file; int audio_track; - public: - Ref<VideoStreamPlayback> instance_playback() { - Ref<VideoStreamPlaybackTheora> pb = memnew( VideoStreamPlaybackTheora ); + Ref<VideoStreamPlaybackTheora> pb = memnew(VideoStreamPlaybackTheora); pb->set_audio_track(audio_track); pb->set_file(file); return pb; } - void set_file(const String& p_file) { file=p_file; } - void set_audio_track(int p_track) { audio_track=p_track; } - - VideoStreamTheora() { audio_track=0; } + void set_file(const String &p_file) { file = p_file; } + void set_audio_track(int p_track) { audio_track = p_track; } + VideoStreamTheora() { audio_track = 0; } }; class ResourceFormatLoaderVideoStreamTheora : public ResourceFormatLoader { public: - 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 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; - }; #endif diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp index 59794be29..b79bcd034 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp @@ -28,60 +28,57 @@ /*************************************************************************/ #include "audio_stream_ogg_vorbis.h" - - -size_t AudioStreamPlaybackOGGVorbis::_ov_read_func(void *p_dst,size_t p_data, size_t p_count, void *_f) { +size_t AudioStreamPlaybackOGGVorbis::_ov_read_func(void *p_dst, size_t p_data, size_t p_count, void *_f) { //printf("read to %p, %i bytes, %i nmemb, %p\n",p_dst,p_data,p_count,_f); - FileAccess *fa=(FileAccess*)_f; - size_t read_total = p_data*p_count; + FileAccess *fa = (FileAccess *)_f; + size_t read_total = p_data * p_count; if (fa->eof_reached()) return 0; - uint8_t *dst=(uint8_t*)p_dst; + uint8_t *dst = (uint8_t *)p_dst; int read = fa->get_buffer(dst, read_total); return read; } -int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f,ogg_int64_t offs, int whence) { +int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f, ogg_int64_t offs, int whence) { - //printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence); +//printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence); #ifdef SEEK_SET //printf("seek set defined\n"); - FileAccess *fa=(FileAccess*)_f; + FileAccess *fa = (FileAccess *)_f; - if (whence==SEEK_SET) { + if (whence == SEEK_SET) { fa->seek(offs); - } else if (whence==SEEK_CUR) { + } else if (whence == SEEK_CUR) { - fa->seek(fa->get_pos()+offs); - } else if (whence==SEEK_END) { + fa->seek(fa->get_pos() + offs); + } else if (whence == SEEK_END) { fa->seek_end(offs); } else { ERR_PRINT("BUG, wtf was whence set to?\n"); } - int ret=fa->eof_reached()?-1:0; + int ret = fa->eof_reached() ? -1 : 0; //printf("returning %i\n",ret); return ret; #else return -1; // no seeking #endif - } int AudioStreamPlaybackOGGVorbis::_ov_close_func(void *_f) { -// printf("close %p\n",_f); + // printf("close %p\n",_f); if (!_f) return 0; - FileAccess *fa=(FileAccess*)_f; + FileAccess *fa = (FileAccess *)_f; if (fa->is_open()) fa->close(); return 0; @@ -90,40 +87,38 @@ long AudioStreamPlaybackOGGVorbis::_ov_tell_func(void *_f) { //printf("close %p\n",_f); - FileAccess *fa=(FileAccess*)_f; + FileAccess *fa = (FileAccess *)_f; return fa->get_pos(); } - - -int AudioStreamPlaybackOGGVorbis::mix(int16_t* p_bufer,int p_frames) { +int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_bufer, int p_frames) { if (!playing) return 0; - int total=p_frames; + int total = p_frames; while (true) { int todo = p_frames; - if (todo==0 || todo<MIN_MIX) { + if (todo == 0 || todo < MIN_MIX) { break; } - //printf("to mix %i - mix me %i bytes\n",to_mix,to_mix*stream_channels*sizeof(int16_t)); +//printf("to mix %i - mix me %i bytes\n",to_mix,to_mix*stream_channels*sizeof(int16_t)); - #ifdef BIG_ENDIAN_ENABLED - long ret=ov_read(&vf,(char*)p_bufer,todo*stream_channels*sizeof(int16_t), 1, 2, 1, ¤t_section); - #else - long ret=ov_read(&vf,(char*)p_bufer,todo*stream_channels*sizeof(int16_t), 0, 2, 1, ¤t_section); - #endif +#ifdef BIG_ENDIAN_ENABLED + long ret = ov_read(&vf, (char *)p_bufer, todo * stream_channels * sizeof(int16_t), 1, 2, 1, ¤t_section); +#else + long ret = ov_read(&vf, (char *)p_bufer, todo * stream_channels * sizeof(int16_t), 0, 2, 1, ¤t_section); +#endif - if (ret<0) { + if (ret < 0) { playing = false; - ERR_EXPLAIN("Error reading OGG Vorbis File: "+file); - ERR_BREAK(ret<0); - } else if (ret==0) { // end of song, reload? + ERR_EXPLAIN("Error reading OGG Vorbis File: " + file); + ERR_BREAK(ret < 0); + } else if (ret == 0) { // end of song, reload? ov_clear(&vf); @@ -131,65 +126,59 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t* p_bufer,int p_frames) { if (!has_loop()) { - playing=false; - repeats=1; + playing = false; + repeats = 1; break; } - f=FileAccess::open(file,FileAccess::READ); + f = FileAccess::open(file, FileAccess::READ); - int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks); - if (errv!=0) { - playing=false; + int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); + if (errv != 0) { + playing = false; break; // :( } if (loop_restart_time) { - bool ok = ov_time_seek(&vf,loop_restart_time)==0; + bool ok = ov_time_seek(&vf, loop_restart_time) == 0; if (!ok) { - playing=false; + playing = false; //ERR_EXPLAIN("loop restart time rejected"); ERR_PRINT("loop restart time rejected") } - frames_mixed=stream_srate*loop_restart_time; + frames_mixed = stream_srate * loop_restart_time; } else { - frames_mixed=0; + frames_mixed = 0; } repeats++; continue; - } - ret/=stream_channels; - ret/=sizeof(int16_t); - - frames_mixed+=ret; + ret /= stream_channels; + ret /= sizeof(int16_t); - p_bufer+=ret*stream_channels; - p_frames-=ret; + frames_mixed += ret; + p_bufer += ret * stream_channels; + p_frames -= ret; } - return total-p_frames; - + return total - p_frames; } - - void AudioStreamPlaybackOGGVorbis::play(float p_from) { if (playing) stop(); - if (_load_stream()!=OK) + if (_load_stream() != OK) return; - - frames_mixed=0; - playing=true; - if (p_from>0) { + frames_mixed = 0; + playing = true; + if (p_from > 0) { seek_pos(p_from); } } @@ -199,7 +188,7 @@ void AudioStreamPlaybackOGGVorbis::_close_file() { if (f) { memdelete(f); - f=NULL; + f = NULL; } } @@ -209,39 +198,35 @@ bool AudioStreamPlaybackOGGVorbis::is_playing() const { void AudioStreamPlaybackOGGVorbis::stop() { _clear_stream(); - playing=false; + playing = false; //_clear(); } - - float AudioStreamPlaybackOGGVorbis::get_pos() const { int32_t frames = int32_t(frames_mixed); if (frames < 0) - frames=0; + frames = 0; return double(frames) / stream_srate; } void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) { - - if (!playing) return; - bool ok = ov_time_seek(&vf,p_time)==0; + bool ok = ov_time_seek(&vf, p_time) == 0; ERR_FAIL_COND(!ok); - frames_mixed=stream_srate*p_time; + frames_mixed = stream_srate * p_time; } -String AudioStreamPlaybackOGGVorbis::get_stream_name() const { +String AudioStreamPlaybackOGGVorbis::get_stream_name() const { return ""; } void AudioStreamPlaybackOGGVorbis::set_loop(bool p_enable) { - loops=p_enable; + loops = p_enable; } bool AudioStreamPlaybackOGGVorbis::has_loop() const { @@ -253,99 +238,103 @@ int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return repeats; } +Error AudioStreamPlaybackOGGVorbis::set_file(const String &p_file) { -Error AudioStreamPlaybackOGGVorbis::set_file(const String& p_file) { - - file=p_file; - stream_valid=false; + file = p_file; + stream_valid = false; Error err; - f=FileAccess::open(file,FileAccess::READ,&err); + f = FileAccess::open(file, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V( err, err ); + ERR_FAIL_COND_V(err, err); } - int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks); - switch(errv) { + int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); + switch (errv) { case OV_EREAD: { // - A read from media returned an error. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CANT_READ ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CANT_READ); } break; - case OV_EVERSION: // - Vorbis version mismatch. + case OV_EVERSION: // - Vorbis version mismatch. case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_UNRECOGNIZED ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } break; case OV_EBADHEADER: { // - Invalid Vorbis bitstream header. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CORRUPT ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CORRUPT); } break; case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_BUG ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_BUG); } break; } - const vorbis_info *vinfo=ov_info(&vf,-1); - stream_channels=vinfo->channels; - stream_srate=vinfo->rate; - length = ov_time_total(&vf,-1); + const vorbis_info *vinfo = ov_info(&vf, -1); + stream_channels = vinfo->channels; + stream_srate = vinfo->rate; + length = ov_time_total(&vf, -1); ov_clear(&vf); memdelete(f); - f=NULL; - stream_valid=true; - + f = NULL; + stream_valid = true; return OK; } -Error AudioStreamPlaybackOGGVorbis::_load_stream() { +Error AudioStreamPlaybackOGGVorbis::_load_stream() { - ERR_FAIL_COND_V(!stream_valid,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED); _clear_stream(); - if (file=="") + if (file == "") return ERR_INVALID_DATA; Error err; - f=FileAccess::open(file,FileAccess::READ,&err); + f = FileAccess::open(file, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V( err, err ); + ERR_FAIL_COND_V(err, err); } - int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks); - switch(errv) { + int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); + switch (errv) { case OV_EREAD: { // - A read from media returned an error. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CANT_READ ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CANT_READ); } break; - case OV_EVERSION: // - Vorbis version mismatch. + case OV_EVERSION: // - Vorbis version mismatch. case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_UNRECOGNIZED ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } break; case OV_EBADHEADER: { // - Invalid Vorbis bitstream header. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_FILE_CORRUPT ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_FILE_CORRUPT); } break; case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); f=NULL; - ERR_FAIL_V( ERR_BUG ); + memdelete(f); + f = NULL; + ERR_FAIL_V(ERR_BUG); } break; } - repeats=0; - stream_loaded=true; - + repeats = 0; + stream_loaded = true; return OK; } - float AudioStreamPlaybackOGGVorbis::get_length() const { if (!stream_loaded) { - if (const_cast<AudioStreamPlaybackOGGVorbis*>(this)->_load_stream()!=OK) + if (const_cast<AudioStreamPlaybackOGGVorbis *>(this)->_load_stream() != OK) return 0; } return length; @@ -359,14 +348,14 @@ void AudioStreamPlaybackOGGVorbis::_clear_stream() { ov_clear(&vf); _close_file(); - stream_loaded=false; + stream_loaded = false; //stream_channels=1; - playing=false; + playing = false; } void AudioStreamPlaybackOGGVorbis::set_paused(bool p_paused) { - paused=p_paused; + paused = p_paused; } bool AudioStreamPlaybackOGGVorbis::is_paused(bool p_paused) const { @@ -374,39 +363,34 @@ bool AudioStreamPlaybackOGGVorbis::is_paused(bool p_paused) const { return paused; } - AudioStreamPlaybackOGGVorbis::AudioStreamPlaybackOGGVorbis() { - loops=false; - playing=false; - _ov_callbacks.read_func=_ov_read_func; - _ov_callbacks.seek_func=_ov_seek_func; - _ov_callbacks.close_func=_ov_close_func; - _ov_callbacks.tell_func=_ov_tell_func; + loops = false; + playing = false; + _ov_callbacks.read_func = _ov_read_func; + _ov_callbacks.seek_func = _ov_seek_func; + _ov_callbacks.close_func = _ov_close_func; + _ov_callbacks.tell_func = _ov_tell_func; f = NULL; - stream_loaded=false; - stream_valid=false; - repeats=0; - paused=true; - stream_channels=0; - stream_srate=0; - current_section=0; - length=0; - loop_restart_time=0; + stream_loaded = false; + stream_valid = false; + repeats = 0; + paused = true; + stream_channels = 0; + stream_srate = 0; + current_section = 0; + length = 0; + loop_restart_time = 0; } - AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { _clear_stream(); - } - - -RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=OK; + *r_error = OK; AudioStreamOGGVorbis *ogg_stream = memnew(AudioStreamOGGVorbis); ogg_stream->set_file(p_path); @@ -419,12 +403,11 @@ void ResourceFormatLoaderAudioStreamOGGVorbis::get_recognized_extensions(List<St } String ResourceFormatLoaderAudioStreamOGGVorbis::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="ogg") + if (p_path.extension().to_lower() == "ogg") return "AudioStreamOGGVorbis"; return ""; } -bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String& p_type) const { - return (p_type=="AudioStream" || p_type=="AudioStreamOGG" || p_type=="AudioStreamOGGVorbis"); +bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String &p_type) const { + return (p_type == "AudioStream" || p_type == "AudioStreamOGG" || p_type == "AudioStreamOGGVorbis"); } - diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h index adeef6cc3..b16b25068 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.h +++ b/modules/vorbis/audio_stream_ogg_vorbis.h @@ -38,18 +38,18 @@ class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback { - OBJ_TYPE(AudioStreamPlaybackOGGVorbis,AudioStreamPlayback); + OBJ_TYPE(AudioStreamPlaybackOGGVorbis, AudioStreamPlayback); enum { - MIN_MIX=1024 + MIN_MIX = 1024 }; FileAccess *f; ov_callbacks _ov_callbacks; float length; - static size_t _ov_read_func(void *p_dst,size_t p_data, size_t p_count, void *_f); - static int _ov_seek_func(void *_f,ogg_int64_t offs, int whence); + static size_t _ov_read_func(void *p_dst, size_t p_data, size_t p_count, void *_f); + static int _ov_seek_func(void *_f, ogg_int64_t offs, int whence); static int _ov_close_func(void *_f); static long _ov_tell_func(void *_f); @@ -63,7 +63,6 @@ class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback { int stream_srate; int current_section; - bool paused; bool loops; int repeats; @@ -75,17 +74,14 @@ class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback { bool stream_valid; float loop_restart_time; - public: + Error set_file(const String &p_file); - - Error set_file(const String& p_file); - - virtual void play(float p_from=0); + virtual void play(float p_from = 0); virtual void stop(); virtual bool is_playing() const; - virtual void set_loop_restart_time(float p_time) { loop_restart_time=p_time; } + virtual void set_loop_restart_time(float p_time) { loop_restart_time = p_time; } virtual void set_paused(bool p_paused); virtual bool is_paused(bool p_paused) const; @@ -106,37 +102,34 @@ public: virtual int get_mix_rate() const { return stream_srate; } virtual int get_minimum_buffer_size() const { return 0; } - virtual int mix(int16_t* p_bufer,int p_frames); + virtual int mix(int16_t *p_bufer, int p_frames); AudioStreamPlaybackOGGVorbis(); ~AudioStreamPlaybackOGGVorbis(); }; - class AudioStreamOGGVorbis : public AudioStream { - OBJ_TYPE(AudioStreamOGGVorbis,AudioStream); + OBJ_TYPE(AudioStreamOGGVorbis, AudioStream); String file; -public: +public: Ref<AudioStreamPlayback> instance_playback() { - Ref<AudioStreamPlaybackOGGVorbis> pb = memnew( AudioStreamPlaybackOGGVorbis ); + Ref<AudioStreamPlaybackOGGVorbis> pb = memnew(AudioStreamPlaybackOGGVorbis); pb->set_file(file); return pb; } - void set_file(const String& p_file) { file=p_file; } - + void set_file(const String &p_file) { file = p_file; } }; class ResourceFormatLoaderAudioStreamOGGVorbis : public ResourceFormatLoader { public: - 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 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; }; - #endif // AUDIO_STREAM_OGG_H diff --git a/modules/vorbis/register_types.cpp b/modules/vorbis/register_types.cpp index d33946249..ef35e77ea 100644 --- a/modules/vorbis/register_types.cpp +++ b/modules/vorbis/register_types.cpp @@ -34,12 +34,12 @@ static ResourceFormatLoaderAudioStreamOGGVorbis *vorbis_stream_loader = NULL; void register_vorbis_types() { - vorbis_stream_loader = memnew( ResourceFormatLoaderAudioStreamOGGVorbis ); + vorbis_stream_loader = memnew(ResourceFormatLoaderAudioStreamOGGVorbis); ResourceLoader::add_resource_format_loader(vorbis_stream_loader); ObjectTypeDB::register_type<AudioStreamOGGVorbis>(); } void unregister_vorbis_types() { - memdelete( vorbis_stream_loader ); + memdelete(vorbis_stream_loader); } diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index ebeb674a7..a4a61ba00 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -29,59 +29,59 @@ #include "image_loader_webp.h" #include "io/marshalls.h" -#include "print_string.h" #include "os/os.h" +#include "print_string.h" #include <stdlib.h> #include <webp/decode.h> #include <webp/encode.h> -static DVector<uint8_t> _webp_lossy_pack(const Image& p_image,float p_quality) { +static DVector<uint8_t> _webp_lossy_pack(const Image &p_image, float p_quality) { - ERR_FAIL_COND_V(p_image.empty(),DVector<uint8_t>()); + ERR_FAIL_COND_V(p_image.empty(), DVector<uint8_t>()); - Image img=p_image; + Image img = p_image; if (img.detect_alpha()) img.convert(Image::FORMAT_RGBA); else img.convert(Image::FORMAT_RGB); - Size2 s(img.get_width(),img.get_height()); + Size2 s(img.get_width(), img.get_height()); DVector<uint8_t> data = img.get_data(); DVector<uint8_t>::Read r = data.read(); - uint8_t *dst_buff=NULL; - size_t dst_size=0; - if (img.get_format()==Image::FORMAT_RGB) { + uint8_t *dst_buff = NULL; + size_t dst_size = 0; + if (img.get_format() == Image::FORMAT_RGB) { - dst_size = WebPEncodeRGB(r.ptr(),s.width,s.height,3*s.width,CLAMP(p_quality*100.0,0,100.0),&dst_buff); + dst_size = WebPEncodeRGB(r.ptr(), s.width, s.height, 3 * s.width, CLAMP(p_quality * 100.0, 0, 100.0), &dst_buff); } else { - dst_size = WebPEncodeRGBA(r.ptr(),s.width,s.height,4*s.width,CLAMP(p_quality*100.0,0,100.0),&dst_buff); + dst_size = WebPEncodeRGBA(r.ptr(), s.width, s.height, 4 * s.width, CLAMP(p_quality * 100.0, 0, 100.0), &dst_buff); } - ERR_FAIL_COND_V(dst_size==0,DVector<uint8_t>()); + ERR_FAIL_COND_V(dst_size == 0, DVector<uint8_t>()); DVector<uint8_t> dst; - dst.resize(4+dst_size); + dst.resize(4 + dst_size); DVector<uint8_t>::Write w = dst.write(); - w[0]='W'; - w[1]='E'; - w[2]='B'; - w[3]='P'; - copymem(&w[4],dst_buff,dst_size); + w[0] = 'W'; + w[1] = 'E'; + w[2] = 'B'; + w[3] = 'P'; + copymem(&w[4], dst_buff, dst_size); free(dst_buff); - w=DVector<uint8_t>::Write(); + w = DVector<uint8_t>::Write(); return dst; } -static Image _webp_lossy_unpack(const DVector<uint8_t>& p_buffer) { +static Image _webp_lossy_unpack(const DVector<uint8_t> &p_buffer) { - int size = p_buffer.size()-4; - ERR_FAIL_COND_V(size<=0,Image()); + int size = p_buffer.size() - 4; + ERR_FAIL_COND_V(size <= 0, Image()); DVector<uint8_t>::Read r = p_buffer.read(); - ERR_FAIL_COND_V(r[0]!='W' || r[1]!='E' || r[2]!='B' || r[3]!='P',Image()); + ERR_FAIL_COND_V(r[0] != 'W' || r[1] != 'E' || r[2] != 'B' || r[3] != 'P', Image()); WebPBitstreamFeatures features; - if (WebPGetFeatures(&r[4],size,&features)!=VP8_STATUS_OK) { + if (WebPGetFeatures(&r[4], size, &features) != VP8_STATUS_OK) { ERR_EXPLAIN("Error unpacking WEBP image:"); ERR_FAIL_V(Image()); } @@ -91,31 +91,27 @@ static Image _webp_lossy_unpack(const DVector<uint8_t>& p_buffer) { //print_line("alpha: "+itos(features.has_alpha)); DVector<uint8_t> dst_image; - int datasize = features.width*features.height*(features.has_alpha?4:3); + int datasize = features.width * features.height * (features.has_alpha ? 4 : 3); dst_image.resize(datasize); DVector<uint8_t>::Write dst_w = dst_image.write(); - bool errdec=false; - if (features.has_alpha) { - errdec = WebPDecodeRGBAInto(&r[4],size,dst_w.ptr(),datasize,4*features.width)==NULL; + bool errdec = false; + if (features.has_alpha) { + errdec = WebPDecodeRGBAInto(&r[4], size, dst_w.ptr(), datasize, 4 * features.width) == NULL; } else { - errdec = WebPDecodeRGBInto(&r[4],size,dst_w.ptr(),datasize,3*features.width)==NULL; - + errdec = WebPDecodeRGBInto(&r[4], size, dst_w.ptr(), datasize, 3 * features.width) == NULL; } //ERR_EXPLAIN("Error decoding webp! - "+p_file); - ERR_FAIL_COND_V(errdec,Image()); + ERR_FAIL_COND_V(errdec, Image()); dst_w = DVector<uint8_t>::Write(); - return Image(features.width,features.height,0,features.has_alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB,dst_image); - + return Image(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA : Image::FORMAT_RGB, dst_image); } - -Error ImageLoaderWEBP::load_image(Image *p_image,FileAccess *f) { - +Error ImageLoaderWEBP::load_image(Image *p_image, FileAccess *f) { uint32_t size = f->get_len(); DVector<uint8_t> src_image; @@ -124,60 +120,53 @@ Error ImageLoaderWEBP::load_image(Image *p_image,FileAccess *f) { WebPBitstreamFeatures features; DVector<uint8_t>::Write src_w = src_image.write(); - f->get_buffer(src_w.ptr(),size); + f->get_buffer(src_w.ptr(), size); ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_EOF); - if (WebPGetFeatures(src_w.ptr(),size,&features)!=VP8_STATUS_OK) { + if (WebPGetFeatures(src_w.ptr(), size, &features) != VP8_STATUS_OK) { f->close(); //ERR_EXPLAIN("Error decoding WEBP image: "+p_file); ERR_FAIL_V(ERR_FILE_CORRUPT); } - print_line("width: "+itos(features.width)); - print_line("height: "+itos(features.height)); - print_line("alpha: "+itos(features.has_alpha)); + print_line("width: " + itos(features.width)); + print_line("height: " + itos(features.height)); + print_line("alpha: " + itos(features.has_alpha)); src_w = DVector<uint8_t>::Write(); DVector<uint8_t> dst_image; - int datasize = features.width*features.height*(features.has_alpha?4:3); + int datasize = features.width * features.height * (features.has_alpha ? 4 : 3); dst_image.resize(datasize); DVector<uint8_t>::Read src_r = src_image.read(); DVector<uint8_t>::Write dst_w = dst_image.write(); - - bool errdec=false; - if (features.has_alpha) { - errdec = WebPDecodeRGBAInto(src_r.ptr(),size,dst_w.ptr(),datasize,4*features.width)==NULL; + bool errdec = false; + if (features.has_alpha) { + errdec = WebPDecodeRGBAInto(src_r.ptr(), size, dst_w.ptr(), datasize, 4 * features.width) == NULL; } else { - errdec = WebPDecodeRGBInto(src_r.ptr(),size,dst_w.ptr(),datasize,3*features.width)==NULL; - + errdec = WebPDecodeRGBInto(src_r.ptr(), size, dst_w.ptr(), datasize, 3 * features.width) == NULL; } //ERR_EXPLAIN("Error decoding webp! - "+p_file); - ERR_FAIL_COND_V(errdec,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(errdec, ERR_FILE_CORRUPT); src_r = DVector<uint8_t>::Read(); dst_w = DVector<uint8_t>::Write(); - *p_image = Image(features.width,features.height,0,features.has_alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB,dst_image); - + *p_image = Image(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA : Image::FORMAT_RGB, dst_image); return OK; - } void ImageLoaderWEBP::get_recognized_extensions(List<String> *p_extensions) const { - + p_extensions->push_back("webp"); } - ImageLoaderWEBP::ImageLoaderWEBP() { - Image::lossy_packer=_webp_lossy_pack; - Image::lossy_unpacker=_webp_lossy_unpack; + Image::lossy_packer = _webp_lossy_pack; + Image::lossy_unpacker = _webp_lossy_unpack; } - - diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h index eb1b32ac9..ccf22bae1 100644 --- a/modules/webp/image_loader_webp.h +++ b/modules/webp/image_loader_webp.h @@ -36,14 +36,10 @@ */ class ImageLoaderWEBP : public ImageFormatLoader { - public: - - virtual Error load_image(Image *p_image,FileAccess *f); - virtual void get_recognized_extensions(List<String> *p_extensions) const; + virtual Error load_image(Image *p_image, FileAccess *f); + virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderWEBP(); }; - - #endif diff --git a/modules/webp/register_types.cpp b/modules/webp/register_types.cpp index 7a4e35dc4..8a708aae6 100644 --- a/modules/webp/register_types.cpp +++ b/modules/webp/register_types.cpp @@ -34,11 +34,11 @@ static ImageLoaderWEBP *image_loader_webp = NULL; void register_webp_types() { - image_loader_webp = memnew( ImageLoaderWEBP ); + image_loader_webp = memnew(ImageLoaderWEBP); ImageLoader::add_image_format_loader(image_loader_webp); } void unregister_webp_types() { - memdelete( image_loader_webp ); + memdelete(image_loader_webp); } |
