diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
commit | 5dbf1809c6e3e905b94b8764e99491e608122261 (patch) | |
tree | 5e5a5360db15d86d59ec8c6e4f7eb511388c5a9a /servers | |
parent | 45438e9918d421b244bfd7776a30e67dc7f2d3e3 (diff) |
A Whole New World (clang-format edition)
I can show you the code
Pretty, with proper whitespace
Tell me, coder, now when did
You last write readable code?
I can open your eyes
Make you see your bad indent
Force you to respect the style
The core devs agreed upon
A whole new world
A new fantastic code format
A de facto standard
With some sugar
Enforced with clang-format
A whole new world
A dazzling style we all dreamed of
And when we read it through
It's crystal clear
That now we're in a whole new world of code
Diffstat (limited to 'servers')
147 files changed, 17030 insertions, 20307 deletions
diff --git a/servers/audio/audio_driver_dummy.cpp b/servers/audio/audio_driver_dummy.cpp index 6c12957851..e3022225a3 100644 --- a/servers/audio/audio_driver_dummy.cpp +++ b/servers/audio/audio_driver_dummy.cpp @@ -31,42 +31,37 @@ #include "global_config.h" #include "os/os.h" - - Error AudioDriverDummy::init() { - active=false; - thread_exited=false; - exit_thread=false; + active = false; + thread_exited = false; + exit_thread = false; pcm_open = false; samples_in = NULL; - mix_rate = 44100; speaker_mode = SPEAKER_MODE_STEREO; channels = 2; - int latency = GLOBAL_DEF("audio/output_latency",25); - buffer_size = nearest_power_of_2( latency * mix_rate / 1000 ); + int latency = GLOBAL_DEF("audio/output_latency", 25); + buffer_size = nearest_power_of_2(latency * mix_rate / 1000); - samples_in = memnew_arr(int32_t, buffer_size*channels); + samples_in = memnew_arr(int32_t, buffer_size * channels); - mutex=Mutex::create(); + mutex = Mutex::create(); thread = Thread::create(AudioDriverDummy::thread_func, this); return OK; }; -void AudioDriverDummy::thread_func(void* p_udata) { +void AudioDriverDummy::thread_func(void *p_udata) { - AudioDriverDummy* ad = (AudioDriverDummy*)p_udata; - - uint64_t usdelay = (ad->buffer_size / float(ad->mix_rate))*1000000; + AudioDriverDummy *ad = (AudioDriverDummy *)p_udata; + uint64_t usdelay = (ad->buffer_size / float(ad->mix_rate)) * 1000000; while (!ad->exit_thread) { - if (!ad->active) { } else { @@ -76,15 +71,12 @@ void AudioDriverDummy::thread_func(void* p_udata) { ad->audio_server_process(ad->buffer_size, ad->samples_in); ad->unlock(); - }; OS::get_singleton()->delay_usec(usdelay); - }; - ad->thread_exited=true; - + ad->thread_exited = true; }; void AudioDriverDummy::start() { @@ -137,12 +129,9 @@ void AudioDriverDummy::finish() { AudioDriverDummy::AudioDriverDummy() { mutex = NULL; - thread=NULL; - + thread = NULL; }; -AudioDriverDummy::~AudioDriverDummy() { +AudioDriverDummy::~AudioDriverDummy(){ }; - - diff --git a/servers/audio/audio_driver_dummy.h b/servers/audio/audio_driver_dummy.h index 78ec41ea09..02f6a5407c 100644 --- a/servers/audio/audio_driver_dummy.h +++ b/servers/audio/audio_driver_dummy.h @@ -31,18 +31,17 @@ #include "servers/audio_server.h" -#include "core/os/thread.h" #include "core/os/mutex.h" - +#include "core/os/thread.h" class AudioDriverDummy : public AudioDriver { - Thread* thread; - Mutex* mutex; + Thread *thread; + Mutex *mutex; - int32_t* samples_in; + int32_t *samples_in; - static void thread_func(void* p_udata); + static void thread_func(void *p_udata); int buffer_size; unsigned int mix_rate; @@ -56,8 +55,7 @@ class AudioDriverDummy : public AudioDriver { bool pcm_open; public: - - const char* get_name() const { + const char *get_name() const { return "Dummy"; }; diff --git a/servers/audio/audio_effect.cpp b/servers/audio/audio_effect.cpp index b0844ff924..bb1179134c 100644 --- a/servers/audio/audio_effect.cpp +++ b/servers/audio/audio_effect.cpp @@ -28,7 +28,5 @@ /*************************************************************************/ #include "audio_effect.h" -AudioEffect::AudioEffect() -{ - +AudioEffect::AudioEffect() { } diff --git a/servers/audio/audio_effect.h b/servers/audio/audio_effect.h index db3ec91195..6981cf0db7 100644 --- a/servers/audio/audio_effect.h +++ b/servers/audio/audio_effect.h @@ -32,22 +32,17 @@ #include "audio_frame.h" #include "resource.h" - class AudioEffectInstance : public Reference { - GDCLASS(AudioEffectInstance,Reference) + GDCLASS(AudioEffectInstance, Reference) public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count)=0; - + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) = 0; }; - class AudioEffect : public Resource { - GDCLASS(AudioEffect,Resource) + GDCLASS(AudioEffect, Resource) public: - - virtual Ref<AudioEffectInstance> instance()=0; + virtual Ref<AudioEffectInstance> instance() = 0; AudioEffect(); }; diff --git a/servers/audio/audio_filter_sw.cpp b/servers/audio/audio_filter_sw.cpp index e97eb75d04..b3ed76f22c 100644 --- a/servers/audio/audio_filter_sw.cpp +++ b/servers/audio/audio_filter_sw.cpp @@ -34,62 +34,57 @@ void AudioFilterSW::set_mode(Mode p_mode) { } void AudioFilterSW::set_cutoff(float p_cutoff) { - cutoff=p_cutoff; + cutoff = p_cutoff; } void AudioFilterSW::set_resonance(float p_resonance) { - resonance=p_resonance; + resonance = p_resonance; } void AudioFilterSW::set_gain(float p_gain) { - gain=p_gain; + gain = p_gain; } void AudioFilterSW::set_sampling_rate(float p_srate) { - sampling_rate=p_srate; + sampling_rate = p_srate; } - void AudioFilterSW::prepare_coefficients(Coeffs *p_coeffs) { - int sr_limit = (sampling_rate/2)+512; - - - double final_cutoff=(cutoff>sr_limit)?sr_limit:cutoff; - if (final_cutoff<1) //avoid crapness - final_cutoff=1; //dont allow less than this + int sr_limit = (sampling_rate / 2) + 512; + double final_cutoff = (cutoff > sr_limit) ? sr_limit : cutoff; + if (final_cutoff < 1) //avoid crapness + final_cutoff = 1; //dont allow less than this + double omega = 2.0 * Math_PI * final_cutoff / sampling_rate; - double omega=2.0*Math_PI*final_cutoff/sampling_rate; + double sin_v = Math::sin(omega); + double cos_v = Math::cos(omega); - double sin_v=Math::sin(omega); - double cos_v=Math::cos(omega); - - double Q=resonance; - if (Q<=0.0) { - Q=0.0001; + double Q = resonance; + if (Q <= 0.0) { + Q = 0.0001; } + if (mode == BANDPASS) + Q *= 2.0; + else if (mode == PEAK) + Q *= 3.0; - if (mode==BANDPASS) - Q*=2.0; - else if (mode==PEAK) - Q*=3.0; - - double tmpgain=gain; + double tmpgain = gain; - if (tmpgain<0.001) - tmpgain=0.001; + if (tmpgain < 0.001) + tmpgain = 0.001; - if (stages>1) { + if (stages > 1) { - Q=(Q>1.0 ? Math::pow(Q,1.0/stages) : Q); - tmpgain = Math::pow(tmpgain,1.0/(stages+1)); + Q = (Q > 1.0 ? Math::pow(Q, 1.0 / stages) : Q); + tmpgain = Math::pow(tmpgain, 1.0 / (stages + 1)); } - double alpha = sin_v/(2*Q); + double alpha = sin_v / (2 * Q); double a0 = 1.0 + alpha; @@ -97,169 +92,159 @@ void AudioFilterSW::prepare_coefficients(Coeffs *p_coeffs) { case LOWPASS: { - p_coeffs->b0= (1.0 - cos_v)/2.0 ; - p_coeffs->b1= 1.0 - cos_v ; - p_coeffs->b2= (1.0 - cos_v)/2.0 ; - p_coeffs->a1= -2.0*cos_v; - p_coeffs->a2= 1.0 - alpha ; + p_coeffs->b0 = (1.0 - cos_v) / 2.0; + p_coeffs->b1 = 1.0 - cos_v; + p_coeffs->b2 = (1.0 - cos_v) / 2.0; + p_coeffs->a1 = -2.0 * cos_v; + p_coeffs->a2 = 1.0 - alpha; } break; - case HIGHPASS: { - p_coeffs->b0 = (1.0 + cos_v)/2.0; + p_coeffs->b0 = (1.0 + cos_v) / 2.0; p_coeffs->b1 = -(1.0 + cos_v); - p_coeffs->b2 = (1.0 + cos_v)/2.0; - p_coeffs->a1 = -2.0*cos_v; - p_coeffs->a2 = 1.0 - alpha; + p_coeffs->b2 = (1.0 + cos_v) / 2.0; + p_coeffs->a1 = -2.0 * cos_v; + p_coeffs->a2 = 1.0 - alpha; } break; case BANDPASS: { - p_coeffs->b0 = alpha*sqrt(Q+1); - p_coeffs->b1 = 0.0 ; - p_coeffs->b2 = -alpha*sqrt(Q+1); - p_coeffs->a1 = -2.0*cos_v; - p_coeffs->a2 = 1.0 - alpha; + p_coeffs->b0 = alpha * sqrt(Q + 1); + p_coeffs->b1 = 0.0; + p_coeffs->b2 = -alpha * sqrt(Q + 1); + p_coeffs->a1 = -2.0 * cos_v; + p_coeffs->a2 = 1.0 - alpha; } break; case NOTCH: { - p_coeffs->b0 = 1.0; - p_coeffs->b1 = -2.0*cos_v; - p_coeffs->b2 = 1.0; - p_coeffs->a1 = -2.0*cos_v; - p_coeffs->a2 = 1.0 - alpha; + p_coeffs->b0 = 1.0; + p_coeffs->b1 = -2.0 * cos_v; + p_coeffs->b2 = 1.0; + p_coeffs->a1 = -2.0 * cos_v; + p_coeffs->a2 = 1.0 - alpha; } break; case PEAK: { - p_coeffs->b0 = (1.0+alpha*tmpgain); - p_coeffs->b1 = (-2.0*cos_v); - p_coeffs->b2 = (1.0-alpha*tmpgain); - p_coeffs->a1 = -2*cos_v; - p_coeffs->a2 = (1-alpha/tmpgain); + p_coeffs->b0 = (1.0 + alpha * tmpgain); + p_coeffs->b1 = (-2.0 * cos_v); + p_coeffs->b2 = (1.0 - alpha * tmpgain); + p_coeffs->a1 = -2 * cos_v; + p_coeffs->a2 = (1 - alpha / tmpgain); } break; case BANDLIMIT: { //this one is extra tricky - double hicutoff=resonance; - double centercutoff = (cutoff+resonance)/2.0; - double bandwidth=(Math::log(centercutoff)-Math::log(hicutoff))/Math::log((double)2); - omega=2.0*Math_PI*centercutoff/sampling_rate; - alpha = Math::sin(omega)*Math::sinh( Math::log((double)2)/2 * bandwidth * omega/Math::sin(omega) ); - a0=1+alpha; - - p_coeffs->b0 = alpha; - p_coeffs->b1 = 0; - p_coeffs->b2 = -alpha; - p_coeffs->a1 = -2*Math::cos(omega); - p_coeffs->a2 = 1-alpha; + double hicutoff = resonance; + double centercutoff = (cutoff + resonance) / 2.0; + double bandwidth = (Math::log(centercutoff) - Math::log(hicutoff)) / Math::log((double)2); + omega = 2.0 * Math_PI * centercutoff / sampling_rate; + alpha = Math::sin(omega) * Math::sinh(Math::log((double)2) / 2 * bandwidth * omega / Math::sin(omega)); + a0 = 1 + alpha; + + p_coeffs->b0 = alpha; + p_coeffs->b1 = 0; + p_coeffs->b2 = -alpha; + p_coeffs->a1 = -2 * Math::cos(omega); + p_coeffs->a2 = 1 - alpha; } break; case LOWSHELF: { - double tmpq = Math::sqrt(Q); - if (tmpq<=0) - tmpq=0.001; + double tmpq = Math::sqrt(Q); + if (tmpq <= 0) + tmpq = 0.001; alpha = sin_v / (2 * tmpq); - double beta = Math::sqrt(tmpgain) / tmpq; + double beta = Math::sqrt(tmpgain) / tmpq; - a0=(tmpgain+1.0)+(tmpgain-1.0)*cos_v+beta*sin_v; - p_coeffs->b0=tmpgain*((tmpgain+1.0)-(tmpgain-1.0)*cos_v+beta*sin_v); - p_coeffs->b1=2.0*tmpgain*((tmpgain-1.0)-(tmpgain+1.0)*cos_v); - p_coeffs->b2=tmpgain*((tmpgain+1.0)-(tmpgain-1.0)*cos_v-beta*sin_v); - p_coeffs->a1=-2.0*((tmpgain-1.0)+(tmpgain+1.0)*cos_v); - p_coeffs->a2=((tmpgain+1.0)+(tmpgain-1.0)*cos_v-beta*sin_v); + a0 = (tmpgain + 1.0) + (tmpgain - 1.0) * cos_v + beta * sin_v; + p_coeffs->b0 = tmpgain * ((tmpgain + 1.0) - (tmpgain - 1.0) * cos_v + beta * sin_v); + p_coeffs->b1 = 2.0 * tmpgain * ((tmpgain - 1.0) - (tmpgain + 1.0) * cos_v); + p_coeffs->b2 = tmpgain * ((tmpgain + 1.0) - (tmpgain - 1.0) * cos_v - beta * sin_v); + p_coeffs->a1 = -2.0 * ((tmpgain - 1.0) + (tmpgain + 1.0) * cos_v); + p_coeffs->a2 = ((tmpgain + 1.0) + (tmpgain - 1.0) * cos_v - beta * sin_v); } break; case HIGHSHELF: { - double tmpq= Math::sqrt(Q); - if (tmpq<=0) - tmpq=0.001; + double tmpq = Math::sqrt(Q); + if (tmpq <= 0) + tmpq = 0.001; alpha = sin_v / (2 * tmpq); - double beta = Math::sqrt(tmpgain) / tmpq; - - a0=(tmpgain+1.0)-(tmpgain-1.0)*cos_v+beta*sin_v; - p_coeffs->b0=tmpgain*((tmpgain+1.0)+(tmpgain-1.0)*cos_v+beta*sin_v); - p_coeffs->b1=-2.0*tmpgain*((tmpgain-1.0)+(tmpgain+1.0)*cos_v); - p_coeffs->b2=tmpgain*((tmpgain+1.0)+(tmpgain-1.0)*cos_v-beta*sin_v); - p_coeffs->a1=2.0*((tmpgain-1.0)-(tmpgain+1.0)*cos_v); - p_coeffs->a2=((tmpgain+1.0)-(tmpgain-1.0)*cos_v-beta*sin_v); + double beta = Math::sqrt(tmpgain) / tmpq; + a0 = (tmpgain + 1.0) - (tmpgain - 1.0) * cos_v + beta * sin_v; + p_coeffs->b0 = tmpgain * ((tmpgain + 1.0) + (tmpgain - 1.0) * cos_v + beta * sin_v); + p_coeffs->b1 = -2.0 * tmpgain * ((tmpgain - 1.0) + (tmpgain + 1.0) * cos_v); + p_coeffs->b2 = tmpgain * ((tmpgain + 1.0) + (tmpgain - 1.0) * cos_v - beta * sin_v); + p_coeffs->a1 = 2.0 * ((tmpgain - 1.0) - (tmpgain + 1.0) * cos_v); + p_coeffs->a2 = ((tmpgain + 1.0) - (tmpgain - 1.0) * cos_v - beta * sin_v); } break; + }; - }; + p_coeffs->b0 /= a0; + p_coeffs->b1 /= a0; + p_coeffs->b2 /= a0; + p_coeffs->a1 /= 0.0 - a0; + p_coeffs->a2 /= 0.0 - a0; - p_coeffs->b0/=a0; - p_coeffs->b1/=a0; - p_coeffs->b2/=a0; - p_coeffs->a1/=0.0-a0; - p_coeffs->a2/=0.0-a0; - - //undenormalise -/* p_coeffs->b0=undenormalise(p_coeffs->b0); + //undenormalise + /* p_coeffs->b0=undenormalise(p_coeffs->b0); p_coeffs->b1=undenormalise(p_coeffs->b1); p_coeffs->b2=undenormalise(p_coeffs->b2); p_coeffs->a1=undenormalise(p_coeffs->a1); p_coeffs->a2=undenormalise(p_coeffs->a2);*/ - } void AudioFilterSW::set_stages(int p_stages) { //adjust for multiple stages - stages=p_stages; + stages = p_stages; } /* Fouriertransform kernel to obtain response */ -float AudioFilterSW::get_response(float p_freq,Coeffs *p_coeffs) { +float AudioFilterSW::get_response(float p_freq, Coeffs *p_coeffs) { - float freq=p_freq / sampling_rate * Math_PI * 2.0f; + float freq = p_freq / sampling_rate * Math_PI * 2.0f; - float cx=p_coeffs->b0,cy=0.0; + float cx = p_coeffs->b0, cy = 0.0; cx += cos(freq) * p_coeffs->b1; cy -= sin(freq) * p_coeffs->b1; - cx += cos(2*freq) * p_coeffs->b2; - cy -= sin(2*freq) * p_coeffs->b2; - - - float H=cx*cx+cy*cy; - cx=1.0; - cy=0.0; + cx += cos(2 * freq) * p_coeffs->b2; + cy -= sin(2 * freq) * p_coeffs->b2; + float H = cx * cx + cy * cy; + cx = 1.0; + cy = 0.0; cx -= cos(freq) * p_coeffs->a1; cy += sin(freq) * p_coeffs->a1; - cx -= cos(2*freq) * p_coeffs->a2; - cy += sin(2*freq) * p_coeffs->a2; - + cx -= cos(2 * freq) * p_coeffs->a2; + cy += sin(2 * freq) * p_coeffs->a2; - H=H/(cx*cx+cy*cy); + H = H / (cx * cx + cy * cy); return H; } - AudioFilterSW::AudioFilterSW() { - - sampling_rate=44100; - resonance=0.5; - cutoff=5000; - gain=1.0; - mode=LOWPASS; - stages=1; + sampling_rate = 44100; + resonance = 0.5; + cutoff = 5000; + gain = 1.0; + mode = LOWPASS; + stages = 1; } AudioFilterSW::Processor::Processor() { set_filter(NULL); - } -void AudioFilterSW::Processor::set_filter(AudioFilterSW * p_filter) { +void AudioFilterSW::Processor::set_filter(AudioFilterSW *p_filter) { - ha1=ha2=hb1=hb2=0; - filter=p_filter; + ha1 = ha2 = hb1 = hb2 = 0; + filter = p_filter; } void AudioFilterSW::Processor::update_coeffs() { @@ -268,19 +253,16 @@ void AudioFilterSW::Processor::update_coeffs() { return; filter->prepare_coefficients(&coeffs); - } -void AudioFilterSW::Processor::process(float *p_samples,int p_amount, int p_stride) { +void AudioFilterSW::Processor::process(float *p_samples, int p_amount, int p_stride) { if (!filter) return; - for (int i=0;i<p_amount;i++) { + for (int i = 0; i < p_amount; i++) { process_one(*p_samples); - p_samples+=p_stride; + p_samples += p_stride; } - - } diff --git a/servers/audio/audio_filter_sw.h b/servers/audio/audio_filter_sw.h index b711944ca8..bbd006e525 100644 --- a/servers/audio/audio_filter_sw.h +++ b/servers/audio/audio_filter_sw.h @@ -29,19 +29,17 @@ #ifndef AUDIO_FILTER_SW_H #define AUDIO_FILTER_SW_H - #include "math_funcs.h" class AudioFilterSW { public: - struct Coeffs { - float a1,a2; - float b0,b1,b2; + float a1, a2; + float b0, b1, b2; //bool operator==(const Coeffs &p_rv) { return (FLOATS_EQ(a1,p_rv.a1) && FLOATS_EQ(a2,p_rv.a2) && FLOATS_EQ(b1,p_rv.b1) && FLOATS_EQ(b2,p_rv.b2) && FLOATS_EQ(b0,p_rv.b0) ); } - Coeffs() { a1=a2=b0=b1=b2=0.0; } + Coeffs() { a1 = a2 = b0 = b1 = b2 = 0.0; } }; enum Mode { @@ -58,21 +56,19 @@ public: class Processor { // simple filter processor - AudioFilterSW * filter; + AudioFilterSW *filter; Coeffs coeffs; - float ha1,ha2,hb1,hb2; //history + float ha1, ha2, hb1, hb2; //history public: - void set_filter(AudioFilterSW * p_filter); - void process(float *p_samples,int p_amount, int p_stride=1); + void set_filter(AudioFilterSW *p_filter); + void process(float *p_samples, int p_amount, int p_stride = 1); void update_coeffs(); - _ALWAYS_INLINE_ void process_one(float& p_sample); + _ALWAYS_INLINE_ void process_one(float &p_sample); Processor(); }; private: - - float cutoff; float resonance; float gain; @@ -80,11 +76,8 @@ private: int stages; Mode mode; - - public: - - float get_response(float p_freq,Coeffs *p_coeffs); + float get_response(float p_freq, Coeffs *p_coeffs); void set_mode(Mode p_mode); void set_cutoff(float p_cutoff); @@ -96,24 +89,18 @@ public: void prepare_coefficients(Coeffs *p_coeffs); AudioFilterSW(); - }; - - - /* inline methods */ - void AudioFilterSW::Processor::process_one(float &p_val) { - float pre=p_val; - p_val = (p_val * coeffs.b0 + hb1 * coeffs.b1 + hb2 * coeffs.b2 + ha1 * coeffs.a1 + ha2 * coeffs.a2); - ha2=ha1; - hb2=hb1; - hb1=pre; - ha1=p_val; + float pre = p_val; + p_val = (p_val * coeffs.b0 + hb1 * coeffs.b1 + hb2 * coeffs.b2 + ha1 * coeffs.a1 + ha2 * coeffs.a2); + ha2 = ha1; + hb2 = hb1; + hb1 = pre; + ha1 = p_val; } - #endif // AUDIO_FILTER_SW_H diff --git a/servers/audio/audio_rb_resampler.cpp b/servers/audio/audio_rb_resampler.cpp index 28f0007b5b..bf10f813a2 100644 --- a/servers/audio/audio_rb_resampler.cpp +++ b/servers/audio/audio_rb_resampler.cpp @@ -28,7 +28,6 @@ /*************************************************************************/ #include "audio_rb_resampler.h" - int AudioRBResampler::get_channel_count() const { if (!rb) @@ -37,153 +36,142 @@ int AudioRBResampler::get_channel_count() const { return channels; } +template <int C> +uint32_t AudioRBResampler::_resample(int32_t *p_dest, int p_todo, int32_t p_increment) { -template<int C> -uint32_t AudioRBResampler::_resample(int32_t *p_dest,int p_todo,int32_t p_increment) { - - uint32_t read=offset&MIX_FRAC_MASK; + uint32_t read = offset & MIX_FRAC_MASK; - for (int i=0;i<p_todo;i++) { + for (int i = 0; i < p_todo; i++) { - offset = (offset + p_increment)&(((1<<(rb_bits+MIX_FRAC_BITS))-1)); - read+=p_increment; + offset = (offset + p_increment) & (((1 << (rb_bits + MIX_FRAC_BITS)) - 1)); + read += p_increment; uint32_t pos = offset >> MIX_FRAC_BITS; uint32_t frac = offset & MIX_FRAC_MASK; #ifndef FAST_AUDIO - ERR_FAIL_COND_V(pos>=rb_len,0); + ERR_FAIL_COND_V(pos >= rb_len, 0); #endif - uint32_t pos_next = (pos+1)&rb_mask; + uint32_t pos_next = (pos + 1) & rb_mask; //printf("rb pos %i\n",pos); // since this is a template with a known compile time value (C), conditionals go away when compiling. - if (C==1) { + if (C == 1) { int32_t v0 = rb[pos]; - int32_t v0n=rb[pos_next]; + int32_t v0n = rb[pos_next]; #ifndef FAST_AUDIO - v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS; + v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS; #endif - v0<<=16; - p_dest[i]=v0; - + v0 <<= 16; + p_dest[i] = v0; } - if (C==2) { + if (C == 2) { - int32_t v0 = rb[(pos<<1)+0]; - int32_t v1 = rb[(pos<<1)+1]; - int32_t v0n=rb[(pos_next<<1)+0]; - int32_t v1n=rb[(pos_next<<1)+1]; + int32_t v0 = rb[(pos << 1) + 0]; + int32_t v1 = rb[(pos << 1) + 1]; + int32_t v0n = rb[(pos_next << 1) + 0]; + int32_t v1n = rb[(pos_next << 1) + 1]; #ifndef FAST_AUDIO - v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS; - v1+=(v1n-v1)*(int32_t)frac >> MIX_FRAC_BITS; + v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS; + v1 += (v1n - v1) * (int32_t)frac >> MIX_FRAC_BITS; #endif - v0<<=16; - v1<<=16; - p_dest[(i<<1)+0]=v0; - p_dest[(i<<1)+1]=v1; - + v0 <<= 16; + v1 <<= 16; + p_dest[(i << 1) + 0] = v0; + p_dest[(i << 1) + 1] = v1; } - if (C==4) { + if (C == 4) { - int32_t v0 = rb[(pos<<2)+0]; - int32_t v1 = rb[(pos<<2)+1]; - int32_t v2 = rb[(pos<<2)+2]; - int32_t v3 = rb[(pos<<2)+3]; - int32_t v0n = rb[(pos_next<<2)+0]; - int32_t v1n=rb[(pos_next<<2)+1]; - int32_t v2n=rb[(pos_next<<2)+2]; - int32_t v3n=rb[(pos_next<<2)+3]; + int32_t v0 = rb[(pos << 2) + 0]; + int32_t v1 = rb[(pos << 2) + 1]; + int32_t v2 = rb[(pos << 2) + 2]; + int32_t v3 = rb[(pos << 2) + 3]; + int32_t v0n = rb[(pos_next << 2) + 0]; + int32_t v1n = rb[(pos_next << 2) + 1]; + int32_t v2n = rb[(pos_next << 2) + 2]; + int32_t v3n = rb[(pos_next << 2) + 3]; #ifndef FAST_AUDIO - v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS; - v1+=(v1n-v1)*(int32_t)frac >> MIX_FRAC_BITS; - v2+=(v2n-v2)*(int32_t)frac >> MIX_FRAC_BITS; - v3+=(v3n-v3)*(int32_t)frac >> MIX_FRAC_BITS; + v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS; + v1 += (v1n - v1) * (int32_t)frac >> MIX_FRAC_BITS; + v2 += (v2n - v2) * (int32_t)frac >> MIX_FRAC_BITS; + v3 += (v3n - v3) * (int32_t)frac >> MIX_FRAC_BITS; #endif - v0<<=16; - v1<<=16; - v2<<=16; - v3<<=16; - p_dest[(i<<2)+0]=v0; - p_dest[(i<<2)+1]=v1; - p_dest[(i<<2)+2]=v2; - p_dest[(i<<2)+3]=v3; - + v0 <<= 16; + v1 <<= 16; + v2 <<= 16; + v3 <<= 16; + p_dest[(i << 2) + 0] = v0; + p_dest[(i << 2) + 1] = v1; + p_dest[(i << 2) + 2] = v2; + p_dest[(i << 2) + 3] = v3; } - if (C==6) { - - int32_t v0 = rb[(pos*6)+0]; - int32_t v1 = rb[(pos*6)+1]; - int32_t v2 = rb[(pos*6)+2]; - int32_t v3 = rb[(pos*6)+3]; - int32_t v4 = rb[(pos*6)+4]; - int32_t v5 = rb[(pos*6)+5]; - int32_t v0n = rb[(pos_next*6)+0]; - int32_t v1n=rb[(pos_next*6)+1]; - int32_t v2n=rb[(pos_next*6)+2]; - int32_t v3n=rb[(pos_next*6)+3]; - int32_t v4n=rb[(pos_next*6)+4]; - int32_t v5n=rb[(pos_next*6)+5]; + if (C == 6) { + + int32_t v0 = rb[(pos * 6) + 0]; + int32_t v1 = rb[(pos * 6) + 1]; + int32_t v2 = rb[(pos * 6) + 2]; + int32_t v3 = rb[(pos * 6) + 3]; + int32_t v4 = rb[(pos * 6) + 4]; + int32_t v5 = rb[(pos * 6) + 5]; + int32_t v0n = rb[(pos_next * 6) + 0]; + int32_t v1n = rb[(pos_next * 6) + 1]; + int32_t v2n = rb[(pos_next * 6) + 2]; + int32_t v3n = rb[(pos_next * 6) + 3]; + int32_t v4n = rb[(pos_next * 6) + 4]; + int32_t v5n = rb[(pos_next * 6) + 5]; #ifndef FAST_AUDIO - v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS; - v1+=(v1n-v1)*(int32_t)frac >> MIX_FRAC_BITS; - v2+=(v2n-v2)*(int32_t)frac >> MIX_FRAC_BITS; - v3+=(v3n-v3)*(int32_t)frac >> MIX_FRAC_BITS; - v4+=(v4n-v4)*(int32_t)frac >> MIX_FRAC_BITS; - v5+=(v5n-v5)*(int32_t)frac >> MIX_FRAC_BITS; + v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS; + v1 += (v1n - v1) * (int32_t)frac >> MIX_FRAC_BITS; + v2 += (v2n - v2) * (int32_t)frac >> MIX_FRAC_BITS; + v3 += (v3n - v3) * (int32_t)frac >> MIX_FRAC_BITS; + v4 += (v4n - v4) * (int32_t)frac >> MIX_FRAC_BITS; + v5 += (v5n - v5) * (int32_t)frac >> MIX_FRAC_BITS; #endif - v0<<=16; - v1<<=16; - v2<<=16; - v3<<=16; - v4<<=16; - v5<<=16; - p_dest[(i*6)+0]=v0; - p_dest[(i*6)+1]=v1; - p_dest[(i*6)+2]=v2; - p_dest[(i*6)+3]=v3; - p_dest[(i*6)+4]=v4; - p_dest[(i*6)+5]=v5; - + v0 <<= 16; + v1 <<= 16; + v2 <<= 16; + v3 <<= 16; + v4 <<= 16; + v5 <<= 16; + p_dest[(i * 6) + 0] = v0; + p_dest[(i * 6) + 1] = v1; + p_dest[(i * 6) + 2] = v2; + p_dest[(i * 6) + 3] = v3; + p_dest[(i * 6) + 4] = v4; + p_dest[(i * 6) + 5] = v5; } - - } - - return read>>MIX_FRAC_BITS;//rb_read_pos=offset>>MIX_FRAC_BITS; - + return read >> MIX_FRAC_BITS; //rb_read_pos=offset>>MIX_FRAC_BITS; } - bool AudioRBResampler::mix(int32_t *p_dest, int p_frames) { - if (!rb) return false; - int write_pos_cache=rb_write_pos; + int write_pos_cache = rb_write_pos; - int32_t increment=(src_mix_rate*MIX_FRAC_LEN)/target_mix_rate; + int32_t increment = (src_mix_rate * MIX_FRAC_LEN) / target_mix_rate; int rb_todo; - if (write_pos_cache==rb_read_pos) { + if (write_pos_cache == rb_read_pos) { return false; //out of buffer - } else if (rb_read_pos<write_pos_cache) { + } else if (rb_read_pos < write_pos_cache) { - rb_todo=write_pos_cache-rb_read_pos; //-1? + rb_todo = write_pos_cache - rb_read_pos; //-1? } else { - rb_todo=(rb_len-rb_read_pos)+write_pos_cache; //-1? + rb_todo = (rb_len - rb_read_pos) + write_pos_cache; //-1? } - int todo = MIN( ((int64_t(rb_todo)<<MIX_FRAC_BITS)/increment)+1, p_frames ); + int todo = MIN(((int64_t(rb_todo) << MIX_FRAC_BITS) / increment) + 1, p_frames); #if 0 if (int(src_mix_rate)==target_mix_rate) { @@ -224,118 +212,104 @@ bool AudioRBResampler::mix(int32_t *p_dest, int p_frames) { #endif { - uint32_t read=0; - switch(channels) { - case 1: read=_resample<1>(p_dest,todo,increment); break; - case 2: read=_resample<2>(p_dest,todo,increment); break; - case 4: read=_resample<4>(p_dest,todo,increment); break; - case 6: read=_resample<6>(p_dest,todo,increment); break; + uint32_t read = 0; + switch (channels) { + case 1: read = _resample<1>(p_dest, todo, increment); break; + case 2: read = _resample<2>(p_dest, todo, increment); break; + case 4: read = _resample<4>(p_dest, todo, increment); break; + case 6: read = _resample<6>(p_dest, todo, increment); break; } #if 1 //end of stream, fadeout - int remaining = p_frames-todo; - if (remaining && todo>0) { + int remaining = p_frames - todo; + if (remaining && todo > 0) { //print_line("fadeout"); - for(int c=0;c<channels;c++) { + for (int c = 0; c < channels; c++) { - for(int i=0;i<todo;i++) { + for (int i = 0; i < todo; i++) { - int32_t samp = p_dest[i*channels+c]>>8; - uint32_t mul = (todo-i) * 256 /todo; + int32_t samp = p_dest[i * channels + c] >> 8; + uint32_t mul = (todo - i) * 256 / todo; //print_line("mul: "+itos(i)+" "+itos(mul)); - p_dest[i*channels+c]=samp*mul; + p_dest[i * channels + c] = samp * mul; } - } - } #else - int remaining = p_frames-todo; - if (remaining && todo>0) { - + int remaining = p_frames - todo; + if (remaining && todo > 0) { - for(int c=0;c<channels;c++) { + for (int c = 0; c < channels; c++) { - int32_t from = p_dest[(todo-1)*channels+c]>>8; + int32_t from = p_dest[(todo - 1) * channels + c] >> 8; - for(int i=0;i<remaining;i++) { + for (int i = 0; i < remaining; i++) { - uint32_t mul = (remaining-i) * 256 /remaining; - p_dest[(todo+i)*channels+c]=from*mul; + uint32_t mul = (remaining - i) * 256 / remaining; + p_dest[(todo + i) * channels + c] = from * mul; } - } - } #endif //zero out what remains there to avoid glitches - for(int i=todo*channels;i<int(p_frames)*channels;i++) { + for (int i = todo * channels; i < int(p_frames) * channels; i++) { - p_dest[i]=0; + p_dest[i] = 0; } - if (read>rb_todo) - read=rb_todo; - - rb_read_pos = (rb_read_pos+read)&rb_mask; - - - + if (read > rb_todo) + read = rb_todo; + rb_read_pos = (rb_read_pos + read) & rb_mask; } return true; } +Error AudioRBResampler::setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed) { -Error AudioRBResampler::setup(int p_channels,int p_src_mix_rate,int p_target_mix_rate,int p_buffer_msec,int p_minbuff_needed) { - - ERR_FAIL_COND_V(p_channels!=1 && p_channels!=2 && p_channels!=4 && p_channels!=6,ERR_INVALID_PARAMETER); - + ERR_FAIL_COND_V(p_channels != 1 && p_channels != 2 && p_channels != 4 && p_channels != 6, ERR_INVALID_PARAMETER); //float buffering_sec = int(GLOBAL_DEF("audio/stream_buffering_ms",500))/1000.0; - int desired_rb_bits =nearest_shift(MAX((p_buffer_msec/1000.0)*p_src_mix_rate,p_minbuff_needed)); + int desired_rb_bits = nearest_shift(MAX((p_buffer_msec / 1000.0) * p_src_mix_rate, p_minbuff_needed)); - bool recreate=!rb; + bool recreate = !rb; - if (rb && (uint32_t(desired_rb_bits)!=rb_bits || channels!=uint32_t(p_channels))) { + if (rb && (uint32_t(desired_rb_bits) != rb_bits || channels != uint32_t(p_channels))) { //recreate memdelete_arr(rb); memdelete_arr(read_buf); - recreate=true; - + recreate = true; } if (recreate) { - channels=p_channels; - rb_bits=desired_rb_bits; - rb_len=(1<<rb_bits); - rb_mask=rb_len-1; - rb = memnew_arr( int16_t, rb_len * p_channels ); - read_buf = memnew_arr( int16_t, rb_len * p_channels ); - + channels = p_channels; + rb_bits = desired_rb_bits; + rb_len = (1 << rb_bits); + rb_mask = rb_len - 1; + rb = memnew_arr(int16_t, rb_len * p_channels); + read_buf = memnew_arr(int16_t, rb_len * p_channels); } - src_mix_rate=p_src_mix_rate; - target_mix_rate=p_target_mix_rate; - offset=0; - rb_read_pos=0; - rb_write_pos=0; + src_mix_rate = p_src_mix_rate; + target_mix_rate = p_target_mix_rate; + offset = 0; + rb_read_pos = 0; + rb_write_pos = 0; //avoid maybe strange noises upon load - for (int i=0;i<(rb_len*channels);i++) { + for (int i = 0; i < (rb_len * channels); i++) { - rb[i]=0; - read_buf[i]=0; + rb[i] = 0; + read_buf[i] = 0; } return OK; - } void AudioRBResampler::clear() { @@ -348,29 +322,28 @@ void AudioRBResampler::clear() { memdelete_arr(rb); memdelete_arr(read_buf); } - rb=NULL; - offset=0; - rb_read_pos=0; - rb_write_pos=0; - read_buf=NULL; + rb = NULL; + offset = 0; + rb_read_pos = 0; + rb_write_pos = 0; + read_buf = NULL; } AudioRBResampler::AudioRBResampler() { - rb=NULL; - offset=0; - read_buf=NULL; - rb_read_pos=0; - rb_write_pos=0; - - rb_bits=0; - rb_len=0; - rb_mask=0; - read_buff_len=0; - channels=0; - src_mix_rate=0; - target_mix_rate=0; - + rb = NULL; + offset = 0; + read_buf = NULL; + rb_read_pos = 0; + rb_write_pos = 0; + + rb_bits = 0; + rb_len = 0; + rb_mask = 0; + read_buff_len = 0; + channels = 0; + src_mix_rate = 0; + target_mix_rate = 0; } AudioRBResampler::~AudioRBResampler() { @@ -379,6 +352,4 @@ AudioRBResampler::~AudioRBResampler() { memdelete_arr(rb); memdelete_arr(read_buf); } - } - diff --git a/servers/audio/audio_rb_resampler.h b/servers/audio/audio_rb_resampler.h index e97e275b68..d775aed0d9 100644 --- a/servers/audio/audio_rb_resampler.h +++ b/servers/audio/audio_rb_resampler.h @@ -29,8 +29,8 @@ #ifndef AUDIO_RB_RESAMPLER_H #define AUDIO_RB_RESAMPLER_H -#include "typedefs.h" #include "os/memory.h" +#include "typedefs.h" struct AudioRBResampler { @@ -47,58 +47,53 @@ struct AudioRBResampler { int32_t offset; //contains the fractional remainder of the resampler enum { - MIX_FRAC_BITS=13, - MIX_FRAC_LEN=(1<<MIX_FRAC_BITS), - MIX_FRAC_MASK=MIX_FRAC_LEN-1, + MIX_FRAC_BITS = 13, + MIX_FRAC_LEN = (1 << MIX_FRAC_BITS), + MIX_FRAC_MASK = MIX_FRAC_LEN - 1, }; int16_t *read_buf; int16_t *rb; - - template<int C> - uint32_t _resample(int32_t *p_dest,int p_todo,int32_t p_increment); - + template <int C> + uint32_t _resample(int32_t *p_dest, int p_todo, int32_t p_increment); public: - _FORCE_INLINE_ void flush() { - rb_read_pos=0; - rb_write_pos=0; - offset=0; + rb_read_pos = 0; + rb_write_pos = 0; + offset = 0; } - _FORCE_INLINE_ bool is_ready() const{ - return rb!=NULL; + _FORCE_INLINE_ bool is_ready() const { + return rb != NULL; } - _FORCE_INLINE_ int get_total() const { - return rb_len-1; + return rb_len - 1; } _FORCE_INLINE_ int get_todo() const { //return amount of frames to mix int todo; - int read_pos_cache=rb_read_pos; + int read_pos_cache = rb_read_pos; - if (read_pos_cache==rb_write_pos) { - todo=rb_len-1; - } else if (read_pos_cache>rb_write_pos) { + if (read_pos_cache == rb_write_pos) { + todo = rb_len - 1; + } else if (read_pos_cache > rb_write_pos) { - todo=read_pos_cache-rb_write_pos-1; + todo = read_pos_cache - rb_write_pos - 1; } else { - todo=(rb_len-rb_write_pos)+read_pos_cache-1; + todo = (rb_len - rb_write_pos) + read_pos_cache - 1; } return todo; } - _FORCE_INLINE_ bool has_data() const { - return rb && rb_read_pos!=rb_write_pos; + return rb && rb_read_pos != rb_write_pos; } _FORCE_INLINE_ int16_t *get_write_buffer() { return read_buf; } @@ -106,57 +101,54 @@ public: ERR_FAIL_COND(p_frames >= rb_len); - switch(channels) { + switch (channels) { case 1: { - for(uint32_t i=0;i<p_frames;i++) { + for (uint32_t i = 0; i < p_frames; i++) { - rb[ rb_write_pos ] = read_buf[i]; - rb_write_pos=(rb_write_pos+1)&rb_mask; + rb[rb_write_pos] = read_buf[i]; + rb_write_pos = (rb_write_pos + 1) & rb_mask; } } break; case 2: { - for(uint32_t i=0;i<p_frames;i++) { + for (uint32_t i = 0; i < p_frames; i++) { - rb[ (rb_write_pos<<1)+0 ] = read_buf[(i<<1)+0]; - rb[ (rb_write_pos<<1)+1 ] = read_buf[(i<<1)+1]; - rb_write_pos=(rb_write_pos+1)&rb_mask; + rb[(rb_write_pos << 1) + 0] = read_buf[(i << 1) + 0]; + rb[(rb_write_pos << 1) + 1] = read_buf[(i << 1) + 1]; + rb_write_pos = (rb_write_pos + 1) & rb_mask; } } break; case 4: { - for(uint32_t i=0;i<p_frames;i++) { + for (uint32_t i = 0; i < p_frames; i++) { - rb[ (rb_write_pos<<2)+0 ] = read_buf[(i<<2)+0]; - rb[ (rb_write_pos<<2)+1 ] = read_buf[(i<<2)+1]; - rb[ (rb_write_pos<<2)+2 ] = read_buf[(i<<2)+2]; - rb[ (rb_write_pos<<2)+3 ] = read_buf[(i<<2)+3]; - rb_write_pos=(rb_write_pos+1)&rb_mask; + rb[(rb_write_pos << 2) + 0] = read_buf[(i << 2) + 0]; + rb[(rb_write_pos << 2) + 1] = read_buf[(i << 2) + 1]; + rb[(rb_write_pos << 2) + 2] = read_buf[(i << 2) + 2]; + rb[(rb_write_pos << 2) + 3] = read_buf[(i << 2) + 3]; + rb_write_pos = (rb_write_pos + 1) & rb_mask; } } break; case 6: { - for(uint32_t i=0;i<p_frames;i++) { + for (uint32_t i = 0; i < p_frames; i++) { - rb[ (rb_write_pos*6)+0 ] = read_buf[(i*6)+0]; - rb[ (rb_write_pos*6)+1 ] = read_buf[(i*6)+1]; - rb[ (rb_write_pos*6)+2 ] = read_buf[(i*6)+2]; - rb[ (rb_write_pos*6)+3 ] = read_buf[(i*6)+3]; - rb[ (rb_write_pos*6)+4 ] = read_buf[(i*6)+4]; - rb[ (rb_write_pos*6)+5 ] = read_buf[(i*6)+5]; - rb_write_pos=(rb_write_pos+1)&rb_mask; + rb[(rb_write_pos * 6) + 0] = read_buf[(i * 6) + 0]; + rb[(rb_write_pos * 6) + 1] = read_buf[(i * 6) + 1]; + rb[(rb_write_pos * 6) + 2] = read_buf[(i * 6) + 2]; + rb[(rb_write_pos * 6) + 3] = read_buf[(i * 6) + 3]; + rb[(rb_write_pos * 6) + 4] = read_buf[(i * 6) + 4]; + rb[(rb_write_pos * 6) + 5] = read_buf[(i * 6) + 5]; + rb_write_pos = (rb_write_pos + 1) & rb_mask; } } break; - - } - } int get_channel_count() const; - Error setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed=-1); + Error setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed = -1); void clear(); bool mix(int32_t *p_dest, int p_frames); diff --git a/servers/audio/audio_stream.cpp b/servers/audio/audio_stream.cpp index f4214838a1..5f77eb54f6 100644 --- a/servers/audio/audio_stream.cpp +++ b/servers/audio/audio_stream.cpp @@ -30,57 +30,53 @@ ////////////////////////////// - - void AudioStreamPlaybackResampled::_begin_resample() { //clear cubic interpolation history - internal_buffer[0]=AudioFrame(0.0,0.0); - internal_buffer[1]=AudioFrame(0.0,0.0); - internal_buffer[2]=AudioFrame(0.0,0.0); - internal_buffer[3]=AudioFrame(0.0,0.0); + internal_buffer[0] = AudioFrame(0.0, 0.0); + internal_buffer[1] = AudioFrame(0.0, 0.0); + internal_buffer[2] = AudioFrame(0.0, 0.0); + internal_buffer[3] = AudioFrame(0.0, 0.0); //mix buffer - _mix_internal(internal_buffer+4,INTERNAL_BUFFER_LEN); - mix_offset=0; + _mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN); + mix_offset = 0; } -void AudioStreamPlaybackResampled::mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames) { +void AudioStreamPlaybackResampled::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) { float target_rate = AudioServer::get_singleton()->get_mix_rate() * p_rate_scale; - uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double( FP_LEN )); - - for(int i=0;i<p_frames;i++) { - + uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double(FP_LEN)); + for (int i = 0; i < p_frames; i++) { uint32_t idx = CUBIC_INTERP_HISTORY + uint32_t(mix_offset >> FP_BITS); //standard cubic interpolation (great quality/performance ratio) //this used to be moved to a LUT for greater performance, but nowadays CPU speed is generally faster than memory. - float mu = (mix_offset&FP_MASK)/float(FP_LEN); - AudioFrame y0 = internal_buffer[idx-3]; - AudioFrame y1 = internal_buffer[idx-2]; - AudioFrame y2 = internal_buffer[idx-1]; - AudioFrame y3 = internal_buffer[idx-0]; + float mu = (mix_offset & FP_MASK) / float(FP_LEN); + AudioFrame y0 = internal_buffer[idx - 3]; + AudioFrame y1 = internal_buffer[idx - 2]; + AudioFrame y2 = internal_buffer[idx - 1]; + AudioFrame y3 = internal_buffer[idx - 0]; - float mu2 = mu*mu; + float mu2 = mu * mu; AudioFrame a0 = y3 - y2 - y0 + y1; AudioFrame a1 = y0 - y1 - a0; AudioFrame a2 = y2 - y0; AudioFrame a3 = y1; - p_buffer[i] = (a0*mu*mu2 + a1*mu2 + a2*mu + a3); + p_buffer[i] = (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3); - mix_offset+=mix_increment; + mix_offset += mix_increment; - while ( (mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN ) { + while ((mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN) { - internal_buffer[0]=internal_buffer[INTERNAL_BUFFER_LEN+0]; - internal_buffer[1]=internal_buffer[INTERNAL_BUFFER_LEN+1]; - internal_buffer[2]=internal_buffer[INTERNAL_BUFFER_LEN+2]; - internal_buffer[3]=internal_buffer[INTERNAL_BUFFER_LEN+3]; - _mix_internal(internal_buffer+4,INTERNAL_BUFFER_LEN); - mix_offset-=(INTERNAL_BUFFER_LEN<<FP_BITS); + internal_buffer[0] = internal_buffer[INTERNAL_BUFFER_LEN + 0]; + internal_buffer[1] = internal_buffer[INTERNAL_BUFFER_LEN + 1]; + internal_buffer[2] = internal_buffer[INTERNAL_BUFFER_LEN + 2]; + internal_buffer[3] = internal_buffer[INTERNAL_BUFFER_LEN + 3]; + _mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN); + mix_offset -= (INTERNAL_BUFFER_LEN << FP_BITS); } } } diff --git a/servers/audio/audio_stream.h b/servers/audio/audio_stream.h index d08fedb084..0d7b4adbfe 100644 --- a/servers/audio/audio_stream.h +++ b/servers/audio/audio_stream.h @@ -34,68 +34,57 @@ class AudioStreamPlayback : public Reference { - GDCLASS( AudioStreamPlayback, Reference ) + GDCLASS(AudioStreamPlayback, Reference) public: + virtual void start(float p_from_pos = 0.0) = 0; + virtual void stop() = 0; + virtual bool is_playing() const = 0; - virtual void start(float p_from_pos=0.0)=0; - virtual void stop()=0; - virtual bool is_playing() const=0; + virtual int get_loop_count() const = 0; //times it looped - virtual int get_loop_count() const=0; //times it looped - - virtual float get_pos() const=0; - virtual void seek_pos(float p_time)=0; - - virtual void mix(AudioFrame* p_bufer,float p_rate_scale,int p_frames)=0; - - virtual float get_length() const=0; //if supported, otherwise return 0 + virtual float get_pos() const = 0; + virtual void seek_pos(float p_time) = 0; + virtual void mix(AudioFrame *p_bufer, float p_rate_scale, int p_frames) = 0; + virtual float get_length() const = 0; //if supported, otherwise return 0 }; class AudioStreamPlaybackResampled : public AudioStreamPlayback { - GDCLASS( AudioStreamPlaybackResampled, AudioStreamPlayback ) - - + GDCLASS(AudioStreamPlaybackResampled, AudioStreamPlayback) enum { - FP_BITS=16, //fixed point used for resampling - FP_LEN=(1<<FP_BITS), - FP_MASK=FP_LEN-1, - INTERNAL_BUFFER_LEN=256, - CUBIC_INTERP_HISTORY=4 + FP_BITS = 16, //fixed point used for resampling + FP_LEN = (1 << FP_BITS), + FP_MASK = FP_LEN - 1, + INTERNAL_BUFFER_LEN = 256, + CUBIC_INTERP_HISTORY = 4 }; - AudioFrame internal_buffer[INTERNAL_BUFFER_LEN+CUBIC_INTERP_HISTORY]; + AudioFrame internal_buffer[INTERNAL_BUFFER_LEN + CUBIC_INTERP_HISTORY]; uint64_t mix_offset; protected: void _begin_resample(); - virtual void _mix_internal(AudioFrame* p_bufer,int p_frames)=0; - virtual float get_stream_sampling_rate()=0; + virtual void _mix_internal(AudioFrame *p_bufer, int p_frames) = 0; + virtual float get_stream_sampling_rate() = 0; public: + virtual void mix(AudioFrame *p_bufer, float p_rate_scale, int p_frames); - virtual void mix(AudioFrame* p_bufer,float p_rate_scale,int p_frames); - - AudioStreamPlaybackResampled() { mix_offset=0; } + AudioStreamPlaybackResampled() { mix_offset = 0; } }; class AudioStream : public Resource { - GDCLASS( AudioStream, Resource ) - OBJ_SAVE_TYPE( AudioStream ) //children are all saved as AudioStream, so they can be exchanged - + GDCLASS(AudioStream, Resource) + OBJ_SAVE_TYPE(AudioStream) //children are all saved as AudioStream, so they can be exchanged public: - - virtual Ref<AudioStreamPlayback> instance_playback()=0; - virtual String get_stream_name() const=0; - - + virtual Ref<AudioStreamPlayback> instance_playback() = 0; + virtual String get_stream_name() const = 0; }; - #endif // AUDIO_STREAM_H diff --git a/servers/audio/effects/audio_effect_amplify.cpp b/servers/audio/effects/audio_effect_amplify.cpp index a0796f5224..6a4d03e517 100644 --- a/servers/audio/effects/audio_effect_amplify.cpp +++ b/servers/audio/effects/audio_effect_amplify.cpp @@ -28,35 +28,31 @@ /*************************************************************************/ #include "audio_effect_amplify.h" - -void AudioEffectAmplifyInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { - +void AudioEffectAmplifyInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { //multiply volume interpolating to avoid clicks if this changes float volume_db = base->volume_db; float vol = Math::db2linear(mix_volume_db); - float vol_inc = (Math::db2linear(volume_db) - vol)/float(p_frame_count); + float vol_inc = (Math::db2linear(volume_db) - vol) / float(p_frame_count); - for(int i=0;i<p_frame_count;i++) { - p_dst_frames[i]=p_src_frames[i]*vol; - vol+=vol_inc; + for (int i = 0; i < p_frame_count; i++) { + p_dst_frames[i] = p_src_frames[i] * vol; + vol += vol_inc; } //set volume for next mix mix_volume_db = volume_db; - } - Ref<AudioEffectInstance> AudioEffectAmplify::instance() { Ref<AudioEffectAmplifyInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectAmplify>(this); - ins->mix_volume_db=volume_db; + ins->base = Ref<AudioEffectAmplify>(this); + ins->mix_volume_db = volume_db; return ins; } void AudioEffectAmplify::set_volume_db(float p_volume) { - volume_db=p_volume; + volume_db = p_volume; } float AudioEffectAmplify::get_volume_db() const { @@ -66,13 +62,12 @@ float AudioEffectAmplify::get_volume_db() const { void AudioEffectAmplify::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_volume_db","volume"),&AudioEffectAmplify::set_volume_db); - ClassDB::bind_method(D_METHOD("get_volume_db"),&AudioEffectAmplify::get_volume_db); + ClassDB::bind_method(D_METHOD("set_volume_db", "volume"), &AudioEffectAmplify::set_volume_db); + ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioEffectAmplify::get_volume_db); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24,0.01"),"set_volume_db","get_volume_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24,0.01"), "set_volume_db", "get_volume_db"); } -AudioEffectAmplify::AudioEffectAmplify() -{ - volume_db=0; +AudioEffectAmplify::AudioEffectAmplify() { + volume_db = 0; } diff --git a/servers/audio/effects/audio_effect_amplify.h b/servers/audio/effects/audio_effect_amplify.h index 03f558e52e..0c75b43691 100644 --- a/servers/audio/effects/audio_effect_amplify.h +++ b/servers/audio/effects/audio_effect_amplify.h @@ -34,30 +34,26 @@ class AudioEffectAmplify; class AudioEffectAmplifyInstance : public AudioEffectInstance { - GDCLASS(AudioEffectAmplifyInstance,AudioEffectInstance) -friend class AudioEffectAmplify; + GDCLASS(AudioEffectAmplifyInstance, AudioEffectInstance) + friend class AudioEffectAmplify; Ref<AudioEffectAmplify> base; float mix_volume_db; -public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectAmplify : public AudioEffect { - GDCLASS(AudioEffectAmplify,AudioEffect) + GDCLASS(AudioEffectAmplify, AudioEffect) -friend class AudioEffectAmplifyInstance; + friend class AudioEffectAmplifyInstance; float volume_db; protected: - static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); void set_volume_db(float p_volume); float get_volume_db() const; diff --git a/servers/audio/effects/audio_effect_chorus.cpp b/servers/audio/effects/audio_effect_chorus.cpp index 20b45b5725..fa3a571c6e 100644 --- a/servers/audio/effects/audio_effect_chorus.cpp +++ b/servers/audio/effects/audio_effect_chorus.cpp @@ -27,161 +27,153 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_effect_chorus.h" -#include "servers/audio_server.h" #include "math_funcs.h" +#include "servers/audio_server.h" -void AudioEffectChorusInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectChorusInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { int todo = p_frame_count; - while(todo) { + while (todo) { - int to_mix = MIN(todo,256); //can't mix too much + int to_mix = MIN(todo, 256); //can't mix too much - _process_chunk(p_src_frames,p_dst_frames,to_mix); + _process_chunk(p_src_frames, p_dst_frames, to_mix); - p_src_frames+=to_mix; - p_dst_frames+=to_mix; + p_src_frames += to_mix; + p_dst_frames += to_mix; - todo-=to_mix; + todo -= to_mix; } } -void AudioEffectChorusInstance::_process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { - +void AudioEffectChorusInstance::_process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { //fill ringbuffer - for(int i=0;i<p_frame_count;i++) { - audio_buffer[(buffer_pos+i)&buffer_mask]=p_src_frames[i]; - p_dst_frames[i]=p_src_frames[i]*base->dry; + for (int i = 0; i < p_frame_count; i++) { + audio_buffer[(buffer_pos + i) & buffer_mask] = p_src_frames[i]; + p_dst_frames[i] = p_src_frames[i] * base->dry; } float mix_rate = AudioServer::get_singleton()->get_mix_rate(); /* process voices */ - for (int vc=0;vc<base->voice_count;vc++) { + for (int vc = 0; vc < base->voice_count; vc++) { - AudioEffectChorus::Voice &v=base->voice[vc]; + AudioEffectChorus::Voice &v = base->voice[vc]; + double time_to_mix = (float)p_frame_count / mix_rate; + double cycles_to_mix = time_to_mix * v.rate; - double time_to_mix=(float)p_frame_count/mix_rate; - double cycles_to_mix=time_to_mix*v.rate; + unsigned int local_rb_pos = buffer_pos; + AudioFrame *dst_buff = p_dst_frames; + AudioFrame *rb_buff = audio_buffer.ptr(); - unsigned int local_rb_pos=buffer_pos; - AudioFrame *dst_buff=p_dst_frames; - AudioFrame *rb_buff=audio_buffer.ptr(); + double delay_msec = v.delay; + unsigned int delay_frames = Math::fast_ftoi((delay_msec / 1000.0) * mix_rate); + float max_depth_frames = (v.depth / 1000.0) * mix_rate; - double delay_msec=v.delay; - unsigned int delay_frames=Math::fast_ftoi((delay_msec/1000.0)*mix_rate); - float max_depth_frames=(v.depth/1000.0)*mix_rate; - - uint64_t local_cycles=cycles[vc]; - uint64_t increment=llrint(cycles_to_mix/(double)p_frame_count*(double)(1<<AudioEffectChorus::CYCLES_FRAC)); + uint64_t local_cycles = cycles[vc]; + uint64_t increment = llrint(cycles_to_mix / (double)p_frame_count * (double)(1 << AudioEffectChorus::CYCLES_FRAC)); //check the LFO doesnt read ahead of the write pos - if ((((int)max_depth_frames)+10)>delay_frames) { //10 as some threshold to avoid precision stuff - delay_frames+=(int)max_depth_frames-delay_frames; - delay_frames+=10; //threshold to avoid precision stuff - + if ((((int)max_depth_frames) + 10) > delay_frames) { //10 as some threshold to avoid precision stuff + delay_frames += (int)max_depth_frames - delay_frames; + delay_frames += 10; //threshold to avoid precision stuff } - - //low pass filter - if (v.cutoff==0) + if (v.cutoff == 0) continue; - float auxlp=expf(-2.0*Math_PI*v.cutoff/mix_rate); - float c1=1.0-auxlp; - float c2=auxlp; - AudioFrame h=filter_h[vc]; - if (v.cutoff>=AudioEffectChorus::MS_CUTOFF_MAX) { - c1=1.0; c2=0.0; + float auxlp = expf(-2.0 * Math_PI * v.cutoff / mix_rate); + float c1 = 1.0 - auxlp; + float c2 = auxlp; + AudioFrame h = filter_h[vc]; + if (v.cutoff >= AudioEffectChorus::MS_CUTOFF_MAX) { + c1 = 1.0; + c2 = 0.0; } //vol modifier - AudioFrame vol_modifier=AudioFrame(base->wet,base->wet) * Math::db2linear(v.level); - vol_modifier.l*=CLAMP( 1.0 - v.pan, 0, 1); - vol_modifier.r*=CLAMP( 1.0 + v.pan, 0, 1); - + AudioFrame vol_modifier = AudioFrame(base->wet, base->wet) * Math::db2linear(v.level); + vol_modifier.l *= CLAMP(1.0 - v.pan, 0, 1); + vol_modifier.r *= CLAMP(1.0 + v.pan, 0, 1); - - for (int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { /** COMPUTE WAVEFORM **/ - float phase=(float)(local_cycles&AudioEffectChorus::CYCLES_MASK)/(float)(1<<AudioEffectChorus::CYCLES_FRAC); + float phase = (float)(local_cycles & AudioEffectChorus::CYCLES_MASK) / (float)(1 << AudioEffectChorus::CYCLES_FRAC); - float wave_delay=sinf(phase*2.0*Math_PI)*max_depth_frames; + float wave_delay = sinf(phase * 2.0 * Math_PI) * max_depth_frames; - int wave_delay_frames=lrint(floor(wave_delay)); - float wave_delay_frac=wave_delay-(float)wave_delay_frames; + int wave_delay_frames = lrint(floor(wave_delay)); + float wave_delay_frac = wave_delay - (float)wave_delay_frames; /** COMPUTE RINGBUFFER POS**/ - unsigned int rb_source=local_rb_pos; - rb_source-=delay_frames; + unsigned int rb_source = local_rb_pos; + rb_source -= delay_frames; - rb_source-=wave_delay_frames; + rb_source -= wave_delay_frames; /** READ FROM RINGBUFFER, LINEARLY INTERPOLATE */ - AudioFrame val=rb_buff[rb_source&buffer_mask]; - AudioFrame val_next=rb_buff[(rb_source-1)&buffer_mask]; + AudioFrame val = rb_buff[rb_source & buffer_mask]; + AudioFrame val_next = rb_buff[(rb_source - 1) & buffer_mask]; - val+=(val_next-val)*wave_delay_frac; + val += (val_next - val) * wave_delay_frac; - val=val*c1+h*c2; - h=val; + val = val * c1 + h * c2; + h = val; /** MIX VALUE TO OUTPUT **/ - dst_buff[i]+=val*vol_modifier; + dst_buff[i] += val * vol_modifier; - local_cycles+=increment; + local_cycles += increment; local_rb_pos++; - } - filter_h[vc]=h; - cycles[vc]+=Math::fast_ftoi(cycles_to_mix*(double)(1<<AudioEffectChorus::CYCLES_FRAC)); + filter_h[vc] = h; + cycles[vc] += Math::fast_ftoi(cycles_to_mix * (double)(1 << AudioEffectChorus::CYCLES_FRAC)); } - buffer_pos+=p_frame_count; + buffer_pos += p_frame_count; } - Ref<AudioEffectInstance> AudioEffectChorus::instance() { Ref<AudioEffectChorusInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectChorus>(this); - for(int i=0;i<4;i++) { - ins->filter_h[i]=AudioFrame(0,0); - ins->cycles[i]=0; + ins->base = Ref<AudioEffectChorus>(this); + for (int i = 0; i < 4; i++) { + ins->filter_h[i] = AudioFrame(0, 0); + ins->cycles[i] = 0; } - float ring_buffer_max_size=AudioEffectChorus::MAX_DELAY_MS+AudioEffectChorus::MAX_DEPTH_MS+AudioEffectChorus::MAX_WIDTH_MS; + float ring_buffer_max_size = AudioEffectChorus::MAX_DELAY_MS + AudioEffectChorus::MAX_DEPTH_MS + AudioEffectChorus::MAX_WIDTH_MS; - ring_buffer_max_size*=2; //just to avoid complications - ring_buffer_max_size/=1000.0;//convert to seconds - ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate(); + ring_buffer_max_size *= 2; //just to avoid complications + ring_buffer_max_size /= 1000.0; //convert to seconds + ring_buffer_max_size *= AudioServer::get_singleton()->get_mix_rate(); - int ringbuff_size=ring_buffer_max_size; + int ringbuff_size = ring_buffer_max_size; - int bits=0; + int bits = 0; - while(ringbuff_size>0) { + while (ringbuff_size > 0) { bits++; - ringbuff_size/=2; + ringbuff_size /= 2; } - ringbuff_size=1<<bits; - ins->buffer_mask=ringbuff_size-1; - ins->buffer_pos=0; + ringbuff_size = 1 << bits; + ins->buffer_mask = ringbuff_size - 1; + ins->buffer_pos = 0; ins->audio_buffer.resize(ringbuff_size); - for(int i=0;i<ringbuff_size;i++) { - ins->audio_buffer[i]=AudioFrame(0,0); + for (int i = 0; i < ringbuff_size; i++) { + ins->audio_buffer[i] = AudioFrame(0, 0); } return ins; @@ -189,205 +181,195 @@ Ref<AudioEffectInstance> AudioEffectChorus::instance() { void AudioEffectChorus::set_voice_count(int p_voices) { - ERR_FAIL_COND(p_voices<1 || p_voices>=MAX_VOICES); - voice_count=p_voices; + ERR_FAIL_COND(p_voices < 1 || p_voices >= MAX_VOICES); + voice_count = p_voices; _change_notify(); } - -int AudioEffectChorus::get_voice_count() const{ +int AudioEffectChorus::get_voice_count() const { return voice_count; } -void AudioEffectChorus::set_voice_delay_ms(int p_voice,float p_delay_ms){ - - ERR_FAIL_INDEX(p_voice,MAX_VOICES); +void AudioEffectChorus::set_voice_delay_ms(int p_voice, float p_delay_ms) { - voice[p_voice].delay=p_delay_ms; + ERR_FAIL_INDEX(p_voice, MAX_VOICES); + voice[p_voice].delay = p_delay_ms; } -float AudioEffectChorus::get_voice_delay_ms(int p_voice) const{ +float AudioEffectChorus::get_voice_delay_ms(int p_voice) const { - ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); + ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0); return voice[p_voice].delay; } -void AudioEffectChorus::set_voice_rate_hz(int p_voice,float p_rate_hz){ - ERR_FAIL_INDEX(p_voice,MAX_VOICES); +void AudioEffectChorus::set_voice_rate_hz(int p_voice, float p_rate_hz) { + ERR_FAIL_INDEX(p_voice, MAX_VOICES); - voice[p_voice].rate=p_rate_hz; + voice[p_voice].rate = p_rate_hz; } -float AudioEffectChorus::get_voice_rate_hz(int p_voice) const{ +float AudioEffectChorus::get_voice_rate_hz(int p_voice) const { - ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); + ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0); return voice[p_voice].rate; } -void AudioEffectChorus::set_voice_depth_ms(int p_voice,float p_depth_ms){ +void AudioEffectChorus::set_voice_depth_ms(int p_voice, float p_depth_ms) { - ERR_FAIL_INDEX(p_voice,MAX_VOICES); + ERR_FAIL_INDEX(p_voice, MAX_VOICES); - voice[p_voice].depth=p_depth_ms; + voice[p_voice].depth = p_depth_ms; } -float AudioEffectChorus::get_voice_depth_ms(int p_voice) const{ +float AudioEffectChorus::get_voice_depth_ms(int p_voice) const { - ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); + ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0); return voice[p_voice].depth; } -void AudioEffectChorus::set_voice_level_db(int p_voice,float p_level_db){ +void AudioEffectChorus::set_voice_level_db(int p_voice, float p_level_db) { - ERR_FAIL_INDEX(p_voice,MAX_VOICES); + ERR_FAIL_INDEX(p_voice, MAX_VOICES); - voice[p_voice].level=p_level_db; + voice[p_voice].level = p_level_db; } -float AudioEffectChorus::get_voice_level_db(int p_voice) const{ +float AudioEffectChorus::get_voice_level_db(int p_voice) const { - ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); + ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0); return voice[p_voice].level; } +void AudioEffectChorus::set_voice_cutoff_hz(int p_voice, float p_cutoff_hz) { -void AudioEffectChorus::set_voice_cutoff_hz(int p_voice,float p_cutoff_hz){ + ERR_FAIL_INDEX(p_voice, MAX_VOICES); - ERR_FAIL_INDEX(p_voice,MAX_VOICES); - - voice[p_voice].cutoff=p_cutoff_hz; + voice[p_voice].cutoff = p_cutoff_hz; } -float AudioEffectChorus::get_voice_cutoff_hz(int p_voice) const{ +float AudioEffectChorus::get_voice_cutoff_hz(int p_voice) const { - ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); + ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0); return voice[p_voice].cutoff; } -void AudioEffectChorus::set_voice_pan(int p_voice,float p_pan){ +void AudioEffectChorus::set_voice_pan(int p_voice, float p_pan) { - ERR_FAIL_INDEX(p_voice,MAX_VOICES); + ERR_FAIL_INDEX(p_voice, MAX_VOICES); - voice[p_voice].pan=p_pan; + voice[p_voice].pan = p_pan; } -float AudioEffectChorus::get_voice_pan(int p_voice) const{ +float AudioEffectChorus::get_voice_pan(int p_voice) const { - ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); + ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0); return voice[p_voice].pan; } +void AudioEffectChorus::set_wet(float amount) { -void AudioEffectChorus::set_wet(float amount){ - - - wet=amount; + wet = amount; } -float AudioEffectChorus::get_wet() const{ +float AudioEffectChorus::get_wet() const { return wet; } -void AudioEffectChorus::set_dry(float amount){ - - dry=amount; +void AudioEffectChorus::set_dry(float amount) { + dry = amount; } -float AudioEffectChorus::get_dry() const{ +float AudioEffectChorus::get_dry() const { return dry; } -void AudioEffectChorus::_validate_property(PropertyInfo& property) const { +void AudioEffectChorus::_validate_property(PropertyInfo &property) const { if (property.name.begins_with("voice/")) { - int voice_idx = property.name.get_slice("/",1).to_int(); - if (voice_idx>voice_count) { - property.usage=0; + int voice_idx = property.name.get_slice("/", 1).to_int(); + if (voice_idx > voice_count) { + property.usage = 0; } } } - void AudioEffectChorus::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_voice_count","voices"),&AudioEffectChorus::set_voice_count); - ClassDB::bind_method(D_METHOD("get_voice_count"),&AudioEffectChorus::get_voice_count); - - - ClassDB::bind_method(D_METHOD("set_voice_delay_ms","voice_idx","delay_ms"),&AudioEffectChorus::set_voice_delay_ms); - ClassDB::bind_method(D_METHOD("get_voice_delay_ms","voice_idx"),&AudioEffectChorus::get_voice_delay_ms); + ClassDB::bind_method(D_METHOD("set_voice_count", "voices"), &AudioEffectChorus::set_voice_count); + ClassDB::bind_method(D_METHOD("get_voice_count"), &AudioEffectChorus::get_voice_count); - ClassDB::bind_method(D_METHOD("set_voice_rate_hz","voice_idx","rate_hz"),&AudioEffectChorus::set_voice_rate_hz); - ClassDB::bind_method(D_METHOD("get_voice_rate_hz","voice_idx"),&AudioEffectChorus::get_voice_rate_hz); + ClassDB::bind_method(D_METHOD("set_voice_delay_ms", "voice_idx", "delay_ms"), &AudioEffectChorus::set_voice_delay_ms); + ClassDB::bind_method(D_METHOD("get_voice_delay_ms", "voice_idx"), &AudioEffectChorus::get_voice_delay_ms); - ClassDB::bind_method(D_METHOD("set_voice_depth_ms","voice_idx","depth_ms"),&AudioEffectChorus::set_voice_depth_ms); - ClassDB::bind_method(D_METHOD("get_voice_depth_ms","voice_idx"),&AudioEffectChorus::get_voice_depth_ms); + ClassDB::bind_method(D_METHOD("set_voice_rate_hz", "voice_idx", "rate_hz"), &AudioEffectChorus::set_voice_rate_hz); + ClassDB::bind_method(D_METHOD("get_voice_rate_hz", "voice_idx"), &AudioEffectChorus::get_voice_rate_hz); - ClassDB::bind_method(D_METHOD("set_voice_level_db","voice_idx","level_db"),&AudioEffectChorus::set_voice_level_db); - ClassDB::bind_method(D_METHOD("get_voice_level_db","voice_idx"),&AudioEffectChorus::get_voice_level_db); + ClassDB::bind_method(D_METHOD("set_voice_depth_ms", "voice_idx", "depth_ms"), &AudioEffectChorus::set_voice_depth_ms); + ClassDB::bind_method(D_METHOD("get_voice_depth_ms", "voice_idx"), &AudioEffectChorus::get_voice_depth_ms); - ClassDB::bind_method(D_METHOD("set_voice_cutoff_hz","voice_idx","cutoff_hz"),&AudioEffectChorus::set_voice_cutoff_hz); - ClassDB::bind_method(D_METHOD("get_voice_cutoff_hz","voice_idx"),&AudioEffectChorus::get_voice_cutoff_hz); + ClassDB::bind_method(D_METHOD("set_voice_level_db", "voice_idx", "level_db"), &AudioEffectChorus::set_voice_level_db); + ClassDB::bind_method(D_METHOD("get_voice_level_db", "voice_idx"), &AudioEffectChorus::get_voice_level_db); - ClassDB::bind_method(D_METHOD("set_voice_pan","voice_idx","pan"),&AudioEffectChorus::set_voice_pan); - ClassDB::bind_method(D_METHOD("get_voice_pan","voice_idx"),&AudioEffectChorus::get_voice_pan); + ClassDB::bind_method(D_METHOD("set_voice_cutoff_hz", "voice_idx", "cutoff_hz"), &AudioEffectChorus::set_voice_cutoff_hz); + ClassDB::bind_method(D_METHOD("get_voice_cutoff_hz", "voice_idx"), &AudioEffectChorus::get_voice_cutoff_hz); - ClassDB::bind_method(D_METHOD("set_wet","amount"),&AudioEffectChorus::set_wet); - ClassDB::bind_method(D_METHOD("get_wet"),&AudioEffectChorus::get_wet); + ClassDB::bind_method(D_METHOD("set_voice_pan", "voice_idx", "pan"), &AudioEffectChorus::set_voice_pan); + ClassDB::bind_method(D_METHOD("get_voice_pan", "voice_idx"), &AudioEffectChorus::get_voice_pan); - ClassDB::bind_method(D_METHOD("set_dry","amount"),&AudioEffectChorus::set_dry); - ClassDB::bind_method(D_METHOD("get_dry"),&AudioEffectChorus::get_dry); + ClassDB::bind_method(D_METHOD("set_wet", "amount"), &AudioEffectChorus::set_wet); + ClassDB::bind_method(D_METHOD("get_wet"), &AudioEffectChorus::get_wet); - ADD_PROPERTY(PropertyInfo(Variant::INT,"voice_count",PROPERTY_HINT_RANGE,"1,4,1"),"set_voice_count","get_voice_count"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dry","get_dry"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_wet","get_wet"); + ClassDB::bind_method(D_METHOD("set_dry", "amount"), &AudioEffectChorus::set_dry); + ClassDB::bind_method(D_METHOD("get_dry"), &AudioEffectChorus::get_dry); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",0); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",0); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",0); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",0); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",0); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",0); + ADD_PROPERTY(PropertyInfo(Variant::INT, "voice_count", PROPERTY_HINT_RANGE, "1,4,1"), "set_voice_count", "get_voice_count"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "wet", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_wet", "get_wet"); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",1); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",1); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",1); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",1); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",1); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",1); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 0); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 0); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 0); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 0); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 0); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 0); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",2); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",2); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",2); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",2); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",2); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 1); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 1); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 1); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 1); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 1); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 1); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",3); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",3); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",3); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",3); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",3); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",3); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 2); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 3); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 3); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 3); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 3); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 3); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 3); } -AudioEffectChorus::AudioEffectChorus() -{ - voice_count=2; - voice[0].delay=15; - voice[1].delay=20; - voice[0].rate=0.8; - voice[1].rate=1.2; - voice[0].depth=2; - voice[1].depth=3; - voice[0].cutoff=8000; - voice[1].cutoff=8000; - voice[0].pan=-0.5; - voice[1].pan=0.5; - - wet=0.5; - dry=1.0; +AudioEffectChorus::AudioEffectChorus() { + voice_count = 2; + voice[0].delay = 15; + voice[1].delay = 20; + voice[0].rate = 0.8; + voice[1].rate = 1.2; + voice[0].depth = 2; + voice[1].depth = 3; + voice[0].cutoff = 8000; + voice[1].cutoff = 8000; + voice[0].pan = -0.5; + voice[1].pan = 0.5; + + wet = 0.5; + dry = 1.0; } diff --git a/servers/audio/effects/audio_effect_chorus.h b/servers/audio/effects/audio_effect_chorus.h index ae0964bd53..9af9ab1b9a 100644 --- a/servers/audio/effects/audio_effect_chorus.h +++ b/servers/audio/effects/audio_effect_chorus.h @@ -29,14 +29,13 @@ #ifndef AUDIOEFFECTCHORUS_H #define AUDIOEFFECTCHORUS_H - #include "servers/audio/audio_effect.h" class AudioEffectChorus; class AudioEffectChorusInstance : public AudioEffectInstance { - GDCLASS(AudioEffectChorusInstance,AudioEffectInstance) -friend class AudioEffectChorus; + GDCLASS(AudioEffectChorusInstance, AudioEffectInstance) + friend class AudioEffectChorus; Ref<AudioEffectChorus> base; Vector<AudioFrame> audio_buffer; @@ -46,34 +45,31 @@ friend class AudioEffectChorus; AudioFrame filter_h[4]; uint64_t cycles[4]; - void _process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + void _process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); - + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectChorus : public AudioEffect { - GDCLASS(AudioEffectChorus,AudioEffect) + GDCLASS(AudioEffectChorus, AudioEffect) + + friend class AudioEffectChorusInstance; -friend class AudioEffectChorusInstance; public: enum { - MAX_DELAY_MS=50, - MAX_DEPTH_MS=20, - MAX_WIDTH_MS=50, - MAX_VOICES=4, - CYCLES_FRAC=16, - CYCLES_MASK=(1<<CYCLES_FRAC)-1, - MAX_CHANNELS=4, - MS_CUTOFF_MAX=16000 + MAX_DELAY_MS = 50, + MAX_DEPTH_MS = 20, + MAX_WIDTH_MS = 50, + MAX_VOICES = 4, + CYCLES_FRAC = 16, + CYCLES_MASK = (1 << CYCLES_FRAC) - 1, + MAX_CHANNELS = 4, + MS_CUTOFF_MAX = 16000 }; private: - struct Voice { float delay; @@ -85,13 +81,12 @@ private: Voice() { - delay=12.0; - rate=1; - depth=0; - level=0; - cutoff=MS_CUTOFF_MAX; - pan=0; - + delay = 12.0; + rate = 1; + depth = 0; + level = 0; + cutoff = MS_CUTOFF_MAX; + pan = 0; } } voice[MAX_VOICES]; @@ -101,32 +96,31 @@ private: float wet; float dry; - protected: - void _validate_property(PropertyInfo& property) const; + void _validate_property(PropertyInfo &property) const; static void _bind_methods(); -public: +public: void set_voice_count(int p_voices); int get_voice_count() const; - void set_voice_delay_ms(int p_voice,float p_delay_ms); + void set_voice_delay_ms(int p_voice, float p_delay_ms); float get_voice_delay_ms(int p_voice) const; - void set_voice_rate_hz(int p_voice,float p_rate_hz); + void set_voice_rate_hz(int p_voice, float p_rate_hz); float get_voice_rate_hz(int p_voice) const; - void set_voice_depth_ms(int p_voice,float p_depth_ms); + void set_voice_depth_ms(int p_voice, float p_depth_ms); float get_voice_depth_ms(int p_voice) const; - void set_voice_level_db(int p_voice,float p_level_db); + void set_voice_level_db(int p_voice, float p_level_db); float get_voice_level_db(int p_voice) const; - void set_voice_cutoff_hz(int p_voice,float p_cutoff_hz); + void set_voice_cutoff_hz(int p_voice, float p_cutoff_hz); float get_voice_cutoff_hz(int p_voice) const; - void set_voice_pan(int p_voice,float p_pan); + void set_voice_pan(int p_voice, float p_pan); float get_voice_pan(int p_voice) const; void set_wet(float amount); diff --git a/servers/audio/effects/audio_effect_compressor.cpp b/servers/audio/effects/audio_effect_compressor.cpp index c08302c58e..8b67353229 100644 --- a/servers/audio/effects/audio_effect_compressor.cpp +++ b/servers/audio/effects/audio_effect_compressor.cpp @@ -29,11 +29,10 @@ #include "audio_effect_compressor.h" #include "servers/audio_server.h" -void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { - +void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { float treshold = Math::db2linear(base->treshold); - float sample_rate=AudioServer::get_singleton()->get_mix_rate(); + float sample_rate = AudioServer::get_singleton()->get_mix_rate(); float ratatcoef = exp(-1 / (0.00001f * sample_rate)); float ratrelcoef = exp(-1 / (0.5f * sample_rate)); @@ -49,35 +48,35 @@ void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,Audio const AudioFrame *src = p_src_frames; - if (base->sidechain!=StringName() && current_channel!=-1) { + if (base->sidechain != StringName() && current_channel != -1) { int bus = AudioServer::get_singleton()->thread_find_bus_index(base->sidechain); - if (bus>=0) { - src = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus,current_channel); + if (bus >= 0) { + src = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus, current_channel); } } - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { AudioFrame s = src[i]; //convert to positive s.l = Math::abs(s.l); s.r = Math::abs(s.r); - float peak = MAX(s.l,s.r); + float peak = MAX(s.l, s.r); - float overdb = 2.08136898f * Math::linear2db(peak/treshold); + float overdb = 2.08136898f * Math::linear2db(peak / treshold); - if (overdb<0.0) //we only care about what goes over to compress - overdb=0.0; + if (overdb < 0.0) //we only care about what goes over to compress + overdb = 0.0; - if(overdb-rundb>5) // diffeence is too large + if (overdb - rundb > 5) // diffeence is too large averatio = 4; - if(overdb > rundb) { + if (overdb > rundb) { rundb = overdb + atcoef * (rundb - overdb); runratio = averatio + ratatcoef * (runratio - averatio); - } else { + } else { rundb = overdb + relcoef * (rundb - overdb); runratio = averatio + ratrelcoef * (runratio - averatio); } @@ -87,52 +86,47 @@ void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,Audio float cratio; - if(false) { //rato all-in + if (false) { //rato all-in cratio = 12 + averatio; } else { cratio = base->ratio; } - float gr = -overdb * (cratio-1)/cratio; + float gr = -overdb * (cratio - 1) / cratio; float grv = Math::db2linear(gr); - runmax = maxover + relcoef * (runmax - maxover); // highest peak for setting att/rel decays in reltime + runmax = maxover + relcoef * (runmax - maxover); // highest peak for setting att/rel decays in reltime maxover = runmax; if (grv < gr_meter) { - gr_meter=grv; + gr_meter = grv; } else { - gr_meter*=gr_meter_decay; - if(gr_meter>1) - gr_meter=1; + gr_meter *= gr_meter_decay; + if (gr_meter > 1) + gr_meter = 1; } - - p_dst_frames[i] = p_src_frames[i] * grv * makeup * mix + p_src_frames[i] * (1.0-mix); - + p_dst_frames[i] = p_src_frames[i] * grv * makeup * mix + p_src_frames[i] * (1.0 - mix); } - } - Ref<AudioEffectInstance> AudioEffectCompressor::instance() { Ref<AudioEffectCompressorInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectCompressor>(this); - ins->rundb=0; - ins->runratio=0; - ins->averatio=0; - ins->runmax=0; - ins->maxover=0; - ins->gr_meter=1.0; - ins->current_channel=-1; + ins->base = Ref<AudioEffectCompressor>(this); + ins->rundb = 0; + ins->runratio = 0; + ins->averatio = 0; + ins->runmax = 0; + ins->maxover = 0; + ins->gr_meter = 1.0; + ins->current_channel = -1; return ins; } - void AudioEffectCompressor::set_treshold(float p_treshold) { - treshold=p_treshold; + treshold = p_treshold; } float AudioEffectCompressor::get_treshold() const { @@ -142,7 +136,7 @@ float AudioEffectCompressor::get_treshold() const { void AudioEffectCompressor::set_ratio(float p_ratio) { - ratio=p_ratio; + ratio = p_ratio; } float AudioEffectCompressor::get_ratio() const { @@ -151,7 +145,7 @@ float AudioEffectCompressor::get_ratio() const { void AudioEffectCompressor::set_gain(float p_gain) { - gain=p_gain; + gain = p_gain; } float AudioEffectCompressor::get_gain() const { @@ -160,7 +154,7 @@ float AudioEffectCompressor::get_gain() const { void AudioEffectCompressor::set_attack_us(float p_attack_us) { - attack_us=p_attack_us; + attack_us = p_attack_us; } float AudioEffectCompressor::get_attack_us() const { @@ -169,7 +163,7 @@ float AudioEffectCompressor::get_attack_us() const { void AudioEffectCompressor::set_release_ms(float p_release_ms) { - release_ms=p_release_ms; + release_ms = p_release_ms; } float AudioEffectCompressor::get_release_ms() const { @@ -178,17 +172,17 @@ float AudioEffectCompressor::get_release_ms() const { void AudioEffectCompressor::set_mix(float p_mix) { - mix=p_mix; + mix = p_mix; } float AudioEffectCompressor::get_mix() const { return mix; } -void AudioEffectCompressor::set_sidechain(const StringName& p_sidechain) { +void AudioEffectCompressor::set_sidechain(const StringName &p_sidechain) { AudioServer::get_singleton()->lock(); - sidechain=p_sidechain; + sidechain = p_sidechain; AudioServer::get_singleton()->unlock(); } @@ -197,59 +191,57 @@ StringName AudioEffectCompressor::get_sidechain() const { return sidechain; } -void AudioEffectCompressor::_validate_property(PropertyInfo& property) const { +void AudioEffectCompressor::_validate_property(PropertyInfo &property) const { - if (property.name=="sidechain") { + if (property.name == "sidechain") { - String buses=""; - for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { - buses+=","; - buses+=AudioServer::get_singleton()->get_bus_name(i); + String buses = ""; + for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { + buses += ","; + buses += AudioServer::get_singleton()->get_bus_name(i); } - property.hint_string=buses; + property.hint_string = buses; } } void AudioEffectCompressor::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_treshold","treshold"),&AudioEffectCompressor::set_treshold); - ClassDB::bind_method(D_METHOD("get_treshold"),&AudioEffectCompressor::get_treshold); - - ClassDB::bind_method(D_METHOD("set_ratio","ratio"),&AudioEffectCompressor::set_ratio); - ClassDB::bind_method(D_METHOD("get_ratio"),&AudioEffectCompressor::get_ratio); + ClassDB::bind_method(D_METHOD("set_treshold", "treshold"), &AudioEffectCompressor::set_treshold); + ClassDB::bind_method(D_METHOD("get_treshold"), &AudioEffectCompressor::get_treshold); - ClassDB::bind_method(D_METHOD("set_gain","gain"),&AudioEffectCompressor::set_gain); - ClassDB::bind_method(D_METHOD("get_gain"),&AudioEffectCompressor::get_gain); + ClassDB::bind_method(D_METHOD("set_ratio", "ratio"), &AudioEffectCompressor::set_ratio); + ClassDB::bind_method(D_METHOD("get_ratio"), &AudioEffectCompressor::get_ratio); - ClassDB::bind_method(D_METHOD("set_attack_us","attack_us"),&AudioEffectCompressor::set_attack_us); - ClassDB::bind_method(D_METHOD("get_attack_us"),&AudioEffectCompressor::get_attack_us); + ClassDB::bind_method(D_METHOD("set_gain", "gain"), &AudioEffectCompressor::set_gain); + ClassDB::bind_method(D_METHOD("get_gain"), &AudioEffectCompressor::get_gain); - ClassDB::bind_method(D_METHOD("set_release_ms","release_ms"),&AudioEffectCompressor::set_release_ms); - ClassDB::bind_method(D_METHOD("get_release_ms"),&AudioEffectCompressor::get_release_ms); + ClassDB::bind_method(D_METHOD("set_attack_us", "attack_us"), &AudioEffectCompressor::set_attack_us); + ClassDB::bind_method(D_METHOD("get_attack_us"), &AudioEffectCompressor::get_attack_us); - ClassDB::bind_method(D_METHOD("set_mix","mix"),&AudioEffectCompressor::set_mix); - ClassDB::bind_method(D_METHOD("get_mix"),&AudioEffectCompressor::get_mix); + ClassDB::bind_method(D_METHOD("set_release_ms", "release_ms"), &AudioEffectCompressor::set_release_ms); + ClassDB::bind_method(D_METHOD("get_release_ms"), &AudioEffectCompressor::get_release_ms); - ClassDB::bind_method(D_METHOD("set_sidechain","sidechain"),&AudioEffectCompressor::set_sidechain); - ClassDB::bind_method(D_METHOD("get_sidechain"),&AudioEffectCompressor::get_sidechain); + ClassDB::bind_method(D_METHOD("set_mix", "mix"), &AudioEffectCompressor::set_mix); + ClassDB::bind_method(D_METHOD("get_mix"), &AudioEffectCompressor::get_mix); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"treshold",PROPERTY_HINT_RANGE,"-60,0,0.1"),"set_treshold","get_treshold"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ratio",PROPERTY_HINT_RANGE,"1,48,0.1"),"set_ratio","get_ratio"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"-20,20,0.1"),"set_gain","get_gain"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"attack_us",PROPERTY_HINT_RANGE,"20,2000,1"),"set_attack_us","get_attack_us"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"release_ms",PROPERTY_HINT_RANGE,"20,2000,1"),"set_release_ms","get_release_ms"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"mix",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_mix","get_mix"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"sidechain",PROPERTY_HINT_ENUM),"set_sidechain","get_sidechain"); + ClassDB::bind_method(D_METHOD("set_sidechain", "sidechain"), &AudioEffectCompressor::set_sidechain); + ClassDB::bind_method(D_METHOD("get_sidechain"), &AudioEffectCompressor::get_sidechain); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "treshold", PROPERTY_HINT_RANGE, "-60,0,0.1"), "set_treshold", "get_treshold"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ratio", PROPERTY_HINT_RANGE, "1,48,0.1"), "set_ratio", "get_ratio"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "gain", PROPERTY_HINT_RANGE, "-20,20,0.1"), "set_gain", "get_gain"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "attack_us", PROPERTY_HINT_RANGE, "20,2000,1"), "set_attack_us", "get_attack_us"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "release_ms", PROPERTY_HINT_RANGE, "20,2000,1"), "set_release_ms", "get_release_ms"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "mix", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_mix", "get_mix"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "sidechain", PROPERTY_HINT_ENUM), "set_sidechain", "get_sidechain"); } -AudioEffectCompressor::AudioEffectCompressor() -{ - treshold=0; - ratio=4; - gain=0; - attack_us=20; - release_ms=250; - mix=1; +AudioEffectCompressor::AudioEffectCompressor() { + treshold = 0; + ratio = 4; + gain = 0; + attack_us = 20; + release_ms = 250; + mix = 1; } diff --git a/servers/audio/effects/audio_effect_compressor.h b/servers/audio/effects/audio_effect_compressor.h index 3988ad1526..34f80348db 100644 --- a/servers/audio/effects/audio_effect_compressor.h +++ b/servers/audio/effects/audio_effect_compressor.h @@ -29,30 +29,27 @@ #ifndef AUDIOEFFECTCOMPRESSOR_H #define AUDIOEFFECTCOMPRESSOR_H - #include "servers/audio/audio_effect.h" class AudioEffectCompressor; class AudioEffectCompressorInstance : public AudioEffectInstance { - GDCLASS(AudioEffectCompressorInstance,AudioEffectInstance) -friend class AudioEffectCompressor; + GDCLASS(AudioEffectCompressorInstance, AudioEffectInstance) + friend class AudioEffectCompressor; Ref<AudioEffectCompressor> base; - float rundb,averatio,runratio,runmax,maxover,gr_meter; + float rundb, averatio, runratio, runmax, maxover, gr_meter; int current_channel; -public: - - void set_current_channel(int p_channel) { current_channel=p_channel; } - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + void set_current_channel(int p_channel) { current_channel = p_channel; } + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectCompressor : public AudioEffect { - GDCLASS(AudioEffectCompressor,AudioEffect) + GDCLASS(AudioEffectCompressor, AudioEffect) -friend class AudioEffectCompressorInstance; + friend class AudioEffectCompressorInstance; float treshold; float ratio; float gain; @@ -61,16 +58,13 @@ friend class AudioEffectCompressorInstance; float mix; StringName sidechain; - protected: - void _validate_property(PropertyInfo& property) const; + void _validate_property(PropertyInfo &property) const; static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); - void set_treshold(float p_treshold); float get_treshold() const; @@ -89,7 +83,7 @@ public: void set_mix(float p_mix); float get_mix() const; - void set_sidechain(const StringName& p_sidechain); + void set_sidechain(const StringName &p_sidechain); StringName get_sidechain() const; AudioEffectCompressor(); diff --git a/servers/audio/effects/audio_effect_delay.cpp b/servers/audio/effects/audio_effect_delay.cpp index a6d2048896..b643f801a7 100644 --- a/servers/audio/effects/audio_effect_delay.cpp +++ b/servers/audio/effects/audio_effect_delay.cpp @@ -27,328 +27,315 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_effect_delay.h" -#include "servers/audio_server.h" #include "math_funcs.h" +#include "servers/audio_server.h" -void AudioEffectDelayInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectDelayInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { int todo = p_frame_count; - while(todo) { + while (todo) { - int to_mix = MIN(todo,256); //can't mix too much + int to_mix = MIN(todo, 256); //can't mix too much - _process_chunk(p_src_frames,p_dst_frames,to_mix); + _process_chunk(p_src_frames, p_dst_frames, to_mix); - p_src_frames+=to_mix; - p_dst_frames+=to_mix; + p_src_frames += to_mix; + p_dst_frames += to_mix; - todo-=to_mix; + todo -= to_mix; } } -void AudioEffectDelayInstance::_process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { - - - - float main_level_f=base->dry; +void AudioEffectDelayInstance::_process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { + float main_level_f = base->dry; float mix_rate = AudioServer::get_singleton()->get_mix_rate(); - float tap_1_level_f=base->tap_1_active?Math::db2linear(base->tap_1_level):0.0; - int tap_1_delay_frames=int((base->tap_1_delay_ms/1000.0)*mix_rate);; + float tap_1_level_f = base->tap_1_active ? Math::db2linear(base->tap_1_level) : 0.0; + int tap_1_delay_frames = int((base->tap_1_delay_ms / 1000.0) * mix_rate); + ; - float tap_2_level_f=base->tap_2_active?Math::db2linear(base->tap_2_level):0.0; - int tap_2_delay_frames=int((base->tap_2_delay_ms/1000.0)*mix_rate);; + float tap_2_level_f = base->tap_2_active ? Math::db2linear(base->tap_2_level) : 0.0; + int tap_2_delay_frames = int((base->tap_2_delay_ms / 1000.0) * mix_rate); + ; - float feedback_level_f=base->feedback_active?Math::db2linear(base->feedback_level):0.0; - unsigned int feedback_delay_frames=int((base->feedback_delay_ms/1000.0)*mix_rate);; + float feedback_level_f = base->feedback_active ? Math::db2linear(base->feedback_level) : 0.0; + unsigned int feedback_delay_frames = int((base->feedback_delay_ms / 1000.0) * mix_rate); + ; + AudioFrame tap1_vol = AudioFrame(tap_1_level_f, tap_1_level_f); - AudioFrame tap1_vol=AudioFrame(tap_1_level_f,tap_1_level_f); + tap1_vol.l *= CLAMP(1.0 - base->tap_1_pan, 0, 1); + tap1_vol.r *= CLAMP(1.0 + base->tap_1_pan, 0, 1); - tap1_vol.l*=CLAMP( 1.0 - base->tap_1_pan, 0, 1); - tap1_vol.r*=CLAMP( 1.0 + base->tap_1_pan, 0, 1); + AudioFrame tap2_vol = AudioFrame(tap_2_level_f, tap_2_level_f); - AudioFrame tap2_vol=AudioFrame(tap_2_level_f,tap_2_level_f); - - tap2_vol.l*=CLAMP( 1.0 - base->tap_2_pan, 0, 1); - tap2_vol.r*=CLAMP( 1.0 + base->tap_2_pan, 0, 1); + tap2_vol.l *= CLAMP(1.0 - base->tap_2_pan, 0, 1); + tap2_vol.r *= CLAMP(1.0 + base->tap_2_pan, 0, 1); // feedback lowpass here - float lpf_c=expf(-2.0*Math_PI*base->feedback_lowpass/mix_rate); // 0 .. 10khz - float lpf_ic=1.0-lpf_c; - - const AudioFrame *src=p_src_frames; - AudioFrame *dst=p_dst_frames; - AudioFrame *rb_buf=ring_buffer.ptr(); - AudioFrame *fb_buf=feedback_buffer.ptr(); + float lpf_c = expf(-2.0 * Math_PI * base->feedback_lowpass / mix_rate); // 0 .. 10khz + float lpf_ic = 1.0 - lpf_c; + const AudioFrame *src = p_src_frames; + AudioFrame *dst = p_dst_frames; + AudioFrame *rb_buf = ring_buffer.ptr(); + AudioFrame *fb_buf = feedback_buffer.ptr(); - for (int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { + rb_buf[ring_buffer_pos & ring_buffer_mask] = src[i]; - rb_buf[ring_buffer_pos&ring_buffer_mask]=src[i]; + AudioFrame main_val = src[i] * main_level_f; + AudioFrame tap_1_val = rb_buf[(ring_buffer_pos - tap_1_delay_frames) & ring_buffer_mask] * tap1_vol; + AudioFrame tap_2_val = rb_buf[(ring_buffer_pos - tap_2_delay_frames) & ring_buffer_mask] * tap2_vol; - AudioFrame main_val=src[i]*main_level_f; - AudioFrame tap_1_val=rb_buf[(ring_buffer_pos-tap_1_delay_frames)&ring_buffer_mask]*tap1_vol; - AudioFrame tap_2_val=rb_buf[(ring_buffer_pos-tap_2_delay_frames)&ring_buffer_mask]*tap2_vol; + AudioFrame out = main_val + tap_1_val + tap_2_val; - AudioFrame out=main_val+tap_1_val+tap_2_val; - - out+=fb_buf[ feedback_buffer_pos ]; + out += fb_buf[feedback_buffer_pos]; //apply lowpass and feedback gain - AudioFrame fb_in=out*feedback_level_f*lpf_ic+h*lpf_c; + AudioFrame fb_in = out * feedback_level_f * lpf_ic + h * lpf_c; fb_in.undenormalise(); //avoid denormals - h=fb_in; - fb_buf[ feedback_buffer_pos ]=fb_in; + h = fb_in; + fb_buf[feedback_buffer_pos] = fb_in; - dst[i]=out; + dst[i] = out; ring_buffer_pos++; - if ( (++feedback_buffer_pos) >= feedback_delay_frames ) - feedback_buffer_pos=0; + if ((++feedback_buffer_pos) >= feedback_delay_frames) + feedback_buffer_pos = 0; } } - - Ref<AudioEffectInstance> AudioEffectDelay::instance() { Ref<AudioEffectDelayInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectDelay>(this); + ins->base = Ref<AudioEffectDelay>(this); - float ring_buffer_max_size=MAX_DELAY_MS+100; //add 100ms of extra room, just in case - ring_buffer_max_size/=1000.0;//convert to seconds - ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate(); + float ring_buffer_max_size = MAX_DELAY_MS + 100; //add 100ms of extra room, just in case + ring_buffer_max_size /= 1000.0; //convert to seconds + ring_buffer_max_size *= AudioServer::get_singleton()->get_mix_rate(); - int ringbuff_size=ring_buffer_max_size; + int ringbuff_size = ring_buffer_max_size; - int bits=0; + int bits = 0; - while(ringbuff_size>0) { + while (ringbuff_size > 0) { bits++; - ringbuff_size/=2; + ringbuff_size /= 2; } - ringbuff_size=1<<bits; - ins->ring_buffer_mask=ringbuff_size-1; - ins->ring_buffer_pos=0; + ringbuff_size = 1 << bits; + ins->ring_buffer_mask = ringbuff_size - 1; + ins->ring_buffer_pos = 0; - ins->ring_buffer.resize( ringbuff_size ); - ins->feedback_buffer.resize( ringbuff_size ); + ins->ring_buffer.resize(ringbuff_size); + ins->feedback_buffer.resize(ringbuff_size); - ins->feedback_buffer_pos=0; + ins->feedback_buffer_pos = 0; - ins->h=AudioFrame(0,0); + ins->h = AudioFrame(0, 0); return ins; } - void AudioEffectDelay::set_dry(float p_dry) { - dry=p_dry; + dry = p_dry; } -float AudioEffectDelay::get_dry(){ +float AudioEffectDelay::get_dry() { return dry; } -void AudioEffectDelay::set_tap1_active(bool p_active){ +void AudioEffectDelay::set_tap1_active(bool p_active) { - tap_1_active=p_active; + tap_1_active = p_active; } -bool AudioEffectDelay::is_tap1_active() const{ +bool AudioEffectDelay::is_tap1_active() const { return tap_1_active; } -void AudioEffectDelay::set_tap1_delay_ms(float p_delay_ms){ +void AudioEffectDelay::set_tap1_delay_ms(float p_delay_ms) { - tap_1_delay_ms=p_delay_ms; + tap_1_delay_ms = p_delay_ms; } -float AudioEffectDelay::get_tap1_delay_ms() const{ +float AudioEffectDelay::get_tap1_delay_ms() const { return tap_1_delay_ms; } -void AudioEffectDelay::set_tap1_level_db(float p_level_db){ +void AudioEffectDelay::set_tap1_level_db(float p_level_db) { - tap_1_level=p_level_db; + tap_1_level = p_level_db; } -float AudioEffectDelay::get_tap1_level_db() const{ +float AudioEffectDelay::get_tap1_level_db() const { return tap_1_level; } -void AudioEffectDelay::set_tap1_pan(float p_pan){ +void AudioEffectDelay::set_tap1_pan(float p_pan) { - tap_1_pan=p_pan; + tap_1_pan = p_pan; } -float AudioEffectDelay::get_tap1_pan() const{ +float AudioEffectDelay::get_tap1_pan() const { return tap_1_pan; } +void AudioEffectDelay::set_tap2_active(bool p_active) { -void AudioEffectDelay::set_tap2_active(bool p_active){ - - tap_2_active=p_active; + tap_2_active = p_active; } -bool AudioEffectDelay::is_tap2_active() const{ +bool AudioEffectDelay::is_tap2_active() const { return tap_2_active; } -void AudioEffectDelay::set_tap2_delay_ms(float p_delay_ms){ +void AudioEffectDelay::set_tap2_delay_ms(float p_delay_ms) { - tap_2_delay_ms=p_delay_ms; + tap_2_delay_ms = p_delay_ms; } -float AudioEffectDelay::get_tap2_delay_ms() const{ +float AudioEffectDelay::get_tap2_delay_ms() const { return tap_2_delay_ms; } -void AudioEffectDelay::set_tap2_level_db(float p_level_db){ +void AudioEffectDelay::set_tap2_level_db(float p_level_db) { - tap_2_level=p_level_db; + tap_2_level = p_level_db; } -float AudioEffectDelay::get_tap2_level_db() const{ +float AudioEffectDelay::get_tap2_level_db() const { return tap_2_level; } -void AudioEffectDelay::set_tap2_pan(float p_pan){ +void AudioEffectDelay::set_tap2_pan(float p_pan) { - tap_2_pan=p_pan; + tap_2_pan = p_pan; } -float AudioEffectDelay::get_tap2_pan() const{ +float AudioEffectDelay::get_tap2_pan() const { return tap_2_pan; } -void AudioEffectDelay::set_feedback_active(bool p_active){ +void AudioEffectDelay::set_feedback_active(bool p_active) { - feedback_active=p_active; + feedback_active = p_active; } -bool AudioEffectDelay::is_feedback_active() const{ +bool AudioEffectDelay::is_feedback_active() const { return feedback_active; } -void AudioEffectDelay::set_feedback_delay_ms(float p_delay_ms){ +void AudioEffectDelay::set_feedback_delay_ms(float p_delay_ms) { - feedback_delay_ms=p_delay_ms; + feedback_delay_ms = p_delay_ms; } -float AudioEffectDelay::get_feedback_delay_ms() const{ +float AudioEffectDelay::get_feedback_delay_ms() const { return feedback_delay_ms; } -void AudioEffectDelay::set_feedback_level_db(float p_level_db){ +void AudioEffectDelay::set_feedback_level_db(float p_level_db) { - feedback_level=p_level_db; + feedback_level = p_level_db; } -float AudioEffectDelay::get_feedback_level_db() const{ +float AudioEffectDelay::get_feedback_level_db() const { return feedback_level; } -void AudioEffectDelay::set_feedback_lowpass(float p_lowpass){ +void AudioEffectDelay::set_feedback_lowpass(float p_lowpass) { - feedback_lowpass=p_lowpass; + feedback_lowpass = p_lowpass; } -float AudioEffectDelay::get_feedback_lowpass() const{ +float AudioEffectDelay::get_feedback_lowpass() const { return feedback_lowpass; } - void AudioEffectDelay::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_dry","amount"),&AudioEffectDelay::set_dry); - ClassDB::bind_method(D_METHOD("get_dry"),&AudioEffectDelay::get_dry); + ClassDB::bind_method(D_METHOD("set_dry", "amount"), &AudioEffectDelay::set_dry); + ClassDB::bind_method(D_METHOD("get_dry"), &AudioEffectDelay::get_dry); - ClassDB::bind_method(D_METHOD("set_tap1_active","amount"),&AudioEffectDelay::set_tap1_active); - ClassDB::bind_method(D_METHOD("is_tap1_active"),&AudioEffectDelay::is_tap1_active); + ClassDB::bind_method(D_METHOD("set_tap1_active", "amount"), &AudioEffectDelay::set_tap1_active); + ClassDB::bind_method(D_METHOD("is_tap1_active"), &AudioEffectDelay::is_tap1_active); - ClassDB::bind_method(D_METHOD("set_tap1_delay_ms","amount"),&AudioEffectDelay::set_tap1_delay_ms); - ClassDB::bind_method(D_METHOD("get_tap1_delay_ms"),&AudioEffectDelay::get_tap1_delay_ms); + ClassDB::bind_method(D_METHOD("set_tap1_delay_ms", "amount"), &AudioEffectDelay::set_tap1_delay_ms); + ClassDB::bind_method(D_METHOD("get_tap1_delay_ms"), &AudioEffectDelay::get_tap1_delay_ms); - ClassDB::bind_method(D_METHOD("set_tap1_level_db","amount"),&AudioEffectDelay::set_tap1_level_db); - ClassDB::bind_method(D_METHOD("get_tap1_level_db"),&AudioEffectDelay::get_tap1_level_db); + ClassDB::bind_method(D_METHOD("set_tap1_level_db", "amount"), &AudioEffectDelay::set_tap1_level_db); + ClassDB::bind_method(D_METHOD("get_tap1_level_db"), &AudioEffectDelay::get_tap1_level_db); - ClassDB::bind_method(D_METHOD("set_tap1_pan","amount"),&AudioEffectDelay::set_tap1_pan); - ClassDB::bind_method(D_METHOD("get_tap1_pan"),&AudioEffectDelay::get_tap1_pan); + ClassDB::bind_method(D_METHOD("set_tap1_pan", "amount"), &AudioEffectDelay::set_tap1_pan); + ClassDB::bind_method(D_METHOD("get_tap1_pan"), &AudioEffectDelay::get_tap1_pan); - ClassDB::bind_method(D_METHOD("set_tap2_active","amount"),&AudioEffectDelay::set_tap2_active); - ClassDB::bind_method(D_METHOD("is_tap2_active"),&AudioEffectDelay::is_tap2_active); + ClassDB::bind_method(D_METHOD("set_tap2_active", "amount"), &AudioEffectDelay::set_tap2_active); + ClassDB::bind_method(D_METHOD("is_tap2_active"), &AudioEffectDelay::is_tap2_active); - ClassDB::bind_method(D_METHOD("set_tap2_delay_ms","amount"),&AudioEffectDelay::set_tap2_delay_ms); - ClassDB::bind_method(D_METHOD("get_tap2_delay_ms"),&AudioEffectDelay::get_tap2_delay_ms); + ClassDB::bind_method(D_METHOD("set_tap2_delay_ms", "amount"), &AudioEffectDelay::set_tap2_delay_ms); + ClassDB::bind_method(D_METHOD("get_tap2_delay_ms"), &AudioEffectDelay::get_tap2_delay_ms); - ClassDB::bind_method(D_METHOD("set_tap2_level_db","amount"),&AudioEffectDelay::set_tap2_level_db); - ClassDB::bind_method(D_METHOD("get_tap2_level_db"),&AudioEffectDelay::get_tap2_level_db); + ClassDB::bind_method(D_METHOD("set_tap2_level_db", "amount"), &AudioEffectDelay::set_tap2_level_db); + ClassDB::bind_method(D_METHOD("get_tap2_level_db"), &AudioEffectDelay::get_tap2_level_db); - ClassDB::bind_method(D_METHOD("set_tap2_pan","amount"),&AudioEffectDelay::set_tap2_pan); - ClassDB::bind_method(D_METHOD("get_tap2_pan"),&AudioEffectDelay::get_tap2_pan); + ClassDB::bind_method(D_METHOD("set_tap2_pan", "amount"), &AudioEffectDelay::set_tap2_pan); + ClassDB::bind_method(D_METHOD("get_tap2_pan"), &AudioEffectDelay::get_tap2_pan); + ClassDB::bind_method(D_METHOD("set_feedback_active", "amount"), &AudioEffectDelay::set_feedback_active); + ClassDB::bind_method(D_METHOD("is_feedback_active"), &AudioEffectDelay::is_feedback_active); - ClassDB::bind_method(D_METHOD("set_feedback_active","amount"),&AudioEffectDelay::set_feedback_active); - ClassDB::bind_method(D_METHOD("is_feedback_active"),&AudioEffectDelay::is_feedback_active); + ClassDB::bind_method(D_METHOD("set_feedback_delay_ms", "amount"), &AudioEffectDelay::set_feedback_delay_ms); + ClassDB::bind_method(D_METHOD("get_feedback_delay_ms"), &AudioEffectDelay::get_feedback_delay_ms); - ClassDB::bind_method(D_METHOD("set_feedback_delay_ms","amount"),&AudioEffectDelay::set_feedback_delay_ms); - ClassDB::bind_method(D_METHOD("get_feedback_delay_ms"),&AudioEffectDelay::get_feedback_delay_ms); + ClassDB::bind_method(D_METHOD("set_feedback_level_db", "amount"), &AudioEffectDelay::set_feedback_level_db); + ClassDB::bind_method(D_METHOD("get_feedback_level_db"), &AudioEffectDelay::get_feedback_level_db); - ClassDB::bind_method(D_METHOD("set_feedback_level_db","amount"),&AudioEffectDelay::set_feedback_level_db); - ClassDB::bind_method(D_METHOD("get_feedback_level_db"),&AudioEffectDelay::get_feedback_level_db); + ClassDB::bind_method(D_METHOD("set_feedback_lowpass", "amount"), &AudioEffectDelay::set_feedback_lowpass); + ClassDB::bind_method(D_METHOD("get_feedback_lowpass"), &AudioEffectDelay::get_feedback_lowpass); - ClassDB::bind_method(D_METHOD("set_feedback_lowpass","amount"),&AudioEffectDelay::set_feedback_lowpass); - ClassDB::bind_method(D_METHOD("get_feedback_lowpass"),&AudioEffectDelay::get_feedback_lowpass); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dry","get_dry"); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"tap1/active"),"set_tap1_active","is_tap1_active"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),"set_tap1_delay_ms","get_tap1_delay_ms"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),"set_tap1_level_db","get_tap1_level_db"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_tap1_pan","get_tap1_pan"); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"tap2/active"),"set_tap2_active","is_tap2_active"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),"set_tap2_delay_ms","get_tap2_delay_ms"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),"set_tap2_level_db","get_tap2_level_db"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_tap2_pan","get_tap2_pan"); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"feedback/active"),"set_feedback_active","is_feedback_active"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),"set_feedback_delay_ms","get_feedback_delay_ms"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),"set_feedback_level_db","get_feedback_level_db"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/lowpass",PROPERTY_HINT_RANGE,"1,16000,1"),"set_feedback_lowpass","get_feedback_lowpass"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap1/active"), "set_tap1_active", "is_tap1_active"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap1/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1"), "set_tap1_delay_ms", "get_tap1_delay_ms"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap1/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01"), "set_tap1_level_db", "get_tap1_level_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap1/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap1_pan", "get_tap1_pan"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap2/active"), "set_tap2_active", "is_tap2_active"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap2/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1"), "set_tap2_delay_ms", "get_tap2_delay_ms"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap2/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01"), "set_tap2_level_db", "get_tap2_level_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap2/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap2_pan", "get_tap2_pan"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "feedback/active"), "set_feedback_active", "is_feedback_active"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1"), "set_feedback_delay_ms", "get_feedback_delay_ms"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01"), "set_feedback_level_db", "get_feedback_level_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback/lowpass", PROPERTY_HINT_RANGE, "1,16000,1"), "set_feedback_lowpass", "get_feedback_lowpass"); } -AudioEffectDelay::AudioEffectDelay() -{ - tap_1_active=true; - tap_1_delay_ms=250; - tap_1_level=-6; - tap_1_pan=0.2; - - tap_2_active=true; - tap_2_delay_ms=500; - tap_2_level=-12; - tap_2_pan=-0.4; +AudioEffectDelay::AudioEffectDelay() { + tap_1_active = true; + tap_1_delay_ms = 250; + tap_1_level = -6; + tap_1_pan = 0.2; - feedback_active=false; - feedback_delay_ms=340; - feedback_level=-6; - feedback_lowpass=16000; + tap_2_active = true; + tap_2_delay_ms = 500; + tap_2_level = -12; + tap_2_pan = -0.4; - dry=1.0; + feedback_active = false; + feedback_delay_ms = 340; + feedback_level = -6; + feedback_lowpass = 16000; + dry = 1.0; } diff --git a/servers/audio/effects/audio_effect_delay.h b/servers/audio/effects/audio_effect_delay.h index 3e9f7f0584..247fddac00 100644 --- a/servers/audio/effects/audio_effect_delay.h +++ b/servers/audio/effects/audio_effect_delay.h @@ -34,8 +34,8 @@ class AudioEffectDelay; class AudioEffectDelayInstance : public AudioEffectInstance { - GDCLASS(AudioEffectDelayInstance,AudioEffectInstance) -friend class AudioEffectDelay; + GDCLASS(AudioEffectDelayInstance, AudioEffectInstance) + friend class AudioEffectDelay; Ref<AudioEffectDelay> base; Vector<AudioFrame> ring_buffer; @@ -49,23 +49,20 @@ friend class AudioEffectDelay; unsigned int feedback_buffer_pos; AudioFrame h; - void _process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + void _process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); - + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectDelay : public AudioEffect { - GDCLASS(AudioEffectDelay,AudioEffect) + GDCLASS(AudioEffectDelay, AudioEffect) -friend class AudioEffectDelayInstance; + friend class AudioEffectDelayInstance; enum { - MAX_DELAY_MS=3000, - MAX_TAPS=2 + MAX_DELAY_MS = 3000, + MAX_TAPS = 2 }; float dry; @@ -85,13 +82,10 @@ friend class AudioEffectDelayInstance; float feedback_level; float feedback_lowpass; - - protected: - static void _bind_methods(); -public: +public: void set_dry(float p_dry); float get_dry(); @@ -136,5 +130,4 @@ public: AudioEffectDelay(); }; - #endif // AUDIOEFFECTDELAY_H diff --git a/servers/audio/effects/audio_effect_distortion.cpp b/servers/audio/effects/audio_effect_distortion.cpp index b72cd8e0a6..e5430fcd21 100644 --- a/servers/audio/effects/audio_effect_distortion.cpp +++ b/servers/audio/effects/audio_effect_distortion.cpp @@ -27,173 +27,159 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_effect_distortion.h" -#include "servers/audio_server.h" #include "math_funcs.h" +#include "servers/audio_server.h" +void AudioEffectDistortionInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { - -void AudioEffectDistortionInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { - - const float *src = (const float*)p_src_frames; - float *dst = (float*)p_dst_frames; + const float *src = (const float *)p_src_frames; + float *dst = (float *)p_dst_frames; //float lpf_c=expf(-2.0*Math_PI*keep_hf_hz.get()/(mix_rate*(float)OVERSAMPLE)); - float lpf_c=expf(-2.0*Math_PI*base->keep_hf_hz/(AudioServer::get_singleton()->get_mix_rate())); - float lpf_ic=1.0-lpf_c; + float lpf_c = expf(-2.0 * Math_PI * base->keep_hf_hz / (AudioServer::get_singleton()->get_mix_rate())); + float lpf_ic = 1.0 - lpf_c; - float drive_f=base->drive; - float pregain_f=Math::db2linear(base->pre_gain); - float postgain_f=Math::db2linear(base->post_gain); + float drive_f = base->drive; + float pregain_f = Math::db2linear(base->pre_gain); + float postgain_f = Math::db2linear(base->post_gain); - float atan_mult=pow(10,drive_f*drive_f*3.0)-1.0+0.001; - float atan_div=1.0/(atanf(atan_mult)*(1.0+drive_f*8)); + float atan_mult = pow(10, drive_f * drive_f * 3.0) - 1.0 + 0.001; + float atan_div = 1.0 / (atanf(atan_mult) * (1.0 + drive_f * 8)); - float lofi_mult=powf(2.0,2.0+(1.0-drive_f)*14); //goes from 16 to 2 bits + float lofi_mult = powf(2.0, 2.0 + (1.0 - drive_f) * 14); //goes from 16 to 2 bits - for (int i=0;i<p_frame_count*2;i++) { + for (int i = 0; i < p_frame_count * 2; i++) { - float out=undenormalise(src[i]*lpf_ic+lpf_c*h[i&1]); - h[i&1]=out; - float a=out; - float ha=src[i]-out; //high freqs - a*=pregain_f; + float out = undenormalise(src[i] * lpf_ic + lpf_c * h[i & 1]); + h[i & 1] = out; + float a = out; + float ha = src[i] - out; //high freqs + a *= pregain_f; switch (base->mode) { case AudioEffectDistortion::MODE_CLIP: { - a=powf(a,1.0001-drive_f); - if (a>1.0) - a=1.0; - else if (a<(-1.0)) - a=-1.0; + a = powf(a, 1.0001 - drive_f); + if (a > 1.0) + a = 1.0; + else if (a < (-1.0)) + a = -1.0; } break; case AudioEffectDistortion::MODE_ATAN: { - - a=atanf(a*atan_mult)*atan_div; + a = atanf(a * atan_mult) * atan_div; } break; case AudioEffectDistortion::MODE_LOFI: { - a = floorf(a*lofi_mult+0.5)/lofi_mult; + a = floorf(a * lofi_mult + 0.5) / lofi_mult; } break; case AudioEffectDistortion::MODE_OVERDRIVE: { - const double x = a * 0.686306; - const double z = 1 + exp (sqrt (fabs (x)) * -0.75); + const double z = 1 + exp(sqrt(fabs(x)) * -0.75); a = (expf(x) - expf(-x * z)) / (expf(x) + expf(-x)); } break; case AudioEffectDistortion::MODE_WAVESHAPE: { float x = a; - float k= 2*drive_f/(1.00001-drive_f); - - a = (1.0+k)*x/(1.0+k*fabsf(x)); + float k = 2 * drive_f / (1.00001 - drive_f); + a = (1.0 + k) * x / (1.0 + k * fabsf(x)); } break; } - dst[i]=a*postgain_f+ha; - + dst[i] = a * postgain_f + ha; } - - } - Ref<AudioEffectInstance> AudioEffectDistortion::instance() { Ref<AudioEffectDistortionInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectDistortion>(this); - ins->h[0]=0; - ins->h[1]=0; + ins->base = Ref<AudioEffectDistortion>(this); + ins->h[0] = 0; + ins->h[1] = 0; return ins; } - void AudioEffectDistortion::set_mode(Mode p_mode) { - mode=p_mode; + mode = p_mode; } -AudioEffectDistortion::Mode AudioEffectDistortion::get_mode() const{ +AudioEffectDistortion::Mode AudioEffectDistortion::get_mode() const { return mode; } -void AudioEffectDistortion::set_pre_gain(float p_pre_gain){ +void AudioEffectDistortion::set_pre_gain(float p_pre_gain) { - pre_gain=p_pre_gain; + pre_gain = p_pre_gain; } -float AudioEffectDistortion::get_pre_gain() const{ +float AudioEffectDistortion::get_pre_gain() const { return pre_gain; } -void AudioEffectDistortion::set_keep_hf_hz(float p_keep_hf_hz){ +void AudioEffectDistortion::set_keep_hf_hz(float p_keep_hf_hz) { - keep_hf_hz=p_keep_hf_hz; + keep_hf_hz = p_keep_hf_hz; } -float AudioEffectDistortion::get_keep_hf_hz() const{ +float AudioEffectDistortion::get_keep_hf_hz() const { return keep_hf_hz; } -void AudioEffectDistortion::set_drive(float p_drive){ +void AudioEffectDistortion::set_drive(float p_drive) { - drive=p_drive; + drive = p_drive; } -float AudioEffectDistortion::get_drive() const{ +float AudioEffectDistortion::get_drive() const { return drive; } -void AudioEffectDistortion::set_post_gain(float p_post_gain){ +void AudioEffectDistortion::set_post_gain(float p_post_gain) { - post_gain=p_post_gain; + post_gain = p_post_gain; } -float AudioEffectDistortion::get_post_gain() const{ +float AudioEffectDistortion::get_post_gain() const { return post_gain; } - void AudioEffectDistortion::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_mode","mode"),&AudioEffectDistortion::set_mode); - ClassDB::bind_method(D_METHOD("get_mode"),&AudioEffectDistortion::get_mode); - - ClassDB::bind_method(D_METHOD("set_pre_gain","pre_gain"),&AudioEffectDistortion::set_pre_gain); - ClassDB::bind_method(D_METHOD("get_pre_gain"),&AudioEffectDistortion::get_pre_gain); + ClassDB::bind_method(D_METHOD("set_mode", "mode"), &AudioEffectDistortion::set_mode); + ClassDB::bind_method(D_METHOD("get_mode"), &AudioEffectDistortion::get_mode); - ClassDB::bind_method(D_METHOD("set_keep_hf_hz","keep_hf_hz"),&AudioEffectDistortion::set_keep_hf_hz); - ClassDB::bind_method(D_METHOD("get_keep_hf_hz"),&AudioEffectDistortion::get_keep_hf_hz); + ClassDB::bind_method(D_METHOD("set_pre_gain", "pre_gain"), &AudioEffectDistortion::set_pre_gain); + ClassDB::bind_method(D_METHOD("get_pre_gain"), &AudioEffectDistortion::get_pre_gain); - ClassDB::bind_method(D_METHOD("set_drive","drive"),&AudioEffectDistortion::set_drive); - ClassDB::bind_method(D_METHOD("get_drive"),&AudioEffectDistortion::get_drive); + ClassDB::bind_method(D_METHOD("set_keep_hf_hz", "keep_hf_hz"), &AudioEffectDistortion::set_keep_hf_hz); + ClassDB::bind_method(D_METHOD("get_keep_hf_hz"), &AudioEffectDistortion::get_keep_hf_hz); + ClassDB::bind_method(D_METHOD("set_drive", "drive"), &AudioEffectDistortion::set_drive); + ClassDB::bind_method(D_METHOD("get_drive"), &AudioEffectDistortion::get_drive); - ClassDB::bind_method(D_METHOD("set_post_gain","post_gain"),&AudioEffectDistortion::set_post_gain); - ClassDB::bind_method(D_METHOD("get_post_gain"),&AudioEffectDistortion::get_post_gain); + ClassDB::bind_method(D_METHOD("set_post_gain", "post_gain"), &AudioEffectDistortion::set_post_gain); + ClassDB::bind_method(D_METHOD("get_post_gain"), &AudioEffectDistortion::get_post_gain); - ADD_PROPERTY(PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Clip,ATan,LoFi,Overdrive,WaveShape"),"set_mode","get_mode"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"pre_gain",PROPERTY_HINT_RANGE,"-60,60,0.01"),"set_pre_gain","get_pre_gain"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"keep_hf_hz",PROPERTY_HINT_RANGE,"1,20000,1"),"set_keep_hf_hz","get_keep_hf_hz"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"drive",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drive","get_drive"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"post_gain",PROPERTY_HINT_RANGE,"-80,24,0.01"),"set_post_gain","get_post_gain"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Clip,ATan,LoFi,Overdrive,WaveShape"), "set_mode", "get_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pre_gain", PROPERTY_HINT_RANGE, "-60,60,0.01"), "set_pre_gain", "get_pre_gain"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "keep_hf_hz", PROPERTY_HINT_RANGE, "1,20000,1"), "set_keep_hf_hz", "get_keep_hf_hz"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "drive", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drive", "get_drive"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "post_gain", PROPERTY_HINT_RANGE, "-80,24,0.01"), "set_post_gain", "get_post_gain"); } -AudioEffectDistortion::AudioEffectDistortion() -{ - mode=MODE_CLIP; - pre_gain=0; - post_gain=0; - keep_hf_hz=16000; - drive=0; +AudioEffectDistortion::AudioEffectDistortion() { + mode = MODE_CLIP; + pre_gain = 0; + post_gain = 0; + keep_hf_hz = 16000; + drive = 0; } - diff --git a/servers/audio/effects/audio_effect_distortion.h b/servers/audio/effects/audio_effect_distortion.h index c4388f0256..6cd92dea18 100644 --- a/servers/audio/effects/audio_effect_distortion.h +++ b/servers/audio/effects/audio_effect_distortion.h @@ -34,19 +34,17 @@ class AudioEffectDistortion; class AudioEffectDistortionInstance : public AudioEffectInstance { - GDCLASS(AudioEffectDistortionInstance,AudioEffectInstance) -friend class AudioEffectDistortion; + GDCLASS(AudioEffectDistortionInstance, AudioEffectInstance) + friend class AudioEffectDistortion; Ref<AudioEffectDistortion> base; float h[2]; -public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectDistortion : public AudioEffect { - GDCLASS(AudioEffectDistortion,AudioEffect) + GDCLASS(AudioEffectDistortion, AudioEffect) public: enum Mode { MODE_CLIP, @@ -56,7 +54,7 @@ public: MODE_WAVESHAPE, }; -friend class AudioEffectDistortionInstance; + friend class AudioEffectDistortionInstance; Mode mode; float pre_gain; float post_gain; @@ -64,14 +62,11 @@ friend class AudioEffectDistortionInstance; float drive; protected: - static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); - void set_mode(Mode p_mode); Mode get_mode() const; @@ -87,11 +82,9 @@ public: void set_post_gain(float post_gain); float get_post_gain() const; - - AudioEffectDistortion(); }; -VARIANT_ENUM_CAST( AudioEffectDistortion::Mode ) +VARIANT_ENUM_CAST(AudioEffectDistortion::Mode) #endif // AUDIOEFFECTDISTORTION_H diff --git a/servers/audio/effects/audio_effect_eq.cpp b/servers/audio/effects/audio_effect_eq.cpp index 2caec9e49e..a103d34d0f 100644 --- a/servers/audio/effects/audio_effect_eq.cpp +++ b/servers/audio/effects/audio_effect_eq.cpp @@ -29,24 +29,22 @@ #include "audio_effect_eq.h" #include "servers/audio_server.h" - -void AudioEffectEQInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectEQInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { int band_count = bands[0].size(); EQ::BandProcess *proc_l = bands[0].ptr(); EQ::BandProcess *proc_r = bands[1].ptr(); float *bgain = gains.ptr(); - for(int i=0;i<band_count;i++) { - bgain[i]=Math::db2linear(base->gain[i]); + for (int i = 0; i < band_count; i++) { + bgain[i] = Math::db2linear(base->gain[i]); } - - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { AudioFrame src = p_src_frames[i]; - AudioFrame dst = AudioFrame(0,0); + AudioFrame dst = AudioFrame(0, 0); - for(int j=0;j<band_count;j++) { + for (int j = 0; j < band_count; j++) { float l = src.l; float r = src.r; @@ -54,38 +52,36 @@ void AudioEffectEQInstance::process(const AudioFrame *p_src_frames,AudioFrame *p proc_l[j].process_one(l); proc_r[j].process_one(r); - dst.l+=l * bgain[j]; - dst.r+=r * bgain[j]; + dst.l += l * bgain[j]; + dst.r += r * bgain[j]; } - p_dst_frames[i]=dst; + p_dst_frames[i] = dst; } - } - Ref<AudioEffectInstance> AudioEffectEQ::instance() { Ref<AudioEffectEQInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectEQ>(this); + ins->base = Ref<AudioEffectEQ>(this); ins->gains.resize(eq.get_band_count()); - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { ins->bands[i].resize(eq.get_band_count()); - for(int j=0;j<ins->bands[i].size();j++) { - ins->bands[i][j]=eq.get_band_processor(j); + for (int j = 0; j < ins->bands[i].size(); j++) { + ins->bands[i][j] = eq.get_band_processor(j); } } return ins; } -void AudioEffectEQ::set_band_gain_db(int p_band,float p_volume) { - ERR_FAIL_INDEX(p_band,gain.size()); - gain[p_band]=p_volume; +void AudioEffectEQ::set_band_gain_db(int p_band, float p_volume) { + ERR_FAIL_INDEX(p_band, gain.size()); + gain[p_band] = p_volume; } float AudioEffectEQ::get_band_gain_db(int p_band) const { - ERR_FAIL_INDEX_V(p_band,gain.size(),0); + ERR_FAIL_INDEX_V(p_band, gain.size(), 0); return gain[p_band]; } @@ -93,58 +89,52 @@ int AudioEffectEQ::get_band_count() const { return gain.size(); } -bool AudioEffectEQ::_set(const StringName& p_name, const Variant& p_value) { +bool AudioEffectEQ::_set(const StringName &p_name, const Variant &p_value) { - const Map<StringName,int>::Element *E=prop_band_map.find(p_name); + const Map<StringName, int>::Element *E = prop_band_map.find(p_name); if (E) { - set_band_gain_db(E->get(),p_value); + set_band_gain_db(E->get(), p_value); return true; } return false; } -bool AudioEffectEQ::_get(const StringName& p_name,Variant &r_ret) const{ +bool AudioEffectEQ::_get(const StringName &p_name, Variant &r_ret) const { - const Map<StringName,int>::Element *E=prop_band_map.find(p_name); + const Map<StringName, int>::Element *E = prop_band_map.find(p_name); if (E) { - r_ret=get_band_gain_db(E->get()); + r_ret = get_band_gain_db(E->get()); return true; } return false; - } -void AudioEffectEQ::_get_property_list( List<PropertyInfo> *p_list) const{ +void AudioEffectEQ::_get_property_list(List<PropertyInfo> *p_list) const { - for(int i=0;i<band_names.size();i++) { + for (int i = 0; i < band_names.size(); i++) { - p_list->push_back(PropertyInfo(Variant::REAL,band_names[i],PROPERTY_HINT_RANGE,"-60,24,0.1")); + p_list->push_back(PropertyInfo(Variant::REAL, band_names[i], PROPERTY_HINT_RANGE, "-60,24,0.1")); } } - - void AudioEffectEQ::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_band_gain_db","band_idx","volume_db"),&AudioEffectEQ::set_band_gain_db); - ClassDB::bind_method(D_METHOD("get_band_gain_db","band_idx"),&AudioEffectEQ::get_band_gain_db); - ClassDB::bind_method(D_METHOD("get_band_count"),&AudioEffectEQ::get_band_count); - + ClassDB::bind_method(D_METHOD("set_band_gain_db", "band_idx", "volume_db"), &AudioEffectEQ::set_band_gain_db); + ClassDB::bind_method(D_METHOD("get_band_gain_db", "band_idx"), &AudioEffectEQ::get_band_gain_db); + ClassDB::bind_method(D_METHOD("get_band_count"), &AudioEffectEQ::get_band_count); } -AudioEffectEQ::AudioEffectEQ(EQ::Preset p_preset) -{ - +AudioEffectEQ::AudioEffectEQ(EQ::Preset p_preset) { eq.set_mix_rate(AudioServer::get_singleton()->get_mix_rate()); eq.set_preset_band_mode(p_preset); gain.resize(eq.get_band_count()); - for(int i=0;i<gain.size();i++) { - gain[i]=0.0; - String name = "band_db/"+itos(eq.get_band_frequency(i))+"_hz"; - prop_band_map[name]=i; + for (int i = 0; i < gain.size(); i++) { + gain[i] = 0.0; + String name = "band_db/" + itos(eq.get_band_frequency(i)) + "_hz"; + prop_band_map[name] = i; band_names.push_back(name); } } diff --git a/servers/audio/effects/audio_effect_eq.h b/servers/audio/effects/audio_effect_eq.h index 2f577ffd20..917bf584c7 100644 --- a/servers/audio/effects/audio_effect_eq.h +++ b/servers/audio/effects/audio_effect_eq.h @@ -29,72 +29,68 @@ #ifndef AUDIOEFFECTEQ_H #define AUDIOEFFECTEQ_H - #include "servers/audio/audio_effect.h" #include "servers/audio/effects/eq.h" class AudioEffectEQ; class AudioEffectEQInstance : public AudioEffectInstance { - GDCLASS(AudioEffectEQInstance,AudioEffectInstance) -friend class AudioEffectEQ; + GDCLASS(AudioEffectEQInstance, AudioEffectInstance) + friend class AudioEffectEQ; Ref<AudioEffectEQ> base; Vector<EQ::BandProcess> bands[2]; Vector<float> gains; -public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectEQ : public AudioEffect { - GDCLASS(AudioEffectEQ,AudioEffect) + GDCLASS(AudioEffectEQ, AudioEffect) -friend class AudioEffectEQInstance; + friend class AudioEffectEQInstance; EQ eq; Vector<float> gain; - Map<StringName,int> prop_band_map; + Map<StringName, int> prop_band_map; Vector<String> band_names; 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; static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); - void set_band_gain_db(int p_band,float p_volume); + void set_band_gain_db(int p_band, float p_volume); float get_band_gain_db(int p_band) const; int get_band_count() const; - AudioEffectEQ(EQ::Preset p_preset=EQ::PRESET_6_BANDS); + AudioEffectEQ(EQ::Preset p_preset = EQ::PRESET_6_BANDS); }; - class AudioEffectEQ6 : public AudioEffectEQ { - GDCLASS(AudioEffectEQ6,AudioEffectEQ) + GDCLASS(AudioEffectEQ6, AudioEffectEQ) public: - AudioEffectEQ6() : AudioEffectEQ(EQ::PRESET_6_BANDS) {} + AudioEffectEQ6() + : AudioEffectEQ(EQ::PRESET_6_BANDS) {} }; class AudioEffectEQ10 : public AudioEffectEQ { - GDCLASS(AudioEffectEQ10,AudioEffectEQ) + GDCLASS(AudioEffectEQ10, AudioEffectEQ) public: - AudioEffectEQ10() : AudioEffectEQ(EQ::PRESET_10_BANDS) {} + AudioEffectEQ10() + : AudioEffectEQ(EQ::PRESET_10_BANDS) {} }; class AudioEffectEQ21 : public AudioEffectEQ { - GDCLASS(AudioEffectEQ21,AudioEffectEQ) + GDCLASS(AudioEffectEQ21, AudioEffectEQ) public: - AudioEffectEQ21() : AudioEffectEQ(EQ::PRESET_21_BANDS) {} + AudioEffectEQ21() + : AudioEffectEQ(EQ::PRESET_21_BANDS) {} }; #endif // AUDIOEFFECTEQ_H diff --git a/servers/audio/effects/audio_effect_filter.cpp b/servers/audio/effects/audio_effect_filter.cpp index c854842943..4c158ce44e 100644 --- a/servers/audio/effects/audio_effect_filter.cpp +++ b/servers/audio/effects/audio_effect_filter.cpp @@ -29,118 +29,110 @@ #include "audio_effect_filter.h" #include "servers/audio_server.h" -template<int S> -void AudioEffectFilterInstance::_process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +template <int S> +void AudioEffectFilterInstance::_process_filter(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { float f = p_src_frames[i].l; filter_process[0][0].process_one(f); - if (S>1) + if (S > 1) filter_process[0][1].process_one(f); - if (S>2) + if (S > 2) filter_process[0][2].process_one(f); - if (S>3) + if (S > 3) filter_process[0][3].process_one(f); - p_dst_frames[i].l=f; + p_dst_frames[i].l = f; } - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { float f = p_src_frames[i].r; filter_process[1][0].process_one(f); - if (S>1) + if (S > 1) filter_process[1][1].process_one(f); - if (S>2) + if (S > 2) filter_process[1][2].process_one(f); - if (S>3) + if (S > 3) filter_process[1][3].process_one(f); - p_dst_frames[i].r=f; + p_dst_frames[i].r = f; } - } -void AudioEffectFilterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectFilterInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { filter.set_cutoff(base->cutoff); filter.set_gain(base->gain); filter.set_resonance(base->resonance); filter.set_mode(base->mode); - int stages = int(base->db)+1; + int stages = int(base->db) + 1; filter.set_stages(stages); filter.set_sampling_rate(AudioServer::get_singleton()->get_mix_rate()); - for(int i=0;i<2;i++) { - for(int j=0;j<4;j++) { + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 4; j++) { filter_process[i][j].update_coeffs(); } } - - if (stages==1) { - _process_filter<1>(p_src_frames,p_dst_frames,p_frame_count); - } else if (stages==2) { - _process_filter<2>(p_src_frames,p_dst_frames,p_frame_count); - } else if (stages==3) { - _process_filter<3>(p_src_frames,p_dst_frames,p_frame_count); - } else if (stages==4) { - _process_filter<4>(p_src_frames,p_dst_frames,p_frame_count); + if (stages == 1) { + _process_filter<1>(p_src_frames, p_dst_frames, p_frame_count); + } else if (stages == 2) { + _process_filter<2>(p_src_frames, p_dst_frames, p_frame_count); + } else if (stages == 3) { + _process_filter<3>(p_src_frames, p_dst_frames, p_frame_count); + } else if (stages == 4) { + _process_filter<4>(p_src_frames, p_dst_frames, p_frame_count); } - } - AudioEffectFilterInstance::AudioEffectFilterInstance() { - for(int i=0;i<2;i++) { - for(int j=0;j<4;j++) { + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 4; j++) { filter_process[i][j].set_filter(&filter); } } - } - Ref<AudioEffectInstance> AudioEffectFilter::instance() { Ref<AudioEffectFilterInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectFilter>(this); + ins->base = Ref<AudioEffectFilter>(this); return ins; } void AudioEffectFilter::set_cutoff(float p_freq) { - cutoff=p_freq; + cutoff = p_freq; } -float AudioEffectFilter::get_cutoff() const{ +float AudioEffectFilter::get_cutoff() const { return cutoff; } -void AudioEffectFilter::set_resonance(float p_amount){ +void AudioEffectFilter::set_resonance(float p_amount) { - resonance=p_amount; + resonance = p_amount; } -float AudioEffectFilter::get_resonance() const{ +float AudioEffectFilter::get_resonance() const { return resonance; } -void AudioEffectFilter::set_gain(float p_amount){ +void AudioEffectFilter::set_gain(float p_amount) { - gain=p_amount; + gain = p_amount; } float AudioEffectFilter::get_gain() const { return gain; } - - void AudioEffectFilter::set_db(FilterDB p_db) { - db=p_db; + db = p_db; } AudioEffectFilter::FilterDB AudioEffectFilter::get_db() const { @@ -150,30 +142,29 @@ AudioEffectFilter::FilterDB AudioEffectFilter::get_db() const { void AudioEffectFilter::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_cutoff","freq"),&AudioEffectFilter::set_cutoff); - ClassDB::bind_method(D_METHOD("get_cutoff"),&AudioEffectFilter::get_cutoff); + ClassDB::bind_method(D_METHOD("set_cutoff", "freq"), &AudioEffectFilter::set_cutoff); + ClassDB::bind_method(D_METHOD("get_cutoff"), &AudioEffectFilter::get_cutoff); - ClassDB::bind_method(D_METHOD("set_resonance","amount"),&AudioEffectFilter::set_resonance); - ClassDB::bind_method(D_METHOD("get_resonance"),&AudioEffectFilter::get_resonance); + ClassDB::bind_method(D_METHOD("set_resonance", "amount"), &AudioEffectFilter::set_resonance); + ClassDB::bind_method(D_METHOD("get_resonance"), &AudioEffectFilter::get_resonance); - ClassDB::bind_method(D_METHOD("set_gain","amount"),&AudioEffectFilter::set_gain); - ClassDB::bind_method(D_METHOD("get_gain"),&AudioEffectFilter::get_gain); + ClassDB::bind_method(D_METHOD("set_gain", "amount"), &AudioEffectFilter::set_gain); + ClassDB::bind_method(D_METHOD("get_gain"), &AudioEffectFilter::get_gain); - ClassDB::bind_method(D_METHOD("set_db","amount"),&AudioEffectFilter::set_db); - ClassDB::bind_method(D_METHOD("get_db"),&AudioEffectFilter::get_db); + ClassDB::bind_method(D_METHOD("set_db", "amount"), &AudioEffectFilter::set_db); + ClassDB::bind_method(D_METHOD("get_db"), &AudioEffectFilter::get_db); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"cutoff_hz",PROPERTY_HINT_RANGE,"1,40000,0.1"),"set_cutoff","get_cutoff"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"resonance",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_resonance","get_resonance"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"0,4,0.01"),"set_gain","get_gain"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"dB",PROPERTY_HINT_ENUM,"6db,12db,18db,24db"),"set_db","get_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "cutoff_hz", PROPERTY_HINT_RANGE, "1,40000,0.1"), "set_cutoff", "get_cutoff"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "resonance", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_resonance", "get_resonance"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "gain", PROPERTY_HINT_RANGE, "0,4,0.01"), "set_gain", "get_gain"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "dB", PROPERTY_HINT_ENUM, "6db,12db,18db,24db"), "set_db", "get_db"); } -AudioEffectFilter::AudioEffectFilter(AudioFilterSW::Mode p_mode) -{ +AudioEffectFilter::AudioEffectFilter(AudioFilterSW::Mode p_mode) { - mode=p_mode; - cutoff=2000; - resonance=0.5; - gain=1.0; - db=FILTER_6DB; + mode = p_mode; + cutoff = 2000; + resonance = 0.5; + gain = 1.0; + db = FILTER_6DB; } diff --git a/servers/audio/effects/audio_effect_filter.h b/servers/audio/effects/audio_effect_filter.h index 0215f5a141..4973630198 100644 --- a/servers/audio/effects/audio_effect_filter.h +++ b/servers/audio/effects/audio_effect_filter.h @@ -35,33 +35,31 @@ class AudioEffectFilter; class AudioEffectFilterInstance : public AudioEffectInstance { - GDCLASS(AudioEffectFilterInstance,AudioEffectInstance) -friend class AudioEffectFilter; + GDCLASS(AudioEffectFilterInstance, AudioEffectInstance) + friend class AudioEffectFilter; Ref<AudioEffectFilter> base; AudioFilterSW filter; AudioFilterSW::Processor filter_process[2][4]; - template<int S> - void _process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); -public: + template <int S> + void _process_filter(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); AudioEffectFilterInstance(); }; - class AudioEffectFilter : public AudioEffect { - GDCLASS(AudioEffectFilter,AudioEffect) + GDCLASS(AudioEffectFilter, AudioEffect) public: - enum FilterDB { - FILTER_6DB, - FILTER_12DB, - FILTER_18DB, - FILTER_24DB, + FILTER_6DB, + FILTER_12DB, + FILTER_18DB, + FILTER_24DB, }; friend class AudioEffectFilterInstance; @@ -71,13 +69,10 @@ public: float gain; FilterDB db; - protected: - - static void _bind_methods(); -public: +public: void set_cutoff(float p_freq); float get_cutoff() const; @@ -92,62 +87,58 @@ public: Ref<AudioEffectInstance> instance(); - AudioEffectFilter(AudioFilterSW::Mode p_mode=AudioFilterSW::LOWPASS); + AudioEffectFilter(AudioFilterSW::Mode p_mode = AudioFilterSW::LOWPASS); }; VARIANT_ENUM_CAST(AudioEffectFilter::FilterDB) class AudioEffectLowPassFilter : public AudioEffectFilter { - GDCLASS(AudioEffectLowPassFilter,AudioEffectFilter) + GDCLASS(AudioEffectLowPassFilter, AudioEffectFilter) public: - - AudioEffectLowPassFilter() : AudioEffectFilter(AudioFilterSW::LOWPASS) {} + AudioEffectLowPassFilter() + : AudioEffectFilter(AudioFilterSW::LOWPASS) {} }; class AudioEffectHighPassFilter : public AudioEffectFilter { - GDCLASS(AudioEffectHighPassFilter,AudioEffectFilter) + GDCLASS(AudioEffectHighPassFilter, AudioEffectFilter) public: - - AudioEffectHighPassFilter() : AudioEffectFilter(AudioFilterSW::HIGHPASS) {} + AudioEffectHighPassFilter() + : AudioEffectFilter(AudioFilterSW::HIGHPASS) {} }; class AudioEffectBandPassFilter : public AudioEffectFilter { - GDCLASS(AudioEffectBandPassFilter,AudioEffectFilter) + GDCLASS(AudioEffectBandPassFilter, AudioEffectFilter) public: - - AudioEffectBandPassFilter() : AudioEffectFilter(AudioFilterSW::BANDPASS) {} + AudioEffectBandPassFilter() + : AudioEffectFilter(AudioFilterSW::BANDPASS) {} }; class AudioEffectNotchFilter : public AudioEffectFilter { - GDCLASS(AudioEffectNotchFilter,AudioEffectFilter) + GDCLASS(AudioEffectNotchFilter, AudioEffectFilter) public: - - AudioEffectNotchFilter() : AudioEffectFilter(AudioFilterSW::NOTCH) {} + AudioEffectNotchFilter() + : AudioEffectFilter(AudioFilterSW::NOTCH) {} }; class AudioEffectBandLimitFilter : public AudioEffectFilter { - GDCLASS(AudioEffectBandLimitFilter,AudioEffectFilter) + GDCLASS(AudioEffectBandLimitFilter, AudioEffectFilter) public: - - AudioEffectBandLimitFilter() : AudioEffectFilter(AudioFilterSW::BANDLIMIT) {} + AudioEffectBandLimitFilter() + : AudioEffectFilter(AudioFilterSW::BANDLIMIT) {} }; - class AudioEffectLowShelfFilter : public AudioEffectFilter { - GDCLASS(AudioEffectLowShelfFilter,AudioEffectFilter) + GDCLASS(AudioEffectLowShelfFilter, AudioEffectFilter) public: - - AudioEffectLowShelfFilter() : AudioEffectFilter(AudioFilterSW::LOWSHELF) {} + AudioEffectLowShelfFilter() + : AudioEffectFilter(AudioFilterSW::LOWSHELF) {} }; - class AudioEffectHighShelfFilter : public AudioEffectFilter { - GDCLASS(AudioEffectHighShelfFilter,AudioEffectFilter) + GDCLASS(AudioEffectHighShelfFilter, AudioEffectFilter) public: - - AudioEffectHighShelfFilter() : AudioEffectFilter(AudioFilterSW::HIGHSHELF) {} + AudioEffectHighShelfFilter() + : AudioEffectFilter(AudioFilterSW::HIGHSHELF) {} }; - - #endif // AUDIOEFFECTFILTER_H diff --git a/servers/audio/effects/audio_effect_limiter.cpp b/servers/audio/effects/audio_effect_limiter.cpp index a44bb51762..022d2d9aa4 100644 --- a/servers/audio/effects/audio_effect_limiter.cpp +++ b/servers/audio/effects/audio_effect_limiter.cpp @@ -28,7 +28,7 @@ /*************************************************************************/ #include "audio_effect_limiter.h" -void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { float thresh = Math::db2linear(base->treshold); float threshdb = base->treshold; @@ -44,25 +44,23 @@ void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFra float scratio = base->soft_clip_ratio; float scmult = Math::abs((ceildb - sc) / (peakdb - sc)); - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { float spl0 = p_src_frames[i].l; float spl1 = p_src_frames[i].r; spl0 = spl0 * makeup; spl1 = spl1 * makeup; - float sign0 = (spl0 < 0.0 ? -1.0 : 1.0 ); - float sign1 = (spl1 < 0.0 ? -1.0 : 1.0 ); + float sign0 = (spl0 < 0.0 ? -1.0 : 1.0); + float sign1 = (spl1 < 0.0 ? -1.0 : 1.0); float abs0 = Math::abs(spl0); float abs1 = Math::abs(spl1); float overdb0 = Math::linear2db(abs0) - ceildb; float overdb1 = Math::linear2db(abs1) - ceildb; - if (abs0 > scv) - { + if (abs0 > scv) { spl0 = sign0 * (scv + Math::db2linear(overdb0 * scmult)); } - if (abs1 > scv) - { + if (abs1 > scv) { spl1 = sign1 * (scv + Math::db2linear(overdb1 * scmult)); } @@ -72,81 +70,76 @@ void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFra p_dst_frames[i].l = spl0; p_dst_frames[i].r = spl1; } - } - Ref<AudioEffectInstance> AudioEffectLimiter::instance() { Ref<AudioEffectLimiterInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectLimiter>(this); + ins->base = Ref<AudioEffectLimiter>(this); return ins; } - void AudioEffectLimiter::set_treshold_db(float p_treshold) { - treshold=p_treshold; + treshold = p_treshold; } -float AudioEffectLimiter::get_treshold_db() const{ +float AudioEffectLimiter::get_treshold_db() const { return treshold; } -void AudioEffectLimiter::set_ceiling_db(float p_ceiling){ +void AudioEffectLimiter::set_ceiling_db(float p_ceiling) { - ceiling=p_ceiling; + ceiling = p_ceiling; } -float AudioEffectLimiter::get_ceiling_db() const{ +float AudioEffectLimiter::get_ceiling_db() const { return ceiling; } -void AudioEffectLimiter::set_soft_clip_db(float p_soft_clip){ +void AudioEffectLimiter::set_soft_clip_db(float p_soft_clip) { - soft_clip=p_soft_clip; + soft_clip = p_soft_clip; } -float AudioEffectLimiter::get_soft_clip_db() const{ +float AudioEffectLimiter::get_soft_clip_db() const { return soft_clip; } -void AudioEffectLimiter::set_soft_clip_ratio(float p_soft_clip){ +void AudioEffectLimiter::set_soft_clip_ratio(float p_soft_clip) { - soft_clip_ratio=p_soft_clip; + soft_clip_ratio = p_soft_clip; } -float AudioEffectLimiter::get_soft_clip_ratio() const{ +float AudioEffectLimiter::get_soft_clip_ratio() const { return soft_clip; } - void AudioEffectLimiter::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_ceiling_db","ceiling"),&AudioEffectLimiter::set_ceiling_db); - ClassDB::bind_method(D_METHOD("get_ceiling_db"),&AudioEffectLimiter::get_ceiling_db); + ClassDB::bind_method(D_METHOD("set_ceiling_db", "ceiling"), &AudioEffectLimiter::set_ceiling_db); + ClassDB::bind_method(D_METHOD("get_ceiling_db"), &AudioEffectLimiter::get_ceiling_db); - ClassDB::bind_method(D_METHOD("set_treshold_db","treshold"),&AudioEffectLimiter::set_treshold_db); - ClassDB::bind_method(D_METHOD("get_treshold_db"),&AudioEffectLimiter::get_treshold_db); + ClassDB::bind_method(D_METHOD("set_treshold_db", "treshold"), &AudioEffectLimiter::set_treshold_db); + ClassDB::bind_method(D_METHOD("get_treshold_db"), &AudioEffectLimiter::get_treshold_db); - ClassDB::bind_method(D_METHOD("set_soft_clip_db","soft_clip"),&AudioEffectLimiter::set_soft_clip_db); - ClassDB::bind_method(D_METHOD("get_soft_clip_db"),&AudioEffectLimiter::get_soft_clip_db); + ClassDB::bind_method(D_METHOD("set_soft_clip_db", "soft_clip"), &AudioEffectLimiter::set_soft_clip_db); + ClassDB::bind_method(D_METHOD("get_soft_clip_db"), &AudioEffectLimiter::get_soft_clip_db); - ClassDB::bind_method(D_METHOD("set_soft_clip_ratio","soft_clip"),&AudioEffectLimiter::set_soft_clip_ratio); - ClassDB::bind_method(D_METHOD("get_soft_clip_ratio"),&AudioEffectLimiter::get_soft_clip_ratio); + ClassDB::bind_method(D_METHOD("set_soft_clip_ratio", "soft_clip"), &AudioEffectLimiter::set_soft_clip_ratio); + ClassDB::bind_method(D_METHOD("get_soft_clip_ratio"), &AudioEffectLimiter::get_soft_clip_ratio); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ceiling_db",PROPERTY_HINT_RANGE,"-20,-0.1,0.1"),"set_ceiling_db","get_ceiling_db"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"treshold_db",PROPERTY_HINT_RANGE,"-30,0,0.1"),"set_treshold_db","get_treshold_db"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"soft_clip_db",PROPERTY_HINT_RANGE,"0,6,0.1"),"set_soft_clip_db","get_soft_clip_db"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"soft_clip_ratio",PROPERTY_HINT_RANGE,"3,20,0.1"),"set_soft_clip_ratio","get_soft_clip_ratio"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ceiling_db", PROPERTY_HINT_RANGE, "-20,-0.1,0.1"), "set_ceiling_db", "get_ceiling_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "treshold_db", PROPERTY_HINT_RANGE, "-30,0,0.1"), "set_treshold_db", "get_treshold_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "soft_clip_db", PROPERTY_HINT_RANGE, "0,6,0.1"), "set_soft_clip_db", "get_soft_clip_db"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "soft_clip_ratio", PROPERTY_HINT_RANGE, "3,20,0.1"), "set_soft_clip_ratio", "get_soft_clip_ratio"); } -AudioEffectLimiter::AudioEffectLimiter() -{ - treshold=0; - ceiling=-0.1; - soft_clip=2; - soft_clip_ratio=10; +AudioEffectLimiter::AudioEffectLimiter() { + treshold = 0; + ceiling = -0.1; + soft_clip = 2; + soft_clip_ratio = 10; } diff --git a/servers/audio/effects/audio_effect_limiter.h b/servers/audio/effects/audio_effect_limiter.h index 12639498d9..9863a788f5 100644 --- a/servers/audio/effects/audio_effect_limiter.h +++ b/servers/audio/effects/audio_effect_limiter.h @@ -29,39 +29,34 @@ #ifndef AUDIO_EFFECT_LIMITER_H #define AUDIO_EFFECT_LIMITER_H - #include "servers/audio/audio_effect.h" class AudioEffectLimiter; class AudioEffectLimiterInstance : public AudioEffectInstance { - GDCLASS(AudioEffectLimiterInstance,AudioEffectInstance) -friend class AudioEffectLimiter; + GDCLASS(AudioEffectLimiterInstance, AudioEffectInstance) + friend class AudioEffectLimiter; Ref<AudioEffectLimiter> base; float mix_volume_db; -public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectLimiter : public AudioEffect { - GDCLASS(AudioEffectLimiter,AudioEffect) + GDCLASS(AudioEffectLimiter, AudioEffect) -friend class AudioEffectLimiterInstance; + friend class AudioEffectLimiterInstance; float treshold; float ceiling; float soft_clip; float soft_clip_ratio; protected: - static void _bind_methods(); -public: - +public: void set_treshold_db(float p_treshold); float get_treshold_db() const; @@ -74,7 +69,6 @@ public: void set_soft_clip_ratio(float p_soft_clip); float get_soft_clip_ratio() const; - Ref<AudioEffectInstance> instance(); void set_volume_db(float p_volume); float get_volume_db() const; @@ -82,5 +76,4 @@ public: AudioEffectLimiter(); }; - #endif // AUDIO_EFFECT_LIMITER_H diff --git a/servers/audio/effects/audio_effect_panner.cpp b/servers/audio/effects/audio_effect_panner.cpp index 937575a5b5..ec0ccab453 100644 --- a/servers/audio/effects/audio_effect_panner.cpp +++ b/servers/audio/effects/audio_effect_panner.cpp @@ -28,32 +28,27 @@ /*************************************************************************/ #include "audio_effect_panner.h" +void AudioEffectPannerInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { -void AudioEffectPannerInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { + float lvol = CLAMP(1.0 - base->pan, 0, 1); + float rvol = CLAMP(1.0 + base->pan, 0, 1); - - float lvol = CLAMP( 1.0 - base->pan, 0, 1); - float rvol = CLAMP( 1.0 + base->pan, 0, 1); - - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { p_dst_frames[i].l = p_src_frames[i].l * lvol + p_src_frames[i].r * (1.0 - rvol); p_dst_frames[i].r = p_src_frames[i].r * rvol + p_src_frames[i].l * (1.0 - lvol); - } - } - Ref<AudioEffectInstance> AudioEffectPanner::instance() { Ref<AudioEffectPannerInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectPanner>(this); + ins->base = Ref<AudioEffectPanner>(this); return ins; } void AudioEffectPanner::set_pan(float p_cpanume) { - pan=p_cpanume; + pan = p_cpanume; } float AudioEffectPanner::get_pan() const { @@ -63,13 +58,12 @@ float AudioEffectPanner::get_pan() const { void AudioEffectPanner::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_pan","cpanume"),&AudioEffectPanner::set_pan); - ClassDB::bind_method(D_METHOD("get_pan"),&AudioEffectPanner::get_pan); + ClassDB::bind_method(D_METHOD("set_pan", "cpanume"), &AudioEffectPanner::set_pan); + ClassDB::bind_method(D_METHOD("get_pan"), &AudioEffectPanner::get_pan); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_pan","get_pan"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_pan", "get_pan"); } -AudioEffectPanner::AudioEffectPanner() -{ - pan=0; +AudioEffectPanner::AudioEffectPanner() { + pan = 0; } diff --git a/servers/audio/effects/audio_effect_panner.h b/servers/audio/effects/audio_effect_panner.h index 999b5f5649..19bef45f1e 100644 --- a/servers/audio/effects/audio_effect_panner.h +++ b/servers/audio/effects/audio_effect_panner.h @@ -34,29 +34,24 @@ class AudioEffectPanner; class AudioEffectPannerInstance : public AudioEffectInstance { - GDCLASS(AudioEffectPannerInstance,AudioEffectInstance) -friend class AudioEffectPanner; + GDCLASS(AudioEffectPannerInstance, AudioEffectInstance) + friend class AudioEffectPanner; Ref<AudioEffectPanner> base; public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); - + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectPanner : public AudioEffect { - GDCLASS(AudioEffectPanner,AudioEffect) + GDCLASS(AudioEffectPanner, AudioEffect) -friend class AudioEffectPannerInstance; + friend class AudioEffectPannerInstance; float pan; protected: - static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); void set_pan(float p_volume); float get_pan() const; @@ -64,5 +59,4 @@ public: AudioEffectPanner(); }; - #endif // AUDIOEFFECTPANNER_H diff --git a/servers/audio/effects/audio_effect_phaser.cpp b/servers/audio/effects/audio_effect_phaser.cpp index c9576404f1..72549009c8 100644 --- a/servers/audio/effects/audio_effect_phaser.cpp +++ b/servers/audio/effects/audio_effect_phaser.cpp @@ -27,113 +27,107 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_effect_phaser.h" -#include "servers/audio_server.h" #include "math_funcs.h" +#include "servers/audio_server.h" -void AudioEffectPhaserInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectPhaserInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { float sampling_rate = AudioServer::get_singleton()->get_mix_rate(); - float dmin = base->range_min / (sampling_rate/2.0); - float dmax = base->range_max / (sampling_rate/2.0); + float dmin = base->range_min / (sampling_rate / 2.0); + float dmax = base->range_max / (sampling_rate / 2.0); float increment = 2.f * Math_PI * (base->rate / sampling_rate); - for(int i=0;i<p_frame_count;i++) { + for (int i = 0; i < p_frame_count; i++) { phase += increment; - while ( phase >= Math_PI * 2.f ) { + while (phase >= Math_PI * 2.f) { phase -= Math_PI * 2.f; } - float d = dmin + (dmax-dmin) * ((sin( phase ) + 1.f)/2.f); - + float d = dmin + (dmax - dmin) * ((sin(phase) + 1.f) / 2.f); //update filter coeffs - for( int j=0; j<6; j++ ) { - allpass[0][j].delay( d ); - allpass[1][j].delay( d ); + for (int j = 0; j < 6; j++) { + allpass[0][j].delay(d); + allpass[1][j].delay(d); } //calculate output - float y = allpass[0][0].update( - allpass[0][1].update( - allpass[0][2].update( - allpass[0][3].update( - allpass[0][4].update( - allpass[0][5].update( p_src_frames[i].l + h.l * base->feedback )))))); - h.l=y; + float y = allpass[0][0].update( + allpass[0][1].update( + allpass[0][2].update( + allpass[0][3].update( + allpass[0][4].update( + allpass[0][5].update(p_src_frames[i].l + h.l * base->feedback)))))); + h.l = y; p_dst_frames[i].l = p_src_frames[i].l + y * base->depth; - y = allpass[1][0].update( - allpass[1][1].update( - allpass[1][2].update( - allpass[1][3].update( - allpass[1][4].update( - allpass[1][5].update( p_src_frames[i].r + h.r * base->feedback )))))); - h.r=y; + y = allpass[1][0].update( + allpass[1][1].update( + allpass[1][2].update( + allpass[1][3].update( + allpass[1][4].update( + allpass[1][5].update(p_src_frames[i].r + h.r * base->feedback)))))); + h.r = y; p_dst_frames[i].r = p_src_frames[i].r + y * base->depth; - - } - } - Ref<AudioEffectInstance> AudioEffectPhaser::instance() { Ref<AudioEffectPhaserInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectPhaser>(this); - ins->phase=0; - ins->h=AudioFrame(0,0); + ins->base = Ref<AudioEffectPhaser>(this); + ins->phase = 0; + ins->h = AudioFrame(0, 0); return ins; } - void AudioEffectPhaser::set_range_min_hz(float p_hz) { - range_min=p_hz; + range_min = p_hz; } -float AudioEffectPhaser::get_range_min_hz() const{ +float AudioEffectPhaser::get_range_min_hz() const { return range_min; } -void AudioEffectPhaser::set_range_max_hz(float p_hz){ +void AudioEffectPhaser::set_range_max_hz(float p_hz) { - range_max=p_hz; + range_max = p_hz; } -float AudioEffectPhaser::get_range_max_hz() const{ +float AudioEffectPhaser::get_range_max_hz() const { return range_max; } -void AudioEffectPhaser::set_rate_hz(float p_hz){ +void AudioEffectPhaser::set_rate_hz(float p_hz) { - rate=p_hz; + rate = p_hz; } -float AudioEffectPhaser::get_rate_hz() const{ +float AudioEffectPhaser::get_rate_hz() const { return rate; } -void AudioEffectPhaser::set_feedback(float p_fbk){ +void AudioEffectPhaser::set_feedback(float p_fbk) { - feedback=p_fbk; + feedback = p_fbk; } -float AudioEffectPhaser::get_feedback() const{ +float AudioEffectPhaser::get_feedback() const { return feedback; } void AudioEffectPhaser::set_depth(float p_depth) { - depth=p_depth; + depth = p_depth; } float AudioEffectPhaser::get_depth() const { @@ -143,34 +137,32 @@ float AudioEffectPhaser::get_depth() const { void AudioEffectPhaser::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_range_min_hz","hz"),&AudioEffectPhaser::set_range_min_hz); - ClassDB::bind_method(D_METHOD("get_range_min_hz"),&AudioEffectPhaser::get_range_min_hz); - - ClassDB::bind_method(D_METHOD("set_range_max_hz","hz"),&AudioEffectPhaser::set_range_max_hz); - ClassDB::bind_method(D_METHOD("get_range_max_hz"),&AudioEffectPhaser::get_range_max_hz); + ClassDB::bind_method(D_METHOD("set_range_min_hz", "hz"), &AudioEffectPhaser::set_range_min_hz); + ClassDB::bind_method(D_METHOD("get_range_min_hz"), &AudioEffectPhaser::get_range_min_hz); - ClassDB::bind_method(D_METHOD("set_rate_hz","hz"),&AudioEffectPhaser::set_rate_hz); - ClassDB::bind_method(D_METHOD("get_rate_hz"),&AudioEffectPhaser::get_rate_hz); + ClassDB::bind_method(D_METHOD("set_range_max_hz", "hz"), &AudioEffectPhaser::set_range_max_hz); + ClassDB::bind_method(D_METHOD("get_range_max_hz"), &AudioEffectPhaser::get_range_max_hz); - ClassDB::bind_method(D_METHOD("set_feedback","fbk"),&AudioEffectPhaser::set_feedback); - ClassDB::bind_method(D_METHOD("get_feedback"),&AudioEffectPhaser::get_feedback); + ClassDB::bind_method(D_METHOD("set_rate_hz", "hz"), &AudioEffectPhaser::set_rate_hz); + ClassDB::bind_method(D_METHOD("get_rate_hz"), &AudioEffectPhaser::get_rate_hz); - ClassDB::bind_method(D_METHOD("set_depth","depth"),&AudioEffectPhaser::set_depth); - ClassDB::bind_method(D_METHOD("get_depth"),&AudioEffectPhaser::get_depth); + ClassDB::bind_method(D_METHOD("set_feedback", "fbk"), &AudioEffectPhaser::set_feedback); + ClassDB::bind_method(D_METHOD("get_feedback"), &AudioEffectPhaser::get_feedback); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"range_min_hz",PROPERTY_HINT_RANGE,"10,10000"),"set_range_min_hz","get_range_min_hz"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"range_max_hz",PROPERTY_HINT_RANGE,"10,10000"),"set_range_max_hz","get_range_max_hz"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"rate_hz",PROPERTY_HINT_RANGE,"0.01,20"),"set_rate_hz","get_rate_hz"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback",PROPERTY_HINT_RANGE,"0.1,0.9,0.1"),"set_feedback","get_feedback"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"depth",PROPERTY_HINT_RANGE,"0.1,4,0.1"),"set_depth","get_depth"); + ClassDB::bind_method(D_METHOD("set_depth", "depth"), &AudioEffectPhaser::set_depth); + ClassDB::bind_method(D_METHOD("get_depth"), &AudioEffectPhaser::get_depth); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "range_min_hz", PROPERTY_HINT_RANGE, "10,10000"), "set_range_min_hz", "get_range_min_hz"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "range_max_hz", PROPERTY_HINT_RANGE, "10,10000"), "set_range_max_hz", "get_range_max_hz"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "rate_hz", PROPERTY_HINT_RANGE, "0.01,20"), "set_rate_hz", "get_rate_hz"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback", PROPERTY_HINT_RANGE, "0.1,0.9,0.1"), "set_feedback", "get_feedback"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "depth", PROPERTY_HINT_RANGE, "0.1,4,0.1"), "set_depth", "get_depth"); } -AudioEffectPhaser::AudioEffectPhaser() -{ - range_min=440; - range_max=1600; - rate=0.5; - feedback=0.7; - depth=1; +AudioEffectPhaser::AudioEffectPhaser() { + range_min = 440; + range_max = 1600; + rate = 0.5; + feedback = 0.7; + depth = 1; } diff --git a/servers/audio/effects/audio_effect_phaser.h b/servers/audio/effects/audio_effect_phaser.h index a7294183f6..70b3a3a4c4 100644 --- a/servers/audio/effects/audio_effect_phaser.h +++ b/servers/audio/effects/audio_effect_phaser.h @@ -29,50 +29,48 @@ #ifndef AUDIO_EFFECT_PHASER_H #define AUDIO_EFFECT_PHASER_H - - #include "servers/audio/audio_effect.h" class AudioEffectPhaser; class AudioEffectPhaserInstance : public AudioEffectInstance { - GDCLASS(AudioEffectPhaserInstance,AudioEffectInstance) -friend class AudioEffectPhaser; + GDCLASS(AudioEffectPhaserInstance, AudioEffectInstance) + friend class AudioEffectPhaser; Ref<AudioEffectPhaser> base; float phase; AudioFrame h; - class AllpassDelay{ + class AllpassDelay { float a, h; - public: - _ALWAYS_INLINE_ void delay( float d ) { + public: + _ALWAYS_INLINE_ void delay(float d) { a = (1.f - d) / (1.f + d); } - _ALWAYS_INLINE_ float update( float s ){ + _ALWAYS_INLINE_ float update(float s) { float y = s * -a + h; h = y * a + s; return y; } - AllpassDelay() { a =0; h = 0;} - + AllpassDelay() { + a = 0; + h = 0; + } }; AllpassDelay allpass[2][6]; -public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); +public: + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectPhaser : public AudioEffect { - GDCLASS(AudioEffectPhaser,AudioEffect) + GDCLASS(AudioEffectPhaser, AudioEffect) -friend class AudioEffectPhaserInstance; + friend class AudioEffectPhaserInstance; float range_min; float range_max; float rate; @@ -80,11 +78,9 @@ friend class AudioEffectPhaserInstance; float depth; protected: - static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); void set_range_min_hz(float p_hz); @@ -105,5 +101,4 @@ public: AudioEffectPhaser(); }; - #endif // AUDIO_EFFECT_PHASER_H diff --git a/servers/audio/effects/audio_effect_pitch_shift.cpp b/servers/audio/effects/audio_effect_pitch_shift.cpp index e00755e1a0..6a14ba7155 100644 --- a/servers/audio/effects/audio_effect_pitch_shift.cpp +++ b/servers/audio/effects/audio_effect_pitch_shift.cpp @@ -28,8 +28,8 @@ /*************************************************************************/ #include "audio_effect_pitch_shift.h" -#include "servers/audio_server.h" #include "math_funcs.h" +#include "servers/audio_server.h" /* Thirdparty code, so disable clang-format with Godot style */ /* clang-format off */ @@ -281,34 +281,31 @@ void SMBPitchShift::smbFft(float *fftBuffer, long fftFrameSize, long sign) /* Godot code again */ /* clang-format on */ -void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { float sample_rate = AudioServer::get_singleton()->get_mix_rate(); - float *in_l = (float*)p_src_frames; + float *in_l = (float *)p_src_frames; float *in_r = in_l + 1; - float *out_l = (float*)p_dst_frames; + float *out_l = (float *)p_dst_frames; float *out_r = out_l + 1; - shift_l.PitchShift(base->pitch_scale,p_frame_count,2048,4,sample_rate,in_l,out_l,2); - shift_r.PitchShift(base->pitch_scale,p_frame_count,2048,4,sample_rate,in_r,out_r,2); - + shift_l.PitchShift(base->pitch_scale, p_frame_count, 2048, 4, sample_rate, in_l, out_l, 2); + shift_r.PitchShift(base->pitch_scale, p_frame_count, 2048, 4, sample_rate, in_r, out_r, 2); } - Ref<AudioEffectInstance> AudioEffectPitchShift::instance() { Ref<AudioEffectPitchShiftInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectPitchShift>(this); - + ins->base = Ref<AudioEffectPitchShift>(this); return ins; } void AudioEffectPitchShift::set_pitch_scale(float p_adjust) { - pitch_scale=p_adjust; + pitch_scale = p_adjust; } float AudioEffectPitchShift::get_pitch_scale() const { @@ -316,17 +313,14 @@ float AudioEffectPitchShift::get_pitch_scale() const { return pitch_scale; } - void AudioEffectPitchShift::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_pitch_scale","rate"),&AudioEffectPitchShift::set_pitch_scale); - ClassDB::bind_method(D_METHOD("get_pitch_scale"),&AudioEffectPitchShift::get_pitch_scale); - - ADD_PROPERTY(PropertyInfo(Variant::REAL,"pitch_scale",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_pitch_scale","get_pitch_scale"); + ClassDB::bind_method(D_METHOD("set_pitch_scale", "rate"), &AudioEffectPitchShift::set_pitch_scale); + ClassDB::bind_method(D_METHOD("get_pitch_scale"), &AudioEffectPitchShift::get_pitch_scale); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_pitch_scale", "get_pitch_scale"); } AudioEffectPitchShift::AudioEffectPitchShift() { - pitch_scale=1.0; - + pitch_scale = 1.0; } diff --git a/servers/audio/effects/audio_effect_pitch_shift.h b/servers/audio/effects/audio_effect_pitch_shift.h index 1320976f5f..610efdc0e1 100644 --- a/servers/audio/effects/audio_effect_pitch_shift.h +++ b/servers/audio/effects/audio_effect_pitch_shift.h @@ -29,21 +29,20 @@ #ifndef AUDIO_EFFECT_PITCH_SHIFT_H #define AUDIO_EFFECT_PITCH_SHIFT_H - #include "servers/audio/audio_effect.h" class SMBPitchShift { enum { - MAX_FRAME_LENGTH=8192 + MAX_FRAME_LENGTH = 8192 }; float gInFIFO[MAX_FRAME_LENGTH]; float gOutFIFO[MAX_FRAME_LENGTH]; - float gFFTworksp[2*MAX_FRAME_LENGTH]; - float gLastPhase[MAX_FRAME_LENGTH/2+1]; - float gSumPhase[MAX_FRAME_LENGTH/2+1]; - float gOutputAccum[2*MAX_FRAME_LENGTH]; + float gFFTworksp[2 * MAX_FRAME_LENGTH]; + float gLastPhase[MAX_FRAME_LENGTH / 2 + 1]; + float gSumPhase[MAX_FRAME_LENGTH / 2 + 1]; + float gOutputAccum[2 * MAX_FRAME_LENGTH]; float gAnaFreq[MAX_FRAME_LENGTH]; float gAnaMagn[MAX_FRAME_LENGTH]; float gSynFreq[MAX_FRAME_LENGTH]; @@ -51,47 +50,41 @@ class SMBPitchShift { long gRover; void smbFft(float *fftBuffer, long fftFrameSize, long sign); + public: void PitchShift(float pitchShift, long numSampsToProcess, long fftFrameSize, long osamp, float sampleRate, float *indata, float *outdata, int stride); SMBPitchShift() { - gRover=0; - memset(gInFIFO, 0, MAX_FRAME_LENGTH*sizeof(float)); - memset(gOutFIFO, 0, MAX_FRAME_LENGTH*sizeof(float)); - memset(gFFTworksp, 0, 2*MAX_FRAME_LENGTH*sizeof(float)); - memset(gLastPhase, 0, (MAX_FRAME_LENGTH/2+1)*sizeof(float)); - memset(gSumPhase, 0, (MAX_FRAME_LENGTH/2+1)*sizeof(float)); - memset(gOutputAccum, 0, 2*MAX_FRAME_LENGTH*sizeof(float)); - memset(gAnaFreq, 0, MAX_FRAME_LENGTH*sizeof(float)); - memset(gAnaMagn, 0, MAX_FRAME_LENGTH*sizeof(float)); + gRover = 0; + memset(gInFIFO, 0, MAX_FRAME_LENGTH * sizeof(float)); + memset(gOutFIFO, 0, MAX_FRAME_LENGTH * sizeof(float)); + memset(gFFTworksp, 0, 2 * MAX_FRAME_LENGTH * sizeof(float)); + memset(gLastPhase, 0, (MAX_FRAME_LENGTH / 2 + 1) * sizeof(float)); + memset(gSumPhase, 0, (MAX_FRAME_LENGTH / 2 + 1) * sizeof(float)); + memset(gOutputAccum, 0, 2 * MAX_FRAME_LENGTH * sizeof(float)); + memset(gAnaFreq, 0, MAX_FRAME_LENGTH * sizeof(float)); + memset(gAnaMagn, 0, MAX_FRAME_LENGTH * sizeof(float)); } - - }; - class AudioEffectPitchShift; class AudioEffectPitchShiftInstance : public AudioEffectInstance { - GDCLASS(AudioEffectPitchShiftInstance,AudioEffectInstance) -friend class AudioEffectPitchShift; + GDCLASS(AudioEffectPitchShiftInstance, AudioEffectInstance) + friend class AudioEffectPitchShift; Ref<AudioEffectPitchShift> base; SMBPitchShift shift_l; SMBPitchShift shift_r; - public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); - + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); }; - class AudioEffectPitchShift : public AudioEffect { - GDCLASS(AudioEffectPitchShift,AudioEffect) + GDCLASS(AudioEffectPitchShift, AudioEffect) -friend class AudioEffectPitchShiftInstance; + friend class AudioEffectPitchShiftInstance; float pitch_scale; int window_size; @@ -100,11 +93,9 @@ friend class AudioEffectPitchShiftInstance; bool filter; protected: - static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); void set_pitch_scale(float p_adjust); @@ -113,5 +104,4 @@ public: AudioEffectPitchShift(); }; - #endif // AUDIO_EFFECT_PITCH_SHIFT_H diff --git a/servers/audio/effects/audio_effect_reverb.cpp b/servers/audio/effects/audio_effect_reverb.cpp index d668c63e8e..f01bd266b8 100644 --- a/servers/audio/effects/audio_effect_reverb.cpp +++ b/servers/audio/effects/audio_effect_reverb.cpp @@ -28,99 +28,98 @@ /*************************************************************************/ #include "audio_effect_reverb.h" #include "servers/audio_server.h" -void AudioEffectReverbInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { - - for(int i=0;i<2;i++) { - Reverb &r=reverb[i]; - - r.set_predelay( base->predelay); - r.set_predelay_feedback( base->predelay_fb ); - r.set_highpass( base->hpf ); - r.set_room_size( base->room_size ); - r.set_damp( base->damping ); - r.set_extra_spread( base->spread ); - r.set_wet( base->wet ); - r.set_dry( base->dry ); +void AudioEffectReverbInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { + + for (int i = 0; i < 2; i++) { + Reverb &r = reverb[i]; + + r.set_predelay(base->predelay); + r.set_predelay_feedback(base->predelay_fb); + r.set_highpass(base->hpf); + r.set_room_size(base->room_size); + r.set_damp(base->damping); + r.set_extra_spread(base->spread); + r.set_wet(base->wet); + r.set_dry(base->dry); } int todo = p_frame_count; - int offset=0; + int offset = 0; - while(todo) { + while (todo) { - int to_mix = MIN(todo,Reverb::INPUT_BUFFER_MAX_SIZE); + int to_mix = MIN(todo, Reverb::INPUT_BUFFER_MAX_SIZE); - for(int j=0;j<to_mix;j++) { - tmp_src[j]=p_src_frames[offset+j].l; + for (int j = 0; j < to_mix; j++) { + tmp_src[j] = p_src_frames[offset + j].l; } - reverb[0].process(tmp_src,tmp_dst,to_mix); + reverb[0].process(tmp_src, tmp_dst, to_mix); - for(int j=0;j<to_mix;j++) { - p_dst_frames[offset+j].l=tmp_dst[j]; - tmp_src[j]=p_src_frames[offset+j].r; + for (int j = 0; j < to_mix; j++) { + p_dst_frames[offset + j].l = tmp_dst[j]; + tmp_src[j] = p_src_frames[offset + j].r; } - reverb[1].process(tmp_src,tmp_dst,to_mix); + reverb[1].process(tmp_src, tmp_dst, to_mix); - for(int j=0;j<to_mix;j++) { - p_dst_frames[offset+j].r=tmp_dst[j]; + for (int j = 0; j < to_mix; j++) { + p_dst_frames[offset + j].r = tmp_dst[j]; } - offset+=to_mix; - todo-=to_mix; + offset += to_mix; + todo -= to_mix; } } AudioEffectReverbInstance::AudioEffectReverbInstance() { - reverb[0].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() ); + reverb[0].set_mix_rate(AudioServer::get_singleton()->get_mix_rate()); reverb[0].set_extra_spread_base(0); - reverb[1].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() ); + reverb[1].set_mix_rate(AudioServer::get_singleton()->get_mix_rate()); reverb[1].set_extra_spread_base(0.000521); //for stereo effect - } Ref<AudioEffectInstance> AudioEffectReverb::instance() { Ref<AudioEffectReverbInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectReverb>(this); + ins->base = Ref<AudioEffectReverb>(this); return ins; } void AudioEffectReverb::set_predelay_msec(float p_msec) { - predelay=p_msec; + predelay = p_msec; } -void AudioEffectReverb::set_predelay_feedback(float p_feedback){ +void AudioEffectReverb::set_predelay_feedback(float p_feedback) { - predelay_fb=p_feedback; + predelay_fb = p_feedback; } -void AudioEffectReverb::set_room_size(float p_size){ +void AudioEffectReverb::set_room_size(float p_size) { - room_size=p_size; + room_size = p_size; } -void AudioEffectReverb::set_damping(float p_damping){ +void AudioEffectReverb::set_damping(float p_damping) { - damping=p_damping; + damping = p_damping; } -void AudioEffectReverb::set_spread(float p_spread){ +void AudioEffectReverb::set_spread(float p_spread) { - spread=p_spread; + spread = p_spread; } -void AudioEffectReverb::set_dry(float p_dry){ +void AudioEffectReverb::set_dry(float p_dry) { - dry=p_dry; + dry = p_dry; } -void AudioEffectReverb::set_wet(float p_wet){ +void AudioEffectReverb::set_wet(float p_wet) { - wet=p_wet; + wet = p_wet; } void AudioEffectReverb::set_hpf(float p_hpf) { - hpf=p_hpf; + hpf = p_hpf; } float AudioEffectReverb::get_predelay_msec() const { @@ -156,55 +155,51 @@ float AudioEffectReverb::get_hpf() const { return hpf; } - void AudioEffectReverb::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_predelay_msec", "msec"), &AudioEffectReverb::set_predelay_msec); + ClassDB::bind_method(D_METHOD("get_predelay_msec"), &AudioEffectReverb::get_predelay_msec); - ClassDB::bind_method(D_METHOD("set_predelay_msec","msec"),&AudioEffectReverb::set_predelay_msec); - ClassDB::bind_method(D_METHOD("get_predelay_msec"),&AudioEffectReverb::get_predelay_msec); - - ClassDB::bind_method(D_METHOD("set_predelay_feedback","feedback"),&AudioEffectReverb::set_predelay_feedback); - ClassDB::bind_method(D_METHOD("get_predelay_feedback"),&AudioEffectReverb::get_predelay_feedback); + ClassDB::bind_method(D_METHOD("set_predelay_feedback", "feedback"), &AudioEffectReverb::set_predelay_feedback); + ClassDB::bind_method(D_METHOD("get_predelay_feedback"), &AudioEffectReverb::get_predelay_feedback); - ClassDB::bind_method(D_METHOD("set_room_size","size"),&AudioEffectReverb::set_room_size); - ClassDB::bind_method(D_METHOD("get_room_size"),&AudioEffectReverb::get_room_size); + ClassDB::bind_method(D_METHOD("set_room_size", "size"), &AudioEffectReverb::set_room_size); + ClassDB::bind_method(D_METHOD("get_room_size"), &AudioEffectReverb::get_room_size); - ClassDB::bind_method(D_METHOD("set_damping","amount"),&AudioEffectReverb::set_damping); - ClassDB::bind_method(D_METHOD("get_damping"),&AudioEffectReverb::get_damping); + ClassDB::bind_method(D_METHOD("set_damping", "amount"), &AudioEffectReverb::set_damping); + ClassDB::bind_method(D_METHOD("get_damping"), &AudioEffectReverb::get_damping); - ClassDB::bind_method(D_METHOD("set_spread","amount"),&AudioEffectReverb::set_spread); - ClassDB::bind_method(D_METHOD("get_spread"),&AudioEffectReverb::get_spread); + ClassDB::bind_method(D_METHOD("set_spread", "amount"), &AudioEffectReverb::set_spread); + ClassDB::bind_method(D_METHOD("get_spread"), &AudioEffectReverb::get_spread); - ClassDB::bind_method(D_METHOD("set_dry","amount"),&AudioEffectReverb::set_dry); - ClassDB::bind_method(D_METHOD("get_dry"),&AudioEffectReverb::get_dry); + ClassDB::bind_method(D_METHOD("set_dry", "amount"), &AudioEffectReverb::set_dry); + ClassDB::bind_method(D_METHOD("get_dry"), &AudioEffectReverb::get_dry); - ClassDB::bind_method(D_METHOD("set_wet","amount"),&AudioEffectReverb::set_wet); - ClassDB::bind_method(D_METHOD("get_wet"),&AudioEffectReverb::get_wet); + ClassDB::bind_method(D_METHOD("set_wet", "amount"), &AudioEffectReverb::set_wet); + ClassDB::bind_method(D_METHOD("get_wet"), &AudioEffectReverb::get_wet); - ClassDB::bind_method(D_METHOD("set_hpf","amount"),&AudioEffectReverb::set_hpf); - ClassDB::bind_method(D_METHOD("get_hpf"),&AudioEffectReverb::get_hpf); + ClassDB::bind_method(D_METHOD("set_hpf", "amount"), &AudioEffectReverb::set_hpf); + ClassDB::bind_method(D_METHOD("get_hpf"), &AudioEffectReverb::get_hpf); - - ADD_GROUP("Predelay","predelay_"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_msec",PROPERTY_HINT_RANGE,"20,500,1"),"set_predelay_msec","get_predelay_msec"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_feedback",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_predelay_msec","get_predelay_msec"); - ADD_GROUP("",""); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"room_size",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_room_size","get_room_size"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_damping","get_damping"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"spread",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_spread","get_spread"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"hipass",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_hpf","get_hpf"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dry","get_dry"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_wet","get_wet"); + ADD_GROUP("Predelay", "predelay_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "predelay_msec", PROPERTY_HINT_RANGE, "20,500,1"), "set_predelay_msec", "get_predelay_msec"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "predelay_feedback", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_predelay_msec", "get_predelay_msec"); + ADD_GROUP("", ""); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "room_size", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_room_size", "get_room_size"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_damping", "get_damping"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "spread", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_spread", "get_spread"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "hipass", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_hpf", "get_hpf"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "wet", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_wet", "get_wet"); } AudioEffectReverb::AudioEffectReverb() { - predelay=150; - predelay_fb=0.4; - hpf=0; - room_size=0.8; - damping=0.5; - spread=1.0; - dry=1.0; - wet=0.5; - + predelay = 150; + predelay_fb = 0.4; + hpf = 0; + room_size = 0.8; + damping = 0.5; + spread = 1.0; + dry = 1.0; + wet = 0.5; } diff --git a/servers/audio/effects/audio_effect_reverb.h b/servers/audio/effects/audio_effect_reverb.h index 41b4f15cf0..2c665ca916 100644 --- a/servers/audio/effects/audio_effect_reverb.h +++ b/servers/audio/effects/audio_effect_reverb.h @@ -29,36 +29,32 @@ #ifndef AUDIOEFFECTREVERB_H #define AUDIOEFFECTREVERB_H - #include "servers/audio/audio_effect.h" #include "servers/audio/effects/reverb.h" class AudioEffectReverb; class AudioEffectReverbInstance : public AudioEffectInstance { - GDCLASS(AudioEffectReverbInstance,AudioEffectInstance) + GDCLASS(AudioEffectReverbInstance, AudioEffectInstance) Ref<AudioEffectReverb> base; float tmp_src[Reverb::INPUT_BUFFER_MAX_SIZE]; float tmp_dst[Reverb::INPUT_BUFFER_MAX_SIZE]; -friend class AudioEffectReverb; + friend class AudioEffectReverb; Reverb reverb[2]; - public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); AudioEffectReverbInstance(); }; - class AudioEffectReverb : public AudioEffect { - GDCLASS(AudioEffectReverb,AudioEffect) + GDCLASS(AudioEffectReverb, AudioEffect) -friend class AudioEffectReverbInstance; + friend class AudioEffectReverbInstance; float predelay; float predelay_fb; @@ -70,11 +66,9 @@ friend class AudioEffectReverbInstance; float wet; protected: - static void _bind_methods(); -public: - +public: void set_predelay_msec(float p_msec); void set_predelay_feedback(float p_feedback); void set_room_size(float p_size); @@ -100,5 +94,4 @@ public: AudioEffectReverb(); }; - #endif // AUDIOEFFECTREVERB_H diff --git a/servers/audio/effects/audio_effect_stereo_enhance.cpp b/servers/audio/effects/audio_effect_stereo_enhance.cpp index 388c38ed17..9aed528bd3 100644 --- a/servers/audio/effects/audio_effect_stereo_enhance.cpp +++ b/servers/audio/effects/audio_effect_stereo_enhance.cpp @@ -28,55 +28,50 @@ /*************************************************************************/ #include "audio_effect_stereo_enhance.h" #include "servers/audio_server.h" -void AudioEffectStereoEnhanceInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { +void AudioEffectStereoEnhanceInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) { + float intensity = base->pan_pullout; + bool surround_mode = base->surround > 0; + float surround_amount = base->surround; + unsigned int delay_frames = (base->time_pullout / 1000.0) * AudioServer::get_singleton()->get_mix_rate(); - float intensity=base->pan_pullout; - bool surround_mode=base->surround>0; - float surround_amount=base->surround; - unsigned int delay_frames=(base->time_pullout/1000.0)*AudioServer::get_singleton()->get_mix_rate(); + for (int i = 0; i < p_frame_count; i++) { - for (int i=0;i<p_frame_count;i++) { + float l = p_src_frames[i].l; + float r = p_src_frames[i].r; - float l=p_src_frames[i].l; - float r=p_src_frames[i].r; + float center = (l + r) / 2.0f; - float center=(l+r)/2.0f; - - l=( center+(l-center)*intensity ); - r=( center+(r-center)*intensity ); + l = (center + (l - center) * intensity); + r = (center + (r - center) * intensity); if (surround_mode) { - float val=(l+r)/2.0; + float val = (l + r) / 2.0; - delay_ringbuff[ringbuff_pos&ringbuff_mask]=val; + delay_ringbuff[ringbuff_pos & ringbuff_mask] = val; - float out=delay_ringbuff[(ringbuff_pos-delay_frames)&ringbuff_mask]*surround_amount; + float out = delay_ringbuff[(ringbuff_pos - delay_frames) & ringbuff_mask] * surround_amount; - l+=out; - r+=-out; + l += out; + r += -out; } else { - float val=r; + float val = r; - delay_ringbuff[ringbuff_pos&ringbuff_mask]=val; + delay_ringbuff[ringbuff_pos & ringbuff_mask] = val; //r is delayed - r=delay_ringbuff[(ringbuff_pos-delay_frames)&ringbuff_mask];; - - + r = delay_ringbuff[(ringbuff_pos - delay_frames) & ringbuff_mask]; + ; } - p_dst_frames[i].l=l; - p_dst_frames[i].r=r; + p_dst_frames[i].l = l; + p_dst_frames[i].r = r; ringbuff_pos++; - } - } - AudioEffectStereoEnhanceInstance::~AudioEffectStereoEnhanceInstance() { memdelete_arr(delay_ringbuff); @@ -86,78 +81,76 @@ Ref<AudioEffectInstance> AudioEffectStereoEnhance::instance() { Ref<AudioEffectStereoEnhanceInstance> ins; ins.instance(); - ins->base=Ref<AudioEffectStereoEnhance>(this); - + ins->base = Ref<AudioEffectStereoEnhance>(this); - float ring_buffer_max_size=AudioEffectStereoEnhanceInstance::MAX_DELAY_MS+2; - ring_buffer_max_size/=1000.0;//convert to seconds - ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate(); + float ring_buffer_max_size = AudioEffectStereoEnhanceInstance::MAX_DELAY_MS + 2; + ring_buffer_max_size /= 1000.0; //convert to seconds + ring_buffer_max_size *= AudioServer::get_singleton()->get_mix_rate(); - int ringbuff_size=(int)ring_buffer_max_size; + int ringbuff_size = (int)ring_buffer_max_size; - int bits=0; + int bits = 0; - while(ringbuff_size>0) { + while (ringbuff_size > 0) { bits++; - ringbuff_size/=2; + ringbuff_size /= 2; } - ringbuff_size=1<<bits; - ins->ringbuff_mask=ringbuff_size-1; - ins->ringbuff_pos=0; + ringbuff_size = 1 << bits; + ins->ringbuff_mask = ringbuff_size - 1; + ins->ringbuff_pos = 0; - ins->delay_ringbuff = memnew_arr(float,ringbuff_size ); + ins->delay_ringbuff = memnew_arr(float, ringbuff_size); return ins; } -void AudioEffectStereoEnhance::set_pan_pullout(float p_amount) { +void AudioEffectStereoEnhance::set_pan_pullout(float p_amount) { - pan_pullout=p_amount; + pan_pullout = p_amount; } -float AudioEffectStereoEnhance::get_pan_pullout() const { +float AudioEffectStereoEnhance::get_pan_pullout() const { return pan_pullout; } -void AudioEffectStereoEnhance::set_time_pullout(float p_amount) { +void AudioEffectStereoEnhance::set_time_pullout(float p_amount) { - time_pullout=p_amount; + time_pullout = p_amount; } -float AudioEffectStereoEnhance::get_time_pullout() const { +float AudioEffectStereoEnhance::get_time_pullout() const { return time_pullout; } -void AudioEffectStereoEnhance::set_surround(float p_amount) { +void AudioEffectStereoEnhance::set_surround(float p_amount) { - surround=p_amount; + surround = p_amount; } -float AudioEffectStereoEnhance::get_surround() const { +float AudioEffectStereoEnhance::get_surround() const { return surround; } void AudioEffectStereoEnhance::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_pan_pullout","amount"),&AudioEffectStereoEnhance::set_pan_pullout); - ClassDB::bind_method(D_METHOD("get_pan_pullout"),&AudioEffectStereoEnhance::get_pan_pullout); + ClassDB::bind_method(D_METHOD("set_pan_pullout", "amount"), &AudioEffectStereoEnhance::set_pan_pullout); + ClassDB::bind_method(D_METHOD("get_pan_pullout"), &AudioEffectStereoEnhance::get_pan_pullout); - ClassDB::bind_method(D_METHOD("set_time_pullout","amount"),&AudioEffectStereoEnhance::set_time_pullout); - ClassDB::bind_method(D_METHOD("get_time_pullout"),&AudioEffectStereoEnhance::get_time_pullout); + ClassDB::bind_method(D_METHOD("set_time_pullout", "amount"), &AudioEffectStereoEnhance::set_time_pullout); + ClassDB::bind_method(D_METHOD("get_time_pullout"), &AudioEffectStereoEnhance::get_time_pullout); - ClassDB::bind_method(D_METHOD("set_surround","amount"),&AudioEffectStereoEnhance::set_surround); - ClassDB::bind_method(D_METHOD("get_surround"),&AudioEffectStereoEnhance::get_surround); + ClassDB::bind_method(D_METHOD("set_surround", "amount"), &AudioEffectStereoEnhance::set_surround); + ClassDB::bind_method(D_METHOD("get_surround"), &AudioEffectStereoEnhance::get_surround); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"pan_pullout",PROPERTY_HINT_RANGE,"0,4,0.01"),"set_pan_pullout","get_pan_pullout"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"time_pullout_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_time_pullout","get_time_pullout"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"surround",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_surround","get_surround"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pan_pullout", PROPERTY_HINT_RANGE, "0,4,0.01"), "set_pan_pullout", "get_pan_pullout"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "time_pullout_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_time_pullout", "get_time_pullout"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "surround", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_surround", "get_surround"); } -AudioEffectStereoEnhance::AudioEffectStereoEnhance() -{ - pan_pullout=1; - time_pullout=0; - surround=0; +AudioEffectStereoEnhance::AudioEffectStereoEnhance() { + pan_pullout = 1; + time_pullout = 0; + surround = 0; } diff --git a/servers/audio/effects/audio_effect_stereo_enhance.h b/servers/audio/effects/audio_effect_stereo_enhance.h index 5eef8a33b2..21331692e9 100644 --- a/servers/audio/effects/audio_effect_stereo_enhance.h +++ b/servers/audio/effects/audio_effect_stereo_enhance.h @@ -29,38 +29,34 @@ #ifndef AUDIOEFFECTSTEREOENHANCE_H #define AUDIOEFFECTSTEREOENHANCE_H - #include "servers/audio/audio_effect.h" class AudioEffectStereoEnhance; class AudioEffectStereoEnhanceInstance : public AudioEffectInstance { - GDCLASS(AudioEffectStereoEnhanceInstance,AudioEffectInstance) -friend class AudioEffectStereoEnhance; + GDCLASS(AudioEffectStereoEnhanceInstance, AudioEffectInstance) + friend class AudioEffectStereoEnhance; Ref<AudioEffectStereoEnhance> base; enum { - MAX_DELAY_MS=50 + MAX_DELAY_MS = 50 }; float *delay_ringbuff; unsigned int ringbuff_pos; unsigned int ringbuff_mask; - public: - - virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count); + virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count); ~AudioEffectStereoEnhanceInstance(); }; - class AudioEffectStereoEnhance : public AudioEffect { - GDCLASS(AudioEffectStereoEnhance,AudioEffect) + GDCLASS(AudioEffectStereoEnhance, AudioEffect) -friend class AudioEffectStereoEnhanceInstance; + friend class AudioEffectStereoEnhanceInstance; float volume_db; float pan_pullout; @@ -68,11 +64,9 @@ friend class AudioEffectStereoEnhanceInstance; float surround; protected: - static void _bind_methods(); -public: - +public: Ref<AudioEffectInstance> instance(); void set_pan_pullout(float p_amount); diff --git a/servers/audio/effects/eq.cpp b/servers/audio/effects/eq.cpp index 4b461e97bb..857f81e856 100644 --- a/servers/audio/effects/eq.cpp +++ b/servers/audio/effects/eq.cpp @@ -30,135 +30,119 @@ // Author: reduzio@gmail.com (C) 2006 #include "eq.h" -#include <math.h> #include "error_macros.h" #include "math_funcs.h" +#include <math.h> -#define POW2(v) ((v)*(v)) +#define POW2(v) ((v) * (v)) /* Helper */ - static int solve_quadratic(double a,double b,double c,double *r1, double *r2) { -//solves quadractic and returns number of roots +static int solve_quadratic(double a, double b, double c, double *r1, double *r2) { + //solves quadractic and returns number of roots - double base=2*a; + double base = 2 * a; if (base == 0.0f) return 0; - double squared=b*b-4*a*c; - if (squared<0.0) + double squared = b * b - 4 * a * c; + if (squared < 0.0) return 0; - squared=sqrt(squared); + squared = sqrt(squared); - *r1=(-b+squared)/base; - *r2=(-b-squared)/base; + *r1 = (-b + squared) / base; + *r2 = (-b - squared) / base; - if (*r1==*r2) + if (*r1 == *r2) return 1; else return 2; - } +} EQ::BandProcess::BandProcess() { - c1=c2=c3=history.a1=history.a2=history.a3=0; - history.b1=history.b2=history.b3=0; + c1 = c2 = c3 = history.a1 = history.a2 = history.a3 = 0; + history.b1 = history.b2 = history.b3 = 0; } void EQ::recalculate_band_coefficients() { -#define BAND_LOG( m_f ) ( log((m_f)) / log(2.) ) +#define BAND_LOG(m_f) (log((m_f)) / log(2.)) - for (int i=0;i<band.size();i++) { + for (int i = 0; i < band.size(); i++) { double octave_size; - double frq=band[i].freq; + double frq = band[i].freq; - if (i==0) { + if (i == 0) { - octave_size=BAND_LOG(band[1].freq)-BAND_LOG(frq); - } else if (i==(band.size()-1)) { + octave_size = BAND_LOG(band[1].freq) - BAND_LOG(frq); + } else if (i == (band.size() - 1)) { - octave_size=BAND_LOG(frq)-BAND_LOG(band[i-1].freq); + octave_size = BAND_LOG(frq) - BAND_LOG(band[i - 1].freq); } else { - double next=BAND_LOG(band[i+1].freq)-BAND_LOG(frq); - double prev=BAND_LOG(frq)-BAND_LOG(band[i-1].freq); - octave_size=(next+prev)/2.0; + double next = BAND_LOG(band[i + 1].freq) - BAND_LOG(frq); + double prev = BAND_LOG(frq) - BAND_LOG(band[i - 1].freq); + octave_size = (next + prev) / 2.0; } + double frq_l = round(frq / pow(2.0, octave_size / 2.0)); + double side_gain2 = POW2(Math_SQRT12); + double th = 2.0 * Math_PI * frq / mix_rate; + double th_l = 2.0 * Math_PI * frq_l / mix_rate; - double frq_l=round(frq/pow(2.0,octave_size/2.0)); - - + double c2a = side_gain2 * POW2(cos(th)) - 2.0 * side_gain2 * cos(th_l) * cos(th) + side_gain2 - POW2(sin(th_l)); - double side_gain2=POW2(Math_SQRT12); - double th=2.0*Math_PI*frq/mix_rate; - double th_l=2.0*Math_PI*frq_l/mix_rate; + double c2b = 2.0 * side_gain2 * POW2(cos(th_l)) + side_gain2 * POW2(cos(th)) - 2.0 * side_gain2 * cos(th_l) * cos(th) - side_gain2 + POW2(sin(th_l)); - double c2a=side_gain2 * POW2(cos(th)) - - 2.0 * side_gain2 * cos(th_l) * cos(th) - + side_gain2 - - POW2(sin(th_l)); - - double c2b=2.0 * side_gain2 * POW2(cos(th_l)) - + side_gain2 * POW2(cos(th)) - - 2.0 * side_gain2 * cos(th_l) * cos(th) - - side_gain2 - + POW2(sin(th_l)); - - double c2c=0.25 * side_gain2 * POW2(cos(th)) - - 0.5 * side_gain2 * cos(th_l) * cos(th) - + 0.25 * side_gain2 - - 0.25 * POW2(sin(th_l)); + double c2c = 0.25 * side_gain2 * POW2(cos(th)) - 0.5 * side_gain2 * cos(th_l) * cos(th) + 0.25 * side_gain2 - 0.25 * POW2(sin(th_l)); //printf("band %i, precoefs = %f,%f,%f\n",i,c2a,c2b,c2c); - double r1,r2; //roots - int roots=solve_quadratic(c2a,c2b,c2c,&r1,&r2); + double r1, r2; //roots + int roots = solve_quadratic(c2a, c2b, c2c, &r1, &r2); - ERR_CONTINUE( roots==0 ); + ERR_CONTINUE(roots == 0); - band[i].c1=2.0 * ((0.5-r1)/2.0); - band[i].c2=2.0 * r1; - band[i].c3=2.0 * (0.5+r1) * cos(th); + band[i].c1 = 2.0 * ((0.5 - r1) / 2.0); + band[i].c2 = 2.0 * r1; + band[i].c3 = 2.0 * (0.5 + r1) * cos(th); //printf("band %i, coefs = %f,%f,%f\n",i,(float)bands[i].c1,(float)bands[i].c2,(float)bands[i].c3); - } } void EQ::set_preset_band_mode(Preset p_preset) { - band.clear(); -#define PUSH_BANDS(m_bands) \ - for (int i=0;i<m_bands;i++) { \ - Band b; \ - b.freq=bands[i];\ - band.push_back(b);\ +#define PUSH_BANDS(m_bands) \ + for (int i = 0; i < m_bands; i++) { \ + Band b; \ + b.freq = bands[i]; \ + band.push_back(b); \ } switch (p_preset) { case PRESET_6_BANDS: { - static const double bands[] = { 32 , 100 , 320 , 1e3, 3200, 10e3 }; + static const double bands[] = { 32, 100, 320, 1e3, 3200, 10e3 }; PUSH_BANDS(6); } break; case PRESET_8_BANDS: { - static const double bands[] = { 32,72,192,512,1200,3000,7500,16e3 }; + static const double bands[] = { 32, 72, 192, 512, 1200, 3000, 7500, 16e3 }; PUSH_BANDS(8); } break; case PRESET_10_BANDS: { - static const double bands[] = { 31.25, 62.5, 125 , 250 , 500 , 1e3, 2e3, 4e3, 8e3, 16e3 }; + static const double bands[] = { 31.25, 62.5, 125, 250, 500, 1e3, 2e3, 4e3, 8e3, 16e3 }; PUSH_BANDS(10); @@ -166,17 +150,16 @@ void EQ::set_preset_band_mode(Preset p_preset) { case PRESET_21_BANDS: { - static const double bands[] = { 22 , 32 , 44 , 63 , 90 , 125 , 175 , 250 , 350 , 500 , 700 , 1e3, 1400 , 2e3, 2800 , 4e3, 5600 , 8e3, 11e3, 16e3, 22e3 }; + static const double bands[] = { 22, 32, 44, 63, 90, 125, 175, 250, 350, 500, 700, 1e3, 1400, 2e3, 2800, 4e3, 5600, 8e3, 11e3, 16e3, 22e3 }; PUSH_BANDS(21); } break; case PRESET_31_BANDS: { - static const double bands[] = { 20, 25, 31.5, 40 , 50 , 63 , 80 , 100 , 125 , 160 , 200 , 250 , 315 , 400 , 500 , 630 , 800 , 1e3 , 1250 , 1600 , 2e3, 2500 , 3150 , 4e3, 5e3, 6300 , 8e3, 10e3, 12500 , 16e3, 20e3 }; + static const double bands[] = { 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1e3, 1250, 1600, 2e3, 2500, 3150, 4e3, 5e3, 6300, 8e3, 10e3, 12500, 16e3, 20e3 }; PUSH_BANDS(31); } break; - }; recalculate_band_coefficients(); @@ -188,52 +171,42 @@ int EQ::get_band_count() const { } float EQ::get_band_frequency(int p_band) { - ERR_FAIL_INDEX_V(p_band,band.size(),0); + ERR_FAIL_INDEX_V(p_band, band.size(), 0); return band[p_band].freq; } -void EQ::set_bands(const Vector<float>& p_bands) { +void EQ::set_bands(const Vector<float> &p_bands) { band.resize(p_bands.size()); - for (int i=0;i<p_bands.size();i++) { + for (int i = 0; i < p_bands.size(); i++) { - band[i].freq=p_bands[i]; + band[i].freq = p_bands[i]; } recalculate_band_coefficients(); - } void EQ::set_mix_rate(float p_mix_rate) { - mix_rate=p_mix_rate; + mix_rate = p_mix_rate; recalculate_band_coefficients(); } EQ::BandProcess EQ::get_band_processor(int p_band) const { - EQ::BandProcess band_proc; - ERR_FAIL_INDEX_V(p_band,band.size(),band_proc); + ERR_FAIL_INDEX_V(p_band, band.size(), band_proc); - band_proc.c1=band[p_band].c1; - band_proc.c2=band[p_band].c2; - band_proc.c3=band[p_band].c3; + band_proc.c1 = band[p_band].c1; + band_proc.c2 = band[p_band].c2; + band_proc.c3 = band[p_band].c3; return band_proc; - - } - -EQ::EQ() -{ - mix_rate=44100; +EQ::EQ() { + mix_rate = 44100; } - -EQ::~EQ() -{ +EQ::~EQ() { } - - diff --git a/servers/audio/effects/eq.h b/servers/audio/effects/eq.h index 1a568ee213..a6d471cc4a 100644 --- a/servers/audio/effects/eq.h +++ b/servers/audio/effects/eq.h @@ -32,18 +32,15 @@ #ifndef EQ_FILTER_H #define EQ_FILTER_H - #include "typedefs.h" #include "vector.h" - /** @author Juan Linietsky */ class EQ { public: - enum Preset { PRESET_6_BANDS, @@ -53,21 +50,18 @@ public: PRESET_31_BANDS }; - - class BandProcess { - friend class EQ; - float c1,c2,c3; + friend class EQ; + float c1, c2, c3; struct History { - float a1,a2,a3; - float b1,b2,b3; + float a1, a2, a3; + float b1, b2, b3; } history; public: - - inline void process_one(float & p_data); + inline void process_one(float &p_data); BandProcess(); }; @@ -76,7 +70,7 @@ private: struct Band { float freq; - float c1,c2,c3; + float c1, c2, c3; }; Vector<Band> band; @@ -86,41 +80,32 @@ private: void recalculate_band_coefficients(); public: - - void set_mix_rate(float p_mix_rate); int get_band_count() const; void set_preset_band_mode(Preset p_preset); - void set_bands(const Vector<float>& p_bands); + void set_bands(const Vector<float> &p_bands); BandProcess get_band_processor(int p_band) const; float get_band_frequency(int p_band); EQ(); ~EQ(); - }; - /* Inline Function */ -inline void EQ::BandProcess::process_one(float & p_data) { +inline void EQ::BandProcess::process_one(float &p_data) { + history.a1 = p_data; - history.a1=p_data; - - history.b1= c1 * ( history.a1 - history.a3 ) - + c3 * history.b2 - - c2 * history.b3; + history.b1 = c1 * (history.a1 - history.a3) + c3 * history.b2 - c2 * history.b3; p_data = history.b1; - history.a3=history.a2; - history.a2=history.a1; - history.b3=history.b2; - history.b2=history.b1; - + history.a3 = history.a2; + history.a2 = history.a1; + history.b3 = history.b2; + history.b2 = history.b1; } - #endif diff --git a/servers/audio/effects/reverb.cpp b/servers/audio/effects/reverb.cpp index bc3212201f..6462977d7c 100644 --- a/servers/audio/effects/reverb.cpp +++ b/servers/audio/effects/reverb.cpp @@ -30,11 +30,10 @@ // Author: Juan Linietsky <reduzio@gmail.com>, (C) 2006 #include "reverb.h" -#include <math.h> #include "math_funcs.h" +#include <math.h> - -const float Reverb::comb_tunings[MAX_COMBS]={ +const float Reverb::comb_tunings[MAX_COMBS] = { //freeverb comb tunings 0.025306122448979593, 0.026938775510204082, @@ -46,7 +45,7 @@ const float Reverb::comb_tunings[MAX_COMBS]={ 0.036666666666666667 }; -const float Reverb::allpass_tunings[MAX_ALLPASS]={ +const float Reverb::allpass_tunings[MAX_ALLPASS] = { //freeverb allpass tunings 0.0051020408163265302, 0.007732426303854875, @@ -54,76 +53,72 @@ const float Reverb::allpass_tunings[MAX_ALLPASS]={ 0.012607709750566893 }; +void Reverb::process(float *p_src, float *p_dst, int p_frames) { + if (p_frames > INPUT_BUFFER_MAX_SIZE) + p_frames = INPUT_BUFFER_MAX_SIZE; -void Reverb::process(float *p_src,float *p_dst,int p_frames) { - - if (p_frames>INPUT_BUFFER_MAX_SIZE) - p_frames=INPUT_BUFFER_MAX_SIZE; - - int predelay_frames=lrint((params.predelay/1000.0)*params.mix_rate); - if (predelay_frames<10) - predelay_frames=10; - if (predelay_frames>=echo_buffer_size) - predelay_frames=echo_buffer_size-1; + int predelay_frames = lrint((params.predelay / 1000.0) * params.mix_rate); + if (predelay_frames < 10) + predelay_frames = 10; + if (predelay_frames >= echo_buffer_size) + predelay_frames = echo_buffer_size - 1; - for (int i=0;i<p_frames;i++) { + for (int i = 0; i < p_frames; i++) { - if (echo_buffer_pos>=echo_buffer_size) - echo_buffer_pos=0; + if (echo_buffer_pos >= echo_buffer_size) + echo_buffer_pos = 0; - int read_pos=echo_buffer_pos-predelay_frames; - while (read_pos<0) - read_pos+=echo_buffer_size; + int read_pos = echo_buffer_pos - predelay_frames; + while (read_pos < 0) + read_pos += echo_buffer_size; - float in=undenormalise(echo_buffer[read_pos]*params.predelay_fb+p_src[i]); + float in = undenormalise(echo_buffer[read_pos] * params.predelay_fb + p_src[i]); - echo_buffer[echo_buffer_pos]=in; + echo_buffer[echo_buffer_pos] = in; - input_buffer[i]=in; + input_buffer[i] = in; - p_dst[i]=0; //take the chance and clear this + p_dst[i] = 0; //take the chance and clear this echo_buffer_pos++; } - if (params.hpf>0) { - float hpaux=expf(-2.0*Math_PI*params.hpf*6000/params.mix_rate); - float hp_a1=(1.0+hpaux)/2.0; - float hp_a2=-(1.0+hpaux)/2.0; - float hp_b1=hpaux; + if (params.hpf > 0) { + float hpaux = expf(-2.0 * Math_PI * params.hpf * 6000 / params.mix_rate); + float hp_a1 = (1.0 + hpaux) / 2.0; + float hp_a2 = -(1.0 + hpaux) / 2.0; + float hp_b1 = hpaux; - for (int i=0;i<p_frames;i++) { + for (int i = 0; i < p_frames; i++) { - float in=input_buffer[i]; - input_buffer[i]=in*hp_a1+hpf_h1*hp_a2+hpf_h2*hp_b1; - hpf_h2=input_buffer[i]; - hpf_h1=in; + float in = input_buffer[i]; + input_buffer[i] = in * hp_a1 + hpf_h1 * hp_a2 + hpf_h2 * hp_b1; + hpf_h2 = input_buffer[i]; + hpf_h1 = in; } } - for (int i=0;i<MAX_COMBS;i++) { + for (int i = 0; i < MAX_COMBS; i++) { - Comb &c=comb[i]; + Comb &c = comb[i]; - int size_limit=c.size-lrintf((float)c.extra_spread_frames*(1.0-params.extra_spread)); - for (int j=0;j<p_frames;j++) { + int size_limit = c.size - lrintf((float)c.extra_spread_frames * (1.0 - params.extra_spread)); + for (int j = 0; j < p_frames; j++) { - if (c.pos>=size_limit) //reset this now just in case - c.pos=0; + if (c.pos >= size_limit) //reset this now just in case + c.pos = 0; - float out=undenormalise(c.buffer[c.pos]*c.feedback); - out=out*(1.0-c.damp)+c.damp_h*c.damp; //lowpass - c.damp_h=out; - c.buffer[c.pos]=input_buffer[j]+out; - p_dst[j]+=out; + float out = undenormalise(c.buffer[c.pos] * c.feedback); + out = out * (1.0 - c.damp) + c.damp_h * c.damp; //lowpass + c.damp_h = out; + c.buffer[c.pos] = input_buffer[j] + out; + p_dst[j] += out; c.pos++; } - } - - static const float allpass_feedback=0.7; + static const float allpass_feedback = 0.7; /* this one works, but the other version is just nicer.... int ap_size_limit[MAX_ALLPASS]; @@ -158,170 +153,154 @@ void Reverb::process(float *p_src,float *p_dst,int p_frames) { } */ - for (int i=0;i<MAX_ALLPASS;i++) { + for (int i = 0; i < MAX_ALLPASS; i++) { - AllPass &a=allpass[i]; - int size_limit=a.size-lrintf((float)a.extra_spread_frames*(1.0-params.extra_spread)); + AllPass &a = allpass[i]; + int size_limit = a.size - lrintf((float)a.extra_spread_frames * (1.0 - params.extra_spread)); - for (int j=0;j<p_frames;j++) { + for (int j = 0; j < p_frames; j++) { - if (a.pos>=size_limit) - a.pos=0; + if (a.pos >= size_limit) + a.pos = 0; - float aux=a.buffer[a.pos]; - a.buffer[a.pos]=undenormalise(allpass_feedback*aux+p_dst[j]); - p_dst[j]=aux-allpass_feedback*a.buffer[a.pos]; + float aux = a.buffer[a.pos]; + a.buffer[a.pos] = undenormalise(allpass_feedback * aux + p_dst[j]); + p_dst[j] = aux - allpass_feedback * a.buffer[a.pos]; a.pos++; - } } - static const float wet_scale=0.6; - - for (int i=0;i<p_frames;i++) { + static const float wet_scale = 0.6; + for (int i = 0; i < p_frames; i++) { - p_dst[i]=p_dst[i]*params.wet*wet_scale+p_src[i]*params.dry; + p_dst[i] = p_dst[i] * params.wet * wet_scale + p_src[i] * params.dry; } - } - void Reverb::set_room_size(float p_size) { - params.room_size=p_size; + params.room_size = p_size; update_parameters(); - } void Reverb::set_damp(float p_damp) { - params.damp=p_damp; + params.damp = p_damp; update_parameters(); - } void Reverb::set_wet(float p_wet) { - params.wet=p_wet; - + params.wet = p_wet; } void Reverb::set_dry(float p_dry) { - params.dry=p_dry; - + params.dry = p_dry; } void Reverb::set_predelay(float p_predelay) { - params.predelay=p_predelay; + params.predelay = p_predelay; } void Reverb::set_predelay_feedback(float p_predelay_fb) { - params.predelay_fb=p_predelay_fb; - + params.predelay_fb = p_predelay_fb; } void Reverb::set_highpass(float p_frq) { - if (p_frq>1) - p_frq=1; - if (p_frq<0) - p_frq=0; - params.hpf=p_frq; + if (p_frq > 1) + p_frq = 1; + if (p_frq < 0) + p_frq = 0; + params.hpf = p_frq; } void Reverb::set_extra_spread(float p_spread) { - params.extra_spread=p_spread; - + params.extra_spread = p_spread; } - void Reverb::set_mix_rate(float p_mix_rate) { - params.mix_rate=p_mix_rate; + params.mix_rate = p_mix_rate; configure_buffers(); } void Reverb::set_extra_spread_base(float p_sec) { - params.extra_spread_base=p_sec; + params.extra_spread_base = p_sec; configure_buffers(); } - void Reverb::configure_buffers() { clear_buffers(); //clear if necesary - for (int i=0;i<MAX_COMBS;i++) { - - Comb &c=comb[i]; - + for (int i = 0; i < MAX_COMBS; i++) { - c.extra_spread_frames=lrint(params.extra_spread_base*params.mix_rate); + Comb &c = comb[i]; - int len=lrint(comb_tunings[i]*params.mix_rate)+c.extra_spread_frames; - if (len<5) - len=5; //may this happen? + c.extra_spread_frames = lrint(params.extra_spread_base * params.mix_rate); - c.buffer = memnew_arr(float,len); - c.pos=0; - for (int j=0;j<len;j++) - c.buffer[j]=0; - c.size=len; + int len = lrint(comb_tunings[i] * params.mix_rate) + c.extra_spread_frames; + if (len < 5) + len = 5; //may this happen? + c.buffer = memnew_arr(float, len); + c.pos = 0; + for (int j = 0; j < len; j++) + c.buffer[j] = 0; + c.size = len; } - for (int i=0;i<MAX_ALLPASS;i++) { + for (int i = 0; i < MAX_ALLPASS; i++) { - AllPass &a=allpass[i]; + AllPass &a = allpass[i]; - a.extra_spread_frames=lrint(params.extra_spread_base*params.mix_rate); + a.extra_spread_frames = lrint(params.extra_spread_base * params.mix_rate); - int len=lrint(allpass_tunings[i]*params.mix_rate)+a.extra_spread_frames; - if (len<5) - len=5; //may this happen? + int len = lrint(allpass_tunings[i] * params.mix_rate) + a.extra_spread_frames; + if (len < 5) + len = 5; //may this happen? - a.buffer = memnew_arr(float,len); - a.pos=0; - for (int j=0;j<len;j++) - a.buffer[j]=0; - a.size=len; + a.buffer = memnew_arr(float, len); + a.pos = 0; + for (int j = 0; j < len; j++) + a.buffer[j] = 0; + a.size = len; } - echo_buffer_size=(int)(((float)MAX_ECHO_MS/1000.0)*params.mix_rate+1.0); - echo_buffer = memnew_arr(float,echo_buffer_size); - for (int i=0;i<echo_buffer_size;i++) { + echo_buffer_size = (int)(((float)MAX_ECHO_MS / 1000.0) * params.mix_rate + 1.0); + echo_buffer = memnew_arr(float, echo_buffer_size); + for (int i = 0; i < echo_buffer_size; i++) { - echo_buffer[i]=0; + echo_buffer[i] = 0; } - echo_buffer_pos=0; + echo_buffer_pos = 0; } - void Reverb::update_parameters() { //more freeverb derived constants static const float room_scale = 0.28f; static const float room_offset = 0.7f; - for (int i=0;i<MAX_COMBS;i++) { + for (int i = 0; i < MAX_COMBS; i++) { - Comb &c=comb[i]; - c.feedback=room_offset+params.room_size*room_scale; - if (c.feedback<room_offset) - c.feedback=room_offset; - else if (c.feedback>(room_offset+room_scale)) - c.feedback=(room_offset+room_scale); + Comb &c = comb[i]; + c.feedback = room_offset + params.room_size * room_scale; + if (c.feedback < room_offset) + c.feedback = room_offset; + else if (c.feedback > (room_offset + room_scale)) + c.feedback = (room_offset + room_scale); - float auxdmp=params.damp/2.0+0.5; //only half the range (0.5 .. 1.0 is enough) - auxdmp*=auxdmp; + float auxdmp = params.damp / 2.0 + 0.5; //only half the range (0.5 .. 1.0 is enough) + auxdmp *= auxdmp; - c.damp=expf(-2.0*Math_PI*auxdmp*10000/params.mix_rate); // 0 .. 10khz + c.damp = expf(-2.0 * Math_PI * auxdmp * 10000 / params.mix_rate); // 0 .. 10khz } - } void Reverb::clear_buffers() { @@ -329,55 +308,47 @@ void Reverb::clear_buffers() { if (echo_buffer) memdelete_arr(echo_buffer); - for (int i=0;i<MAX_COMBS;i++) { + for (int i = 0; i < MAX_COMBS; i++) { if (comb[i].buffer) memdelete_arr(comb[i].buffer); - comb[i].buffer=0; - + comb[i].buffer = 0; } - for (int i=0;i<MAX_ALLPASS;i++) { + for (int i = 0; i < MAX_ALLPASS; i++) { if (allpass[i].buffer) memdelete_arr(allpass[i].buffer); - allpass[i].buffer=0; + allpass[i].buffer = 0; } - } Reverb::Reverb() { - params.room_size=0.8; - params.damp=0.5; - params.dry=1.0; - params.wet=0.0; - params.mix_rate=44100; - params.extra_spread_base=0; - params.extra_spread=1.0; - params.predelay=150; - params.predelay_fb=0.4; - params.hpf=0; - hpf_h1=0; - hpf_h2=0; - - - input_buffer=memnew_arr(float,INPUT_BUFFER_MAX_SIZE); - echo_buffer=0; + params.room_size = 0.8; + params.damp = 0.5; + params.dry = 1.0; + params.wet = 0.0; + params.mix_rate = 44100; + params.extra_spread_base = 0; + params.extra_spread = 1.0; + params.predelay = 150; + params.predelay_fb = 0.4; + params.hpf = 0; + hpf_h1 = 0; + hpf_h2 = 0; + + input_buffer = memnew_arr(float, INPUT_BUFFER_MAX_SIZE); + echo_buffer = 0; configure_buffers(); update_parameters(); - - } - Reverb::~Reverb() { memdelete_arr(input_buffer); clear_buffers(); } - - diff --git a/servers/audio/effects/reverb.h b/servers/audio/effects/reverb.h index f0a0466f8a..33f11e59fe 100644 --- a/servers/audio/effects/reverb.h +++ b/servers/audio/effects/reverb.h @@ -32,27 +32,26 @@ #ifndef REVERB_H #define REVERB_H -#include "typedefs.h" -#include "os/memory.h" #include "audio_frame.h" +#include "os/memory.h" +#include "typedefs.h" class Reverb { public: enum { - INPUT_BUFFER_MAX_SIZE=1024, + INPUT_BUFFER_MAX_SIZE = 1024, }; + private: enum { - MAX_COMBS=8, - MAX_ALLPASS=4, - MAX_ECHO_MS=500 + MAX_COMBS = 8, + MAX_ALLPASS = 4, + MAX_ECHO_MS = 500 }; - - static const float comb_tunings[MAX_COMBS]; static const float allpass_tunings[MAX_ALLPASS]; @@ -66,7 +65,13 @@ private: int pos; int extra_spread_frames; - Comb() { size=0; buffer=0; feedback=0; damp_h=0; pos=0; } + Comb() { + size = 0; + buffer = 0; + feedback = 0; + damp_h = 0; + pos = 0; + } }; struct AllPass { @@ -75,7 +80,11 @@ private: float *buffer; int pos; int extra_spread_frames; - AllPass() { size=0; buffer=0; pos=0; } + AllPass() { + size = 0; + buffer = 0; + pos = 0; + } }; Comb comb[MAX_COMBS]; @@ -85,8 +94,7 @@ private: int echo_buffer_size; int echo_buffer_pos; - float hpf_h1,hpf_h2; - + float hpf_h1, hpf_h2; struct Parameters { @@ -105,8 +113,8 @@ private: void configure_buffers(); void update_parameters(); void clear_buffers(); -public: +public: void set_room_size(float p_size); void set_damp(float p_damp); void set_wet(float p_wet); @@ -118,14 +126,11 @@ public: void set_extra_spread(float p_spread); void set_extra_spread_base(float p_sec); - void process(float *p_src,float *p_dst,int p_frames); + void process(float *p_src, float *p_dst, int p_frames); Reverb(); ~Reverb(); - }; - - #endif diff --git a/servers/audio/reverb_sw.cpp b/servers/audio/reverb_sw.cpp index 5e02f37679..ea89f7e198 100644 --- a/servers/audio/reverb_sw.cpp +++ b/servers/audio/reverb_sw.cpp @@ -27,223 +27,217 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "reverb_sw.h" -#include "stdlib.h" #include "print_string.h" -#define SETMIN( x, y ) (x) = MIN ( (x), (y) ) -#define rangeloop( c, min, max ) \ - for ( (c) = (min) ; (c) < (max) ; (c)++ ) - -#define ABSDIFF(x, y)\ - ( ((x) < (y)) ? ((y) - (x)) : ((x) - (y)) ) +#include "stdlib.h" +#define SETMIN(x, y) (x) = MIN((x), (y)) +#define rangeloop(c, min, max) \ + for ((c) = (min); (c) < (max); (c)++) +#define ABSDIFF(x, y) \ + (((x) < (y)) ? ((y) - (x)) : ((x) - (y))) #ifdef bleh_MSC_VER #if _MSC_VER >= 1400 - _FORCE_INLINE_ int32_tMULSHIFT_S32 ( +_FORCE_INLINE_ int32_tMULSHIFT_S32( int32_t Factor1, int32_t Factor2, - uint8_t Bits - ) { - - return __ll_rshift ( - __emul ( Factor1, Factor2 ), - Bits - ); - } + uint8_t Bits) { + + return __ll_rshift( + __emul(Factor1, Factor2), + Bits); +} #endif #else -#define MULSHIFT_S32( Factor1, Factor2, Bits )\ - ( (int) (( (int64_t)(Factor1) * (Factor2) ) >> (Bits)) ) +#define MULSHIFT_S32(Factor1, Factor2, Bits) \ + ((int)(((int64_t)(Factor1) * (Factor2)) >> (Bits))) #endif - - struct ReverbParamsSW { - unsigned int BufferSize; // Required buffer size - int gLPF; // Coefficient - int gEcho0; // Coefficient - int gEcho1; // Coefficient - int gEcho2; // Coefficient - int gEcho3; // Coefficient - int gWall; // Coefficient - int gReva; // Coefficient - int gRevb; // Coefficient - int gInputL; // Coefficient - int gInputR; // Coefficient - unsigned int nRevaOldL; // Offset - unsigned int nRevaOldR; // Offset - unsigned int nRevbOldL; // Offset - unsigned int nRevbOldR; // Offset - unsigned int nLwlNew; // Offset - unsigned int nRwrNew; // Offset - unsigned int nEcho0L; // Offset - unsigned int nEcho0R; // Offset - unsigned int nEcho1L; // Offset - unsigned int nEcho1R; // Offset - unsigned int nLwlOld; // Offset - unsigned int nRwrOld; // Offset - unsigned int nLwrNew; // Offset - unsigned int nRwlNew; // Offset - unsigned int nEcho2L; // Offset - unsigned int nEcho2R; // Offset - unsigned int nEcho3L; // Offset - unsigned int nEcho3R; // Offset - unsigned int nLwrOld; // Offset - unsigned int nRwlOld; // Offset - unsigned int nRevaNewL; // Offset - unsigned int nRevaNewR; // Offset - unsigned int nRevbNewL; // Offset - unsigned int nRevbNewR; // Offset + unsigned int BufferSize; // Required buffer size + int gLPF; // Coefficient + int gEcho0; // Coefficient + int gEcho1; // Coefficient + int gEcho2; // Coefficient + int gEcho3; // Coefficient + int gWall; // Coefficient + int gReva; // Coefficient + int gRevb; // Coefficient + int gInputL; // Coefficient + int gInputR; // Coefficient + unsigned int nRevaOldL; // Offset + unsigned int nRevaOldR; // Offset + unsigned int nRevbOldL; // Offset + unsigned int nRevbOldR; // Offset + unsigned int nLwlNew; // Offset + unsigned int nRwrNew; // Offset + unsigned int nEcho0L; // Offset + unsigned int nEcho0R; // Offset + unsigned int nEcho1L; // Offset + unsigned int nEcho1R; // Offset + unsigned int nLwlOld; // Offset + unsigned int nRwrOld; // Offset + unsigned int nLwrNew; // Offset + unsigned int nRwlNew; // Offset + unsigned int nEcho2L; // Offset + unsigned int nEcho2R; // Offset + unsigned int nEcho3L; // Offset + unsigned int nEcho3R; // Offset + unsigned int nLwrOld; // Offset + unsigned int nRwlOld; // Offset + unsigned int nRevaNewL; // Offset + unsigned int nRevaNewR; // Offset + unsigned int nRevbNewL; // Offset + unsigned int nRevbNewR; // Offset }; static ReverbParamsSW reverb_params_Room = { - 0x26C0/2, + 0x26C0 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x6D80, 0x54B8, -0x4130, 0x0000, 0x0000, -0x4580, + 0x6D80, 0x54B8, -0x4130, 0x0000, 0x0000, -0x4580, //gReva gRevb gInputL gInputR - 0x5800, 0x5300, -0x8000, -0x8000, + 0x5800, 0x5300, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x01B4 - 0x007D, 0x0136 - 0x007D, 0x00B8 - 0x005B, 0x005C - 0x005B, + 0x01B4 - 0x007D, 0x0136 - 0x007D, 0x00B8 - 0x005B, 0x005C - 0x005B, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x04D6, 0x0333, 0x03F0, 0x0227, 0x0374, 0x01EF, + 0x04D6, 0x0333, 0x03F0, 0x0227, 0x0374, 0x01EF, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x0334, 0x01B5, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0334, 0x01B5, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x0000, 0x0000, 0x01B4, 0x0136, 0x00B8, 0x005C + 0x0000, 0x0000, 0x01B4, 0x0136, 0x00B8, 0x005C }; static ReverbParamsSW reverb_params_StudioSmall = { - 0x1F40/2, + 0x1F40 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x70F0, 0x4FA8, -0x4320, 0x4410, -0x3F10, -0x6400, + 0x70F0, 0x4FA8, -0x4320, 0x4410, -0x3F10, -0x6400, //gReva gRevb gInputL gInputR - 0x5280, 0x4EC0, -0x8000, -0x8000, + 0x5280, 0x4EC0, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x00B4 - 0x0033, 0x0080 - 0x0033, 0x004C - 0x0025, 0x0026 - 0x0025, + 0x00B4 - 0x0033, 0x0080 - 0x0033, 0x004C - 0x0025, 0x0026 - 0x0025, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x03E4, 0x031B, 0x03A4, 0x02AF, 0x0372, 0x0266, + 0x03E4, 0x031B, 0x03A4, 0x02AF, 0x0372, 0x0266, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x031C, 0x025D, 0x025C, 0x018E, 0x022F, 0x0135, 0x01D2, 0x00B7, + 0x031C, 0x025D, 0x025C, 0x018E, 0x022F, 0x0135, 0x01D2, 0x00B7, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x018F, 0x00B5, 0x00B4, 0x0080, 0x004C, 0x0026 + 0x018F, 0x00B5, 0x00B4, 0x0080, 0x004C, 0x0026 }; static ReverbParamsSW reverb_params_StudioMedium = { - 0x4840/2, + 0x4840 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x4B40, + 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x4B40, //gReva gRevb gInputL gInputR - 0x5280, 0x4EC0, -0x8000, -0x8000, + 0x5280, 0x4EC0, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x0264 - 0x00B1, 0x01B2 - 0x00B1, 0x0100 - 0x007F, 0x0080 - 0x007F, + 0x0264 - 0x00B1, 0x01B2 - 0x00B1, 0x0100 - 0x007F, 0x0080 - 0x007F, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x0904, 0x076B, 0x0824, 0x065F, 0x07A2, 0x0616, + 0x0904, 0x076B, 0x0824, 0x065F, 0x07A2, 0x0616, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x076C, 0x05ED, 0x05EC, 0x042E, 0x050F, 0x0305, 0x0462, 0x02B7, + 0x076C, 0x05ED, 0x05EC, 0x042E, 0x050F, 0x0305, 0x0462, 0x02B7, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x042F, 0x0265, 0x0264, 0x01B2, 0x0100, 0x0080 + 0x042F, 0x0265, 0x0264, 0x01B2, 0x0100, 0x0080 }; static ReverbParamsSW reverb_params_StudioLarge = { - 0x6FE0/2, + 0x6FE0 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x6F60, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x5980, + 0x6F60, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x5980, //gReva gRevb gInputL gInputR - 0x5680, 0x52C0, -0x8000, -0x8000, + 0x5680, 0x52C0, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x031C - 0x00E3, 0x0238 - 0x00E3, 0x0154 - 0x00A9, 0x00AA - 0x00A9, + 0x031C - 0x00E3, 0x0238 - 0x00E3, 0x0154 - 0x00A9, 0x00AA - 0x00A9, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x0DFB, 0x0B58, 0x0D09, 0x0A3C, 0x0BD9, 0x0973, + 0x0DFB, 0x0B58, 0x0D09, 0x0A3C, 0x0BD9, 0x0973, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x0B59, 0x08DA, 0x08D9, 0x05E9, 0x07EC, 0x04B0, 0x06EF, 0x03D2, + 0x0B59, 0x08DA, 0x08D9, 0x05E9, 0x07EC, 0x04B0, 0x06EF, 0x03D2, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x05EA, 0x031D, 0x031C, 0x0238, 0x0154, 0x00AA + 0x05EA, 0x031D, 0x031C, 0x0238, 0x0154, 0x00AA }; static ReverbParamsSW reverb_params_Hall = { - 0xADE0/2, + 0xADE0 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x6000, 0x5000, 0x4C00, -0x4800, -0x4400, -0x4000, + 0x6000, 0x5000, 0x4C00, -0x4800, -0x4400, -0x4000, //gReva gRevb gInputL gInputR - 0x6000, 0x5C00, -0x8000, -0x8000, + 0x6000, 0x5C00, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x05C0 - 0x01A5, 0x041A - 0x01A5, 0x0274 - 0x0139, 0x013A - 0x0139, + 0x05C0 - 0x01A5, 0x041A - 0x01A5, 0x0274 - 0x0139, 0x013A - 0x0139, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x15BA, 0x11BB, 0x14C2, 0x10BD, 0x11BC, 0x0DC1, + 0x15BA, 0x11BB, 0x14C2, 0x10BD, 0x11BC, 0x0DC1, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x11C0, 0x0DC3, 0x0DC0, 0x09C1, 0x0BC4, 0x07C1, 0x0A00, 0x06CD, + 0x11C0, 0x0DC3, 0x0DC0, 0x09C1, 0x0BC4, 0x07C1, 0x0A00, 0x06CD, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x09C2, 0x05C1, 0x05C0, 0x041A, 0x0274, 0x013A + 0x09C2, 0x05C1, 0x05C0, 0x041A, 0x0274, 0x013A }; static ReverbParamsSW reverb_params_SpaceEcho = { - 0xF6C0/2, + 0xF6C0 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x7E00, 0x5000, -0x4C00, -0x5000, 0x4C00, -0x5000, + 0x7E00, 0x5000, -0x4C00, -0x5000, 0x4C00, -0x5000, //gReva gRevb gInputL gInputR - 0x6000, 0x5400, -0x8000, -0x8000, + 0x6000, 0x5400, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x0AE0 - 0x033D, 0x07A2 - 0x033D, 0x0464 - 0x0231, 0x0232 - 0x0231, + 0x0AE0 - 0x033D, 0x07A2 - 0x033D, 0x0464 - 0x0231, 0x0232 - 0x0231, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x1ED6, 0x1A31, 0x1D14, 0x183B, 0x1BC2, 0x16B2, + 0x1ED6, 0x1A31, 0x1D14, 0x183B, 0x1BC2, 0x16B2, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x1A32, 0x15EF, 0x15EE, 0x1055, 0x1334, 0x0F2D, 0x11F6, 0x0C5D, + 0x1A32, 0x15EF, 0x15EE, 0x1055, 0x1334, 0x0F2D, 0x11F6, 0x0C5D, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x1056, 0x0AE1, 0x0AE0, 0x07A2, 0x0464, 0x0232 + 0x1056, 0x0AE1, 0x0AE0, 0x07A2, 0x0464, 0x0232 }; static ReverbParamsSW reverb_params_Echo = { - 0x18040/2, + 0x18040 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, -0x7F00, + 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, -0x7F00, //gReva gRevb gInputL gInputR - 0x0000, 0x0000, -0x8000, -0x8000, + 0x0000, 0x0000, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001, + 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000, + 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002 + 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002 }; static ReverbParamsSW reverb_params_Delay = { - 0x18040/2, + 0x18040 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, 0x0000, + 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, 0x0000, //gReva gRevb gInputL gInputR - 0x0000, 0x0000, -0x8000, -0x8000, + 0x0000, 0x0000, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001, + 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000, + 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002 + 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002 }; static ReverbParamsSW reverb_params_HalfEcho = { - 0x3C00/2, + 0x3C00 / 2, //gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall - 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x7B00, + 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x7B00, //gReva gRevb gInputL gInputR - 0x5F80, 0x54C0, -0x8000, -0x8000, + 0x5F80, 0x54C0, -0x8000, -0x8000, //nRevaOldL nRevaOldR nRevbOldL nRevbOldR - 0x0058 - 0x0017, 0x0040 - 0x0017, 0x0028 - 0x0013, 0x0014 - 0x0013, + 0x0058 - 0x0017, 0x0040 - 0x0017, 0x0028 - 0x0013, 0x0014 - 0x0013, //nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R - 0x0371, 0x02AF, 0x02E5, 0x01DF, 0x02B0, 0x01D7, + 0x0371, 0x02AF, 0x02E5, 0x01DF, 0x02B0, 0x01D7, //nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R - 0x0358, 0x026A, 0x01D6, 0x011E, 0x012D, 0x00B1, 0x011F, 0x0059, + 0x0358, 0x026A, 0x01D6, 0x011E, 0x012D, 0x00B1, 0x011F, 0x0059, //nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR - 0x01A0, 0x00E3, 0x0058, 0x0040, 0x0028, 0x0014 + 0x01A0, 0x00E3, 0x0058, 0x0040, 0x0028, 0x0014 }; - -static ReverbParamsSW * reverb_param_modes[] = { +static ReverbParamsSW *reverb_param_modes[] = { &reverb_params_Room, &reverb_params_StudioSmall, &reverb_params_StudioMedium, @@ -255,25 +249,24 @@ static ReverbParamsSW * reverb_param_modes[] = { &reverb_params_HalfEcho, }; -bool ReverbSW::process(int *p_input,int *p_output,int p_frames,int p_stereo_stride) { +bool ReverbSW::process(int *p_input, int *p_output, int p_frames, int p_stereo_stride) { if (!reverb_buffer) return false; +// +// p_input must point to a non-looping buffer. +// BOTH p_input and p_output must be touched (use ClearModuleBuffer). - // - // p_input must point to a non-looping buffer. - // BOTH p_input and p_output must be touched (use ClearModuleBuffer). - - // LOCAL MACROS +// LOCAL MACROS #undef LM_SETSRCOFFSET -#define LM_SETSRCOFFSET(x) \ - (x) = current_params->x + Offset; \ - if ( (x) >= reverb_buffer_size ) { \ - (x) -= reverb_buffer_size; \ - } \ - SETMIN ( aSample, reverb_buffer_size - (x) ); +#define LM_SETSRCOFFSET(x) \ + (x) = current_params->x + Offset; \ + if ((x) >= reverb_buffer_size) { \ + (x) -= reverb_buffer_size; \ + } \ + SETMIN(aSample, reverb_buffer_size - (x)); /* #undef LM_SETSRCOFFSET2 @@ -286,15 +279,15 @@ bool ReverbSW::process(int *p_input,int *p_output,int p_frames,int p_stereo_stri SETMIN ( aSample, reverb_buffer_size - (x) ); */ #undef LM_SRCADVANCE -#define LM_SRCADVANCE(x) \ - (x) += aSample; +#define LM_SRCADVANCE(x) \ + (x) += aSample; #undef LM_MUL -#define LM_MUL(x,y) \ -MULSHIFT_S32 ( x, current_params->y, 15 ) +#define LM_MUL(x, y) \ + MULSHIFT_S32(x, current_params->y, 15) #undef LM_REVERB -#define LM_REVERB(x) reverb_buffer[ (x) + cSample ] +#define LM_REVERB(x) reverb_buffer[(x) + cSample] // LOCAL VARIABLES @@ -305,16 +298,15 @@ MULSHIFT_S32 ( x, current_params->y, 15 ) // CODE - lwl = state.lwl; lwr = state.lwr; rwl = state.rwl; rwr = state.rwr; Offset = state.Offset; - int max=0; + int max = 0; - while ( p_frames ) { + while (p_frames) { // Offsets @@ -354,109 +346,110 @@ MULSHIFT_S32 ( x, current_params->y, 15 ) // Set initial offsets - LM_SETSRCOFFSET ( nLwlOld ); - LM_SETSRCOFFSET ( nRwrOld ); - LM_SETSRCOFFSET ( nLwlNew ); - LM_SETSRCOFFSET ( nRwrNew ); - LM_SETSRCOFFSET ( nLwrOld ); - LM_SETSRCOFFSET ( nRwlOld ); - LM_SETSRCOFFSET ( nLwrNew ); - LM_SETSRCOFFSET ( nRwlNew ); - LM_SETSRCOFFSET ( nEcho0L ); - LM_SETSRCOFFSET ( nEcho1L ); - LM_SETSRCOFFSET ( nEcho2L ); - LM_SETSRCOFFSET ( nEcho3L ); - LM_SETSRCOFFSET ( nEcho0R ); - LM_SETSRCOFFSET ( nEcho1R ); - LM_SETSRCOFFSET ( nEcho2R ); - LM_SETSRCOFFSET ( nEcho3R ); - LM_SETSRCOFFSET ( nRevaOldL ); - LM_SETSRCOFFSET ( nRevaOldR ); - LM_SETSRCOFFSET ( nRevbOldL ); - LM_SETSRCOFFSET ( nRevbOldR ); - LM_SETSRCOFFSET ( nRevaNewL ); - LM_SETSRCOFFSET ( nRevaNewR ); - LM_SETSRCOFFSET ( nRevbNewL ); - LM_SETSRCOFFSET ( nRevbNewR ); + LM_SETSRCOFFSET(nLwlOld); + LM_SETSRCOFFSET(nRwrOld); + LM_SETSRCOFFSET(nLwlNew); + LM_SETSRCOFFSET(nRwrNew); + LM_SETSRCOFFSET(nLwrOld); + LM_SETSRCOFFSET(nRwlOld); + LM_SETSRCOFFSET(nLwrNew); + LM_SETSRCOFFSET(nRwlNew); + LM_SETSRCOFFSET(nEcho0L); + LM_SETSRCOFFSET(nEcho1L); + LM_SETSRCOFFSET(nEcho2L); + LM_SETSRCOFFSET(nEcho3L); + LM_SETSRCOFFSET(nEcho0R); + LM_SETSRCOFFSET(nEcho1R); + LM_SETSRCOFFSET(nEcho2R); + LM_SETSRCOFFSET(nEcho3R); + LM_SETSRCOFFSET(nRevaOldL); + LM_SETSRCOFFSET(nRevaOldR); + LM_SETSRCOFFSET(nRevbOldL); + LM_SETSRCOFFSET(nRevbOldR); + LM_SETSRCOFFSET(nRevaNewL); + LM_SETSRCOFFSET(nRevaNewR); + LM_SETSRCOFFSET(nRevbNewL); + LM_SETSRCOFFSET(nRevbNewR); //SETMIN ( aSample, p_output.Size - p_output.Offset ); - for (unsigned int cSample=0;cSample<aSample;cSample++) { + for (unsigned int cSample = 0; cSample < aSample; cSample++) { int tempL0, tempL1, tempR0, tempR1; - tempL1 = p_input[(cSample<<p_stereo_stride)]>>8; - tempR1 = p_input[(cSample<<p_stereo_stride) + 1]>>8; + tempL1 = p_input[(cSample << p_stereo_stride)] >> 8; + tempR1 = p_input[(cSample << p_stereo_stride) + 1] >> 8; - tempL0 = LM_MUL ( tempL1, gInputL ); - tempR0 = LM_MUL ( tempR1, gInputR ); + tempL0 = LM_MUL(tempL1, gInputL); + tempR0 = LM_MUL(tempR1, gInputR); /* Left -> Wall -> Left Reflection */ - tempL1 = tempL0 + LM_MUL ( LM_REVERB( nLwlOld ), gWall ); - tempR1 = tempR0 + LM_MUL ( LM_REVERB( nRwrOld ), gWall ); - lwl += LM_MUL ( tempL1 - lwl, gLPF ); - rwr += LM_MUL ( tempR1 - rwr, gLPF ); - LM_REVERB( nLwlNew ) = lwl; - LM_REVERB( nRwrNew ) = rwr; + tempL1 = tempL0 + LM_MUL(LM_REVERB(nLwlOld), gWall); + tempR1 = tempR0 + LM_MUL(LM_REVERB(nRwrOld), gWall); + lwl += LM_MUL(tempL1 - lwl, gLPF); + rwr += LM_MUL(tempR1 - rwr, gLPF); + LM_REVERB(nLwlNew) = lwl; + LM_REVERB(nRwrNew) = rwr; /* Left -> Wall -> Right Reflection */ - tempL1 = tempL0 + LM_MUL ( LM_REVERB( nRwlOld ), gWall ); - tempR1 = tempR0 + LM_MUL ( LM_REVERB( nLwrOld ), gWall ); - lwr += LM_MUL ( tempL1 - lwr, gLPF ); - rwl += LM_MUL ( tempR1 - rwl, gLPF ); - LM_REVERB( nLwrNew ) = lwr; - LM_REVERB( nRwlNew ) = rwl; + tempL1 = tempL0 + LM_MUL(LM_REVERB(nRwlOld), gWall); + tempR1 = tempR0 + LM_MUL(LM_REVERB(nLwrOld), gWall); + lwr += LM_MUL(tempL1 - lwr, gLPF); + rwl += LM_MUL(tempR1 - rwl, gLPF); + LM_REVERB(nLwrNew) = lwr; + LM_REVERB(nRwlNew) = rwl; /* Early Echo(Early Reflection) */ tempL0 = - LM_MUL ( LM_REVERB( nEcho0L ), gEcho0 ) + - LM_MUL ( LM_REVERB( nEcho1L ), gEcho1 ) + - LM_MUL ( LM_REVERB( nEcho2L ), gEcho2 ) + - LM_MUL ( LM_REVERB( nEcho3L ), gEcho3 ); + LM_MUL(LM_REVERB(nEcho0L), gEcho0) + + LM_MUL(LM_REVERB(nEcho1L), gEcho1) + + LM_MUL(LM_REVERB(nEcho2L), gEcho2) + + LM_MUL(LM_REVERB(nEcho3L), gEcho3); tempR0 = - LM_MUL ( LM_REVERB( nEcho0R ), gEcho0 ) + - LM_MUL ( LM_REVERB( nEcho1R ), gEcho1 ) + - LM_MUL ( LM_REVERB( nEcho2R ), gEcho2 ) + - LM_MUL ( LM_REVERB( nEcho3R ), gEcho3 ); + LM_MUL(LM_REVERB(nEcho0R), gEcho0) + + LM_MUL(LM_REVERB(nEcho1R), gEcho1) + + LM_MUL(LM_REVERB(nEcho2R), gEcho2) + + LM_MUL(LM_REVERB(nEcho3R), gEcho3); /* Late Reverb */ - tempL1 = LM_REVERB( nRevaOldL ); - tempR1 = LM_REVERB( nRevaOldR ); - tempL0 -= LM_MUL ( tempL1, gReva ); - tempR0 -= LM_MUL ( tempR1, gReva ); - LM_REVERB( nRevaNewL ) = tempL0; - LM_REVERB( nRevaNewR ) = tempR0; - tempL0 = LM_MUL ( tempL0, gReva ) + tempL1; - tempR0 = LM_MUL ( tempR0, gReva ) + tempR1; - tempL1 = LM_REVERB( nRevbOldL ); - tempR1 = LM_REVERB( nRevbOldR ); - tempL0 -= LM_MUL ( tempL1, gRevb ); - tempR0 -= LM_MUL ( tempR1, gRevb ); - LM_REVERB( nRevbNewL ) = tempL0; - LM_REVERB( nRevbNewR ) = tempR0; - tempL0 = LM_MUL ( tempL0, gRevb ) + tempL1; - tempR0 = LM_MUL ( tempR0, gRevb ) + tempR1; + tempL1 = LM_REVERB(nRevaOldL); + tempR1 = LM_REVERB(nRevaOldR); + tempL0 -= LM_MUL(tempL1, gReva); + tempR0 -= LM_MUL(tempR1, gReva); + LM_REVERB(nRevaNewL) = tempL0; + LM_REVERB(nRevaNewR) = tempR0; + tempL0 = LM_MUL(tempL0, gReva) + tempL1; + tempR0 = LM_MUL(tempR0, gReva) + tempR1; + tempL1 = LM_REVERB(nRevbOldL); + tempR1 = LM_REVERB(nRevbOldR); + tempL0 -= LM_MUL(tempL1, gRevb); + tempR0 -= LM_MUL(tempR1, gRevb); + LM_REVERB(nRevbNewL) = tempL0; + LM_REVERB(nRevbNewR) = tempR0; + tempL0 = LM_MUL(tempL0, gRevb) + tempL1; + tempR0 = LM_MUL(tempR0, gRevb) + tempR1; /* Output */ - max|=abs(tempL0); - max|=abs(tempR0); - - p_output[(cSample<<p_stereo_stride)] += tempL0<<8; - p_output[(cSample<<p_stereo_stride) + 1] += tempR0<<8; + max |= abs(tempL0); + max |= abs(tempR0); + p_output[(cSample << p_stereo_stride)] += tempL0 << 8; + p_output[(cSample << p_stereo_stride) + 1] += tempR0 << 8; } // Advance offsets Offset += aSample; - if ( Offset >= reverb_buffer_size ) { Offset -= reverb_buffer_size; } + if (Offset >= reverb_buffer_size) { + Offset -= reverb_buffer_size; + } p_input += aSample << p_stereo_stride; p_output += aSample << p_stereo_stride; @@ -470,100 +463,91 @@ MULSHIFT_S32 ( x, current_params->y, 15 ) state.rwr = rwr; state.Offset = Offset; - return (max&0x7FFFFF00)!=0; // audio was mixed? + return (max & 0x7FFFFF00) != 0; // audio was mixed? } void ReverbSW::adjust_current_params() { - *current_params=*reverb_param_modes[mode]; - - uint32_t maxofs=0; - -#define LM_CONFIG_PARAM( x )\ - current_params->x=(int)( ( (int64_t)current_params->x*(int64_t)mix_rate*8L)/(int64_t)44100);\ - if (current_params->x>maxofs)\ - maxofs=current_params->x; - - - LM_CONFIG_PARAM ( nLwlOld ); - LM_CONFIG_PARAM ( nRwrOld ); - LM_CONFIG_PARAM ( nLwlNew ); - LM_CONFIG_PARAM ( nRwrNew ); - LM_CONFIG_PARAM ( nLwrOld ); - LM_CONFIG_PARAM ( nRwlOld ); - LM_CONFIG_PARAM ( nLwrNew ); - LM_CONFIG_PARAM ( nRwlNew ); - LM_CONFIG_PARAM ( nEcho0L ); - LM_CONFIG_PARAM ( nEcho1L ); - LM_CONFIG_PARAM ( nEcho2L ); - LM_CONFIG_PARAM ( nEcho3L ); - LM_CONFIG_PARAM ( nEcho0R ); - LM_CONFIG_PARAM ( nEcho1R ); - LM_CONFIG_PARAM ( nEcho2R ); - LM_CONFIG_PARAM ( nEcho3R ); - LM_CONFIG_PARAM ( nRevaOldL ); - LM_CONFIG_PARAM ( nRevaOldR ); - LM_CONFIG_PARAM ( nRevbOldL ); - LM_CONFIG_PARAM ( nRevbOldR ); - LM_CONFIG_PARAM ( nRevaNewL ); - LM_CONFIG_PARAM ( nRevaNewR ); - LM_CONFIG_PARAM ( nRevbNewL ); - LM_CONFIG_PARAM ( nRevbNewR ); - - int needed_buffer_size=maxofs+1; + *current_params = *reverb_param_modes[mode]; + + uint32_t maxofs = 0; + +#define LM_CONFIG_PARAM(x) \ + current_params->x = (int)(((int64_t)current_params->x * (int64_t)mix_rate * 8L) / (int64_t)44100); \ + if (current_params->x > maxofs) \ + maxofs = current_params->x; + + LM_CONFIG_PARAM(nLwlOld); + LM_CONFIG_PARAM(nRwrOld); + LM_CONFIG_PARAM(nLwlNew); + LM_CONFIG_PARAM(nRwrNew); + LM_CONFIG_PARAM(nLwrOld); + LM_CONFIG_PARAM(nRwlOld); + LM_CONFIG_PARAM(nLwrNew); + LM_CONFIG_PARAM(nRwlNew); + LM_CONFIG_PARAM(nEcho0L); + LM_CONFIG_PARAM(nEcho1L); + LM_CONFIG_PARAM(nEcho2L); + LM_CONFIG_PARAM(nEcho3L); + LM_CONFIG_PARAM(nEcho0R); + LM_CONFIG_PARAM(nEcho1R); + LM_CONFIG_PARAM(nEcho2R); + LM_CONFIG_PARAM(nEcho3R); + LM_CONFIG_PARAM(nRevaOldL); + LM_CONFIG_PARAM(nRevaOldR); + LM_CONFIG_PARAM(nRevbOldL); + LM_CONFIG_PARAM(nRevbOldR); + LM_CONFIG_PARAM(nRevaNewL); + LM_CONFIG_PARAM(nRevaNewR); + LM_CONFIG_PARAM(nRevbNewL); + LM_CONFIG_PARAM(nRevbNewR); + + int needed_buffer_size = maxofs + 1; if (reverb_buffer) memdelete_arr(reverb_buffer); - reverb_buffer = memnew_arr(int,needed_buffer_size); - reverb_buffer_size=needed_buffer_size; + reverb_buffer = memnew_arr(int, needed_buffer_size); + reverb_buffer_size = needed_buffer_size; - for (uint32_t i=0;i<reverb_buffer_size;i++) - reverb_buffer[i]=0; + for (uint32_t i = 0; i < reverb_buffer_size; i++) + reverb_buffer[i] = 0; state.reset(); - - } void ReverbSW::set_mode(ReverbMode p_mode) { - if (mode==p_mode) + if (mode == p_mode) return; - mode=p_mode; + mode = p_mode; adjust_current_params(); } void ReverbSW::set_mix_rate(int p_mix_rate) { - if (p_mix_rate==mix_rate) + if (p_mix_rate == mix_rate) return; - mix_rate=p_mix_rate; + mix_rate = p_mix_rate; adjust_current_params(); - } - ReverbSW::ReverbSW() { - reverb_buffer=0; - reverb_buffer_size=0; - mode=REVERB_MODE_ROOM; - mix_rate=1; + reverb_buffer = 0; + reverb_buffer_size = 0; + mode = REVERB_MODE_ROOM; + mix_rate = 1; current_params = memnew(ReverbParamsSW); } - ReverbSW::~ReverbSW() { - if (reverb_buffer) memdelete_arr(reverb_buffer); memdelete(current_params); - } - diff --git a/servers/audio/reverb_sw.h b/servers/audio/reverb_sw.h index d9f16a5fbb..06a14322a6 100644 --- a/servers/audio/reverb_sw.h +++ b/servers/audio/reverb_sw.h @@ -29,8 +29,8 @@ #ifndef REVERB_SW_H #define REVERB_SW_H -#include "typedefs.h" #include "os/memory.h" +#include "typedefs.h" class ReverbParamsSW; @@ -55,13 +55,18 @@ private: int rwl; int rwr; unsigned int Offset; - void reset() { lwl=0; lwr=0; rwl=0; rwr=0; Offset=0; } + void reset() { + lwl = 0; + lwr = 0; + rwl = 0; + rwr = 0; + Offset = 0; + } State() { reset(); } } state; ReverbParamsSW *current_params; - int *reverb_buffer; unsigned int reverb_buffer_size; ReverbMode mode; @@ -70,15 +75,12 @@ private: void adjust_current_params(); public: - - void set_mode(ReverbMode p_mode); - bool process(int *p_input,int *p_output,int p_frames,int p_stereo_stride=1); // return tru if audio was created + bool process(int *p_input, int *p_output, int p_frames, int p_stereo_stride = 1); // return tru if audio was created void set_mix_rate(int p_mix_rate); ReverbSW(); ~ReverbSW(); - }; #endif diff --git a/servers/audio/voice_rb_sw.h b/servers/audio/voice_rb_sw.h index cbf1392482..117a62a436 100644 --- a/servers/audio/voice_rb_sw.h +++ b/servers/audio/voice_rb_sw.h @@ -29,13 +29,12 @@ #ifndef VOICE_RB_SW_H #define VOICE_RB_SW_H -#include "servers/audio_server.h" #include "os/os.h" +#include "servers/audio_server.h" class VoiceRBSW { public: - enum { - VOICE_RB_SIZE=1024 + VOICE_RB_SIZE = 1024 }; struct Command { @@ -72,7 +71,7 @@ public: struct { - float pan,depth,height; + float pan, depth, height; } pan; struct { @@ -100,47 +99,42 @@ public: bool positional; } positional; - }; - Command() { type=CMD_NONE; } - + Command() { type = CMD_NONE; } }; -private: +private: Command voice_cmd_rb[VOICE_RB_SIZE]; volatile int read_pos; volatile int write_pos; public: - - _FORCE_INLINE_ bool commands_left() const { return read_pos!=write_pos; } + _FORCE_INLINE_ bool commands_left() const { return read_pos != write_pos; } _FORCE_INLINE_ Command pop_command() { - ERR_FAIL_COND_V( read_pos==write_pos, Command() ); - Command cmd=voice_cmd_rb[read_pos]; - read_pos=(read_pos+1)%VOICE_RB_SIZE; + ERR_FAIL_COND_V(read_pos == write_pos, Command()); + Command cmd = voice_cmd_rb[read_pos]; + read_pos = (read_pos + 1) % VOICE_RB_SIZE; return cmd; } - _FORCE_INLINE_ void push_command(const Command& p_command) { + _FORCE_INLINE_ void push_command(const Command &p_command) { - bool full = ((write_pos+1)%VOICE_RB_SIZE)==read_pos; + bool full = ((write_pos + 1) % VOICE_RB_SIZE) == read_pos; if (full) { #ifdef DEBUG_ENABLED if (OS::get_singleton()->is_stdout_verbose()) { ERR_EXPLAIN("Audio Ring Buffer Full (too many commands"); - ERR_FAIL_COND( ((write_pos+1)%VOICE_RB_SIZE)==read_pos); + ERR_FAIL_COND(((write_pos + 1) % VOICE_RB_SIZE) == read_pos); } #endif return; } - voice_cmd_rb[write_pos]=p_command; - write_pos=(write_pos+1)%VOICE_RB_SIZE; - + voice_cmd_rb[write_pos] = p_command; + write_pos = (write_pos + 1) % VOICE_RB_SIZE; } - VoiceRBSW() { read_pos=write_pos=0; } - + VoiceRBSW() { read_pos = write_pos = 0; } }; #endif // VOICE_RB_SW_H diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp index 192d958a64..5419c5cfe7 100644 --- a/servers/audio_server.cpp +++ b/servers/audio_server.cpp @@ -28,10 +28,10 @@ /*************************************************************************/ #include "audio_server.h" #include "global_config.h" -#include "os/os.h" -#include "servers/audio/effects/audio_effect_compressor.h" #include "io/resource_loader.h" #include "os/file_access.h" +#include "os/os.h" +#include "servers/audio/effects/audio_effect_compressor.h" #ifdef TOOLS_ENABLED #define MARK_EDITED set_edited(true); @@ -42,7 +42,7 @@ #endif -AudioDriver *AudioDriver::singleton=NULL; +AudioDriver *AudioDriver::singleton = NULL; AudioDriver *AudioDriver::get_singleton() { return singleton; @@ -50,51 +50,44 @@ AudioDriver *AudioDriver::get_singleton() { void AudioDriver::set_singleton() { - singleton=this; + singleton = this; } -void AudioDriver::audio_server_process(int p_frames,int32_t *p_buffer,bool p_update_mix_time) { - +void AudioDriver::audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time) { if (p_update_mix_time) update_mix_time(p_frames); if (AudioServer::get_singleton()) - AudioServer::get_singleton()->_driver_process(p_frames,p_buffer); + AudioServer::get_singleton()->_driver_process(p_frames, p_buffer); } - - void AudioDriver::update_mix_time(int p_frames) { - _mix_amount+=p_frames; - _last_mix_time=OS::get_singleton()->get_ticks_usec(); + _mix_amount += p_frames; + _last_mix_time = OS::get_singleton()->get_ticks_usec(); } double AudioDriver::get_mix_time() const { double total = (OS::get_singleton()->get_ticks_usec() - _last_mix_time) / 1000000.0; - total+=_mix_amount/(double)get_mix_rate(); + total += _mix_amount / (double)get_mix_rate(); return total; - } - AudioDriver::AudioDriver() { - _last_mix_time=0; - _mix_amount=0; + _last_mix_time = 0; + _mix_amount = 0; } - AudioDriver *AudioDriverManager::drivers[MAX_DRIVERS]; -int AudioDriverManager::driver_count=0; - +int AudioDriverManager::driver_count = 0; void AudioDriverManager::add_driver(AudioDriver *p_driver) { - ERR_FAIL_COND(driver_count>=MAX_DRIVERS); - drivers[driver_count++]=p_driver; + ERR_FAIL_COND(driver_count >= MAX_DRIVERS); + drivers[driver_count++] = p_driver; } int AudioDriverManager::get_driver_count() { @@ -103,213 +96,197 @@ int AudioDriverManager::get_driver_count() { } AudioDriver *AudioDriverManager::get_driver(int p_driver) { - ERR_FAIL_INDEX_V(p_driver,driver_count,NULL); + ERR_FAIL_INDEX_V(p_driver, driver_count, NULL); return drivers[p_driver]; } - ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////////////////////////////////////// -void AudioServer::_driver_process(int p_frames,int32_t* p_buffer) { +void AudioServer::_driver_process(int p_frames, int32_t *p_buffer) { - int todo=p_frames; + int todo = p_frames; - while(todo) { + while (todo) { - if (to_mix==0) { + if (to_mix == 0) { _mix_step(); } - int to_copy = MIN(to_mix,todo); + int to_copy = MIN(to_mix, todo); Bus *master = buses[0]; - int from = buffer_size-to_mix; - int from_buf=p_frames-todo; + int from = buffer_size - to_mix; + int from_buf = p_frames - todo; //master master, send to output int cs = master->channels.size(); - for(int k=0;k<cs;k++) { + for (int k = 0; k < cs; k++) { if (master->channels[k].active) { AudioFrame *buf = master->channels[k].buffer.ptr(); - for(int j=0;j<to_copy;j++) { + for (int j = 0; j < to_copy; j++) { - float l = CLAMP(buf[from+j].l,-1.0,1.0); - int32_t vl = l*((1<<20)-1); - p_buffer[(from_buf+j)*(cs*2)+k*2+0]=vl<<11; + float l = CLAMP(buf[from + j].l, -1.0, 1.0); + int32_t vl = l * ((1 << 20) - 1); + p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 0] = vl << 11; - float r = CLAMP(buf[from+j].r,-1.0,1.0); - int32_t vr = r*((1<<20)-1); - p_buffer[(from_buf+j)*(cs*2)+k*2+1]=vr<<11; + float r = CLAMP(buf[from + j].r, -1.0, 1.0); + int32_t vr = r * ((1 << 20) - 1); + p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 1] = vr << 11; } } else { - for(int j=0;j<to_copy;j++) { + for (int j = 0; j < to_copy; j++) { - p_buffer[(from_buf+j)*(cs*2)+k*2+0]=0; - p_buffer[(from_buf+j)*(cs*2)+k*2+1]=0; + p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 0] = 0; + p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 1] = 0; } } - } - todo-=to_copy; - to_mix-=to_copy; - + todo -= to_copy; + to_mix -= to_copy; } - } void AudioServer::_mix_step() { - for(int i=0;i<buses.size();i++) { + for (int i = 0; i < buses.size(); i++) { Bus *bus = buses[i]; - bus->index_cache=i; //might be moved around by editor, so.. - for(int k=0;k<bus->channels.size();k++) { + bus->index_cache = i; //might be moved around by editor, so.. + for (int k = 0; k < bus->channels.size(); k++) { - bus->channels[k].used=false; + bus->channels[k].used = false; } } //make callbacks for mixing the audio - for (Set<CallbackItem>::Element *E=callbacks.front();E;E=E->next()) { + for (Set<CallbackItem>::Element *E = callbacks.front(); E; E = E->next()) { E->get().callback(E->get().userdata); } - for(int i=buses.size()-1;i>=0;i--) { + for (int i = buses.size() - 1; i >= 0; i--) { //go bus by bus Bus *bus = buses[i]; - - for(int k=0;k<bus->channels.size();k++) { + for (int k = 0; k < bus->channels.size(); k++) { if (bus->channels[k].active && !bus->channels[k].used) { //buffer was not used, but it's still active, so it must be cleaned AudioFrame *buf = bus->channels[k].buffer.ptr(); - for(uint32_t j=0;j<buffer_size;j++) { + for (uint32_t j = 0; j < buffer_size; j++) { - buf[j]=AudioFrame(0,0); + buf[j] = AudioFrame(0, 0); } } - } - //process effects - for(int j=0;j<bus->effects.size();j++) { + for (int j = 0; j < bus->effects.size(); j++) { if (!bus->effects[j].enabled) continue; - for(int k=0;k<bus->channels.size();k++) { + for (int k = 0; k < bus->channels.size(); k++) { if (!bus->channels[k].active) continue; - bus->channels[k].effect_instances[j]->process(bus->channels[k].buffer.ptr(),temp_buffer[k].ptr(),buffer_size); + bus->channels[k].effect_instances[j]->process(bus->channels[k].buffer.ptr(), temp_buffer[k].ptr(), buffer_size); } //swap buffers, so internal buffer always has the right data - for(int k=0;k<bus->channels.size();k++) { + for (int k = 0; k < bus->channels.size(); k++) { if (!buses[i]->channels[k].active) continue; - SWAP(bus->channels[k].buffer,temp_buffer[k]); + SWAP(bus->channels[k].buffer, temp_buffer[k]); } } //process send - Bus *send=NULL; + Bus *send = NULL; - if (i>0) { + if (i > 0) { //everything has a send save for master bus if (!bus_map.has(bus->send)) { - send=buses[0]; + send = buses[0]; } else { - send=bus_map[bus->send]; - if (send->index_cache>=bus->index_cache) { //invalid, send to master - send=buses[0]; + send = bus_map[bus->send]; + if (send->index_cache >= bus->index_cache) { //invalid, send to master + send = buses[0]; } } } - - for(int k=0;k<bus->channels.size();k++) { + for (int k = 0; k < bus->channels.size(); k++) { if (!bus->channels[k].active) continue; AudioFrame *buf = bus->channels[k].buffer.ptr(); - - AudioFrame peak = AudioFrame(0,0); - for(uint32_t j=0;j<buffer_size;j++) { + AudioFrame peak = AudioFrame(0, 0); + for (uint32_t j = 0; j < buffer_size; j++) { float l = ABS(buf[j].l); - if (l>peak.l) { - peak.l=l; + if (l > peak.l) { + peak.l = l; } float r = ABS(buf[j].r); - if (r>peak.r) { - peak.r=r; + if (r > peak.r) { + peak.r = r; } } - bus->channels[k].peak_volume=AudioFrame(Math::linear2db(peak.l+0.0000000001),Math::linear2db(peak.r+0.0000000001)); - + bus->channels[k].peak_volume = AudioFrame(Math::linear2db(peak.l + 0.0000000001), Math::linear2db(peak.r + 0.0000000001)); if (!bus->channels[k].used) { //see if any audio is contained, because channel was not used - - if (MAX(peak.r,peak.l) > Math::db2linear(channel_disable_treshold_db)) { - bus->channels[k].last_mix_with_audio=mix_frames; - } else if (mix_frames-bus->channels[k].last_mix_with_audio > channel_disable_frames ) { - bus->channels[k].active=false; + if (MAX(peak.r, peak.l) > Math::db2linear(channel_disable_treshold_db)) { + bus->channels[k].last_mix_with_audio = mix_frames; + } else if (mix_frames - bus->channels[k].last_mix_with_audio > channel_disable_frames) { + bus->channels[k].active = false; continue; //went inactive, dont mix. } } if (send) { //if not master bus, send - AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache,k); + AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache, k); - for(uint32_t j=0;j<buffer_size;j++) { - target_buf[j]+=buf[j]; + for (uint32_t j = 0; j < buffer_size; j++) { + target_buf[j] += buf[j]; } } - } - } - - mix_frames+=buffer_size; - to_mix=buffer_size; - + mix_frames += buffer_size; + to_mix = buffer_size; } -AudioFrame *AudioServer::thread_get_channel_mix_buffer(int p_bus,int p_buffer) { +AudioFrame *AudioServer::thread_get_channel_mix_buffer(int p_bus, int p_buffer) { - ERR_FAIL_INDEX_V(p_bus,buses.size(),NULL); - ERR_FAIL_INDEX_V(p_buffer,buses[p_bus]->channels.size(),NULL); + ERR_FAIL_INDEX_V(p_bus, buses.size(), NULL); + ERR_FAIL_INDEX_V(p_buffer, buses[p_bus]->channels.size(), NULL); AudioFrame *data = buses[p_bus]->channels[p_buffer].buffer.ptr(); - if (!buses[p_bus]->channels[p_buffer].used) { - buses[p_bus]->channels[p_buffer].used=true; - buses[p_bus]->channels[p_buffer].active=true; - buses[p_bus]->channels[p_buffer].last_mix_with_audio=mix_frames; - for(uint32_t i=0;i<buffer_size;i++) { - data[i]=AudioFrame(0,0); + buses[p_bus]->channels[p_buffer].used = true; + buses[p_bus]->channels[p_buffer].active = true; + buses[p_bus]->channels[p_buffer].last_mix_with_audio = mix_frames; + for (uint32_t i = 0; i < buffer_size; i++) { + data[i] = AudioFrame(0, 0); } } @@ -321,28 +298,27 @@ int AudioServer::thread_get_mix_buffer_size() const { return buffer_size; } -int AudioServer::thread_find_bus_index(const StringName& p_name) { +int AudioServer::thread_find_bus_index(const StringName &p_name) { if (bus_map.has(p_name)) { return bus_map[p_name]->index_cache; } else { return 0; } - } void AudioServer::set_bus_count(int p_count) { - ERR_FAIL_COND(p_count<1); - ERR_FAIL_INDEX(p_count,256); + ERR_FAIL_COND(p_count < 1); + ERR_FAIL_INDEX(p_count, 256); MARK_EDITED lock(); int cb = buses.size(); - if (p_count<buses.size()) { - for(int i=p_count;i<buses.size();i++) { + if (p_count < buses.size()) { + for (int i = p_count; i < buses.size(); i++) { bus_map.erase(buses[i]->name); memdelete(buses[i]); } @@ -350,47 +326,44 @@ void AudioServer::set_bus_count(int p_count) { buses.resize(p_count); - for(int i=cb;i<buses.size();i++) { + for (int i = cb; i < buses.size(); i++) { - String attempt="New Bus"; - int attempts=1; - while(true) { + String attempt = "New Bus"; + int attempts = 1; + while (true) { - bool name_free=true; - for(int j=0;j<i;j++) { + bool name_free = true; + for (int j = 0; j < i; j++) { - if (buses[j]->name==attempt) { - name_free=false; + if (buses[j]->name == attempt) { + name_free = false; break; } } if (!name_free) { attempts++; - attempt="New Bus " +itos(attempts); + attempt = "New Bus " + itos(attempts); } else { break; } - } - - buses[i]=memnew(Bus); + buses[i] = memnew(Bus); buses[i]->channels.resize(_get_channel_count()); - for(int j=0;j<_get_channel_count();j++) { + for (int j = 0; j < _get_channel_count(); j++) { buses[i]->channels[j].buffer.resize(buffer_size); } - buses[i]->name=attempt; - buses[i]->solo=false; - buses[i]->mute=false; - buses[i]->bypass=false; - buses[i]->volume_db=0; - if (i>0) { - buses[i]->send="Master"; + buses[i]->name = attempt; + buses[i]->solo = false; + buses[i]->mute = false; + buses[i]->bypass = false; + buses[i]->volume_db = 0; + if (i > 0) { + buses[i]->send = "Master"; } - bus_map[attempt]=buses[i]; - + bus_map[attempt] = buses[i]; } unlock(); @@ -398,11 +371,10 @@ void AudioServer::set_bus_count(int p_count) { emit_signal("bus_layout_changed"); } - void AudioServer::remove_bus(int p_index) { - ERR_FAIL_INDEX(p_index,buses.size()); - ERR_FAIL_COND(p_index==0); + ERR_FAIL_INDEX(p_index, buses.size()); + ERR_FAIL_COND(p_index == 0); MARK_EDITED @@ -417,76 +389,74 @@ void AudioServer::add_bus(int p_at_pos) { MARK_EDITED - if (p_at_pos>=buses.size()) { - p_at_pos=-1; - } else if (p_at_pos==0) { - if (buses.size()>1) - p_at_pos=1; + if (p_at_pos >= buses.size()) { + p_at_pos = -1; + } else if (p_at_pos == 0) { + if (buses.size() > 1) + p_at_pos = 1; else - p_at_pos=-1; + p_at_pos = -1; } - String attempt="New Bus"; - int attempts=1; - while(true) { + String attempt = "New Bus"; + int attempts = 1; + while (true) { - bool name_free=true; - for(int j=0;j<buses.size();j++) { + bool name_free = true; + for (int j = 0; j < buses.size(); j++) { - if (buses[j]->name==attempt) { - name_free=false; + if (buses[j]->name == attempt) { + name_free = false; break; } } if (!name_free) { attempts++; - attempt="New Bus " +itos(attempts); + attempt = "New Bus " + itos(attempts); } else { break; } - } - Bus* bus =memnew(Bus); + Bus *bus = memnew(Bus); bus->channels.resize(_get_channel_count()); - for(int j=0;j<_get_channel_count();j++) { + for (int j = 0; j < _get_channel_count(); j++) { bus->channels[j].buffer.resize(buffer_size); } - bus->name=attempt; - bus->solo=false; - bus->mute=false; - bus->bypass=false; - bus->volume_db=0; + bus->name = attempt; + bus->solo = false; + bus->mute = false; + bus->bypass = false; + bus->volume_db = 0; - bus_map[attempt]=bus; + bus_map[attempt] = bus; - if (p_at_pos==-1) + if (p_at_pos == -1) buses.push_back(bus); else - buses.insert(p_at_pos,bus); - + buses.insert(p_at_pos, bus); } -void AudioServer::move_bus(int p_bus,int p_to_pos) { +void AudioServer::move_bus(int p_bus, int p_to_pos) { - ERR_FAIL_COND(p_bus<1 || p_bus>=buses.size()); - ERR_FAIL_COND(p_to_pos!=-1 && (p_to_pos<1 || p_to_pos>buses.size())); + ERR_FAIL_COND(p_bus < 1 || p_bus >= buses.size()); + ERR_FAIL_COND(p_to_pos != -1 && (p_to_pos < 1 || p_to_pos > buses.size())); MARK_EDITED - if (p_bus==p_to_pos) + if (p_bus == p_to_pos) return; Bus *bus = buses[p_bus]; buses.remove(p_bus); - if (p_to_pos==-1) { + if (p_to_pos == -1) { buses.push_back(bus); - } else if (p_to_pos<p_bus) { - buses.insert(p_to_pos,bus); + } else if (p_to_pos < p_bus) { + buses.insert(p_to_pos, bus); } else { - buses.insert(p_to_pos-1,bus); + buses.insert(p_to_pos - 1, bus); } } @@ -495,32 +465,31 @@ int AudioServer::get_bus_count() const { return buses.size(); } +void AudioServer::set_bus_name(int p_bus, const String &p_name) { -void AudioServer::set_bus_name(int p_bus,const String& p_name) { - - ERR_FAIL_INDEX(p_bus,buses.size()); - if (p_bus==0 && p_name!="Master") + ERR_FAIL_INDEX(p_bus, buses.size()); + if (p_bus == 0 && p_name != "Master") return; //bus 0 is always master MARK_EDITED lock(); - if (buses[p_bus]->name==p_name) { + if (buses[p_bus]->name == p_name) { unlock(); return; } - String attempt=p_name; - int attempts=1; + String attempt = p_name; + int attempts = 1; - while(true) { + while (true) { - bool name_free=true; - for(int i=0;i<buses.size();i++) { + bool name_free = true; + for (int i = 0; i < buses.size(); i++) { - if (buses[i]->name==attempt) { - name_free=false; + if (buses[i]->name == attempt) { + name_free = false; break; } } @@ -530,142 +499,128 @@ void AudioServer::set_bus_name(int p_bus,const String& p_name) { } attempts++; - attempt=p_name+" "+itos(attempts); + attempt = p_name + " " + itos(attempts); } bus_map.erase(buses[p_bus]->name); - buses[p_bus]->name=attempt; - bus_map[attempt]=buses[p_bus]; + buses[p_bus]->name = attempt; + bus_map[attempt] = buses[p_bus]; unlock(); emit_signal("bus_layout_changed"); - } String AudioServer::get_bus_name(int p_bus) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),String()); + ERR_FAIL_INDEX_V(p_bus, buses.size(), String()); return buses[p_bus]->name; } -void AudioServer::set_bus_volume_db(int p_bus,float p_volume_db) { +void AudioServer::set_bus_volume_db(int p_bus, float p_volume_db) { - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - buses[p_bus]->volume_db=p_volume_db; - + buses[p_bus]->volume_db = p_volume_db; } float AudioServer::get_bus_volume_db(int p_bus) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),0); + ERR_FAIL_INDEX_V(p_bus, buses.size(), 0); return buses[p_bus]->volume_db; - } -void AudioServer::set_bus_send(int p_bus,const StringName& p_send) { +void AudioServer::set_bus_send(int p_bus, const StringName &p_send) { - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - buses[p_bus]->send=p_send; - + buses[p_bus]->send = p_send; } StringName AudioServer::get_bus_send(int p_bus) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),StringName()); + ERR_FAIL_INDEX_V(p_bus, buses.size(), StringName()); return buses[p_bus]->send; - } +void AudioServer::set_bus_solo(int p_bus, bool p_enable) { -void AudioServer::set_bus_solo(int p_bus,bool p_enable) { - - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - buses[p_bus]->solo=p_enable; - + buses[p_bus]->solo = p_enable; } -bool AudioServer::is_bus_solo(int p_bus) const{ +bool AudioServer::is_bus_solo(int p_bus) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + ERR_FAIL_INDEX_V(p_bus, buses.size(), false); return buses[p_bus]->solo; - } -void AudioServer::set_bus_mute(int p_bus,bool p_enable){ +void AudioServer::set_bus_mute(int p_bus, bool p_enable) { - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - buses[p_bus]->mute=p_enable; + buses[p_bus]->mute = p_enable; } -bool AudioServer::is_bus_mute(int p_bus) const{ +bool AudioServer::is_bus_mute(int p_bus) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + ERR_FAIL_INDEX_V(p_bus, buses.size(), false); return buses[p_bus]->mute; - } -void AudioServer::set_bus_bypass_effects(int p_bus,bool p_enable){ +void AudioServer::set_bus_bypass_effects(int p_bus, bool p_enable) { - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - buses[p_bus]->bypass=p_enable; + buses[p_bus]->bypass = p_enable; } -bool AudioServer::is_bus_bypassing_effects(int p_bus) const{ +bool AudioServer::is_bus_bypassing_effects(int p_bus) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),false); + ERR_FAIL_INDEX_V(p_bus, buses.size(), false); return buses[p_bus]->bypass; - } - void AudioServer::_update_bus_effects(int p_bus) { - for(int i=0;i<buses[p_bus]->channels.size();i++) { + for (int i = 0; i < buses[p_bus]->channels.size(); i++) { buses[p_bus]->channels[i].effect_instances.resize(buses[p_bus]->effects.size()); - for(int j=0;j<buses[p_bus]->effects.size();j++) { + for (int j = 0; j < buses[p_bus]->effects.size(); j++) { Ref<AudioEffectInstance> fx = buses[p_bus]->effects[j].effect->instance(); if (fx->cast_to<AudioEffectCompressorInstance>()) { fx->cast_to<AudioEffectCompressorInstance>()->set_current_channel(i); } - buses[p_bus]->channels[i].effect_instances[j]=fx; - + buses[p_bus]->channels[i].effect_instances[j] = fx; } } } - -void AudioServer::add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int p_at_pos) { +void AudioServer::add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos) { ERR_FAIL_COND(p_effect.is_null()); - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - lock(); Bus::Effect fx; - fx.effect=p_effect; + fx.effect = p_effect; //fx.instance=p_effect->instance(); - fx.enabled=true; + fx.enabled = true; - if (p_at_pos>=buses[p_bus]->effects.size() || p_at_pos<0) { + if (p_at_pos >= buses[p_bus]->effects.size() || p_at_pos < 0) { buses[p_bus]->effects.push_back(fx); } else { - buses[p_bus]->effects.insert(p_at_pos,fx); + buses[p_bus]->effects.insert(p_at_pos, fx); } _update_bus_effects(p_bus); @@ -673,14 +628,12 @@ void AudioServer::add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int unlock(); } +void AudioServer::remove_bus_effect(int p_bus, int p_effect) { -void AudioServer::remove_bus_effect(int p_bus,int p_effect) { - - ERR_FAIL_INDEX(p_bus,buses.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); MARK_EDITED - lock(); buses[p_bus]->effects.remove(p_effect); @@ -691,88 +644,78 @@ void AudioServer::remove_bus_effect(int p_bus,int p_effect) { int AudioServer::get_bus_effect_count(int p_bus) { - ERR_FAIL_INDEX_V(p_bus,buses.size(),0); + ERR_FAIL_INDEX_V(p_bus, buses.size(), 0); return buses[p_bus]->effects.size(); - } -Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus,int p_effect) { +Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus, int p_effect) { - ERR_FAIL_INDEX_V(p_bus,buses.size(),Ref<AudioEffect>()); - ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),Ref<AudioEffect>()); + ERR_FAIL_INDEX_V(p_bus, buses.size(), Ref<AudioEffect>()); + ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), Ref<AudioEffect>()); return buses[p_bus]->effects[p_effect].effect; - } -void AudioServer::swap_bus_effects(int p_bus,int p_effect,int p_by_effect) { +void AudioServer::swap_bus_effects(int p_bus, int p_effect, int p_by_effect) { - ERR_FAIL_INDEX(p_bus,buses.size()); - ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size()); - ERR_FAIL_INDEX(p_by_effect,buses[p_bus]->effects.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); + ERR_FAIL_INDEX(p_effect, buses[p_bus]->effects.size()); + ERR_FAIL_INDEX(p_by_effect, buses[p_bus]->effects.size()); MARK_EDITED - lock(); - SWAP( buses[p_bus]->effects[p_effect], buses[p_bus]->effects[p_by_effect] ); + SWAP(buses[p_bus]->effects[p_effect], buses[p_bus]->effects[p_by_effect]); _update_bus_effects(p_bus); unlock(); } -void AudioServer::set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled) { +void AudioServer::set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled) { - ERR_FAIL_INDEX(p_bus,buses.size()); - ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size()); + ERR_FAIL_INDEX(p_bus, buses.size()); + ERR_FAIL_INDEX(p_effect, buses[p_bus]->effects.size()); MARK_EDITED - - buses[p_bus]->effects[p_effect].enabled=p_enabled; - + buses[p_bus]->effects[p_effect].enabled = p_enabled; } -bool AudioServer::is_bus_effect_enabled(int p_bus,int p_effect) const { +bool AudioServer::is_bus_effect_enabled(int p_bus, int p_effect) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),false); - ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),false); + ERR_FAIL_INDEX_V(p_bus, buses.size(), false); + ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), false); return buses[p_bus]->effects[p_effect].enabled; - } +float AudioServer::get_bus_peak_volume_left_db(int p_bus, int p_channel) const { -float AudioServer::get_bus_peak_volume_left_db(int p_bus,int p_channel) const { - - ERR_FAIL_INDEX_V(p_bus,buses.size(),0); - ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0); + ERR_FAIL_INDEX_V(p_bus, buses.size(), 0); + ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), 0); return buses[p_bus]->channels[p_channel].peak_volume.l; - } -float AudioServer::get_bus_peak_volume_right_db(int p_bus,int p_channel) const { +float AudioServer::get_bus_peak_volume_right_db(int p_bus, int p_channel) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),0); - ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0); + ERR_FAIL_INDEX_V(p_bus, buses.size(), 0); + ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), 0); return buses[p_bus]->channels[p_channel].peak_volume.r; - } -bool AudioServer::is_bus_channel_active(int p_bus,int p_channel) const { +bool AudioServer::is_bus_channel_active(int p_bus, int p_channel) const { - ERR_FAIL_INDEX_V(p_bus,buses.size(),false); - ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),false); + ERR_FAIL_INDEX_V(p_bus, buses.size(), false); + ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), false); return buses[p_bus]->channels[p_channel].active; - } void AudioServer::init() { - channel_disable_treshold_db=GLOBAL_DEF("audio/channel_disable_treshold_db",-60.0); - channel_disable_frames=float(GLOBAL_DEF("audio/channel_disable_time",2.0))*get_mix_rate(); - buffer_size=1024; //harcoded for now - switch( get_speaker_mode() ) { + channel_disable_treshold_db = GLOBAL_DEF("audio/channel_disable_treshold_db", -60.0); + channel_disable_frames = float(GLOBAL_DEF("audio/channel_disable_time", 2.0)) * get_mix_rate(); + buffer_size = 1024; //harcoded for now + switch (get_speaker_mode()) { case SPEAKER_MODE_STEREO: { temp_buffer.resize(1); } break; @@ -784,21 +727,20 @@ void AudioServer::init() { } break; } - for(int i=0;i<temp_buffer.size();i++) { + for (int i = 0; i < temp_buffer.size(); i++) { temp_buffer[i].resize(buffer_size); } - mix_count=0; - set_bus_count(1);; - set_bus_name(0,"Master"); - + mix_count = 0; + set_bus_count(1); + ; + set_bus_name(0, "Master"); if (AudioDriver::get_singleton()) AudioDriver::get_singleton()->start(); #ifdef TOOLS_ENABLED set_edited(false); //avoid editors from thinking this was edited #endif - } void AudioServer::load_default_bus_layout() { @@ -809,20 +751,17 @@ void AudioServer::load_default_bus_layout() { set_bus_layout(default_layout); } } - } void AudioServer::finish() { - for(int i=0;i<buses.size();i++) { + for (int i = 0; i < buses.size(); i++) { memdelete(buses[i]); } buses.clear(); } void AudioServer::update() { - - } /* MISC config */ @@ -834,11 +773,9 @@ void AudioServer::lock() { void AudioServer::unlock() { AudioDriver::get_singleton()->unlock(); - } - -AudioServer::SpeakerMode AudioServer::get_speaker_mode() const { +AudioServer::SpeakerMode AudioServer::get_speaker_mode() const { return (AudioServer::SpeakerMode)AudioDriver::get_singleton()->get_speaker_mode(); } @@ -866,29 +803,26 @@ double AudioServer::get_output_delay() const { return 0; } -AudioServer* AudioServer::singleton=NULL; - - - +AudioServer *AudioServer::singleton = NULL; -void* AudioServer::audio_data_alloc(uint32_t p_data_len,const uint8_t *p_from_data) { +void *AudioServer::audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data) { - void * ad = memalloc( p_data_len ); - ERR_FAIL_COND_V(!ad,NULL); + void *ad = memalloc(p_data_len); + ERR_FAIL_COND_V(!ad, NULL); if (p_from_data) { - copymem(ad,p_from_data,p_data_len); + copymem(ad, p_from_data, p_data_len); } audio_data_lock->lock(); - audio_data[ad]=p_data_len; - audio_data_total_mem+=p_data_len; - audio_data_max_mem=MAX(audio_data_total_mem,audio_data_max_mem); + audio_data[ad] = p_data_len; + audio_data_total_mem += p_data_len; + audio_data_max_mem = MAX(audio_data_total_mem, audio_data_max_mem); audio_data_lock->unlock(); return ad; } -void AudioServer::audio_data_free(void* p_data) { +void AudioServer::audio_data_free(void *p_data) { audio_data_lock->lock(); if (!audio_data.has(p_data)) { @@ -896,86 +830,82 @@ void AudioServer::audio_data_free(void* p_data) { ERR_FAIL(); } - audio_data_total_mem-=audio_data[p_data]; + audio_data_total_mem -= audio_data[p_data]; audio_data.erase(p_data); memfree(p_data); audio_data_lock->unlock(); - - } -size_t AudioServer::audio_data_get_total_memory_usage() const{ +size_t AudioServer::audio_data_get_total_memory_usage() const { return audio_data_total_mem; } -size_t AudioServer::audio_data_get_max_memory_usage() const{ +size_t AudioServer::audio_data_get_max_memory_usage() const { return audio_data_max_mem; - } -void AudioServer::add_callback(AudioCallback p_callback,void *p_userdata) { +void AudioServer::add_callback(AudioCallback p_callback, void *p_userdata) { lock(); CallbackItem ci; - ci.callback=p_callback; - ci.userdata=p_userdata; + ci.callback = p_callback; + ci.userdata = p_userdata; callbacks.insert(ci); unlock(); } -void AudioServer::remove_callback(AudioCallback p_callback,void *p_userdata) { +void AudioServer::remove_callback(AudioCallback p_callback, void *p_userdata) { lock(); CallbackItem ci; - ci.callback=p_callback; - ci.userdata=p_userdata; + ci.callback = p_callback; + ci.userdata = p_userdata; callbacks.erase(ci); unlock(); - } void AudioServer::set_bus_layout(const Ref<AudioBusLayout> &p_state) { - ERR_FAIL_COND(p_state.is_null() || p_state->buses.size()==0); + ERR_FAIL_COND(p_state.is_null() || p_state->buses.size() == 0); lock(); - for(int i=0;i<buses.size();i++) { + for (int i = 0; i < buses.size(); i++) { memdelete(buses[i]); } buses.resize(p_state->buses.size()); bus_map.clear(); - for(int i=0;i<p_state->buses.size();i++) { - Bus * bus = memnew(Bus); - if (i==0) { - bus->name="Master"; + for (int i = 0; i < p_state->buses.size(); i++) { + Bus *bus = memnew(Bus); + if (i == 0) { + bus->name = "Master"; } else { - bus->name=p_state->buses[i].name; - bus->send=p_state->buses[i].send; + bus->name = p_state->buses[i].name; + bus->send = p_state->buses[i].send; } - bus->solo=p_state->buses[i].solo; - bus->mute=p_state->buses[i].mute; - bus->bypass=p_state->buses[i].bypass; - bus->volume_db=p_state->buses[i].volume_db; + bus->solo = p_state->buses[i].solo; + bus->mute = p_state->buses[i].mute; + bus->bypass = p_state->buses[i].bypass; + bus->volume_db = p_state->buses[i].volume_db; - for(int j=0;j<p_state->buses[i].effects.size();j++) { + for (int j = 0; j < p_state->buses[i].effects.size(); j++) { Ref<AudioEffect> fx = p_state->buses[i].effects[j].effect; if (fx.is_valid()) { Bus::Effect bfx; - bfx.effect=fx; - bfx.enabled=p_state->buses[i].effects[j].enabled; + bfx.effect = fx; + bfx.enabled = p_state->buses[i].effects[j].enabled; bus->effects.push_back(bfx); } } - bus_map[bus->name]=bus; - buses[i]=bus; + bus_map[bus->name] = bus; + buses[i] = bus; buses[i]->channels.resize(_get_channel_count()); - for(int j=0;j<_get_channel_count();j++) { + for (int j = 0; j < _get_channel_count(); j++) { buses[i]->channels[j].buffer.resize(buffer_size); } _update_bus_effects(i); @@ -984,100 +914,94 @@ void AudioServer::set_bus_layout(const Ref<AudioBusLayout> &p_state) { set_edited(false); #endif unlock(); - } - Ref<AudioBusLayout> AudioServer::generate_bus_layout() const { Ref<AudioBusLayout> state; state.instance(); - state->buses.resize( buses.size() ); + state->buses.resize(buses.size()); - for(int i=0;i<buses.size();i++) { + for (int i = 0; i < buses.size(); i++) { - state->buses[i].name=buses[i]->name; - state->buses[i].send=buses[i]->send; - state->buses[i].mute=buses[i]->mute; - state->buses[i].solo=buses[i]->solo; - state->buses[i].bypass=buses[i]->bypass; - state->buses[i].volume_db=buses[i]->volume_db; - for(int j=0;j<buses[i]->effects.size();j++) { + state->buses[i].name = buses[i]->name; + state->buses[i].send = buses[i]->send; + state->buses[i].mute = buses[i]->mute; + state->buses[i].solo = buses[i]->solo; + state->buses[i].bypass = buses[i]->bypass; + state->buses[i].volume_db = buses[i]->volume_db; + for (int j = 0; j < buses[i]->effects.size(); j++) { AudioBusLayout::Bus::Effect fx; - fx.effect=buses[i]->effects[j].effect; - fx.enabled=buses[i]->effects[j].enabled; + fx.effect = buses[i]->effects[j].effect; + fx.enabled = buses[i]->effects[j].enabled; state->buses[i].effects.push_back(fx); - } } return state; } - void AudioServer::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_bus_count", "amount"), &AudioServer::set_bus_count); + ClassDB::bind_method(D_METHOD("get_bus_count"), &AudioServer::get_bus_count); - ClassDB::bind_method(D_METHOD("set_bus_count","amount"),&AudioServer::set_bus_count); - ClassDB::bind_method(D_METHOD("get_bus_count"),&AudioServer::get_bus_count); + ClassDB::bind_method(D_METHOD("remove_bus", "index"), &AudioServer::remove_bus); + ClassDB::bind_method(D_METHOD("add_bus", "at_pos"), &AudioServer::add_bus, DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("move_bus", "index", "to_index"), &AudioServer::move_bus); - ClassDB::bind_method(D_METHOD("remove_bus","index"),&AudioServer::remove_bus); - ClassDB::bind_method(D_METHOD("add_bus","at_pos"),&AudioServer::add_bus,DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("move_bus","index","to_index"),&AudioServer::move_bus); + ClassDB::bind_method(D_METHOD("set_bus_name", "bus_idx", "name"), &AudioServer::set_bus_name); + ClassDB::bind_method(D_METHOD("get_bus_name", "bus_idx"), &AudioServer::get_bus_name); - ClassDB::bind_method(D_METHOD("set_bus_name","bus_idx","name"),&AudioServer::set_bus_name); - ClassDB::bind_method(D_METHOD("get_bus_name","bus_idx"),&AudioServer::get_bus_name); + ClassDB::bind_method(D_METHOD("set_bus_volume_db", "bus_idx", "volume_db"), &AudioServer::set_bus_volume_db); + ClassDB::bind_method(D_METHOD("get_bus_volume_db", "bus_idx"), &AudioServer::get_bus_volume_db); - ClassDB::bind_method(D_METHOD("set_bus_volume_db","bus_idx","volume_db"),&AudioServer::set_bus_volume_db); - ClassDB::bind_method(D_METHOD("get_bus_volume_db","bus_idx"),&AudioServer::get_bus_volume_db); + ClassDB::bind_method(D_METHOD("set_bus_send", "bus_idx", "send"), &AudioServer::set_bus_send); + ClassDB::bind_method(D_METHOD("get_bus_send", "bus_idx"), &AudioServer::get_bus_send); - ClassDB::bind_method(D_METHOD("set_bus_send","bus_idx","send"),&AudioServer::set_bus_send); - ClassDB::bind_method(D_METHOD("get_bus_send","bus_idx"),&AudioServer::get_bus_send); + ClassDB::bind_method(D_METHOD("set_bus_solo", "bus_idx", "enable"), &AudioServer::set_bus_solo); + ClassDB::bind_method(D_METHOD("is_bus_solo", "bus_idx"), &AudioServer::is_bus_solo); - ClassDB::bind_method(D_METHOD("set_bus_solo","bus_idx","enable"),&AudioServer::set_bus_solo); - ClassDB::bind_method(D_METHOD("is_bus_solo","bus_idx"),&AudioServer::is_bus_solo); + ClassDB::bind_method(D_METHOD("set_bus_mute", "bus_idx", "enable"), &AudioServer::set_bus_mute); + ClassDB::bind_method(D_METHOD("is_bus_mute", "bus_idx"), &AudioServer::is_bus_mute); - ClassDB::bind_method(D_METHOD("set_bus_mute","bus_idx","enable"),&AudioServer::set_bus_mute); - ClassDB::bind_method(D_METHOD("is_bus_mute","bus_idx"),&AudioServer::is_bus_mute); + ClassDB::bind_method(D_METHOD("set_bus_bypass_effects", "bus_idx", "enable"), &AudioServer::set_bus_bypass_effects); + ClassDB::bind_method(D_METHOD("is_bus_bypassing_effects", "bus_idx"), &AudioServer::is_bus_bypassing_effects); - ClassDB::bind_method(D_METHOD("set_bus_bypass_effects","bus_idx","enable"),&AudioServer::set_bus_bypass_effects); - ClassDB::bind_method(D_METHOD("is_bus_bypassing_effects","bus_idx"),&AudioServer::is_bus_bypassing_effects); + ClassDB::bind_method(D_METHOD("add_bus_effect", "bus_idx", "effect:AudioEffect"), &AudioServer::add_bus_effect, DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("remove_bus_effect", "bus_idx", "effect_idx"), &AudioServer::remove_bus_effect); - ClassDB::bind_method(D_METHOD("add_bus_effect","bus_idx","effect:AudioEffect"),&AudioServer::add_bus_effect,DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("remove_bus_effect","bus_idx","effect_idx"),&AudioServer::remove_bus_effect); + ClassDB::bind_method(D_METHOD("get_bus_effect_count", "bus_idx"), &AudioServer::add_bus_effect); + ClassDB::bind_method(D_METHOD("get_bus_effect:AudioEffect", "bus_idx", "effect_idx"), &AudioServer::get_bus_effect); + ClassDB::bind_method(D_METHOD("swap_bus_effects", "bus_idx", "effect_idx", "by_effect_idx"), &AudioServer::swap_bus_effects); - ClassDB::bind_method(D_METHOD("get_bus_effect_count","bus_idx"),&AudioServer::add_bus_effect); - ClassDB::bind_method(D_METHOD("get_bus_effect:AudioEffect","bus_idx","effect_idx"),&AudioServer::get_bus_effect); - ClassDB::bind_method(D_METHOD("swap_bus_effects","bus_idx","effect_idx","by_effect_idx"),&AudioServer::swap_bus_effects); + ClassDB::bind_method(D_METHOD("set_bus_effect_enabled", "bus_idx", "effect_idx", "enabled"), &AudioServer::set_bus_effect_enabled); + ClassDB::bind_method(D_METHOD("is_bus_effect_enabled", "bus_idx", "effect_idx"), &AudioServer::is_bus_effect_enabled); - ClassDB::bind_method(D_METHOD("set_bus_effect_enabled","bus_idx","effect_idx","enabled"),&AudioServer::set_bus_effect_enabled); - ClassDB::bind_method(D_METHOD("is_bus_effect_enabled","bus_idx","effect_idx"),&AudioServer::is_bus_effect_enabled); + ClassDB::bind_method(D_METHOD("get_bus_peak_volume_left_db", "bus_idx", "channel"), &AudioServer::get_bus_peak_volume_left_db); + ClassDB::bind_method(D_METHOD("get_bus_peak_volume_right_db", "bus_idx", "channel"), &AudioServer::get_bus_peak_volume_right_db); - ClassDB::bind_method(D_METHOD("get_bus_peak_volume_left_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_left_db); - ClassDB::bind_method(D_METHOD("get_bus_peak_volume_right_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_right_db); + ClassDB::bind_method(D_METHOD("lock"), &AudioServer::lock); + ClassDB::bind_method(D_METHOD("unlock"), &AudioServer::unlock); - ClassDB::bind_method(D_METHOD("lock"),&AudioServer::lock); - ClassDB::bind_method(D_METHOD("unlock"),&AudioServer::unlock); + ClassDB::bind_method(D_METHOD("get_speaker_mode"), &AudioServer::get_speaker_mode); + ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioServer::get_mix_rate); - ClassDB::bind_method(D_METHOD("get_speaker_mode"),&AudioServer::get_speaker_mode); - ClassDB::bind_method(D_METHOD("get_mix_rate"),&AudioServer::get_mix_rate); + ClassDB::bind_method(D_METHOD("set_state", "state:AudioServerState"), &AudioServer::set_bus_layout); + ClassDB::bind_method(D_METHOD("generate_state:AudioServerState"), &AudioServer::generate_bus_layout); - ClassDB::bind_method(D_METHOD("set_state","state:AudioServerState"),&AudioServer::set_bus_layout); - ClassDB::bind_method(D_METHOD("generate_state:AudioServerState"),&AudioServer::generate_bus_layout); - - ADD_SIGNAL(MethodInfo("bus_layout_changed") ); + ADD_SIGNAL(MethodInfo("bus_layout_changed")); } AudioServer::AudioServer() { - singleton=this; - audio_data_total_mem=0; - audio_data_max_mem=0; - audio_data_lock=Mutex::create(); - mix_frames=0; - to_mix=0; - + singleton = this; + audio_data_total_mem = 0; + audio_data_max_mem = 0; + audio_data_lock = Mutex::create(); + mix_frames = 0; + to_mix = 0; } AudioServer::~AudioServer() { @@ -1087,46 +1011,44 @@ AudioServer::~AudioServer() { ///////////////////////////////// - - -bool AudioBusLayout::_set(const StringName& p_name, const Variant& p_value) { +bool AudioBusLayout::_set(const StringName &p_name, const Variant &p_value) { String s = p_name; if (s.begins_with("bus/")) { - int index = s.get_slice("/",1).to_int(); - if (buses.size()<=index) { - buses.resize(index+1); + int index = s.get_slice("/", 1).to_int(); + if (buses.size() <= index) { + buses.resize(index + 1); } Bus &bus = buses[index]; - String what = s.get_slice("/",2); - - if (what=="name") { - bus.name=p_value; - } else if (what=="solo") { - bus.solo=p_value; - } else if (what=="mute") { - bus.mute=p_value; - } else if (what=="bypass_fx") { - bus.bypass=p_value; - } else if (what=="volume_db") { - bus.volume_db=p_value; - } else if (what=="send") { - bus.send=p_value; - } else if (what=="effect") { - int which = s.get_slice("/",3).to_int(); - if (bus.effects.size()<=which) { - bus.effects.resize(which+1); + String what = s.get_slice("/", 2); + + if (what == "name") { + bus.name = p_value; + } else if (what == "solo") { + bus.solo = p_value; + } else if (what == "mute") { + bus.mute = p_value; + } else if (what == "bypass_fx") { + bus.bypass = p_value; + } else if (what == "volume_db") { + bus.volume_db = p_value; + } else if (what == "send") { + bus.send = p_value; + } else if (what == "effect") { + int which = s.get_slice("/", 3).to_int(); + if (bus.effects.size() <= which) { + bus.effects.resize(which + 1); } Bus::Effect &fx = bus.effects[which]; - String fxwhat = s.get_slice("/",4); - if (fxwhat=="effect") { - fx.effect=p_value; - } else if (fxwhat=="enabled") { - fx.enabled=p_value; + String fxwhat = s.get_slice("/", 4); + if (fxwhat == "effect") { + fx.effect = p_value; + } else if (fxwhat == "enabled") { + fx.enabled = p_value; } else { return false; } @@ -1140,47 +1062,46 @@ bool AudioBusLayout::_set(const StringName& p_name, const Variant& p_value) { } return false; - } -bool AudioBusLayout::_get(const StringName& p_name,Variant &r_ret) const{ +bool AudioBusLayout::_get(const StringName &p_name, Variant &r_ret) const { String s = p_name; if (s.begins_with("bus/")) { - int index = s.get_slice("/",1).to_int(); - if (index<0 || index>=buses.size()) + int index = s.get_slice("/", 1).to_int(); + if (index < 0 || index >= buses.size()) return false; const Bus &bus = buses[index]; - String what = s.get_slice("/",2); - - if (what=="name") { - r_ret=bus.name; - } else if (what=="solo") { - r_ret=bus.solo; - } else if (what=="mute") { - r_ret=bus.mute; - } else if (what=="bypass_fx") { - r_ret=bus.bypass; - } else if (what=="volume_db") { - r_ret=bus.volume_db; - } else if (what=="send") { - r_ret=bus.send; - } else if (what=="effect") { - int which = s.get_slice("/",3).to_int(); - if (which<0 || which>=bus.effects.size()) { + String what = s.get_slice("/", 2); + + if (what == "name") { + r_ret = bus.name; + } else if (what == "solo") { + r_ret = bus.solo; + } else if (what == "mute") { + r_ret = bus.mute; + } else if (what == "bypass_fx") { + r_ret = bus.bypass; + } else if (what == "volume_db") { + r_ret = bus.volume_db; + } else if (what == "send") { + r_ret = bus.send; + } else if (what == "effect") { + int which = s.get_slice("/", 3).to_int(); + if (which < 0 || which >= bus.effects.size()) { return false; } const Bus::Effect &fx = bus.effects[which]; - String fxwhat = s.get_slice("/",4); - if (fxwhat=="effect") { - r_ret=fx.effect; - } else if (fxwhat=="enabled") { - r_ret=fx.enabled; + String fxwhat = s.get_slice("/", 4); + if (fxwhat == "effect") { + r_ret = fx.effect; + } else if (fxwhat == "enabled") { + r_ret = fx.enabled; } else { return false; } @@ -1194,28 +1115,26 @@ bool AudioBusLayout::_get(const StringName& p_name,Variant &r_ret) const{ } return false; - } -void AudioBusLayout::_get_property_list( List<PropertyInfo> *p_list) const{ +void AudioBusLayout::_get_property_list(List<PropertyInfo> *p_list) const { - for(int i=0;i<buses.size();i++) { - p_list->push_back(PropertyInfo(Variant::STRING,"bus/"+itos(i)+"/name",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/solo",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/mute",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/bypass_fx",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::REAL,"bus/"+itos(i)+"/volume_db",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::REAL,"bus/"+itos(i)+"/send",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); + for (int i = 0; i < buses.size(); i++) { + p_list->push_back(PropertyInfo(Variant::STRING, "bus/" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/solo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/mute", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/bypass_fx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::REAL, "bus/" + itos(i) + "/volume_db", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::REAL, "bus/" + itos(i) + "/send", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); - for(int j=0;j<buses[i].effects.size();j++) { - p_list->push_back(PropertyInfo(Variant::OBJECT,"bus/"+itos(i)+"/effect/"+itos(j)+"/effect",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/effect/"+itos(j)+"/enabled",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); + for (int j = 0; j < buses[i].effects.size(); j++) { + p_list->push_back(PropertyInfo(Variant::OBJECT, "bus/" + itos(i) + "/effect/" + itos(j) + "/effect", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/effect/" + itos(j) + "/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } } } - AudioBusLayout::AudioBusLayout() { buses.resize(1); - buses[0].name="Master"; + buses[0].name = "Master"; } diff --git a/servers/audio_server.h b/servers/audio_server.h index 88849bb591..46f845f2d4 100644 --- a/servers/audio_server.h +++ b/servers/audio_server.h @@ -29,28 +29,22 @@ #ifndef AUDIO_SERVER_H #define AUDIO_SERVER_H -#include "variant.h" -#include "object.h" #include "audio_frame.h" +#include "object.h" #include "servers/audio/audio_effect.h" - +#include "variant.h" class AudioDriver { - static AudioDriver *singleton; uint64_t _last_mix_time; uint64_t _mix_amount; - protected: - - void audio_server_process(int p_frames,int32_t *p_buffer,bool p_update_mix_time=true); + void audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time = true); void update_mix_time(int p_frames); public: - - double get_mix_time() const; //useful for video -> audio sync enum SpeakerMode { @@ -62,49 +56,43 @@ public: static AudioDriver *get_singleton(); void set_singleton(); - virtual const char* get_name() const=0; + virtual const char *get_name() const = 0; - virtual Error init()=0; - virtual void start()=0; - virtual int get_mix_rate() const =0; - virtual SpeakerMode get_speaker_mode() const=0; - virtual void lock()=0; - virtual void unlock()=0; - virtual void finish()=0; + virtual Error init() = 0; + virtual void start() = 0; + virtual int get_mix_rate() const = 0; + virtual SpeakerMode get_speaker_mode() const = 0; + virtual void lock() = 0; + virtual void unlock() = 0; + virtual void finish() = 0; virtual float get_latency() { return 0; } - - - AudioDriver(); virtual ~AudioDriver() {} }; - - class AudioDriverManager { enum { - MAX_DRIVERS=10 + MAX_DRIVERS = 10 }; static AudioDriver *drivers[MAX_DRIVERS]; static int driver_count; -public: +public: static void add_driver(AudioDriver *p_driver); static int get_driver_count(); static AudioDriver *get_driver(int p_driver); }; - class AudioBusLayout; class AudioServer : public Object { - GDCLASS( AudioServer, Object ) + GDCLASS(AudioServer, Object) public: //re-expose this her, as AudioDriver is not exposed to script enum SpeakerMode { @@ -114,10 +102,10 @@ public: }; enum { - AUDIO_DATA_INVALID_ID=-1 + AUDIO_DATA_INVALID_ID = -1 }; - typedef void (*AudioCallback)(void* p_userdata); + typedef void (*AudioCallback)(void *p_userdata); private: uint32_t buffer_size; @@ -144,12 +132,16 @@ private: Vector<AudioFrame> buffer; Vector<Ref<AudioEffectInstance> > effect_instances; uint64_t last_mix_with_audio; - Channel() { last_mix_with_audio=0; used=false; active=false; peak_volume=AudioFrame(0,0); } + Channel() { + last_mix_with_audio = 0; + used = false; + active = false; + peak_volume = AudioFrame(0, 0); + } }; Vector<Channel> channels; - struct Effect { Ref<AudioEffect> effect; bool enabled; @@ -161,31 +153,26 @@ private: int index_cache; }; - - Vector< Vector<AudioFrame> >temp_buffer; //temp_buffer for each level - Vector<Bus*> buses; - Map<StringName,Bus*> bus_map; + Vector<Vector<AudioFrame> > temp_buffer; //temp_buffer for each level + Vector<Bus *> buses; + Map<StringName, Bus *> bus_map; _FORCE_INLINE_ int _get_channel_count() const { switch (AudioDriver::get_singleton()->get_speaker_mode()) { case AudioDriver::SPEAKER_MODE_STEREO: return 1; case AudioDriver::SPEAKER_SURROUND_51: return 3; case AudioDriver::SPEAKER_SURROUND_71: return 4; - } ERR_FAIL_V(1); } - void _update_bus_effects(int p_bus); - - static AudioServer* singleton; + static AudioServer *singleton; // TODO create an audiodata pool to optimize memory - - Map<void*,uint32_t> audio_data; + Map<void *, uint32_t> audio_data; size_t audio_data_total_mem; size_t audio_data_max_mem; @@ -198,68 +185,66 @@ private: AudioCallback callback; void *userdata; - bool operator<(const CallbackItem& p_item) const { - return (callback==p_item.callback ? userdata < p_item.userdata : callback < p_item.callback); + bool operator<(const CallbackItem &p_item) const { + return (callback == p_item.callback ? userdata < p_item.userdata : callback < p_item.callback); } }; Set<CallbackItem> callbacks; -friend class AudioDriver; + friend class AudioDriver; void _driver_process(int p_frames, int32_t *p_buffer); -protected: +protected: static void _bind_methods(); -public: +public: //do not use from outside audio thread - AudioFrame *thread_get_channel_mix_buffer(int p_bus,int p_buffer); + AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer); int thread_get_mix_buffer_size() const; - int thread_find_bus_index(const StringName& p_name); - + int thread_find_bus_index(const StringName &p_name); void set_bus_count(int p_count); int get_bus_count() const; void remove_bus(int p_index); - void add_bus(int p_at_pos=-1); + void add_bus(int p_at_pos = -1); - void move_bus(int p_bus,int p_to_pos); + void move_bus(int p_bus, int p_to_pos); - void set_bus_name(int p_bus,const String& p_name); + void set_bus_name(int p_bus, const String &p_name); String get_bus_name(int p_bus) const; - void set_bus_volume_db(int p_bus,float p_volume_db); + void set_bus_volume_db(int p_bus, float p_volume_db); float get_bus_volume_db(int p_bus) const; - - void set_bus_send(int p_bus,const StringName& p_send); + void set_bus_send(int p_bus, const StringName &p_send); StringName get_bus_send(int p_bus) const; - void set_bus_solo(int p_bus,bool p_enable); + void set_bus_solo(int p_bus, bool p_enable); bool is_bus_solo(int p_bus) const; - void set_bus_mute(int p_bus,bool p_enable); + void set_bus_mute(int p_bus, bool p_enable); bool is_bus_mute(int p_bus) const; - void set_bus_bypass_effects(int p_bus,bool p_enable); + void set_bus_bypass_effects(int p_bus, bool p_enable); bool is_bus_bypassing_effects(int p_bus) const; - void add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int p_at_pos=-1); - void remove_bus_effect(int p_bus,int p_effect); + void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1); + void remove_bus_effect(int p_bus, int p_effect); int get_bus_effect_count(int p_bus); - Ref<AudioEffect> get_bus_effect(int p_bus,int p_effect); + Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect); - void swap_bus_effects(int p_bus,int p_effect,int p_by_effect); + void swap_bus_effects(int p_bus, int p_effect, int p_by_effect); - void set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled); - bool is_bus_effect_enabled(int p_bus,int p_effect) const; + void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled); + bool is_bus_effect_enabled(int p_bus, int p_effect) const; - float get_bus_peak_volume_left_db(int p_bus,int p_channel) const; - float get_bus_peak_volume_right_db(int p_bus,int p_channel) const; + float get_bus_peak_volume_left_db(int p_bus, int p_channel) const; + float get_bus_peak_volume_right_db(int p_bus, int p_channel) const; - bool is_bus_channel_active(int p_bus,int p_channel) const; + bool is_bus_channel_active(int p_bus, int p_channel) const; virtual void init(); virtual void finish(); @@ -271,7 +256,6 @@ public: virtual void lock(); virtual void unlock(); - virtual SpeakerMode get_speaker_mode() const; virtual float get_mix_rate() const; @@ -282,30 +266,29 @@ public: virtual double get_mix_time() const; //useful for video -> audio sync virtual double get_output_delay() const; - void* audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data=NULL); - void audio_data_free(void* p_data); + void *audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data = NULL); + void audio_data_free(void *p_data); size_t audio_data_get_total_memory_usage() const; size_t audio_data_get_max_memory_usage() const; + void add_callback(AudioCallback p_callback, void *p_userdata); + void remove_callback(AudioCallback p_callback, void *p_userdata); - void add_callback(AudioCallback p_callback,void *p_userdata); - void remove_callback(AudioCallback p_callback,void *p_userdata); - - void set_bus_layout(const Ref<AudioBusLayout>& p_state); + void set_bus_layout(const Ref<AudioBusLayout> &p_state); Ref<AudioBusLayout> generate_bus_layout() const; AudioServer(); virtual ~AudioServer(); }; -VARIANT_ENUM_CAST( AudioServer::SpeakerMode ) +VARIANT_ENUM_CAST(AudioServer::SpeakerMode) class AudioBusLayout : public Resource { - GDCLASS(AudioBusLayout,Resource) + GDCLASS(AudioBusLayout, Resource) -friend class AudioServer; + friend class AudioServer; struct Bus { @@ -325,32 +308,24 @@ friend class AudioServer; StringName send; Bus() { - solo=false; - mute=false; - bypass=false; - volume_db=0; + solo = false; + mute = false; + bypass = false; + volume_db = 0; } }; Vector<Bus> buses; 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; public: - AudioBusLayout(); }; - - - - - typedef AudioServer AS; - #endif // AUDIO_SERVER_H diff --git a/servers/physics/area_pair_sw.cpp b/servers/physics/area_pair_sw.cpp index 3aa0816b06..d1040baa65 100644 --- a/servers/physics/area_pair_sw.cpp +++ b/servers/physics/area_pair_sw.cpp @@ -29,7 +29,6 @@ #include "area_pair_sw.h" #include "collision_solver_sw.h" - bool AreaPairSW::setup(real_t p_step) { if (!area->test_collision_mask(body)) { @@ -37,63 +36,55 @@ bool AreaPairSW::setup(real_t p_step) { return false; } - bool result = CollisionSolverSW::solve_static(body->get_shape(body_shape),body->get_transform() * body->get_shape_transform(body_shape),area->get_shape(area_shape),area->get_transform() * area->get_shape_transform(area_shape),NULL,this); + bool result = CollisionSolverSW::solve_static(body->get_shape(body_shape), body->get_transform() * body->get_shape_transform(body_shape), area->get_shape(area_shape), area->get_transform() * area->get_shape_transform(area_shape), NULL, this); - if (result!=colliding) { + if (result != colliding) { if (result) { - if (area->get_space_override_mode()!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED) + if (area->get_space_override_mode() != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED) body->add_area(area); if (area->has_monitor_callback()) - area->add_body_to_query(body,body_shape,area_shape); + area->add_body_to_query(body, body_shape, area_shape); } else { - if (area->get_space_override_mode()!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED) + if (area->get_space_override_mode() != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED) body->remove_area(area); if (area->has_monitor_callback()) - area->remove_body_from_query(body,body_shape,area_shape); - + area->remove_body_from_query(body, body_shape, area_shape); } - colliding=result; - + colliding = result; } return false; //never do any post solving } void AreaPairSW::solve(real_t p_step) { - - } +AreaPairSW::AreaPairSW(BodySW *p_body, int p_body_shape, AreaSW *p_area, int p_area_shape) { -AreaPairSW::AreaPairSW(BodySW *p_body,int p_body_shape, AreaSW *p_area,int p_area_shape) { - - body=p_body; - area=p_area; - body_shape=p_body_shape; - area_shape=p_area_shape; - colliding=false; - body->add_constraint(this,0); + body = p_body; + area = p_area; + body_shape = p_body_shape; + area_shape = p_area_shape; + colliding = false; + body->add_constraint(this, 0); area->add_constraint(this); - if (p_body->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC) + if (p_body->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC) p_body->set_active(true); - } AreaPairSW::~AreaPairSW() { if (colliding) { - if (area->get_space_override_mode()!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED) + if (area->get_space_override_mode() != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED) body->remove_area(area); if (area->has_monitor_callback()) - area->remove_body_from_query(body,body_shape,area_shape); - - + area->remove_body_from_query(body, body_shape, area_shape); } body->remove_constraint(this); area->remove_constraint(this); @@ -101,8 +92,6 @@ AreaPairSW::~AreaPairSW() { //////////////////////////////////////////////////// - - bool Area2PairSW::setup(real_t p_step) { if (!area_a->test_collision_mask(area_b)) { @@ -111,51 +100,45 @@ bool Area2PairSW::setup(real_t p_step) { } //bool result = area_a->test_collision_mask(area_b) && CollisionSolverSW::solve(area_a->get_shape(shape_a),area_a->get_transform() * area_a->get_shape_transform(shape_a),Vector2(),area_b->get_shape(shape_b),area_b->get_transform() * area_b->get_shape_transform(shape_b),Vector2(),NULL,this); - bool result = CollisionSolverSW::solve_static(area_a->get_shape(shape_a),area_a->get_transform() * area_a->get_shape_transform(shape_a),area_b->get_shape(shape_b),area_b->get_transform() * area_b->get_shape_transform(shape_b),NULL,this); + bool result = CollisionSolverSW::solve_static(area_a->get_shape(shape_a), area_a->get_transform() * area_a->get_shape_transform(shape_a), area_b->get_shape(shape_b), area_b->get_transform() * area_b->get_shape_transform(shape_b), NULL, this); - if (result!=colliding) { + if (result != colliding) { if (result) { if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) - area_b->add_area_to_query(area_a,shape_a,shape_b); + area_b->add_area_to_query(area_a, shape_a, shape_b); if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) - area_a->add_area_to_query(area_b,shape_b,shape_a); + area_a->add_area_to_query(area_b, shape_b, shape_a); } else { if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) - area_b->remove_area_from_query(area_a,shape_a,shape_b); + area_b->remove_area_from_query(area_a, shape_a, shape_b); if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) - area_a->remove_area_from_query(area_b,shape_b,shape_a); + area_a->remove_area_from_query(area_b, shape_b, shape_a); } - colliding=result; - + colliding = result; } return false; //never do any post solving } void Area2PairSW::solve(real_t p_step) { - - } +Area2PairSW::Area2PairSW(AreaSW *p_area_a, int p_shape_a, AreaSW *p_area_b, int p_shape_b) { -Area2PairSW::Area2PairSW(AreaSW *p_area_a,int p_shape_a, AreaSW *p_area_b,int p_shape_b) { - - - area_a=p_area_a; - area_b=p_area_b; - shape_a=p_shape_a; - shape_b=p_shape_b; - colliding=false; + area_a = p_area_a; + area_b = p_area_b; + shape_a = p_shape_a; + shape_b = p_shape_b; + colliding = false; area_a->add_constraint(this); area_b->add_constraint(this); - } Area2PairSW::~Area2PairSW() { @@ -163,10 +146,10 @@ Area2PairSW::~Area2PairSW() { if (colliding) { if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) - area_b->remove_area_from_query(area_a,shape_a,shape_b); + area_b->remove_area_from_query(area_a, shape_a, shape_b); if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) - area_a->remove_area_from_query(area_b,shape_b,shape_a); + area_a->remove_area_from_query(area_b, shape_b, shape_a); } area_a->remove_constraint(this); diff --git a/servers/physics/area_pair_sw.h b/servers/physics/area_pair_sw.h index 637976a095..8fc7e7efaa 100644 --- a/servers/physics/area_pair_sw.h +++ b/servers/physics/area_pair_sw.h @@ -29,9 +29,9 @@ #ifndef AREA_PAIR_SW_H #define AREA_PAIR_SW_H -#include "constraint_sw.h" -#include "body_sw.h" #include "area_sw.h" +#include "body_sw.h" +#include "constraint_sw.h" class AreaPairSW : public ConstraintSW { @@ -40,16 +40,15 @@ class AreaPairSW : public ConstraintSW { int body_shape; int area_shape; bool colliding; -public: +public: bool setup(real_t p_step); void solve(real_t p_step); - AreaPairSW(BodySW *p_body,int p_body_shape, AreaSW *p_area,int p_area_shape); + AreaPairSW(BodySW *p_body, int p_body_shape, AreaSW *p_area, int p_area_shape); ~AreaPairSW(); }; - class Area2PairSW : public ConstraintSW { AreaSW *area_a; @@ -57,15 +56,13 @@ class Area2PairSW : public ConstraintSW { int shape_a; int shape_b; bool colliding; -public: +public: bool setup(real_t p_step); void solve(real_t p_step); - Area2PairSW(AreaSW *p_area_a,int p_shape_a, AreaSW *p_area_b,int p_shape_b); + Area2PairSW(AreaSW *p_area_a, int p_shape_a, AreaSW *p_area_b, int p_shape_b); ~Area2PairSW(); }; - #endif // AREA_PAIR__SW_H - diff --git a/servers/physics/area_sw.cpp b/servers/physics/area_sw.cpp index 8aed07d5e5..dfb5d191bc 100644 --- a/servers/physics/area_sw.cpp +++ b/servers/physics/area_sw.cpp @@ -27,18 +27,26 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "area_sw.h" -#include "space_sw.h" #include "body_sw.h" +#include "space_sw.h" -AreaSW::BodyKey::BodyKey(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; } -AreaSW::BodyKey::BodyKey(AreaSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; } +AreaSW::BodyKey::BodyKey(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { + rid = p_body->get_self(); + instance_id = p_body->get_instance_id(); + body_shape = p_body_shape; + area_shape = p_area_shape; +} +AreaSW::BodyKey::BodyKey(AreaSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { + rid = p_body->get_self(); + instance_id = p_body->get_instance_id(); + body_shape = p_body_shape; + area_shape = p_area_shape; +} void AreaSW::_shapes_changed() { - - } -void AreaSW::set_transform(const Transform& p_transform) { +void AreaSW::set_transform(const Transform &p_transform) { if (!moved_list.in_list() && get_space()) get_space()->area_add_to_moved_list(&moved_list); @@ -54,7 +62,6 @@ void AreaSW::set_space(SpaceSW *p_space) { get_space()->area_remove_from_monitor_query_list(&monitor_query_list); if (moved_list.in_list()) get_space()->area_remove_from_moved_list(&moved_list); - } monitored_bodies.clear(); @@ -63,44 +70,38 @@ void AreaSW::set_space(SpaceSW *p_space) { _set_space(p_space); } +void AreaSW::set_monitor_callback(ObjectID p_id, const StringName &p_method) { -void AreaSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) { - - - if (p_id==monitor_callback_id) { - monitor_callback_method=p_method; + if (p_id == monitor_callback_id) { + monitor_callback_method = p_method; return; } _unregister_shapes(); - monitor_callback_id=p_id; - monitor_callback_method=p_method; + monitor_callback_id = p_id; + monitor_callback_method = p_method; monitored_bodies.clear(); monitored_areas.clear(); - _shape_changed(); if (!moved_list.in_list() && get_space()) get_space()->area_add_to_moved_list(&moved_list); - - } -void AreaSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_method) { +void AreaSW::set_area_monitor_callback(ObjectID p_id, const StringName &p_method) { - - if (p_id==area_monitor_callback_id) { - area_monitor_callback_method=p_method; + if (p_id == area_monitor_callback_id) { + area_monitor_callback_method = p_method; return; } _unregister_shapes(); - area_monitor_callback_id=p_id; - area_monitor_callback_method=p_method; + area_monitor_callback_id = p_id; + area_monitor_callback_method = p_method; monitored_bodies.clear(); monitored_areas.clear(); @@ -109,45 +110,39 @@ void AreaSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_method if (!moved_list.in_list() && get_space()) get_space()->area_add_to_moved_list(&moved_list); - - } - void AreaSW::set_space_override_mode(PhysicsServer::AreaSpaceOverrideMode p_mode) { - bool do_override=p_mode!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED; - if (do_override==(space_override_mode!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)) + bool do_override = p_mode != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED; + if (do_override == (space_override_mode != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)) return; _unregister_shapes(); - space_override_mode=p_mode; + space_override_mode = p_mode; _shape_changed(); } -void AreaSW::set_param(PhysicsServer::AreaParameter p_param, const Variant& p_value) { - - switch(p_param) { - case PhysicsServer::AREA_PARAM_GRAVITY: gravity=p_value; break; - case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector=p_value; break; - case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point=p_value; break; - case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale=p_value; break; - case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation=p_value; break; - case PhysicsServer::AREA_PARAM_LINEAR_DAMP: linear_damp=p_value; break; - case PhysicsServer::AREA_PARAM_ANGULAR_DAMP: angular_damp=p_value; break; - case PhysicsServer::AREA_PARAM_PRIORITY: priority=p_value; break; +void AreaSW::set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value) { + + switch (p_param) { + case PhysicsServer::AREA_PARAM_GRAVITY: gravity = p_value; break; + case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector = p_value; break; + case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point = p_value; break; + case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale = p_value; break; + case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation = p_value; break; + case PhysicsServer::AREA_PARAM_LINEAR_DAMP: linear_damp = p_value; break; + case PhysicsServer::AREA_PARAM_ANGULAR_DAMP: angular_damp = p_value; break; + case PhysicsServer::AREA_PARAM_PRIORITY: priority = p_value; break; } - - } Variant AreaSW::get_param(PhysicsServer::AreaParameter p_param) const { - - switch(p_param) { + switch (p_param) { case PhysicsServer::AREA_PARAM_GRAVITY: return gravity; case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: return gravity_vector; case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: return gravity_is_point; case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: return gravity_distance_scale; - case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation; + case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation; case PhysicsServer::AREA_PARAM_LINEAR_DAMP: return linear_damp; case PhysicsServer::AREA_PARAM_ANGULAR_DAMP: return angular_damp; case PhysicsServer::AREA_PARAM_PRIORITY: return priority; @@ -156,23 +151,20 @@ Variant AreaSW::get_param(PhysicsServer::AreaParameter p_param) const { return Variant(); } - void AreaSW::_queue_monitor_update() { ERR_FAIL_COND(!get_space()); if (!monitor_query_list.in_list()) get_space()->area_add_to_monitor_query_list(&monitor_query_list); - - } void AreaSW::set_monitorable(bool p_monitorable) { - if (monitorable==p_monitorable) + if (monitorable == p_monitorable) return; - monitorable=p_monitorable; + monitorable = p_monitorable; _set_static(!monitorable); } @@ -182,29 +174,29 @@ void AreaSW::call_queries() { Variant res[5]; Variant *resptr[5]; - for(int i=0;i<5;i++) - resptr[i]=&res[i]; + for (int i = 0; i < 5; i++) + resptr[i] = &res[i]; Object *obj = ObjectDB::get_instance(monitor_callback_id); if (!obj) { monitored_bodies.clear(); - monitor_callback_id=0; + monitor_callback_id = 0; return; } - for (Map<BodyKey,BodyState>::Element *E=monitored_bodies.front();E;E=E->next()) { + for (Map<BodyKey, BodyState>::Element *E = monitored_bodies.front(); E; E = E->next()) { - if (E->get().state==0) + if (E->get().state == 0) continue; //nothing happened - res[0]=E->get().state>0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED; - res[1]=E->key().rid; - res[2]=E->key().instance_id; - res[3]=E->key().body_shape; - res[4]=E->key().area_shape; + res[0] = E->get().state > 0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED; + res[1] = E->key().rid; + res[2] = E->key().instance_id; + res[3] = E->key().body_shape; + res[4] = E->key().area_shape; Variant::CallError ce; - obj->call(monitor_callback_method,(const Variant**)resptr,5,ce); + obj->call(monitor_callback_method, (const Variant **)resptr, 5, ce); } } @@ -212,64 +204,56 @@ void AreaSW::call_queries() { if (area_monitor_callback_id && !monitored_areas.empty()) { - Variant res[5]; Variant *resptr[5]; - for(int i=0;i<5;i++) - resptr[i]=&res[i]; + for (int i = 0; i < 5; i++) + resptr[i] = &res[i]; Object *obj = ObjectDB::get_instance(area_monitor_callback_id); if (!obj) { monitored_areas.clear(); - area_monitor_callback_id=0; + area_monitor_callback_id = 0; return; } + for (Map<BodyKey, BodyState>::Element *E = monitored_areas.front(); E; E = E->next()) { - - for (Map<BodyKey,BodyState>::Element *E=monitored_areas.front();E;E=E->next()) { - - if (E->get().state==0) + if (E->get().state == 0) continue; //nothing happened - res[0]=E->get().state>0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED; - res[1]=E->key().rid; - res[2]=E->key().instance_id; - res[3]=E->key().body_shape; - res[4]=E->key().area_shape; - + res[0] = E->get().state > 0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED; + res[1] = E->key().rid; + res[2] = E->key().instance_id; + res[3] = E->key().body_shape; + res[4] = E->key().area_shape; Variant::CallError ce; - obj->call(area_monitor_callback_method,(const Variant**)resptr,5,ce); + obj->call(area_monitor_callback_method, (const Variant **)resptr, 5, ce); } } monitored_areas.clear(); //get_space()->area_remove_from_monitor_query_list(&monitor_query_list); - } -AreaSW::AreaSW() : CollisionObjectSW(TYPE_AREA), monitor_query_list(this), moved_list(this) { +AreaSW::AreaSW() + : CollisionObjectSW(TYPE_AREA), monitor_query_list(this), moved_list(this) { _set_static(true); //areas are never active - space_override_mode=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED; - gravity=9.80665; - gravity_vector=Vector3(0,-1,0); - gravity_is_point=false; - gravity_distance_scale=0; - point_attenuation=1; - angular_damp=1.0; - linear_damp=0.1; - priority=0; + space_override_mode = PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED; + gravity = 9.80665; + gravity_vector = Vector3(0, -1, 0); + gravity_is_point = false; + gravity_distance_scale = 0; + point_attenuation = 1; + angular_damp = 1.0; + linear_damp = 0.1; + priority = 0; set_ray_pickable(false); - monitor_callback_id=0; - area_monitor_callback_id=0; - monitorable=false; - + monitor_callback_id = 0; + area_monitor_callback_id = 0; + monitorable = false; } AreaSW::~AreaSW() { - - } - diff --git a/servers/physics/area_sw.h b/servers/physics/area_sw.h index 4e6f1c5a51..2c0cd8dbcd 100644 --- a/servers/physics/area_sw.h +++ b/servers/physics/area_sw.h @@ -29,17 +29,16 @@ #ifndef AREA_SW_H #define AREA_SW_H -#include "servers/physics_server.h" #include "collision_object_sw.h" #include "self_list.h" +#include "servers/physics_server.h" //#include "servers/physics/query_sw.h" class SpaceSW; class BodySW; class ConstraintSW; -class AreaSW : public CollisionObjectSW{ - +class AreaSW : public CollisionObjectSW { PhysicsServer::AreaSpaceOverrideMode space_override_mode; real_t gravity; @@ -68,24 +67,22 @@ class AreaSW : public CollisionObjectSW{ uint32_t body_shape; uint32_t area_shape; - _FORCE_INLINE_ bool operator<( const BodyKey& p_key) const { + _FORCE_INLINE_ bool operator<(const BodyKey &p_key) const { - if (rid==p_key.rid) { + if (rid == p_key.rid) { - if (body_shape==p_key.body_shape) { + if (body_shape == p_key.body_shape) { return area_shape < p_key.area_shape; } else return body_shape < p_key.body_shape; } else return rid < p_key.rid; - } _FORCE_INLINE_ BodyKey() {} - BodyKey(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); - BodyKey(AreaSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); - + BodyKey(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); + BodyKey(AreaSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); }; struct BodyState { @@ -93,125 +90,111 @@ class AreaSW : public CollisionObjectSW{ int state; _FORCE_INLINE_ void inc() { state++; } _FORCE_INLINE_ void dec() { state--; } - _FORCE_INLINE_ BodyState() { state=0; } + _FORCE_INLINE_ BodyState() { state = 0; } }; - Map<BodyKey,BodyState> monitored_bodies; - Map<BodyKey,BodyState> monitored_areas; + Map<BodyKey, BodyState> monitored_bodies; + Map<BodyKey, BodyState> monitored_areas; //virtual void shape_changed_notify(ShapeSW *p_shape); //virtual void shape_deleted_notify(ShapeSW *p_shape); - Set<ConstraintSW*> constraints; - + Set<ConstraintSW *> constraints; virtual void _shapes_changed(); void _queue_monitor_update(); public: - //_FORCE_INLINE_ const Transform& get_inverse_transform() const { return inverse_transform; } //_FORCE_INLINE_ SpaceSW* get_owner() { return owner; } - void set_monitor_callback(ObjectID p_id, const StringName& p_method); + void set_monitor_callback(ObjectID p_id, const StringName &p_method); _FORCE_INLINE_ bool has_monitor_callback() const { return monitor_callback_id; } - void set_area_monitor_callback(ObjectID p_id, const StringName& p_method); + void set_area_monitor_callback(ObjectID p_id, const StringName &p_method); _FORCE_INLINE_ bool has_area_monitor_callback() const { return area_monitor_callback_id; } - _FORCE_INLINE_ void add_body_to_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); - _FORCE_INLINE_ void remove_body_from_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); + _FORCE_INLINE_ void add_body_to_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); + _FORCE_INLINE_ void remove_body_from_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); - _FORCE_INLINE_ void add_area_to_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape); - _FORCE_INLINE_ void remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape); + _FORCE_INLINE_ void add_area_to_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape); + _FORCE_INLINE_ void remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape); - void set_param(PhysicsServer::AreaParameter p_param, const Variant& p_value); + void set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value); Variant get_param(PhysicsServer::AreaParameter p_param) const; void set_space_override_mode(PhysicsServer::AreaSpaceOverrideMode p_mode); PhysicsServer::AreaSpaceOverrideMode get_space_override_mode() const { return space_override_mode; } - _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity=p_gravity; } + _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity = p_gravity; } _FORCE_INLINE_ real_t get_gravity() const { return gravity; } - _FORCE_INLINE_ void set_gravity_vector(const Vector3& p_gravity) { gravity_vector=p_gravity; } + _FORCE_INLINE_ void set_gravity_vector(const Vector3 &p_gravity) { gravity_vector = p_gravity; } _FORCE_INLINE_ Vector3 get_gravity_vector() const { return gravity_vector; } - _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point=p_enable; } + _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point = p_enable; } _FORCE_INLINE_ bool is_gravity_point() const { return gravity_is_point; } - _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale=scale; } + _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale = scale; } _FORCE_INLINE_ real_t get_gravity_distance_scale() const { return gravity_distance_scale; } - _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation=p_point_attenuation; } + _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation = p_point_attenuation; } _FORCE_INLINE_ real_t get_point_attenuation() const { return point_attenuation; } - _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp=p_linear_damp; } + _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp = p_linear_damp; } _FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; } - _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp=p_angular_damp; } + _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp = p_angular_damp; } _FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; } - _FORCE_INLINE_ void set_priority(int p_priority) { priority=p_priority; } + _FORCE_INLINE_ void set_priority(int p_priority) { priority = p_priority; } _FORCE_INLINE_ int get_priority() const { return priority; } - _FORCE_INLINE_ void add_constraint( ConstraintSW* p_constraint) { constraints.insert(p_constraint); } - _FORCE_INLINE_ void remove_constraint( ConstraintSW* p_constraint) { constraints.erase(p_constraint); } - _FORCE_INLINE_ const Set<ConstraintSW*>& get_constraints() const { return constraints; } + _FORCE_INLINE_ void add_constraint(ConstraintSW *p_constraint) { constraints.insert(p_constraint); } + _FORCE_INLINE_ void remove_constraint(ConstraintSW *p_constraint) { constraints.erase(p_constraint); } + _FORCE_INLINE_ const Set<ConstraintSW *> &get_constraints() const { return constraints; } void set_monitorable(bool p_monitorable); _FORCE_INLINE_ bool is_monitorable() const { return monitorable; } - void set_transform(const Transform& p_transform); + void set_transform(const Transform &p_transform); void set_space(SpaceSW *p_space); - void call_queries(); AreaSW(); ~AreaSW(); }; -void AreaSW::add_body_to_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { +void AreaSW::add_body_to_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { - BodyKey bk(p_body,p_body_shape,p_area_shape); + BodyKey bk(p_body, p_body_shape, p_area_shape); monitored_bodies[bk].inc(); if (!monitor_query_list.in_list()) _queue_monitor_update(); } -void AreaSW::remove_body_from_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { +void AreaSW::remove_body_from_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { - BodyKey bk(p_body,p_body_shape,p_area_shape); + BodyKey bk(p_body, p_body_shape, p_area_shape); monitored_bodies[bk].dec(); if (!monitor_query_list.in_list()) _queue_monitor_update(); } +void AreaSW::add_area_to_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) { -void AreaSW::add_area_to_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) { - - - BodyKey bk(p_area,p_area_shape,p_self_shape); + BodyKey bk(p_area, p_area_shape, p_self_shape); monitored_areas[bk].inc(); if (!monitor_query_list.in_list()) _queue_monitor_update(); - - } -void AreaSW::remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) { - +void AreaSW::remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) { - BodyKey bk(p_area,p_area_shape,p_self_shape); + BodyKey bk(p_area, p_area_shape, p_self_shape); monitored_areas[bk].dec(); if (!monitor_query_list.in_list()) _queue_monitor_update(); - } - - - - - #endif // AREA__SW_H diff --git a/servers/physics/body_pair_sw.cpp b/servers/physics/body_pair_sw.cpp index 7fb3def387..555d5f15c5 100644 --- a/servers/physics/body_pair_sw.cpp +++ b/servers/physics/body_pair_sw.cpp @@ -28,8 +28,8 @@ /*************************************************************************/ #include "body_pair_sw.h" #include "collision_solver_sw.h" -#include "space_sw.h" #include "os/os.h" +#include "space_sw.h" /* #define NO_ACCUMULATE_IMPULSES @@ -41,19 +41,17 @@ #define NO_TANGENTIALS /* BODY PAIR */ - //#define ALLOWED_PENETRATION 0.01 #define RELAXATION_TIMESTEPS 3 #define MIN_VELOCITY 0.0001 -void BodyPairSW::_contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata) { - - BodyPairSW* pair = (BodyPairSW*)p_userdata; - pair->contact_added_callback(p_point_A,p_point_B); +void BodyPairSW::_contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) { + BodyPairSW *pair = (BodyPairSW *)p_userdata; + pair->contact_added_callback(p_point_A, p_point_B); } -void BodyPairSW::contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B) { +void BodyPairSW::contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B) { // check if we already have the contact @@ -61,40 +59,36 @@ void BodyPairSW::contact_added_callback(const Vector3& p_point_A,const Vector3& //Vector3 local_B = B->get_inv_transform().xform(p_point_B); Vector3 local_A = A->get_inv_transform().basis.xform(p_point_A); - Vector3 local_B = B->get_inv_transform().basis.xform(p_point_B-offset_B); - - + Vector3 local_B = B->get_inv_transform().basis.xform(p_point_B - offset_B); int new_index = contact_count; - ERR_FAIL_COND( new_index >= (MAX_CONTACTS+1) ); + ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1)); Contact contact; - contact.acc_normal_impulse=0; - contact.acc_bias_impulse=0; - contact.acc_tangent_impulse=Vector3(); - contact.local_A=local_A; - contact.local_B=local_B; - contact.normal=(p_point_A-p_point_B).normalized(); - - + contact.acc_normal_impulse = 0; + contact.acc_bias_impulse = 0; + contact.acc_tangent_impulse = Vector3(); + contact.local_A = local_A; + contact.local_B = local_B; + contact.normal = (p_point_A - p_point_B).normalized(); // attempt to determine if the contact will be reused - real_t contact_recycle_radius=space->get_contact_recycle_radius(); + real_t contact_recycle_radius = space->get_contact_recycle_radius(); - for (int i=0;i<contact_count;i++) { + for (int i = 0; i < contact_count; i++) { - Contact& c = contacts[i]; + Contact &c = contacts[i]; if ( - c.local_A.distance_squared_to( local_A ) < (contact_recycle_radius*contact_recycle_radius) && - c.local_B.distance_squared_to( local_B ) < (contact_recycle_radius*contact_recycle_radius) ) { - - contact.acc_normal_impulse=c.acc_normal_impulse; - contact.acc_bias_impulse=c.acc_bias_impulse; - contact.acc_tangent_impulse=c.acc_tangent_impulse; - new_index=i; - break; + c.local_A.distance_squared_to(local_A) < (contact_recycle_radius * contact_recycle_radius) && + c.local_B.distance_squared_to(local_B) < (contact_recycle_radius * contact_recycle_radius)) { + + contact.acc_normal_impulse = c.acc_normal_impulse; + contact.acc_bias_impulse = c.acc_bias_impulse; + contact.acc_tangent_impulse = c.acc_tangent_impulse; + new_index = i; + break; } } @@ -104,66 +98,63 @@ void BodyPairSW::contact_added_callback(const Vector3& p_point_A,const Vector3& // remove the contact with the minimum depth - int least_deep=-1; - real_t min_depth=1e10; + int least_deep = -1; + real_t min_depth = 1e10; - for (int i=0;i<=contact_count;i++) { + for (int i = 0; i <= contact_count; i++) { - Contact& c = (i==contact_count)?contact:contacts[i]; + Contact &c = (i == contact_count) ? contact : contacts[i]; Vector3 global_A = A->get_transform().basis.xform(c.local_A); - Vector3 global_B = B->get_transform().basis.xform(c.local_B)+offset_B; + Vector3 global_B = B->get_transform().basis.xform(c.local_B) + offset_B; Vector3 axis = global_A - global_B; - real_t depth = axis.dot( c.normal ); + real_t depth = axis.dot(c.normal); - if (depth<min_depth) { + if (depth < min_depth) { - min_depth=depth; - least_deep=i; + min_depth = depth; + least_deep = i; } } - ERR_FAIL_COND(least_deep==-1); + ERR_FAIL_COND(least_deep == -1); if (least_deep < contact_count) { //replace the last deep contact by the new one - contacts[least_deep]=contact; + contacts[least_deep] = contact; } return; } - contacts[new_index]=contact; + contacts[new_index] = contact; - if (new_index==contact_count) { + if (new_index == contact_count) { contact_count++; } - } void BodyPairSW::validate_contacts() { //make sure to erase contacts that are no longer valid - real_t contact_max_separation=space->get_contact_max_separation(); - for (int i=0;i<contact_count;i++) { + real_t contact_max_separation = space->get_contact_max_separation(); + for (int i = 0; i < contact_count; i++) { - Contact& c = contacts[i]; + Contact &c = contacts[i]; Vector3 global_A = A->get_transform().basis.xform(c.local_A); - Vector3 global_B = B->get_transform().basis.xform(c.local_B)+offset_B; + Vector3 global_B = B->get_transform().basis.xform(c.local_B) + offset_B; Vector3 axis = global_A - global_B; - real_t depth = axis.dot( c.normal ); + real_t depth = axis.dot(c.normal); if (depth < -contact_max_separation || (global_B + c.normal * depth - global_A).length() > contact_max_separation) { // contact no longer needed, remove - - if ((i+1) < contact_count) { + if ((i + 1) < contact_count) { // swap with the last one - SWAP( contacts[i], contacts[ contact_count-1 ] ); - + SWAP(contacts[i], contacts[contact_count - 1]); } i--; @@ -172,21 +163,18 @@ void BodyPairSW::validate_contacts() { } } +bool BodyPairSW::_test_ccd(real_t p_step, BodySW *p_A, int p_shape_A, const Transform &p_xform_A, BodySW *p_B, int p_shape_B, const Transform &p_xform_B) { -bool BodyPairSW::_test_ccd(real_t p_step,BodySW *p_A, int p_shape_A,const Transform& p_xform_A,BodySW *p_B, int p_shape_B,const Transform& p_xform_B) { - - - - Vector3 motion = p_A->get_linear_velocity()*p_step; + Vector3 motion = p_A->get_linear_velocity() * p_step; real_t mlen = motion.length(); - if (mlen<CMP_EPSILON) + if (mlen < CMP_EPSILON) return false; Vector3 mnormal = motion / mlen; - real_t min,max; - p_A->get_shape(p_shape_A)->project_range(mnormal,p_xform_A,min,max); - bool fast_object = mlen > (max-min)*0.3; //going too fast in that direction + real_t min, max; + p_A->get_shape(p_shape_A)->project_range(mnormal, p_xform_A, min, max); + bool fast_object = mlen > (max - min) * 0.3; //going too fast in that direction if (!fast_object) { //did it move enough in this direction to even attempt raycast? let's say it should move more than 1/3 the size of the object in that axis return false; @@ -194,35 +182,34 @@ bool BodyPairSW::_test_ccd(real_t p_step,BodySW *p_A, int p_shape_A,const Transf //cast a segment from support in motion normal, in the same direction of motion by motion length //support is the worst case collision point, so real collision happened before - Vector3 s=p_A->get_shape(p_shape_A)->get_support(p_xform_A.basis.xform(mnormal).normalized()); + Vector3 s = p_A->get_shape(p_shape_A)->get_support(p_xform_A.basis.xform(mnormal).normalized()); Vector3 from = p_xform_A.xform(s); Vector3 to = from + motion; Transform from_inv = p_xform_B.affine_inverse(); - Vector3 local_from = from_inv.xform(from-mnormal*mlen*0.1); //start from a little inside the bounding box + Vector3 local_from = from_inv.xform(from - mnormal * mlen * 0.1); //start from a little inside the bounding box Vector3 local_to = from_inv.xform(to); - Vector3 rpos,rnorm; - if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from,local_to,rpos,rnorm)) { + Vector3 rpos, rnorm; + if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm)) { return false; } //shorten the linear velocity so it does not hit, but gets close enough, next frame will hit softly or soft enough Vector3 hitpos = p_xform_B.xform(rpos); - real_t newlen = hitpos.distance_to(from)-(max-min)*0.01; - p_A->set_linear_velocity((mnormal*newlen)/p_step); + real_t newlen = hitpos.distance_to(from) - (max - min) * 0.01; + p_A->set_linear_velocity((mnormal * newlen) / p_step); return true; } - bool BodyPairSW::setup(real_t p_step) { //cannot collide - if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported()==0 && B->get_max_contacts_reported()==0)) { - collided=false; + if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported() == 0 && B->get_max_contacts_reported() == 0)) { + collided = false; return false; } @@ -231,86 +218,79 @@ bool BodyPairSW::setup(real_t p_step) { validate_contacts(); Vector3 offset_A = A->get_transform().get_origin(); - Transform xform_Au = Transform(A->get_transform().basis,Vector3()); + Transform xform_Au = Transform(A->get_transform().basis, Vector3()); Transform xform_A = xform_Au * A->get_shape_transform(shape_A); Transform xform_Bu = B->get_transform(); - xform_Bu.origin-=offset_A; + xform_Bu.origin -= offset_A; Transform xform_B = xform_Bu * B->get_shape_transform(shape_B); - ShapeSW *shape_A_ptr=A->get_shape(shape_A); - ShapeSW *shape_B_ptr=B->get_shape(shape_B); - - bool collided = CollisionSolverSW::solve_static(shape_A_ptr,xform_A,shape_B_ptr,xform_B,_contact_added_callback,this,&sep_axis); - this->collided=collided; + ShapeSW *shape_A_ptr = A->get_shape(shape_A); + ShapeSW *shape_B_ptr = B->get_shape(shape_B); + bool collided = CollisionSolverSW::solve_static(shape_A_ptr, xform_A, shape_B_ptr, xform_B, _contact_added_callback, this, &sep_axis); + this->collided = collided; if (!collided) { //test ccd (currently just a raycast) - if (A->is_continuous_collision_detection_enabled() && A->get_mode()>PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC) { - _test_ccd(p_step,A,shape_A,xform_A,B,shape_B,xform_B); + if (A->is_continuous_collision_detection_enabled() && A->get_mode() > PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC) { + _test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B); } - if (B->is_continuous_collision_detection_enabled() && B->get_mode()>PhysicsServer::BODY_MODE_KINEMATIC && A->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC) { - _test_ccd(p_step,B,shape_B,xform_B,A,shape_A,xform_A); + if (B->is_continuous_collision_detection_enabled() && B->get_mode() > PhysicsServer::BODY_MODE_KINEMATIC && A->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC) { + _test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A); } return false; } - - real_t max_penetration = space->get_contact_max_allowed_penetration(); real_t bias = (real_t)0.3; if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) { - if (shape_A_ptr->get_custom_bias()==0) - bias=shape_B_ptr->get_custom_bias(); - else if (shape_B_ptr->get_custom_bias()==0) - bias=shape_A_ptr->get_custom_bias(); + if (shape_A_ptr->get_custom_bias() == 0) + bias = shape_B_ptr->get_custom_bias(); + else if (shape_B_ptr->get_custom_bias() == 0) + bias = shape_A_ptr->get_custom_bias(); else - bias=(shape_B_ptr->get_custom_bias()+shape_A_ptr->get_custom_bias())*0.5; + bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5; } + real_t inv_dt = 1.0 / p_step; - - real_t inv_dt = 1.0/p_step; - - for(int i=0;i<contact_count;i++) { + for (int i = 0; i < contact_count; i++) { Contact &c = contacts[i]; - c.active=false; + c.active = false; Vector3 global_A = xform_Au.xform(c.local_A); Vector3 global_B = xform_Bu.xform(c.local_B); - real_t depth = c.normal.dot(global_A - global_B); - if (depth<=0) { - c.active=false; + if (depth <= 0) { + c.active = false; continue; } - c.active=true; + c.active = true; #ifdef DEBUG_ENABLED - if (space->is_debugging_contacts()) { - space->add_debug_contact(global_A+offset_A); - space->add_debug_contact(global_B+offset_A); + space->add_debug_contact(global_A + offset_A); + space->add_debug_contact(global_B + offset_A); } #endif - c.rA = global_A-A->get_center_of_mass(); - c.rB = global_B-B->get_center_of_mass()-offset_B; + c.rA = global_A - A->get_center_of_mass(); + c.rB = global_B - B->get_center_of_mass() - offset_B; - // contact query reporting... +// contact query reporting... #if 0 if (A->get_body_type() == PhysicsServer::BODY_CHARACTER) static_cast<CharacterBodySW*>(A)->report_character_contact( global_A, global_B, B ); @@ -323,30 +303,28 @@ bool BodyPairSW::setup(real_t p_step) { #endif if (A->can_report_contacts()) { - Vector3 crA = A->get_angular_velocity().cross( c.rA ) + A->get_linear_velocity(); - A->add_contact(global_A,-c.normal,depth,shape_A,global_B,shape_B,B->get_instance_id(),B->get_self(),crA); + Vector3 crA = A->get_angular_velocity().cross(c.rA) + A->get_linear_velocity(); + A->add_contact(global_A, -c.normal, depth, shape_A, global_B, shape_B, B->get_instance_id(), B->get_self(), crA); } if (B->can_report_contacts()) { - Vector3 crB = B->get_angular_velocity().cross( c.rB ) + B->get_linear_velocity(); - B->add_contact(global_B,c.normal,depth,shape_B,global_A,shape_A,A->get_instance_id(),A->get_self(),crB); + Vector3 crB = B->get_angular_velocity().cross(c.rB) + B->get_linear_velocity(); + B->add_contact(global_B, c.normal, depth, shape_B, global_A, shape_A, A->get_instance_id(), A->get_self(), crB); } - if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC)) { - c.active=false; - collided=false; + if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC)) { + c.active = false; + collided = false; continue; - } - - c.active=true; + c.active = true; // Precompute normal mass, tangent mass, and bias. - Vector3 inertia_A = A->get_inv_inertia_tensor().xform( c.rA.cross( c.normal ) ); - Vector3 inertia_B = B->get_inv_inertia_tensor().xform( c.rB.cross( c.normal ) ); + Vector3 inertia_A = A->get_inv_inertia_tensor().xform(c.rA.cross(c.normal)); + Vector3 inertia_B = B->get_inv_inertia_tensor().xform(c.rB.cross(c.normal)); real_t kNormal = A->get_inv_mass() + B->get_inv_mass(); - kNormal += c.normal.dot( inertia_A.cross(c.rA ) ) + c.normal.dot( inertia_B.cross( c.rB )); + kNormal += c.normal.dot(inertia_A.cross(c.rA)) + c.normal.dot(inertia_B.cross(c.rB)); c.mass_normal = 1.0f / kNormal; #if 1 @@ -354,34 +332,32 @@ bool BodyPairSW::setup(real_t p_step) { #else if (depth > max_penetration) { - c.bias = (depth - max_penetration) * (1.0/(p_step*(1.0/RELAXATION_TIMESTEPS))); + c.bias = (depth - max_penetration) * (1.0 / (p_step * (1.0 / RELAXATION_TIMESTEPS))); } else { real_t approach = -0.1 * (depth - max_penetration) / (CMP_EPSILON + max_penetration); - approach = CLAMP( approach, CMP_EPSILON, 1.0 ); - c.bias = approach * (depth - max_penetration) * (1.0/p_step); + approach = CLAMP(approach, CMP_EPSILON, 1.0); + c.bias = approach * (depth - max_penetration) * (1.0 / p_step); } #endif - c.depth=depth; + c.depth = depth; Vector3 j_vec = c.normal * c.acc_normal_impulse + c.acc_tangent_impulse; - A->apply_impulse( c.rA+A->get_center_of_mass(), -j_vec ); - B->apply_impulse( c.rB+B->get_center_of_mass(), j_vec ); - c.acc_bias_impulse=0; + A->apply_impulse(c.rA + A->get_center_of_mass(), -j_vec); + B->apply_impulse(c.rB + B->get_center_of_mass(), j_vec); + c.acc_bias_impulse = 0; Vector3 jb_vec = c.normal * c.acc_bias_impulse; - A->apply_bias_impulse( c.rA+A->get_center_of_mass(), -jb_vec ); - B->apply_bias_impulse( c.rB+B->get_center_of_mass(), jb_vec ); + A->apply_bias_impulse(c.rA + A->get_center_of_mass(), -jb_vec); + B->apply_bias_impulse(c.rB + B->get_center_of_mass(), jb_vec); - c.bounce = MAX(A->get_bounce(),B->get_bounce()); + c.bounce = MAX(A->get_bounce(), B->get_bounce()); if (c.bounce) { - Vector3 crA = A->get_angular_velocity().cross( c.rA ); - Vector3 crB = B->get_angular_velocity().cross( c.rB ); + Vector3 crA = A->get_angular_velocity().cross(c.rA); + Vector3 crB = B->get_angular_velocity().cross(c.rB); Vector3 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA; //normal impule c.bounce = c.bounce * dv.dot(c.normal); } - - } return true; @@ -392,68 +368,63 @@ void BodyPairSW::solve(real_t p_step) { if (!collided) return; - - for(int i=0;i<contact_count;i++) { + for (int i = 0; i < contact_count; i++) { Contact &c = contacts[i]; if (!c.active) continue; - c.active=false; //try to deactivate, will activate itself if still needed + c.active = false; //try to deactivate, will activate itself if still needed //bias impule - Vector3 crbA = A->get_biased_angular_velocity().cross( c.rA ); - Vector3 crbB = B->get_biased_angular_velocity().cross( c.rB ); + Vector3 crbA = A->get_biased_angular_velocity().cross(c.rA); + Vector3 crbB = B->get_biased_angular_velocity().cross(c.rB); Vector3 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA; real_t vbn = dbv.dot(c.normal); - if (Math::abs(-vbn+c.bias)>MIN_VELOCITY) { + if (Math::abs(-vbn + c.bias) > MIN_VELOCITY) { - real_t jbn = (-vbn + c.bias)*c.mass_normal; + real_t jbn = (-vbn + c.bias) * c.mass_normal; real_t jbnOld = c.acc_bias_impulse; c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f); Vector3 jb = c.normal * (c.acc_bias_impulse - jbnOld); + A->apply_bias_impulse(c.rA + A->get_center_of_mass(), -jb); + B->apply_bias_impulse(c.rB + B->get_center_of_mass(), jb); - A->apply_bias_impulse(c.rA+A->get_center_of_mass(),-jb); - B->apply_bias_impulse(c.rB+B->get_center_of_mass(), jb); - - c.active=true; + c.active = true; } - - Vector3 crA = A->get_angular_velocity().cross( c.rA ); - Vector3 crB = B->get_angular_velocity().cross( c.rB ); + Vector3 crA = A->get_angular_velocity().cross(c.rA); + Vector3 crB = B->get_angular_velocity().cross(c.rB); Vector3 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA; //normal impule real_t vn = dv.dot(c.normal); - if (Math::abs(vn)>MIN_VELOCITY) { + if (Math::abs(vn) > MIN_VELOCITY) { - real_t jn = -(c.bounce + vn)*c.mass_normal; + real_t jn = -(c.bounce + vn) * c.mass_normal; real_t jnOld = c.acc_normal_impulse; c.acc_normal_impulse = MAX(jnOld + jn, 0.0f); + Vector3 j = c.normal * (c.acc_normal_impulse - jnOld); - Vector3 j =c.normal * (c.acc_normal_impulse - jnOld); - - - A->apply_impulse(c.rA+A->get_center_of_mass(),-j); - B->apply_impulse(c.rB+B->get_center_of_mass(), j); + A->apply_impulse(c.rA + A->get_center_of_mass(), -j); + B->apply_impulse(c.rB + B->get_center_of_mass(), j); - c.active=true; + c.active = true; } //friction impule real_t friction = A->get_friction() * B->get_friction(); - Vector3 lvA = A->get_linear_velocity() + A->get_angular_velocity().cross( c.rA ); - Vector3 lvB = B->get_linear_velocity() + B->get_angular_velocity().cross( c.rB ); + Vector3 lvA = A->get_linear_velocity() + A->get_angular_velocity().cross(c.rA); + Vector3 lvB = B->get_linear_velocity() + B->get_angular_velocity().cross(c.rB); Vector3 dtv = lvB - lvA; real_t tn = c.normal.dot(dtv); @@ -466,15 +437,14 @@ void BodyPairSW::solve(real_t p_step) { tv /= tvl; - Vector3 temp1 = A->get_inv_inertia_tensor().xform( c.rA.cross( tv ) ); - Vector3 temp2 = B->get_inv_inertia_tensor().xform( c.rB.cross( tv ) ); + Vector3 temp1 = A->get_inv_inertia_tensor().xform(c.rA.cross(tv)); + Vector3 temp2 = B->get_inv_inertia_tensor().xform(c.rB.cross(tv)); real_t t = -tvl / - (A->get_inv_mass() + B->get_inv_mass() + tv.dot(temp1.cross(c.rA) + temp2.cross(c.rB))); + (A->get_inv_mass() + B->get_inv_mass() + tv.dot(temp1.cross(c.rA) + temp2.cross(c.rB))); Vector3 jt = t * tv; - Vector3 jtOld = c.acc_tangent_impulse; c.acc_tangent_impulse += jt; @@ -483,46 +453,35 @@ void BodyPairSW::solve(real_t p_step) { if (fi_len > CMP_EPSILON && fi_len > jtMax) { - c.acc_tangent_impulse*=jtMax / fi_len; + c.acc_tangent_impulse *= jtMax / fi_len; } jt = c.acc_tangent_impulse - jtOld; + A->apply_impulse(c.rA + A->get_center_of_mass(), -jt); + B->apply_impulse(c.rB + B->get_center_of_mass(), jt); - A->apply_impulse( c.rA+A->get_center_of_mass(), -jt ); - B->apply_impulse( c.rB+B->get_center_of_mass(), jt ); - - c.active=true; - + c.active = true; } - - } - } - - - - -BodyPairSW::BodyPairSW(BodySW *p_A, int p_shape_A,BodySW *p_B, int p_shape_B) : ConstraintSW(_arr,2) { - - A=p_A; - B=p_B; - shape_A=p_shape_A; - shape_B=p_shape_B; - space=A->get_space(); - A->add_constraint(this,0); - B->add_constraint(this,1); - contact_count=0; - collided=false; - +BodyPairSW::BodyPairSW(BodySW *p_A, int p_shape_A, BodySW *p_B, int p_shape_B) + : ConstraintSW(_arr, 2) { + + A = p_A; + B = p_B; + shape_A = p_shape_A; + shape_B = p_shape_B; + space = A->get_space(); + A->add_constraint(this, 0); + B->add_constraint(this, 1); + contact_count = 0; + collided = false; } - BodyPairSW::~BodyPairSW() { A->remove_constraint(this); B->remove_constraint(this); - } diff --git a/servers/physics/body_pair_sw.h b/servers/physics/body_pair_sw.h index f282a56b9e..fa426adafd 100644 --- a/servers/physics/body_pair_sw.h +++ b/servers/physics/body_pair_sw.h @@ -35,7 +35,7 @@ class BodyPairSW : public ConstraintSW { enum { - MAX_CONTACTS=4 + MAX_CONTACTS = 4 }; union { @@ -50,22 +50,21 @@ class BodyPairSW : public ConstraintSW { int shape_A; int shape_B; - struct Contact { Vector3 position; Vector3 normal; Vector3 local_A, local_B; - real_t acc_normal_impulse; // accumulated normal impulse (Pn) - Vector3 acc_tangent_impulse; // accumulated tangent impulse (Pt) - real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb) + real_t acc_normal_impulse; // accumulated normal impulse (Pn) + Vector3 acc_tangent_impulse; // accumulated tangent impulse (Pt) + real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb) real_t mass_normal; real_t bias; real_t bounce; real_t depth; bool active; - Vector3 rA,rB; // Offset in world orientation with respect to center of mass + Vector3 rA, rB; // Offset in world orientation with respect to center of mass }; Vector3 offset_B; //use local A coordinates to avoid numerical issues on collision detection @@ -76,24 +75,21 @@ class BodyPairSW : public ConstraintSW { bool collided; int cc; + static void _contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata); - static void _contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata); - - void contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B); + void contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B); void validate_contacts(); - bool _test_ccd(real_t p_step,BodySW *p_A, int p_shape_A,const Transform& p_xform_A,BodySW *p_B, int p_shape_B,const Transform& p_xform_B); + bool _test_ccd(real_t p_step, BodySW *p_A, int p_shape_A, const Transform &p_xform_A, BodySW *p_B, int p_shape_B, const Transform &p_xform_B); SpaceSW *space; public: - bool setup(real_t p_step); void solve(real_t p_step); - BodyPairSW(BodySW *p_A, int p_shape_A,BodySW *p_B, int p_shape_B); + BodyPairSW(BodySW *p_A, int p_shape_A, BodySW *p_B, int p_shape_B); ~BodyPairSW(); - }; #endif // BODY_PAIR__SW_H diff --git a/servers/physics/body_sw.cpp b/servers/physics/body_sw.cpp index 7fcd767268..a4fc694f67 100644 --- a/servers/physics/body_sw.cpp +++ b/servers/physics/body_sw.cpp @@ -27,18 +27,17 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "body_sw.h" -#include "space_sw.h" #include "area_sw.h" +#include "space_sw.h" void BodySW::_update_inertia() { if (get_space() && !inertia_update_list.in_list()) get_space()->body_add_to_inertia_update_list(&inertia_update_list); - } void BodySW::_update_transform_dependant() { - + center_of_mass = get_transform().basis.xform(center_of_mass_local); principal_inertia_axes = get_transform().basis * principal_inertia_axes_local; @@ -47,30 +46,29 @@ void BodySW::_update_transform_dependant() { Basis tbt = tb.transposed(); tb.scale(_inv_inertia); _inv_inertia_tensor = tb * tbt; - } void BodySW::update_inertias() { //update shapes and motions - switch(mode) { + switch (mode) { case PhysicsServer::BODY_MODE_RIGID: { //update tensor for all shapes, not the best way but should be somehow OK. (inspired from bullet) - real_t total_area=0; + real_t total_area = 0; - for (int i=0;i<get_shape_count();i++) { + for (int i = 0; i < get_shape_count(); i++) { - total_area+=get_shape_area(i); + total_area += get_shape_area(i); } // We have to recompute the center of mass center_of_mass_local.zero(); - for (int i=0; i<get_shape_count(); i++) { - real_t area=get_shape_area(i); + for (int i = 0; i < get_shape_count(); i++) { + real_t area = get_shape_area(i); real_t mass = area * this->mass / total_area; @@ -84,25 +82,23 @@ void BodySW::update_inertias() { Basis inertia_tensor; inertia_tensor.set_zero(); - for (int i=0;i<get_shape_count();i++) { + for (int i = 0; i < get_shape_count(); i++) { - const ShapeSW* shape=get_shape(i); + const ShapeSW *shape = get_shape(i); - real_t area=get_shape_area(i); + real_t area = get_shape_area(i); real_t mass = area * this->mass / total_area; - Basis shape_inertia_tensor=shape->get_moment_of_inertia(mass).to_diagonal_matrix(); - Transform shape_transform=get_shape_transform(i); + Basis shape_inertia_tensor = shape->get_moment_of_inertia(mass).to_diagonal_matrix(); + Transform shape_transform = get_shape_transform(i); Basis shape_basis = shape_transform.basis.orthonormalized(); // NOTE: we don't take the scale of collision shapes into account when computing the inertia tensor! shape_inertia_tensor = shape_basis * shape_inertia_tensor * shape_basis.transposed(); Vector3 shape_origin = shape_transform.origin - center_of_mass_local; - inertia_tensor += shape_inertia_tensor + (Basis()*shape_origin.dot(shape_origin)-shape_origin.outer(shape_origin))*mass; - - + inertia_tensor += shape_inertia_tensor + (Basis() * shape_origin.dot(shape_origin) - shape_origin.outer(shape_origin)) * mass; } // Compute the principal axes of inertia @@ -110,9 +106,9 @@ void BodySW::update_inertias() { _inv_inertia = inertia_tensor.get_main_diagonal().inverse(); if (mass) - _inv_mass=1.0/mass; + _inv_mass = 1.0 / mass; else - _inv_mass=0; + _inv_mass = 0; } break; @@ -120,42 +116,39 @@ void BodySW::update_inertias() { case PhysicsServer::BODY_MODE_STATIC: { _inv_inertia_tensor.set_zero(); - _inv_mass=0; + _inv_mass = 0; } break; case PhysicsServer::BODY_MODE_CHARACTER: { _inv_inertia_tensor.set_zero(); - _inv_mass=1.0/mass; + _inv_mass = 1.0 / mass; } break; } - //_update_shapes(); _update_transform_dependant(); } - - void BodySW::set_active(bool p_active) { - if (active==p_active) + if (active == p_active) return; - active=p_active; + active = p_active; if (!p_active) { if (get_space()) get_space()->body_remove_from_active_list(&active_list); } else { - if (mode==PhysicsServer::BODY_MODE_STATIC) + if (mode == PhysicsServer::BODY_MODE_STATIC) return; //static bodies can't become active if (get_space()) get_space()->body_add_to_active_list(&active_list); //still_time=0; } -/* + /* if (!space) return; @@ -168,43 +161,41 @@ void BodySW::set_active(bool p_active) { */ } - - void BodySW::set_param(PhysicsServer::BodyParameter p_param, real_t p_value) { - switch(p_param) { + switch (p_param) { case PhysicsServer::BODY_PARAM_BOUNCE: { - bounce=p_value; + bounce = p_value; } break; case PhysicsServer::BODY_PARAM_FRICTION: { - friction=p_value; + friction = p_value; } break; case PhysicsServer::BODY_PARAM_MASS: { - ERR_FAIL_COND(p_value<=0); - mass=p_value; + ERR_FAIL_COND(p_value <= 0); + mass = p_value; _update_inertia(); } break; case PhysicsServer::BODY_PARAM_GRAVITY_SCALE: { - gravity_scale=p_value; + gravity_scale = p_value; } break; case PhysicsServer::BODY_PARAM_LINEAR_DAMP: { - linear_damp=p_value; + linear_damp = p_value; } break; case PhysicsServer::BODY_PARAM_ANGULAR_DAMP: { - angular_damp=p_value; + angular_damp = p_value; } break; - default:{} + default: {} } } real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const { - switch(p_param) { + switch (p_param) { case PhysicsServer::BODY_PARAM_BOUNCE: { return bounce; @@ -228,7 +219,7 @@ real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const { return angular_damp; } break; - default:{} + default: {} } return 0; @@ -236,35 +227,35 @@ real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const { void BodySW::set_mode(PhysicsServer::BodyMode p_mode) { - PhysicsServer::BodyMode prev=mode; - mode=p_mode; + PhysicsServer::BodyMode prev = mode; + mode = p_mode; - switch(p_mode) { + switch (p_mode) { //CLEAR UP EVERYTHING IN CASE IT NOT WORKS! case PhysicsServer::BODY_MODE_STATIC: case PhysicsServer::BODY_MODE_KINEMATIC: { _set_inv_transform(get_transform().affine_inverse()); - _inv_mass=0; - _set_static(p_mode==PhysicsServer::BODY_MODE_STATIC); + _inv_mass = 0; + _set_static(p_mode == PhysicsServer::BODY_MODE_STATIC); //set_active(p_mode==PhysicsServer::BODY_MODE_KINEMATIC); - set_active(p_mode==PhysicsServer::BODY_MODE_KINEMATIC && contacts.size()); - linear_velocity=Vector3(); - angular_velocity=Vector3(); - if (mode==PhysicsServer::BODY_MODE_KINEMATIC && prev!=mode) { - first_time_kinematic=true; + set_active(p_mode == PhysicsServer::BODY_MODE_KINEMATIC && contacts.size()); + linear_velocity = Vector3(); + angular_velocity = Vector3(); + if (mode == PhysicsServer::BODY_MODE_KINEMATIC && prev != mode) { + first_time_kinematic = true; } } break; case PhysicsServer::BODY_MODE_RIGID: { - _inv_mass=mass>0?(1.0/mass):0; + _inv_mass = mass > 0 ? (1.0 / mass) : 0; _set_static(false); } break; case PhysicsServer::BODY_MODE_CHARACTER: { - _inv_mass=mass>0?(1.0/mass):0; + _inv_mass = mass > 0 ? (1.0 / mass) : 0; _set_static(false); } break; } @@ -274,7 +265,6 @@ void BodySW::set_mode(PhysicsServer::BodyMode p_mode) { if (get_space()) _update_queries(); */ - } PhysicsServer::BodyMode BodySW::get_mode() const { @@ -286,35 +276,33 @@ void BodySW::_shapes_changed() { _update_inertia(); } -void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant& p_variant) { +void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant &p_variant) { - switch(p_state) { + switch (p_state) { case PhysicsServer::BODY_STATE_TRANSFORM: { - - if (mode==PhysicsServer::BODY_MODE_KINEMATIC) { - new_transform=p_variant; + if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { + new_transform = p_variant; //wakeup_neighbours(); set_active(true); if (first_time_kinematic) { _set_transform(p_variant); _set_inv_transform(get_transform().affine_inverse()); - first_time_kinematic=false; + first_time_kinematic = false; } - } else if (mode==PhysicsServer::BODY_MODE_STATIC) { + } else if (mode == PhysicsServer::BODY_MODE_STATIC) { _set_transform(p_variant); _set_inv_transform(get_transform().affine_inverse()); wakeup_neighbours(); } else { Transform t = p_variant; t.orthonormalize(); - new_transform=get_transform(); //used as old to compute motion - if (new_transform==t) + new_transform = get_transform(); //used as old to compute motion + if (new_transform == t) break; _set_transform(t); _set_inv_transform(get_transform().inverse()); - } wakeup(); @@ -325,7 +313,7 @@ void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant& p_varian if (mode==PhysicsServer::BODY_MODE_STATIC) break; */ - linear_velocity=p_variant; + linear_velocity = p_variant; wakeup(); } break; case PhysicsServer::BODY_STATE_ANGULAR_VELOCITY: { @@ -333,38 +321,37 @@ void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant& p_varian if (mode!=PhysicsServer::BODY_MODE_RIGID) break; */ - angular_velocity=p_variant; + angular_velocity = p_variant; wakeup(); } break; case PhysicsServer::BODY_STATE_SLEEPING: { //? - if (mode==PhysicsServer::BODY_MODE_STATIC || mode==PhysicsServer::BODY_MODE_KINEMATIC) + if (mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC) break; - bool do_sleep=p_variant; + bool do_sleep = p_variant; if (do_sleep) { - linear_velocity=Vector3(); + linear_velocity = Vector3(); //biased_linear_velocity=Vector3(); - angular_velocity=Vector3(); + angular_velocity = Vector3(); //biased_angular_velocity=Vector3(); set_active(false); } else { - if (mode!=PhysicsServer::BODY_MODE_STATIC) + if (mode != PhysicsServer::BODY_MODE_STATIC) set_active(true); } } break; case PhysicsServer::BODY_STATE_CAN_SLEEP: { - can_sleep=p_variant; - if (mode==PhysicsServer::BODY_MODE_RIGID && !active && !can_sleep) + can_sleep = p_variant; + if (mode == PhysicsServer::BODY_MODE_RIGID && !active && !can_sleep) set_active(true); } break; } - } Variant BodySW::get_state(PhysicsServer::BodyState p_state) const { - switch(p_state) { + switch (p_state) { case PhysicsServer::BODY_STATE_TRANSFORM: { return get_transform(); } break; @@ -385,8 +372,7 @@ Variant BodySW::get_state(PhysicsServer::BodyState p_state) const { return Variant(); } - -void BodySW::set_space(SpaceSW *p_space){ +void BodySW::set_space(SpaceSW *p_space) { if (get_space()) { @@ -396,7 +382,6 @@ void BodySW::set_space(SpaceSW *p_space){ get_space()->body_remove_from_active_list(&active_list); if (direct_state_query_list.in_list()) get_space()->body_remove_from_state_query_list(&direct_state_query_list); - } _set_space(p_space); @@ -413,19 +398,17 @@ void BodySW::set_space(SpaceSW *p_space){ set_active(true); } */ - } - first_integration=true; - + first_integration = true; } void BodySW::_compute_area_gravity_and_dampenings(const AreaSW *p_area) { if (p_area->is_gravity_point()) { - if(p_area->get_gravity_distance_scale() > 0) { + if (p_area->get_gravity_distance_scale() > 0) { Vector3 v = p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin(); - gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale()+1, 2) ); + gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale() + 1, 2)); } else { gravity += (p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin()).normalized() * p_area->get_gravity(); } @@ -439,8 +422,7 @@ void BodySW::_compute_area_gravity_and_dampenings(const AreaSW *p_area) { void BodySW::integrate_forces(real_t p_step) { - - if (mode==PhysicsServer::BODY_MODE_STATIC) + if (mode == PhysicsServer::BODY_MODE_STATIC) return; AreaSW *def_area = get_space()->get_default_area(); @@ -450,192 +432,179 @@ void BodySW::integrate_forces(real_t p_step) { int ac = areas.size(); bool stopped = false; - gravity = Vector3(0,0,0); + gravity = Vector3(0, 0, 0); area_linear_damp = 0; area_angular_damp = 0; if (ac) { areas.sort(); const AreaCMP *aa = &areas[0]; // damp_area = aa[ac-1].area; - for(int i=ac-1;i>=0 && !stopped;i--) { - PhysicsServer::AreaSpaceOverrideMode mode=aa[i].area->get_space_override_mode(); + for (int i = ac - 1; i >= 0 && !stopped; i--) { + PhysicsServer::AreaSpaceOverrideMode mode = aa[i].area->get_space_override_mode(); switch (mode) { case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE: case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: { _compute_area_gravity_and_dampenings(aa[i].area); - stopped = mode==PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE; + stopped = mode == PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE; } break; case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE: case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: { - gravity = Vector3(0,0,0); + gravity = Vector3(0, 0, 0); area_angular_damp = 0; area_linear_damp = 0; _compute_area_gravity_and_dampenings(aa[i].area); - stopped = mode==PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE; + stopped = mode == PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE; } break; default: {} } } } - if( !stopped ) { + if (!stopped) { _compute_area_gravity_and_dampenings(def_area); } - gravity*=gravity_scale; + gravity *= gravity_scale; // If less than 0, override dampenings with that of the Body - if (angular_damp>=0) - area_angular_damp=angular_damp; + if (angular_damp >= 0) + area_angular_damp = angular_damp; /* else area_angular_damp=damp_area->get_angular_damp(); */ - if (linear_damp>=0) - area_linear_damp=linear_damp; + if (linear_damp >= 0) + area_linear_damp = linear_damp; /* else area_linear_damp=damp_area->get_linear_damp(); */ - Vector3 motion; - bool do_motion=false; + bool do_motion = false; - if (mode==PhysicsServer::BODY_MODE_KINEMATIC) { + if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { //compute motion, angular and etc. velocities from prev transform - linear_velocity = (new_transform.origin - get_transform().origin)/p_step; + linear_velocity = (new_transform.origin - get_transform().origin) / p_step; //compute a FAKE angular velocity, not so easy - Basis rot=new_transform.basis.orthonormalized().transposed() * get_transform().basis.orthonormalized(); + Basis rot = new_transform.basis.orthonormalized().transposed() * get_transform().basis.orthonormalized(); Vector3 axis; real_t angle; - rot.get_axis_and_angle(axis,angle); + rot.get_axis_and_angle(axis, angle); axis.normalize(); - angular_velocity=axis.normalized() * (angle/p_step); + angular_velocity = axis.normalized() * (angle / p_step); motion = new_transform.origin - get_transform().origin; - do_motion=true; + do_motion = true; } else { if (!omit_force_integration && !first_integration) { //overriden by direct state query - Vector3 force=gravity*mass; - force+=applied_force; - Vector3 torque=applied_torque; + Vector3 force = gravity * mass; + force += applied_force; + Vector3 torque = applied_torque; real_t damp = 1.0 - p_step * area_linear_damp; - if (damp<0) // reached zero in the given time - damp=0; + if (damp < 0) // reached zero in the given time + damp = 0; real_t angular_damp = 1.0 - p_step * area_angular_damp; - if (angular_damp<0) // reached zero in the given time - angular_damp=0; + if (angular_damp < 0) // reached zero in the given time + angular_damp = 0; - linear_velocity*=damp; - angular_velocity*=angular_damp; + linear_velocity *= damp; + angular_velocity *= angular_damp; - linear_velocity+=_inv_mass * force * p_step; - angular_velocity+=_inv_inertia_tensor.xform(torque)*p_step; + linear_velocity += _inv_mass * force * p_step; + angular_velocity += _inv_inertia_tensor.xform(torque) * p_step; } if (continuous_cd) { - motion=linear_velocity*p_step; - do_motion=true; + motion = linear_velocity * p_step; + do_motion = true; } - } - applied_force=Vector3(); - applied_torque=Vector3(); - first_integration=false; + applied_force = Vector3(); + applied_torque = Vector3(); + first_integration = false; //motion=linear_velocity*p_step; - biased_angular_velocity=Vector3(); - biased_linear_velocity=Vector3(); - + biased_angular_velocity = Vector3(); + biased_linear_velocity = Vector3(); - if (do_motion) {//shapes temporarily extend for raycast + if (do_motion) { //shapes temporarily extend for raycast _update_shapes_with_motion(motion); } - - def_area=NULL; // clear the area, so it is set in the next frame - contact_count=0; - + def_area = NULL; // clear the area, so it is set in the next frame + contact_count = 0; } void BodySW::integrate_velocities(real_t p_step) { - if (mode==PhysicsServer::BODY_MODE_STATIC) + if (mode == PhysicsServer::BODY_MODE_STATIC) return; if (fi_callback) get_space()->body_add_to_state_query_list(&direct_state_query_list); - if (mode==PhysicsServer::BODY_MODE_KINEMATIC) { + if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { - _set_transform(new_transform,false); + _set_transform(new_transform, false); _set_inv_transform(new_transform.affine_inverse()); - if (contacts.size()==0 && linear_velocity==Vector3() && angular_velocity==Vector3()) + if (contacts.size() == 0 && linear_velocity == Vector3() && angular_velocity == Vector3()) set_active(false); //stopped moving, deactivate return; } - - //apply axis lock - if (axis_lock!=PhysicsServer::BODY_AXIS_LOCK_DISABLED) { + if (axis_lock != PhysicsServer::BODY_AXIS_LOCK_DISABLED) { - - int axis=axis_lock-1; - for(int i=0;i<3;i++) { - if (i==axis) { - linear_velocity[i]=0; - biased_linear_velocity[i]=0; + int axis = axis_lock - 1; + for (int i = 0; i < 3; i++) { + if (i == axis) { + linear_velocity[i] = 0; + biased_linear_velocity[i] = 0; } else { - angular_velocity[i]=0; - biased_angular_velocity[i]=0; + angular_velocity[i] = 0; + biased_angular_velocity[i] = 0; } } - } - - Vector3 total_angular_velocity = angular_velocity+biased_angular_velocity; - - + Vector3 total_angular_velocity = angular_velocity + biased_angular_velocity; real_t ang_vel = total_angular_velocity.length(); Transform transform = get_transform(); - - if (ang_vel!=0.0) { + if (ang_vel != 0.0) { Vector3 ang_vel_axis = total_angular_velocity / ang_vel; - Basis rot( ang_vel_axis, ang_vel*p_step ); + Basis rot(ang_vel_axis, ang_vel * p_step); Basis identity3(1, 0, 0, 0, 1, 0, 0, 0, 1); transform.origin += ((identity3 - rot) * transform.basis).xform(center_of_mass_local); transform.basis = rot * transform.basis; transform.orthonormalize(); } - Vector3 total_linear_velocity=linear_velocity+biased_linear_velocity; + Vector3 total_linear_velocity = linear_velocity + biased_linear_velocity; /*for(int i=0;i<3;i++) { if (axis_lock&(1<<i)) { transform.origin[i]=0.0; } }*/ - transform.origin+=total_linear_velocity * p_step; + transform.origin += total_linear_velocity * p_step; _set_transform(transform); _set_inv_transform(get_transform().inverse()); @@ -684,18 +653,18 @@ void BodySW::simulate_motion(const Transform& p_xform,real_t p_step) { void BodySW::wakeup_neighbours() { - for(Map<ConstraintSW*,int>::Element *E=constraint_map.front();E;E=E->next()) { + for (Map<ConstraintSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) { - const ConstraintSW *c=E->key(); + const ConstraintSW *c = E->key(); BodySW **n = c->get_body_ptr(); - int bc=c->get_body_count(); + int bc = c->get_body_count(); - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { - if (i==E->get()) + if (i == E->get()) continue; BodySW *b = n[i]; - if (b->mode!=PhysicsServer::BODY_MODE_RIGID) + if (b->mode != PhysicsServer::BODY_MODE_RIGID) continue; if (!b->is_active()) @@ -706,109 +675,96 @@ void BodySW::wakeup_neighbours() { void BodySW::call_queries() { - if (fi_callback) { PhysicsDirectBodyStateSW *dbs = PhysicsDirectBodyStateSW::singleton; - dbs->body=this; + dbs->body = this; - Variant v=dbs; + Variant v = dbs; Object *obj = ObjectDB::get_instance(fi_callback->id); if (!obj) { - set_force_integration_callback(0,StringName()); + set_force_integration_callback(0, StringName()); } else { - const Variant *vp[2]={&v,&fi_callback->udata}; + const Variant *vp[2] = { &v, &fi_callback->udata }; Variant::CallError ce; - int argc=(fi_callback->udata.get_type()==Variant::NIL)?1:2; - obj->call(fi_callback->method,vp,argc,ce); + int argc = (fi_callback->udata.get_type() == Variant::NIL) ? 1 : 2; + obj->call(fi_callback->method, vp, argc, ce); } - - } - - } +bool BodySW::sleep_test(real_t p_step) { -bool BodySW::sleep_test(real_t p_step) { - - if (mode==PhysicsServer::BODY_MODE_STATIC || mode==PhysicsServer::BODY_MODE_KINEMATIC) + if (mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC) return true; // - else if (mode==PhysicsServer::BODY_MODE_CHARACTER) + else if (mode == PhysicsServer::BODY_MODE_CHARACTER) return !active; // characters don't sleep unless asked to sleep else if (!can_sleep) return false; + if (Math::abs(angular_velocity.length()) < get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold() * get_space()->get_body_linear_velocity_sleep_treshold()) { - - - if (Math::abs(angular_velocity.length())<get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold()*get_space()->get_body_linear_velocity_sleep_treshold()) { - - still_time+=p_step; + still_time += p_step; return still_time > get_space()->get_body_time_to_sleep(); } else { - still_time=0; //maybe this should be set to 0 on set_active? + still_time = 0; //maybe this should be set to 0 on set_active? return false; } } - -void BodySW::set_force_integration_callback(ObjectID p_id,const StringName& p_method,const Variant& p_udata) { +void BodySW::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) { if (fi_callback) { memdelete(fi_callback); - fi_callback=NULL; + fi_callback = NULL; } + if (p_id != 0) { - if (p_id!=0) { - - fi_callback=memnew(ForceIntegrationCallback); - fi_callback->id=p_id; - fi_callback->method=p_method; - fi_callback->udata=p_udata; + fi_callback = memnew(ForceIntegrationCallback); + fi_callback->id = p_id; + fi_callback->method = p_method; + fi_callback->udata = p_udata; } - } -BodySW::BodySW() : CollisionObjectSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) { - +BodySW::BodySW() + : CollisionObjectSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) { - mode=PhysicsServer::BODY_MODE_RIGID; - active=true; + mode = PhysicsServer::BODY_MODE_RIGID; + active = true; - mass=1; + mass = 1; //_inv_inertia=Transform(); - _inv_mass=1; - bounce=0; - friction=1; - omit_force_integration=false; + _inv_mass = 1; + bounce = 0; + friction = 1; + omit_force_integration = false; //applied_torque=0; - island_step=0; - island_next=NULL; - island_list_next=NULL; - first_time_kinematic=false; - first_integration=false; + island_step = 0; + island_next = NULL; + island_list_next = NULL; + first_time_kinematic = false; + first_integration = false; _set_static(false); - contact_count=0; - gravity_scale=1.0; + contact_count = 0; + gravity_scale = 1.0; - area_angular_damp=0; - area_linear_damp=0; - - still_time=0; - continuous_cd=false; - can_sleep=false; - fi_callback=NULL; - axis_lock=PhysicsServer::BODY_AXIS_LOCK_DISABLED; + area_angular_damp = 0; + area_linear_damp = 0; + still_time = 0; + continuous_cd = false; + can_sleep = false; + fi_callback = NULL; + axis_lock = PhysicsServer::BODY_AXIS_LOCK_DISABLED; } BodySW::~BodySW() { @@ -817,9 +773,9 @@ BodySW::~BodySW() { memdelete(fi_callback); } -PhysicsDirectBodyStateSW *PhysicsDirectBodyStateSW::singleton=NULL; +PhysicsDirectBodyStateSW *PhysicsDirectBodyStateSW::singleton = NULL; -PhysicsDirectSpaceState* PhysicsDirectBodyStateSW::get_space_state() { +PhysicsDirectSpaceState *PhysicsDirectBodyStateSW::get_space_state() { return body->get_space()->get_direct_state(); } diff --git a/servers/physics/body_sw.h b/servers/physics/body_sw.h index 2383d2d688..4b1af6fca5 100644 --- a/servers/physics/body_sw.h +++ b/servers/physics/body_sw.h @@ -29,16 +29,14 @@ #ifndef BODY_SW_H #define BODY_SW_H +#include "area_sw.h" #include "collision_object_sw.h" #include "vset.h" -#include "area_sw.h" class ConstraintSW; - class BodySW : public CollisionObjectSW { - PhysicsServer::BodyMode mode; Vector3 linear_velocity; @@ -78,7 +76,6 @@ class BodySW : public CollisionObjectSW { real_t area_angular_damp; real_t area_linear_damp; - SelfList<BodySW> active_list; SelfList<BodySW> inertia_update_list; SelfList<BodySW> direct_state_query_list; @@ -96,23 +93,25 @@ class BodySW : public CollisionObjectSW { virtual void _shapes_changed(); Transform new_transform; - Map<ConstraintSW*,int> constraint_map; + Map<ConstraintSW *, int> constraint_map; struct AreaCMP { AreaSW *area; int refCount; - _FORCE_INLINE_ bool operator==(const AreaCMP& p_cmp) const { return area->get_self() == p_cmp.area->get_self();} - _FORCE_INLINE_ bool operator<(const AreaCMP& p_cmp) const { return area->get_priority() < p_cmp.area->get_priority();} + _FORCE_INLINE_ bool operator==(const AreaCMP &p_cmp) const { return area->get_self() == p_cmp.area->get_self(); } + _FORCE_INLINE_ bool operator<(const AreaCMP &p_cmp) const { return area->get_priority() < p_cmp.area->get_priority(); } _FORCE_INLINE_ AreaCMP() {} - _FORCE_INLINE_ AreaCMP(AreaSW *p_area) { area=p_area; refCount=1;} + _FORCE_INLINE_ AreaCMP(AreaSW *p_area) { + area = p_area; + refCount = 1; + } }; Vector<AreaCMP> areas; struct Contact { - Vector3 local_pos; Vector3 local_normal; real_t depth; @@ -136,7 +135,6 @@ class BodySW : public CollisionObjectSW { ForceIntegrationCallback *fi_callback; - uint64_t island_step; BodySW *island_next; BodySW *island_list_next; @@ -145,16 +143,14 @@ class BodySW : public CollisionObjectSW { _FORCE_INLINE_ void _update_transform_dependant(); -friend class PhysicsDirectBodyStateSW; // i give up, too many functions to expose + friend class PhysicsDirectBodyStateSW; // i give up, too many functions to expose public: - - - void set_force_integration_callback(ObjectID p_id,const StringName& p_method,const Variant& p_udata=Variant()); + void set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata = Variant()); _FORCE_INLINE_ void add_area(AreaSW *p_area) { int index = areas.find(AreaCMP(p_area)); - if( index > -1 ) { + if (index > -1) { areas[index].refCount += 1; } else { areas.ordered_insert(AreaCMP(p_area)); @@ -163,77 +159,80 @@ public: _FORCE_INLINE_ void remove_area(AreaSW *p_area) { int index = areas.find(AreaCMP(p_area)); - if( index > -1 ) { + if (index > -1) { areas[index].refCount -= 1; - if( areas[index].refCount < 1 ) + if (areas[index].refCount < 1) areas.remove(index); } } - _FORCE_INLINE_ void set_max_contacts_reported(int p_size) { contacts.resize(p_size); contact_count=0; if (mode==PhysicsServer::BODY_MODE_KINEMATIC && p_size) set_active(true);} + _FORCE_INLINE_ void set_max_contacts_reported(int p_size) { + contacts.resize(p_size); + contact_count = 0; + if (mode == PhysicsServer::BODY_MODE_KINEMATIC && p_size) set_active(true); + } _FORCE_INLINE_ int get_max_contacts_reported() const { return contacts.size(); } _FORCE_INLINE_ bool can_report_contacts() const { return !contacts.empty(); } - _FORCE_INLINE_ void add_contact(const Vector3& p_local_pos,const Vector3& p_local_normal, real_t p_depth, int p_local_shape, const Vector3& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector3& p_collider_velocity_at_pos); - + _FORCE_INLINE_ void add_contact(const Vector3 &p_local_pos, const Vector3 &p_local_normal, real_t p_depth, int p_local_shape, const Vector3 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector3 &p_collider_velocity_at_pos); - _FORCE_INLINE_ void add_exception(const RID& p_exception) { exceptions.insert(p_exception);} - _FORCE_INLINE_ void remove_exception(const RID& p_exception) { exceptions.erase(p_exception);} - _FORCE_INLINE_ bool has_exception(const RID& p_exception) const { return exceptions.has(p_exception);} - _FORCE_INLINE_ const VSet<RID>& get_exceptions() const { return exceptions;} + _FORCE_INLINE_ void add_exception(const RID &p_exception) { exceptions.insert(p_exception); } + _FORCE_INLINE_ void remove_exception(const RID &p_exception) { exceptions.erase(p_exception); } + _FORCE_INLINE_ bool has_exception(const RID &p_exception) const { return exceptions.has(p_exception); } + _FORCE_INLINE_ const VSet<RID> &get_exceptions() const { return exceptions; } _FORCE_INLINE_ uint64_t get_island_step() const { return island_step; } - _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; } + _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; } - _FORCE_INLINE_ BodySW* get_island_next() const { return island_next; } - _FORCE_INLINE_ void set_island_next(BodySW* p_next) { island_next=p_next; } + _FORCE_INLINE_ BodySW *get_island_next() const { return island_next; } + _FORCE_INLINE_ void set_island_next(BodySW *p_next) { island_next = p_next; } - _FORCE_INLINE_ BodySW* get_island_list_next() const { return island_list_next; } - _FORCE_INLINE_ void set_island_list_next(BodySW* p_next) { island_list_next=p_next; } + _FORCE_INLINE_ BodySW *get_island_list_next() const { return island_list_next; } + _FORCE_INLINE_ void set_island_list_next(BodySW *p_next) { island_list_next = p_next; } - _FORCE_INLINE_ void add_constraint(ConstraintSW* p_constraint, int p_pos) { constraint_map[p_constraint]=p_pos; } - _FORCE_INLINE_ void remove_constraint(ConstraintSW* p_constraint) { constraint_map.erase(p_constraint); } - const Map<ConstraintSW*,int>& get_constraint_map() const { return constraint_map; } + _FORCE_INLINE_ void add_constraint(ConstraintSW *p_constraint, int p_pos) { constraint_map[p_constraint] = p_pos; } + _FORCE_INLINE_ void remove_constraint(ConstraintSW *p_constraint) { constraint_map.erase(p_constraint); } + const Map<ConstraintSW *, int> &get_constraint_map() const { return constraint_map; } - _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration=p_omit_force_integration; } + _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration = p_omit_force_integration; } _FORCE_INLINE_ bool get_omit_force_integration() const { return omit_force_integration; } _FORCE_INLINE_ Basis get_principal_inertia_axes() const { return principal_inertia_axes; } _FORCE_INLINE_ Vector3 get_center_of_mass() const { return center_of_mass; } - _FORCE_INLINE_ Vector3 xform_local_to_principal(const Vector3& p_pos) const { return principal_inertia_axes_local.xform(p_pos - center_of_mass_local); } + _FORCE_INLINE_ Vector3 xform_local_to_principal(const Vector3 &p_pos) const { return principal_inertia_axes_local.xform(p_pos - center_of_mass_local); } - _FORCE_INLINE_ void set_linear_velocity(const Vector3& p_velocity) {linear_velocity=p_velocity; } + _FORCE_INLINE_ void set_linear_velocity(const Vector3 &p_velocity) { linear_velocity = p_velocity; } _FORCE_INLINE_ Vector3 get_linear_velocity() const { return linear_velocity; } - _FORCE_INLINE_ void set_angular_velocity(const Vector3& p_velocity) { angular_velocity=p_velocity; } + _FORCE_INLINE_ void set_angular_velocity(const Vector3 &p_velocity) { angular_velocity = p_velocity; } _FORCE_INLINE_ Vector3 get_angular_velocity() const { return angular_velocity; } - _FORCE_INLINE_ const Vector3& get_biased_linear_velocity() const { return biased_linear_velocity; } - _FORCE_INLINE_ const Vector3& get_biased_angular_velocity() const { return biased_angular_velocity; } + _FORCE_INLINE_ const Vector3 &get_biased_linear_velocity() const { return biased_linear_velocity; } + _FORCE_INLINE_ const Vector3 &get_biased_angular_velocity() const { return biased_angular_velocity; } - _FORCE_INLINE_ void apply_impulse(const Vector3& p_pos, const Vector3& p_j) { + _FORCE_INLINE_ void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) { linear_velocity += p_j * _inv_mass; - angular_velocity += _inv_inertia_tensor.xform( (p_pos-center_of_mass).cross(p_j) ); + angular_velocity += _inv_inertia_tensor.xform((p_pos - center_of_mass).cross(p_j)); } - _FORCE_INLINE_ void apply_torque_impulse(const Vector3& p_j) { + _FORCE_INLINE_ void apply_torque_impulse(const Vector3 &p_j) { angular_velocity += _inv_inertia_tensor.xform(p_j); } - _FORCE_INLINE_ void apply_bias_impulse(const Vector3& p_pos, const Vector3& p_j) { + _FORCE_INLINE_ void apply_bias_impulse(const Vector3 &p_pos, const Vector3 &p_j) { biased_linear_velocity += p_j * _inv_mass; - biased_angular_velocity += _inv_inertia_tensor.xform( (p_pos-center_of_mass).cross(p_j) ); + biased_angular_velocity += _inv_inertia_tensor.xform((p_pos - center_of_mass).cross(p_j)); } - _FORCE_INLINE_ void apply_bias_torque_impulse(const Vector3& p_j) { + _FORCE_INLINE_ void apply_bias_torque_impulse(const Vector3 &p_j) { biased_angular_velocity += _inv_inertia_tensor.xform(p_j); } - _FORCE_INLINE_ void add_force(const Vector3& p_force, const Vector3& p_pos) { + _FORCE_INLINE_ void add_force(const Vector3 &p_force, const Vector3 &p_pos) { applied_force += p_force; applied_torque += p_pos.cross(p_force); @@ -243,7 +242,7 @@ public: _FORCE_INLINE_ bool is_active() const { return active; } _FORCE_INLINE_ void wakeup() { - if ((!get_space()) || mode==PhysicsServer::BODY_MODE_STATIC || mode==PhysicsServer::BODY_MODE_KINEMATIC) + if ((!get_space()) || mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC) return; set_active(true); } @@ -254,16 +253,16 @@ public: void set_mode(PhysicsServer::BodyMode p_mode); PhysicsServer::BodyMode get_mode() const; - void set_state(PhysicsServer::BodyState p_state, const Variant& p_variant); + void set_state(PhysicsServer::BodyState p_state, const Variant &p_variant); Variant get_state(PhysicsServer::BodyState p_state) const; - void set_applied_force(const Vector3& p_force) { applied_force=p_force; } + void set_applied_force(const Vector3 &p_force) { applied_force = p_force; } Vector3 get_applied_force() const { return applied_force; } - void set_applied_torque(const Vector3& p_torque) { applied_torque=p_torque; } + void set_applied_torque(const Vector3 &p_torque) { applied_torque = p_torque; } Vector3 get_applied_torque() const { return applied_torque; } - _FORCE_INLINE_ void set_continuous_collision_detection(bool p_enable) { continuous_cd=p_enable; } + _FORCE_INLINE_ void set_continuous_collision_detection(bool p_enable) { continuous_cd = p_enable; } _FORCE_INLINE_ bool is_continuous_collision_detection_enabled() const { return continuous_cd; } void set_space(SpaceSW *p_space); @@ -277,33 +276,32 @@ public: _FORCE_INLINE_ Vector3 get_gravity() const { return gravity; } _FORCE_INLINE_ real_t get_bounce() const { return bounce; } - _FORCE_INLINE_ void set_axis_lock(PhysicsServer::BodyAxisLock p_lock) { axis_lock=p_lock; } + _FORCE_INLINE_ void set_axis_lock(PhysicsServer::BodyAxisLock p_lock) { axis_lock = p_lock; } _FORCE_INLINE_ PhysicsServer::BodyAxisLock get_axis_lock() const { return axis_lock; } void integrate_forces(real_t p_step); void integrate_velocities(real_t p_step); - _FORCE_INLINE_ Vector3 get_velocity_in_local_point(const Vector3& rel_pos) const { + _FORCE_INLINE_ Vector3 get_velocity_in_local_point(const Vector3 &rel_pos) const { - return linear_velocity + angular_velocity.cross(rel_pos-center_of_mass); + return linear_velocity + angular_velocity.cross(rel_pos - center_of_mass); } - _FORCE_INLINE_ real_t compute_impulse_denominator(const Vector3& p_pos, const Vector3& p_normal) const { + _FORCE_INLINE_ real_t compute_impulse_denominator(const Vector3 &p_pos, const Vector3 &p_normal) const { - Vector3 r0 = p_pos - get_transform().origin - center_of_mass; + Vector3 r0 = p_pos - get_transform().origin - center_of_mass; - Vector3 c0 = (r0).cross(p_normal); + Vector3 c0 = (r0).cross(p_normal); - Vector3 vec = (_inv_inertia_tensor.xform_inv(c0)).cross(r0); + Vector3 vec = (_inv_inertia_tensor.xform_inv(c0)).cross(r0); - return _inv_mass + p_normal.dot(vec); - - } + return _inv_mass + p_normal.dot(vec); + } - _FORCE_INLINE_ real_t compute_angular_impulse_denominator(const Vector3& p_axis) const { + _FORCE_INLINE_ real_t compute_angular_impulse_denominator(const Vector3 &p_axis) const { - return p_axis.dot( _inv_inertia_tensor.xform_inv(p_axis) ); - } + return p_axis.dot(_inv_inertia_tensor.xform_inv(p_axis)); + } //void simulate_motion(const Transform& p_xform,real_t p_step); void call_queries(); @@ -313,117 +311,133 @@ public: BodySW(); ~BodySW(); - }; - //add contact inline -void BodySW::add_contact(const Vector3& p_local_pos,const Vector3& p_local_normal, real_t p_depth, int p_local_shape, const Vector3& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector3& p_collider_velocity_at_pos) { +void BodySW::add_contact(const Vector3 &p_local_pos, const Vector3 &p_local_normal, real_t p_depth, int p_local_shape, const Vector3 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector3 &p_collider_velocity_at_pos) { - int c_max=contacts.size(); + int c_max = contacts.size(); - if (c_max==0) + if (c_max == 0) return; Contact *c = &contacts[0]; + int idx = -1; - int idx=-1; - - if (contact_count<c_max) { - idx=contact_count++; + if (contact_count < c_max) { + idx = contact_count++; } else { - real_t least_depth=1e20; - int least_deep=-1; - for(int i=0;i<c_max;i++) { + real_t least_depth = 1e20; + int least_deep = -1; + for (int i = 0; i < c_max; i++) { - if (i==0 || c[i].depth<least_depth) { - least_deep=i; - least_depth=c[i].depth; + if (i == 0 || c[i].depth < least_depth) { + least_deep = i; + least_depth = c[i].depth; } } - if (least_deep>=0 && least_depth<p_depth) { + if (least_deep >= 0 && least_depth < p_depth) { - idx=least_deep; + idx = least_deep; } - if (idx==-1) + if (idx == -1) return; //none least deepe than this } - c[idx].local_pos=p_local_pos; - c[idx].local_normal=p_local_normal; - c[idx].depth=p_depth; - c[idx].local_shape=p_local_shape; - c[idx].collider_pos=p_collider_pos; - c[idx].collider_shape=p_collider_shape; - c[idx].collider_instance_id=p_collider_instance_id; - c[idx].collider=p_collider; - c[idx].collider_velocity_at_pos=p_collider_velocity_at_pos; - + c[idx].local_pos = p_local_pos; + c[idx].local_normal = p_local_normal; + c[idx].depth = p_depth; + c[idx].local_shape = p_local_shape; + c[idx].collider_pos = p_collider_pos; + c[idx].collider_shape = p_collider_shape; + c[idx].collider_instance_id = p_collider_instance_id; + c[idx].collider = p_collider; + c[idx].collider_velocity_at_pos = p_collider_velocity_at_pos; } - class PhysicsDirectBodyStateSW : public PhysicsDirectBodyState { - GDCLASS( PhysicsDirectBodyStateSW, PhysicsDirectBodyState ); + GDCLASS(PhysicsDirectBodyStateSW, PhysicsDirectBodyState); public: - static PhysicsDirectBodyStateSW *singleton; BodySW *body; real_t step; - virtual Vector3 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area - virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area - virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area + virtual Vector3 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area + virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area + virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area virtual Vector3 get_center_of_mass() const { return body->get_center_of_mass(); } virtual Basis get_principal_inertia_axes() const { return body->get_principal_inertia_axes(); } - virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass - virtual Vector3 get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space - virtual Basis get_inverse_inertia_tensor() const { return body->get_inv_inertia_tensor(); } // get density of this body space + virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass + virtual Vector3 get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space + virtual Basis get_inverse_inertia_tensor() const { return body->get_inv_inertia_tensor(); } // get density of this body space - virtual void set_linear_velocity(const Vector3& p_velocity) { body->set_linear_velocity(p_velocity); } - virtual Vector3 get_linear_velocity() const { return body->get_linear_velocity(); } + virtual void set_linear_velocity(const Vector3 &p_velocity) { body->set_linear_velocity(p_velocity); } + virtual Vector3 get_linear_velocity() const { return body->get_linear_velocity(); } - virtual void set_angular_velocity(const Vector3& p_velocity) { body->set_angular_velocity(p_velocity); } - virtual Vector3 get_angular_velocity() const { return body->get_angular_velocity(); } + virtual void set_angular_velocity(const Vector3 &p_velocity) { body->set_angular_velocity(p_velocity); } + virtual Vector3 get_angular_velocity() const { return body->get_angular_velocity(); } - virtual void set_transform(const Transform& p_transform) { body->set_state(PhysicsServer::BODY_STATE_TRANSFORM,p_transform); } - virtual Transform get_transform() const { return body->get_transform(); } + virtual void set_transform(const Transform &p_transform) { body->set_state(PhysicsServer::BODY_STATE_TRANSFORM, p_transform); } + virtual Transform get_transform() const { return body->get_transform(); } - virtual void add_force(const Vector3& p_force, const Vector3& p_pos) { body->add_force(p_force,p_pos); } - virtual void apply_impulse(const Vector3& p_pos, const Vector3& p_j) { body->apply_impulse(p_pos,p_j); } - virtual void apply_torque_impulse(const Vector3& p_j) { body->apply_torque_impulse(p_j); } + virtual void add_force(const Vector3 &p_force, const Vector3 &p_pos) { body->add_force(p_force, p_pos); } + virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) { body->apply_impulse(p_pos, p_j); } + virtual void apply_torque_impulse(const Vector3 &p_j) { body->apply_torque_impulse(p_j); } - virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); } - virtual bool is_sleeping() const { return !body->is_active(); } + virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); } + virtual bool is_sleeping() const { return !body->is_active(); } - virtual int get_contact_count() const { return body->contact_count; } + virtual int get_contact_count() const { return body->contact_count; } virtual Vector3 get_contact_local_pos(int p_contact_idx) const { - ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3()); return body->contacts[p_contact_idx].local_pos; } - virtual Vector3 get_contact_local_normal(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); return body->contacts[p_contact_idx].local_normal; } - virtual int get_contact_local_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,-1); return body->contacts[p_contact_idx].local_shape; } - - virtual RID get_contact_collider(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,RID()); return body->contacts[p_contact_idx].collider; } - virtual Vector3 get_contact_collider_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); return body->contacts[p_contact_idx].collider_pos; } - virtual ObjectID get_contact_collider_id(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_instance_id; } - virtual int get_contact_collider_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_shape; } - virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); return body->contacts[p_contact_idx].collider_velocity_at_pos; } + virtual Vector3 get_contact_local_normal(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3()); + return body->contacts[p_contact_idx].local_normal; + } + virtual int get_contact_local_shape(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, -1); + return body->contacts[p_contact_idx].local_shape; + } - virtual PhysicsDirectSpaceState* get_space_state(); + virtual RID get_contact_collider(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, RID()); + return body->contacts[p_contact_idx].collider; + } + virtual Vector3 get_contact_collider_pos(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3()); + return body->contacts[p_contact_idx].collider_pos; + } + virtual ObjectID get_contact_collider_id(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0); + return body->contacts[p_contact_idx].collider_instance_id; + } + virtual int get_contact_collider_shape(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0); + return body->contacts[p_contact_idx].collider_shape; + } + virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3()); + return body->contacts[p_contact_idx].collider_velocity_at_pos; + } + virtual PhysicsDirectSpaceState *get_space_state(); virtual real_t get_step() const { return step; } - PhysicsDirectBodyStateSW() { singleton=this; body=NULL; } + PhysicsDirectBodyStateSW() { + singleton = this; + body = NULL; + } }; - #endif // BODY__SW_H diff --git a/servers/physics/broad_phase_basic.cpp b/servers/physics/broad_phase_basic.cpp index f1c22caae3..ca9bb40842 100644 --- a/servers/physics/broad_phase_basic.cpp +++ b/servers/physics/broad_phase_basic.cpp @@ -31,117 +31,111 @@ #include "print_string.h" BroadPhaseSW::ID BroadPhaseBasic::create(CollisionObjectSW *p_object_, int p_subindex) { - if (p_object_==NULL) { + if (p_object_ == NULL) { - ERR_FAIL_COND_V(p_object_==NULL,0); + ERR_FAIL_COND_V(p_object_ == NULL, 0); } current++; Element e; - e.owner=p_object_; - e._static=false; - e.subindex=p_subindex; + e.owner = p_object_; + e._static = false; + e.subindex = p_subindex; - element_map[current]=e; + element_map[current] = e; return current; } -void BroadPhaseBasic::move(ID p_id, const Rect3& p_aabb) { +void BroadPhaseBasic::move(ID p_id, const Rect3 &p_aabb) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - E->get().aabb=p_aabb; - + E->get().aabb = p_aabb; } void BroadPhaseBasic::set_static(ID p_id, bool p_static) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - E->get()._static=p_static; - + E->get()._static = p_static; } void BroadPhaseBasic::remove(ID p_id) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); List<PairKey> to_erase; //unpair must be done immediately on removal to avoid potential invalid pointers - for (Map<PairKey,void*>::Element *F=pair_map.front();F;F=F->next()) { + for (Map<PairKey, void *>::Element *F = pair_map.front(); F; F = F->next()) { - if (F->key().a==p_id || F->key().b==p_id) { + if (F->key().a == p_id || F->key().b == p_id) { if (unpair_callback) { - Element *elem_A=&element_map[F->key().a]; - Element *elem_B=&element_map[F->key().b]; - unpair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,F->get(),unpair_userdata); + Element *elem_A = &element_map[F->key().a]; + Element *elem_B = &element_map[F->key().b]; + unpair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, F->get(), unpair_userdata); } to_erase.push_back(F->key()); } } - while(to_erase.size()) { + while (to_erase.size()) { pair_map.erase(to_erase.front()->get()); to_erase.pop_front(); } element_map.erase(E); - } CollisionObjectSW *BroadPhaseBasic::get_object(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,NULL); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, NULL); return E->get().owner; - } bool BroadPhaseBasic::is_static(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,false); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, false); return E->get()._static; - } int BroadPhaseBasic::get_subindex(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,-1); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, -1); return E->get().subindex; } -int BroadPhaseBasic::cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices) { +int BroadPhaseBasic::cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) { - int rc=0; + int rc = 0; - for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) { + for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) { - const Rect3 aabb=E->get().aabb; - if (aabb.intersects_segment(p_from,p_to)) { + const Rect3 aabb = E->get().aabb; + if (aabb.intersects_segment(p_from, p_to)) { - p_results[rc]=E->get().owner; - p_result_indices[rc]=E->get().subindex; + p_results[rc] = E->get().owner; + p_result_indices[rc] = E->get().subindex; rc++; - if (rc>=p_max_results) + if (rc >= p_max_results) break; } } return rc; - } -int BroadPhaseBasic::cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices) { +int BroadPhaseBasic::cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) { - int rc=0; + int rc = 0; - for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) { + for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) { - const Rect3 aabb=E->get().aabb; + const Rect3 aabb = E->get().aabb; if (aabb.intersects(p_aabb)) { - p_results[rc]=E->get().owner; - p_result_indices[rc]=E->get().subindex; + p_results[rc] = E->get().owner; + p_result_indices[rc] = E->get().subindex; rc++; - if (rc>=p_max_results) + if (rc >= p_max_results) break; } } @@ -149,68 +143,63 @@ int BroadPhaseBasic::cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results return rc; } -void BroadPhaseBasic::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) { - - pair_userdata=p_userdata; - pair_callback=p_pair_callback; +void BroadPhaseBasic::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) { + pair_userdata = p_userdata; + pair_callback = p_pair_callback; } -void BroadPhaseBasic::set_unpair_callback(UnpairCallback p_pair_callback,void *p_userdata) { - - unpair_userdata=p_userdata; - unpair_callback=p_pair_callback; +void BroadPhaseBasic::set_unpair_callback(UnpairCallback p_pair_callback, void *p_userdata) { + unpair_userdata = p_userdata; + unpair_callback = p_pair_callback; } void BroadPhaseBasic::update() { // recompute pairs - for(Map<ID,Element>::Element *I=element_map.front();I;I=I->next()) { + for (Map<ID, Element>::Element *I = element_map.front(); I; I = I->next()) { - for(Map<ID,Element>::Element *J=I->next();J;J=J->next()) { + for (Map<ID, Element>::Element *J = I->next(); J; J = J->next()) { - Element *elem_A=&I->get(); - Element *elem_B=&J->get(); + Element *elem_A = &I->get(); + Element *elem_B = &J->get(); if (elem_A->owner == elem_B->owner) continue; + bool pair_ok = elem_A->aabb.intersects(elem_B->aabb) && (!elem_A->_static || !elem_B->_static); - bool pair_ok=elem_A->aabb.intersects( elem_B->aabb ) && (!elem_A->_static || !elem_B->_static ); - - PairKey key(I->key(),J->key()); + PairKey key(I->key(), J->key()); - Map<PairKey,void*>::Element *E=pair_map.find(key); + Map<PairKey, void *>::Element *E = pair_map.find(key); if (!pair_ok && E) { if (unpair_callback) - unpair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,E->get(),unpair_userdata); + unpair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, E->get(), unpair_userdata); pair_map.erase(key); } if (pair_ok && !E) { - void *data=NULL; + void *data = NULL; if (pair_callback) - data=pair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,unpair_userdata); - pair_map.insert(key,data); + data = pair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, unpair_userdata); + pair_map.insert(key, data); } } } - } BroadPhaseSW *BroadPhaseBasic::_create() { - return memnew( BroadPhaseBasic ); + return memnew(BroadPhaseBasic); } BroadPhaseBasic::BroadPhaseBasic() { - current=1; - unpair_callback=NULL; - unpair_userdata=NULL; - pair_callback=NULL; - pair_userdata=NULL; - + current = 1; + unpair_callback = NULL; + unpair_userdata = NULL; + pair_callback = NULL; + pair_userdata = NULL; } diff --git a/servers/physics/broad_phase_basic.h b/servers/physics/broad_phase_basic.h index 9f07e896c4..2824af6b68 100644 --- a/servers/physics/broad_phase_basic.h +++ b/servers/physics/broad_phase_basic.h @@ -42,8 +42,7 @@ class BroadPhaseBasic : public BroadPhaseSW { int subindex; }; - - Map<ID,Element> element_map; + Map<ID, Element> element_map; ID current; @@ -57,17 +56,23 @@ class BroadPhaseBasic : public BroadPhaseSW { uint64_t key; }; - _FORCE_INLINE_ bool operator<(const PairKey& p_key) const { + _FORCE_INLINE_ bool operator<(const PairKey &p_key) const { return key < p_key.key; } - PairKey() { key=0; } - PairKey(ID p_a, ID p_b) { if (p_a>p_b) { a=p_b; b=p_a; } else { a=p_a; b=p_b; }} - + PairKey() { key = 0; } + PairKey(ID p_a, ID p_b) { + if (p_a > p_b) { + a = p_b; + b = p_a; + } else { + a = p_a; + b = p_b; + } + } }; - Map<PairKey,void*> pair_map; - + Map<PairKey, void *> pair_map; PairCallback pair_callback; void *pair_userdata; @@ -75,10 +80,9 @@ class BroadPhaseBasic : public BroadPhaseSW { void *unpair_userdata; public: - // 0 is an invalid ID - virtual ID create(CollisionObjectSW *p_object_, int p_subindex=0); - virtual void move(ID p_id, const Rect3& p_aabb); + virtual ID create(CollisionObjectSW *p_object_, int p_subindex = 0); + virtual void move(ID p_id, const Rect3 &p_aabb); virtual void set_static(ID p_id, bool p_static); virtual void remove(ID p_id); @@ -86,11 +90,11 @@ public: virtual bool is_static(ID p_id) const; virtual int get_subindex(ID p_id) const; - virtual int cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL); - virtual int cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL); + virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL); + virtual int cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL); - virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata); - virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata); + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata); + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata); virtual void update(); diff --git a/servers/physics/broad_phase_octree.cpp b/servers/physics/broad_phase_octree.cpp index 89581997a2..cb64077d9a 100644 --- a/servers/physics/broad_phase_octree.cpp +++ b/servers/physics/broad_phase_octree.cpp @@ -31,85 +31,77 @@ BroadPhaseSW::ID BroadPhaseOctree::create(CollisionObjectSW *p_object, int p_subindex) { - ID oid = octree.create(p_object,Rect3(),p_subindex,false,1<<p_object->get_type(),0); + ID oid = octree.create(p_object, Rect3(), p_subindex, false, 1 << p_object->get_type(), 0); return oid; } -void BroadPhaseOctree::move(ID p_id, const Rect3& p_aabb){ +void BroadPhaseOctree::move(ID p_id, const Rect3 &p_aabb) { - octree.move(p_id,p_aabb); + octree.move(p_id, p_aabb); } -void BroadPhaseOctree::set_static(ID p_id, bool p_static){ +void BroadPhaseOctree::set_static(ID p_id, bool p_static) { CollisionObjectSW *it = octree.get(p_id); - octree.set_pairable(p_id,p_static?false:true,1<<it->get_type(),p_static?0:0xFFFFF); //pair everything, don't care 1? - + octree.set_pairable(p_id, p_static ? false : true, 1 << it->get_type(), p_static ? 0 : 0xFFFFF); //pair everything, don't care 1? } -void BroadPhaseOctree::remove(ID p_id){ +void BroadPhaseOctree::remove(ID p_id) { octree.erase(p_id); } -CollisionObjectSW *BroadPhaseOctree::get_object(ID p_id) const{ +CollisionObjectSW *BroadPhaseOctree::get_object(ID p_id) const { CollisionObjectSW *it = octree.get(p_id); - ERR_FAIL_COND_V(!it,NULL); + ERR_FAIL_COND_V(!it, NULL); return it; } -bool BroadPhaseOctree::is_static(ID p_id) const{ +bool BroadPhaseOctree::is_static(ID p_id) const { return !octree.is_pairable(p_id); } -int BroadPhaseOctree::get_subindex(ID p_id) const{ +int BroadPhaseOctree::get_subindex(ID p_id) const { return octree.get_subindex(p_id); } -int BroadPhaseOctree::cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices){ +int BroadPhaseOctree::cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) { - return octree.cull_segment(p_from,p_to,p_results,p_max_results,p_result_indices); + return octree.cull_segment(p_from, p_to, p_results, p_max_results, p_result_indices); } -int BroadPhaseOctree::cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices) { - - return octree.cull_AABB(p_aabb,p_results,p_max_results,p_result_indices); +int BroadPhaseOctree::cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) { + return octree.cull_AABB(p_aabb, p_results, p_max_results, p_result_indices); } +void *BroadPhaseOctree::_pair_callback(void *self, OctreeElementID p_A, CollisionObjectSW *p_object_A, int subindex_A, OctreeElementID p_B, CollisionObjectSW *p_object_B, int subindex_B) { -void* BroadPhaseOctree::_pair_callback(void*self,OctreeElementID p_A, CollisionObjectSW*p_object_A,int subindex_A,OctreeElementID p_B, CollisionObjectSW*p_object_B,int subindex_B) { - - BroadPhaseOctree *bpo=(BroadPhaseOctree*)(self); + BroadPhaseOctree *bpo = (BroadPhaseOctree *)(self); if (!bpo->pair_callback) return NULL; - return bpo->pair_callback(p_object_A,subindex_A,p_object_B,subindex_B,bpo->pair_userdata); - + return bpo->pair_callback(p_object_A, subindex_A, p_object_B, subindex_B, bpo->pair_userdata); } -void BroadPhaseOctree::_unpair_callback(void*self,OctreeElementID p_A, CollisionObjectSW*p_object_A,int subindex_A,OctreeElementID p_B, CollisionObjectSW*p_object_B,int subindex_B,void*pairdata) { +void BroadPhaseOctree::_unpair_callback(void *self, OctreeElementID p_A, CollisionObjectSW *p_object_A, int subindex_A, OctreeElementID p_B, CollisionObjectSW *p_object_B, int subindex_B, void *pairdata) { - BroadPhaseOctree *bpo=(BroadPhaseOctree*)(self); + BroadPhaseOctree *bpo = (BroadPhaseOctree *)(self); if (!bpo->unpair_callback) return; - bpo->unpair_callback(p_object_A,subindex_A,p_object_B,subindex_B,pairdata,bpo->unpair_userdata); - + bpo->unpair_callback(p_object_A, subindex_A, p_object_B, subindex_B, pairdata, bpo->unpair_userdata); } +void BroadPhaseOctree::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) { -void BroadPhaseOctree::set_pair_callback(PairCallback p_pair_callback,void *p_userdata){ - - pair_callback=p_pair_callback; - pair_userdata=p_userdata; - + pair_callback = p_pair_callback; + pair_userdata = p_userdata; } -void BroadPhaseOctree::set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata){ - - unpair_callback=p_unpair_callback; - unpair_userdata=p_userdata; +void BroadPhaseOctree::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) { + unpair_callback = p_unpair_callback; + unpair_userdata = p_userdata; } void BroadPhaseOctree::update() { @@ -118,16 +110,14 @@ void BroadPhaseOctree::update() { BroadPhaseSW *BroadPhaseOctree::_create() { - return memnew( BroadPhaseOctree ); + return memnew(BroadPhaseOctree); } BroadPhaseOctree::BroadPhaseOctree() { - octree.set_pair_callback(_pair_callback,this); - octree.set_unpair_callback(_unpair_callback,this); - pair_callback=NULL; - pair_userdata=NULL; - pair_callback=NULL; - unpair_userdata=NULL; + octree.set_pair_callback(_pair_callback, this); + octree.set_unpair_callback(_unpair_callback, this); + pair_callback = NULL; + pair_userdata = NULL; + pair_callback = NULL; + unpair_userdata = NULL; } - - diff --git a/servers/physics/broad_phase_octree.h b/servers/physics/broad_phase_octree.h index 29f1123edf..f9a8bd17ed 100644 --- a/servers/physics/broad_phase_octree.h +++ b/servers/physics/broad_phase_octree.h @@ -34,12 +34,10 @@ class BroadPhaseOctree : public BroadPhaseSW { + Octree<CollisionObjectSW, true> octree; - Octree<CollisionObjectSW,true> octree; - - static void* _pair_callback(void*,OctreeElementID, CollisionObjectSW*,int,OctreeElementID, CollisionObjectSW*,int); - static void _unpair_callback(void*,OctreeElementID, CollisionObjectSW*,int,OctreeElementID, CollisionObjectSW*,int,void*); - + static void *_pair_callback(void *, OctreeElementID, CollisionObjectSW *, int, OctreeElementID, CollisionObjectSW *, int); + static void _unpair_callback(void *, OctreeElementID, CollisionObjectSW *, int, OctreeElementID, CollisionObjectSW *, int, void *); PairCallback pair_callback; void *pair_userdata; @@ -47,10 +45,9 @@ class BroadPhaseOctree : public BroadPhaseSW { void *unpair_userdata; public: - // 0 is an invalid ID - virtual ID create(CollisionObjectSW *p_object_, int p_subindex=0); - virtual void move(ID p_id, const Rect3& p_aabb); + virtual ID create(CollisionObjectSW *p_object_, int p_subindex = 0); + virtual void move(ID p_id, const Rect3 &p_aabb); virtual void set_static(ID p_id, bool p_static); virtual void remove(ID p_id); @@ -58,11 +55,11 @@ public: virtual bool is_static(ID p_id) const; virtual int get_subindex(ID p_id) const; - virtual int cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL); - virtual int cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL); + virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL); + virtual int cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL); - virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata); - virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata); + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata); + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata); virtual void update(); diff --git a/servers/physics/broad_phase_sw.cpp b/servers/physics/broad_phase_sw.cpp index 2a897dea2b..f9a19e558b 100644 --- a/servers/physics/broad_phase_sw.cpp +++ b/servers/physics/broad_phase_sw.cpp @@ -28,8 +28,7 @@ /*************************************************************************/ #include "broad_phase_sw.h" -BroadPhaseSW::CreateFunction BroadPhaseSW::create_func=NULL; +BroadPhaseSW::CreateFunction BroadPhaseSW::create_func = NULL; -BroadPhaseSW::~BroadPhaseSW() -{ +BroadPhaseSW::~BroadPhaseSW() { } diff --git a/servers/physics/broad_phase_sw.h b/servers/physics/broad_phase_sw.h index 20b3efc7fb..df6ea1cc73 100644 --- a/servers/physics/broad_phase_sw.h +++ b/servers/physics/broad_phase_sw.h @@ -34,40 +34,37 @@ class CollisionObjectSW; - class BroadPhaseSW { public: - typedef BroadPhaseSW* (*CreateFunction)(); + typedef BroadPhaseSW *(*CreateFunction)(); static CreateFunction create_func; typedef uint32_t ID; - - typedef void* (*PairCallback)(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_userdata); - typedef void (*UnpairCallback)(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_data,void *p_userdata); + typedef void *(*PairCallback)(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_userdata); + typedef void (*UnpairCallback)(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_userdata); // 0 is an invalid ID - virtual ID create(CollisionObjectSW *p_object_, int p_subindex=0)=0; - virtual void move(ID p_id, const Rect3& p_aabb)=0; - virtual void set_static(ID p_id, bool p_static)=0; - virtual void remove(ID p_id)=0; + virtual ID create(CollisionObjectSW *p_object_, int p_subindex = 0) = 0; + virtual void move(ID p_id, const Rect3 &p_aabb) = 0; + virtual void set_static(ID p_id, bool p_static) = 0; + virtual void remove(ID p_id) = 0; - virtual CollisionObjectSW *get_object(ID p_id) const=0; - virtual bool is_static(ID p_id) const=0; - virtual int get_subindex(ID p_id) const=0; + virtual CollisionObjectSW *get_object(ID p_id) const = 0; + virtual bool is_static(ID p_id) const = 0; + virtual int get_subindex(ID p_id) const = 0; - virtual int cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL)=0; - virtual int cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL)=0; + virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0; + virtual int cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0; - virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata)=0; - virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata)=0; + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata) = 0; + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) = 0; - virtual void update()=0; + virtual void update() = 0; virtual ~BroadPhaseSW(); - }; #endif // BROAD_PHASE__SW_H diff --git a/servers/physics/collision_object_sw.cpp b/servers/physics/collision_object_sw.cpp index 88aa737579..36704b6eb8 100644 --- a/servers/physics/collision_object_sw.cpp +++ b/servers/physics/collision_object_sw.cpp @@ -29,37 +29,35 @@ #include "collision_object_sw.h" #include "space_sw.h" -void CollisionObjectSW::add_shape(ShapeSW *p_shape,const Transform& p_transform) { +void CollisionObjectSW::add_shape(ShapeSW *p_shape, const Transform &p_transform) { Shape s; - s.shape=p_shape; - s.xform=p_transform; - s.xform_inv=s.xform.affine_inverse(); - s.bpid=0; //needs update + s.shape = p_shape; + s.xform = p_transform; + s.xform_inv = s.xform.affine_inverse(); + s.bpid = 0; //needs update shapes.push_back(s); p_shape->add_owner(this); _update_shapes(); _shapes_changed(); - } -void CollisionObjectSW::set_shape(int p_index,ShapeSW *p_shape){ +void CollisionObjectSW::set_shape(int p_index, ShapeSW *p_shape) { - ERR_FAIL_INDEX(p_index,shapes.size()); + ERR_FAIL_INDEX(p_index, shapes.size()); shapes[p_index].shape->remove_owner(this); - shapes[p_index].shape=p_shape; + shapes[p_index].shape = p_shape; p_shape->add_owner(this); _update_shapes(); _shapes_changed(); - } -void CollisionObjectSW::set_shape_transform(int p_index,const Transform& p_transform){ +void CollisionObjectSW::set_shape_transform(int p_index, const Transform &p_transform) { - ERR_FAIL_INDEX(p_index,shapes.size()); + ERR_FAIL_INDEX(p_index, shapes.size()); - shapes[p_index].xform=p_transform; - shapes[p_index].xform_inv=p_transform.affine_inverse(); + shapes[p_index].xform = p_transform; + shapes[p_index].xform_inv = p_transform.affine_inverse(); _update_shapes(); _shapes_changed(); } @@ -67,61 +65,58 @@ void CollisionObjectSW::set_shape_transform(int p_index,const Transform& p_trans void CollisionObjectSW::remove_shape(ShapeSW *p_shape) { //remove a shape, all the times it appears - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - if (shapes[i].shape==p_shape) { + if (shapes[i].shape == p_shape) { remove_shape(i); i--; } } } -void CollisionObjectSW::remove_shape(int p_index){ +void CollisionObjectSW::remove_shape(int p_index) { //remove anything from shape to be erased to end, so subindices don't change - ERR_FAIL_INDEX(p_index,shapes.size()); - for(int i=p_index;i<shapes.size();i++) { + ERR_FAIL_INDEX(p_index, shapes.size()); + for (int i = p_index; i < shapes.size(); i++) { - if (shapes[i].bpid==0) + if (shapes[i].bpid == 0) continue; //should never get here with a null owner space->get_broadphase()->remove(shapes[i].bpid); - shapes[i].bpid=0; + shapes[i].bpid = 0; } shapes[p_index].shape->remove_owner(this); shapes.remove(p_index); _shapes_changed(); - } void CollisionObjectSW::_set_static(bool p_static) { - if (_static==p_static) + if (_static == p_static) return; - _static=p_static; + _static = p_static; if (!space) return; - for(int i=0;i<get_shape_count();i++) { - Shape &s=shapes[i]; - if (s.bpid>0) { - space->get_broadphase()->set_static(s.bpid,_static); + for (int i = 0; i < get_shape_count(); i++) { + Shape &s = shapes[i]; + if (s.bpid > 0) { + space->get_broadphase()->set_static(s.bpid, _static); } } - } void CollisionObjectSW::_unregister_shapes() { - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; - if (s.bpid>0) { + Shape &s = shapes[i]; + if (s.bpid > 0) { space->get_broadphase()->remove(s.bpid); - s.bpid=0; + s.bpid = 0; } } - } void CollisionObjectSW::_update_shapes() { @@ -129,54 +124,50 @@ void CollisionObjectSW::_update_shapes() { if (!space) return; - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; - if (s.bpid==0) { - s.bpid=space->get_broadphase()->create(this,i); - space->get_broadphase()->set_static(s.bpid,_static); + Shape &s = shapes[i]; + if (s.bpid == 0) { + s.bpid = space->get_broadphase()->create(this, i); + space->get_broadphase()->set_static(s.bpid, _static); } //not quite correct, should compute the next matrix.. - Rect3 shape_aabb=s.shape->get_aabb(); + Rect3 shape_aabb = s.shape->get_aabb(); Transform xform = transform * s.xform; - shape_aabb=xform.xform(shape_aabb); - s.aabb_cache=shape_aabb; - s.aabb_cache=s.aabb_cache.grow( (s.aabb_cache.size.x + s.aabb_cache.size.y)*0.5*0.05 ); + shape_aabb = xform.xform(shape_aabb); + s.aabb_cache = shape_aabb; + s.aabb_cache = s.aabb_cache.grow((s.aabb_cache.size.x + s.aabb_cache.size.y) * 0.5 * 0.05); Vector3 scale = xform.get_basis().get_scale(); - s.area_cache=s.shape->get_area()*scale.x*scale.y*scale.z; + s.area_cache = s.shape->get_area() * scale.x * scale.y * scale.z; - space->get_broadphase()->move(s.bpid,s.aabb_cache); + space->get_broadphase()->move(s.bpid, s.aabb_cache); } - } -void CollisionObjectSW::_update_shapes_with_motion(const Vector3& p_motion) { - +void CollisionObjectSW::_update_shapes_with_motion(const Vector3 &p_motion) { if (!space) return; - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; - if (s.bpid==0) { - s.bpid=space->get_broadphase()->create(this,i); - space->get_broadphase()->set_static(s.bpid,_static); + Shape &s = shapes[i]; + if (s.bpid == 0) { + s.bpid = space->get_broadphase()->create(this, i); + space->get_broadphase()->set_static(s.bpid, _static); } //not quite correct, should compute the next matrix.. - Rect3 shape_aabb=s.shape->get_aabb(); + Rect3 shape_aabb = s.shape->get_aabb(); Transform xform = transform * s.xform; - shape_aabb=xform.xform(shape_aabb); - shape_aabb=shape_aabb.merge(Rect3( shape_aabb.pos+p_motion,shape_aabb.size)); //use motion - s.aabb_cache=shape_aabb; + shape_aabb = xform.xform(shape_aabb); + shape_aabb = shape_aabb.merge(Rect3(shape_aabb.pos + p_motion, shape_aabb.size)); //use motion + s.aabb_cache = shape_aabb; - space->get_broadphase()->move(s.bpid,shape_aabb); + space->get_broadphase()->move(s.bpid, shape_aabb); } - - } void CollisionObjectSW::_set_space(SpaceSW *p_space) { @@ -185,25 +176,23 @@ void CollisionObjectSW::_set_space(SpaceSW *p_space) { space->remove_object(this); - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; + Shape &s = shapes[i]; if (s.bpid) { space->get_broadphase()->remove(s.bpid); - s.bpid=0; + s.bpid = 0; } } - } - space=p_space; + space = p_space; if (space) { space->add_object(this); _update_shapes(); } - } void CollisionObjectSW::_shape_changed() { @@ -214,11 +203,11 @@ void CollisionObjectSW::_shape_changed() { CollisionObjectSW::CollisionObjectSW(Type p_type) { - _static=true; - type=p_type; - space=NULL; - instance_id=0; - layer_mask=1; - collision_mask=1; - ray_pickable=true; + _static = true; + type = p_type; + space = NULL; + instance_id = 0; + layer_mask = 1; + collision_mask = 1; + ray_pickable = true; } diff --git a/servers/physics/collision_object_sw.h b/servers/physics/collision_object_sw.h index c46a7f4a5f..9a7626d583 100644 --- a/servers/physics/collision_object_sw.h +++ b/servers/physics/collision_object_sw.h @@ -29,14 +29,14 @@ #ifndef COLLISION_OBJECT_SW_H #define COLLISION_OBJECT_SW_H -#include "shape_sw.h" -#include "servers/physics_server.h" -#include "self_list.h" #include "broad_phase_sw.h" +#include "self_list.h" +#include "servers/physics_server.h" +#include "shape_sw.h" #ifdef DEBUG_ENABLED #define MAX_OBJECT_DISTANCE 10000000.0 -#define MAX_OBJECT_DISTANCE_X2 (MAX_OBJECT_DISTANCE*MAX_OBJECT_DISTANCE) +#define MAX_OBJECT_DISTANCE_X2 (MAX_OBJECT_DISTANCE * MAX_OBJECT_DISTANCE) #endif class SpaceSW; @@ -47,8 +47,8 @@ public: TYPE_AREA, TYPE_BODY }; -private: +private: Type type; RID self; ObjectID instance_id; @@ -65,7 +65,7 @@ private: ShapeSW *shape; bool trigger; - Shape() { trigger=false; } + Shape() { trigger = false; } }; Vector<Shape> shapes; @@ -77,84 +77,80 @@ private: void _update_shapes(); protected: - - - void _update_shapes_with_motion(const Vector3& p_motion); + void _update_shapes_with_motion(const Vector3 &p_motion); void _unregister_shapes(); - _FORCE_INLINE_ void _set_transform(const Transform& p_transform,bool p_update_shapes=true) { + _FORCE_INLINE_ void _set_transform(const Transform &p_transform, bool p_update_shapes = true) { #ifdef DEBUG_ENABLED if (p_transform.origin.length_squared() > MAX_OBJECT_DISTANCE_X2) { - ERR_EXPLAIN("Object went too far away (more than "+itos(MAX_OBJECT_DISTANCE)+"mts from origin)."); + ERR_EXPLAIN("Object went too far away (more than " + itos(MAX_OBJECT_DISTANCE) + "mts from origin)."); ERR_FAIL(); } #endif - transform=p_transform; if (p_update_shapes) _update_shapes(); - + transform = p_transform; + if (p_update_shapes) _update_shapes(); } - _FORCE_INLINE_ void _set_inv_transform(const Transform& p_transform) { inv_transform=p_transform; } + _FORCE_INLINE_ void _set_inv_transform(const Transform &p_transform) { inv_transform = p_transform; } void _set_static(bool p_static); - virtual void _shapes_changed()=0; + virtual void _shapes_changed() = 0; void _set_space(SpaceSW *space); bool ray_pickable; - CollisionObjectSW(Type p_type); -public: - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } +public: + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } _FORCE_INLINE_ RID get_self() const { return self; } - _FORCE_INLINE_ void set_instance_id(const ObjectID& p_instance_id) { instance_id=p_instance_id; } + _FORCE_INLINE_ void set_instance_id(const ObjectID &p_instance_id) { instance_id = p_instance_id; } _FORCE_INLINE_ ObjectID get_instance_id() const { return instance_id; } void _shape_changed(); _FORCE_INLINE_ Type get_type() const { return type; } - void add_shape(ShapeSW *p_shape,const Transform& p_transform=Transform()); - void set_shape(int p_index,ShapeSW *p_shape); - void set_shape_transform(int p_index,const Transform& p_transform); + void add_shape(ShapeSW *p_shape, const Transform &p_transform = Transform()); + void set_shape(int p_index, ShapeSW *p_shape); + void set_shape_transform(int p_index, const Transform &p_transform); _FORCE_INLINE_ int get_shape_count() const { return shapes.size(); } _FORCE_INLINE_ ShapeSW *get_shape(int p_index) const { return shapes[p_index].shape; } - _FORCE_INLINE_ const Transform& get_shape_transform(int p_index) const { return shapes[p_index].xform; } - _FORCE_INLINE_ const Transform& get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; } - _FORCE_INLINE_ const Rect3& get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; } + _FORCE_INLINE_ const Transform &get_shape_transform(int p_index) const { return shapes[p_index].xform; } + _FORCE_INLINE_ const Transform &get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; } + _FORCE_INLINE_ const Rect3 &get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; } _FORCE_INLINE_ const real_t get_shape_area(int p_index) const { return shapes[p_index].area_cache; } _FORCE_INLINE_ Transform get_transform() const { return transform; } _FORCE_INLINE_ Transform get_inv_transform() const { return inv_transform; } - _FORCE_INLINE_ SpaceSW* get_space() const { return space; } + _FORCE_INLINE_ SpaceSW *get_space() const { return space; } - _FORCE_INLINE_ void set_ray_pickable(bool p_enable) { ray_pickable=p_enable; } + _FORCE_INLINE_ void set_ray_pickable(bool p_enable) { ray_pickable = p_enable; } _FORCE_INLINE_ bool is_ray_pickable() const { return ray_pickable; } - _FORCE_INLINE_ void set_shape_as_trigger(int p_idx,bool p_enable) { shapes[p_idx].trigger=p_enable; } + _FORCE_INLINE_ void set_shape_as_trigger(int p_idx, bool p_enable) { shapes[p_idx].trigger = p_enable; } _FORCE_INLINE_ bool is_shape_set_as_trigger(int p_idx) const { return shapes[p_idx].trigger; } - _FORCE_INLINE_ void set_layer_mask(uint32_t p_mask) { layer_mask=p_mask; } + _FORCE_INLINE_ void set_layer_mask(uint32_t p_mask) { layer_mask = p_mask; } _FORCE_INLINE_ uint32_t get_layer_mask() const { return layer_mask; } - _FORCE_INLINE_ void set_collision_mask(uint32_t p_mask) { collision_mask=p_mask; } + _FORCE_INLINE_ void set_collision_mask(uint32_t p_mask) { collision_mask = p_mask; } _FORCE_INLINE_ uint32_t get_collision_mask() const { return collision_mask; } - _FORCE_INLINE_ bool test_collision_mask(CollisionObjectSW* p_other) const { - return layer_mask&p_other->collision_mask || p_other->layer_mask&collision_mask; + _FORCE_INLINE_ bool test_collision_mask(CollisionObjectSW *p_other) const { + return layer_mask & p_other->collision_mask || p_other->layer_mask & collision_mask; } void remove_shape(ShapeSW *p_shape); void remove_shape(int p_index); - virtual void set_space(SpaceSW *p_space)=0; + virtual void set_space(SpaceSW *p_space) = 0; - _FORCE_INLINE_ bool is_static() const { return _static; } + _FORCE_INLINE_ bool is_static() const { return _static; } virtual ~CollisionObjectSW() {} - }; #endif // COLLISION_OBJECT_SW_H diff --git a/servers/physics/collision_solver_sat.cpp b/servers/physics/collision_solver_sat.cpp index 9d3e1db47b..003e6b3257 100644 --- a/servers/physics/collision_solver_sat.cpp +++ b/servers/physics/collision_solver_sat.cpp @@ -40,7 +40,7 @@ struct _CollectorCallback { Vector3 normal; Vector3 *prev_axis; - _FORCE_INLINE_ void call(const Vector3& p_point_A, const Vector3& p_point_B) { + _FORCE_INLINE_ void call(const Vector3 &p_point_A, const Vector3 &p_point_B) { /* if (normal.dot(p_point_A) >= normal.dot(p_point_B)) @@ -49,69 +49,61 @@ struct _CollectorCallback { */ if (swap) - callback(p_point_B,p_point_A,userdata); + callback(p_point_B, p_point_A, userdata); else - callback(p_point_A,p_point_B,userdata); + callback(p_point_A, p_point_B, userdata); } - }; -typedef void (*GenerateContactsFunc)(const Vector3 *,int, const Vector3 *,int ,_CollectorCallback *); - +typedef void (*GenerateContactsFunc)(const Vector3 *, int, const Vector3 *, int, _CollectorCallback *); -static void _generate_contacts_point_point(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) { +static void _generate_contacts_point_point(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 1 ); - ERR_FAIL_COND( p_point_count_B != 1 ); + ERR_FAIL_COND(p_point_count_A != 1); + ERR_FAIL_COND(p_point_count_B != 1); #endif - p_callback->call(*p_points_A,*p_points_B); + p_callback->call(*p_points_A, *p_points_B); } -static void _generate_contacts_point_edge(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) { +static void _generate_contacts_point_edge(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 1 ); - ERR_FAIL_COND( p_point_count_B != 2 ); + ERR_FAIL_COND(p_point_count_A != 1); + ERR_FAIL_COND(p_point_count_B != 2); #endif - Vector3 closest_B = Geometry::get_closest_point_to_segment_uncapped(*p_points_A, p_points_B ); - p_callback->call(*p_points_A,closest_B); - + Vector3 closest_B = Geometry::get_closest_point_to_segment_uncapped(*p_points_A, p_points_B); + p_callback->call(*p_points_A, closest_B); } -static void _generate_contacts_point_face(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) { +static void _generate_contacts_point_face(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 1 ); - ERR_FAIL_COND( p_point_count_B < 3 ); + ERR_FAIL_COND(p_point_count_A != 1); + ERR_FAIL_COND(p_point_count_B < 3); #endif + Vector3 closest_B = Plane(p_points_B[0], p_points_B[1], p_points_B[2]).project(*p_points_A); - Vector3 closest_B=Plane(p_points_B[0],p_points_B[1],p_points_B[2]).project( *p_points_A ); - - p_callback->call(*p_points_A,closest_B); - + p_callback->call(*p_points_A, closest_B); } - -static void _generate_contacts_edge_edge(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) { +static void _generate_contacts_edge_edge(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 2 ); - ERR_FAIL_COND( p_point_count_B != 2 ); // circle is actually a 4x3 matrix + ERR_FAIL_COND(p_point_count_A != 2); + ERR_FAIL_COND(p_point_count_B != 2); // circle is actually a 4x3 matrix #endif + Vector3 rel_A = p_points_A[1] - p_points_A[0]; + Vector3 rel_B = p_points_B[1] - p_points_B[0]; - - Vector3 rel_A=p_points_A[1]-p_points_A[0]; - Vector3 rel_B=p_points_B[1]-p_points_B[0]; - - Vector3 c=rel_A.cross(rel_B).cross(rel_B); + Vector3 c = rel_A.cross(rel_B).cross(rel_B); //if ( Math::abs(rel_A.dot(c) )<_EDGE_IS_VALID_SUPPORT_TRESHOLD ) { - if ( Math::abs(rel_A.dot(c) )<CMP_EPSILON ) { + if (Math::abs(rel_A.dot(c)) < CMP_EPSILON) { // should handle somehow.. //ERR_PRINT("TODO FIX"); @@ -122,117 +114,110 @@ static void _generate_contacts_edge_edge(const Vector3 * p_points_A,int p_point_ Vector3 base_B = p_points_B[0] - axis * axis.dot(p_points_B[0]); //sort all 4 points in axis - real_t dvec[4]={ axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) }; + real_t dvec[4] = { axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) }; SortArray<real_t> sa; - sa.sort(dvec,4); + sa.sort(dvec, 4); //use the middle ones as contacts - p_callback->call(base_A+axis*dvec[1],base_B+axis*dvec[1]); - p_callback->call(base_A+axis*dvec[2],base_B+axis*dvec[2]); + p_callback->call(base_A + axis * dvec[1], base_B + axis * dvec[1]); + p_callback->call(base_A + axis * dvec[2], base_B + axis * dvec[2]); return; - } - real_t d = (c.dot( p_points_B[0] ) - p_points_A[0].dot(c))/rel_A.dot(c); + real_t d = (c.dot(p_points_B[0]) - p_points_A[0].dot(c)) / rel_A.dot(c); - if (d<0.0) - d=0.0; - else if (d>1.0) - d=1.0; - - Vector3 closest_A=p_points_A[0]+rel_A*d; - Vector3 closest_B=Geometry::get_closest_point_to_segment_uncapped(closest_A, p_points_B); - p_callback->call(closest_A,closest_B); + if (d < 0.0) + d = 0.0; + else if (d > 1.0) + d = 1.0; + Vector3 closest_A = p_points_A[0] + rel_A * d; + Vector3 closest_B = Geometry::get_closest_point_to_segment_uncapped(closest_A, p_points_B); + p_callback->call(closest_A, closest_B); } -static void _generate_contacts_face_face(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) { +static void _generate_contacts_face_face(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A <2 ); - ERR_FAIL_COND( p_point_count_B <3 ); + ERR_FAIL_COND(p_point_count_A < 2); + ERR_FAIL_COND(p_point_count_B < 3); #endif - static const int max_clip=32; + static const int max_clip = 32; Vector3 _clipbuf1[max_clip]; Vector3 _clipbuf2[max_clip]; - Vector3 *clipbuf_src=_clipbuf1; - Vector3 *clipbuf_dst=_clipbuf2; - int clipbuf_len=p_point_count_A; + Vector3 *clipbuf_src = _clipbuf1; + Vector3 *clipbuf_dst = _clipbuf2; + int clipbuf_len = p_point_count_A; // copy A points to clipbuf_src - for (int i=0;i<p_point_count_A;i++) { + for (int i = 0; i < p_point_count_A; i++) { - clipbuf_src[i]=p_points_A[i]; + clipbuf_src[i] = p_points_A[i]; } - Plane plane_B(p_points_B[0],p_points_B[1],p_points_B[2]); + Plane plane_B(p_points_B[0], p_points_B[1], p_points_B[2]); // go through all of B points - for (int i=0;i<p_point_count_B;i++) { + for (int i = 0; i < p_point_count_B; i++) { - int i_n=(i+1)%p_point_count_B; + int i_n = (i + 1) % p_point_count_B; - Vector3 edge0_B=p_points_B[i]; - Vector3 edge1_B=p_points_B[i_n]; + Vector3 edge0_B = p_points_B[i]; + Vector3 edge1_B = p_points_B[i_n]; - Vector3 clip_normal = (edge0_B - edge1_B).cross( plane_B.normal ).normalized(); + Vector3 clip_normal = (edge0_B - edge1_B).cross(plane_B.normal).normalized(); // make a clip plane - - Plane clip(edge0_B,clip_normal); + Plane clip(edge0_B, clip_normal); // avoid double clip if A is edge - int dst_idx=0; - bool edge = clipbuf_len==2; - for (int j=0;j<clipbuf_len;j++) { + int dst_idx = 0; + bool edge = clipbuf_len == 2; + for (int j = 0; j < clipbuf_len; j++) { - int j_n=(j+1)%clipbuf_len; + int j_n = (j + 1) % clipbuf_len; - Vector3 edge0_A=clipbuf_src[j]; - Vector3 edge1_A=clipbuf_src[j_n]; + Vector3 edge0_A = clipbuf_src[j]; + Vector3 edge1_A = clipbuf_src[j_n]; real_t dist0 = clip.distance_to(edge0_A); real_t dist1 = clip.distance_to(edge1_A); + if (dist0 <= 0) { // behind plane - if ( dist0 <= 0 ) { // behind plane - - ERR_FAIL_COND( dst_idx >= max_clip ); - clipbuf_dst[dst_idx++]=clipbuf_src[j]; - + ERR_FAIL_COND(dst_idx >= max_clip); + clipbuf_dst[dst_idx++] = clipbuf_src[j]; } - // check for different sides and non coplanar //if ( (dist0*dist1) < -CMP_EPSILON && !(edge && j)) { - if ( (dist0*dist1) < 0 && !(edge && j)) { + if ((dist0 * dist1) < 0 && !(edge && j)) { // calculate intersection Vector3 rel = edge1_A - edge0_A; - real_t den=clip.normal.dot( rel ); - real_t dist=-(clip.normal.dot( edge0_A )-clip.d)/den; - Vector3 inters = edge0_A+rel*dist; + real_t den = clip.normal.dot(rel); + real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den; + Vector3 inters = edge0_A + rel * dist; - ERR_FAIL_COND( dst_idx >= max_clip ); - clipbuf_dst[dst_idx]=inters; + ERR_FAIL_COND(dst_idx >= max_clip); + clipbuf_dst[dst_idx] = inters; dst_idx++; } } - clipbuf_len=dst_idx; - SWAP(clipbuf_src,clipbuf_dst); + clipbuf_len = dst_idx; + SWAP(clipbuf_src, clipbuf_dst); } - // generate contacts //Plane plane_A(p_points_A[0],p_points_A[1],p_points_A[2]); - int added=0; + int added = 0; - for (int i=0;i<clipbuf_len;i++) { + for (int i = 0; i < clipbuf_len; i++) { real_t d = plane_B.distance_to(clipbuf_src[i]); /* @@ -240,40 +225,37 @@ static void _generate_contacts_face_face(const Vector3 * p_points_A,int p_point_ continue; */ - Vector3 closest_B=clipbuf_src[i] - plane_B.normal*d; + Vector3 closest_B = clipbuf_src[i] - plane_B.normal * d; if (p_callback->normal.dot(clipbuf_src[i]) >= p_callback->normal.dot(closest_B)) continue; - p_callback->call(clipbuf_src[i],closest_B); + p_callback->call(clipbuf_src[i], closest_B); added++; - } - } - -static void _generate_contacts_from_supports(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) { - +static void _generate_contacts_from_supports(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A <1 ); - ERR_FAIL_COND( p_point_count_B <1 ); + ERR_FAIL_COND(p_point_count_A < 1); + ERR_FAIL_COND(p_point_count_B < 1); #endif - - static const GenerateContactsFunc generate_contacts_func_table[3][3]={ + static const GenerateContactsFunc generate_contacts_func_table[3][3] = { + { + _generate_contacts_point_point, + _generate_contacts_point_edge, + _generate_contacts_point_face, + }, { - _generate_contacts_point_point, - _generate_contacts_point_edge, - _generate_contacts_point_face, - },{ - 0, - _generate_contacts_edge_edge, - _generate_contacts_face_face, - },{ - 0,0, - _generate_contacts_face_face, + 0, + _generate_contacts_edge_edge, + _generate_contacts_face_face, + }, + { + 0, 0, + _generate_contacts_face_face, } }; @@ -289,28 +271,25 @@ static void _generate_contacts_from_supports(const Vector3 * p_points_A,int p_po pointcount_B = p_point_count_A; pointcount_A = p_point_count_B; - points_A=p_points_B; - points_B=p_points_A; + points_A = p_points_B; + points_B = p_points_A; } else { pointcount_B = p_point_count_B; pointcount_A = p_point_count_A; - points_A=p_points_A; - points_B=p_points_B; + points_A = p_points_A; + points_B = p_points_B; } - int version_A = (pointcount_A > 3 ? 3 : pointcount_A) -1; - int version_B = (pointcount_B > 3 ? 3 : pointcount_B) -1; + int version_A = (pointcount_A > 3 ? 3 : pointcount_A) - 1; + int version_B = (pointcount_B > 3 ? 3 : pointcount_B) - 1; GenerateContactsFunc contacts_func = generate_contacts_func_table[version_A][version_B]; ERR_FAIL_COND(!contacts_func); - contacts_func(points_A,pointcount_A,points_B,pointcount_B,p_callback); - + contacts_func(points_A, pointcount_A, points_B, pointcount_B, p_callback); } - - -template<class ShapeA, class ShapeB, bool withMargin=false> +template <class ShapeA, class ShapeB, bool withMargin = false> class SeparatorAxisTest { const ShapeA *shape_A; @@ -325,46 +304,45 @@ class SeparatorAxisTest { Vector3 separator_axis; public: - _FORCE_INLINE_ bool test_previous_axis() { - if (callback && callback->prev_axis && *callback->prev_axis!=Vector3()) + if (callback && callback->prev_axis && *callback->prev_axis != Vector3()) return test_axis(*callback->prev_axis); else return true; } - _FORCE_INLINE_ bool test_axis(const Vector3& p_axis) { + _FORCE_INLINE_ bool test_axis(const Vector3 &p_axis) { - Vector3 axis=p_axis; + Vector3 axis = p_axis; - if ( Math::abs(axis.x)<CMP_EPSILON && - Math::abs(axis.y)<CMP_EPSILON && - Math::abs(axis.z)<CMP_EPSILON ) { + if (Math::abs(axis.x) < CMP_EPSILON && + Math::abs(axis.y) < CMP_EPSILON && + Math::abs(axis.z) < CMP_EPSILON) { // strange case, try an upwards separator - axis=Vector3(0.0,1.0,0.0); + axis = Vector3(0.0, 1.0, 0.0); } - real_t min_A,max_A,min_B,max_B; + real_t min_A, max_A, min_B, max_B; - shape_A->project_range(axis,*transform_A,min_A,max_A); - shape_B->project_range(axis,*transform_B,min_B,max_B); + shape_A->project_range(axis, *transform_A, min_A, max_A); + shape_B->project_range(axis, *transform_B, min_B, max_B); if (withMargin) { - min_A-=margin_A; - max_A+=margin_A; - min_B-=margin_B; - max_B+=margin_B; + min_A -= margin_A; + max_A += margin_A; + min_B -= margin_B; + max_B += margin_B; } - min_B -= ( max_A - min_A ) * 0.5; - max_B += ( max_A - min_A ) * 0.5; + min_B -= (max_A - min_A) * 0.5; + max_B += (max_A - min_A) * 0.5; - real_t dmin = min_B - ( min_A + max_A ) * 0.5; - real_t dmax = max_B - ( min_A + max_A ) * 0.5; + real_t dmin = min_B - (min_A + max_A) * 0.5; + real_t dmax = max_B - (min_A + max_A) * 0.5; if (dmin > 0.0 || dmax < 0.0) { - separator_axis=axis; + separator_axis = axis; return false; // doesn't contain 0 } @@ -372,68 +350,65 @@ public: dmin = Math::abs(dmin); - if ( dmax < dmin ) { - if ( dmax < best_depth ) { - best_depth=dmax; - best_axis=axis; + if (dmax < dmin) { + if (dmax < best_depth) { + best_depth = dmax; + best_axis = axis; } } else { - if ( dmin < best_depth ) { - best_depth=dmin; - best_axis=-axis; // keep it as A axis + if (dmin < best_depth) { + best_depth = dmin; + best_axis = -axis; // keep it as A axis } } return true; } - _FORCE_INLINE_ void generate_contacts() { // nothing to do, don't generate - if (best_axis==Vector3(0.0,0.0,0.0)) + if (best_axis == Vector3(0.0, 0.0, 0.0)) return; if (!callback->callback) { //just was checking intersection? - callback->collided=true; + callback->collided = true; if (callback->prev_axis) - *callback->prev_axis=best_axis; + *callback->prev_axis = best_axis; return; } - static const int max_supports=16; + static const int max_supports = 16; Vector3 supports_A[max_supports]; int support_count_A; - shape_A->get_supports(transform_A->basis.xform_inv(-best_axis).normalized(),max_supports,supports_A,support_count_A); - for(int i=0;i<support_count_A;i++) { + shape_A->get_supports(transform_A->basis.xform_inv(-best_axis).normalized(), max_supports, supports_A, support_count_A); + for (int i = 0; i < support_count_A; i++) { supports_A[i] = transform_A->xform(supports_A[i]); } if (withMargin) { - for(int i=0;i<support_count_A;i++) { - supports_A[i]+=-best_axis*margin_A; + for (int i = 0; i < support_count_A; i++) { + supports_A[i] += -best_axis * margin_A; } - } - Vector3 supports_B[max_supports]; int support_count_B; - shape_B->get_supports(transform_B->basis.xform_inv(best_axis).normalized(),max_supports,supports_B,support_count_B); - for(int i=0;i<support_count_B;i++) { + shape_B->get_supports(transform_B->basis.xform_inv(best_axis).normalized(), max_supports, supports_B, support_count_B); + for (int i = 0; i < support_count_B; i++) { supports_B[i] = transform_B->xform(supports_B[i]); } if (withMargin) { - for(int i=0;i<support_count_B;i++) { - supports_B[i]+=best_axis*margin_B; + for (int i = 0; i < support_count_B; i++) { + supports_B[i] += best_axis * margin_B; } } -/* + /* print_line("best depth: "+rtos(best_depth)); print_line("best axis: "+(best_axis)); for(int i=0;i<support_count_A;i++) { @@ -445,29 +420,26 @@ public: print_line("B-"+itos(i)+": "+supports_B[i]); } */ - callback->normal=best_axis; + callback->normal = best_axis; if (callback->prev_axis) - *callback->prev_axis=best_axis; - _generate_contacts_from_supports(supports_A,support_count_A,supports_B,support_count_B,callback); + *callback->prev_axis = best_axis; + _generate_contacts_from_supports(supports_A, support_count_A, supports_B, support_count_B, callback); - callback->collided=true; + callback->collided = true; //CollisionSolverSW::CallbackResult cbk=NULL; //cbk(Vector3(),Vector3(),NULL); - } - _FORCE_INLINE_ SeparatorAxisTest(const ShapeA *p_shape_A,const Transform& p_transform_A, const ShapeB *p_shape_B,const Transform& p_transform_B,_CollectorCallback *p_callback,real_t p_margin_A=0,real_t p_margin_B=0) { - best_depth=1e15; - shape_A=p_shape_A; - shape_B=p_shape_B; - transform_A=&p_transform_A; - transform_B=&p_transform_B; - callback=p_callback; - margin_A=p_margin_A; - margin_B=p_margin_B; - + _FORCE_INLINE_ SeparatorAxisTest(const ShapeA *p_shape_A, const Transform &p_transform_A, const ShapeB *p_shape_B, const Transform &p_transform_B, _CollectorCallback *p_callback, real_t p_margin_A = 0, real_t p_margin_B = 0) { + best_depth = 1e15; + shape_A = p_shape_A; + shape_B = p_shape_B; + transform_A = &p_transform_A; + transform_B = &p_transform_B; + callback = p_callback; + margin_A = p_margin_A; + margin_B = p_margin_B; } - }; /****** SAT TESTS *******/ @@ -475,92 +447,84 @@ public: /****** SAT TESTS *******/ /****** SAT TESTS *******/ +typedef void (*CollisionFunc)(const ShapeSW *, const Transform &, const ShapeSW *, const Transform &, _CollectorCallback *p_callback, real_t, real_t); -typedef void (*CollisionFunc)(const ShapeSW*,const Transform&,const ShapeSW*,const Transform&,_CollectorCallback *p_callback,real_t,real_t); - - -template<bool withMargin> -static void _collision_sphere_sphere(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - +template <bool withMargin> +static void _collision_sphere_sphere(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a); - const SphereShapeSW *sphere_B = static_cast<const SphereShapeSW*>(p_b); + const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a); + const SphereShapeSW *sphere_B = static_cast<const SphereShapeSW *>(p_b); - SeparatorAxisTest<SphereShapeSW,SphereShapeSW,withMargin> separator(sphere_A,p_transform_a,sphere_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<SphereShapeSW, SphereShapeSW, withMargin> separator(sphere_A, p_transform_a, sphere_B, p_transform_b, p_collector, p_margin_a, p_margin_b); // previous axis if (!separator.test_previous_axis()) return; - if (!separator.test_axis( (p_transform_a.origin-p_transform_b.origin).normalized() )) + if (!separator.test_axis((p_transform_a.origin - p_transform_b.origin).normalized())) return; separator.generate_contacts(); } -template<bool withMargin> -static void _collision_sphere_box(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { +template <bool withMargin> +static void _collision_sphere_box(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { + const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a); + const BoxShapeSW *box_B = static_cast<const BoxShapeSW *>(p_b); - const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a); - const BoxShapeSW *box_B = static_cast<const BoxShapeSW*>(p_b); - - SeparatorAxisTest<SphereShapeSW,BoxShapeSW,withMargin> separator(sphere_A,p_transform_a,box_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<SphereShapeSW, BoxShapeSW, withMargin> separator(sphere_A, p_transform_a, box_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; // test faces - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis = p_transform_b.basis.get_axis(i).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } // calculate closest point to sphere - Vector3 cnormal=p_transform_b.xform_inv( p_transform_a.origin ); + Vector3 cnormal = p_transform_b.xform_inv(p_transform_a.origin); - Vector3 cpoint=p_transform_b.xform( Vector3( + Vector3 cpoint = p_transform_b.xform(Vector3( - (cnormal.x<0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x, - (cnormal.y<0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y, - (cnormal.z<0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z - ) ); + (cnormal.x < 0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x, + (cnormal.y < 0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y, + (cnormal.z < 0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z)); // use point to test axis Vector3 point_axis = (p_transform_a.origin - cpoint).normalized(); - if (!separator.test_axis( point_axis )) + if (!separator.test_axis(point_axis)) return; // test edges - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - Vector3 axis = point_axis.cross( p_transform_b.basis.get_axis(i) ).cross( p_transform_b.basis.get_axis(i) ).normalized(); + Vector3 axis = point_axis.cross(p_transform_b.basis.get_axis(i)).cross(p_transform_b.basis.get_axis(i)).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } separator.generate_contacts(); - - } -template<bool withMargin> -static void _collision_sphere_capsule(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { +template <bool withMargin> +static void _collision_sphere_capsule(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a); - const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW*>(p_b); + const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a); + const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW *>(p_b); - SeparatorAxisTest<SphereShapeSW,CapsuleShapeSW,withMargin> separator(sphere_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<SphereShapeSW, CapsuleShapeSW, withMargin> separator(sphere_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; @@ -571,38 +535,35 @@ static void _collision_sphere_capsule(const ShapeSW *p_a,const Transform &p_tran Vector3 capsule_ball_1 = p_transform_b.origin + capsule_axis; - if (!separator.test_axis( (capsule_ball_1 - p_transform_a.origin).normalized() ) ) + if (!separator.test_axis((capsule_ball_1 - p_transform_a.origin).normalized())) return; //capsule sphere 2, sphere Vector3 capsule_ball_2 = p_transform_b.origin - capsule_axis; - if (!separator.test_axis( (capsule_ball_2 - p_transform_a.origin).normalized() ) ) + if (!separator.test_axis((capsule_ball_2 - p_transform_a.origin).normalized())) return; //capsule edge, sphere Vector3 b2a = p_transform_a.origin - p_transform_b.origin; - Vector3 axis = b2a.cross( capsule_axis ).cross( capsule_axis ).normalized(); + Vector3 axis = b2a.cross(capsule_axis).cross(capsule_axis).normalized(); - - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; separator.generate_contacts(); } -template<bool withMargin> -static void _collision_sphere_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - +template <bool withMargin> +static void _collision_sphere_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a); - const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b); - - SeparatorAxisTest<SphereShapeSW,ConvexPolygonShapeSW,withMargin> separator(sphere_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a); + const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b); + SeparatorAxisTest<SphereShapeSW, ConvexPolygonShapeSW, withMargin> separator(sphere_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; @@ -616,146 +577,127 @@ static void _collision_sphere_convex_polygon(const ShapeSW *p_a,const Transform const Vector3 *vertices = mesh.vertices.ptr(); int vertex_count = mesh.vertices.size(); - // faces of B - for (int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - Vector3 axis = p_transform_b.xform( faces[i].plane ).normal; + Vector3 axis = p_transform_b.xform(faces[i].plane).normal; - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } - // edges of B - for(int i=0;i<edge_count;i++) { - + for (int i = 0; i < edge_count; i++) { - Vector3 v1=p_transform_b.xform( vertices[ edges[i].a ] ); - Vector3 v2=p_transform_b.xform( vertices[ edges[i].b ] ); - Vector3 v3=p_transform_a.origin; + Vector3 v1 = p_transform_b.xform(vertices[edges[i].a]); + Vector3 v2 = p_transform_b.xform(vertices[edges[i].b]); + Vector3 v3 = p_transform_a.origin; - - Vector3 n1=v2-v1; - Vector3 n2=v2-v3; + Vector3 n1 = v2 - v1; + Vector3 n2 = v2 - v3; Vector3 axis = n1.cross(n2).cross(n1).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } // vertices of B - for(int i=0;i<vertex_count;i++) { + for (int i = 0; i < vertex_count; i++) { + Vector3 v1 = p_transform_b.xform(vertices[i]); + Vector3 v2 = p_transform_a.origin; - Vector3 v1=p_transform_b.xform( vertices[i] ); - Vector3 v2=p_transform_a.origin; + Vector3 axis = (v2 - v1).normalized(); - Vector3 axis = (v2-v1).normalized(); - - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } separator.generate_contacts(); - - } -template<bool withMargin> -static void _collision_sphere_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { +template <bool withMargin> +static void _collision_sphere_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a); - const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b); + const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a); + const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b); + SeparatorAxisTest<SphereShapeSW, FaceShapeSW, withMargin> separator(sphere_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - - SeparatorAxisTest<SphereShapeSW,FaceShapeSW,withMargin> separator(sphere_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b); - - - Vector3 vertex[3]={ - p_transform_b.xform( face_B->vertex[0] ), - p_transform_b.xform( face_B->vertex[1] ), - p_transform_b.xform( face_B->vertex[2] ), + Vector3 vertex[3] = { + p_transform_b.xform(face_B->vertex[0]), + p_transform_b.xform(face_B->vertex[1]), + p_transform_b.xform(face_B->vertex[2]), }; - if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() )) + if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized())) return; // edges and points of B - for(int i=0;i<3;i++) { - + for (int i = 0; i < 3; i++) { - Vector3 n1=vertex[i]-p_transform_a.origin; + Vector3 n1 = vertex[i] - p_transform_a.origin; - if (!separator.test_axis( n1.normalized() )) { + if (!separator.test_axis(n1.normalized())) { return; } - Vector3 n2=vertex[(i+1)%3]-vertex[i]; + Vector3 n2 = vertex[(i + 1) % 3] - vertex[i]; Vector3 axis = n1.cross(n2).cross(n2).normalized(); - if (!separator.test_axis( axis )) { + if (!separator.test_axis(axis)) { return; } - } separator.generate_contacts(); } +template <bool withMargin> +static void _collision_box_box(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { -template<bool withMargin> -static void _collision_box_box(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - + const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a); + const BoxShapeSW *box_B = static_cast<const BoxShapeSW *>(p_b); - const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a); - const BoxShapeSW *box_B = static_cast<const BoxShapeSW*>(p_b); - - SeparatorAxisTest<BoxShapeSW,BoxShapeSW,withMargin> separator(box_A,p_transform_a,box_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<BoxShapeSW, BoxShapeSW, withMargin> separator(box_A, p_transform_a, box_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; // test faces of A - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis = p_transform_a.basis.get_axis(i).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } // test faces of B - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis = p_transform_b.basis.get_axis(i).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } // test combined edges - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - Vector3 axis = p_transform_a.basis.get_axis(i).cross( p_transform_b.basis.get_axis(j) ); + Vector3 axis = p_transform_a.basis.get_axis(i).cross(p_transform_b.basis.get_axis(j)); - if (axis.length_squared()<CMP_EPSILON) + if (axis.length_squared() < CMP_EPSILON) continue; axis.normalize(); - - if (!separator.test_axis( axis )) { + if (!separator.test_axis(axis)) { return; } } @@ -768,110 +710,103 @@ static void _collision_box_box(const ShapeSW *p_a,const Transform &p_transform_a Vector3 ab_vec = p_transform_b.origin - p_transform_a.origin; - Vector3 cnormal_a=p_transform_a.basis.xform_inv( ab_vec ); + Vector3 cnormal_a = p_transform_a.basis.xform_inv(ab_vec); - Vector3 support_a=p_transform_a.xform( Vector3( + Vector3 support_a = p_transform_a.xform(Vector3( - (cnormal_a.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, - (cnormal_a.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, - (cnormal_a.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z - ) ); + (cnormal_a.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, + (cnormal_a.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, + (cnormal_a.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z)); + Vector3 cnormal_b = p_transform_b.basis.xform_inv(-ab_vec); - Vector3 cnormal_b=p_transform_b.basis.xform_inv( -ab_vec ); + Vector3 support_b = p_transform_b.xform(Vector3( - Vector3 support_b=p_transform_b.xform( Vector3( + (cnormal_b.x < 0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x, + (cnormal_b.y < 0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y, + (cnormal_b.z < 0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z)); - (cnormal_b.x<0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x, - (cnormal_b.y<0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y, - (cnormal_b.z<0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z - ) ); + Vector3 axis_ab = (support_a - support_b); - Vector3 axis_ab = (support_a-support_b); - - if (!separator.test_axis( axis_ab.normalized() )) { + if (!separator.test_axis(axis_ab.normalized())) { return; } //now try edges, which become cylinders! - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { //a ->b Vector3 axis_a = p_transform_a.basis.get_axis(i); - if (!separator.test_axis( axis_ab.cross(axis_a).cross(axis_a).normalized() )) + if (!separator.test_axis(axis_ab.cross(axis_a).cross(axis_a).normalized())) return; //b ->a Vector3 axis_b = p_transform_b.basis.get_axis(i); - if (!separator.test_axis( axis_ab.cross(axis_b).cross(axis_b).normalized() )) + if (!separator.test_axis(axis_ab.cross(axis_b).cross(axis_b).normalized())) return; - } } separator.generate_contacts(); - - } -template<bool withMargin> -static void _collision_box_capsule(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { +template <bool withMargin> +static void _collision_box_capsule(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a); - const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW*>(p_b); + const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a); + const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW *>(p_b); - SeparatorAxisTest<BoxShapeSW,CapsuleShapeSW,withMargin> separator(box_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<BoxShapeSW, CapsuleShapeSW, withMargin> separator(box_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; // faces of A - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis = p_transform_a.basis.get_axis(i); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } - Vector3 cyl_axis = p_transform_b.basis.get_axis(2).normalized(); // edges of A, capsule cylinder - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { // cylinder Vector3 box_axis = p_transform_a.basis.get_axis(i); - Vector3 axis = box_axis.cross( cyl_axis ); + Vector3 axis = box_axis.cross(cyl_axis); if (axis.length_squared() < CMP_EPSILON) continue; - if (!separator.test_axis( axis.normalized() )) + if (!separator.test_axis(axis.normalized())) return; } // points of A, capsule cylinder // this sure could be made faster somehow.. - for (int i=0;i<2;i++) { - for (int j=0;j<2;j++) { - for (int k=0;k<2;k++) { + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + for (int k = 0; k < 2; k++) { Vector3 he = box_A->get_half_extents(); - he.x*=(i*2-1); - he.y*=(j*2-1); - he.z*=(k*2-1); - Vector3 point=p_transform_a.origin; - for(int l=0;l<3;l++) - point+=p_transform_a.basis.get_axis(l)*he[l]; + he.x *= (i * 2 - 1); + he.y *= (j * 2 - 1); + he.z *= (k * 2 - 1); + Vector3 point = p_transform_a.origin; + for (int l = 0; l < 3; l++) + point += p_transform_a.basis.get_axis(l) * he[l]; //Vector3 axis = (point - cyl_axis * cyl_axis.dot(point)).normalized(); - Vector3 axis = Plane(cyl_axis,0).project(point).normalized(); + Vector3 axis = Plane(cyl_axis, 0).project(point).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } } @@ -879,58 +814,51 @@ static void _collision_box_capsule(const ShapeSW *p_a,const Transform &p_transfo // capsule balls, edges of A - for (int i=0;i<2;i++) { - - - Vector3 capsule_axis = p_transform_b.basis.get_axis(2)*(capsule_B->get_height()*0.5); + for (int i = 0; i < 2; i++) { - Vector3 sphere_pos = p_transform_b.origin + ((i==0)?capsule_axis:-capsule_axis); + Vector3 capsule_axis = p_transform_b.basis.get_axis(2) * (capsule_B->get_height() * 0.5); + Vector3 sphere_pos = p_transform_b.origin + ((i == 0) ? capsule_axis : -capsule_axis); - Vector3 cnormal=p_transform_a.xform_inv( sphere_pos ); + Vector3 cnormal = p_transform_a.xform_inv(sphere_pos); - Vector3 cpoint=p_transform_a.xform( Vector3( + Vector3 cpoint = p_transform_a.xform(Vector3( - (cnormal.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, - (cnormal.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, - (cnormal.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z - ) ); + (cnormal.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, + (cnormal.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, + (cnormal.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z)); // use point to test axis Vector3 point_axis = (sphere_pos - cpoint).normalized(); - if (!separator.test_axis( point_axis )) + if (!separator.test_axis(point_axis)) return; // test edges of A - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - Vector3 axis = point_axis.cross( p_transform_a.basis.get_axis(i) ).cross( p_transform_a.basis.get_axis(i) ).normalized(); + Vector3 axis = point_axis.cross(p_transform_a.basis.get_axis(i)).cross(p_transform_a.basis.get_axis(i)).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } } - separator.generate_contacts(); } -template<bool withMargin> -static void _collision_box_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - +template <bool withMargin> +static void _collision_box_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { + const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a); + const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b); - const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a); - const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b); - - SeparatorAxisTest<BoxShapeSW,ConvexPolygonShapeSW,withMargin> separator(box_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<BoxShapeSW, ConvexPolygonShapeSW, withMargin> separator(box_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; - const Geometry::MeshData &mesh = convex_polygon_B->get_mesh(); const Geometry::MeshData::Face *faces = mesh.faces.ptr(); @@ -941,97 +869,92 @@ static void _collision_box_convex_polygon(const ShapeSW *p_a,const Transform &p_ int vertex_count = mesh.vertices.size(); // faces of A - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis = p_transform_a.basis.get_axis(i).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // faces of B - for (int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - Vector3 axis = p_transform_b.xform( faces[i].plane ).normal; + Vector3 axis = p_transform_b.xform(faces[i].plane).normal; - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // A<->B edges - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 e1 = p_transform_a.basis.get_axis(i); - for (int j=0;j<edge_count;j++) { + for (int j = 0; j < edge_count; j++) { - Vector3 e2=p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]); + Vector3 e2 = p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]); - Vector3 axis=e1.cross( e2 ).normalized(); + Vector3 axis = e1.cross(e2).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } } if (withMargin) { // calculate closest points between vertices and box edges - for(int v=0;v<vertex_count;v++) { - + for (int v = 0; v < vertex_count; v++) { Vector3 vtxb = p_transform_b.xform(vertices[v]); Vector3 ab_vec = vtxb - p_transform_a.origin; - Vector3 cnormal_a=p_transform_a.basis.xform_inv( ab_vec ); + Vector3 cnormal_a = p_transform_a.basis.xform_inv(ab_vec); - Vector3 support_a=p_transform_a.xform( Vector3( + Vector3 support_a = p_transform_a.xform(Vector3( - (cnormal_a.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, - (cnormal_a.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, - (cnormal_a.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z - ) ); + (cnormal_a.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, + (cnormal_a.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, + (cnormal_a.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z)); + Vector3 axis_ab = support_a - vtxb; - Vector3 axis_ab = support_a-vtxb; - - if (!separator.test_axis( axis_ab.normalized() )) { + if (!separator.test_axis(axis_ab.normalized())) { return; } //now try edges, which become cylinders! - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { //a ->b Vector3 axis_a = p_transform_a.basis.get_axis(i); - if (!separator.test_axis( axis_ab.cross(axis_a).cross(axis_a).normalized() )) + if (!separator.test_axis(axis_ab.cross(axis_a).cross(axis_a).normalized())) return; } } //convex edges and box points - for (int i=0;i<2;i++) { - for (int j=0;j<2;j++) { - for (int k=0;k<2;k++) { + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + for (int k = 0; k < 2; k++) { Vector3 he = box_A->get_half_extents(); - he.x*=(i*2-1); - he.y*=(j*2-1); - he.z*=(k*2-1); - Vector3 point=p_transform_a.origin; - for(int l=0;l<3;l++) - point+=p_transform_a.basis.get_axis(l)*he[l]; - - for(int e=0;e<edge_count;e++) { + he.x *= (i * 2 - 1); + he.y *= (j * 2 - 1); + he.z *= (k * 2 - 1); + Vector3 point = p_transform_a.origin; + for (int l = 0; l < 3; l++) + point += p_transform_a.basis.get_axis(l) * he[l]; - Vector3 p1=p_transform_b.xform(vertices[edges[e].a]); - Vector3 p2=p_transform_b.xform(vertices[edges[e].b]); - Vector3 n = (p2-p1); + for (int e = 0; e < edge_count; e++) { + Vector3 p1 = p_transform_b.xform(vertices[edges[e].a]); + Vector3 p2 = p_transform_b.xform(vertices[edges[e].b]); + Vector3 n = (p2 - p1); - if (!separator.test_axis( (point-p2).cross(n).cross(n).normalized() )) + if (!separator.test_axis((point - p2).cross(n).cross(n).normalized())) return; } } @@ -1040,130 +963,119 @@ static void _collision_box_convex_polygon(const ShapeSW *p_a,const Transform &p_ } separator.generate_contacts(); - - } +template <bool withMargin> +static void _collision_box_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { -template<bool withMargin> -static void _collision_box_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - - - const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a); - const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b); + const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a); + const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b); - SeparatorAxisTest<BoxShapeSW,FaceShapeSW,withMargin> separator(box_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<BoxShapeSW, FaceShapeSW, withMargin> separator(box_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - Vector3 vertex[3]={ - p_transform_b.xform( face_B->vertex[0] ), - p_transform_b.xform( face_B->vertex[1] ), - p_transform_b.xform( face_B->vertex[2] ), + Vector3 vertex[3] = { + p_transform_b.xform(face_B->vertex[0]), + p_transform_b.xform(face_B->vertex[1]), + p_transform_b.xform(face_B->vertex[2]), }; - if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() )) + if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized())) return; // faces of A - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis = p_transform_a.basis.get_axis(i).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // combined edges - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - Vector3 e=vertex[i]-vertex[(i+1)%3]; + Vector3 e = vertex[i] - vertex[(i + 1) % 3]; - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { Vector3 axis = p_transform_a.basis.get_axis(j); - if (!separator.test_axis( e.cross(axis).normalized() )) + if (!separator.test_axis(e.cross(axis).normalized())) return; } - } if (withMargin) { // calculate closest points between vertices and box edges - for(int v=0;v<3;v++) { - + for (int v = 0; v < 3; v++) { Vector3 ab_vec = vertex[v] - p_transform_a.origin; - Vector3 cnormal_a=p_transform_a.basis.xform_inv( ab_vec ); + Vector3 cnormal_a = p_transform_a.basis.xform_inv(ab_vec); - Vector3 support_a=p_transform_a.xform( Vector3( + Vector3 support_a = p_transform_a.xform(Vector3( - (cnormal_a.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, - (cnormal_a.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, - (cnormal_a.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z - ) ); + (cnormal_a.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x, + (cnormal_a.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y, + (cnormal_a.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z)); + Vector3 axis_ab = support_a - vertex[v]; - Vector3 axis_ab = support_a-vertex[v]; - - if (!separator.test_axis( axis_ab.normalized() )) { + if (!separator.test_axis(axis_ab.normalized())) { return; } //now try edges, which become cylinders! - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { //a ->b Vector3 axis_a = p_transform_a.basis.get_axis(i); - if (!separator.test_axis( axis_ab.cross(axis_a).cross(axis_a).normalized() )) + if (!separator.test_axis(axis_ab.cross(axis_a).cross(axis_a).normalized())) return; } } //convex edges and box points, there has to be a way to speed up this (get closest point?) - for (int i=0;i<2;i++) { - for (int j=0;j<2;j++) { - for (int k=0;k<2;k++) { + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + for (int k = 0; k < 2; k++) { Vector3 he = box_A->get_half_extents(); - he.x*=(i*2-1); - he.y*=(j*2-1); - he.z*=(k*2-1); - Vector3 point=p_transform_a.origin; - for(int l=0;l<3;l++) - point+=p_transform_a.basis.get_axis(l)*he[l]; + he.x *= (i * 2 - 1); + he.y *= (j * 2 - 1); + he.z *= (k * 2 - 1); + Vector3 point = p_transform_a.origin; + for (int l = 0; l < 3; l++) + point += p_transform_a.basis.get_axis(l) * he[l]; - for(int e=0;e<3;e++) { + for (int e = 0; e < 3; e++) { - Vector3 p1=vertex[e]; - Vector3 p2=vertex[(e+1)%3]; + Vector3 p1 = vertex[e]; + Vector3 p2 = vertex[(e + 1) % 3]; - Vector3 n = (p2-p1); + Vector3 n = (p2 - p1); - if (!separator.test_axis( (point-p2).cross(n).cross(n).normalized() )) + if (!separator.test_axis((point - p2).cross(n).cross(n).normalized())) return; } } } } - } separator.generate_contacts(); - } +template <bool withMargin> +static void _collision_capsule_capsule(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { -template<bool withMargin> -static void _collision_capsule_capsule(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - - const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW*>(p_a); - const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW*>(p_b); + const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW *>(p_a); + const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW *>(p_b); - SeparatorAxisTest<CapsuleShapeSW,CapsuleShapeSW,withMargin> separator(capsule_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<CapsuleShapeSW, CapsuleShapeSW, withMargin> separator(capsule_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; @@ -1180,49 +1092,45 @@ static void _collision_capsule_capsule(const ShapeSW *p_a,const Transform &p_tra //balls-balls - if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_1 ).normalized() ) ) + if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_1).normalized())) return; - if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_2 ).normalized() ) ) + if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_2).normalized())) return; - if (!separator.test_axis( (capsule_A_ball_2 - capsule_B_ball_1 ).normalized() ) ) + if (!separator.test_axis((capsule_A_ball_2 - capsule_B_ball_1).normalized())) return; - if (!separator.test_axis( (capsule_A_ball_2 - capsule_B_ball_2 ).normalized() ) ) + if (!separator.test_axis((capsule_A_ball_2 - capsule_B_ball_2).normalized())) return; - // edges-balls - if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_1 ).cross(capsule_A_axis).cross(capsule_A_axis).normalized() ) ) + if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_1).cross(capsule_A_axis).cross(capsule_A_axis).normalized())) return; - if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_2 ).cross(capsule_A_axis).cross(capsule_A_axis).normalized() ) ) + if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_2).cross(capsule_A_axis).cross(capsule_A_axis).normalized())) return; - if (!separator.test_axis( (capsule_B_ball_1 - capsule_A_ball_1 ).cross(capsule_B_axis).cross(capsule_B_axis).normalized() ) ) + if (!separator.test_axis((capsule_B_ball_1 - capsule_A_ball_1).cross(capsule_B_axis).cross(capsule_B_axis).normalized())) return; - if (!separator.test_axis( (capsule_B_ball_1 - capsule_A_ball_2 ).cross(capsule_B_axis).cross(capsule_B_axis).normalized() ) ) + if (!separator.test_axis((capsule_B_ball_1 - capsule_A_ball_2).cross(capsule_B_axis).cross(capsule_B_axis).normalized())) return; // edges - if (!separator.test_axis( capsule_A_axis.cross(capsule_B_axis).normalized() ) ) + if (!separator.test_axis(capsule_A_axis.cross(capsule_B_axis).normalized())) return; - separator.generate_contacts(); - } -template<bool withMargin> -static void _collision_capsule_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - +template <bool withMargin> +static void _collision_capsule_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW*>(p_a); - const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b); + const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW *>(p_a); + const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b); - SeparatorAxisTest<CapsuleShapeSW,ConvexPolygonShapeSW,withMargin> separator(capsule_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<CapsuleShapeSW, ConvexPolygonShapeSW, withMargin> separator(capsule_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; @@ -1236,127 +1144,113 @@ static void _collision_capsule_convex_polygon(const ShapeSW *p_a,const Transform const Vector3 *vertices = mesh.vertices.ptr(); // faces of B - for (int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { - Vector3 axis = p_transform_b.xform( faces[i].plane ).normal; + Vector3 axis = p_transform_b.xform(faces[i].plane).normal; - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // edges of B, capsule cylinder - for (int i=0;i<edge_count;i++) { + for (int i = 0; i < edge_count; i++) { // cylinder - Vector3 edge_axis = p_transform_b.basis.xform( vertices[ edges[i].a] ) - p_transform_b.basis.xform( vertices[ edges[i].b] ); - Vector3 axis = edge_axis.cross( p_transform_a.basis.get_axis(2) ).normalized(); + Vector3 edge_axis = p_transform_b.basis.xform(vertices[edges[i].a]) - p_transform_b.basis.xform(vertices[edges[i].b]); + Vector3 axis = edge_axis.cross(p_transform_a.basis.get_axis(2)).normalized(); - - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // capsule balls, edges of B - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { // edges of B, capsule cylinder - Vector3 capsule_axis = p_transform_a.basis.get_axis(2)*(capsule_A->get_height()*0.5); - - Vector3 sphere_pos = p_transform_a.origin + ((i==0)?capsule_axis:-capsule_axis); + Vector3 capsule_axis = p_transform_a.basis.get_axis(2) * (capsule_A->get_height() * 0.5); - for (int j=0;j<edge_count;j++) { + Vector3 sphere_pos = p_transform_a.origin + ((i == 0) ? capsule_axis : -capsule_axis); + for (int j = 0; j < edge_count; j++) { - Vector3 n1=sphere_pos - p_transform_b.xform( vertices[ edges[j].a] ); - Vector3 n2=p_transform_b.basis.xform( vertices[ edges[j].a] ) - p_transform_b.basis.xform( vertices[ edges[j].b] ); + Vector3 n1 = sphere_pos - p_transform_b.xform(vertices[edges[j].a]); + Vector3 n2 = p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]); Vector3 axis = n1.cross(n2).cross(n2).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } } - separator.generate_contacts(); - } +template <bool withMargin> +static void _collision_capsule_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { -template<bool withMargin> -static void _collision_capsule_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - - const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW*>(p_a); - const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b); - - SeparatorAxisTest<CapsuleShapeSW,FaceShapeSW,withMargin> separator(capsule_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW *>(p_a); + const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b); + SeparatorAxisTest<CapsuleShapeSW, FaceShapeSW, withMargin> separator(capsule_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - - Vector3 vertex[3]={ - p_transform_b.xform( face_B->vertex[0] ), - p_transform_b.xform( face_B->vertex[1] ), - p_transform_b.xform( face_B->vertex[2] ), + Vector3 vertex[3] = { + p_transform_b.xform(face_B->vertex[0]), + p_transform_b.xform(face_B->vertex[1]), + p_transform_b.xform(face_B->vertex[2]), }; - if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() )) + if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized())) return; // edges of B, capsule cylinder - Vector3 capsule_axis = p_transform_a.basis.get_axis(2)*(capsule_A->get_height()*0.5); + Vector3 capsule_axis = p_transform_a.basis.get_axis(2) * (capsule_A->get_height() * 0.5); - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { // edge-cylinder - Vector3 edge_axis = vertex[i]-vertex[(i+1)%3]; - Vector3 axis = edge_axis.cross( capsule_axis ).normalized(); + Vector3 edge_axis = vertex[i] - vertex[(i + 1) % 3]; + Vector3 axis = edge_axis.cross(capsule_axis).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - if (!separator.test_axis( (p_transform_a.origin-vertex[i]).cross(capsule_axis).cross(capsule_axis).normalized() )) + if (!separator.test_axis((p_transform_a.origin - vertex[i]).cross(capsule_axis).cross(capsule_axis).normalized())) return; - for (int j=0;j<2;j++) { + for (int j = 0; j < 2; j++) { // point-spheres - Vector3 sphere_pos = p_transform_a.origin + ( (j==0) ? capsule_axis : -capsule_axis ); + Vector3 sphere_pos = p_transform_a.origin + ((j == 0) ? capsule_axis : -capsule_axis); - Vector3 n1=sphere_pos - vertex[i]; + Vector3 n1 = sphere_pos - vertex[i]; - if (!separator.test_axis( n1.normalized() )) + if (!separator.test_axis(n1.normalized())) return; - Vector3 n2=edge_axis; + Vector3 n2 = edge_axis; axis = n1.cross(n2).cross(n2); - if (!separator.test_axis( axis.normalized() )) + if (!separator.test_axis(axis.normalized())) return; - - } - } - separator.generate_contacts(); - } +template <bool withMargin> +static void _collision_convex_polygon_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { -template<bool withMargin> -static void _collision_convex_polygon_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { - - - const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW*>(p_a); - const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b); + const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW *>(p_a); + const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b); - SeparatorAxisTest<ConvexPolygonShapeSW,ConvexPolygonShapeSW,withMargin> separator(convex_polygon_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<ConvexPolygonShapeSW, ConvexPolygonShapeSW, withMargin> separator(convex_polygon_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b); if (!separator.test_previous_axis()) return; @@ -1380,107 +1274,97 @@ static void _collision_convex_polygon_convex_polygon(const ShapeSW *p_a,const Tr int vertex_count_B = mesh_B.vertices.size(); // faces of A - for (int i=0;i<face_count_A;i++) { + for (int i = 0; i < face_count_A; i++) { - Vector3 axis = p_transform_a.xform( faces_A[i].plane ).normal; + Vector3 axis = p_transform_a.xform(faces_A[i].plane).normal; //Vector3 axis = p_transform_a.basis.xform( faces_A[i].plane.normal ).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // faces of B - for (int i=0;i<face_count_B;i++) { + for (int i = 0; i < face_count_B; i++) { - Vector3 axis = p_transform_b.xform( faces_B[i].plane ).normal; + Vector3 axis = p_transform_b.xform(faces_B[i].plane).normal; //Vector3 axis = p_transform_b.basis.xform( faces_B[i].plane.normal ).normalized(); - - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } // A<->B edges - for (int i=0;i<edge_count_A;i++) { + for (int i = 0; i < edge_count_A; i++) { - Vector3 e1=p_transform_a.basis.xform( vertices_A[ edges_A[i].a] ) -p_transform_a.basis.xform( vertices_A[ edges_A[i].b] ); + Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].a]) - p_transform_a.basis.xform(vertices_A[edges_A[i].b]); - for (int j=0;j<edge_count_B;j++) { + for (int j = 0; j < edge_count_B; j++) { - Vector3 e2=p_transform_b.basis.xform( vertices_B[ edges_B[j].a] ) -p_transform_b.basis.xform( vertices_B[ edges_B[j].b] ); + Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[j].a]) - p_transform_b.basis.xform(vertices_B[edges_B[j].b]); - Vector3 axis=e1.cross( e2 ).normalized(); + Vector3 axis = e1.cross(e2).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; - } } if (withMargin) { //vertex-vertex - for(int i=0;i<vertex_count_A;i++) { + for (int i = 0; i < vertex_count_A; i++) { Vector3 va = p_transform_a.xform(vertices_A[i]); - for(int j=0;j<vertex_count_B;j++) { + for (int j = 0; j < vertex_count_B; j++) { - if (!separator.test_axis( (va-p_transform_b.xform(vertices_B[j])).normalized() )) + if (!separator.test_axis((va - p_transform_b.xform(vertices_B[j])).normalized())) return; - } } //edge-vertex( hsell) - for (int i=0;i<edge_count_A;i++) { - - Vector3 e1=p_transform_a.basis.xform( vertices_A[ edges_A[i].a] ); - Vector3 e2=p_transform_a.basis.xform( vertices_A[ edges_A[i].b] ); - Vector3 n = (e2-e1); + for (int i = 0; i < edge_count_A; i++) { - for(int j=0;j<vertex_count_B;j++) { + Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].a]); + Vector3 e2 = p_transform_a.basis.xform(vertices_A[edges_A[i].b]); + Vector3 n = (e2 - e1); - Vector3 e3=p_transform_b.xform(vertices_B[j]); + for (int j = 0; j < vertex_count_B; j++) { + Vector3 e3 = p_transform_b.xform(vertices_B[j]); - if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() )) + if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized())) return; } } - for (int i=0;i<edge_count_B;i++) { + for (int i = 0; i < edge_count_B; i++) { - Vector3 e1=p_transform_b.basis.xform( vertices_B[ edges_B[i].a] ); - Vector3 e2=p_transform_b.basis.xform( vertices_B[ edges_B[i].b] ); - Vector3 n = (e2-e1); + Vector3 e1 = p_transform_b.basis.xform(vertices_B[edges_B[i].a]); + Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[i].b]); + Vector3 n = (e2 - e1); - for(int j=0;j<vertex_count_A;j++) { + for (int j = 0; j < vertex_count_A; j++) { - Vector3 e3=p_transform_a.xform(vertices_A[j]); + Vector3 e3 = p_transform_a.xform(vertices_A[j]); - - if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() )) + if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized())) return; } } - - } separator.generate_contacts(); - } +template <bool withMargin> +static void _collision_convex_polygon_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { -template<bool withMargin> -static void _collision_convex_polygon_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) { + const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW *>(p_a); + const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b); - - const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW*>(p_a); - const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b); - - SeparatorAxisTest<ConvexPolygonShapeSW,FaceShapeSW,withMargin> separator(convex_polygon_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b); + SeparatorAxisTest<ConvexPolygonShapeSW, FaceShapeSW, withMargin> separator(convex_polygon_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b); const Geometry::MeshData &mesh = convex_polygon_A->get_mesh(); @@ -1491,207 +1375,192 @@ static void _collision_convex_polygon_face(const ShapeSW *p_a,const Transform &p const Vector3 *vertices = mesh.vertices.ptr(); int vertex_count = mesh.vertices.size(); - - - Vector3 vertex[3]={ - p_transform_b.xform( face_B->vertex[0] ), - p_transform_b.xform( face_B->vertex[1] ), - p_transform_b.xform( face_B->vertex[2] ), + Vector3 vertex[3] = { + p_transform_b.xform(face_B->vertex[0]), + p_transform_b.xform(face_B->vertex[1]), + p_transform_b.xform(face_B->vertex[2]), }; - if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() )) + if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized())) return; - // faces of A - for (int i=0;i<face_count;i++) { + for (int i = 0; i < face_count; i++) { //Vector3 axis = p_transform_a.xform( faces[i].plane ).normal; - Vector3 axis = p_transform_a.basis.xform( faces[i].plane.normal ).normalized(); + Vector3 axis = p_transform_a.basis.xform(faces[i].plane.normal).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } - // A<->B edges - for (int i=0;i<edge_count;i++) { + for (int i = 0; i < edge_count; i++) { - Vector3 e1=p_transform_a.xform( vertices[edges[i].a] ) - p_transform_a.xform( vertices[edges[i].b] ); + Vector3 e1 = p_transform_a.xform(vertices[edges[i].a]) - p_transform_a.xform(vertices[edges[i].b]); - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - Vector3 e2=vertex[j]-vertex[(j+1)%3]; + Vector3 e2 = vertex[j] - vertex[(j + 1) % 3]; - Vector3 axis=e1.cross( e2 ).normalized(); + Vector3 axis = e1.cross(e2).normalized(); - if (!separator.test_axis( axis )) + if (!separator.test_axis(axis)) return; } } - if (withMargin) { //vertex-vertex - for(int i=0;i<vertex_count;i++) { + for (int i = 0; i < vertex_count; i++) { Vector3 va = p_transform_a.xform(vertices[i]); - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - if (!separator.test_axis( (va-vertex[j]).normalized() )) + if (!separator.test_axis((va - vertex[j]).normalized())) return; - } } //edge-vertex( hsell) - for (int i=0;i<edge_count;i++) { + for (int i = 0; i < edge_count; i++) { - Vector3 e1=p_transform_a.basis.xform( vertices[ edges[i].a] ); - Vector3 e2=p_transform_a.basis.xform( vertices[ edges[i].b] ); - Vector3 n = (e2-e1); + Vector3 e1 = p_transform_a.basis.xform(vertices[edges[i].a]); + Vector3 e2 = p_transform_a.basis.xform(vertices[edges[i].b]); + Vector3 n = (e2 - e1); - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - Vector3 e3=vertex[j]; + Vector3 e3 = vertex[j]; - - if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() )) + if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized())) return; } } - for (int i=0;i<3;i++) { - - Vector3 e1=vertex[i]; - Vector3 e2=vertex[(i+1)%3]; - Vector3 n = (e2-e1); + for (int i = 0; i < 3; i++) { - for(int j=0;j<vertex_count;j++) { + Vector3 e1 = vertex[i]; + Vector3 e2 = vertex[(i + 1) % 3]; + Vector3 n = (e2 - e1); - Vector3 e3=p_transform_a.xform(vertices[j]); + for (int j = 0; j < vertex_count; j++) { + Vector3 e3 = p_transform_a.xform(vertices[j]); - if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() )) + if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized())) return; } } } separator.generate_contacts(); - } - -bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata,bool p_swap,Vector3* r_prev_axis,real_t p_margin_a,real_t p_margin_b) { - - PhysicsServer::ShapeType type_A=p_shape_A->get_type(); - - ERR_FAIL_COND_V(type_A==PhysicsServer::SHAPE_PLANE,false); - ERR_FAIL_COND_V(type_A==PhysicsServer::SHAPE_RAY,false); - ERR_FAIL_COND_V(p_shape_A->is_concave(),false); - - PhysicsServer::ShapeType type_B=p_shape_B->get_type(); - - ERR_FAIL_COND_V(type_B==PhysicsServer::SHAPE_PLANE,false); - ERR_FAIL_COND_V(type_B==PhysicsServer::SHAPE_RAY,false); - ERR_FAIL_COND_V(p_shape_B->is_concave(),false); - - - static const CollisionFunc collision_table[5][5]={ - {_collision_sphere_sphere<false>, - _collision_sphere_box<false>, - _collision_sphere_capsule<false>, - _collision_sphere_convex_polygon<false>, - _collision_sphere_face<false>}, - {0, - _collision_box_box<false>, - _collision_box_capsule<false>, - _collision_box_convex_polygon<false>, - _collision_box_face<false>}, - {0, - 0, - _collision_capsule_capsule<false>, - _collision_capsule_convex_polygon<false>, - _collision_capsule_face<false>}, - {0, - 0, - 0, - _collision_convex_polygon_convex_polygon<false>, - _collision_convex_polygon_face<false>}, - {0, - 0, - 0, - 0, - 0}, +bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap, Vector3 *r_prev_axis, real_t p_margin_a, real_t p_margin_b) { + + PhysicsServer::ShapeType type_A = p_shape_A->get_type(); + + ERR_FAIL_COND_V(type_A == PhysicsServer::SHAPE_PLANE, false); + ERR_FAIL_COND_V(type_A == PhysicsServer::SHAPE_RAY, false); + ERR_FAIL_COND_V(p_shape_A->is_concave(), false); + + PhysicsServer::ShapeType type_B = p_shape_B->get_type(); + + ERR_FAIL_COND_V(type_B == PhysicsServer::SHAPE_PLANE, false); + ERR_FAIL_COND_V(type_B == PhysicsServer::SHAPE_RAY, false); + ERR_FAIL_COND_V(p_shape_B->is_concave(), false); + + static const CollisionFunc collision_table[5][5] = { + { _collision_sphere_sphere<false>, + _collision_sphere_box<false>, + _collision_sphere_capsule<false>, + _collision_sphere_convex_polygon<false>, + _collision_sphere_face<false> }, + { 0, + _collision_box_box<false>, + _collision_box_capsule<false>, + _collision_box_convex_polygon<false>, + _collision_box_face<false> }, + { 0, + 0, + _collision_capsule_capsule<false>, + _collision_capsule_convex_polygon<false>, + _collision_capsule_face<false> }, + { 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<false>, + _collision_convex_polygon_face<false> }, + { 0, + 0, + 0, + 0, + 0 }, }; - static const CollisionFunc collision_table_margin[5][5]={ - {_collision_sphere_sphere<true>, - _collision_sphere_box<true>, - _collision_sphere_capsule<true>, - _collision_sphere_convex_polygon<true>, - _collision_sphere_face<true>}, - {0, - _collision_box_box<true>, - _collision_box_capsule<true>, - _collision_box_convex_polygon<true>, - _collision_box_face<true>}, - {0, - 0, - _collision_capsule_capsule<true>, - _collision_capsule_convex_polygon<true>, - _collision_capsule_face<true>}, - {0, - 0, - 0, - _collision_convex_polygon_convex_polygon<true>, - _collision_convex_polygon_face<true>}, - {0, - 0, - 0, - 0, - 0}, + static const CollisionFunc collision_table_margin[5][5] = { + { _collision_sphere_sphere<true>, + _collision_sphere_box<true>, + _collision_sphere_capsule<true>, + _collision_sphere_convex_polygon<true>, + _collision_sphere_face<true> }, + { 0, + _collision_box_box<true>, + _collision_box_capsule<true>, + _collision_box_convex_polygon<true>, + _collision_box_face<true> }, + { 0, + 0, + _collision_capsule_capsule<true>, + _collision_capsule_convex_polygon<true>, + _collision_capsule_face<true> }, + { 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<true>, + _collision_convex_polygon_face<true> }, + { 0, + 0, + 0, + 0, + 0 }, }; _CollectorCallback callback; - callback.callback=p_result_callback; - callback.swap=p_swap; - callback.userdata=p_userdata; - callback.collided=false; - callback.prev_axis=r_prev_axis; - - const ShapeSW *A=p_shape_A; - const ShapeSW *B=p_shape_B; - const Transform *transform_A=&p_transform_A; - const Transform *transform_B=&p_transform_B; - real_t margin_A=p_margin_a; - real_t margin_B=p_margin_b; + callback.callback = p_result_callback; + callback.swap = p_swap; + callback.userdata = p_userdata; + callback.collided = false; + callback.prev_axis = r_prev_axis; + + const ShapeSW *A = p_shape_A; + const ShapeSW *B = p_shape_B; + const Transform *transform_A = &p_transform_A; + const Transform *transform_B = &p_transform_B; + real_t margin_A = p_margin_a; + real_t margin_B = p_margin_b; if (type_A > type_B) { - SWAP(A,B); - SWAP(transform_A,transform_B); - SWAP(type_A,type_B); - SWAP(margin_A,margin_B); + SWAP(A, B); + SWAP(transform_A, transform_B); + SWAP(type_A, type_B); + SWAP(margin_A, margin_B); callback.swap = !callback.swap; } - CollisionFunc collision_func; - if (margin_A!=0.0 || margin_B!=0.0) { - collision_func = collision_table_margin[type_A-2][type_B-2]; + if (margin_A != 0.0 || margin_B != 0.0) { + collision_func = collision_table_margin[type_A - 2][type_B - 2]; } else { - collision_func = collision_table[type_A-2][type_B-2]; - + collision_func = collision_table[type_A - 2][type_B - 2]; } - ERR_FAIL_COND_V(!collision_func,false); + ERR_FAIL_COND_V(!collision_func, false); - - collision_func(A,*transform_A,B,*transform_B,&callback,margin_A,margin_B); + collision_func(A, *transform_A, B, *transform_B, &callback, margin_A, margin_B); return callback.collided; - } diff --git a/servers/physics/collision_solver_sat.h b/servers/physics/collision_solver_sat.h index 15fe7dc34a..67ffb0b068 100644 --- a/servers/physics/collision_solver_sat.h +++ b/servers/physics/collision_solver_sat.h @@ -31,7 +31,6 @@ #include "collision_solver_sw.h" - -bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap=false,Vector3* r_prev_axis=NULL,real_t p_margin_a=0,real_t p_margin_b=0); +bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap = false, Vector3 *r_prev_axis = NULL, real_t p_margin_a = 0, real_t p_margin_b = 0); #endif // COLLISION_SOLVER_SAT_H diff --git a/servers/physics/collision_solver_sw.cpp b/servers/physics/collision_solver_sw.cpp index f0ddde3a76..0f6e964359 100644 --- a/servers/physics/collision_solver_sw.cpp +++ b/servers/physics/collision_solver_sw.cpp @@ -29,18 +29,16 @@ #include "collision_solver_sw.h" #include "collision_solver_sat.h" -#include "gjk_epa.h" #include "collision_solver_sat.h" - +#include "gjk_epa.h" #define collision_solver sat_calculate_penetration //#define collision_solver gjk_epa_calculate_penetration +bool CollisionSolverSW::solve_static_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) { -bool CollisionSolverSW::solve_static_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result) { - - const PlaneShapeSW *plane = static_cast<const PlaneShapeSW*>(p_shape_A); - if (p_shape_B->get_type()==PhysicsServer::SHAPE_PLANE) + const PlaneShapeSW *plane = static_cast<const PlaneShapeSW *>(p_shape_A); + if (p_shape_B->get_type() == PhysicsServer::SHAPE_PLANE) return false; Plane p = p_transform_A.xform(plane->get_plane()); @@ -48,57 +46,54 @@ bool CollisionSolverSW::solve_static_plane(const ShapeSW *p_shape_A,const Transf Vector3 supports[max_supports]; int support_count; - p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(),max_supports,supports,support_count); + p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(), max_supports, supports, support_count); - bool found=false; + bool found = false; - for(int i=0;i<support_count;i++) { + for (int i = 0; i < support_count; i++) { - supports[i] = p_transform_B.xform( supports[i] ); - if (p.distance_to(supports[i])>=0) + supports[i] = p_transform_B.xform(supports[i]); + if (p.distance_to(supports[i]) >= 0) continue; - found=true; + found = true; Vector3 support_A = p.project(supports[i]); if (p_result_callback) { if (p_swap_result) - p_result_callback(supports[i],support_A,p_userdata); + p_result_callback(supports[i], support_A, p_userdata); else - p_result_callback(support_A,supports[i],p_userdata); + p_result_callback(support_A, supports[i], p_userdata); } - } - return found; } -bool CollisionSolverSW::solve_ray(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result) { +bool CollisionSolverSW::solve_ray(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) { - - const RayShapeSW *ray = static_cast<const RayShapeSW*>(p_shape_A); + const RayShapeSW *ray = static_cast<const RayShapeSW *>(p_shape_A); Vector3 from = p_transform_A.origin; - Vector3 to = from+p_transform_A.basis.get_axis(2)*ray->get_length(); - Vector3 support_A=to; + Vector3 to = from + p_transform_A.basis.get_axis(2) * ray->get_length(); + Vector3 support_A = to; Transform ai = p_transform_B.affine_inverse(); from = ai.xform(from); to = ai.xform(to); - Vector3 p,n; - if (!p_shape_B->intersect_segment(from,to,p,n)) + Vector3 p, n; + if (!p_shape_B->intersect_segment(from, to, p, n)) return false; - Vector3 support_B=p_transform_B.xform(p); + Vector3 support_B = p_transform_B.xform(p); if (p_result_callback) { if (p_swap_result) - p_result_callback(support_B,support_A,p_userdata); + p_result_callback(support_B, support_A, p_userdata); else - p_result_callback(support_A,support_B,p_userdata); + p_result_callback(support_A, support_B, p_userdata); } return true; } @@ -117,169 +112,153 @@ struct _ConcaveCollisionInfo { bool tested; real_t margin_A; real_t margin_B; - Vector3 close_A,close_B; - + Vector3 close_A, close_B; }; void CollisionSolverSW::concave_callback(void *p_userdata, ShapeSW *p_convex) { - - _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo*)(p_userdata); + _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo *)(p_userdata); cinfo.aabb_tests++; - bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, p_convex,*cinfo.transform_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result,NULL,cinfo.margin_A,cinfo.margin_B); + bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, p_convex, *cinfo.transform_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, NULL, cinfo.margin_A, cinfo.margin_B); if (!collided) return; - cinfo.collided=true; + cinfo.collided = true; cinfo.collisions++; - } -bool CollisionSolverSW::solve_concave(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,real_t p_margin_A,real_t p_margin_B) { +bool CollisionSolverSW::solve_concave(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, real_t p_margin_A, real_t p_margin_B) { - - const ConcaveShapeSW *concave_B=static_cast<const ConcaveShapeSW*>(p_shape_B); + const ConcaveShapeSW *concave_B = static_cast<const ConcaveShapeSW *>(p_shape_B); _ConcaveCollisionInfo cinfo; - cinfo.transform_A=&p_transform_A; - cinfo.shape_A=p_shape_A; - cinfo.transform_B=&p_transform_B; - cinfo.result_callback=p_result_callback; - cinfo.userdata=p_userdata; - cinfo.swap_result=p_swap_result; - cinfo.collided=false; - cinfo.collisions=0; - cinfo.margin_A=p_margin_A; - cinfo.margin_B=p_margin_B; - - cinfo.aabb_tests=0; + cinfo.transform_A = &p_transform_A; + cinfo.shape_A = p_shape_A; + cinfo.transform_B = &p_transform_B; + cinfo.result_callback = p_result_callback; + cinfo.userdata = p_userdata; + cinfo.swap_result = p_swap_result; + cinfo.collided = false; + cinfo.collisions = 0; + cinfo.margin_A = p_margin_A; + cinfo.margin_B = p_margin_B; + + cinfo.aabb_tests = 0; Transform rel_transform = p_transform_A; - rel_transform.origin-=p_transform_B.origin; + rel_transform.origin -= p_transform_B.origin; //quickly compute a local AABB Rect3 local_aabb; - for(int i=0;i<3;i++) { - - Vector3 axis( p_transform_B.basis.get_axis(i) ); - real_t axis_scale = 1.0/axis.length(); - axis*=axis_scale; + for (int i = 0; i < 3; i++) { - real_t smin,smax; - p_shape_A->project_range(axis,rel_transform,smin,smax); - smin-=p_margin_A; - smax+=p_margin_A; - smin*=axis_scale; - smax*=axis_scale; + Vector3 axis(p_transform_B.basis.get_axis(i)); + real_t axis_scale = 1.0 / axis.length(); + axis *= axis_scale; + real_t smin, smax; + p_shape_A->project_range(axis, rel_transform, smin, smax); + smin -= p_margin_A; + smax += p_margin_A; + smin *= axis_scale; + smax *= axis_scale; - local_aabb.pos[i]=smin; - local_aabb.size[i]=smax-smin; + local_aabb.pos[i] = smin; + local_aabb.size[i] = smax - smin; } - concave_B->cull(local_aabb,concave_callback,&cinfo); + concave_B->cull(local_aabb, concave_callback, &cinfo); //print_line("COL AABB TESTS: "+itos(cinfo.aabb_tests)); return cinfo.collided; } +bool CollisionSolverSW::solve_static(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, Vector3 *r_sep_axis, real_t p_margin_A, real_t p_margin_B) { -bool CollisionSolverSW::solve_static(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,Vector3 *r_sep_axis,real_t p_margin_A,real_t p_margin_B) { - - - PhysicsServer::ShapeType type_A=p_shape_A->get_type(); - PhysicsServer::ShapeType type_B=p_shape_B->get_type(); - bool concave_A=p_shape_A->is_concave(); - bool concave_B=p_shape_B->is_concave(); + PhysicsServer::ShapeType type_A = p_shape_A->get_type(); + PhysicsServer::ShapeType type_B = p_shape_B->get_type(); + bool concave_A = p_shape_A->is_concave(); + bool concave_B = p_shape_B->is_concave(); bool swap = false; - if (type_A>type_B) { - SWAP(type_A,type_B); - SWAP(concave_A,concave_B); - swap=true; + if (type_A > type_B) { + SWAP(type_A, type_B); + SWAP(concave_A, concave_B); + swap = true; } - if (type_A==PhysicsServer::SHAPE_PLANE) { + if (type_A == PhysicsServer::SHAPE_PLANE) { - if (type_B==PhysicsServer::SHAPE_PLANE) + if (type_B == PhysicsServer::SHAPE_PLANE) return false; - if (type_B==PhysicsServer::SHAPE_RAY) { + if (type_B == PhysicsServer::SHAPE_RAY) { return false; } if (swap) { - return solve_static_plane(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true); + return solve_static_plane(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true); } else { - return solve_static_plane(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false); + return solve_static_plane(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false); } - } else if (type_A==PhysicsServer::SHAPE_RAY) { + } else if (type_A == PhysicsServer::SHAPE_RAY) { - if (type_B==PhysicsServer::SHAPE_RAY) + if (type_B == PhysicsServer::SHAPE_RAY) return false; if (swap) { - return solve_ray(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true); + return solve_ray(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true); } else { - return solve_ray(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false); + return solve_ray(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false); } } else if (concave_B) { - if (concave_A) return false; if (!swap) - return solve_concave(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false,p_margin_A,p_margin_B); + return solve_concave(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, p_margin_A, p_margin_B); else - return solve_concave(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true,p_margin_A,p_margin_B); - - + return solve_concave(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true, p_margin_A, p_margin_B); } else { - return collision_solver(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback,p_userdata,false,r_sep_axis,p_margin_A,p_margin_B); + return collision_solver(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, r_sep_axis, p_margin_A, p_margin_B); } - return false; } - void CollisionSolverSW::concave_distance_callback(void *p_userdata, ShapeSW *p_convex) { - - _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo*)(p_userdata); + _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo *)(p_userdata); cinfo.aabb_tests++; if (cinfo.collided) return; - Vector3 close_A,close_B; - cinfo.collided = !gjk_epa_calculate_distance(cinfo.shape_A,*cinfo.transform_A,p_convex,*cinfo.transform_B,close_A,close_B); + Vector3 close_A, close_B; + cinfo.collided = !gjk_epa_calculate_distance(cinfo.shape_A, *cinfo.transform_A, p_convex, *cinfo.transform_B, close_A, close_B); if (cinfo.collided) return; if (!cinfo.tested || close_A.distance_squared_to(close_B) < cinfo.close_A.distance_squared_to(cinfo.close_B)) { - cinfo.close_A=close_A; - cinfo.close_B=close_B; - cinfo.tested=true; + cinfo.close_A = close_A; + cinfo.close_B = close_B; + cinfo.tested = true; } cinfo.collisions++; - } +bool CollisionSolverSW::solve_distance_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B) { - -bool CollisionSolverSW::solve_distance_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B) { - - const PlaneShapeSW *plane = static_cast<const PlaneShapeSW*>(p_shape_A); - if (p_shape_B->get_type()==PhysicsServer::SHAPE_PLANE) + const PlaneShapeSW *plane = static_cast<const PlaneShapeSW *>(p_shape_A); + if (p_shape_B->get_type() == PhysicsServer::SHAPE_PLANE) return false; Plane p = p_transform_A.xform(plane->get_plane()); @@ -287,43 +266,41 @@ bool CollisionSolverSW::solve_distance_plane(const ShapeSW *p_shape_A,const Tran Vector3 supports[max_supports]; int support_count; - p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(),max_supports,supports,support_count); + p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(), max_supports, supports, support_count); - bool collided=false; + bool collided = false; Vector3 closest; real_t closest_d; + for (int i = 0; i < support_count; i++) { - for(int i=0;i<support_count;i++) { - - supports[i] = p_transform_B.xform( supports[i] ); + supports[i] = p_transform_B.xform(supports[i]); real_t d = p.distance_to(supports[i]); - if (i==0 || d<closest_d) { - closest=supports[i]; - closest_d=d; - if (d<=0) - collided=true; + if (i == 0 || d < closest_d) { + closest = supports[i]; + closest_d = d; + if (d <= 0) + collided = true; } - } - r_point_A=p.project(closest); - r_point_B=closest; + r_point_A = p.project(closest); + r_point_B = closest; return collided; } -bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B,const Rect3& p_concave_hint,Vector3 *r_sep_axis) { +bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B, const Rect3 &p_concave_hint, Vector3 *r_sep_axis) { if (p_shape_A->is_concave()) return false; - if (p_shape_B->get_type()==PhysicsServer::SHAPE_PLANE) { + if (p_shape_B->get_type() == PhysicsServer::SHAPE_PLANE) { - Vector3 a,b; - bool col = solve_distance_plane(p_shape_B,p_transform_B,p_shape_A,p_transform_A,a,b); - r_point_A=b; - r_point_B=a; + Vector3 a, b; + bool col = solve_distance_plane(p_shape_B, p_transform_B, p_shape_A, p_transform_A, a, b); + r_point_A = b; + r_point_B = a; return !col; } else if (p_shape_B->is_concave()) { @@ -331,62 +308,59 @@ bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A,const Transform& if (p_shape_A->is_concave()) return false; - - const ConcaveShapeSW *concave_B=static_cast<const ConcaveShapeSW*>(p_shape_B); + const ConcaveShapeSW *concave_B = static_cast<const ConcaveShapeSW *>(p_shape_B); _ConcaveCollisionInfo cinfo; - cinfo.transform_A=&p_transform_A; - cinfo.shape_A=p_shape_A; - cinfo.transform_B=&p_transform_B; - cinfo.result_callback=NULL; - cinfo.userdata=NULL; - cinfo.swap_result=false; - cinfo.collided=false; - cinfo.collisions=0; - cinfo.aabb_tests=0; - cinfo.tested=false; + cinfo.transform_A = &p_transform_A; + cinfo.shape_A = p_shape_A; + cinfo.transform_B = &p_transform_B; + cinfo.result_callback = NULL; + cinfo.userdata = NULL; + cinfo.swap_result = false; + cinfo.collided = false; + cinfo.collisions = 0; + cinfo.aabb_tests = 0; + cinfo.tested = false; Transform rel_transform = p_transform_A; - rel_transform.origin-=p_transform_B.origin; + rel_transform.origin -= p_transform_B.origin; //quickly compute a local AABB - bool use_cc_hint=p_concave_hint!=Rect3(); + bool use_cc_hint = p_concave_hint != Rect3(); Rect3 cc_hint_aabb; if (use_cc_hint) { - cc_hint_aabb=p_concave_hint; - cc_hint_aabb.pos-=p_transform_B.origin; + cc_hint_aabb = p_concave_hint; + cc_hint_aabb.pos -= p_transform_B.origin; } Rect3 local_aabb; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - Vector3 axis( p_transform_B.basis.get_axis(i) ); - real_t axis_scale = ((real_t)1.0)/axis.length(); - axis*=axis_scale; + Vector3 axis(p_transform_B.basis.get_axis(i)); + real_t axis_scale = ((real_t)1.0) / axis.length(); + axis *= axis_scale; - real_t smin,smax; + real_t smin, smax; - if (use_cc_hint) { - cc_hint_aabb.project_range_in_plane(Plane(axis,0),smin,smax); - } else { - p_shape_A->project_range(axis,rel_transform,smin,smax); - } + if (use_cc_hint) { + cc_hint_aabb.project_range_in_plane(Plane(axis, 0), smin, smax); + } else { + p_shape_A->project_range(axis, rel_transform, smin, smax); + } - smin*=axis_scale; - smax*=axis_scale; + smin *= axis_scale; + smax *= axis_scale; - local_aabb.pos[i]=smin; - local_aabb.size[i]=smax-smin; + local_aabb.pos[i] = smin; + local_aabb.size[i] = smax - smin; } - - concave_B->cull(local_aabb,concave_distance_callback,&cinfo); + concave_B->cull(local_aabb, concave_distance_callback, &cinfo); if (!cinfo.collided) { //print_line(itos(cinfo.tested)); - r_point_A=cinfo.close_A; - r_point_B=cinfo.close_B; - + r_point_A = cinfo.close_A; + r_point_B = cinfo.close_B; } //print_line("DIST AABB TESTS: "+itos(cinfo.aabb_tests)); @@ -394,10 +368,8 @@ bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A,const Transform& return !cinfo.collided; } else { - return gjk_epa_calculate_distance(p_shape_A,p_transform_A,p_shape_B,p_transform_B,r_point_A,r_point_B); //should pass sepaxis.. + return gjk_epa_calculate_distance(p_shape_A, p_transform_A, p_shape_B, p_transform_B, r_point_A, r_point_B); //should pass sepaxis.. } - return false; } - diff --git a/servers/physics/collision_solver_sw.h b/servers/physics/collision_solver_sw.h index b8d37a8a96..b0f18dc0ac 100644 --- a/servers/physics/collision_solver_sw.h +++ b/servers/physics/collision_solver_sw.h @@ -31,25 +31,21 @@ #include "shape_sw.h" -class CollisionSolverSW -{ +class CollisionSolverSW { public: - typedef void (*CallbackResult)(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata); -private: + typedef void (*CallbackResult)(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata); +private: static void concave_callback(void *p_userdata, ShapeSW *p_convex); - static bool solve_static_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result); - static bool solve_ray(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result); - static bool solve_concave(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,real_t p_margin_A=0,real_t p_margin_B=0); + static bool solve_static_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result); + static bool solve_ray(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result); + static bool solve_concave(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, real_t p_margin_A = 0, real_t p_margin_B = 0); static void concave_distance_callback(void *p_userdata, ShapeSW *p_convex); - static bool solve_distance_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B); + static bool solve_distance_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B); public: - - - static bool solve_static(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,Vector3 *r_sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0); - static bool solve_distance(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B,const Rect3& p_concave_hint,Vector3 *r_sep_axis=NULL); - + static bool solve_static(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, Vector3 *r_sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0); + static bool solve_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B, const Rect3 &p_concave_hint, Vector3 *r_sep_axis = NULL); }; #endif // COLLISION_SOLVER__SW_H diff --git a/servers/physics/constraint_sw.h b/servers/physics/constraint_sw.h index f5bbe4bbd0..2cd0e1a420 100644 --- a/servers/physics/constraint_sw.h +++ b/servers/physics/constraint_sw.h @@ -40,35 +40,37 @@ class ConstraintSW : public RID_Data { ConstraintSW *island_list_next; int priority; - RID self; protected: - ConstraintSW(BodySW **p_body_ptr=NULL,int p_body_count=0) { _body_ptr=p_body_ptr; _body_count=p_body_count; island_step=0; priority=1; } -public: + ConstraintSW(BodySW **p_body_ptr = NULL, int p_body_count = 0) { + _body_ptr = p_body_ptr; + _body_count = p_body_count; + island_step = 0; + priority = 1; + } - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } +public: + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } _FORCE_INLINE_ RID get_self() const { return self; } _FORCE_INLINE_ uint64_t get_island_step() const { return island_step; } - _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; } + _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; } + _FORCE_INLINE_ ConstraintSW *get_island_next() const { return island_next; } + _FORCE_INLINE_ void set_island_next(ConstraintSW *p_next) { island_next = p_next; } - _FORCE_INLINE_ ConstraintSW* get_island_next() const { return island_next; } - _FORCE_INLINE_ void set_island_next(ConstraintSW* p_next) { island_next=p_next; } - - _FORCE_INLINE_ ConstraintSW* get_island_list_next() const { return island_list_next; } - _FORCE_INLINE_ void set_island_list_next(ConstraintSW* p_next) { island_list_next=p_next; } + _FORCE_INLINE_ ConstraintSW *get_island_list_next() const { return island_list_next; } + _FORCE_INLINE_ void set_island_list_next(ConstraintSW *p_next) { island_list_next = p_next; } _FORCE_INLINE_ BodySW **get_body_ptr() const { return _body_ptr; } _FORCE_INLINE_ int get_body_count() const { return _body_count; } - _FORCE_INLINE_ void set_priority(int p_priority) { priority=p_priority; } + _FORCE_INLINE_ void set_priority(int p_priority) { priority = p_priority; } _FORCE_INLINE_ int get_priority() const { return priority; } - - virtual bool setup(real_t p_step)=0; - virtual void solve(real_t p_step)=0; + virtual bool setup(real_t p_step) = 0; + virtual void solve(real_t p_step) = 0; virtual ~ConstraintSW() {} }; diff --git a/servers/physics/gjk_epa.cpp b/servers/physics/gjk_epa.cpp index 06c2c2382c..f65e6768ab 100644 --- a/servers/physics/gjk_epa.cpp +++ b/servers/physics/gjk_epa.cpp @@ -884,33 +884,30 @@ bool Penetration( const ShapeSW* shape0, /* clang-format on */ - -bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, Vector3& r_result_A, Vector3& r_result_B) { - +bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_result_A, Vector3 &r_result_B) { GjkEpa2::sResults res; - if (GjkEpa2::Distance(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_transform_B.origin-p_transform_A.origin,res)) { + if (GjkEpa2::Distance(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_transform_B.origin - p_transform_A.origin, res)) { - r_result_A=res.witnesses[0]; - r_result_B=res.witnesses[1]; + r_result_A = res.witnesses[0]; + r_result_B = res.witnesses[1]; return true; } return false; - } -bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap ) { +bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap) { GjkEpa2::sResults res; - if (GjkEpa2::Penetration(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_transform_B.origin-p_transform_A.origin,res)) { + if (GjkEpa2::Penetration(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_transform_B.origin - p_transform_A.origin, res)) { if (p_result_callback) { if (p_swap) - p_result_callback(res.witnesses[1],res.witnesses[0],p_userdata); + p_result_callback(res.witnesses[1], res.witnesses[0], p_userdata); else - p_result_callback(res.witnesses[0],res.witnesses[1],p_userdata); + p_result_callback(res.witnesses[0], res.witnesses[1], p_userdata); } return true; } diff --git a/servers/physics/gjk_epa.h b/servers/physics/gjk_epa.h index 58cf8f50ce..ae5db733b5 100644 --- a/servers/physics/gjk_epa.h +++ b/servers/physics/gjk_epa.h @@ -35,7 +35,7 @@ */ #include "collision_solver_sw.h" -bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap=false); -bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, Vector3& r_result_A, Vector3& r_result_B); +bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap = false); +bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_result_A, Vector3 &r_result_B); #endif diff --git a/servers/physics/joints/cone_twist_joint_sw.cpp b/servers/physics/joints/cone_twist_joint_sw.cpp index d78bcbd16d..8cab81de2c 100644 --- a/servers/physics/joints/cone_twist_joint_sw.cpp +++ b/servers/physics/joints/cone_twist_joint_sw.cpp @@ -34,29 +34,26 @@ See corresponding header file for licensing info. #include "cone_twist_joint_sw.h" -static void plane_space(const Vector3& n, Vector3& p, Vector3& q) { - - if (Math::abs(n.z) > 0.707106781186547524400844362) { - // choose p in y-z plane - real_t a = n[1]*n[1] + n[2]*n[2]; - real_t k = 1.0/Math::sqrt(a); - p=Vector3(0,-n[2]*k,n[1]*k); - // set q = n x p - q=Vector3(a*k,-n[0]*p[2],n[0]*p[1]); - } - else { - // choose p in x-y plane - real_t a = n.x*n.x + n.y*n.y; - real_t k = 1.0/Math::sqrt(a); - p=Vector3(-n.y*k,n.x*k,0); - // set q = n x p - q=Vector3(-n.z*p.y,n.z*p.x,a*k); - } +static void plane_space(const Vector3 &n, Vector3 &p, Vector3 &q) { + + if (Math::abs(n.z) > 0.707106781186547524400844362) { + // choose p in y-z plane + real_t a = n[1] * n[1] + n[2] * n[2]; + real_t k = 1.0 / Math::sqrt(a); + p = Vector3(0, -n[2] * k, n[1] * k); + // set q = n x p + q = Vector3(a * k, -n[0] * p[2], n[0] * p[1]); + } else { + // choose p in x-y plane + real_t a = n.x * n.x + n.y * n.y; + real_t k = 1.0 / Math::sqrt(a); + p = Vector3(-n.y * k, n.x * k, 0); + // set q = n x p + q = Vector3(-n.z * p.y, n.z * p.x, a * k); + } } - -static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) -{ +static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) { real_t coeff_1 = Math_PI / 4.0f; real_t coeff_2 = 3.0f * coeff_1; real_t abs_y = Math::abs(y); @@ -71,32 +68,31 @@ static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) return (y < 0.0f) ? -angle : angle; } -ConeTwistJointSW::ConeTwistJointSW(BodySW* rbA,BodySW* rbB,const Transform& rbAFrame, const Transform& rbBFrame) : JointSW(_arr,2) { +ConeTwistJointSW::ConeTwistJointSW(BodySW *rbA, BodySW *rbB, const Transform &rbAFrame, const Transform &rbBFrame) + : JointSW(_arr, 2) { - A=rbA; - B=rbB; + A = rbA; + B = rbB; + m_rbAFrame = rbAFrame; + m_rbBFrame = rbBFrame; - m_rbAFrame=rbAFrame; - m_rbBFrame=rbBFrame; - - m_swingSpan1 = Math_PI/4.0; - m_swingSpan2 = Math_PI/4.0; - m_twistSpan = Math_PI*2; + m_swingSpan1 = Math_PI / 4.0; + m_swingSpan2 = Math_PI / 4.0; + m_twistSpan = Math_PI * 2; m_biasFactor = 0.3f; m_relaxationFactor = 1.0f; m_solveTwistLimit = false; m_solveSwingLimit = false; - A->add_constraint(this,0); - B->add_constraint(this,1); + A->add_constraint(this, 0); + B->add_constraint(this, 1); - m_appliedImpulse=0; + m_appliedImpulse = 0; } - -bool ConeTwistJointSW::setup(real_t p_step) { +bool ConeTwistJointSW::setup(real_t p_step) { m_appliedImpulse = real_t(0.); //set bias, sign, clear accumulator @@ -107,109 +103,97 @@ bool ConeTwistJointSW::setup(real_t p_step) { m_accTwistLimitImpulse = real_t(0.); m_accSwingLimitImpulse = real_t(0.); - if (!m_angularOnly) - { + if (!m_angularOnly) { Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin); Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin); Vector3 relPos = pivotBInW - pivotAInW; Vector3 normal[3]; - if (relPos.length_squared() > CMP_EPSILON) - { + if (relPos.length_squared() > CMP_EPSILON) { normal[0] = relPos.normalized(); - } - else - { - normal[0]=Vector3(real_t(1.0),0,0); + } else { + normal[0] = Vector3(real_t(1.0), 0, 0); } plane_space(normal[0], normal[1], normal[2]); - for (int i=0;i<3;i++) - { + for (int i = 0; i < 3; i++) { memnew_placement(&m_jac[i], JacobianEntrySW( - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - pivotAInW - A->get_transform().origin - A->get_center_of_mass(), - pivotBInW - B->get_transform().origin - B->get_center_of_mass(), - normal[i], - A->get_inv_inertia(), - A->get_inv_mass(), - B->get_inv_inertia(), - B->get_inv_mass())); + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + pivotAInW - A->get_transform().origin - A->get_center_of_mass(), + pivotBInW - B->get_transform().origin - B->get_center_of_mass(), + normal[i], + A->get_inv_inertia(), + A->get_inv_mass(), + B->get_inv_inertia(), + B->get_inv_mass())); } } - Vector3 b1Axis1,b1Axis2,b1Axis3; - Vector3 b2Axis1,b2Axis2; + Vector3 b1Axis1, b1Axis2, b1Axis3; + Vector3 b2Axis1, b2Axis2; - b1Axis1 = A->get_transform().basis.xform( this->m_rbAFrame.basis.get_axis(0) ); - b2Axis1 = B->get_transform().basis.xform( this->m_rbBFrame.basis.get_axis(0) ); + b1Axis1 = A->get_transform().basis.xform(this->m_rbAFrame.basis.get_axis(0)); + b2Axis1 = B->get_transform().basis.xform(this->m_rbBFrame.basis.get_axis(0)); - real_t swing1=real_t(0.),swing2 = real_t(0.); + real_t swing1 = real_t(0.), swing2 = real_t(0.); - real_t swx=real_t(0.),swy = real_t(0.); + real_t swx = real_t(0.), swy = real_t(0.); real_t thresh = real_t(10.); real_t fact; // Get Frame into world space - if (m_swingSpan1 >= real_t(0.05f)) - { - b1Axis2 = A->get_transform().basis.xform( this->m_rbAFrame.basis.get_axis(1) ); + if (m_swingSpan1 >= real_t(0.05f)) { + b1Axis2 = A->get_transform().basis.xform(this->m_rbAFrame.basis.get_axis(1)); //swing1 = btAtan2Fast( b2Axis1.dot(b1Axis2),b2Axis1.dot(b1Axis1) ); swx = b2Axis1.dot(b1Axis1); swy = b2Axis1.dot(b1Axis2); - swing1 = atan2fast(swy, swx); - fact = (swy*swy + swx*swx) * thresh * thresh; + swing1 = atan2fast(swy, swx); + fact = (swy * swy + swx * swx) * thresh * thresh; fact = fact / (fact + real_t(1.0)); swing1 *= fact; - } - if (m_swingSpan2 >= real_t(0.05f)) - { - b1Axis3 = A->get_transform().basis.xform( this->m_rbAFrame.basis.get_axis(2) ); + if (m_swingSpan2 >= real_t(0.05f)) { + b1Axis3 = A->get_transform().basis.xform(this->m_rbAFrame.basis.get_axis(2)); //swing2 = btAtan2Fast( b2Axis1.dot(b1Axis3),b2Axis1.dot(b1Axis1) ); swx = b2Axis1.dot(b1Axis1); swy = b2Axis1.dot(b1Axis3); - swing2 = atan2fast(swy, swx); - fact = (swy*swy + swx*swx) * thresh * thresh; + swing2 = atan2fast(swy, swx); + fact = (swy * swy + swx * swx) * thresh * thresh; fact = fact / (fact + real_t(1.0)); swing2 *= fact; } - real_t RMaxAngle1Sq = 1.0f / (m_swingSpan1*m_swingSpan1); - real_t RMaxAngle2Sq = 1.0f / (m_swingSpan2*m_swingSpan2); - real_t EllipseAngle = Math::abs(swing1*swing1)* RMaxAngle1Sq + Math::abs(swing2*swing2) * RMaxAngle2Sq; + real_t RMaxAngle1Sq = 1.0f / (m_swingSpan1 * m_swingSpan1); + real_t RMaxAngle2Sq = 1.0f / (m_swingSpan2 * m_swingSpan2); + real_t EllipseAngle = Math::abs(swing1 * swing1) * RMaxAngle1Sq + Math::abs(swing2 * swing2) * RMaxAngle2Sq; - if (EllipseAngle > 1.0f) - { - m_swingCorrection = EllipseAngle-1.0f; + if (EllipseAngle > 1.0f) { + m_swingCorrection = EllipseAngle - 1.0f; m_solveSwingLimit = true; // Calculate necessary axis & factors - m_swingAxis = b2Axis1.cross(b1Axis2* b2Axis1.dot(b1Axis2) + b1Axis3* b2Axis1.dot(b1Axis3)); + m_swingAxis = b2Axis1.cross(b1Axis2 * b2Axis1.dot(b1Axis2) + b1Axis3 * b2Axis1.dot(b1Axis3)); m_swingAxis.normalize(); real_t swingAxisSign = (b2Axis1.dot(b1Axis1) >= 0.0f) ? 1.0f : -1.0f; m_swingAxis *= swingAxisSign; - m_kSwing = real_t(1.) / (A->compute_angular_impulse_denominator(m_swingAxis) + - B->compute_angular_impulse_denominator(m_swingAxis)); - + m_kSwing = real_t(1.) / (A->compute_angular_impulse_denominator(m_swingAxis) + + B->compute_angular_impulse_denominator(m_swingAxis)); } // Twist limits - if (m_twistSpan >= real_t(0.)) - { - Vector3 b2Axis2 = B->get_transform().basis.xform( this->m_rbBFrame.basis.get_axis(1) ); - Quat rotationArc = Quat(b2Axis1,b1Axis1); + if (m_twistSpan >= real_t(0.)) { + Vector3 b2Axis2 = B->get_transform().basis.xform(this->m_rbBFrame.basis.get_axis(1)); + Quat rotationArc = Quat(b2Axis1, b1Axis1); Vector3 TwistRef = rotationArc.xform(b2Axis2); - real_t twist = atan2fast( TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2) ); + real_t twist = atan2fast(TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2)); real_t lockedFreeFactor = (m_twistSpan > real_t(0.05f)) ? m_limitSoftness : real_t(0.); - if (twist <= -m_twistSpan*lockedFreeFactor) - { + if (twist <= -m_twistSpan * lockedFreeFactor) { m_twistCorrection = -(twist + m_twistSpan); m_solveTwistLimit = true; @@ -218,28 +202,24 @@ bool ConeTwistJointSW::setup(real_t p_step) { m_twistAxis *= -1.0f; m_kTwist = real_t(1.) / (A->compute_angular_impulse_denominator(m_twistAxis) + - B->compute_angular_impulse_denominator(m_twistAxis)); - - } else - if (twist > m_twistSpan*lockedFreeFactor) - { - m_twistCorrection = (twist - m_twistSpan); - m_solveTwistLimit = true; + B->compute_angular_impulse_denominator(m_twistAxis)); - m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f; - m_twistAxis.normalize(); + } else if (twist > m_twistSpan * lockedFreeFactor) { + m_twistCorrection = (twist - m_twistSpan); + m_solveTwistLimit = true; - m_kTwist = real_t(1.) / (A->compute_angular_impulse_denominator(m_twistAxis) + - B->compute_angular_impulse_denominator(m_twistAxis)); + m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f; + m_twistAxis.normalize(); - } + m_kTwist = real_t(1.) / (A->compute_angular_impulse_denominator(m_twistAxis) + + B->compute_angular_impulse_denominator(m_twistAxis)); + } } return true; } -void ConeTwistJointSW::solve(real_t timeStep) -{ +void ConeTwistJointSW::solve(real_t timeStep) { Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin); Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin); @@ -247,8 +227,7 @@ void ConeTwistJointSW::solve(real_t timeStep) real_t tau = real_t(0.3); //linear part - if (!m_angularOnly) - { + if (!m_angularOnly) { Vector3 rel_pos1 = pivotAInW - A->get_transform().origin; Vector3 rel_pos2 = pivotBInW - B->get_transform().origin; @@ -256,16 +235,15 @@ void ConeTwistJointSW::solve(real_t timeStep) Vector3 vel2 = B->get_velocity_in_local_point(rel_pos2); Vector3 vel = vel1 - vel2; - for (int i=0;i<3;i++) - { - const Vector3& normal = m_jac[i].m_linearJointAxis; + for (int i = 0; i < 3; i++) { + const Vector3 &normal = m_jac[i].m_linearJointAxis; real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal(); real_t rel_vel; rel_vel = normal.dot(vel); //positional error (zeroth order error) real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal - real_t impulse = depth*tau/timeStep * jacDiagABInv - rel_vel * jacDiagABInv; + real_t impulse = depth * tau / timeStep * jacDiagABInv - rel_vel * jacDiagABInv; m_appliedImpulse += impulse; Vector3 impulse_vector = normal * impulse; A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector); @@ -275,79 +253,73 @@ void ConeTwistJointSW::solve(real_t timeStep) { ///solve angular part - const Vector3& angVelA = A->get_angular_velocity(); - const Vector3& angVelB = B->get_angular_velocity(); + const Vector3 &angVelA = A->get_angular_velocity(); + const Vector3 &angVelB = B->get_angular_velocity(); // solve swing limit - if (m_solveSwingLimit) - { - real_t amplitude = ((angVelB - angVelA).dot( m_swingAxis )*m_relaxationFactor*m_relaxationFactor + m_swingCorrection*(real_t(1.)/timeStep)*m_biasFactor); + if (m_solveSwingLimit) { + real_t amplitude = ((angVelB - angVelA).dot(m_swingAxis) * m_relaxationFactor * m_relaxationFactor + m_swingCorrection * (real_t(1.) / timeStep) * m_biasFactor); real_t impulseMag = amplitude * m_kSwing; // Clamp the accumulated impulse real_t temp = m_accSwingLimitImpulse; - m_accSwingLimitImpulse = MAX(m_accSwingLimitImpulse + impulseMag, real_t(0.0) ); + m_accSwingLimitImpulse = MAX(m_accSwingLimitImpulse + impulseMag, real_t(0.0)); impulseMag = m_accSwingLimitImpulse - temp; Vector3 impulse = m_swingAxis * impulseMag; A->apply_torque_impulse(impulse); B->apply_torque_impulse(-impulse); - } // solve twist limit - if (m_solveTwistLimit) - { - real_t amplitude = ((angVelB - angVelA).dot( m_twistAxis )*m_relaxationFactor*m_relaxationFactor + m_twistCorrection*(real_t(1.)/timeStep)*m_biasFactor ); + if (m_solveTwistLimit) { + real_t amplitude = ((angVelB - angVelA).dot(m_twistAxis) * m_relaxationFactor * m_relaxationFactor + m_twistCorrection * (real_t(1.) / timeStep) * m_biasFactor); real_t impulseMag = amplitude * m_kTwist; // Clamp the accumulated impulse real_t temp = m_accTwistLimitImpulse; - m_accTwistLimitImpulse = MAX(m_accTwistLimitImpulse + impulseMag, real_t(0.0) ); + m_accTwistLimitImpulse = MAX(m_accTwistLimitImpulse + impulseMag, real_t(0.0)); impulseMag = m_accTwistLimitImpulse - temp; Vector3 impulse = m_twistAxis * impulseMag; A->apply_torque_impulse(impulse); B->apply_torque_impulse(-impulse); - } - } - } void ConeTwistJointSW::set_param(PhysicsServer::ConeTwistJointParam p_param, real_t p_value) { - switch(p_param) { + switch (p_param) { case PhysicsServer::CONE_TWIST_JOINT_SWING_SPAN: { - m_swingSpan1=p_value; - m_swingSpan2=p_value; + m_swingSpan1 = p_value; + m_swingSpan2 = p_value; } break; case PhysicsServer::CONE_TWIST_JOINT_TWIST_SPAN: { - m_twistSpan=p_value; + m_twistSpan = p_value; } break; case PhysicsServer::CONE_TWIST_JOINT_BIAS: { - m_biasFactor=p_value; + m_biasFactor = p_value; } break; case PhysicsServer::CONE_TWIST_JOINT_SOFTNESS: { - m_limitSoftness=p_value; + m_limitSoftness = p_value; } break; case PhysicsServer::CONE_TWIST_JOINT_RELAXATION: { - m_relaxationFactor=p_value; + m_relaxationFactor = p_value; } break; } } -real_t ConeTwistJointSW::get_param(PhysicsServer::ConeTwistJointParam p_param) const{ +real_t ConeTwistJointSW::get_param(PhysicsServer::ConeTwistJointParam p_param) const { - switch(p_param) { + switch (p_param) { case PhysicsServer::CONE_TWIST_JOINT_SWING_SPAN: { return m_swingSpan1; diff --git a/servers/physics/joints/cone_twist_joint_sw.h b/servers/physics/joints/cone_twist_joint_sw.h index eb7a5cd1b1..c122c22258 100644 --- a/servers/physics/joints/cone_twist_joint_sw.h +++ b/servers/physics/joints/cone_twist_joint_sw.h @@ -51,14 +51,11 @@ Written by: Marcus Hennix #ifndef CONE_TWIST_JOINT_SW_H #define CONE_TWIST_JOINT_SW_H -#include "servers/physics/joints_sw.h" #include "servers/physics/joints/jacobian_entry_sw.h" - - +#include "servers/physics/joints_sw.h" ///ConeTwistJointSW can be used to simulate ragdoll joints (upper arm, leg etc) -class ConeTwistJointSW : public JointSW -{ +class ConeTwistJointSW : public JointSW { #ifdef IN_PARALLELL_SOLVER public: #endif @@ -72,86 +69,73 @@ public: BodySW *_arr[2]; }; - JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints - + JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints real_t m_appliedImpulse; Transform m_rbAFrame; Transform m_rbBFrame; - real_t m_limitSoftness; - real_t m_biasFactor; - real_t m_relaxationFactor; - - real_t m_swingSpan1; - real_t m_swingSpan2; - real_t m_twistSpan; + real_t m_limitSoftness; + real_t m_biasFactor; + real_t m_relaxationFactor; - Vector3 m_swingAxis; - Vector3 m_twistAxis; + real_t m_swingSpan1; + real_t m_swingSpan2; + real_t m_twistSpan; - real_t m_kSwing; - real_t m_kTwist; + Vector3 m_swingAxis; + Vector3 m_twistAxis; - real_t m_twistLimitSign; - real_t m_swingCorrection; - real_t m_twistCorrection; + real_t m_kSwing; + real_t m_kTwist; - real_t m_accSwingLimitImpulse; - real_t m_accTwistLimitImpulse; + real_t m_twistLimitSign; + real_t m_swingCorrection; + real_t m_twistCorrection; - bool m_angularOnly; - bool m_solveTwistLimit; - bool m_solveSwingLimit; + real_t m_accSwingLimitImpulse; + real_t m_accTwistLimitImpulse; + bool m_angularOnly; + bool m_solveTwistLimit; + bool m_solveSwingLimit; public: - virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_CONE_TWIST; } virtual bool setup(real_t p_step); virtual void solve(real_t p_step); - ConeTwistJointSW(BodySW* rbA,BodySW* rbB,const Transform& rbAFrame, const Transform& rbBFrame); - + ConeTwistJointSW(BodySW *rbA, BodySW *rbB, const Transform &rbAFrame, const Transform &rbBFrame); - void setAngularOnly(bool angularOnly) - { + void setAngularOnly(bool angularOnly) { m_angularOnly = angularOnly; } - void setLimit(real_t _swingSpan1,real_t _swingSpan2,real_t _twistSpan, real_t _softness = 0.8f, real_t _biasFactor = 0.3f, real_t _relaxationFactor = 1.0f) - { + void setLimit(real_t _swingSpan1, real_t _swingSpan2, real_t _twistSpan, real_t _softness = 0.8f, real_t _biasFactor = 0.3f, real_t _relaxationFactor = 1.0f) { m_swingSpan1 = _swingSpan1; m_swingSpan2 = _swingSpan2; - m_twistSpan = _twistSpan; + m_twistSpan = _twistSpan; - m_limitSoftness = _softness; + m_limitSoftness = _softness; m_biasFactor = _biasFactor; m_relaxationFactor = _relaxationFactor; } - inline int getSolveTwistLimit() - { + inline int getSolveTwistLimit() { return m_solveTwistLimit; } - inline int getSolveSwingLimit() - { + inline int getSolveSwingLimit() { return m_solveTwistLimit; } - inline real_t getTwistLimitSign() - { + inline real_t getTwistLimitSign() { return m_twistLimitSign; } void set_param(PhysicsServer::ConeTwistJointParam p_param, real_t p_value); real_t get_param(PhysicsServer::ConeTwistJointParam p_param) const; - - }; - - #endif // CONE_TWIST_JOINT_SW_H diff --git a/servers/physics/joints/generic_6dof_joint_sw.cpp b/servers/physics/joints/generic_6dof_joint_sw.cpp index bd07f3122a..1e07bc73fb 100644 --- a/servers/physics/joints/generic_6dof_joint_sw.cpp +++ b/servers/physics/joints/generic_6dof_joint_sw.cpp @@ -34,118 +34,90 @@ See corresponding header file for licensing info. #include "generic_6dof_joint_sw.h" - - #define GENERIC_D6_DISABLE_WARMSTARTING 1 - //////////////////////////// G6DOFRotationalLimitMotorSW //////////////////////////////////// - -int G6DOFRotationalLimitMotorSW::testLimitValue(real_t test_value) -{ - if(m_loLimit>m_hiLimit) - { - m_currentLimit = 0;//Free from violation +int G6DOFRotationalLimitMotorSW::testLimitValue(real_t test_value) { + if (m_loLimit > m_hiLimit) { + m_currentLimit = 0; //Free from violation return 0; } - if (test_value < m_loLimit) - { - m_currentLimit = 1;//low limit violation - m_currentLimitError = test_value - m_loLimit; + if (test_value < m_loLimit) { + m_currentLimit = 1; //low limit violation + m_currentLimitError = test_value - m_loLimit; return 1; - } - else if (test_value> m_hiLimit) - { - m_currentLimit = 2;//High limit violation + } else if (test_value > m_hiLimit) { + m_currentLimit = 2; //High limit violation m_currentLimitError = test_value - m_hiLimit; return 2; }; - m_currentLimit = 0;//Free from violation + m_currentLimit = 0; //Free from violation return 0; - } - real_t G6DOFRotationalLimitMotorSW::solveAngularLimits( - real_t timeStep,Vector3& axis,real_t jacDiagABInv, - BodySW * body0, BodySW * body1) -{ - if (needApplyTorques()==false) return 0.0f; + real_t timeStep, Vector3 &axis, real_t jacDiagABInv, + BodySW *body0, BodySW *body1) { + if (needApplyTorques() == false) return 0.0f; - real_t target_velocity = m_targetVelocity; - real_t maxMotorForce = m_maxMotorForce; + real_t target_velocity = m_targetVelocity; + real_t maxMotorForce = m_maxMotorForce; //current error correction - if (m_currentLimit!=0) - { - target_velocity = -m_ERP*m_currentLimitError/(timeStep); - maxMotorForce = m_maxLimitForce; - } - - maxMotorForce *= timeStep; - - // current velocity difference - Vector3 vel_diff = body0->get_angular_velocity(); - if (body1) - { - vel_diff -= body1->get_angular_velocity(); - } + if (m_currentLimit != 0) { + target_velocity = -m_ERP * m_currentLimitError / (timeStep); + maxMotorForce = m_maxLimitForce; + } + maxMotorForce *= timeStep; + // current velocity difference + Vector3 vel_diff = body0->get_angular_velocity(); + if (body1) { + vel_diff -= body1->get_angular_velocity(); + } - real_t rel_vel = axis.dot(vel_diff); + real_t rel_vel = axis.dot(vel_diff); // correction velocity - real_t motor_relvel = m_limitSoftness*(target_velocity - m_damping*rel_vel); - - - if ( motor_relvel < CMP_EPSILON && motor_relvel > -CMP_EPSILON ) - { - return 0.0f;//no need for applying force - } + real_t motor_relvel = m_limitSoftness * (target_velocity - m_damping * rel_vel); + if (motor_relvel < CMP_EPSILON && motor_relvel > -CMP_EPSILON) { + return 0.0f; //no need for applying force + } // correction impulse - real_t unclippedMotorImpulse = (1+m_bounce)*motor_relvel*jacDiagABInv; + real_t unclippedMotorImpulse = (1 + m_bounce) * motor_relvel * jacDiagABInv; // clip correction impulse - real_t clippedMotorImpulse; - - ///@todo: should clip against accumulated impulse - if (unclippedMotorImpulse>0.0f) - { - clippedMotorImpulse = unclippedMotorImpulse > maxMotorForce? maxMotorForce: unclippedMotorImpulse; - } - else - { - clippedMotorImpulse = unclippedMotorImpulse < -maxMotorForce ? -maxMotorForce: unclippedMotorImpulse; - } + real_t clippedMotorImpulse; + ///@todo: should clip against accumulated impulse + if (unclippedMotorImpulse > 0.0f) { + clippedMotorImpulse = unclippedMotorImpulse > maxMotorForce ? maxMotorForce : unclippedMotorImpulse; + } else { + clippedMotorImpulse = unclippedMotorImpulse < -maxMotorForce ? -maxMotorForce : unclippedMotorImpulse; + } // sort with accumulated impulses - real_t lo = real_t(-1e30); - real_t hi = real_t(1e30); - - real_t oldaccumImpulse = m_accumulatedImpulse; - real_t sum = oldaccumImpulse + clippedMotorImpulse; - m_accumulatedImpulse = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum; - - clippedMotorImpulse = m_accumulatedImpulse - oldaccumImpulse; + real_t lo = real_t(-1e30); + real_t hi = real_t(1e30); + real_t oldaccumImpulse = m_accumulatedImpulse; + real_t sum = oldaccumImpulse + clippedMotorImpulse; + m_accumulatedImpulse = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum; + clippedMotorImpulse = m_accumulatedImpulse - oldaccumImpulse; - Vector3 motorImp = clippedMotorImpulse * axis; - - - body0->apply_torque_impulse(motorImp); - if (body1) body1->apply_torque_impulse(-motorImp); - - return clippedMotorImpulse; + Vector3 motorImp = clippedMotorImpulse * axis; + body0->apply_torque_impulse(motorImp); + if (body1) body1->apply_torque_impulse(-motorImp); + return clippedMotorImpulse; } //////////////////////////// End G6DOFRotationalLimitMotorSW //////////////////////////////////// @@ -153,120 +125,96 @@ real_t G6DOFRotationalLimitMotorSW::solveAngularLimits( //////////////////////////// G6DOFTranslationalLimitMotorSW //////////////////////////////////// real_t G6DOFTranslationalLimitMotorSW::solveLinearAxis( real_t timeStep, - real_t jacDiagABInv, - BodySW* body1,const Vector3 &pointInA, - BodySW* body2,const Vector3 &pointInB, - int limit_index, - const Vector3 & axis_normal_on_a, - const Vector3 & anchorPos) -{ - -///find relative velocity -// Vector3 rel_pos1 = pointInA - body1->get_transform().origin; -// Vector3 rel_pos2 = pointInB - body2->get_transform().origin; - Vector3 rel_pos1 = anchorPos - body1->get_transform().origin; - Vector3 rel_pos2 = anchorPos - body2->get_transform().origin; + real_t jacDiagABInv, + BodySW *body1, const Vector3 &pointInA, + BodySW *body2, const Vector3 &pointInB, + int limit_index, + const Vector3 &axis_normal_on_a, + const Vector3 &anchorPos) { - Vector3 vel1 = body1->get_velocity_in_local_point(rel_pos1); - Vector3 vel2 = body2->get_velocity_in_local_point(rel_pos2); - Vector3 vel = vel1 - vel2; + ///find relative velocity + // Vector3 rel_pos1 = pointInA - body1->get_transform().origin; + // Vector3 rel_pos2 = pointInB - body2->get_transform().origin; + Vector3 rel_pos1 = anchorPos - body1->get_transform().origin; + Vector3 rel_pos2 = anchorPos - body2->get_transform().origin; - real_t rel_vel = axis_normal_on_a.dot(vel); + Vector3 vel1 = body1->get_velocity_in_local_point(rel_pos1); + Vector3 vel2 = body2->get_velocity_in_local_point(rel_pos2); + Vector3 vel = vel1 - vel2; + real_t rel_vel = axis_normal_on_a.dot(vel); + /// apply displacement correction -/// apply displacement correction + //positional error (zeroth order error) + real_t depth = -(pointInA - pointInB).dot(axis_normal_on_a); + real_t lo = real_t(-1e30); + real_t hi = real_t(1e30); -//positional error (zeroth order error) - real_t depth = -(pointInA - pointInB).dot(axis_normal_on_a); - real_t lo = real_t(-1e30); - real_t hi = real_t(1e30); + real_t minLimit = m_lowerLimit[limit_index]; + real_t maxLimit = m_upperLimit[limit_index]; - real_t minLimit = m_lowerLimit[limit_index]; - real_t maxLimit = m_upperLimit[limit_index]; - - //handle the limits - if (minLimit < maxLimit) - { - { - if (depth > maxLimit) - { - depth -= maxLimit; - lo = real_t(0.); - - } - else - { - if (depth < minLimit) - { - depth -= minLimit; - hi = real_t(0.); - } - else + //handle the limits + if (minLimit < maxLimit) { { - return 0.0f; + if (depth > maxLimit) { + depth -= maxLimit; + lo = real_t(0.); + + } else { + if (depth < minLimit) { + depth -= minLimit; + hi = real_t(0.); + } else { + return 0.0f; + } + } } - } } - } - real_t normalImpulse= m_limitSoftness[limit_index]*(m_restitution[limit_index]*depth/timeStep - m_damping[limit_index]*rel_vel) * jacDiagABInv; + real_t normalImpulse = m_limitSoftness[limit_index] * (m_restitution[limit_index] * depth / timeStep - m_damping[limit_index] * rel_vel) * jacDiagABInv; + real_t oldNormalImpulse = m_accumulatedImpulse[limit_index]; + real_t sum = oldNormalImpulse + normalImpulse; + m_accumulatedImpulse[limit_index] = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum; + normalImpulse = m_accumulatedImpulse[limit_index] - oldNormalImpulse; - - - real_t oldNormalImpulse = m_accumulatedImpulse[limit_index]; - real_t sum = oldNormalImpulse + normalImpulse; - m_accumulatedImpulse[limit_index] = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum; - normalImpulse = m_accumulatedImpulse[limit_index] - oldNormalImpulse; - - Vector3 impulse_vector = axis_normal_on_a * normalImpulse; - body1->apply_impulse( rel_pos1, impulse_vector); - body2->apply_impulse( rel_pos2, -impulse_vector); - return normalImpulse; + Vector3 impulse_vector = axis_normal_on_a * normalImpulse; + body1->apply_impulse(rel_pos1, impulse_vector); + body2->apply_impulse(rel_pos2, -impulse_vector); + return normalImpulse; } //////////////////////////// G6DOFTranslationalLimitMotorSW //////////////////////////////////// - -Generic6DOFJointSW::Generic6DOFJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB, bool useLinearReferenceFrameA) - : JointSW(_arr,2) - , m_frameInA(frameInA) - , m_frameInB(frameInB), - m_useLinearReferenceFrameA(useLinearReferenceFrameA) -{ - A=rbA; - B=rbB; - A->add_constraint(this,0); - B->add_constraint(this,1); +Generic6DOFJointSW::Generic6DOFJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB, bool useLinearReferenceFrameA) + : JointSW(_arr, 2), m_frameInA(frameInA), m_frameInB(frameInB), + m_useLinearReferenceFrameA(useLinearReferenceFrameA) { + A = rbA; + B = rbB; + A->add_constraint(this, 0); + B->add_constraint(this, 1); } - - - - -void Generic6DOFJointSW::calculateAngleInfo() -{ - Basis relative_frame = m_calculatedTransformA.basis.inverse()*m_calculatedTransformB.basis; +void Generic6DOFJointSW::calculateAngleInfo() { + Basis relative_frame = m_calculatedTransformA.basis.inverse() * m_calculatedTransformB.basis; m_calculatedAxisAngleDiff = relative_frame.get_euler(); - - // in euler angle mode we do not actually constrain the angular velocity - // along the axes axis[0] and axis[2] (although we do use axis[1]) : - // - // to get constrain w2-w1 along ...not - // ------ --------------------- ------ - // d(angle[0])/dt = 0 ax[1] x ax[2] ax[0] - // d(angle[1])/dt = 0 ax[1] - // d(angle[2])/dt = 0 ax[0] x ax[1] ax[2] - // - // constraining w2-w1 along an axis 'a' means that a'*(w2-w1)=0. - // to prove the result for angle[0], write the expression for angle[0] from - // GetInfo1 then take the derivative. to prove this for angle[2] it is - // easier to take the euler rate expression for d(angle[2])/dt with respect - // to the components of w and set that to 0. + // along the axes axis[0] and axis[2] (although we do use axis[1]) : + // + // to get constrain w2-w1 along ...not + // ------ --------------------- ------ + // d(angle[0])/dt = 0 ax[1] x ax[2] ax[0] + // d(angle[1])/dt = 0 ax[1] + // d(angle[2])/dt = 0 ax[0] x ax[1] ax[2] + // + // constraining w2-w1 along an axis 'a' means that a'*(w2-w1)=0. + // to prove the result for angle[0], write the expression for angle[0] from + // GetInfo1 then take the derivative. to prove this for angle[2] it is + // easier to take the euler rate expression for d(angle[2])/dt with respect + // to the components of w and set that to 0. Vector3 axis0 = m_calculatedTransformB.basis.get_axis(0); Vector3 axis2 = m_calculatedTransformA.basis.get_axis(2); @@ -275,7 +223,6 @@ void Generic6DOFJointSW::calculateAngleInfo() m_calculatedAxis[0] = m_calculatedAxis[1].cross(axis2); m_calculatedAxis[2] = axis0.cross(m_calculatedAxis[1]); - /* if(m_debugDrawer) { @@ -288,280 +235,250 @@ void Generic6DOFJointSW::calculateAngleInfo() m_debugDrawer->reportErrorWarning(buff); } */ - } -void Generic6DOFJointSW::calculateTransforms() -{ - m_calculatedTransformA = A->get_transform() * m_frameInA; - m_calculatedTransformB = B->get_transform() * m_frameInB; +void Generic6DOFJointSW::calculateTransforms() { + m_calculatedTransformA = A->get_transform() * m_frameInA; + m_calculatedTransformB = B->get_transform() * m_frameInB; - calculateAngleInfo(); + calculateAngleInfo(); } - void Generic6DOFJointSW::buildLinearJacobian( - JacobianEntrySW & jacLinear,const Vector3 & normalWorld, - const Vector3 & pivotAInW,const Vector3 & pivotBInW) -{ - memnew_placement(&jacLinear, JacobianEntrySW( - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - pivotAInW - A->get_transform().origin - A->get_center_of_mass(), - pivotBInW - B->get_transform().origin - B->get_center_of_mass(), - normalWorld, - A->get_inv_inertia(), - A->get_inv_mass(), - B->get_inv_inertia(), - B->get_inv_mass())); - + JacobianEntrySW &jacLinear, const Vector3 &normalWorld, + const Vector3 &pivotAInW, const Vector3 &pivotBInW) { + memnew_placement(&jacLinear, JacobianEntrySW( + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + pivotAInW - A->get_transform().origin - A->get_center_of_mass(), + pivotBInW - B->get_transform().origin - B->get_center_of_mass(), + normalWorld, + A->get_inv_inertia(), + A->get_inv_mass(), + B->get_inv_inertia(), + B->get_inv_mass())); } void Generic6DOFJointSW::buildAngularJacobian( - JacobianEntrySW & jacAngular,const Vector3 & jointAxisW) -{ - memnew_placement(&jacAngular, JacobianEntrySW(jointAxisW, - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - A->get_inv_inertia(), - B->get_inv_inertia())); - + JacobianEntrySW &jacAngular, const Vector3 &jointAxisW) { + memnew_placement(&jacAngular, JacobianEntrySW(jointAxisW, + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + A->get_inv_inertia(), + B->get_inv_inertia())); } -bool Generic6DOFJointSW::testAngularLimitMotor(int axis_index) -{ - real_t angle = m_calculatedAxisAngleDiff[axis_index]; +bool Generic6DOFJointSW::testAngularLimitMotor(int axis_index) { + real_t angle = m_calculatedAxisAngleDiff[axis_index]; - //test limits - m_angularLimits[axis_index].testLimitValue(angle); - return m_angularLimits[axis_index].needApplyTorques(); + //test limits + m_angularLimits[axis_index].testLimitValue(angle); + return m_angularLimits[axis_index].needApplyTorques(); } bool Generic6DOFJointSW::setup(real_t p_step) { // Clear accumulated impulses for the next simulation step - m_linearLimits.m_accumulatedImpulse=Vector3(real_t(0.), real_t(0.), real_t(0.)); - int i; - for(i = 0; i < 3; i++) - { - m_angularLimits[i].m_accumulatedImpulse = real_t(0.); - } - //calculates transform - calculateTransforms(); - -// const Vector3& pivotAInW = m_calculatedTransformA.origin; -// const Vector3& pivotBInW = m_calculatedTransformB.origin; + m_linearLimits.m_accumulatedImpulse = Vector3(real_t(0.), real_t(0.), real_t(0.)); + int i; + for (i = 0; i < 3; i++) { + m_angularLimits[i].m_accumulatedImpulse = real_t(0.); + } + //calculates transform + calculateTransforms(); + + // const Vector3& pivotAInW = m_calculatedTransformA.origin; + // const Vector3& pivotBInW = m_calculatedTransformB.origin; calcAnchorPos(); Vector3 pivotAInW = m_AnchorPos; Vector3 pivotBInW = m_AnchorPos; -// not used here -// Vector3 rel_pos1 = pivotAInW - A->get_transform().origin; -// Vector3 rel_pos2 = pivotBInW - B->get_transform().origin; + // not used here + // Vector3 rel_pos1 = pivotAInW - A->get_transform().origin; + // Vector3 rel_pos2 = pivotBInW - B->get_transform().origin; - Vector3 normalWorld; - //linear part - for (i=0;i<3;i++) - { - if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i)) - { + Vector3 normalWorld; + //linear part + for (i = 0; i < 3; i++) { + if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i)) { if (m_useLinearReferenceFrameA) - normalWorld = m_calculatedTransformA.basis.get_axis(i); + normalWorld = m_calculatedTransformA.basis.get_axis(i); else - normalWorld = m_calculatedTransformB.basis.get_axis(i); - - buildLinearJacobian( - m_jacLinear[i],normalWorld , - pivotAInW,pivotBInW); + normalWorld = m_calculatedTransformB.basis.get_axis(i); + buildLinearJacobian( + m_jacLinear[i], normalWorld, + pivotAInW, pivotBInW); + } } - } - // angular part - for (i=0;i<3;i++) - { - //calculates error angle - if (m_angularLimits[i].m_enableLimit && testAngularLimitMotor(i)) - { - normalWorld = this->getAxis(i); - // Create angular atom - buildAngularJacobian(m_jacAng[i],normalWorld); + // angular part + for (i = 0; i < 3; i++) { + //calculates error angle + if (m_angularLimits[i].m_enableLimit && testAngularLimitMotor(i)) { + normalWorld = this->getAxis(i); + // Create angular atom + buildAngularJacobian(m_jacAng[i], normalWorld); + } } - } return true; } +void Generic6DOFJointSW::solve(real_t timeStep) { + m_timeStep = timeStep; -void Generic6DOFJointSW::solve(real_t timeStep) -{ - m_timeStep = timeStep; - - //calculateTransforms(); + //calculateTransforms(); - int i; + int i; - // linear + // linear - Vector3 pointInA = m_calculatedTransformA.origin; + Vector3 pointInA = m_calculatedTransformA.origin; Vector3 pointInB = m_calculatedTransformB.origin; real_t jacDiagABInv; Vector3 linear_axis; - for (i=0;i<3;i++) - { - if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i)) - { - jacDiagABInv = real_t(1.) / m_jacLinear[i].getDiagonal(); + for (i = 0; i < 3; i++) { + if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i)) { + jacDiagABInv = real_t(1.) / m_jacLinear[i].getDiagonal(); if (m_useLinearReferenceFrameA) - linear_axis = m_calculatedTransformA.basis.get_axis(i); + linear_axis = m_calculatedTransformA.basis.get_axis(i); else - linear_axis = m_calculatedTransformB.basis.get_axis(i); - - m_linearLimits.solveLinearAxis( - m_timeStep, - jacDiagABInv, - A,pointInA, - B,pointInB, - i,linear_axis, m_AnchorPos); - + linear_axis = m_calculatedTransformB.basis.get_axis(i); + + m_linearLimits.solveLinearAxis( + m_timeStep, + jacDiagABInv, + A, pointInA, + B, pointInB, + i, linear_axis, m_AnchorPos); + } } - } - - // angular - Vector3 angular_axis; - real_t angularJacDiagABInv; - for (i=0;i<3;i++) - { - if (m_angularLimits[i].m_enableLimit && m_angularLimits[i].needApplyTorques()) - { + + // angular + Vector3 angular_axis; + real_t angularJacDiagABInv; + for (i = 0; i < 3; i++) { + if (m_angularLimits[i].m_enableLimit && m_angularLimits[i].needApplyTorques()) { // get axis angular_axis = getAxis(i); angularJacDiagABInv = real_t(1.) / m_jacAng[i].getDiagonal(); - m_angularLimits[i].solveAngularLimits(m_timeStep,angular_axis,angularJacDiagABInv, A,B); + m_angularLimits[i].solveAngularLimits(m_timeStep, angular_axis, angularJacDiagABInv, A, B); + } } - } } -void Generic6DOFJointSW::updateRHS(real_t timeStep) -{ - (void)timeStep; - +void Generic6DOFJointSW::updateRHS(real_t timeStep) { + (void)timeStep; } -Vector3 Generic6DOFJointSW::getAxis(int axis_index) const -{ - return m_calculatedAxis[axis_index]; +Vector3 Generic6DOFJointSW::getAxis(int axis_index) const { + return m_calculatedAxis[axis_index]; } -real_t Generic6DOFJointSW::getAngle(int axis_index) const -{ - return m_calculatedAxisAngleDiff[axis_index]; +real_t Generic6DOFJointSW::getAngle(int axis_index) const { + return m_calculatedAxisAngleDiff[axis_index]; } -void Generic6DOFJointSW::calcAnchorPos(void) -{ +void Generic6DOFJointSW::calcAnchorPos(void) { real_t imA = A->get_inv_mass(); real_t imB = B->get_inv_mass(); real_t weight; - if(imB == real_t(0.0)) - { + if (imB == real_t(0.0)) { weight = real_t(1.0); - } - else - { + } else { weight = imA / (imA + imB); } - const Vector3& pA = m_calculatedTransformA.origin; - const Vector3& pB = m_calculatedTransformB.origin; + const Vector3 &pA = m_calculatedTransformA.origin; + const Vector3 &pB = m_calculatedTransformB.origin; m_AnchorPos = pA * weight + pB * (real_t(1.0) - weight); return; } // Generic6DOFJointSW::calcAnchorPos() +void Generic6DOFJointSW::set_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value) { -void Generic6DOFJointSW::set_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value) { - - ERR_FAIL_INDEX(p_axis,3); - switch(p_param) { + ERR_FAIL_INDEX(p_axis, 3); + switch (p_param) { case PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT: { - m_linearLimits.m_lowerLimit[p_axis]=p_value; + m_linearLimits.m_lowerLimit[p_axis] = p_value; } break; case PhysicsServer::G6DOF_JOINT_LINEAR_UPPER_LIMIT: { - m_linearLimits.m_upperLimit[p_axis]=p_value; + m_linearLimits.m_upperLimit[p_axis] = p_value; } break; case PhysicsServer::G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS: { - m_linearLimits.m_limitSoftness[p_axis]=p_value; + m_linearLimits.m_limitSoftness[p_axis] = p_value; } break; case PhysicsServer::G6DOF_JOINT_LINEAR_RESTITUTION: { - m_linearLimits.m_restitution[p_axis]=p_value; + m_linearLimits.m_restitution[p_axis] = p_value; } break; case PhysicsServer::G6DOF_JOINT_LINEAR_DAMPING: { - m_linearLimits.m_damping[p_axis]=p_value; + m_linearLimits.m_damping[p_axis] = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_LOWER_LIMIT: { - m_angularLimits[p_axis].m_loLimit=p_value; + m_angularLimits[p_axis].m_loLimit = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_UPPER_LIMIT: { - m_angularLimits[p_axis].m_hiLimit=p_value; + m_angularLimits[p_axis].m_hiLimit = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS: { - m_angularLimits[p_axis].m_limitSoftness=p_value; + m_angularLimits[p_axis].m_limitSoftness = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_DAMPING: { - m_angularLimits[p_axis].m_damping=p_value; + m_angularLimits[p_axis].m_damping = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_RESTITUTION: { - m_angularLimits[p_axis].m_bounce=p_value; + m_angularLimits[p_axis].m_bounce = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_FORCE_LIMIT: { - m_angularLimits[p_axis].m_maxLimitForce=p_value; + m_angularLimits[p_axis].m_maxLimitForce = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_ERP: { - m_angularLimits[p_axis].m_ERP=p_value; + m_angularLimits[p_axis].m_ERP = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY: { - m_angularLimits[p_axis].m_targetVelocity=p_value; + m_angularLimits[p_axis].m_targetVelocity = p_value; } break; case PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT: { - m_angularLimits[p_axis].m_maxLimitForce=p_value; + m_angularLimits[p_axis].m_maxLimitForce = p_value; } break; } } -real_t Generic6DOFJointSW::get_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param) const{ - ERR_FAIL_INDEX_V(p_axis,3,0); - switch(p_param) { +real_t Generic6DOFJointSW::get_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param) const { + ERR_FAIL_INDEX_V(p_axis, 3, 0); + switch (p_param) { case PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT: { return m_linearLimits.m_lowerLimit[p_axis]; @@ -635,31 +552,29 @@ real_t Generic6DOFJointSW::get_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJo return 0; } -void Generic6DOFJointSW::set_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value){ +void Generic6DOFJointSW::set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value) { - ERR_FAIL_INDEX(p_axis,3); + ERR_FAIL_INDEX(p_axis, 3); - switch(p_flag) { + switch (p_flag) { case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT: { - m_linearLimits.enable_limit[p_axis]=p_value; + m_linearLimits.enable_limit[p_axis] = p_value; } break; case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT: { - m_angularLimits[p_axis].m_enableLimit=p_value; + m_angularLimits[p_axis].m_enableLimit = p_value; } break; case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_MOTOR: { - m_angularLimits[p_axis].m_enableMotor=p_value; + m_angularLimits[p_axis].m_enableMotor = p_value; } break; } - - } -bool Generic6DOFJointSW::get_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag) const{ +bool Generic6DOFJointSW::get_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag) const { - ERR_FAIL_INDEX_V(p_axis,3,0); - switch(p_flag) { + ERR_FAIL_INDEX_V(p_axis, 3, 0); + switch (p_flag) { case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT: { return m_linearLimits.enable_limit[p_axis]; diff --git a/servers/physics/joints/generic_6dof_joint_sw.h b/servers/physics/joints/generic_6dof_joint_sw.h index 207ae85a45..87245c6ffe 100644 --- a/servers/physics/joints/generic_6dof_joint_sw.h +++ b/servers/physics/joints/generic_6dof_joint_sw.h @@ -34,9 +34,8 @@ Adapted to Godot from the Bullet library. #ifndef GENERIC_6DOF_JOINT_SW_H #define GENERIC_6DOF_JOINT_SW_H -#include "servers/physics/joints_sw.h" #include "servers/physics/joints/jacobian_entry_sw.h" - +#include "servers/physics/joints_sw.h" /* Bullet Continuous Collision Detection and Physics Library @@ -53,7 +52,6 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ - /* 2007-09-09 Generic6DOFJointSW Refactored by Francisco Le?n @@ -61,80 +59,73 @@ email: projectileman@yahoo.com http://gimpact.sf.net */ - //! Rotation Limit structure for generic joints class G6DOFRotationalLimitMotorSW { public: - //! limit_parameters - //!@{ - real_t m_loLimit;//!< joint limit - real_t m_hiLimit;//!< joint limit - real_t m_targetVelocity;//!< target motor velocity - real_t m_maxMotorForce;//!< max force on motor - real_t m_maxLimitForce;//!< max force on limit - real_t m_damping;//!< Damping. - real_t m_limitSoftness;//! Relaxation factor - real_t m_ERP;//!< Error tolerance factor when joint is at limit - real_t m_bounce;//!< restitution factor - bool m_enableMotor; - bool m_enableLimit; - - //!@} - - //! temp_variables - //!@{ - real_t m_currentLimitError;//! How much is violated this limit - int m_currentLimit;//!< 0=free, 1=at lo limit, 2=at hi limit - real_t m_accumulatedImpulse; - //!@} - - G6DOFRotationalLimitMotorSW() - { - m_accumulatedImpulse = 0.f; - m_targetVelocity = 0; - m_maxMotorForce = 0.1f; - m_maxLimitForce = 300.0f; - m_loLimit = -1e30; - m_hiLimit = 1e30; - m_ERP = 0.5f; - m_bounce = 0.0f; - m_damping = 1.0f; - m_limitSoftness = 0.5f; - m_currentLimit = 0; - m_currentLimitError = 0; - m_enableMotor = false; - m_enableLimit=false; - } - - G6DOFRotationalLimitMotorSW(const G6DOFRotationalLimitMotorSW & limot) - { - m_targetVelocity = limot.m_targetVelocity; - m_maxMotorForce = limot.m_maxMotorForce; - m_limitSoftness = limot.m_limitSoftness; - m_loLimit = limot.m_loLimit; - m_hiLimit = limot.m_hiLimit; - m_ERP = limot.m_ERP; - m_bounce = limot.m_bounce; - m_currentLimit = limot.m_currentLimit; - m_currentLimitError = limot.m_currentLimitError; - m_enableMotor = limot.m_enableMotor; - } + //! limit_parameters + //!@{ + real_t m_loLimit; //!< joint limit + real_t m_hiLimit; //!< joint limit + real_t m_targetVelocity; //!< target motor velocity + real_t m_maxMotorForce; //!< max force on motor + real_t m_maxLimitForce; //!< max force on limit + real_t m_damping; //!< Damping. + real_t m_limitSoftness; //! Relaxation factor + real_t m_ERP; //!< Error tolerance factor when joint is at limit + real_t m_bounce; //!< restitution factor + bool m_enableMotor; + bool m_enableLimit; + + //!@} + + //! temp_variables + //!@{ + real_t m_currentLimitError; //! How much is violated this limit + int m_currentLimit; //!< 0=free, 1=at lo limit, 2=at hi limit + real_t m_accumulatedImpulse; + //!@} + G6DOFRotationalLimitMotorSW() { + m_accumulatedImpulse = 0.f; + m_targetVelocity = 0; + m_maxMotorForce = 0.1f; + m_maxLimitForce = 300.0f; + m_loLimit = -1e30; + m_hiLimit = 1e30; + m_ERP = 0.5f; + m_bounce = 0.0f; + m_damping = 1.0f; + m_limitSoftness = 0.5f; + m_currentLimit = 0; + m_currentLimitError = 0; + m_enableMotor = false; + m_enableLimit = false; + } + G6DOFRotationalLimitMotorSW(const G6DOFRotationalLimitMotorSW &limot) { + m_targetVelocity = limot.m_targetVelocity; + m_maxMotorForce = limot.m_maxMotorForce; + m_limitSoftness = limot.m_limitSoftness; + m_loLimit = limot.m_loLimit; + m_hiLimit = limot.m_hiLimit; + m_ERP = limot.m_ERP; + m_bounce = limot.m_bounce; + m_currentLimit = limot.m_currentLimit; + m_currentLimitError = limot.m_currentLimitError; + m_enableMotor = limot.m_enableMotor; + } //! Is limited - bool isLimited() - { - if(m_loLimit>=m_hiLimit) return false; - return true; - } + bool isLimited() { + if (m_loLimit >= m_hiLimit) return false; + return true; + } //! Need apply correction - bool needApplyTorques() - { - if(m_currentLimit == 0 && m_enableMotor == false) return false; - return true; - } + bool needApplyTorques() { + if (m_currentLimit == 0 && m_enableMotor == false) return false; + return true; + } //! calculates error /*! @@ -143,84 +134,69 @@ public: int testLimitValue(real_t test_value); //! apply the correction impulses for two bodies - real_t solveAngularLimits(real_t timeStep,Vector3& axis, real_t jacDiagABInv,BodySW * body0, BodySW * body1); + real_t solveAngularLimits(real_t timeStep, Vector3 &axis, real_t jacDiagABInv, BodySW *body0, BodySW *body1); +}; +class G6DOFTranslationalLimitMotorSW { +public: + Vector3 m_lowerLimit; //!< the constraint lower limits + Vector3 m_upperLimit; //!< the constraint upper limits + Vector3 m_accumulatedImpulse; + //! Linear_Limit_parameters + //!@{ + Vector3 m_limitSoftness; //!< Softness for linear limit + Vector3 m_damping; //!< Damping for linear limit + Vector3 m_restitution; //! Bounce parameter for linear limit + //!@} + bool enable_limit[3]; -}; + G6DOFTranslationalLimitMotorSW() { + m_lowerLimit = Vector3(0.f, 0.f, 0.f); + m_upperLimit = Vector3(0.f, 0.f, 0.f); + m_accumulatedImpulse = Vector3(0.f, 0.f, 0.f); + m_limitSoftness = Vector3(1, 1, 1) * 0.7f; + m_damping = Vector3(1, 1, 1) * real_t(1.0f); + m_restitution = Vector3(1, 1, 1) * real_t(0.5f); + enable_limit[0] = true; + enable_limit[1] = true; + enable_limit[2] = true; + } -class G6DOFTranslationalLimitMotorSW -{ -public: - Vector3 m_lowerLimit;//!< the constraint lower limits - Vector3 m_upperLimit;//!< the constraint upper limits - Vector3 m_accumulatedImpulse; - //! Linear_Limit_parameters - //!@{ - Vector3 m_limitSoftness;//!< Softness for linear limit - Vector3 m_damping;//!< Damping for linear limit - Vector3 m_restitution;//! Bounce parameter for linear limit - //!@} - bool enable_limit[3]; - - G6DOFTranslationalLimitMotorSW() - { - m_lowerLimit=Vector3(0.f,0.f,0.f); - m_upperLimit=Vector3(0.f,0.f,0.f); - m_accumulatedImpulse=Vector3(0.f,0.f,0.f); - - m_limitSoftness = Vector3(1,1,1)*0.7f; - m_damping = Vector3(1,1,1)*real_t(1.0f); - m_restitution = Vector3(1,1,1)*real_t(0.5f); - - enable_limit[0]=true; - enable_limit[1]=true; - enable_limit[2]=true; - } - - G6DOFTranslationalLimitMotorSW(const G6DOFTranslationalLimitMotorSW & other ) - { - m_lowerLimit = other.m_lowerLimit; - m_upperLimit = other.m_upperLimit; - m_accumulatedImpulse = other.m_accumulatedImpulse; - - m_limitSoftness = other.m_limitSoftness ; - m_damping = other.m_damping; - m_restitution = other.m_restitution; - } - - //! Test limit + G6DOFTranslationalLimitMotorSW(const G6DOFTranslationalLimitMotorSW &other) { + m_lowerLimit = other.m_lowerLimit; + m_upperLimit = other.m_upperLimit; + m_accumulatedImpulse = other.m_accumulatedImpulse; + + m_limitSoftness = other.m_limitSoftness; + m_damping = other.m_damping; + m_restitution = other.m_restitution; + } + + //! Test limit /*! - free means upper < lower, - locked means upper == lower - limited means upper > lower - limitIndex: first 3 are linear, next 3 are angular */ - inline bool isLimited(int limitIndex) - { - return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]); - } - - - real_t solveLinearAxis( - real_t timeStep, - real_t jacDiagABInv, - BodySW* body1,const Vector3 &pointInA, - BodySW* body2,const Vector3 &pointInB, - int limit_index, - const Vector3 & axis_normal_on_a, - const Vector3 & anchorPos); - + inline bool isLimited(int limitIndex) { + return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]); + } + real_t solveLinearAxis( + real_t timeStep, + real_t jacDiagABInv, + BodySW *body1, const Vector3 &pointInA, + BodySW *body2, const Vector3 &pointInB, + int limit_index, + const Vector3 &axis_normal_on_a, + const Vector3 &anchorPos); }; - -class Generic6DOFJointSW : public JointSW -{ +class Generic6DOFJointSW : public JointSW { protected: - - union { struct { BodySW *A; @@ -231,195 +207,167 @@ protected: }; //! relative_frames - //!@{ - Transform m_frameInA;//!< the constraint space w.r.t body A - Transform m_frameInB;//!< the constraint space w.r.t body B - //!@} + //!@{ + Transform m_frameInA; //!< the constraint space w.r.t body A + Transform m_frameInB; //!< the constraint space w.r.t body B + //!@} - //! Jacobians - //!@{ - JacobianEntrySW m_jacLinear[3];//!< 3 orthogonal linear constraints - JacobianEntrySW m_jacAng[3];//!< 3 orthogonal angular constraints - //!@} + //! Jacobians + //!@{ + JacobianEntrySW m_jacLinear[3]; //!< 3 orthogonal linear constraints + JacobianEntrySW m_jacAng[3]; //!< 3 orthogonal angular constraints + //!@} //! Linear_Limit_parameters - //!@{ - G6DOFTranslationalLimitMotorSW m_linearLimits; - //!@} - - - //! hinge_parameters - //!@{ - G6DOFRotationalLimitMotorSW m_angularLimits[3]; + //!@{ + G6DOFTranslationalLimitMotorSW m_linearLimits; //!@} + //! hinge_parameters + //!@{ + G6DOFRotationalLimitMotorSW m_angularLimits[3]; + //!@} protected: - //! temporal variables - //!@{ - real_t m_timeStep; - Transform m_calculatedTransformA; - Transform m_calculatedTransformB; - Vector3 m_calculatedAxisAngleDiff; - Vector3 m_calculatedAxis[3]; + //! temporal variables + //!@{ + real_t m_timeStep; + Transform m_calculatedTransformA; + Transform m_calculatedTransformB; + Vector3 m_calculatedAxisAngleDiff; + Vector3 m_calculatedAxis[3]; Vector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes - bool m_useLinearReferenceFrameA; - - //!@} - - Generic6DOFJointSW& operator=(Generic6DOFJointSW& other) - { - ERR_PRINT("pito"); - (void) other; - return *this; - } - + bool m_useLinearReferenceFrameA; + //!@} - void buildLinearJacobian( - JacobianEntrySW & jacLinear,const Vector3 & normalWorld, - const Vector3 & pivotAInW,const Vector3 & pivotBInW); + Generic6DOFJointSW &operator=(Generic6DOFJointSW &other) { + ERR_PRINT("pito"); + (void)other; + return *this; + } - void buildAngularJacobian(JacobianEntrySW & jacAngular,const Vector3 & jointAxisW); + void buildLinearJacobian( + JacobianEntrySW &jacLinear, const Vector3 &normalWorld, + const Vector3 &pivotAInW, const Vector3 &pivotBInW); + void buildAngularJacobian(JacobianEntrySW &jacAngular, const Vector3 &jointAxisW); //! calcs the euler angles between the two bodies. - void calculateAngleInfo(); - - + void calculateAngleInfo(); public: - Generic6DOFJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB ,bool useLinearReferenceFrameA); + Generic6DOFJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB, bool useLinearReferenceFrameA); - virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_6DOF; } - - virtual bool setup(real_t p_step); - virtual void solve(real_t p_step); + virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_6DOF; } + virtual bool setup(real_t p_step); + virtual void solve(real_t p_step); //! Calcs global transform of the offsets /*! Calcs the global transform for the joint offset for body A an B, and also calcs the agle differences between the bodies. \sa Generic6DOFJointSW.getCalculatedTransformA , Generic6DOFJointSW.getCalculatedTransformB, Generic6DOFJointSW.calculateAngleInfo */ - void calculateTransforms(); + void calculateTransforms(); //! Gets the global transform of the offset for body A - /*! + /*! \sa Generic6DOFJointSW.getFrameOffsetA, Generic6DOFJointSW.getFrameOffsetB, Generic6DOFJointSW.calculateAngleInfo. */ - const Transform & getCalculatedTransformA() const - { - return m_calculatedTransformA; - } + const Transform &getCalculatedTransformA() const { + return m_calculatedTransformA; + } - //! Gets the global transform of the offset for body B - /*! + //! Gets the global transform of the offset for body B + /*! \sa Generic6DOFJointSW.getFrameOffsetA, Generic6DOFJointSW.getFrameOffsetB, Generic6DOFJointSW.calculateAngleInfo. */ - const Transform & getCalculatedTransformB() const - { - return m_calculatedTransformB; - } - - const Transform & getFrameOffsetA() const - { - return m_frameInA; - } - - const Transform & getFrameOffsetB() const - { - return m_frameInB; - } + const Transform &getCalculatedTransformB() const { + return m_calculatedTransformB; + } + const Transform &getFrameOffsetA() const { + return m_frameInA; + } - Transform & getFrameOffsetA() - { - return m_frameInA; - } + const Transform &getFrameOffsetB() const { + return m_frameInB; + } - Transform & getFrameOffsetB() - { - return m_frameInB; - } + Transform &getFrameOffsetA() { + return m_frameInA; + } + Transform &getFrameOffsetB() { + return m_frameInB; + } //! performs Jacobian calculation, and also calculates angle differences and axis - - void updateRHS(real_t timeStep); + void updateRHS(real_t timeStep); //! Get the rotation axis in global coordinates /*! \pre Generic6DOFJointSW.buildJacobian must be called previously. */ - Vector3 getAxis(int axis_index) const; + Vector3 getAxis(int axis_index) const; - //! Get the relative Euler angle - /*! + //! Get the relative Euler angle + /*! \pre Generic6DOFJointSW.buildJacobian must be called previously. */ - real_t getAngle(int axis_index) const; + real_t getAngle(int axis_index) const; //! Test angular limit. /*! Calculates angular correction and returns true if limit needs to be corrected. \pre Generic6DOFJointSW.buildJacobian must be called previously. */ - bool testAngularLimitMotor(int axis_index); - - void setLinearLowerLimit(const Vector3& linearLower) - { - m_linearLimits.m_lowerLimit = linearLower; - } - - void setLinearUpperLimit(const Vector3& linearUpper) - { - m_linearLimits.m_upperLimit = linearUpper; - } - - void setAngularLowerLimit(const Vector3& angularLower) - { - m_angularLimits[0].m_loLimit = angularLower.x; - m_angularLimits[1].m_loLimit = angularLower.y; - m_angularLimits[2].m_loLimit = angularLower.z; - } - - void setAngularUpperLimit(const Vector3& angularUpper) - { - m_angularLimits[0].m_hiLimit = angularUpper.x; - m_angularLimits[1].m_hiLimit = angularUpper.y; - m_angularLimits[2].m_hiLimit = angularUpper.z; - } + bool testAngularLimitMotor(int axis_index); + + void setLinearLowerLimit(const Vector3 &linearLower) { + m_linearLimits.m_lowerLimit = linearLower; + } + + void setLinearUpperLimit(const Vector3 &linearUpper) { + m_linearLimits.m_upperLimit = linearUpper; + } + + void setAngularLowerLimit(const Vector3 &angularLower) { + m_angularLimits[0].m_loLimit = angularLower.x; + m_angularLimits[1].m_loLimit = angularLower.y; + m_angularLimits[2].m_loLimit = angularLower.z; + } + + void setAngularUpperLimit(const Vector3 &angularUpper) { + m_angularLimits[0].m_hiLimit = angularUpper.x; + m_angularLimits[1].m_hiLimit = angularUpper.y; + m_angularLimits[2].m_hiLimit = angularUpper.z; + } //! Retrieves the angular limit informacion - G6DOFRotationalLimitMotorSW * getRotationalLimitMotor(int index) - { - return &m_angularLimits[index]; - } - - //! Retrieves the limit informacion - G6DOFTranslationalLimitMotorSW * getTranslationalLimitMotor() - { - return &m_linearLimits; - } - - //first 3 are linear, next 3 are angular - void setLimit(int axis, real_t lo, real_t hi) - { - if(axis<3) - { - m_linearLimits.m_lowerLimit[axis] = lo; - m_linearLimits.m_upperLimit[axis] = hi; + G6DOFRotationalLimitMotorSW *getRotationalLimitMotor(int index) { + return &m_angularLimits[index]; + } + + //! Retrieves the limit informacion + G6DOFTranslationalLimitMotorSW *getTranslationalLimitMotor() { + return &m_linearLimits; } - else - { - m_angularLimits[axis-3].m_loLimit = lo; - m_angularLimits[axis-3].m_hiLimit = hi; + + //first 3 are linear, next 3 are angular + void setLimit(int axis, real_t lo, real_t hi) { + if (axis < 3) { + m_linearLimits.m_lowerLimit[axis] = lo; + m_linearLimits.m_upperLimit[axis] = hi; + } else { + m_angularLimits[axis - 3].m_loLimit = lo; + m_angularLimits[axis - 3].m_hiLimit = hi; + } } - } //! Test limit /*! @@ -428,34 +376,27 @@ public: - limited means upper > lower - limitIndex: first 3 are linear, next 3 are angular */ - bool isLimited(int limitIndex) - { - if(limitIndex<3) - { + bool isLimited(int limitIndex) { + if (limitIndex < 3) { return m_linearLimits.isLimited(limitIndex); + } + return m_angularLimits[limitIndex - 3].isLimited(); + } + const BodySW *getRigidBodyA() const { + return A; + } + const BodySW *getRigidBodyB() const { + return B; } - return m_angularLimits[limitIndex-3].isLimited(); - } - - const BodySW* getRigidBodyA() const - { - return A; - } - const BodySW* getRigidBodyB() const - { - return B; - } virtual void calcAnchorPos(void); // overridable - void set_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value); - real_t get_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param) const; - - void set_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value); - bool get_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag) const; + void set_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value); + real_t get_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param) const; + void set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value); + bool get_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag) const; }; - #endif // GENERIC_6DOF_JOINT_SW_H diff --git a/servers/physics/joints/hinge_joint_sw.cpp b/servers/physics/joints/hinge_joint_sw.cpp index 9617eb8794..eaa57af873 100644 --- a/servers/physics/joints/hinge_joint_sw.cpp +++ b/servers/physics/joints/hinge_joint_sw.cpp @@ -34,65 +34,63 @@ See corresponding header file for licensing info. #include "hinge_joint_sw.h" -static void plane_space(const Vector3& n, Vector3& p, Vector3& q) { - - if (Math::abs(n.z) > 0.707106781186547524400844362) { - // choose p in y-z plane - real_t a = n[1]*n[1] + n[2]*n[2]; - real_t k = 1.0/Math::sqrt(a); - p=Vector3(0,-n[2]*k,n[1]*k); - // set q = n x p - q=Vector3(a*k,-n[0]*p[2],n[0]*p[1]); - } - else { - // choose p in x-y plane - real_t a = n.x*n.x + n.y*n.y; - real_t k = 1.0/Math::sqrt(a); - p=Vector3(-n.y*k,n.x*k,0); - // set q = n x p - q=Vector3(-n.z*p.y,n.z*p.x,a*k); - } +static void plane_space(const Vector3 &n, Vector3 &p, Vector3 &q) { + + if (Math::abs(n.z) > 0.707106781186547524400844362) { + // choose p in y-z plane + real_t a = n[1] * n[1] + n[2] * n[2]; + real_t k = 1.0 / Math::sqrt(a); + p = Vector3(0, -n[2] * k, n[1] * k); + // set q = n x p + q = Vector3(a * k, -n[0] * p[2], n[0] * p[1]); + } else { + // choose p in x-y plane + real_t a = n.x * n.x + n.y * n.y; + real_t k = 1.0 / Math::sqrt(a); + p = Vector3(-n.y * k, n.x * k, 0); + // set q = n x p + q = Vector3(-n.z * p.y, n.z * p.x, a * k); + } } -HingeJointSW::HingeJointSW(BodySW* rbA,BodySW* rbB, const Transform& frameA, const Transform& frameB) : JointSW(_arr,2) { +HingeJointSW::HingeJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameA, const Transform &frameB) + : JointSW(_arr, 2) { - A=rbA; - B=rbB; + A = rbA; + B = rbB; - m_rbAFrame=frameA; - m_rbBFrame=frameB; + m_rbAFrame = frameA; + m_rbBFrame = frameB; // flip axis m_rbBFrame.basis[0][2] *= real_t(-1.); m_rbBFrame.basis[1][2] *= real_t(-1.); m_rbBFrame.basis[2][2] *= real_t(-1.); - //start with free m_lowerLimit = Math_PI; m_upperLimit = -Math_PI; - m_useLimit = false; m_biasFactor = 0.3f; m_relaxationFactor = 1.0f; m_limitSoftness = 0.9f; m_solveLimit = false; - tau=0.3; - - m_angularOnly=false; - m_enableAngularMotor=false; + tau = 0.3; - A->add_constraint(this,0); - B->add_constraint(this,1); + m_angularOnly = false; + m_enableAngularMotor = false; + A->add_constraint(this, 0); + B->add_constraint(this, 1); } -HingeJointSW::HingeJointSW(BodySW* rbA,BodySW* rbB, const Vector3& pivotInA,const Vector3& pivotInB, - const Vector3& axisInA,const Vector3& axisInB) : JointSW(_arr,2) { +HingeJointSW::HingeJointSW(BodySW *rbA, BodySW *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, + const Vector3 &axisInA, const Vector3 &axisInB) + : JointSW(_arr, 2) { - A=rbA; - B=rbB; + A = rbA; + B = rbB; m_rbAFrame.origin = pivotInA; @@ -112,76 +110,67 @@ HingeJointSW::HingeJointSW(BodySW* rbA,BodySW* rbB, const Vector3& pivotInA,cons rbAxisA1 = rbAxisA2.cross(axisInA); } - m_rbAFrame.basis=Basis( rbAxisA1.x,rbAxisA2.x,axisInA.x, - rbAxisA1.y,rbAxisA2.y,axisInA.y, - rbAxisA1.z,rbAxisA2.z,axisInA.z ); + m_rbAFrame.basis = Basis(rbAxisA1.x, rbAxisA2.x, axisInA.x, + rbAxisA1.y, rbAxisA2.y, axisInA.y, + rbAxisA1.z, rbAxisA2.z, axisInA.z); - Quat rotationArc = Quat(axisInA,axisInB); - Vector3 rbAxisB1 = rotationArc.xform(rbAxisA1); - Vector3 rbAxisB2 = axisInB.cross(rbAxisB1); + Quat rotationArc = Quat(axisInA, axisInB); + Vector3 rbAxisB1 = rotationArc.xform(rbAxisA1); + Vector3 rbAxisB2 = axisInB.cross(rbAxisB1); m_rbBFrame.origin = pivotInB; - m_rbBFrame.basis=Basis( rbAxisB1.x,rbAxisB2.x,-axisInB.x, - rbAxisB1.y,rbAxisB2.y,-axisInB.y, - rbAxisB1.z,rbAxisB2.z,-axisInB.z ); + m_rbBFrame.basis = Basis(rbAxisB1.x, rbAxisB2.x, -axisInB.x, + rbAxisB1.y, rbAxisB2.y, -axisInB.y, + rbAxisB1.z, rbAxisB2.z, -axisInB.z); //start with free m_lowerLimit = Math_PI; m_upperLimit = -Math_PI; - m_useLimit = false; m_biasFactor = 0.3f; m_relaxationFactor = 1.0f; m_limitSoftness = 0.9f; m_solveLimit = false; - tau=0.3; - - m_angularOnly=false; - m_enableAngularMotor=false; + tau = 0.3; - A->add_constraint(this,0); - B->add_constraint(this,1); + m_angularOnly = false; + m_enableAngularMotor = false; + A->add_constraint(this, 0); + B->add_constraint(this, 1); } - - bool HingeJointSW::setup(real_t p_step) { m_appliedImpulse = real_t(0.); - if (!m_angularOnly) - { + if (!m_angularOnly) { Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin); Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin); Vector3 relPos = pivotBInW - pivotAInW; Vector3 normal[3]; - if (relPos.length_squared() > CMP_EPSILON) - { + if (relPos.length_squared() > CMP_EPSILON) { normal[0] = relPos.normalized(); - } - else - { - normal[0]=Vector3(real_t(1.0),0,0); + } else { + normal[0] = Vector3(real_t(1.0), 0, 0); } plane_space(normal[0], normal[1], normal[2]); - for (int i=0;i<3;i++) - { + for (int i = 0; i < 3; i++) { memnew_placement(&m_jac[i], JacobianEntrySW( - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - pivotAInW - A->get_transform().origin - A->get_center_of_mass(), - pivotBInW - B->get_transform().origin - B->get_center_of_mass(), - normal[i], - A->get_inv_inertia(), - A->get_inv_mass(), - B->get_inv_inertia(), - B->get_inv_mass()) ); + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + pivotAInW - A->get_transform().origin - A->get_center_of_mass(), + pivotBInW - B->get_transform().origin - B->get_center_of_mass(), + normal[i], + A->get_inv_inertia(), + A->get_inv_mass(), + B->get_inv_inertia(), + B->get_inv_mass())); } } @@ -192,31 +181,30 @@ bool HingeJointSW::setup(real_t p_step) { Vector3 jointAxis0local; Vector3 jointAxis1local; - plane_space(m_rbAFrame.basis.get_axis(2),jointAxis0local,jointAxis1local); - - A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) ); - Vector3 jointAxis0 = A->get_transform().basis.xform( jointAxis0local ); - Vector3 jointAxis1 = A->get_transform().basis.xform( jointAxis1local ); - Vector3 hingeAxisWorld = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) ); + plane_space(m_rbAFrame.basis.get_axis(2), jointAxis0local, jointAxis1local); - memnew_placement(&m_jacAng[0], JacobianEntrySW(jointAxis0, - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - A->get_inv_inertia(), - B->get_inv_inertia())); + A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2)); + Vector3 jointAxis0 = A->get_transform().basis.xform(jointAxis0local); + Vector3 jointAxis1 = A->get_transform().basis.xform(jointAxis1local); + Vector3 hingeAxisWorld = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2)); - memnew_placement(&m_jacAng[1], JacobianEntrySW(jointAxis1, - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - A->get_inv_inertia(), - B->get_inv_inertia())); + memnew_placement(&m_jacAng[0], JacobianEntrySW(jointAxis0, + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + A->get_inv_inertia(), + B->get_inv_inertia())); - memnew_placement(&m_jacAng[2], JacobianEntrySW(hingeAxisWorld, - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - A->get_inv_inertia(), - B->get_inv_inertia())); + memnew_placement(&m_jacAng[1], JacobianEntrySW(jointAxis1, + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + A->get_inv_inertia(), + B->get_inv_inertia())); + memnew_placement(&m_jacAng[2], JacobianEntrySW(hingeAxisWorld, + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + A->get_inv_inertia(), + B->get_inv_inertia())); // Compute limit information real_t hingeAngle = get_hinge_angle(); @@ -228,26 +216,21 @@ bool HingeJointSW::setup(real_t p_step) { m_solveLimit = false; m_accLimitImpulse = real_t(0.); - - /*if (m_useLimit) { print_line("low: "+rtos(m_lowerLimit)); print_line("hi: "+rtos(m_upperLimit)); }*/ //if (m_lowerLimit < m_upperLimit) - if (m_useLimit && m_lowerLimit <= m_upperLimit) - { + if (m_useLimit && m_lowerLimit <= m_upperLimit) { //if (hingeAngle <= m_lowerLimit*m_limitSoftness) - if (hingeAngle <= m_lowerLimit) - { + if (hingeAngle <= m_lowerLimit) { m_correction = (m_lowerLimit - hingeAngle); m_limitSign = 1.0f; m_solveLimit = true; } //else if (hingeAngle >= m_upperLimit*m_limitSoftness) - else if (hingeAngle >= m_upperLimit) - { + else if (hingeAngle >= m_upperLimit) { m_correction = m_upperLimit - hingeAngle; m_limitSign = -1.0f; m_solveLimit = true; @@ -255,9 +238,9 @@ bool HingeJointSW::setup(real_t p_step) { } //Compute K = J*W*J' for hinge axis - Vector3 axisA = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) ); - m_kHinge = 1.0f / (A->compute_angular_impulse_denominator(axisA) + - B->compute_angular_impulse_denominator(axisA)); + Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2)); + m_kHinge = 1.0f / (A->compute_angular_impulse_denominator(axisA) + + B->compute_angular_impulse_denominator(axisA)); return true; } @@ -270,8 +253,7 @@ void HingeJointSW::solve(real_t p_step) { //real_t tau = real_t(0.3); //linear part - if (!m_angularOnly) - { + if (!m_angularOnly) { Vector3 rel_pos1 = pivotAInW - A->get_transform().origin; Vector3 rel_pos2 = pivotBInW - B->get_transform().origin; @@ -279,80 +261,74 @@ void HingeJointSW::solve(real_t p_step) { Vector3 vel2 = B->get_velocity_in_local_point(rel_pos2); Vector3 vel = vel1 - vel2; - for (int i=0;i<3;i++) - { - const Vector3& normal = m_jac[i].m_linearJointAxis; + for (int i = 0; i < 3; i++) { + const Vector3 &normal = m_jac[i].m_linearJointAxis; real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal(); real_t rel_vel; rel_vel = normal.dot(vel); //positional error (zeroth order error) real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal - real_t impulse = depth*tau/p_step * jacDiagABInv - rel_vel * jacDiagABInv; + real_t impulse = depth * tau / p_step * jacDiagABInv - rel_vel * jacDiagABInv; m_appliedImpulse += impulse; Vector3 impulse_vector = normal * impulse; - A->apply_impulse(pivotAInW - A->get_transform().origin,impulse_vector); - B->apply_impulse(pivotBInW - B->get_transform().origin,-impulse_vector); + A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector); + B->apply_impulse(pivotBInW - B->get_transform().origin, -impulse_vector); } } - { ///solve angular part // get axes in world space - Vector3 axisA = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) ); - Vector3 axisB = B->get_transform().basis.xform( m_rbBFrame.basis.get_axis(2) ); + Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2)); + Vector3 axisB = B->get_transform().basis.xform(m_rbBFrame.basis.get_axis(2)); - const Vector3& angVelA = A->get_angular_velocity(); - const Vector3& angVelB = B->get_angular_velocity(); + const Vector3 &angVelA = A->get_angular_velocity(); + const Vector3 &angVelB = B->get_angular_velocity(); Vector3 angVelAroundHingeAxisA = axisA * axisA.dot(angVelA); Vector3 angVelAroundHingeAxisB = axisB * axisB.dot(angVelB); Vector3 angAorthog = angVelA - angVelAroundHingeAxisA; Vector3 angBorthog = angVelB - angVelAroundHingeAxisB; - Vector3 velrelOrthog = angAorthog-angBorthog; + Vector3 velrelOrthog = angAorthog - angBorthog; { //solve orthogonal angular velocity correction real_t relaxation = real_t(1.); real_t len = velrelOrthog.length(); - if (len > real_t(0.00001)) - { + if (len > real_t(0.00001)) { Vector3 normal = velrelOrthog.normalized(); real_t denom = A->compute_angular_impulse_denominator(normal) + - B->compute_angular_impulse_denominator(normal); + B->compute_angular_impulse_denominator(normal); // scale for mass and relaxation - velrelOrthog *= (real_t(1.)/denom) * m_relaxationFactor; + velrelOrthog *= (real_t(1.) / denom) * m_relaxationFactor; } //solve angular positional correction - Vector3 angularError = -axisA.cross(axisB) *(real_t(1.)/p_step); + Vector3 angularError = -axisA.cross(axisB) * (real_t(1.) / p_step); real_t len2 = angularError.length(); - if (len2>real_t(0.00001)) - { + if (len2 > real_t(0.00001)) { Vector3 normal2 = angularError.normalized(); real_t denom2 = A->compute_angular_impulse_denominator(normal2) + - B->compute_angular_impulse_denominator(normal2); - angularError *= (real_t(1.)/denom2) * relaxation; + B->compute_angular_impulse_denominator(normal2); + angularError *= (real_t(1.) / denom2) * relaxation; } - A->apply_torque_impulse(-velrelOrthog+angularError); - B->apply_torque_impulse(velrelOrthog-angularError); + A->apply_torque_impulse(-velrelOrthog + angularError); + B->apply_torque_impulse(velrelOrthog - angularError); // solve limit - if (m_solveLimit) - { - real_t amplitude = ( (angVelB - angVelA).dot( axisA )*m_relaxationFactor + m_correction* (real_t(1.)/p_step)*m_biasFactor ) * m_limitSign; + if (m_solveLimit) { + real_t amplitude = ((angVelB - angVelA).dot(axisA) * m_relaxationFactor + m_correction * (real_t(1.) / p_step) * m_biasFactor) * m_limitSign; real_t impulseMag = amplitude * m_kHinge; // Clamp the accumulated impulse real_t temp = m_accLimitImpulse; - m_accLimitImpulse = MAX(m_accLimitImpulse + impulseMag, real_t(0) ); + m_accLimitImpulse = MAX(m_accLimitImpulse + impulseMag, real_t(0)); impulseMag = m_accLimitImpulse - temp; - Vector3 impulse = axisA * impulseMag * m_limitSign; A->apply_torque_impulse(impulse); B->apply_torque_impulse(-impulse); @@ -360,10 +336,9 @@ void HingeJointSW::solve(real_t p_step) { } //apply motor - if (m_enableAngularMotor) - { + if (m_enableAngularMotor) { //todo: add limits too - Vector3 angularLimit(0,0,0); + Vector3 angularLimit(0, 0, 0); Vector3 velrel = angVelAroundHingeAxisA - angVelAroundHingeAxisB; real_t projRelVel = velrel.dot(axisA); @@ -377,12 +352,10 @@ void HingeJointSW::solve(real_t p_step) { clippedMotorImpulse = clippedMotorImpulse < -m_maxMotorImpulse ? -m_maxMotorImpulse : clippedMotorImpulse; Vector3 motorImp = clippedMotorImpulse * axisA; - A->apply_torque_impulse(motorImp+angularLimit); - B->apply_torque_impulse(-motorImp-angularLimit); - + A->apply_torque_impulse(motorImp + angularLimit); + B->apply_torque_impulse(-motorImp - angularLimit); } } - } /* void HingeJointSW::updateRHS(real_t timeStep) @@ -392,8 +365,7 @@ void HingeJointSW::updateRHS(real_t timeStep) } */ -static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) -{ +static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) { real_t coeff_1 = Math_PI / 4.0f; real_t coeff_2 = 3.0f * coeff_1; real_t abs_y = Math::abs(y); @@ -408,33 +380,30 @@ static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) return (y < 0.0f) ? -angle : angle; } - real_t HingeJointSW::get_hinge_angle() { - const Vector3 refAxis0 = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(0) ); - const Vector3 refAxis1 = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(1) ); - const Vector3 swingAxis = B->get_transform().basis.xform( m_rbBFrame.basis.get_axis(1) ); + const Vector3 refAxis0 = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(0)); + const Vector3 refAxis1 = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(1)); + const Vector3 swingAxis = B->get_transform().basis.xform(m_rbBFrame.basis.get_axis(1)); - return atan2fast( swingAxis.dot(refAxis0), swingAxis.dot(refAxis1) ); + return atan2fast(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1)); } - void HingeJointSW::set_param(PhysicsServer::HingeJointParam p_param, real_t p_value) { switch (p_param) { - case PhysicsServer::HINGE_JOINT_BIAS: tau=p_value; break; - case PhysicsServer::HINGE_JOINT_LIMIT_UPPER: m_upperLimit=p_value; break; - case PhysicsServer::HINGE_JOINT_LIMIT_LOWER: m_lowerLimit=p_value; break; - case PhysicsServer::HINGE_JOINT_LIMIT_BIAS: m_biasFactor=p_value; break; - case PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS: m_limitSoftness=p_value; break; - case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: m_relaxationFactor=p_value; break; - case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: m_motorTargetVelocity=p_value; break; - case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: m_maxMotorImpulse=p_value; break; - + case PhysicsServer::HINGE_JOINT_BIAS: tau = p_value; break; + case PhysicsServer::HINGE_JOINT_LIMIT_UPPER: m_upperLimit = p_value; break; + case PhysicsServer::HINGE_JOINT_LIMIT_LOWER: m_lowerLimit = p_value; break; + case PhysicsServer::HINGE_JOINT_LIMIT_BIAS: m_biasFactor = p_value; break; + case PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS: m_limitSoftness = p_value; break; + case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: m_relaxationFactor = p_value; break; + case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: m_motorTargetVelocity = p_value; break; + case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: m_maxMotorImpulse = p_value; break; } } -real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const{ +real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const { switch (p_param) { @@ -446,25 +415,23 @@ real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const{ case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: return m_relaxationFactor; case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: return m_motorTargetVelocity; case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: return m_maxMotorImpulse; - } return 0; } -void HingeJointSW::set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value){ +void HingeJointSW::set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value) { switch (p_flag) { - case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: m_useLimit=p_value; break; - case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: m_enableAngularMotor=p_value; break; + case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: m_useLimit = p_value; break; + case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: m_enableAngularMotor = p_value; break; } - } -bool HingeJointSW::get_flag(PhysicsServer::HingeJointFlag p_flag) const{ +bool HingeJointSW::get_flag(PhysicsServer::HingeJointFlag p_flag) const { switch (p_flag) { case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: return m_useLimit; - case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR:return m_enableAngularMotor; + case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: return m_enableAngularMotor; } return false; diff --git a/servers/physics/joints/hinge_joint_sw.h b/servers/physics/joints/hinge_joint_sw.h index 8469fd1ca0..013d9afdbf 100644 --- a/servers/physics/joints/hinge_joint_sw.h +++ b/servers/physics/joints/hinge_joint_sw.h @@ -34,9 +34,8 @@ Adapted to Godot from the Bullet library. #ifndef HINGE_JOINT_SW_H #define HINGE_JOINT_SW_H -#include "servers/physics/joints_sw.h" #include "servers/physics/joints/jacobian_entry_sw.h" - +#include "servers/physics/joints_sw.h" /* Bullet Continuous Collision Detection and Physics Library @@ -53,8 +52,6 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ - - class HingeJointSW : public JointSW { union { @@ -66,41 +63,39 @@ class HingeJointSW : public JointSW { BodySW *_arr[2]; }; - JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints - JacobianEntrySW m_jacAng[3]; //2 orthogonal angular constraints+ 1 for limit/motor + JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints + JacobianEntrySW m_jacAng[3]; //2 orthogonal angular constraints+ 1 for limit/motor Transform m_rbAFrame; // constraint axii. Assumes z is hinge axis. Transform m_rbBFrame; - real_t m_motorTargetVelocity; - real_t m_maxMotorImpulse; + real_t m_motorTargetVelocity; + real_t m_maxMotorImpulse; - real_t m_limitSoftness; - real_t m_biasFactor; - real_t m_relaxationFactor; + real_t m_limitSoftness; + real_t m_biasFactor; + real_t m_relaxationFactor; - real_t m_lowerLimit; - real_t m_upperLimit; + real_t m_lowerLimit; + real_t m_upperLimit; - real_t m_kHinge; + real_t m_kHinge; - real_t m_limitSign; - real_t m_correction; + real_t m_limitSign; + real_t m_correction; - real_t m_accLimitImpulse; + real_t m_accLimitImpulse; real_t tau; - bool m_useLimit; - bool m_angularOnly; - bool m_enableAngularMotor; - bool m_solveLimit; + bool m_useLimit; + bool m_angularOnly; + bool m_enableAngularMotor; + bool m_solveLimit; real_t m_appliedImpulse; - public: - virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_HINGE; } virtual bool setup(real_t p_step); @@ -114,9 +109,8 @@ public: void set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value); bool get_flag(PhysicsServer::HingeJointFlag p_flag) const; - HingeJointSW(BodySW* rbA,BodySW* rbB, const Transform& frameA, const Transform& frameB); - HingeJointSW(BodySW* rbA,BodySW* rbB, const Vector3& pivotInA,const Vector3& pivotInB, const Vector3& axisInA,const Vector3& axisInB); - + HingeJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameA, const Transform &frameB); + HingeJointSW(BodySW *rbA, BodySW *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB); }; #endif // HINGE_JOINT_SW_H diff --git a/servers/physics/joints/jacobian_entry_sw.h b/servers/physics/joints/jacobian_entry_sw.h index cd85162ba5..b0b31ed797 100644 --- a/servers/physics/joints/jacobian_entry_sw.h +++ b/servers/physics/joints/jacobian_entry_sw.h @@ -53,22 +53,21 @@ subject to the following restrictions: class JacobianEntrySW { public: - JacobianEntrySW() {}; + JacobianEntrySW(){}; //constraint between two different rigidbodies JacobianEntrySW( - const Basis& world2A, - const Basis& world2B, - const Vector3& rel_pos1,const Vector3& rel_pos2, - const Vector3& jointAxis, - const Vector3& inertiaInvA, - const real_t massInvA, - const Vector3& inertiaInvB, - const real_t massInvB) - :m_linearJointAxis(jointAxis) - { + const Basis &world2A, + const Basis &world2B, + const Vector3 &rel_pos1, const Vector3 &rel_pos2, + const Vector3 &jointAxis, + const Vector3 &inertiaInvA, + const real_t massInvA, + const Vector3 &inertiaInvB, + const real_t massInvB) + : m_linearJointAxis(jointAxis) { m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis)); m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis)); - m_0MinvJt = inertiaInvA * m_aJ; + m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = inertiaInvB * m_bJ; m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ); @@ -76,104 +75,92 @@ public: } //angular constraint between two different rigidbodies - JacobianEntrySW(const Vector3& jointAxis, - const Basis& world2A, - const Basis& world2B, - const Vector3& inertiaInvA, - const Vector3& inertiaInvB) - :m_linearJointAxis(Vector3(real_t(0.),real_t(0.),real_t(0.))) - { - m_aJ= world2A.xform(jointAxis); + JacobianEntrySW(const Vector3 &jointAxis, + const Basis &world2A, + const Basis &world2B, + const Vector3 &inertiaInvA, + const Vector3 &inertiaInvB) + : m_linearJointAxis(Vector3(real_t(0.), real_t(0.), real_t(0.))) { + m_aJ = world2A.xform(jointAxis); m_bJ = world2B.xform(-jointAxis); - m_0MinvJt = inertiaInvA * m_aJ; + m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = inertiaInvB * m_bJ; - m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ); + m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ); ERR_FAIL_COND(m_Adiag <= real_t(0.0)); } //angular constraint between two different rigidbodies - JacobianEntrySW(const Vector3& axisInA, - const Vector3& axisInB, - const Vector3& inertiaInvA, - const Vector3& inertiaInvB) - : m_linearJointAxis(Vector3(real_t(0.),real_t(0.),real_t(0.))) - , m_aJ(axisInA) - , m_bJ(-axisInB) - { - m_0MinvJt = inertiaInvA * m_aJ; + JacobianEntrySW(const Vector3 &axisInA, + const Vector3 &axisInB, + const Vector3 &inertiaInvA, + const Vector3 &inertiaInvB) + : m_linearJointAxis(Vector3(real_t(0.), real_t(0.), real_t(0.))), m_aJ(axisInA), m_bJ(-axisInB) { + m_0MinvJt = inertiaInvA * m_aJ; m_1MinvJt = inertiaInvB * m_bJ; - m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ); + m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ); ERR_FAIL_COND(m_Adiag <= real_t(0.0)); } //constraint on one rigidbody JacobianEntrySW( - const Basis& world2A, - const Vector3& rel_pos1,const Vector3& rel_pos2, - const Vector3& jointAxis, - const Vector3& inertiaInvA, - const real_t massInvA) - :m_linearJointAxis(jointAxis) - { - m_aJ= world2A.xform(rel_pos1.cross(jointAxis)); + const Basis &world2A, + const Vector3 &rel_pos1, const Vector3 &rel_pos2, + const Vector3 &jointAxis, + const Vector3 &inertiaInvA, + const real_t massInvA) + : m_linearJointAxis(jointAxis) { + m_aJ = world2A.xform(rel_pos1.cross(jointAxis)); m_bJ = world2A.xform(rel_pos2.cross(-jointAxis)); - m_0MinvJt = inertiaInvA * m_aJ; - m_1MinvJt = Vector3(real_t(0.),real_t(0.),real_t(0.)); + m_0MinvJt = inertiaInvA * m_aJ; + m_1MinvJt = Vector3(real_t(0.), real_t(0.), real_t(0.)); m_Adiag = massInvA + m_0MinvJt.dot(m_aJ); ERR_FAIL_COND(m_Adiag <= real_t(0.0)); } - real_t getDiagonal() const { return m_Adiag; } + real_t getDiagonal() const { return m_Adiag; } // for two constraints on the same rigidbody (for example vehicle friction) - real_t getNonDiagonal(const JacobianEntrySW& jacB, const real_t massInvA) const - { - const JacobianEntrySW& jacA = *this; + real_t getNonDiagonal(const JacobianEntrySW &jacB, const real_t massInvA) const { + const JacobianEntrySW &jacA = *this; real_t lin = massInvA * jacA.m_linearJointAxis.dot(jacB.m_linearJointAxis); real_t ang = jacA.m_0MinvJt.dot(jacB.m_aJ); return lin + ang; } - - // for two constraints on sharing two same rigidbodies (for example two contact points between two rigidbodies) - real_t getNonDiagonal(const JacobianEntrySW& jacB,const real_t massInvA,const real_t massInvB) const - { - const JacobianEntrySW& jacA = *this; + real_t getNonDiagonal(const JacobianEntrySW &jacB, const real_t massInvA, const real_t massInvB) const { + const JacobianEntrySW &jacA = *this; Vector3 lin = jacA.m_linearJointAxis * jacB.m_linearJointAxis; Vector3 ang0 = jacA.m_0MinvJt * jacB.m_aJ; Vector3 ang1 = jacA.m_1MinvJt * jacB.m_bJ; - Vector3 lin0 = massInvA * lin ; + Vector3 lin0 = massInvA * lin; Vector3 lin1 = massInvB * lin; - Vector3 sum = ang0+ang1+lin0+lin1; - return sum[0]+sum[1]+sum[2]; + Vector3 sum = ang0 + ang1 + lin0 + lin1; + return sum[0] + sum[1] + sum[2]; } - real_t getRelativeVelocity(const Vector3& linvelA,const Vector3& angvelA,const Vector3& linvelB,const Vector3& angvelB) - { + real_t getRelativeVelocity(const Vector3 &linvelA, const Vector3 &angvelA, const Vector3 &linvelB, const Vector3 &angvelB) { Vector3 linrel = linvelA - linvelB; - Vector3 angvela = angvelA * m_aJ; - Vector3 angvelb = angvelB * m_bJ; + Vector3 angvela = angvelA * m_aJ; + Vector3 angvelb = angvelB * m_bJ; linrel *= m_linearJointAxis; angvela += angvelb; angvela += linrel; - real_t rel_vel2 = angvela[0]+angvela[1]+angvela[2]; + real_t rel_vel2 = angvela[0] + angvela[1] + angvela[2]; return rel_vel2 + CMP_EPSILON; } -//private: + //private: - Vector3 m_linearJointAxis; - Vector3 m_aJ; - Vector3 m_bJ; - Vector3 m_0MinvJt; - Vector3 m_1MinvJt; + Vector3 m_linearJointAxis; + Vector3 m_aJ; + Vector3 m_bJ; + Vector3 m_0MinvJt; + Vector3 m_1MinvJt; //Optimization: can be stored in the w/last component of one of the vectors - real_t m_Adiag; - + real_t m_Adiag; }; - #endif // JACOBIAN_ENTRY_SW_H diff --git a/servers/physics/joints/pin_joint_sw.cpp b/servers/physics/joints/pin_joint_sw.cpp index b545ae630b..e01514f4b6 100644 --- a/servers/physics/joints/pin_joint_sw.cpp +++ b/servers/physics/joints/pin_joint_sw.cpp @@ -38,41 +38,37 @@ bool PinJointSW::setup(real_t p_step) { m_appliedImpulse = real_t(0.); - Vector3 normal(0,0,0); + Vector3 normal(0, 0, 0); - for (int i=0;i<3;i++) - { + for (int i = 0; i < 3; i++) { normal[i] = 1; - memnew_placement(&m_jac[i],JacobianEntrySW( - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - A->get_transform().xform(m_pivotInA) - A->get_transform().origin - A->get_center_of_mass(), - B->get_transform().xform(m_pivotInB) - B->get_transform().origin - B->get_center_of_mass(), - normal, - A->get_inv_inertia(), - A->get_inv_mass(), - B->get_inv_inertia(), - B->get_inv_mass())); + memnew_placement(&m_jac[i], JacobianEntrySW( + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + A->get_transform().xform(m_pivotInA) - A->get_transform().origin - A->get_center_of_mass(), + B->get_transform().xform(m_pivotInB) - B->get_transform().origin - B->get_center_of_mass(), + normal, + A->get_inv_inertia(), + A->get_inv_mass(), + B->get_inv_inertia(), + B->get_inv_mass())); normal[i] = 0; } return true; } -void PinJointSW::solve(real_t p_step){ +void PinJointSW::solve(real_t p_step) { Vector3 pivotAInW = A->get_transform().xform(m_pivotInA); Vector3 pivotBInW = B->get_transform().xform(m_pivotInB); - - Vector3 normal(0,0,0); - + Vector3 normal(0, 0, 0); //Vector3 angvelA = A->get_transform().origin.getBasis().transpose() * A->getAngularVelocity(); //Vector3 angvelB = B->get_transform().origin.getBasis().transpose() * B->getAngularVelocity(); - for (int i=0;i<3;i++) - { + for (int i = 0; i < 3; i++) { normal[i] = 1; real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal(); @@ -87,7 +83,7 @@ void PinJointSW::solve(real_t p_step){ real_t rel_vel; rel_vel = normal.dot(vel); - /* + /* //velocity error (first order error) real_t rel_vel = m_jac[i].getRelativeVelocity(A->getLinearVelocity(),angvelA, B->getLinearVelocity(),angvelB); @@ -96,38 +92,37 @@ void PinJointSW::solve(real_t p_step){ //positional error (zeroth order error) real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal - real_t impulse = depth*m_tau/p_step * jacDiagABInv - m_damping * rel_vel * jacDiagABInv; + real_t impulse = depth * m_tau / p_step * jacDiagABInv - m_damping * rel_vel * jacDiagABInv; real_t impulseClamp = m_impulseClamp; - if (impulseClamp > 0) - { + if (impulseClamp > 0) { if (impulse < -impulseClamp) impulse = -impulseClamp; if (impulse > impulseClamp) impulse = impulseClamp; } - m_appliedImpulse+=impulse; + m_appliedImpulse += impulse; Vector3 impulse_vector = normal * impulse; - A->apply_impulse(pivotAInW - A->get_transform().origin,impulse_vector); - B->apply_impulse(pivotBInW - B->get_transform().origin,-impulse_vector); + A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector); + B->apply_impulse(pivotBInW - B->get_transform().origin, -impulse_vector); normal[i] = 0; } } -void PinJointSW::set_param(PhysicsServer::PinJointParam p_param,real_t p_value) { +void PinJointSW::set_param(PhysicsServer::PinJointParam p_param, real_t p_value) { - switch(p_param) { - case PhysicsServer::PIN_JOINT_BIAS: m_tau=p_value; break; - case PhysicsServer::PIN_JOINT_DAMPING: m_damping=p_value; break; - case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: m_impulseClamp=p_value; break; + switch (p_param) { + case PhysicsServer::PIN_JOINT_BIAS: m_tau = p_value; break; + case PhysicsServer::PIN_JOINT_DAMPING: m_damping = p_value; break; + case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: m_impulseClamp = p_value; break; } } -real_t PinJointSW::get_param(PhysicsServer::PinJointParam p_param) const{ +real_t PinJointSW::get_param(PhysicsServer::PinJointParam p_param) const { - switch(p_param) { + switch (p_param) { case PhysicsServer::PIN_JOINT_BIAS: return m_tau; case PhysicsServer::PIN_JOINT_DAMPING: return m_damping; case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: return m_impulseClamp; @@ -136,26 +131,22 @@ real_t PinJointSW::get_param(PhysicsServer::PinJointParam p_param) const{ return 0; } -PinJointSW::PinJointSW(BodySW* p_body_a,const Vector3& p_pos_a,BodySW* p_body_b,const Vector3& p_pos_b) : JointSW(_arr,2) { - - A=p_body_a; - B=p_body_b; - m_pivotInA=p_pos_a; - m_pivotInB=p_pos_b; - - m_tau=0.3; - m_damping=1; - m_impulseClamp=0; - m_appliedImpulse=0; +PinJointSW::PinJointSW(BodySW *p_body_a, const Vector3 &p_pos_a, BodySW *p_body_b, const Vector3 &p_pos_b) + : JointSW(_arr, 2) { - A->add_constraint(this,0); - B->add_constraint(this,1); + A = p_body_a; + B = p_body_b; + m_pivotInA = p_pos_a; + m_pivotInB = p_pos_b; + m_tau = 0.3; + m_damping = 1; + m_impulseClamp = 0; + m_appliedImpulse = 0; + A->add_constraint(this, 0); + B->add_constraint(this, 1); } PinJointSW::~PinJointSW() { - - - } diff --git a/servers/physics/joints/pin_joint_sw.h b/servers/physics/joints/pin_joint_sw.h index b72b21219d..9500d4b46d 100644 --- a/servers/physics/joints/pin_joint_sw.h +++ b/servers/physics/joints/pin_joint_sw.h @@ -34,8 +34,8 @@ Adapted to Godot from the Bullet library. #ifndef PIN_JOINT_SW_H #define PIN_JOINT_SW_H -#include "servers/physics/joints_sw.h" #include "servers/physics/joints/jacobian_entry_sw.h" +#include "servers/physics/joints_sw.h" /* Bullet Continuous Collision Detection and Physics Library @@ -52,7 +52,6 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ - class PinJointSW : public JointSW { union { @@ -64,37 +63,33 @@ class PinJointSW : public JointSW { BodySW *_arr[2]; }; + real_t m_tau; //bias + real_t m_damping; + real_t m_impulseClamp; + real_t m_appliedImpulse; - real_t m_tau; //bias - real_t m_damping; - real_t m_impulseClamp; - real_t m_appliedImpulse; - - JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints + JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints - Vector3 m_pivotInA; - Vector3 m_pivotInB; + Vector3 m_pivotInA; + Vector3 m_pivotInB; public: - virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_PIN; } virtual bool setup(real_t p_step); virtual void solve(real_t p_step); - void set_param(PhysicsServer::PinJointParam p_param,real_t p_value); + void set_param(PhysicsServer::PinJointParam p_param, real_t p_value); real_t get_param(PhysicsServer::PinJointParam p_param) const; - void set_pos_A(const Vector3& p_pos) { m_pivotInA=p_pos; } - void set_pos_B(const Vector3& p_pos) { m_pivotInB=p_pos; } + void set_pos_A(const Vector3 &p_pos) { m_pivotInA = p_pos; } + void set_pos_B(const Vector3 &p_pos) { m_pivotInB = p_pos; } Vector3 get_pos_A() { return m_pivotInB; } Vector3 get_pos_B() { return m_pivotInA; } - PinJointSW(BodySW* p_body_a,const Vector3& p_pos_a,BodySW* p_body_b,const Vector3& p_pos_b); + PinJointSW(BodySW *p_body_a, const Vector3 &p_pos_a, BodySW *p_body_b, const Vector3 &p_pos_b); ~PinJointSW(); }; - - #endif // PIN_JOINT_SW_H diff --git a/servers/physics/joints/slider_joint_sw.cpp b/servers/physics/joints/slider_joint_sw.cpp index fc728ed0ba..b8a6c1ecaf 100644 --- a/servers/physics/joints/slider_joint_sw.cpp +++ b/servers/physics/joints/slider_joint_sw.cpp @@ -36,8 +36,7 @@ See corresponding header file for licensing info. //----------------------------------------------------------------------------- -static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) -{ +static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) { real_t coeff_1 = Math_PI / 4.0f; real_t coeff_2 = 3.0f * coeff_1; real_t abs_y = Math::abs(y); @@ -52,13 +51,11 @@ static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) return (y < 0.0f) ? -angle : angle; } - -void SliderJointSW::initParams() -{ - m_lowerLinLimit = real_t(1.0); - m_upperLinLimit = real_t(-1.0); - m_lowerAngLimit = real_t(0.); - m_upperAngLimit = real_t(0.); +void SliderJointSW::initParams() { + m_lowerLinLimit = real_t(1.0); + m_upperLinLimit = real_t(-1.0); + m_lowerAngLimit = real_t(0.); + m_upperAngLimit = real_t(0.); m_softnessDirLin = SLIDER_CONSTRAINT_DEF_SOFTNESS; m_restitutionDirLin = SLIDER_CONSTRAINT_DEF_RESTITUTION; m_dampingDirLin = real_t(0.); @@ -84,40 +81,35 @@ void SliderJointSW::initParams() m_accumulatedLinMotorImpulse = real_t(0.0); m_poweredAngMotor = false; - m_targetAngMotorVelocity = real_t(0.); - m_maxAngMotorForce = real_t(0.); + m_targetAngMotorVelocity = real_t(0.); + m_maxAngMotorForce = real_t(0.); m_accumulatedAngMotorImpulse = real_t(0.0); } // SliderJointSW::initParams() //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- -SliderJointSW::SliderJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB) - : JointSW(_arr,2) - , m_frameInA(frameInA) - , m_frameInB(frameInB) -{ +SliderJointSW::SliderJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB) + : JointSW(_arr, 2), m_frameInA(frameInA), m_frameInB(frameInB) { - A=rbA; - B=rbB; + A = rbA; + B = rbB; - A->add_constraint(this,0); - B->add_constraint(this,1); + A->add_constraint(this, 0); + B->add_constraint(this, 1); initParams(); } // SliderJointSW::SliderJointSW() //----------------------------------------------------------------------------- -bool SliderJointSW::setup(real_t p_step) -{ +bool SliderJointSW::setup(real_t p_step) { //calculate transforms - m_calculatedTransformA = A->get_transform() * m_frameInA; - m_calculatedTransformB = B->get_transform() * m_frameInB; + m_calculatedTransformA = A->get_transform() * m_frameInA; + m_calculatedTransformB = B->get_transform() * m_frameInB; m_realPivotAInW = m_calculatedTransformA.origin; m_realPivotBInW = m_calculatedTransformB.origin; m_sliderAxis = m_calculatedTransformA.basis.get_axis(0); // along X @@ -125,42 +117,38 @@ bool SliderJointSW::setup(real_t p_step) m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis; m_relPosA = m_projPivotInW - A->get_transform().origin; m_relPosB = m_realPivotBInW - B->get_transform().origin; - Vector3 normalWorld; - int i; - //linear part - for(i = 0; i < 3; i++) - { + Vector3 normalWorld; + int i; + //linear part + for (i = 0; i < 3; i++) { normalWorld = m_calculatedTransformA.basis.get_axis(i); memnew_placement(&m_jacLin[i], JacobianEntrySW( - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - m_relPosA - A->get_center_of_mass(), - m_relPosB - B->get_center_of_mass(), - normalWorld, - A->get_inv_inertia(), - A->get_inv_mass(), - B->get_inv_inertia(), - B->get_inv_mass() - )); + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + m_relPosA - A->get_center_of_mass(), + m_relPosB - B->get_center_of_mass(), + normalWorld, + A->get_inv_inertia(), + A->get_inv_mass(), + B->get_inv_inertia(), + B->get_inv_mass())); m_jacLinDiagABInv[i] = real_t(1.) / m_jacLin[i].getDiagonal(); m_depth[i] = m_delta.dot(normalWorld); - } + } testLinLimits(); - // angular part - for(i = 0; i < 3; i++) - { + // angular part + for (i = 0; i < 3; i++) { normalWorld = m_calculatedTransformA.basis.get_axis(i); - memnew_placement(&m_jacAng[i], JacobianEntrySW( - normalWorld, - A->get_principal_inertia_axes().transposed(), - B->get_principal_inertia_axes().transposed(), - A->get_inv_inertia(), - B->get_inv_inertia() - )); + memnew_placement(&m_jacAng[i], JacobianEntrySW( + normalWorld, + A->get_principal_inertia_axes().transposed(), + B->get_principal_inertia_axes().transposed(), + A->get_inv_inertia(), + B->get_inv_inertia())); } testAngLimits(); Vector3 axisA = m_calculatedTransformA.basis.get_axis(0); - m_kAngle = real_t(1.0 )/ (A->compute_angular_impulse_denominator(axisA) + B->compute_angular_impulse_denominator(axisA)); + m_kAngle = real_t(1.0) / (A->compute_angular_impulse_denominator(axisA) + B->compute_angular_impulse_denominator(axisA)); // clear accumulator for motors m_accumulatedLinMotorImpulse = real_t(0.0); m_accumulatedAngMotorImpulse = real_t(0.0); @@ -172,14 +160,13 @@ bool SliderJointSW::setup(real_t p_step) void SliderJointSW::solve(real_t p_step) { - int i; - // linear - Vector3 velA = A->get_velocity_in_local_point(m_relPosA); - Vector3 velB = B->get_velocity_in_local_point(m_relPosB); - Vector3 vel = velA - velB; - for(i = 0; i < 3; i++) - { - const Vector3& normal = m_jacLin[i].m_linearJointAxis; + int i; + // linear + Vector3 velA = A->get_velocity_in_local_point(m_relPosA); + Vector3 velB = B->get_velocity_in_local_point(m_relPosB); + Vector3 vel = velA - velB; + for (i = 0; i < 3; i++) { + const Vector3 &normal = m_jacLin[i].m_linearJointAxis; real_t rel_vel = normal.dot(vel); // calculate positional error real_t depth = m_depth[i]; @@ -190,81 +177,70 @@ void SliderJointSW::solve(real_t p_step) { // calcutate and apply impulse real_t normalImpulse = softness * (restitution * depth / p_step - damping * rel_vel) * m_jacLinDiagABInv[i]; Vector3 impulse_vector = normal * normalImpulse; - A->apply_impulse( m_relPosA, impulse_vector); - B->apply_impulse(m_relPosB,-impulse_vector); - if(m_poweredLinMotor && (!i)) - { // apply linear motor - if(m_accumulatedLinMotorImpulse < m_maxLinMotorForce) - { + A->apply_impulse(m_relPosA, impulse_vector); + B->apply_impulse(m_relPosB, -impulse_vector); + if (m_poweredLinMotor && (!i)) { // apply linear motor + if (m_accumulatedLinMotorImpulse < m_maxLinMotorForce) { real_t desiredMotorVel = m_targetLinMotorVelocity; real_t motor_relvel = desiredMotorVel + rel_vel; normalImpulse = -motor_relvel * m_jacLinDiagABInv[i]; // clamp accumulated impulse real_t new_acc = m_accumulatedLinMotorImpulse + Math::abs(normalImpulse); - if(new_acc > m_maxLinMotorForce) - { + if (new_acc > m_maxLinMotorForce) { new_acc = m_maxLinMotorForce; } - real_t del = new_acc - m_accumulatedLinMotorImpulse; - if(normalImpulse < real_t(0.0)) - { + real_t del = new_acc - m_accumulatedLinMotorImpulse; + if (normalImpulse < real_t(0.0)) { normalImpulse = -del; - } - else - { + } else { normalImpulse = del; } m_accumulatedLinMotorImpulse = new_acc; // apply clamped impulse impulse_vector = normal * normalImpulse; - A->apply_impulse( m_relPosA, impulse_vector); - B->apply_impulse( m_relPosB,-impulse_vector); + A->apply_impulse(m_relPosA, impulse_vector); + B->apply_impulse(m_relPosB, -impulse_vector); } } - } + } // angular // get axes in world space - Vector3 axisA = m_calculatedTransformA.basis.get_axis(0); - Vector3 axisB = m_calculatedTransformB.basis.get_axis(0); + Vector3 axisA = m_calculatedTransformA.basis.get_axis(0); + Vector3 axisB = m_calculatedTransformB.basis.get_axis(0); - const Vector3& angVelA = A->get_angular_velocity(); - const Vector3& angVelB = B->get_angular_velocity(); + const Vector3 &angVelA = A->get_angular_velocity(); + const Vector3 &angVelB = B->get_angular_velocity(); Vector3 angVelAroundAxisA = axisA * axisA.dot(angVelA); Vector3 angVelAroundAxisB = axisB * axisB.dot(angVelB); Vector3 angAorthog = angVelA - angVelAroundAxisA; Vector3 angBorthog = angVelB - angVelAroundAxisB; - Vector3 velrelOrthog = angAorthog-angBorthog; + Vector3 velrelOrthog = angAorthog - angBorthog; //solve orthogonal angular velocity correction real_t len = velrelOrthog.length(); - if (len > real_t(0.00001)) - { + if (len > real_t(0.00001)) { Vector3 normal = velrelOrthog.normalized(); real_t denom = A->compute_angular_impulse_denominator(normal) + B->compute_angular_impulse_denominator(normal); - velrelOrthog *= (real_t(1.)/denom) * m_dampingOrthoAng * m_softnessOrthoAng; + velrelOrthog *= (real_t(1.) / denom) * m_dampingOrthoAng * m_softnessOrthoAng; } //solve angular positional correction - Vector3 angularError = axisA.cross(axisB) *(real_t(1.)/p_step); + Vector3 angularError = axisA.cross(axisB) * (real_t(1.) / p_step); real_t len2 = angularError.length(); - if (len2>real_t(0.00001)) - { + if (len2 > real_t(0.00001)) { Vector3 normal2 = angularError.normalized(); real_t denom2 = A->compute_angular_impulse_denominator(normal2) + B->compute_angular_impulse_denominator(normal2); - angularError *= (real_t(1.)/denom2) * m_restitutionOrthoAng * m_softnessOrthoAng; + angularError *= (real_t(1.) / denom2) * m_restitutionOrthoAng * m_softnessOrthoAng; } // apply impulse - A->apply_torque_impulse(-velrelOrthog+angularError); - B->apply_torque_impulse(velrelOrthog-angularError); + A->apply_torque_impulse(-velrelOrthog + angularError); + B->apply_torque_impulse(velrelOrthog - angularError); real_t impulseMag; //solve angular limits - if(m_solveAngLim) - { + if (m_solveAngLim) { impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingLimAng + m_angDepth * m_restitutionLimAng / p_step; impulseMag *= m_kAngle * m_softnessLimAng; - } - else - { + } else { impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingDirAng + m_angDepth * m_restitutionDirAng / p_step; impulseMag *= m_kAngle * m_softnessDirAng; } @@ -272,10 +248,8 @@ void SliderJointSW::solve(real_t p_step) { A->apply_torque_impulse(impulse); B->apply_torque_impulse(-impulse); //apply angular motor - if(m_poweredAngMotor) - { - if(m_accumulatedAngMotorImpulse < m_maxAngMotorForce) - { + if (m_poweredAngMotor) { + if (m_accumulatedAngMotorImpulse < m_maxAngMotorForce) { Vector3 velrel = angVelAroundAxisA - angVelAroundAxisB; real_t projRelVel = velrel.dot(axisA); @@ -285,17 +259,13 @@ void SliderJointSW::solve(real_t p_step) { real_t angImpulse = m_kAngle * motor_relvel; // clamp accumulated impulse real_t new_acc = m_accumulatedAngMotorImpulse + Math::abs(angImpulse); - if(new_acc > m_maxAngMotorForce) - { + if (new_acc > m_maxAngMotorForce) { new_acc = m_maxAngMotorForce; } - real_t del = new_acc - m_accumulatedAngMotorImpulse; - if(angImpulse < real_t(0.0)) - { + real_t del = new_acc - m_accumulatedAngMotorImpulse; + if (angImpulse < real_t(0.0)) { angImpulse = -del; - } - else - { + } else { angImpulse = del; } m_accumulatedAngMotorImpulse = new_acc; @@ -311,96 +281,75 @@ void SliderJointSW::solve(real_t p_step) { //----------------------------------------------------------------------------- -void SliderJointSW::calculateTransforms(void){ - m_calculatedTransformA = A->get_transform() * m_frameInA ; +void SliderJointSW::calculateTransforms(void) { + m_calculatedTransformA = A->get_transform() * m_frameInA; m_calculatedTransformB = B->get_transform() * m_frameInB; m_realPivotAInW = m_calculatedTransformA.origin; m_realPivotBInW = m_calculatedTransformB.origin; m_sliderAxis = m_calculatedTransformA.basis.get_axis(0); // along X m_delta = m_realPivotBInW - m_realPivotAInW; m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis; - Vector3 normalWorld; - int i; - //linear part - for(i = 0; i < 3; i++) - { + Vector3 normalWorld; + int i; + //linear part + for (i = 0; i < 3; i++) { normalWorld = m_calculatedTransformA.basis.get_axis(i); m_depth[i] = m_delta.dot(normalWorld); - } + } } // SliderJointSW::calculateTransforms() //----------------------------------------------------------------------------- -void SliderJointSW::testLinLimits(void) -{ +void SliderJointSW::testLinLimits(void) { m_solveLinLim = false; m_linPos = m_depth[0]; - if(m_lowerLinLimit <= m_upperLinLimit) - { - if(m_depth[0] > m_upperLinLimit) - { + if (m_lowerLinLimit <= m_upperLinLimit) { + if (m_depth[0] > m_upperLinLimit) { m_depth[0] -= m_upperLinLimit; m_solveLinLim = true; - } - else if(m_depth[0] < m_lowerLinLimit) - { + } else if (m_depth[0] < m_lowerLinLimit) { m_depth[0] -= m_lowerLinLimit; m_solveLinLim = true; - } - else - { + } else { m_depth[0] = real_t(0.); } - } - else - { + } else { m_depth[0] = real_t(0.); } } // SliderJointSW::testLinLimits() //----------------------------------------------------------------------------- - -void SliderJointSW::testAngLimits(void) -{ +void SliderJointSW::testAngLimits(void) { m_angDepth = real_t(0.); m_solveAngLim = false; - if(m_lowerAngLimit <= m_upperAngLimit) - { + if (m_lowerAngLimit <= m_upperAngLimit) { const Vector3 axisA0 = m_calculatedTransformA.basis.get_axis(1); const Vector3 axisA1 = m_calculatedTransformA.basis.get_axis(2); const Vector3 axisB0 = m_calculatedTransformB.basis.get_axis(1); real_t rot = atan2fast(axisB0.dot(axisA1), axisB0.dot(axisA0)); - if(rot < m_lowerAngLimit) - { + if (rot < m_lowerAngLimit) { m_angDepth = rot - m_lowerAngLimit; m_solveAngLim = true; - } - else if(rot > m_upperAngLimit) - { + } else if (rot > m_upperAngLimit) { m_angDepth = rot - m_upperAngLimit; m_solveAngLim = true; } } } // SliderJointSW::testAngLimits() - //----------------------------------------------------------------------------- - - -Vector3 SliderJointSW::getAncorInA(void) -{ +Vector3 SliderJointSW::getAncorInA(void) { Vector3 ancorInA; ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * real_t(0.5) * m_sliderAxis; - ancorInA = A->get_transform().inverse().xform( ancorInA ); + ancorInA = A->get_transform().inverse().xform(ancorInA); return ancorInA; } // SliderJointSW::getAncorInA() //----------------------------------------------------------------------------- -Vector3 SliderJointSW::getAncorInB(void) -{ +Vector3 SliderJointSW::getAncorInB(void) { Vector3 ancorInB; ancorInB = m_frameInB.origin; return ancorInB; @@ -408,38 +357,36 @@ Vector3 SliderJointSW::getAncorInB(void) void SliderJointSW::set_param(PhysicsServer::SliderJointParam p_param, real_t p_value) { - switch(p_param) { - case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER: m_upperLinLimit=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER: m_lowerLinLimit=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: m_softnessLimLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: m_restitutionLimLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: m_dampingLimLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: m_softnessDirLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: m_restitutionDirLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING: m_dampingDirLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoLin=p_value; break; - case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: m_dampingOrthoLin=p_value; break; - - case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: m_upperAngLimit=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: m_lowerAngLimit=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: m_softnessLimAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: m_restitutionLimAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: m_dampingLimAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: m_softnessDirAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: m_restitutionDirAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: m_dampingDirAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoAng=p_value; break; - case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: m_dampingOrthoAng=p_value; break; - + switch (p_param) { + case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER: m_upperLinLimit = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER: m_lowerLinLimit = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: m_softnessLimLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: m_restitutionLimLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: m_dampingLimLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: m_softnessDirLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: m_restitutionDirLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING: m_dampingDirLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoLin = p_value; break; + case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: m_dampingOrthoLin = p_value; break; + + case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: m_upperAngLimit = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: m_lowerAngLimit = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: m_softnessLimAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: m_restitutionLimAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: m_dampingLimAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: m_softnessDirAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: m_restitutionDirAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: m_dampingDirAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoAng = p_value; break; + case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: m_dampingOrthoAng = p_value; break; } - } real_t SliderJointSW::get_param(PhysicsServer::SliderJointParam p_param) const { - switch(p_param) { + switch (p_param) { case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER: return m_upperLinLimit; case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER: return m_lowerLinLimit; case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: return m_softnessLimLin; @@ -463,11 +410,7 @@ real_t SliderJointSW::get_param(PhysicsServer::SliderJointParam p_param) const { case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: return m_softnessOrthoAng; case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: return m_restitutionOrthoAng; case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: return m_dampingOrthoAng; - } return 0; - } - - diff --git a/servers/physics/joints/slider_joint_sw.h b/servers/physics/joints/slider_joint_sw.h index d01038df59..faf36bfe9e 100644 --- a/servers/physics/joints/slider_joint_sw.h +++ b/servers/physics/joints/slider_joint_sw.h @@ -34,9 +34,8 @@ Adapted to Godot from the Bullet library. #ifndef SLIDER_JOINT_SW_H #define SLIDER_JOINT_SW_H -#include "servers/physics/joints_sw.h" #include "servers/physics/joints/jacobian_entry_sw.h" - +#include "servers/physics/joints_sw.h" /* Bullet Continuous Collision Detection and Physics Library @@ -59,15 +58,14 @@ April 04, 2008 */ -#define SLIDER_CONSTRAINT_DEF_SOFTNESS (real_t(1.0)) -#define SLIDER_CONSTRAINT_DEF_DAMPING (real_t(1.0)) -#define SLIDER_CONSTRAINT_DEF_RESTITUTION (real_t(0.7)) +#define SLIDER_CONSTRAINT_DEF_SOFTNESS (real_t(1.0)) +#define SLIDER_CONSTRAINT_DEF_DAMPING (real_t(1.0)) +#define SLIDER_CONSTRAINT_DEF_RESTITUTION (real_t(0.7)) //----------------------------------------------------------------------------- class SliderJointSW : public JointSW { protected: - union { struct { BodySW *A; @@ -77,8 +75,8 @@ protected: BodySW *_arr[2]; }; - Transform m_frameInA; - Transform m_frameInB; + Transform m_frameInA; + Transform m_frameInB; // linear limits real_t m_lowerLinLimit; @@ -115,14 +113,14 @@ protected: bool m_solveLinLim; bool m_solveAngLim; - JacobianEntrySW m_jacLin[3]; - real_t m_jacLinDiagABInv[3]; + JacobianEntrySW m_jacLin[3]; + real_t m_jacLinDiagABInv[3]; - JacobianEntrySW m_jacAng[3]; + JacobianEntrySW m_jacAng[3]; real_t m_timeStep; - Transform m_calculatedTransformA; - Transform m_calculatedTransformB; + Transform m_calculatedTransformA; + Transform m_calculatedTransformB; Vector3 m_sliderAxis; Vector3 m_realPivotAInW; @@ -138,45 +136,46 @@ protected: real_t m_angDepth; real_t m_kAngle; - bool m_poweredLinMotor; - real_t m_targetLinMotorVelocity; - real_t m_maxLinMotorForce; - real_t m_accumulatedLinMotorImpulse; + bool m_poweredLinMotor; + real_t m_targetLinMotorVelocity; + real_t m_maxLinMotorForce; + real_t m_accumulatedLinMotorImpulse; - bool m_poweredAngMotor; - real_t m_targetAngMotorVelocity; - real_t m_maxAngMotorForce; - real_t m_accumulatedAngMotorImpulse; + bool m_poweredAngMotor; + real_t m_targetAngMotorVelocity; + real_t m_maxAngMotorForce; + real_t m_accumulatedAngMotorImpulse; //------------------------ void initParams(); + public: // constructors - SliderJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB); - //SliderJointSW(); + SliderJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB); + //SliderJointSW(); // overrides // access - const BodySW* getRigidBodyA() const { return A; } - const BodySW* getRigidBodyB() const { return B; } - const Transform & getCalculatedTransformA() const { return m_calculatedTransformA; } - const Transform & getCalculatedTransformB() const { return m_calculatedTransformB; } - const Transform & getFrameOffsetA() const { return m_frameInA; } - const Transform & getFrameOffsetB() const { return m_frameInB; } - Transform & getFrameOffsetA() { return m_frameInA; } - Transform & getFrameOffsetB() { return m_frameInB; } - real_t getLowerLinLimit() { return m_lowerLinLimit; } - void setLowerLinLimit(real_t lowerLimit) { m_lowerLinLimit = lowerLimit; } - real_t getUpperLinLimit() { return m_upperLinLimit; } - void setUpperLinLimit(real_t upperLimit) { m_upperLinLimit = upperLimit; } - real_t getLowerAngLimit() { return m_lowerAngLimit; } - void setLowerAngLimit(real_t lowerLimit) { m_lowerAngLimit = lowerLimit; } - real_t getUpperAngLimit() { return m_upperAngLimit; } - void setUpperAngLimit(real_t upperLimit) { m_upperAngLimit = upperLimit; } + const BodySW *getRigidBodyA() const { return A; } + const BodySW *getRigidBodyB() const { return B; } + const Transform &getCalculatedTransformA() const { return m_calculatedTransformA; } + const Transform &getCalculatedTransformB() const { return m_calculatedTransformB; } + const Transform &getFrameOffsetA() const { return m_frameInA; } + const Transform &getFrameOffsetB() const { return m_frameInB; } + Transform &getFrameOffsetA() { return m_frameInA; } + Transform &getFrameOffsetB() { return m_frameInB; } + real_t getLowerLinLimit() { return m_lowerLinLimit; } + void setLowerLinLimit(real_t lowerLimit) { m_lowerLinLimit = lowerLimit; } + real_t getUpperLinLimit() { return m_upperLinLimit; } + void setUpperLinLimit(real_t upperLimit) { m_upperLinLimit = upperLimit; } + real_t getLowerAngLimit() { return m_lowerAngLimit; } + void setLowerAngLimit(real_t lowerLimit) { m_lowerAngLimit = lowerLimit; } + real_t getUpperAngLimit() { return m_upperAngLimit; } + void setUpperAngLimit(real_t upperLimit) { m_upperAngLimit = upperLimit; } real_t getSoftnessDirLin() { return m_softnessDirLin; } real_t getRestitutionDirLin() { return m_restitutionDirLin; } - real_t getDampingDirLin() { return m_dampingDirLin ; } + real_t getDampingDirLin() { return m_dampingDirLin; } real_t getSoftnessDirAng() { return m_softnessDirAng; } real_t getRestitutionDirAng() { return m_restitutionDirAng; } real_t getDampingDirAng() { return m_dampingDirAng; } @@ -230,9 +229,9 @@ public: bool getSolveAngLimit() { return m_solveAngLim; } real_t getAngDepth() { return m_angDepth; } // shared code used by ODE solver - void calculateTransforms(void); - void testLinLimits(void); - void testAngLimits(void); + void calculateTransforms(void); + void testLinLimits(void); + void testAngLimits(void); // access for PE Solver Vector3 getAncorInA(void); Vector3 getAncorInB(void); @@ -244,8 +243,6 @@ public: void solve(real_t p_step); virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_SLIDER; } - }; - #endif // SLIDER_JOINT_SW_H diff --git a/servers/physics/joints_sw.h b/servers/physics/joints_sw.h index c87c86b599..0f637faf79 100644 --- a/servers/physics/joints_sw.h +++ b/servers/physics/joints_sw.h @@ -29,19 +29,16 @@ #ifndef JOINTS_SW_H #define JOINTS_SW_H -#include "constraint_sw.h" #include "body_sw.h" - +#include "constraint_sw.h" class JointSW : public ConstraintSW { - public: - - virtual PhysicsServer::JointType get_type() const=0; - _FORCE_INLINE_ JointSW(BodySW **p_body_ptr=NULL,int p_body_count=0) : ConstraintSW(p_body_ptr,p_body_count) { + virtual PhysicsServer::JointType get_type() const = 0; + _FORCE_INLINE_ JointSW(BodySW **p_body_ptr = NULL, int p_body_count = 0) + : ConstraintSW(p_body_ptr, p_body_count) { } - }; #endif // JOINTS_SW_H diff --git a/servers/physics/physics_server_sw.cpp b/servers/physics/physics_server_sw.cpp index 67e3b27852..37be0a8a1c 100644 --- a/servers/physics/physics_server_sw.cpp +++ b/servers/physics/physics_server_sw.cpp @@ -29,57 +29,56 @@ #include "physics_server_sw.h" #include "broad_phase_basic.h" #include "broad_phase_octree.h" -#include "joints/pin_joint_sw.h" -#include "joints/hinge_joint_sw.h" -#include "joints/slider_joint_sw.h" #include "joints/cone_twist_joint_sw.h" #include "joints/generic_6dof_joint_sw.h" -#include "script_language.h" +#include "joints/hinge_joint_sw.h" +#include "joints/pin_joint_sw.h" +#include "joints/slider_joint_sw.h" #include "os/os.h" +#include "script_language.h" RID PhysicsServerSW::shape_create(ShapeType p_shape) { - ShapeSW *shape=NULL; - switch(p_shape) { + ShapeSW *shape = NULL; + switch (p_shape) { case SHAPE_PLANE: { - shape=memnew( PlaneShapeSW ); + shape = memnew(PlaneShapeSW); } break; case SHAPE_RAY: { - shape=memnew( RayShapeSW ); + shape = memnew(RayShapeSW); } break; case SHAPE_SPHERE: { - shape=memnew( SphereShapeSW); + shape = memnew(SphereShapeSW); } break; case SHAPE_BOX: { - shape=memnew( BoxShapeSW); + shape = memnew(BoxShapeSW); } break; case SHAPE_CAPSULE: { - shape=memnew( CapsuleShapeSW ); + shape = memnew(CapsuleShapeSW); } break; case SHAPE_CONVEX_POLYGON: { - shape=memnew( ConvexPolygonShapeSW ); + shape = memnew(ConvexPolygonShapeSW); } break; case SHAPE_CONCAVE_POLYGON: { - shape=memnew( ConcavePolygonShapeSW ); + shape = memnew(ConcavePolygonShapeSW); } break; case SHAPE_HEIGHTMAP: { - shape=memnew( HeightMapShapeSW ); + shape = memnew(HeightMapShapeSW); } break; case SHAPE_CUSTOM: { ERR_FAIL_V(RID()); } break; - } RID id = shape_owner.make_rid(shape); @@ -88,71 +87,62 @@ RID PhysicsServerSW::shape_create(ShapeType p_shape) { return id; }; -void PhysicsServerSW::shape_set_data(RID p_shape, const Variant& p_data) { +void PhysicsServerSW::shape_set_data(RID p_shape, const Variant &p_data) { ShapeSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); shape->set_data(p_data); - - }; - void PhysicsServerSW::shape_set_custom_solver_bias(RID p_shape, real_t p_bias) { ShapeSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); shape->set_custom_bias(p_bias); - } - PhysicsServer::ShapeType PhysicsServerSW::shape_get_type(RID p_shape) const { const ShapeSW *shape = shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,SHAPE_CUSTOM); + ERR_FAIL_COND_V(!shape, SHAPE_CUSTOM); return shape->get_type(); - }; Variant PhysicsServerSW::shape_get_data(RID p_shape) const { const ShapeSW *shape = shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,Variant()); - ERR_FAIL_COND_V(!shape->is_configured(),Variant()); + ERR_FAIL_COND_V(!shape, Variant()); + ERR_FAIL_COND_V(!shape->is_configured(), Variant()); return shape->get_data(); - }; real_t PhysicsServerSW::shape_get_custom_solver_bias(RID p_shape) const { const ShapeSW *shape = shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ERR_FAIL_COND_V(!shape, 0); return shape->get_custom_bias(); - } - RID PhysicsServerSW::space_create() { - SpaceSW *space = memnew( SpaceSW ); + SpaceSW *space = memnew(SpaceSW); RID id = space_owner.make_rid(space); space->set_self(id); RID area_id = area_create(); AreaSW *area = area_owner.get(area_id); - ERR_FAIL_COND_V(!area,RID()); + ERR_FAIL_COND_V(!area, RID()); space->set_default_area(area); area->set_space(space); area->set_priority(-1); RID sgb = body_create(); - body_set_space(sgb,id); - body_set_mode(sgb,BODY_MODE_STATIC); + body_set_space(sgb, id); + body_set_mode(sgb, BODY_MODE_STATIC); space->set_static_global_body(sgb); return id; }; -void PhysicsServerSW::space_set_active(RID p_space,bool p_active) { +void PhysicsServerSW::space_set_active(RID p_space, bool p_active) { SpaceSW *space = space_owner.get(p_space); ERR_FAIL_COND(!space); @@ -165,70 +155,63 @@ void PhysicsServerSW::space_set_active(RID p_space,bool p_active) { bool PhysicsServerSW::space_is_active(RID p_space) const { const SpaceSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,false); + ERR_FAIL_COND_V(!space, false); return active_spaces.has(space); - } -void PhysicsServerSW::space_set_param(RID p_space,SpaceParameter p_param, real_t p_value) { +void PhysicsServerSW::space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) { SpaceSW *space = space_owner.get(p_space); ERR_FAIL_COND(!space); - space->set_param(p_param,p_value); - + space->set_param(p_param, p_value); } -real_t PhysicsServerSW::space_get_param(RID p_space,SpaceParameter p_param) const { +real_t PhysicsServerSW::space_get_param(RID p_space, SpaceParameter p_param) const { const SpaceSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,0); + ERR_FAIL_COND_V(!space, 0); return space->get_param(p_param); } -PhysicsDirectSpaceState* PhysicsServerSW::space_get_direct_state(RID p_space) { +PhysicsDirectSpaceState *PhysicsServerSW::space_get_direct_state(RID p_space) { SpaceSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,NULL); + ERR_FAIL_COND_V(!space, NULL); if (!doing_sync || space->is_locked()) { ERR_EXPLAIN("Space state is inaccesible right now, wait for iteration or fixed process notification."); ERR_FAIL_V(NULL); - - } return space->get_direct_state(); } -void PhysicsServerSW::space_set_debug_contacts(RID p_space,int p_max_contacts) { +void PhysicsServerSW::space_set_debug_contacts(RID p_space, int p_max_contacts) { SpaceSW *space = space_owner.get(p_space); ERR_FAIL_COND(!space); space->set_debug_contacts(p_max_contacts); - } Vector<Vector3> PhysicsServerSW::space_get_contacts(RID p_space) const { SpaceSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,Vector<Vector3>()); + ERR_FAIL_COND_V(!space, Vector<Vector3>()); return space->get_debug_contacts(); - } int PhysicsServerSW::space_get_contact_count(RID p_space) const { SpaceSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,0); + ERR_FAIL_COND_V(!space, 0); return space->get_debug_contact_count(); - } RID PhysicsServerSW::area_create() { - AreaSW *area = memnew( AreaSW ); + AreaSW *area = memnew(AreaSW); RID rid = area_owner.make_rid(area); area->set_self(rid); return rid; @@ -238,20 +221,19 @@ void PhysicsServerSW::area_set_space(RID p_area, RID p_space) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - SpaceSW *space=NULL; + SpaceSW *space = NULL; if (p_space.is_valid()) { space = space_owner.get(p_space); ERR_FAIL_COND(!space); } area->set_space(space); - }; RID PhysicsServerSW::area_get_space(RID p_area) const { AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,RID()); + ERR_FAIL_COND_V(!area, RID()); SpaceSW *space = area->get_space(); if (!space) @@ -261,7 +243,6 @@ RID PhysicsServerSW::area_get_space(RID p_area) const { void PhysicsServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) { - AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -271,13 +252,12 @@ void PhysicsServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverride PhysicsServer::AreaSpaceOverrideMode PhysicsServerSW::area_get_space_override_mode(RID p_area) const { const AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,AREA_SPACE_OVERRIDE_DISABLED); + ERR_FAIL_COND_V(!area, AREA_SPACE_OVERRIDE_DISABLED); return area->get_space_override_mode(); } - -void PhysicsServerSW::area_add_shape(RID p_area, RID p_shape, const Transform& p_transform) { +void PhysicsServerSW::area_add_shape(RID p_area, RID p_shape, const Transform &p_transform) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -285,11 +265,10 @@ void PhysicsServerSW::area_add_shape(RID p_area, RID p_shape, const Transform& p ShapeSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); - area->add_shape(shape,p_transform); - + area->add_shape(shape, p_transform); } -void PhysicsServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) { +void PhysicsServerSW::area_set_shape(RID p_area, int p_shape_idx, RID p_shape) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -298,39 +277,37 @@ void PhysicsServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) { ERR_FAIL_COND(!shape); ERR_FAIL_COND(!shape->is_configured()); - area->set_shape(p_shape_idx,shape); - + area->set_shape(p_shape_idx, shape); } -void PhysicsServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform& p_transform) { +void PhysicsServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_shape_transform(p_shape_idx,p_transform); + area->set_shape_transform(p_shape_idx, p_transform); } int PhysicsServerSW::area_get_shape_count(RID p_area) const { AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,-1); + ERR_FAIL_COND_V(!area, -1); return area->get_shape_count(); - } RID PhysicsServerSW::area_get_shape(RID p_area, int p_shape_idx) const { AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,RID()); + ERR_FAIL_COND_V(!area, RID()); ShapeSW *shape = area->get_shape(p_shape_idx); - ERR_FAIL_COND_V(!shape,RID()); + ERR_FAIL_COND_V(!shape, RID()); return shape->get_self(); } Transform PhysicsServerSW::area_get_shape_transform(RID p_area, int p_shape_idx) const { AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,Transform()); + ERR_FAIL_COND_V(!area, Transform()); return area->get_shape_transform(p_shape_idx); } @@ -348,65 +325,57 @@ void PhysicsServerSW::area_clear_shapes(RID p_area) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - while(area->get_shape_count()) + while (area->get_shape_count()) area->remove_shape(0); - } -void PhysicsServerSW::area_attach_object_instance_ID(RID p_area,ObjectID p_ID) { +void PhysicsServerSW::area_attach_object_instance_ID(RID p_area, ObjectID p_ID) { if (space_owner.owns(p_area)) { - SpaceSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + SpaceSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_instance_id(p_ID); - } ObjectID PhysicsServerSW::area_get_object_instance_ID(RID p_area) const { if (space_owner.owns(p_area)) { - SpaceSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + SpaceSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,0); + ERR_FAIL_COND_V(!area, 0); return area->get_instance_id(); - - } - -void PhysicsServerSW::area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value) { +void PhysicsServerSW::area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) { if (space_owner.owns(p_area)) { - SpaceSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + SpaceSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_param(p_param,p_value); - + area->set_param(p_param, p_value); }; - -void PhysicsServerSW::area_set_transform(RID p_area, const Transform& p_transform) { +void PhysicsServerSW::area_set_transform(RID p_area, const Transform &p_transform) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_transform(p_transform); - }; -Variant PhysicsServerSW::area_get_param(RID p_area,AreaParameter p_param) const { +Variant PhysicsServerSW::area_get_param(RID p_area, AreaParameter p_param) const { if (space_owner.owns(p_area)) { - SpaceSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + SpaceSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,Variant()); + ERR_FAIL_COND_V(!area, Variant()); return area->get_param(p_param); }; @@ -414,12 +383,12 @@ Variant PhysicsServerSW::area_get_param(RID p_area,AreaParameter p_param) const Transform PhysicsServerSW::area_get_transform(RID p_area) const { AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,Transform()); + ERR_FAIL_COND_V(!area, Transform()); return area->get_transform(); }; -void PhysicsServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) { +void PhysicsServerSW::area_set_layer_mask(RID p_area, uint32_t p_mask) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -427,7 +396,7 @@ void PhysicsServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) { area->set_layer_mask(p_mask); } -void PhysicsServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) { +void PhysicsServerSW::area_set_collision_mask(RID p_area, uint32_t p_mask) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -435,7 +404,7 @@ void PhysicsServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) { area->set_collision_mask(p_mask); } -void PhysicsServerSW::area_set_monitorable(RID p_area,bool p_monitorable) { +void PhysicsServerSW::area_set_monitorable(RID p_area, bool p_monitorable) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -443,81 +412,73 @@ void PhysicsServerSW::area_set_monitorable(RID p_area,bool p_monitorable) { area->set_monitorable(p_monitorable); } -void PhysicsServerSW::area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) { +void PhysicsServerSW::area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method); - - + area->set_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method); } -void PhysicsServerSW::area_set_ray_pickable(RID p_area,bool p_enable) { +void PhysicsServerSW::area_set_ray_pickable(RID p_area, bool p_enable) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_ray_pickable(p_enable); - } -bool PhysicsServerSW::area_is_ray_pickable(RID p_area) const{ +bool PhysicsServerSW::area_is_ray_pickable(RID p_area) const { AreaSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,false); + ERR_FAIL_COND_V(!area, false); return area->is_ray_pickable(); - } - -void PhysicsServerSW::area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) { - +void PhysicsServerSW::area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) { AreaSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_area_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method); + area->set_area_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method); } /* BODY API */ -RID PhysicsServerSW::body_create(BodyMode p_mode,bool p_init_sleeping) { +RID PhysicsServerSW::body_create(BodyMode p_mode, bool p_init_sleeping) { - BodySW *body = memnew( BodySW ); - if (p_mode!=BODY_MODE_RIGID) + BodySW *body = memnew(BodySW); + if (p_mode != BODY_MODE_RIGID) body->set_mode(p_mode); if (p_init_sleeping) - body->set_state(BODY_STATE_SLEEPING,p_init_sleeping); + body->set_state(BODY_STATE_SLEEPING, p_init_sleeping); RID rid = body_owner.make_rid(body); body->set_self(rid); return rid; }; - void PhysicsServerSW::body_set_space(RID p_body, RID p_space) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - SpaceSW *space=NULL; + SpaceSW *space = NULL; if (p_space.is_valid()) { space = space_owner.get(p_space); ERR_FAIL_COND(!space); } - if (body->get_space()==space) + if (body->get_space() == space) return; //pointles body->set_space(space); - }; RID PhysicsServerSW::body_get_space(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,RID()); + ERR_FAIL_COND_V(!body, RID()); SpaceSW *space = body->get_space(); if (!space) @@ -525,7 +486,6 @@ RID PhysicsServerSW::body_get_space(RID p_body) const { return space->get_self(); }; - void PhysicsServerSW::body_set_mode(RID p_body, BodyMode p_mode) { BodySW *body = body_owner.get(p_body); @@ -537,12 +497,12 @@ void PhysicsServerSW::body_set_mode(RID p_body, BodyMode p_mode) { PhysicsServer::BodyMode PhysicsServerSW::body_get_mode(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,BODY_MODE_STATIC); + ERR_FAIL_COND_V(!body, BODY_MODE_STATIC); return body->get_mode(); }; -void PhysicsServerSW::body_add_shape(RID p_body, RID p_shape, const Transform& p_transform) { +void PhysicsServerSW::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -550,11 +510,10 @@ void PhysicsServerSW::body_add_shape(RID p_body, RID p_shape, const Transform& p ShapeSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); - body->add_shape(shape,p_transform); - + body->add_shape(shape, p_transform); } -void PhysicsServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) { +void PhysicsServerSW::body_set_shape(RID p_body, int p_shape_idx, RID p_shape) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -563,59 +522,55 @@ void PhysicsServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) { ERR_FAIL_COND(!shape); ERR_FAIL_COND(!shape->is_configured()); - body->set_shape(p_shape_idx,shape); - + body->set_shape(p_shape_idx, shape); } -void PhysicsServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform& p_transform) { +void PhysicsServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_shape_transform(p_shape_idx,p_transform); + body->set_shape_transform(p_shape_idx, p_transform); } int PhysicsServerSW::body_get_shape_count(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,-1); + ERR_FAIL_COND_V(!body, -1); return body->get_shape_count(); - } RID PhysicsServerSW::body_get_shape(RID p_body, int p_shape_idx) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,RID()); + ERR_FAIL_COND_V(!body, RID()); ShapeSW *shape = body->get_shape(p_shape_idx); - ERR_FAIL_COND_V(!shape,RID()); + ERR_FAIL_COND_V(!shape, RID()); return shape->get_self(); } -void PhysicsServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable) { +void PhysicsServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - ERR_FAIL_INDEX(p_shape_idx,body->get_shape_count()); - body->set_shape_as_trigger(p_shape_idx,p_enable); - + ERR_FAIL_INDEX(p_shape_idx, body->get_shape_count()); + body->set_shape_as_trigger(p_shape_idx, p_enable); } -bool PhysicsServerSW::body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const{ +bool PhysicsServerSW::body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); - ERR_FAIL_INDEX_V(p_shape_idx,body->get_shape_count(),false); + ERR_FAIL_COND_V(!body, false); + ERR_FAIL_INDEX_V(p_shape_idx, body->get_shape_count(), false); return body->is_shape_set_as_trigger(p_shape_idx); } - Transform PhysicsServerSW::body_get_shape_transform(RID p_body, int p_shape_idx) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Transform()); + ERR_FAIL_COND_V(!body, Transform()); return body->get_shape_transform(p_shape_idx); } @@ -633,24 +588,22 @@ void PhysicsServerSW::body_clear_shapes(RID p_body) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - while(body->get_shape_count()) + while (body->get_shape_count()) body->remove_shape(0); - } -void PhysicsServerSW::body_set_enable_continuous_collision_detection(RID p_body,bool p_enable) { +void PhysicsServerSW::body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_continuous_collision_detection(p_enable); - } bool PhysicsServerSW::body_is_continuous_collision_detection_enabled(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); + ERR_FAIL_COND_V(!body, false); return body->is_continuous_collision_detection_enabled(); } @@ -662,16 +615,14 @@ void PhysicsServerSW::body_set_layer_mask(RID p_body, uint32_t p_mask) { body->set_layer_mask(p_mask); body->wakeup(); - } -uint32_t PhysicsServerSW::body_get_layer_mask(RID p_body, uint32_t p_mask) const{ +uint32_t PhysicsServerSW::body_get_layer_mask(RID p_body, uint32_t p_mask) const { const BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_layer_mask(); - } void PhysicsServerSW::body_set_collision_mask(RID p_body, uint32_t p_mask) { @@ -681,48 +632,42 @@ void PhysicsServerSW::body_set_collision_mask(RID p_body, uint32_t p_mask) { body->set_collision_mask(p_mask); body->wakeup(); - } -uint32_t PhysicsServerSW::body_get_collision_mask(RID p_body, uint32_t p_mask) const{ +uint32_t PhysicsServerSW::body_get_collision_mask(RID p_body, uint32_t p_mask) const { const BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_collision_mask(); - } - -void PhysicsServerSW::body_attach_object_instance_ID(RID p_body,uint32_t p_ID) { +void PhysicsServerSW::body_attach_object_instance_ID(RID p_body, uint32_t p_ID) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_instance_id(p_ID); - }; uint32_t PhysicsServerSW::body_get_object_instance_ID(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_instance_id(); }; - void PhysicsServerSW::body_set_user_flags(RID p_body, uint32_t p_flags) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - }; uint32_t PhysicsServerSW::body_get_user_flags(RID p_body, uint32_t p_flags) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return 0; }; @@ -732,38 +677,34 @@ void PhysicsServerSW::body_set_param(RID p_body, BodyParameter p_param, real_t p BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_param(p_param,p_value); + body->set_param(p_param, p_value); }; real_t PhysicsServerSW::body_get_param(RID p_body, BodyParameter p_param) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_param(p_param); }; - - -void PhysicsServerSW::body_set_state(RID p_body, BodyState p_state, const Variant& p_variant) { +void PhysicsServerSW::body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_state(p_state,p_variant); - + body->set_state(p_state, p_variant); }; Variant PhysicsServerSW::body_get_state(RID p_body, BodyState p_state) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Variant()); + ERR_FAIL_COND_V(!body, Variant()); return body->get_state(p_state); }; - -void PhysicsServerSW::body_set_applied_force(RID p_body, const Vector3& p_force) { +void PhysicsServerSW::body_set_applied_force(RID p_body, const Vector3 &p_force) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -775,11 +716,11 @@ void PhysicsServerSW::body_set_applied_force(RID p_body, const Vector3& p_force) Vector3 PhysicsServerSW::body_get_applied_force(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Vector3()); + ERR_FAIL_COND_V(!body, Vector3()); return body->get_applied_force(); }; -void PhysicsServerSW::body_set_applied_torque(RID p_body, const Vector3& p_torque) { +void PhysicsServerSW::body_set_applied_torque(RID p_body, const Vector3 &p_torque) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -791,21 +732,21 @@ void PhysicsServerSW::body_set_applied_torque(RID p_body, const Vector3& p_torqu Vector3 PhysicsServerSW::body_get_applied_torque(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Vector3()); + ERR_FAIL_COND_V(!body, Vector3()); return body->get_applied_torque(); }; -void PhysicsServerSW::body_apply_impulse(RID p_body, const Vector3& p_pos, const Vector3& p_impulse) { +void PhysicsServerSW::body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->apply_impulse(p_pos,p_impulse); + body->apply_impulse(p_pos, p_impulse); body->wakeup(); }; -void PhysicsServerSW::body_apply_torque_impulse(RID p_body, const Vector3& p_impulse) { +void PhysicsServerSW::body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -814,40 +755,34 @@ void PhysicsServerSW::body_apply_torque_impulse(RID p_body, const Vector3& p_imp body->wakeup(); }; -void PhysicsServerSW::body_set_axis_velocity(RID p_body, const Vector3& p_axis_velocity) { +void PhysicsServerSW::body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); Vector3 v = body->get_linear_velocity(); Vector3 axis = p_axis_velocity.normalized(); - v-=axis*axis.dot(v); - v+=p_axis_velocity; + v -= axis * axis.dot(v); + v += p_axis_velocity; body->set_linear_velocity(v); body->wakeup(); - }; - -void PhysicsServerSW::body_set_axis_lock(RID p_body,BodyAxisLock p_lock) { +void PhysicsServerSW::body_set_axis_lock(RID p_body, BodyAxisLock p_lock) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_axis_lock(p_lock); body->wakeup(); - } -PhysicsServerSW::BodyAxisLock PhysicsServerSW::body_get_axis_lock(RID p_body) const{ +PhysicsServerSW::BodyAxisLock PhysicsServerSW::body_get_axis_lock(RID p_body) const { const BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,BODY_AXIS_LOCK_DISABLED); + ERR_FAIL_COND_V(!body, BODY_AXIS_LOCK_DISABLED); return body->get_axis_lock(); - } - - void PhysicsServerSW::body_add_collision_exception(RID p_body, RID p_body_b) { BodySW *body = body_owner.get(p_body); @@ -855,7 +790,6 @@ void PhysicsServerSW::body_add_collision_exception(RID p_body, RID p_body_b) { body->add_exception(p_body_b); body->wakeup(); - }; void PhysicsServerSW::body_remove_collision_exception(RID p_body, RID p_body_b) { @@ -865,7 +799,6 @@ void PhysicsServerSW::body_remove_collision_exception(RID p_body, RID p_body_b) body->remove_exception(p_body_b); body->wakeup(); - }; void PhysicsServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) { @@ -873,27 +806,25 @@ void PhysicsServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_exc BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - for(int i=0;i<body->get_exceptions().size();i++) { + for (int i = 0; i < body->get_exceptions().size(); i++) { p_exceptions->push_back(body->get_exceptions()[i]); } - }; void PhysicsServerSW::body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - }; real_t PhysicsServerSW::body_get_contacts_reported_depth_treshold(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return 0; }; -void PhysicsServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) { +void PhysicsServerSW::body_set_omit_force_integration(RID p_body, bool p_omit) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -904,7 +835,7 @@ void PhysicsServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) { bool PhysicsServerSW::body_is_omitting_force_integration(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); + ERR_FAIL_COND_V(!body, false); return body->get_omit_force_integration(); }; @@ -918,355 +849,333 @@ void PhysicsServerSW::body_set_max_contacts_reported(RID p_body, int p_contacts) int PhysicsServerSW::body_get_max_contacts_reported(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,-1); + ERR_FAIL_COND_V(!body, -1); return body->get_max_contacts_reported(); } -void PhysicsServerSW::body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata) { - +void PhysicsServerSW::body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_force_integration_callback(p_receiver?p_receiver->get_instance_ID():ObjectID(0),p_method,p_udata); - + body->set_force_integration_callback(p_receiver ? p_receiver->get_instance_ID() : ObjectID(0), p_method, p_udata); } -void PhysicsServerSW::body_set_ray_pickable(RID p_body,bool p_enable) { +void PhysicsServerSW::body_set_ray_pickable(RID p_body, bool p_enable) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_ray_pickable(p_enable); - } -bool PhysicsServerSW::body_is_ray_pickable(RID p_body) const{ +bool PhysicsServerSW::body_is_ray_pickable(RID p_body) const { BodySW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); + ERR_FAIL_COND_V(!body, false); return body->is_ray_pickable(); - } - /* JOINT API */ -RID PhysicsServerSW::joint_create_pin(RID p_body_A,const Vector3& p_local_A,RID p_body_B,const Vector3& p_local_B) { +RID PhysicsServerSW::joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) { BodySW *body_A = body_owner.get(p_body_A); - ERR_FAIL_COND_V(!body_A,RID()); + ERR_FAIL_COND_V(!body_A, RID()); if (!p_body_B.is_valid()) { - ERR_FAIL_COND_V(!body_A->get_space(),RID()); - p_body_B=body_A->get_space()->get_static_global_body(); + ERR_FAIL_COND_V(!body_A->get_space(), RID()); + p_body_B = body_A->get_space()->get_static_global_body(); } BodySW *body_B = body_owner.get(p_body_B); - ERR_FAIL_COND_V(!body_B,RID()); + ERR_FAIL_COND_V(!body_B, RID()); - ERR_FAIL_COND_V(body_A==body_B,RID()); + ERR_FAIL_COND_V(body_A == body_B, RID()); - JointSW *joint = memnew( PinJointSW(body_A,p_local_A,body_B,p_local_B) ); + JointSW *joint = memnew(PinJointSW(body_A, p_local_A, body_B, p_local_B)); RID rid = joint_owner.make_rid(joint); joint->set_self(rid); return rid; } -void PhysicsServerSW::pin_joint_set_param(RID p_joint,PinJointParam p_param, real_t p_value){ +void PhysicsServerSW::pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_PIN); - PinJointSW *pin_joint = static_cast<PinJointSW*>(joint); - pin_joint->set_param(p_param,p_value); - + ERR_FAIL_COND(joint->get_type() != JOINT_PIN); + PinJointSW *pin_joint = static_cast<PinJointSW *>(joint); + pin_joint->set_param(p_param, p_value); } -real_t PhysicsServerSW::pin_joint_get_param(RID p_joint,PinJointParam p_param) const{ +real_t PhysicsServerSW::pin_joint_get_param(RID p_joint, PinJointParam p_param) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,0); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_PIN,0); - PinJointSW *pin_joint = static_cast<PinJointSW*>(joint); + ERR_FAIL_COND_V(!joint, 0); + ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, 0); + PinJointSW *pin_joint = static_cast<PinJointSW *>(joint); return pin_joint->get_param(p_param); - } -void PhysicsServerSW::pin_joint_set_local_A(RID p_joint, const Vector3& p_A){ +void PhysicsServerSW::pin_joint_set_local_A(RID p_joint, const Vector3 &p_A) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_PIN); - PinJointSW *pin_joint = static_cast<PinJointSW*>(joint); + ERR_FAIL_COND(joint->get_type() != JOINT_PIN); + PinJointSW *pin_joint = static_cast<PinJointSW *>(joint); pin_joint->set_pos_A(p_A); - } -Vector3 PhysicsServerSW::pin_joint_get_local_A(RID p_joint) const{ +Vector3 PhysicsServerSW::pin_joint_get_local_A(RID p_joint) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,Vector3()); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_PIN,Vector3()); - PinJointSW *pin_joint = static_cast<PinJointSW*>(joint); + ERR_FAIL_COND_V(!joint, Vector3()); + ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, Vector3()); + PinJointSW *pin_joint = static_cast<PinJointSW *>(joint); return pin_joint->get_pos_A(); - } -void PhysicsServerSW::pin_joint_set_local_B(RID p_joint, const Vector3& p_B){ +void PhysicsServerSW::pin_joint_set_local_B(RID p_joint, const Vector3 &p_B) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_PIN); - PinJointSW *pin_joint = static_cast<PinJointSW*>(joint); + ERR_FAIL_COND(joint->get_type() != JOINT_PIN); + PinJointSW *pin_joint = static_cast<PinJointSW *>(joint); pin_joint->set_pos_B(p_B); - } -Vector3 PhysicsServerSW::pin_joint_get_local_B(RID p_joint) const{ +Vector3 PhysicsServerSW::pin_joint_get_local_B(RID p_joint) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,Vector3()); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_PIN,Vector3()); - PinJointSW *pin_joint = static_cast<PinJointSW*>(joint); + ERR_FAIL_COND_V(!joint, Vector3()); + ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, Vector3()); + PinJointSW *pin_joint = static_cast<PinJointSW *>(joint); return pin_joint->get_pos_B(); - } - -RID PhysicsServerSW::joint_create_hinge(RID p_body_A,const Transform& p_frame_A,RID p_body_B,const Transform& p_frame_B) { +RID PhysicsServerSW::joint_create_hinge(RID p_body_A, const Transform &p_frame_A, RID p_body_B, const Transform &p_frame_B) { BodySW *body_A = body_owner.get(p_body_A); - ERR_FAIL_COND_V(!body_A,RID()); + ERR_FAIL_COND_V(!body_A, RID()); if (!p_body_B.is_valid()) { - ERR_FAIL_COND_V(!body_A->get_space(),RID()); - p_body_B=body_A->get_space()->get_static_global_body(); + ERR_FAIL_COND_V(!body_A->get_space(), RID()); + p_body_B = body_A->get_space()->get_static_global_body(); } BodySW *body_B = body_owner.get(p_body_B); - ERR_FAIL_COND_V(!body_B,RID()); + ERR_FAIL_COND_V(!body_B, RID()); - ERR_FAIL_COND_V(body_A==body_B,RID()); + ERR_FAIL_COND_V(body_A == body_B, RID()); - JointSW *joint = memnew( HingeJointSW(body_A,body_B,p_frame_A,p_frame_B) ); + JointSW *joint = memnew(HingeJointSW(body_A, body_B, p_frame_A, p_frame_B)); RID rid = joint_owner.make_rid(joint); joint->set_self(rid); return rid; - } - -RID PhysicsServerSW::joint_create_hinge_simple(RID p_body_A,const Vector3& p_pivot_A,const Vector3& p_axis_A,RID p_body_B,const Vector3& p_pivot_B,const Vector3& p_axis_B) { +RID PhysicsServerSW::joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B) { BodySW *body_A = body_owner.get(p_body_A); - ERR_FAIL_COND_V(!body_A,RID()); + ERR_FAIL_COND_V(!body_A, RID()); if (!p_body_B.is_valid()) { - ERR_FAIL_COND_V(!body_A->get_space(),RID()); - p_body_B=body_A->get_space()->get_static_global_body(); + ERR_FAIL_COND_V(!body_A->get_space(), RID()); + p_body_B = body_A->get_space()->get_static_global_body(); } BodySW *body_B = body_owner.get(p_body_B); - ERR_FAIL_COND_V(!body_B,RID()); + ERR_FAIL_COND_V(!body_B, RID()); - ERR_FAIL_COND_V(body_A==body_B,RID()); + ERR_FAIL_COND_V(body_A == body_B, RID()); - JointSW *joint = memnew( HingeJointSW(body_A,body_B,p_pivot_A,p_pivot_B,p_axis_A,p_axis_B) ); + JointSW *joint = memnew(HingeJointSW(body_A, body_B, p_pivot_A, p_pivot_B, p_axis_A, p_axis_B)); RID rid = joint_owner.make_rid(joint); joint->set_self(rid); return rid; - } -void PhysicsServerSW::hinge_joint_set_param(RID p_joint,HingeJointParam p_param, real_t p_value){ +void PhysicsServerSW::hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_HINGE); - HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint); - hinge_joint->set_param(p_param,p_value); - + ERR_FAIL_COND(joint->get_type() != JOINT_HINGE); + HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint); + hinge_joint->set_param(p_param, p_value); } -real_t PhysicsServerSW::hinge_joint_get_param(RID p_joint,HingeJointParam p_param) const{ +real_t PhysicsServerSW::hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,0); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_HINGE,0); - HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint); + ERR_FAIL_COND_V(!joint, 0); + ERR_FAIL_COND_V(joint->get_type() != JOINT_HINGE, 0); + HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint); return hinge_joint->get_param(p_param); - } -void PhysicsServerSW::hinge_joint_set_flag(RID p_joint,HingeJointFlag p_flag, bool p_value){ +void PhysicsServerSW::hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_HINGE); - HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint); - hinge_joint->set_flag(p_flag,p_value); - + ERR_FAIL_COND(joint->get_type() != JOINT_HINGE); + HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint); + hinge_joint->set_flag(p_flag, p_value); } -bool PhysicsServerSW::hinge_joint_get_flag(RID p_joint,HingeJointFlag p_flag) const{ +bool PhysicsServerSW::hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,false); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_HINGE,false); - HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint); + ERR_FAIL_COND_V(!joint, false); + ERR_FAIL_COND_V(joint->get_type() != JOINT_HINGE, false); + HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint); return hinge_joint->get_flag(p_flag); } -void PhysicsServerSW::joint_set_solver_priority(RID p_joint,int p_priority) { +void PhysicsServerSW::joint_set_solver_priority(RID p_joint, int p_priority) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); joint->set_priority(p_priority); } -int PhysicsServerSW::joint_get_solver_priority(RID p_joint) const{ +int PhysicsServerSW::joint_get_solver_priority(RID p_joint) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,0); + ERR_FAIL_COND_V(!joint, 0); return joint->get_priority(); - } PhysicsServerSW::JointType PhysicsServerSW::joint_get_type(RID p_joint) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,JOINT_PIN); + ERR_FAIL_COND_V(!joint, JOINT_PIN); return joint->get_type(); } -RID PhysicsServerSW::joint_create_slider(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B) { +RID PhysicsServerSW::joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) { BodySW *body_A = body_owner.get(p_body_A); - ERR_FAIL_COND_V(!body_A,RID()); + ERR_FAIL_COND_V(!body_A, RID()); if (!p_body_B.is_valid()) { - ERR_FAIL_COND_V(!body_A->get_space(),RID()); - p_body_B=body_A->get_space()->get_static_global_body(); + ERR_FAIL_COND_V(!body_A->get_space(), RID()); + p_body_B = body_A->get_space()->get_static_global_body(); } BodySW *body_B = body_owner.get(p_body_B); - ERR_FAIL_COND_V(!body_B,RID()); + ERR_FAIL_COND_V(!body_B, RID()); - ERR_FAIL_COND_V(body_A==body_B,RID()); + ERR_FAIL_COND_V(body_A == body_B, RID()); - JointSW *joint = memnew( SliderJointSW(body_A,body_B,p_local_frame_A,p_local_frame_B) ); + JointSW *joint = memnew(SliderJointSW(body_A, body_B, p_local_frame_A, p_local_frame_B)); RID rid = joint_owner.make_rid(joint); joint->set_self(rid); return rid; } -void PhysicsServerSW::slider_joint_set_param(RID p_joint,SliderJointParam p_param, real_t p_value){ +void PhysicsServerSW::slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_SLIDER); - SliderJointSW *slider_joint = static_cast<SliderJointSW*>(joint); - slider_joint->set_param(p_param,p_value); + ERR_FAIL_COND(joint->get_type() != JOINT_SLIDER); + SliderJointSW *slider_joint = static_cast<SliderJointSW *>(joint); + slider_joint->set_param(p_param, p_value); } -real_t PhysicsServerSW::slider_joint_get_param(RID p_joint,SliderJointParam p_param) const{ +real_t PhysicsServerSW::slider_joint_get_param(RID p_joint, SliderJointParam p_param) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,0); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_CONE_TWIST,0); - SliderJointSW *slider_joint = static_cast<SliderJointSW*>(joint); + ERR_FAIL_COND_V(!joint, 0); + ERR_FAIL_COND_V(joint->get_type() != JOINT_CONE_TWIST, 0); + SliderJointSW *slider_joint = static_cast<SliderJointSW *>(joint); return slider_joint->get_param(p_param); } - -RID PhysicsServerSW::joint_create_cone_twist(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B) { +RID PhysicsServerSW::joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) { BodySW *body_A = body_owner.get(p_body_A); - ERR_FAIL_COND_V(!body_A,RID()); + ERR_FAIL_COND_V(!body_A, RID()); if (!p_body_B.is_valid()) { - ERR_FAIL_COND_V(!body_A->get_space(),RID()); - p_body_B=body_A->get_space()->get_static_global_body(); + ERR_FAIL_COND_V(!body_A->get_space(), RID()); + p_body_B = body_A->get_space()->get_static_global_body(); } BodySW *body_B = body_owner.get(p_body_B); - ERR_FAIL_COND_V(!body_B,RID()); + ERR_FAIL_COND_V(!body_B, RID()); - ERR_FAIL_COND_V(body_A==body_B,RID()); + ERR_FAIL_COND_V(body_A == body_B, RID()); - JointSW *joint = memnew( ConeTwistJointSW(body_A,body_B,p_local_frame_A,p_local_frame_B) ); + JointSW *joint = memnew(ConeTwistJointSW(body_A, body_B, p_local_frame_A, p_local_frame_B)); RID rid = joint_owner.make_rid(joint); joint->set_self(rid); return rid; } -void PhysicsServerSW::cone_twist_joint_set_param(RID p_joint,ConeTwistJointParam p_param, real_t p_value) { +void PhysicsServerSW::cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_CONE_TWIST); - ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW*>(joint); - cone_twist_joint->set_param(p_param,p_value); + ERR_FAIL_COND(joint->get_type() != JOINT_CONE_TWIST); + ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW *>(joint); + cone_twist_joint->set_param(p_param, p_value); } -real_t PhysicsServerSW::cone_twist_joint_get_param(RID p_joint,ConeTwistJointParam p_param) const { +real_t PhysicsServerSW::cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,0); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_CONE_TWIST,0); - ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW*>(joint); + ERR_FAIL_COND_V(!joint, 0); + ERR_FAIL_COND_V(joint->get_type() != JOINT_CONE_TWIST, 0); + ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW *>(joint); return cone_twist_joint->get_param(p_param); } - -RID PhysicsServerSW::joint_create_generic_6dof(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B) { +RID PhysicsServerSW::joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) { BodySW *body_A = body_owner.get(p_body_A); - ERR_FAIL_COND_V(!body_A,RID()); + ERR_FAIL_COND_V(!body_A, RID()); if (!p_body_B.is_valid()) { - ERR_FAIL_COND_V(!body_A->get_space(),RID()); - p_body_B=body_A->get_space()->get_static_global_body(); + ERR_FAIL_COND_V(!body_A->get_space(), RID()); + p_body_B = body_A->get_space()->get_static_global_body(); } BodySW *body_B = body_owner.get(p_body_B); - ERR_FAIL_COND_V(!body_B,RID()); + ERR_FAIL_COND_V(!body_B, RID()); - ERR_FAIL_COND_V(body_A==body_B,RID()); + ERR_FAIL_COND_V(body_A == body_B, RID()); - JointSW *joint = memnew( Generic6DOFJointSW(body_A,body_B,p_local_frame_A,p_local_frame_B,true) ); + JointSW *joint = memnew(Generic6DOFJointSW(body_A, body_B, p_local_frame_A, p_local_frame_B, true)); RID rid = joint_owner.make_rid(joint); joint->set_self(rid); return rid; } -void PhysicsServerSW::generic_6dof_joint_set_param(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisParam p_param, real_t p_value){ +void PhysicsServerSW::generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, real_t p_value) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_6DOF); - Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint); - generic_6dof_joint->set_param(p_axis,p_param,p_value); + ERR_FAIL_COND(joint->get_type() != JOINT_6DOF); + Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint); + generic_6dof_joint->set_param(p_axis, p_param, p_value); } -real_t PhysicsServerSW::generic_6dof_joint_get_param(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisParam p_param){ +real_t PhysicsServerSW::generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param) { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,0); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_6DOF,0); - Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint); - return generic_6dof_joint->get_param(p_axis,p_param); + ERR_FAIL_COND_V(!joint, 0); + ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, 0); + Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint); + return generic_6dof_joint->get_param(p_axis, p_param); } -void PhysicsServerSW::generic_6dof_joint_set_flag(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisFlag p_flag, bool p_enable){ +void PhysicsServerSW::generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag, bool p_enable) { JointSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - ERR_FAIL_COND(joint->get_type()!=JOINT_6DOF); - Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint); - generic_6dof_joint->set_flag(p_axis,p_flag,p_enable); + ERR_FAIL_COND(joint->get_type() != JOINT_6DOF); + Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint); + generic_6dof_joint->set_flag(p_axis, p_flag, p_enable); } -bool PhysicsServerSW::generic_6dof_joint_get_flag(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisFlag p_flag){ +bool PhysicsServerSW::generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag) { JointSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,false); - ERR_FAIL_COND_V(joint->get_type()!=JOINT_6DOF,false); - Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint); - return generic_6dof_joint->get_flag(p_axis,p_flag); + ERR_FAIL_COND_V(!joint, false); + ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, false); + Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint); + return generic_6dof_joint->get_flag(p_axis, p_flag); } - #if 0 void PhysicsServerSW::joint_set_param(RID p_joint, JointParam p_param, real_t p_value) { @@ -1384,8 +1293,8 @@ void PhysicsServerSW::free(RID p_rid) { ShapeSW *shape = shape_owner.get(p_rid); - while(shape->get_owners().size()) { - ShapeOwnerSW *so=shape->get_owners().front()->key(); + while (shape->get_owners().size()) { + ShapeOwnerSW *so = shape->get_owners().front()->key(); so->remove_shape(shape); } @@ -1405,8 +1314,7 @@ void PhysicsServerSW::free(RID p_rid) { body->set_space(NULL); - - while( body->get_shape_count() ) { + while (body->get_shape_count()) { body->remove_shape(0); } @@ -1431,7 +1339,7 @@ void PhysicsServerSW::free(RID p_rid) { area->set_space(NULL); - while( area->get_shape_count() ) { + while (area->get_shape_count()) { area->remove_shape(0); } @@ -1442,7 +1350,7 @@ void PhysicsServerSW::free(RID p_rid) { SpaceSW *space = space_owner.get(p_rid); - while(space->get_objects().size()) { + while (space->get_objects().size()) { CollisionObjectSW *co = (CollisionObjectSW *)space->get_objects().front()->get(); co->set_space(NULL); } @@ -1457,7 +1365,7 @@ void PhysicsServerSW::free(RID p_rid) { JointSW *joint = joint_owner.get(p_rid); - for(int i=0;i<joint->get_body_count();i++) { + for (int i = 0; i < joint->get_body_count(); i++) { joint->get_body_ptr()[i]->remove_constraint(joint); } @@ -1469,51 +1377,45 @@ void PhysicsServerSW::free(RID p_rid) { ERR_EXPLAIN("Invalid ID"); ERR_FAIL(); } - - }; void PhysicsServerSW::set_active(bool p_active) { - active=p_active; + active = p_active; }; void PhysicsServerSW::init() { - doing_sync=true; - last_step=0.001; - iterations=8;// 8? - stepper = memnew( StepSW ); - direct_state = memnew( PhysicsDirectBodyStateSW ); + doing_sync = true; + last_step = 0.001; + iterations = 8; // 8? + stepper = memnew(StepSW); + direct_state = memnew(PhysicsDirectBodyStateSW); }; - void PhysicsServerSW::step(real_t p_step) { - if (!active) return; + doing_sync = false; - doing_sync=false; - - last_step=p_step; - PhysicsDirectBodyStateSW::singleton->step=p_step; + last_step = p_step; + PhysicsDirectBodyStateSW::singleton->step = p_step; - island_count=0; - active_objects=0; - collision_pairs=0; - for( Set<const SpaceSW*>::Element *E=active_spaces.front();E;E=E->next()) { + island_count = 0; + active_objects = 0; + collision_pairs = 0; + for (Set<const SpaceSW *>::Element *E = active_spaces.front(); E; E = E->next()) { - stepper->step((SpaceSW*)E->get(),p_step,iterations); - island_count+=E->get()->get_island_count(); - active_objects+=E->get()->get_active_objects(); - collision_pairs+=E->get()->get_collision_pairs(); + stepper->step((SpaceSW *)E->get(), p_step, iterations); + island_count += E->get()->get_island_count(); + active_objects += E->get()->get_active_objects(); + collision_pairs += E->get()->get_collision_pairs(); } - } -void PhysicsServerSW::sync() { +void PhysicsServerSW::sync(){ }; @@ -1522,21 +1424,20 @@ void PhysicsServerSW::flush_queries() { if (!active) return; - doing_sync=true; + doing_sync = true; uint64_t time_beg = OS::get_singleton()->get_ticks_usec(); - for( Set<const SpaceSW*>::Element *E=active_spaces.front();E;E=E->next()) { + for (Set<const SpaceSW *>::Element *E = active_spaces.front(); E; E = E->next()) { - SpaceSW *space=(SpaceSW *)E->get(); + SpaceSW *space = (SpaceSW *)E->get(); space->call_queries(); } - if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_profiling()) { uint64_t total_time[SpaceSW::ELAPSED_TIME_MAX]; - static const char* time_name[SpaceSW::ELAPSED_TIME_MAX]={ + static const char *time_name[SpaceSW::ELAPSED_TIME_MAX] = { "integrate_forces", "generate_islands", "setup_constraints", @@ -1544,44 +1445,39 @@ void PhysicsServerSW::flush_queries() { "integrate_velocities" }; - for(int i=0;i<SpaceSW::ELAPSED_TIME_MAX;i++) { - total_time[i]=0; + for (int i = 0; i < SpaceSW::ELAPSED_TIME_MAX; i++) { + total_time[i] = 0; } - for( Set<const SpaceSW*>::Element *E=active_spaces.front();E;E=E->next()) { + for (Set<const SpaceSW *>::Element *E = active_spaces.front(); E; E = E->next()) { - for(int i=0;i<SpaceSW::ELAPSED_TIME_MAX;i++) { - total_time[i]+=E->get()->get_elapsed_time(SpaceSW::ElapsedTime(i)); + for (int i = 0; i < SpaceSW::ELAPSED_TIME_MAX; i++) { + total_time[i] += E->get()->get_elapsed_time(SpaceSW::ElapsedTime(i)); } - } Array values; - values.resize(SpaceSW::ELAPSED_TIME_MAX*2); - for(int i=0;i<SpaceSW::ELAPSED_TIME_MAX;i++) { - values[i*2+0]=time_name[i]; - values[i*2+1]=USEC_TO_SEC(total_time[i]); + values.resize(SpaceSW::ELAPSED_TIME_MAX * 2); + for (int i = 0; i < SpaceSW::ELAPSED_TIME_MAX; i++) { + values[i * 2 + 0] = time_name[i]; + values[i * 2 + 1] = USEC_TO_SEC(total_time[i]); } values.push_back("flush_queries"); - values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec()-time_beg)); - - ScriptDebugger::get_singleton()->add_profiling_frame_data("physics",values); + values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec() - time_beg)); + ScriptDebugger::get_singleton()->add_profiling_frame_data("physics", values); } }; - - void PhysicsServerSW::finish() { memdelete(stepper); memdelete(direct_state); }; - int PhysicsServerSW::get_process_info(ProcessInfo p_info) { - switch(p_info) { + switch (p_info) { case INFO_ACTIVE_OBJECTS: { @@ -1594,64 +1490,55 @@ int PhysicsServerSW::get_process_info(ProcessInfo p_info) { return island_count; } break; - } return 0; } +void PhysicsServerSW::_shape_col_cbk(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) { -void PhysicsServerSW::_shape_col_cbk(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata) { - + CollCbkData *cbk = (CollCbkData *)p_userdata; - CollCbkData *cbk=(CollCbkData *)p_userdata; - - if (cbk->max==0) + if (cbk->max == 0) return; if (cbk->amount == cbk->max) { //find least deep - real_t min_depth=1e20; - int min_depth_idx=0; - for(int i=0;i<cbk->amount;i++) { - - real_t d = cbk->ptr[i*2+0].distance_squared_to(cbk->ptr[i*2+1]); - if (d<min_depth) { - min_depth=d; - min_depth_idx=i; + real_t min_depth = 1e20; + int min_depth_idx = 0; + for (int i = 0; i < cbk->amount; i++) { + + real_t d = cbk->ptr[i * 2 + 0].distance_squared_to(cbk->ptr[i * 2 + 1]); + if (d < min_depth) { + min_depth = d; + min_depth_idx = i; } - } real_t d = p_point_A.distance_squared_to(p_point_B); - if (d<min_depth) + if (d < min_depth) return; - cbk->ptr[min_depth_idx*2+0]=p_point_A; - cbk->ptr[min_depth_idx*2+1]=p_point_B; - + cbk->ptr[min_depth_idx * 2 + 0] = p_point_A; + cbk->ptr[min_depth_idx * 2 + 1] = p_point_B; } else { - cbk->ptr[cbk->amount*2+0]=p_point_A; - cbk->ptr[cbk->amount*2+1]=p_point_B; + cbk->ptr[cbk->amount * 2 + 0] = p_point_A; + cbk->ptr[cbk->amount * 2 + 1] = p_point_B; cbk->amount++; } } - PhysicsServerSW::PhysicsServerSW() { - BroadPhaseSW::create_func=BroadPhaseOctree::_create; - island_count=0; - active_objects=0; - collision_pairs=0; - - active=true; + BroadPhaseSW::create_func = BroadPhaseOctree::_create; + island_count = 0; + active_objects = 0; + collision_pairs = 0; + active = true; }; -PhysicsServerSW::~PhysicsServerSW() { +PhysicsServerSW::~PhysicsServerSW(){ }; - - diff --git a/servers/physics/physics_server_sw.h b/servers/physics/physics_server_sw.h index 6e20474350..cb5a339ee8 100644 --- a/servers/physics/physics_server_sw.h +++ b/servers/physics/physics_server_sw.h @@ -29,19 +29,17 @@ #ifndef PHYSICS_SERVER_SW #define PHYSICS_SERVER_SW - +#include "joints_sw.h" #include "servers/physics_server.h" #include "shape_sw.h" #include "space_sw.h" #include "step_sw.h" -#include "joints_sw.h" - class PhysicsServerSW : public PhysicsServer { - GDCLASS( PhysicsServerSW, PhysicsServer ); + GDCLASS(PhysicsServerSW, PhysicsServer); -friend class PhysicsDirectSpaceStateSW; + friend class PhysicsDirectSpaceStateSW; bool active; int iterations; bool doing_sync; @@ -52,7 +50,7 @@ friend class PhysicsDirectSpaceStateSW; int collision_pairs; StepSW *stepper; - Set<const SpaceSW*> active_spaces; + Set<const SpaceSW *> active_spaces; PhysicsDirectBodyStateSW *direct_state; @@ -64,7 +62,6 @@ friend class PhysicsDirectSpaceStateSW; //void _clear_query(QuerySW *p_query); public: - struct CollCbkData { int max; @@ -72,10 +69,10 @@ public: Vector3 *ptr; }; - static void _shape_col_cbk(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata); + static void _shape_col_cbk(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata); virtual RID shape_create(ShapeType p_shape); - virtual void shape_set_data(RID p_shape, const Variant& p_data); + virtual void shape_set_data(RID p_shape, const Variant &p_data); virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias); virtual ShapeType shape_get_type(RID p_shape) const; @@ -85,16 +82,16 @@ public: /* SPACE API */ virtual RID space_create(); - virtual void space_set_active(RID p_space,bool p_active); + virtual void space_set_active(RID p_space, bool p_active); virtual bool space_is_active(RID p_space) const; - virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value); - virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const; + virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value); + virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const; // this function only works on fixed process, errors and returns null otherwise - virtual PhysicsDirectSpaceState* space_get_direct_state(RID p_space); + virtual PhysicsDirectSpaceState *space_get_direct_state(RID p_space); - virtual void space_set_debug_contacts(RID p_space,int p_max_contacts); + virtual void space_set_debug_contacts(RID p_space, int p_max_contacts); virtual Vector<Vector3> space_get_contacts(RID p_space) const; virtual int space_get_contact_count(RID p_space) const; @@ -108,9 +105,9 @@ public: virtual void area_set_space(RID p_area, RID p_space); virtual RID area_get_space(RID p_area) const; - virtual void area_add_shape(RID p_area, RID p_shape, const Transform& p_transform=Transform()); - virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape); - virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform& p_transform); + virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform()); + virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape); + virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform); virtual int area_get_shape_count(RID p_area) const; virtual RID area_get_shape(RID p_area, int p_shape_idx) const; @@ -119,31 +116,30 @@ public: virtual void area_remove_shape(RID p_area, int p_shape_idx); virtual void area_clear_shapes(RID p_area); - virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID); + virtual void area_attach_object_instance_ID(RID p_area, ObjectID p_ID); virtual ObjectID area_get_object_instance_ID(RID p_area) const; - virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value); - virtual void area_set_transform(RID p_area, const Transform& p_transform); + virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value); + virtual void area_set_transform(RID p_area, const Transform &p_transform); - virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const; + virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const; virtual Transform area_get_transform(RID p_area) const; - virtual void area_set_ray_pickable(RID p_area,bool p_enable); + virtual void area_set_ray_pickable(RID p_area, bool p_enable); virtual bool area_is_ray_pickable(RID p_area) const; - virtual void area_set_collision_mask(RID p_area,uint32_t p_mask); - virtual void area_set_layer_mask(RID p_area,uint32_t p_mask); + virtual void area_set_collision_mask(RID p_area, uint32_t p_mask); + virtual void area_set_layer_mask(RID p_area, uint32_t p_mask); - virtual void area_set_monitorable(RID p_area,bool p_monitorable); - - virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method); - virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method); + virtual void area_set_monitorable(RID p_area, bool p_monitorable); + virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method); + virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method); /* BODY API */ // create a body of a given type - virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false); + virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false); virtual void body_set_space(RID p_body, RID p_space); virtual RID body_get_space(RID p_body) const; @@ -151,24 +147,24 @@ public: virtual void body_set_mode(RID p_body, BodyMode p_mode); virtual BodyMode body_get_mode(RID p_body) const; - virtual void body_add_shape(RID p_body, RID p_shape, const Transform& p_transform=Transform()); - virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape); - virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform& p_transform); + virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform()); + virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape); + virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform); virtual int body_get_shape_count(RID p_body) const; virtual RID body_get_shape(RID p_body, int p_shape_idx) const; virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const; - virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable); + virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable); virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const; virtual void body_remove_shape(RID p_body, int p_shape_idx); virtual void body_clear_shapes(RID p_body); - virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID); + virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID); virtual uint32_t body_get_object_instance_ID(RID p_body) const; - virtual void body_set_enable_continuous_collision_detection(RID p_body,bool p_enable); + virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable); virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const; virtual void body_set_layer_mask(RID p_body, uint32_t p_mask); @@ -183,20 +179,20 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value); virtual real_t body_get_param(RID p_body, BodyParameter p_param) const; - virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant); + virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant); virtual Variant body_get_state(RID p_body, BodyState p_state) const; - virtual void body_set_applied_force(RID p_body, const Vector3& p_force); + virtual void body_set_applied_force(RID p_body, const Vector3 &p_force); virtual Vector3 body_get_applied_force(RID p_body) const; - virtual void body_set_applied_torque(RID p_body, const Vector3& p_torque); + virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque); virtual Vector3 body_get_applied_torque(RID p_body) const; - virtual void body_apply_impulse(RID p_body, const Vector3& p_pos, const Vector3& p_impulse); - virtual void body_apply_torque_impulse(RID p_body, const Vector3& p_impulse); - virtual void body_set_axis_velocity(RID p_body, const Vector3& p_axis_velocity); + virtual void body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse); + virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse); + virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity); - virtual void body_set_axis_lock(RID p_body,BodyAxisLock p_lock); + virtual void body_set_axis_lock(RID p_body, BodyAxisLock p_lock); virtual BodyAxisLock body_get_axis_lock(RID p_body) const; virtual void body_add_collision_exception(RID p_body, RID p_body_b); @@ -206,61 +202,60 @@ public: virtual void body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold); virtual real_t body_get_contacts_reported_depth_treshold(RID p_body) const; - virtual void body_set_omit_force_integration(RID p_body,bool p_omit); + virtual void body_set_omit_force_integration(RID p_body, bool p_omit); virtual bool body_is_omitting_force_integration(RID p_body) const; virtual void body_set_max_contacts_reported(RID p_body, int p_contacts); virtual int body_get_max_contacts_reported(RID p_body) const; - virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant()); + virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()); - virtual void body_set_ray_pickable(RID p_body,bool p_enable); + virtual void body_set_ray_pickable(RID p_body, bool p_enable); virtual bool body_is_ray_pickable(RID p_body) const; /* JOINT API */ - virtual RID joint_create_pin(RID p_body_A,const Vector3& p_local_A,RID p_body_B,const Vector3& p_local_B); + virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B); - virtual void pin_joint_set_param(RID p_joint,PinJointParam p_param, real_t p_value); - virtual real_t pin_joint_get_param(RID p_joint,PinJointParam p_param) const; + virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value); + virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const; - virtual void pin_joint_set_local_A(RID p_joint, const Vector3& p_A); + virtual void pin_joint_set_local_A(RID p_joint, const Vector3 &p_A); virtual Vector3 pin_joint_get_local_A(RID p_joint) const; - virtual void pin_joint_set_local_B(RID p_joint, const Vector3& p_B); + virtual void pin_joint_set_local_B(RID p_joint, const Vector3 &p_B); virtual Vector3 pin_joint_get_local_B(RID p_joint) const; - virtual RID joint_create_hinge(RID p_body_A,const Transform& p_frame_A,RID p_body_B,const Transform& p_frame_B); - virtual RID joint_create_hinge_simple(RID p_body_A,const Vector3& p_pivot_A,const Vector3& p_axis_A,RID p_body_B,const Vector3& p_pivot_B,const Vector3& p_axis_B); - - virtual void hinge_joint_set_param(RID p_joint,HingeJointParam p_param, real_t p_value); - virtual real_t hinge_joint_get_param(RID p_joint,HingeJointParam p_param) const; + virtual RID joint_create_hinge(RID p_body_A, const Transform &p_frame_A, RID p_body_B, const Transform &p_frame_B); + virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B); - virtual void hinge_joint_set_flag(RID p_joint,HingeJointFlag p_flag, bool p_value); - virtual bool hinge_joint_get_flag(RID p_joint,HingeJointFlag p_flag) const; + virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value); + virtual real_t hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const; + virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value); + virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const; - virtual RID joint_create_slider(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B); //reference frame is A + virtual RID joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B); //reference frame is A - virtual void slider_joint_set_param(RID p_joint,SliderJointParam p_param, real_t p_value); - virtual real_t slider_joint_get_param(RID p_joint,SliderJointParam p_param) const; + virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value); + virtual real_t slider_joint_get_param(RID p_joint, SliderJointParam p_param) const; - virtual RID joint_create_cone_twist(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B); //reference frame is A + virtual RID joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B); //reference frame is A - virtual void cone_twist_joint_set_param(RID p_joint,ConeTwistJointParam p_param, real_t p_value); - virtual real_t cone_twist_joint_get_param(RID p_joint,ConeTwistJointParam p_param) const; + virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value); + virtual real_t cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const; - virtual RID joint_create_generic_6dof(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B); //reference frame is A + virtual RID joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B); //reference frame is A - virtual void generic_6dof_joint_set_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param, real_t p_value); - virtual real_t generic_6dof_joint_get_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param); + virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param, real_t p_value); + virtual real_t generic_6dof_joint_get_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param); - virtual void generic_6dof_joint_set_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag, bool p_enable); - virtual bool generic_6dof_joint_get_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag); + virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag, bool p_enable); + virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag); virtual JointType joint_get_type(RID p_joint) const; - virtual void joint_set_solver_priority(RID p_joint,int p_priority); + virtual void joint_set_solver_priority(RID p_joint, int p_priority); virtual int joint_get_solver_priority(RID p_joint) const; #if 0 @@ -290,8 +285,6 @@ public: PhysicsServerSW(); ~PhysicsServerSW(); - }; #endif - diff --git a/servers/physics/shape_sw.cpp b/servers/physics/shape_sw.cpp index dec1c75d9f..4ce716c70a 100644 --- a/servers/physics/shape_sw.cpp +++ b/servers/physics/shape_sw.cpp @@ -28,100 +28,91 @@ /*************************************************************************/ #include "shape_sw.h" #include "geometry.h" -#include "sort.h" #include "quick_hull.h" +#include "sort.h" #define _POINT_SNAP 0.001953125 #define _EDGE_IS_VALID_SUPPORT_TRESHOLD 0.0002 #define _FACE_IS_VALID_SUPPORT_TRESHOLD 0.9998 - -void ShapeSW::configure(const Rect3& p_aabb) { - aabb=p_aabb; - configured=true; - for (Map<ShapeOwnerSW*,int>::Element *E=owners.front();E;E=E->next()) { - ShapeOwnerSW* co=(ShapeOwnerSW*)E->key(); +void ShapeSW::configure(const Rect3 &p_aabb) { + aabb = p_aabb; + configured = true; + for (Map<ShapeOwnerSW *, int>::Element *E = owners.front(); E; E = E->next()) { + ShapeOwnerSW *co = (ShapeOwnerSW *)E->key(); co->_shape_changed(); } } - -Vector3 ShapeSW::get_support(const Vector3& p_normal) const { +Vector3 ShapeSW::get_support(const Vector3 &p_normal) const { Vector3 res; int amnt; - get_supports(p_normal,1,&res,amnt); + get_supports(p_normal, 1, &res, amnt); return res; } void ShapeSW::add_owner(ShapeOwnerSW *p_owner) { - Map<ShapeOwnerSW*,int>::Element *E=owners.find(p_owner); + Map<ShapeOwnerSW *, int>::Element *E = owners.find(p_owner); if (E) { E->get()++; } else { - owners[p_owner]=1; + owners[p_owner] = 1; } } -void ShapeSW::remove_owner(ShapeOwnerSW *p_owner){ +void ShapeSW::remove_owner(ShapeOwnerSW *p_owner) { - Map<ShapeOwnerSW*,int>::Element *E=owners.find(p_owner); + Map<ShapeOwnerSW *, int>::Element *E = owners.find(p_owner); ERR_FAIL_COND(!E); E->get()--; - if (E->get()==0) { + if (E->get() == 0) { owners.erase(E); } - } -bool ShapeSW::is_owner(ShapeOwnerSW *p_owner) const{ +bool ShapeSW::is_owner(ShapeOwnerSW *p_owner) const { return owners.has(p_owner); - } -const Map<ShapeOwnerSW*,int>& ShapeSW::get_owners() const{ +const Map<ShapeOwnerSW *, int> &ShapeSW::get_owners() const { return owners; } - ShapeSW::ShapeSW() { - custom_bias=0; - configured=false; + custom_bias = 0; + configured = false; } - ShapeSW::~ShapeSW() { ERR_FAIL_COND(owners.size()); } - - Plane PlaneShapeSW::get_plane() const { return plane; } -void PlaneShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { +void PlaneShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { // gibberish, a plane is infinity - r_min=-1e7; - r_max=1e7; + r_min = -1e7; + r_max = 1e7; } -Vector3 PlaneShapeSW::get_support(const Vector3& p_normal) const { +Vector3 PlaneShapeSW::get_support(const Vector3 &p_normal) const { - return p_normal*1e15; + return p_normal * 1e15; } +bool PlaneShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { -bool PlaneShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { - - bool inters=plane.intersects_segment(p_begin,p_end,&r_result); - if(inters) - r_normal=plane.normal; + bool inters = plane.intersects_segment(p_begin, p_end, &r_result); + if (inters) + r_normal = plane.normal; return inters; } @@ -130,16 +121,15 @@ Vector3 PlaneShapeSW::get_moment_of_inertia(real_t p_mass) const { return Vector3(); //wtf } -void PlaneShapeSW::_setup(const Plane& p_plane) { +void PlaneShapeSW::_setup(const Plane &p_plane) { - plane=p_plane; - configure(Rect3(Vector3(-1e4,-1e4,-1e4),Vector3(1e4*2,1e4*2,1e4*2))); + plane = p_plane; + configure(Rect3(Vector3(-1e4, -1e4, -1e4), Vector3(1e4 * 2, 1e4 * 2, 1e4 * 2))); } -void PlaneShapeSW::set_data(const Variant& p_data) { +void PlaneShapeSW::set_data(const Variant &p_data) { _setup(p_data); - } Variant PlaneShapeSW::get_data() const { @@ -147,9 +137,7 @@ Variant PlaneShapeSW::get_data() const { return plane; } -PlaneShapeSW::PlaneShapeSW() { - - +PlaneShapeSW::PlaneShapeSW() { } // @@ -159,39 +147,38 @@ real_t RayShapeSW::get_length() const { return length; } -void RayShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { +void RayShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { // don't think this will be even used - r_min=0; - r_max=1; + r_min = 0; + r_max = 1; } -Vector3 RayShapeSW::get_support(const Vector3& p_normal) const { +Vector3 RayShapeSW::get_support(const Vector3 &p_normal) const { - if (p_normal.z>0) - return Vector3(0,0,length); + if (p_normal.z > 0) + return Vector3(0, 0, length); else - return Vector3(0,0,0); + return Vector3(0, 0, 0); } -void RayShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { +void RayShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { if (Math::abs(p_normal.z) < _EDGE_IS_VALID_SUPPORT_TRESHOLD) { - r_amount=2; - r_supports[0]=Vector3(0,0,0); - r_supports[1]=Vector3(0,0,length); - } else if (p_normal.z>0) { - r_amount=1; - *r_supports=Vector3(0,0,length); + r_amount = 2; + r_supports[0] = Vector3(0, 0, 0); + r_supports[1] = Vector3(0, 0, length); + } else if (p_normal.z > 0) { + r_amount = 1; + *r_supports = Vector3(0, 0, length); } else { - r_amount=1; - *r_supports=Vector3(0,0,0); + r_amount = 1; + *r_supports = Vector3(0, 0, 0); } } - -bool RayShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { +bool RayShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { return false; //simply not possible } @@ -201,16 +188,15 @@ Vector3 RayShapeSW::get_moment_of_inertia(real_t p_mass) const { return Vector3(); } -void RayShapeSW::_setup(real_t p_length) { +void RayShapeSW::_setup(real_t p_length) { - length=p_length; - configure(Rect3(Vector3(0,0,0),Vector3(0.1,0.1,length))); + length = p_length; + configure(Rect3(Vector3(0, 0, 0), Vector3(0.1, 0.1, length))); } -void RayShapeSW::set_data(const Variant& p_data) { +void RayShapeSW::set_data(const Variant &p_data) { _setup(p_data); - } Variant RayShapeSW::get_data() const { @@ -218,13 +204,11 @@ Variant RayShapeSW::get_data() const { return length; } -RayShapeSW::RayShapeSW() { +RayShapeSW::RayShapeSW() { - length=1; + length = 1; } - - /********** SPHERE *************/ real_t SphereShapeSW::get_radius() const { @@ -232,50 +216,47 @@ real_t SphereShapeSW::get_radius() const { return radius; } -void SphereShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { +void SphereShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { - real_t d = p_normal.dot( p_transform.origin ); + real_t d = p_normal.dot(p_transform.origin); // figure out scale at point Vector3 local_normal = p_transform.basis.xform_inv(p_normal); real_t scale = local_normal.length(); - r_min = d - (radius) * scale; - r_max = d + (radius) * scale; - + r_min = d - (radius)*scale; + r_max = d + (radius)*scale; } -Vector3 SphereShapeSW::get_support(const Vector3& p_normal) const { +Vector3 SphereShapeSW::get_support(const Vector3 &p_normal) const { - return p_normal*radius; + return p_normal * radius; } -void SphereShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { +void SphereShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { - *r_supports=p_normal*radius; - r_amount=1; + *r_supports = p_normal * radius; + r_amount = 1; } -bool SphereShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { +bool SphereShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { - return Geometry::segment_intersects_sphere(p_begin,p_end,Vector3(),radius,&r_result,&r_normal); + return Geometry::segment_intersects_sphere(p_begin, p_end, Vector3(), radius, &r_result, &r_normal); } Vector3 SphereShapeSW::get_moment_of_inertia(real_t p_mass) const { real_t s = 0.4 * p_mass * radius * radius; - return Vector3(s,s,s); + return Vector3(s, s, s); } void SphereShapeSW::_setup(real_t p_radius) { - - radius=p_radius; - configure(Rect3( Vector3(-radius,-radius,-radius), Vector3(radius*2.0,radius*2.0,radius*2.0))); - + radius = p_radius; + configure(Rect3(Vector3(-radius, -radius, -radius), Vector3(radius * 2.0, radius * 2.0, radius * 2.0))); } -void SphereShapeSW::set_data(const Variant& p_data) { +void SphereShapeSW::set_data(const Variant &p_data) { _setup(p_data); } @@ -287,113 +268,105 @@ Variant SphereShapeSW::get_data() const { SphereShapeSW::SphereShapeSW() { - radius=0; + radius = 0; } - /********** BOX *************/ - -void BoxShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { +void BoxShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { // no matter the angle, the box is mirrored anyway - Vector3 local_normal=p_transform.basis.xform_inv(p_normal); + Vector3 local_normal = p_transform.basis.xform_inv(p_normal); real_t length = local_normal.abs().dot(half_extents); - real_t distance = p_normal.dot( p_transform.origin ); + real_t distance = p_normal.dot(p_transform.origin); r_min = distance - length; r_max = distance + length; - - } -Vector3 BoxShapeSW::get_support(const Vector3& p_normal) const { - +Vector3 BoxShapeSW::get_support(const Vector3 &p_normal) const { Vector3 point( - (p_normal.x<0) ? -half_extents.x : half_extents.x, - (p_normal.y<0) ? -half_extents.y : half_extents.y, - (p_normal.z<0) ? -half_extents.z : half_extents.z - ); + (p_normal.x < 0) ? -half_extents.x : half_extents.x, + (p_normal.y < 0) ? -half_extents.y : half_extents.y, + (p_normal.z < 0) ? -half_extents.z : half_extents.z); return point; } -void BoxShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { +void BoxShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { - static const int next[3]={1,2,0}; - static const int next2[3]={2,0,1}; + static const int next[3] = { 1, 2, 0 }; + static const int next2[3] = { 2, 0, 1 }; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis; - axis[i]=1.0; - real_t dot = p_normal.dot( axis ); - if ( Math::abs( dot ) > _FACE_IS_VALID_SUPPORT_TRESHOLD ) { + axis[i] = 1.0; + real_t dot = p_normal.dot(axis); + if (Math::abs(dot) > _FACE_IS_VALID_SUPPORT_TRESHOLD) { //Vector3 axis_b; - bool neg = dot<0; + bool neg = dot < 0; r_amount = 4; Vector3 point; - point[i]=half_extents[i]; + point[i] = half_extents[i]; - int i_n=next[i]; - int i_n2=next2[i]; + int i_n = next[i]; + int i_n2 = next2[i]; - static const real_t sign[4][2]={ + static const real_t sign[4][2] = { - {-1.0, 1.0}, - { 1.0, 1.0}, - { 1.0,-1.0}, - {-1.0,-1.0}, + { -1.0, 1.0 }, + { 1.0, 1.0 }, + { 1.0, -1.0 }, + { -1.0, -1.0 }, }; - for (int j=0;j<4;j++) { - - point[i_n]=sign[j][0]*half_extents[i_n]; - point[i_n2]=sign[j][1]*half_extents[i_n2]; - r_supports[j]=neg?-point:point; + for (int j = 0; j < 4; j++) { + point[i_n] = sign[j][0] * half_extents[i_n]; + point[i_n2] = sign[j][1] * half_extents[i_n2]; + r_supports[j] = neg ? -point : point; } if (neg) { - SWAP( r_supports[1], r_supports[2] ); - SWAP( r_supports[0], r_supports[3] ); + SWAP(r_supports[1], r_supports[2]); + SWAP(r_supports[0], r_supports[3]); } return; } - r_amount=0; - + r_amount = 0; } - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis; - axis[i]=1.0; + axis[i] = 1.0; - if (Math::abs(p_normal.dot(axis))<_EDGE_IS_VALID_SUPPORT_TRESHOLD) { + if (Math::abs(p_normal.dot(axis)) < _EDGE_IS_VALID_SUPPORT_TRESHOLD) { - r_amount= 2; + r_amount = 2; - int i_n=next[i]; - int i_n2=next2[i]; + int i_n = next[i]; + int i_n2 = next2[i]; - Vector3 point=half_extents; + Vector3 point = half_extents; - if (p_normal[i_n]<0) { - point[i_n]=-point[i_n]; + if (p_normal[i_n] < 0) { + point[i_n] = -point[i_n]; } - if (p_normal[i_n2]<0) { - point[i_n2]=-point[i_n2]; + if (p_normal[i_n2] < 0) { + point[i_n2] = -point[i_n2]; } r_supports[0] = point; - point[i]=-point[i]; + point[i] = -point[i]; r_supports[1] = point; return; } @@ -401,44 +374,38 @@ void BoxShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_suppo /* USE POINT */ Vector3 point( - (p_normal.x<0) ? -half_extents.x : half_extents.x, - (p_normal.y<0) ? -half_extents.y : half_extents.y, - (p_normal.z<0) ? -half_extents.z : half_extents.z - ); + (p_normal.x < 0) ? -half_extents.x : half_extents.x, + (p_normal.y < 0) ? -half_extents.y : half_extents.y, + (p_normal.z < 0) ? -half_extents.z : half_extents.z); - r_amount=1; - r_supports[0]=point; + r_amount = 1; + r_supports[0] = point; } -bool BoxShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { - - Rect3 aabb(-half_extents,half_extents*2.0); +bool BoxShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { - return aabb.intersects_segment(p_begin,p_end,&r_result,&r_normal); + Rect3 aabb(-half_extents, half_extents * 2.0); + return aabb.intersects_segment(p_begin, p_end, &r_result, &r_normal); } Vector3 BoxShapeSW::get_moment_of_inertia(real_t p_mass) const { - real_t lx=half_extents.x; - real_t ly=half_extents.y; - real_t lz=half_extents.z; - - return Vector3( (p_mass/3.0) * (ly*ly + lz*lz), (p_mass/3.0) * (lx*lx + lz*lz), (p_mass/3.0) * (lx*lx + ly*ly) ); + real_t lx = half_extents.x; + real_t ly = half_extents.y; + real_t lz = half_extents.z; + return Vector3((p_mass / 3.0) * (ly * ly + lz * lz), (p_mass / 3.0) * (lx * lx + lz * lz), (p_mass / 3.0) * (lx * lx + ly * ly)); } -void BoxShapeSW::_setup(const Vector3& p_half_extents) { - - half_extents=p_half_extents.abs(); - - configure(Rect3(-half_extents,half_extents*2)); +void BoxShapeSW::_setup(const Vector3 &p_half_extents) { + half_extents = p_half_extents.abs(); + configure(Rect3(-half_extents, half_extents * 2)); } -void BoxShapeSW::set_data(const Variant& p_data) { - +void BoxShapeSW::set_data(const Variant &p_data) { _setup(p_data); } @@ -448,138 +415,128 @@ Variant BoxShapeSW::get_data() const { return half_extents; } -BoxShapeSW::BoxShapeSW() { - - +BoxShapeSW::BoxShapeSW() { } - /********** CAPSULE *************/ +void CapsuleShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { -void CapsuleShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { - - Vector3 n=p_transform.basis.xform_inv(p_normal).normalized(); + Vector3 n = p_transform.basis.xform_inv(p_normal).normalized(); real_t h = (n.z > 0) ? height : -height; n *= radius; n.z += h * 0.5; - r_max=p_normal.dot(p_transform.xform(n)); - r_min=p_normal.dot(p_transform.xform(-n)); + r_max = p_normal.dot(p_transform.xform(n)); + r_min = p_normal.dot(p_transform.xform(-n)); return; n = p_transform.basis.xform(n); - real_t distance = p_normal.dot( p_transform.origin ); + real_t distance = p_normal.dot(p_transform.origin); real_t length = Math::abs(p_normal.dot(n)); r_min = distance - length; r_max = distance + length; - ERR_FAIL_COND( r_max < r_min ); - + ERR_FAIL_COND(r_max < r_min); } -Vector3 CapsuleShapeSW::get_support(const Vector3& p_normal) const { +Vector3 CapsuleShapeSW::get_support(const Vector3 &p_normal) const { - Vector3 n=p_normal; + Vector3 n = p_normal; real_t h = (n.z > 0) ? height : -height; - n*=radius; - n.z += h*0.5; + n *= radius; + n.z += h * 0.5; return n; } -void CapsuleShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { - +void CapsuleShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { - Vector3 n=p_normal; + Vector3 n = p_normal; real_t d = n.z; - if (Math::abs( d )<_EDGE_IS_VALID_SUPPORT_TRESHOLD ) { + if (Math::abs(d) < _EDGE_IS_VALID_SUPPORT_TRESHOLD) { // make it flat - n.z=0.0; + n.z = 0.0; n.normalize(); - n*=radius; + n *= radius; - r_amount=2; - r_supports[0]=n; - r_supports[0].z+=height*0.5; - r_supports[1]=n; - r_supports[1].z-=height*0.5; + r_amount = 2; + r_supports[0] = n; + r_supports[0].z += height * 0.5; + r_supports[1] = n; + r_supports[1].z -= height * 0.5; } else { real_t h = (d > 0) ? height : -height; - n*=radius; - n.z += h*0.5; - r_amount=1; - *r_supports=n; - + n *= radius; + n.z += h * 0.5; + r_amount = 1; + *r_supports = n; } - } +bool CapsuleShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { -bool CapsuleShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { + Vector3 norm = (p_end - p_begin).normalized(); + real_t min_d = 1e20; - Vector3 norm=(p_end-p_begin).normalized(); - real_t min_d=1e20; + Vector3 res, n; + bool collision = false; - - Vector3 res,n; - bool collision=false; - - Vector3 auxres,auxn; + Vector3 auxres, auxn; bool collided; // test against cylinder and spheres :-| - collided = Geometry::segment_intersects_cylinder(p_begin,p_end,height,radius,&auxres,&auxn); + collided = Geometry::segment_intersects_cylinder(p_begin, p_end, height, radius, &auxres, &auxn); if (collided) { - real_t d=norm.dot(auxres); - if (d<min_d) { - min_d=d; - res=auxres; - n=auxn; - collision=true; + real_t d = norm.dot(auxres); + if (d < min_d) { + min_d = d; + res = auxres; + n = auxn; + collision = true; } } - collided = Geometry::segment_intersects_sphere(p_begin,p_end,Vector3(0,0,height*0.5),radius,&auxres,&auxn); + collided = Geometry::segment_intersects_sphere(p_begin, p_end, Vector3(0, 0, height * 0.5), radius, &auxres, &auxn); if (collided) { - real_t d=norm.dot(auxres); - if (d<min_d) { - min_d=d; - res=auxres; - n=auxn; - collision=true; + real_t d = norm.dot(auxres); + if (d < min_d) { + min_d = d; + res = auxres; + n = auxn; + collision = true; } } - collided = Geometry::segment_intersects_sphere(p_begin,p_end,Vector3(0,0,height*-0.5),radius,&auxres,&auxn); + collided = Geometry::segment_intersects_sphere(p_begin, p_end, Vector3(0, 0, height * -0.5), radius, &auxres, &auxn); if (collided) { - real_t d=norm.dot(auxres); + real_t d = norm.dot(auxres); - if (d<min_d) { - min_d=d; - res=auxres; - n=auxn; - collision=true; + if (d < min_d) { + min_d = d; + res = auxres; + n = auxn; + collision = true; } } if (collision) { - r_result=res; - r_normal=n; + r_result = res; + r_normal = n; } return collision; } @@ -587,105 +544,90 @@ bool CapsuleShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_e Vector3 CapsuleShapeSW::get_moment_of_inertia(real_t p_mass) const { // use crappy AABB approximation - Vector3 extents=get_aabb().size*0.5; + Vector3 extents = get_aabb().size * 0.5; return Vector3( - (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z), - (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z), - (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y) - ); - + (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z), + (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z), + (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y)); } +void CapsuleShapeSW::_setup(real_t p_height, real_t p_radius) { - - -void CapsuleShapeSW::_setup(real_t p_height,real_t p_radius) { - - height=p_height; - radius=p_radius; - configure(Rect3(Vector3(-radius,-radius,-height*0.5-radius),Vector3(radius*2,radius*2,height+radius*2.0))); - + height = p_height; + radius = p_radius; + configure(Rect3(Vector3(-radius, -radius, -height * 0.5 - radius), Vector3(radius * 2, radius * 2, height + radius * 2.0))); } -void CapsuleShapeSW::set_data(const Variant& p_data) { +void CapsuleShapeSW::set_data(const Variant &p_data) { Dictionary d = p_data; ERR_FAIL_COND(!d.has("radius")); ERR_FAIL_COND(!d.has("height")); - _setup(d["height"],d["radius"]); - + _setup(d["height"], d["radius"]); } Variant CapsuleShapeSW::get_data() const { Dictionary d; - d["radius"]=radius; - d["height"]=height; + d["radius"] = radius; + d["height"] = height; return d; - } +CapsuleShapeSW::CapsuleShapeSW() { -CapsuleShapeSW::CapsuleShapeSW() { - - height=radius=0; - + height = radius = 0; } /********** CONVEX POLYGON *************/ +void ConvexPolygonShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { -void ConvexPolygonShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { - - - int vertex_count=mesh.vertices.size(); - if (vertex_count==0) + int vertex_count = mesh.vertices.size(); + if (vertex_count == 0) return; - const Vector3 *vrts=&mesh.vertices[0]; + const Vector3 *vrts = &mesh.vertices[0]; - for (int i=0;i<vertex_count;i++) { + for (int i = 0; i < vertex_count; i++) { - real_t d=p_normal.dot( p_transform.xform( vrts[i] ) ); + real_t d = p_normal.dot(p_transform.xform(vrts[i])); - if (i==0 || d > r_max) - r_max=d; - if (i==0 || d < r_min) - r_min=d; + if (i == 0 || d > r_max) + r_max = d; + if (i == 0 || d < r_min) + r_min = d; } } -Vector3 ConvexPolygonShapeSW::get_support(const Vector3& p_normal) const { +Vector3 ConvexPolygonShapeSW::get_support(const Vector3 &p_normal) const { - Vector3 n=p_normal; + Vector3 n = p_normal; - int vert_support_idx=-1; + int vert_support_idx = -1; real_t support_max; - int vertex_count=mesh.vertices.size(); - if (vertex_count==0) + int vertex_count = mesh.vertices.size(); + if (vertex_count == 0) return Vector3(); - const Vector3 *vrts=&mesh.vertices[0]; + const Vector3 *vrts = &mesh.vertices[0]; - for (int i=0;i<vertex_count;i++) { + for (int i = 0; i < vertex_count; i++) { - real_t d=n.dot(vrts[i]); + real_t d = n.dot(vrts[i]); - if (i==0 || d > support_max) { - support_max=d; - vert_support_idx=i; + if (i == 0 || d > support_max) { + support_max = d; + vert_support_idx = i; } } - return vrts[vert_support_idx]; - + return vrts[vert_support_idx]; } - - -void ConvexPolygonShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { +void ConvexPolygonShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { const Geometry::MeshData::Face *faces = mesh.faces.ptr(); int fc = mesh.faces.size(); @@ -700,28 +642,27 @@ void ConvexPolygonShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector real_t max; int vtx; - for (int i=0;i<vc;i++) { + for (int i = 0; i < vc; i++) { - real_t d=p_normal.dot(vertices[i]); + real_t d = p_normal.dot(vertices[i]); - if (i==0 || d > max) { - max=d; - vtx=i; + if (i == 0 || d > max) { + max = d; + vtx = i; } } + for (int i = 0; i < fc; i++) { - for(int i=0;i<fc;i++) { - - if (faces[i].plane.normal.dot(p_normal)>_FACE_IS_VALID_SUPPORT_TRESHOLD) { + if (faces[i].plane.normal.dot(p_normal) > _FACE_IS_VALID_SUPPORT_TRESHOLD) { int ic = faces[i].indices.size(); - const int *ind=faces[i].indices.ptr(); + const int *ind = faces[i].indices.ptr(); - bool valid=false; - for(int j=0;j<ic;j++) { - if (ind[j]==vtx) { - valid=true; + bool valid = false; + for (int j = 0; j < ic; j++) { + if (ind[j] == vtx) { + valid = true; break; } } @@ -729,114 +670,103 @@ void ConvexPolygonShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector if (!valid) continue; - int m = MIN(p_max,ic); - for(int j=0;j<m;j++) { + int m = MIN(p_max, ic); + for (int j = 0; j < m; j++) { - r_supports[j]=vertices[ind[j]]; + r_supports[j] = vertices[ind[j]]; } - r_amount=m; + r_amount = m; return; } } - for(int i=0;i<ec;i++) { + for (int i = 0; i < ec; i++) { + real_t dot = (vertices[edges[i].a] - vertices[edges[i].b]).normalized().dot(p_normal); + dot = ABS(dot); + if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD && (edges[i].a == vtx || edges[i].b == vtx)) { - real_t dot=(vertices[edges[i].a]-vertices[edges[i].b]).normalized().dot(p_normal); - dot=ABS(dot); - if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD && (edges[i].a==vtx || edges[i].b==vtx)) { - - r_amount=2; - r_supports[0]=vertices[edges[i].a]; - r_supports[1]=vertices[edges[i].b]; + r_amount = 2; + r_supports[0] = vertices[edges[i].a]; + r_supports[1] = vertices[edges[i].b]; return; } } - - r_supports[0]=vertices[vtx]; - r_amount=1; + r_supports[0] = vertices[vtx]; + r_amount = 1; } -bool ConvexPolygonShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { - - +bool ConvexPolygonShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { const Geometry::MeshData::Face *faces = mesh.faces.ptr(); int fc = mesh.faces.size(); const Vector3 *vertices = mesh.vertices.ptr(); - Vector3 n = p_end-p_begin; + Vector3 n = p_end - p_begin; real_t min = 1e20; - bool col=false; + bool col = false; - for(int i=0;i<fc;i++) { + for (int i = 0; i < fc; i++) { if (faces[i].plane.normal.dot(n) > 0) continue; //opposing face int ic = faces[i].indices.size(); - const int *ind=faces[i].indices.ptr(); + const int *ind = faces[i].indices.ptr(); - for(int j=1;j<ic-1;j++) { + for (int j = 1; j < ic - 1; j++) { - Face3 f(vertices[ind[0]],vertices[ind[j]],vertices[ind[j+1]]); + Face3 f(vertices[ind[0]], vertices[ind[j]], vertices[ind[j + 1]]); Vector3 result; - if (f.intersects_segment(p_begin,p_end,&result)) { + if (f.intersects_segment(p_begin, p_end, &result)) { real_t d = n.dot(result); - if (d<min) { - min=d; - r_result=result; - r_normal=faces[i].plane.normal; - col=true; + if (d < min) { + min = d; + r_result = result; + r_normal = faces[i].plane.normal; + col = true; } break; } - } } return col; - } Vector3 ConvexPolygonShapeSW::get_moment_of_inertia(real_t p_mass) const { // use crappy AABB approximation - Vector3 extents=get_aabb().size*0.5; - - return Vector3( - (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z), - (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z), - (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y) - ); + Vector3 extents = get_aabb().size * 0.5; + return Vector3( + (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z), + (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z), + (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y)); } -void ConvexPolygonShapeSW::_setup(const Vector<Vector3>& p_vertices) { +void ConvexPolygonShapeSW::_setup(const Vector<Vector3> &p_vertices) { - Error err = QuickHull::build(p_vertices,mesh); + Error err = QuickHull::build(p_vertices, mesh); Rect3 _aabb; - for(int i=0;i<mesh.vertices.size();i++) { + for (int i = 0; i < mesh.vertices.size(); i++) { - if (i==0) - _aabb.pos=mesh.vertices[i]; + if (i == 0) + _aabb.pos = mesh.vertices[i]; else _aabb.expand_to(mesh.vertices[i]); } configure(_aabb); - - } -void ConvexPolygonShapeSW::set_data(const Variant& p_data) { +void ConvexPolygonShapeSW::set_data(const Variant &p_data) { _setup(p_data); - } Variant ConvexPolygonShapeSW::get_data() const { @@ -844,113 +774,105 @@ Variant ConvexPolygonShapeSW::get_data() const { return mesh.vertices; } - -ConvexPolygonShapeSW::ConvexPolygonShapeSW() { - - +ConvexPolygonShapeSW::ConvexPolygonShapeSW() { } - /********** FACE POLYGON *************/ +void FaceShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { -void FaceShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { + for (int i = 0; i < 3; i++) { - for (int i=0;i<3;i++) { + Vector3 v = p_transform.xform(vertex[i]); + real_t d = p_normal.dot(v); - Vector3 v=p_transform.xform(vertex[i]); - real_t d=p_normal.dot(v); + if (i == 0 || d > r_max) + r_max = d; - if (i==0 || d > r_max) - r_max=d; - - if (i==0 || d < r_min) - r_min=d; + if (i == 0 || d < r_min) + r_min = d; } } -Vector3 FaceShapeSW::get_support(const Vector3& p_normal) const { - +Vector3 FaceShapeSW::get_support(const Vector3 &p_normal) const { - int vert_support_idx=-1; + int vert_support_idx = -1; real_t support_max; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - real_t d=p_normal.dot(vertex[i]); + real_t d = p_normal.dot(vertex[i]); - if (i==0 || d > support_max) { - support_max=d; - vert_support_idx=i; + if (i == 0 || d > support_max) { + support_max = d; + vert_support_idx = i; } } return vertex[vert_support_idx]; } -void FaceShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { +void FaceShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { - Vector3 n=p_normal; + Vector3 n = p_normal; /** TEST FACE AS SUPPORT **/ if (normal.dot(n) > _FACE_IS_VALID_SUPPORT_TRESHOLD) { - r_amount=3; - for (int i=0;i<3;i++) { + r_amount = 3; + for (int i = 0; i < 3; i++) { - r_supports[i]=vertex[i]; + r_supports[i] = vertex[i]; } return; - } /** FIND SUPPORT VERTEX **/ - int vert_support_idx=-1; + int vert_support_idx = -1; real_t support_max; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - real_t d=n.dot(vertex[i]); + real_t d = n.dot(vertex[i]); - if (i==0 || d > support_max) { - support_max=d; - vert_support_idx=i; + if (i == 0 || d > support_max) { + support_max = d; + vert_support_idx = i; } } /** TEST EDGES AS SUPPORT **/ - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - int nx=(i+1)%3; - if (i!=vert_support_idx && nx!=vert_support_idx) + int nx = (i + 1) % 3; + if (i != vert_support_idx && nx != vert_support_idx) continue; - // check if edge is valid as a support - real_t dot=(vertex[i]-vertex[nx]).normalized().dot(n); - dot=ABS(dot); + // check if edge is valid as a support + real_t dot = (vertex[i] - vertex[nx]).normalized().dot(n); + dot = ABS(dot); if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD) { - r_amount=2; - r_supports[0]=vertex[i]; - r_supports[1]=vertex[nx]; + r_amount = 2; + r_supports[0] = vertex[i]; + r_supports[1] = vertex[nx]; return; } } - r_amount=1; - r_supports[0]=vertex[vert_support_idx]; + r_amount = 1; + r_supports[0] = vertex[vert_support_idx]; } -bool FaceShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { +bool FaceShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { - - bool c=Geometry::segment_intersects_triangle(p_begin,p_end,vertex[0],vertex[1],vertex[2],&r_result); + bool c = Geometry::segment_intersects_triangle(p_begin, p_end, vertex[0], vertex[1], vertex[2], &r_result); if (c) { - r_normal=Plane(vertex[0],vertex[1],vertex[2]).normal; - if (r_normal.dot(p_end-p_begin)>0) { - r_normal=-r_normal; + r_normal = Plane(vertex[0], vertex[1], vertex[2]).normal; + if (r_normal.dot(p_end - p_begin) > 0) { + r_normal = -r_normal; } } @@ -960,183 +882,162 @@ bool FaceShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end, Vector3 FaceShapeSW::get_moment_of_inertia(real_t p_mass) const { return Vector3(); // Sorry, but i don't think anyone cares, FaceShape! - } -FaceShapeSW::FaceShapeSW() { +FaceShapeSW::FaceShapeSW() { configure(Rect3()); - } - - PoolVector<Vector3> ConcavePolygonShapeSW::get_faces() const { - PoolVector<Vector3> rfaces; - rfaces.resize(faces.size()*3); + rfaces.resize(faces.size() * 3); - for(int i=0;i<faces.size();i++) { + for (int i = 0; i < faces.size(); i++) { - Face f=faces.get(i); + Face f = faces.get(i); - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - rfaces.set(i*3+j, vertices.get( f.indices[j] ) ); + rfaces.set(i * 3 + j, vertices.get(f.indices[j])); } } return rfaces; } -void ConcavePolygonShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { +void ConcavePolygonShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { - int count=vertices.size(); - if (count==0) { - r_min=0; - r_max=0; + int count = vertices.size(); + if (count == 0) { + r_min = 0; + r_max = 0; return; } - PoolVector<Vector3>::Read r=vertices.read(); - const Vector3 *vptr=r.ptr(); + PoolVector<Vector3>::Read r = vertices.read(); + const Vector3 *vptr = r.ptr(); - for (int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - real_t d=p_normal.dot( p_transform.xform( vptr[i] ) ); - - if (i==0 || d > r_max) - r_max=d; - if (i==0 || d < r_min) - r_min=d; + real_t d = p_normal.dot(p_transform.xform(vptr[i])); + if (i == 0 || d > r_max) + r_max = d; + if (i == 0 || d < r_min) + r_min = d; } } -Vector3 ConcavePolygonShapeSW::get_support(const Vector3& p_normal) const { - +Vector3 ConcavePolygonShapeSW::get_support(const Vector3 &p_normal) const { - int count=vertices.size(); - if (count==0) + int count = vertices.size(); + if (count == 0) return Vector3(); - PoolVector<Vector3>::Read r=vertices.read(); - const Vector3 *vptr=r.ptr(); + PoolVector<Vector3>::Read r = vertices.read(); + const Vector3 *vptr = r.ptr(); - Vector3 n=p_normal; + Vector3 n = p_normal; - int vert_support_idx=-1; + int vert_support_idx = -1; real_t support_max; - for (int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - real_t d=n.dot(vptr[i]); + real_t d = n.dot(vptr[i]); - if (i==0 || d > support_max) { - support_max=d; - vert_support_idx=i; + if (i == 0 || d > support_max) { + support_max = d; + vert_support_idx = i; } } - return vptr[vert_support_idx]; - } -void ConcavePolygonShapeSW::_cull_segment(int p_idx,_SegmentCullParams *p_params) const { - - const BVH *bvh=&p_params->bvh[p_idx]; +void ConcavePolygonShapeSW::_cull_segment(int p_idx, _SegmentCullParams *p_params) const { + const BVH *bvh = &p_params->bvh[p_idx]; /* if (p_params->dir.dot(bvh->aabb.get_support(-p_params->dir))>p_params->min_d) return; //test against whole AABB, which isn't very costly */ - //printf("addr: %p\n",bvh); - if (!bvh->aabb.intersects_segment(p_params->from,p_params->to)) { + if (!bvh->aabb.intersects_segment(p_params->from, p_params->to)) { return; } - - if (bvh->face_index>=0) { - + if (bvh->face_index >= 0) { Vector3 res; - Vector3 vertices[3]={ - p_params->vertices[ p_params->faces[ bvh->face_index ].indices[0] ], - p_params->vertices[ p_params->faces[ bvh->face_index ].indices[1] ], - p_params->vertices[ p_params->faces[ bvh->face_index ].indices[2] ] + Vector3 vertices[3] = { + p_params->vertices[p_params->faces[bvh->face_index].indices[0]], + p_params->vertices[p_params->faces[bvh->face_index].indices[1]], + p_params->vertices[p_params->faces[bvh->face_index].indices[2]] }; if (Geometry::segment_intersects_triangle( - p_params->from, - p_params->to, - vertices[0], - vertices[1], - vertices[2], - &res)) { - - - real_t d=p_params->dir.dot(res) - p_params->dir.dot(p_params->from); + p_params->from, + p_params->to, + vertices[0], + vertices[1], + vertices[2], + &res)) { + + real_t d = p_params->dir.dot(res) - p_params->dir.dot(p_params->from); //TODO, seems segmen/triangle intersection is broken :( - if (d>0 && d<p_params->min_d) { + if (d > 0 && d < p_params->min_d) { - p_params->min_d=d; - p_params->result=res; - p_params->normal=Plane(vertices[0],vertices[1],vertices[2]).normal; - if (p_params->normal.dot(p_params->dir)>0) - p_params->normal=-p_params->normal; + p_params->min_d = d; + p_params->result = res; + p_params->normal = Plane(vertices[0], vertices[1], vertices[2]).normal; + if (p_params->normal.dot(p_params->dir) > 0) + p_params->normal = -p_params->normal; p_params->collisions++; } - } - - } else { - if (bvh->left>=0) - _cull_segment(bvh->left,p_params); - if (bvh->right>=0) - _cull_segment(bvh->right,p_params); - - + if (bvh->left >= 0) + _cull_segment(bvh->left, p_params); + if (bvh->right >= 0) + _cull_segment(bvh->right, p_params); } } -bool ConcavePolygonShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { +bool ConcavePolygonShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { - if (faces.size()==0) + if (faces.size() == 0) return false; // unlock data - PoolVector<Face>::Read fr=faces.read(); - PoolVector<Vector3>::Read vr=vertices.read(); - PoolVector<BVH>::Read br=bvh.read(); - + PoolVector<Face>::Read fr = faces.read(); + PoolVector<Vector3>::Read vr = vertices.read(); + PoolVector<BVH>::Read br = bvh.read(); _SegmentCullParams params; - params.from=p_begin; - params.to=p_end; - params.collisions=0; - params.dir=(p_end-p_begin).normalized(); + params.from = p_begin; + params.to = p_end; + params.collisions = 0; + params.dir = (p_end - p_begin).normalized(); - params.faces=fr.ptr(); - params.vertices=vr.ptr(); - params.bvh=br.ptr(); + params.faces = fr.ptr(); + params.vertices = vr.ptr(); + params.bvh = br.ptr(); - params.min_d=1e20; + params.min_d = 1e20; // cull - _cull_segment(0,¶ms); - - if (params.collisions>0) { + _cull_segment(0, ¶ms); + if (params.collisions > 0) { - r_result=params.result; - r_normal=params.normal; + r_result = params.result; + r_normal = params.normal; return true; } else { @@ -1144,81 +1045,76 @@ bool ConcavePolygonShapeSW::intersect_segment(const Vector3& p_begin,const Vecto } } -void ConcavePolygonShapeSW::_cull(int p_idx,_CullParams *p_params) const { +void ConcavePolygonShapeSW::_cull(int p_idx, _CullParams *p_params) const { - const BVH* bvh=&p_params->bvh[p_idx]; + const BVH *bvh = &p_params->bvh[p_idx]; - if (!p_params->aabb.intersects( bvh->aabb )) + if (!p_params->aabb.intersects(bvh->aabb)) return; - if (bvh->face_index>=0) { + if (bvh->face_index >= 0) { - const Face *f=&p_params->faces[ bvh->face_index ]; - FaceShapeSW *face=p_params->face; - face->normal=f->normal; - face->vertex[0]=p_params->vertices[f->indices[0]]; - face->vertex[1]=p_params->vertices[f->indices[1]]; - face->vertex[2]=p_params->vertices[f->indices[2]]; - p_params->callback(p_params->userdata,face); + const Face *f = &p_params->faces[bvh->face_index]; + FaceShapeSW *face = p_params->face; + face->normal = f->normal; + face->vertex[0] = p_params->vertices[f->indices[0]]; + face->vertex[1] = p_params->vertices[f->indices[1]]; + face->vertex[2] = p_params->vertices[f->indices[2]]; + p_params->callback(p_params->userdata, face); } else { - if (bvh->left>=0) { - - _cull(bvh->left,p_params); + if (bvh->left >= 0) { + _cull(bvh->left, p_params); } - if (bvh->right>=0) { + if (bvh->right >= 0) { - _cull(bvh->right,p_params); + _cull(bvh->right, p_params); } - } } -void ConcavePolygonShapeSW::cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const { +void ConcavePolygonShapeSW::cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const { // make matrix local to concave - if (faces.size()==0) + if (faces.size() == 0) return; - Rect3 local_aabb=p_local_aabb; + Rect3 local_aabb = p_local_aabb; // unlock data - PoolVector<Face>::Read fr=faces.read(); - PoolVector<Vector3>::Read vr=vertices.read(); - PoolVector<BVH>::Read br=bvh.read(); + PoolVector<Face>::Read fr = faces.read(); + PoolVector<Vector3>::Read vr = vertices.read(); + PoolVector<BVH>::Read br = bvh.read(); FaceShapeSW face; // use this to send in the callback _CullParams params; - params.aabb=local_aabb; - params.face=&face; - params.faces=fr.ptr(); - params.vertices=vr.ptr(); - params.bvh=br.ptr(); - params.callback=p_callback; - params.userdata=p_userdata; + params.aabb = local_aabb; + params.face = &face; + params.faces = fr.ptr(); + params.vertices = vr.ptr(); + params.bvh = br.ptr(); + params.callback = p_callback; + params.userdata = p_userdata; // cull - _cull(0,¶ms); - + _cull(0, ¶ms); } Vector3 ConcavePolygonShapeSW::get_moment_of_inertia(real_t p_mass) const { // use crappy AABB approximation - Vector3 extents=get_aabb().size*0.5; + Vector3 extents = get_aabb().size * 0.5; return Vector3( - (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z), - (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z), - (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y) - ); + (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z), + (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z), + (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y)); } - struct _VolumeSW_BVH_Element { Rect3 aabb; @@ -1228,26 +1124,25 @@ struct _VolumeSW_BVH_Element { struct _VolumeSW_BVH_CompareX { - _FORCE_INLINE_ bool operator ()(const _VolumeSW_BVH_Element& a, const _VolumeSW_BVH_Element& b) const { + _FORCE_INLINE_ bool operator()(const _VolumeSW_BVH_Element &a, const _VolumeSW_BVH_Element &b) const { - return a.center.x<b.center.x; + return a.center.x < b.center.x; } }; - struct _VolumeSW_BVH_CompareY { - _FORCE_INLINE_ bool operator ()(const _VolumeSW_BVH_Element& a, const _VolumeSW_BVH_Element& b) const { + _FORCE_INLINE_ bool operator()(const _VolumeSW_BVH_Element &a, const _VolumeSW_BVH_Element &b) const { - return a.center.y<b.center.y; + return a.center.y < b.center.y; } }; struct _VolumeSW_BVH_CompareZ { - _FORCE_INLINE_ bool operator ()(const _VolumeSW_BVH_Element& a, const _VolumeSW_BVH_Element& b) const { + _FORCE_INLINE_ bool operator()(const _VolumeSW_BVH_Element &a, const _VolumeSW_BVH_Element &b) const { - return a.center.z<b.center.z; + return a.center.z < b.center.z; } }; @@ -1260,107 +1155,102 @@ struct _VolumeSW_BVH { int face_index; }; +_VolumeSW_BVH *_volume_sw_build_bvh(_VolumeSW_BVH_Element *p_elements, int p_size, int &count) { -_VolumeSW_BVH* _volume_sw_build_bvh(_VolumeSW_BVH_Element *p_elements,int p_size,int &count) { - - _VolumeSW_BVH* bvh = memnew( _VolumeSW_BVH ); + _VolumeSW_BVH *bvh = memnew(_VolumeSW_BVH); - if (p_size==1) { + if (p_size == 1) { //leaf - bvh->aabb=p_elements[0].aabb; - bvh->left=NULL; - bvh->right=NULL; - bvh->face_index=p_elements->face_index; + bvh->aabb = p_elements[0].aabb; + bvh->left = NULL; + bvh->right = NULL; + bvh->face_index = p_elements->face_index; count++; return bvh; } else { - bvh->face_index=-1; + bvh->face_index = -1; } Rect3 aabb; - for(int i=0;i<p_size;i++) { + for (int i = 0; i < p_size; i++) { - if (i==0) - aabb=p_elements[i].aabb; + if (i == 0) + aabb = p_elements[i].aabb; else aabb.merge_with(p_elements[i].aabb); } - bvh->aabb=aabb; - switch(aabb.get_longest_axis_index()) { + bvh->aabb = aabb; + switch (aabb.get_longest_axis_index()) { case 0: { - SortArray<_VolumeSW_BVH_Element,_VolumeSW_BVH_CompareX> sort_x; - sort_x.sort(p_elements,p_size); + SortArray<_VolumeSW_BVH_Element, _VolumeSW_BVH_CompareX> sort_x; + sort_x.sort(p_elements, p_size); } break; case 1: { - SortArray<_VolumeSW_BVH_Element,_VolumeSW_BVH_CompareY> sort_y; - sort_y.sort(p_elements,p_size); + SortArray<_VolumeSW_BVH_Element, _VolumeSW_BVH_CompareY> sort_y; + sort_y.sort(p_elements, p_size); } break; case 2: { - SortArray<_VolumeSW_BVH_Element,_VolumeSW_BVH_CompareZ> sort_z; - sort_z.sort(p_elements,p_size); + SortArray<_VolumeSW_BVH_Element, _VolumeSW_BVH_CompareZ> sort_z; + sort_z.sort(p_elements, p_size); } break; } - int split=p_size/2; - bvh->left=_volume_sw_build_bvh(p_elements,split,count); - bvh->right=_volume_sw_build_bvh(&p_elements[split],p_size-split,count); + int split = p_size / 2; + bvh->left = _volume_sw_build_bvh(p_elements, split, count); + bvh->right = _volume_sw_build_bvh(&p_elements[split], p_size - split, count); //printf("branch at %p - %i: %i\n",bvh,count,bvh->face_index); count++; return bvh; } +void ConcavePolygonShapeSW::_fill_bvh(_VolumeSW_BVH *p_bvh_tree, BVH *p_bvh_array, int &p_idx) { -void ConcavePolygonShapeSW::_fill_bvh(_VolumeSW_BVH* p_bvh_tree,BVH* p_bvh_array,int& p_idx) { - - int idx=p_idx; - + int idx = p_idx; - p_bvh_array[idx].aabb=p_bvh_tree->aabb; - p_bvh_array[idx].face_index=p_bvh_tree->face_index; + p_bvh_array[idx].aabb = p_bvh_tree->aabb; + p_bvh_array[idx].face_index = p_bvh_tree->face_index; //printf("%p - %i: %i(%p) -- %p:%p\n",%p_bvh_array[idx],p_idx,p_bvh_array[i]->face_index,&p_bvh_tree->face_index,p_bvh_tree->left,p_bvh_tree->right); - if (p_bvh_tree->left) { - p_bvh_array[idx].left=++p_idx; - _fill_bvh(p_bvh_tree->left,p_bvh_array,p_idx); + p_bvh_array[idx].left = ++p_idx; + _fill_bvh(p_bvh_tree->left, p_bvh_array, p_idx); } else { - p_bvh_array[p_idx].left=-1; + p_bvh_array[p_idx].left = -1; } if (p_bvh_tree->right) { - p_bvh_array[idx].right=++p_idx; - _fill_bvh(p_bvh_tree->right,p_bvh_array,p_idx); + p_bvh_array[idx].right = ++p_idx; + _fill_bvh(p_bvh_tree->right, p_bvh_array, p_idx); } else { - p_bvh_array[p_idx].right=-1; + p_bvh_array[p_idx].right = -1; } memdelete(p_bvh_tree); - } void ConcavePolygonShapeSW::_setup(PoolVector<Vector3> p_faces) { - int src_face_count=p_faces.size(); - if (src_face_count==0) { + int src_face_count = p_faces.size(); + if (src_face_count == 0) { configure(Rect3()); return; } - ERR_FAIL_COND(src_face_count%3); - src_face_count/=3; + ERR_FAIL_COND(src_face_count % 3); + src_face_count /= 3; PoolVector<Vector3>::Read r = p_faces.read(); - const Vector3 * facesr= r.ptr(); + const Vector3 *facesr = r.ptr(); #if 0 Map<Vector3,int> point_map; @@ -1476,67 +1366,62 @@ void ConcavePolygonShapeSW::_setup(PoolVector<Vector3> p_faces) { #else PoolVector<_VolumeSW_BVH_Element> bvh_array; - bvh_array.resize( src_face_count ); + bvh_array.resize(src_face_count); PoolVector<_VolumeSW_BVH_Element>::Write bvhw = bvh_array.write(); - _VolumeSW_BVH_Element *bvh_arrayw=bvhw.ptr(); + _VolumeSW_BVH_Element *bvh_arrayw = bvhw.ptr(); faces.resize(src_face_count); PoolVector<Face>::Write w = faces.write(); - Face *facesw=w.ptr(); + Face *facesw = w.ptr(); - vertices.resize( src_face_count*3 ); + vertices.resize(src_face_count * 3); PoolVector<Vector3>::Write vw = vertices.write(); - Vector3 *verticesw=vw.ptr(); + Vector3 *verticesw = vw.ptr(); Rect3 _aabb; + for (int i = 0; i < src_face_count; i++) { - for(int i=0;i<src_face_count;i++) { - - Face3 face( facesr[i*3+0], facesr[i*3+1], facesr[i*3+2] ); + Face3 face(facesr[i * 3 + 0], facesr[i * 3 + 1], facesr[i * 3 + 2]); - bvh_arrayw[i].aabb=face.get_aabb(); + bvh_arrayw[i].aabb = face.get_aabb(); bvh_arrayw[i].center = bvh_arrayw[i].aabb.pos + bvh_arrayw[i].aabb.size * 0.5; - bvh_arrayw[i].face_index=i; - facesw[i].indices[0]=i*3+0; - facesw[i].indices[1]=i*3+1; - facesw[i].indices[2]=i*3+2; - facesw[i].normal=face.get_plane().normal; - verticesw[i*3+0]=face.vertex[0]; - verticesw[i*3+1]=face.vertex[1]; - verticesw[i*3+2]=face.vertex[2]; - if (i==0) - _aabb=bvh_arrayw[i].aabb; + bvh_arrayw[i].face_index = i; + facesw[i].indices[0] = i * 3 + 0; + facesw[i].indices[1] = i * 3 + 1; + facesw[i].indices[2] = i * 3 + 2; + facesw[i].normal = face.get_plane().normal; + verticesw[i * 3 + 0] = face.vertex[0]; + verticesw[i * 3 + 1] = face.vertex[1]; + verticesw[i * 3 + 2] = face.vertex[2]; + if (i == 0) + _aabb = bvh_arrayw[i].aabb; else _aabb.merge_with(bvh_arrayw[i].aabb); - } - w=PoolVector<Face>::Write(); - vw=PoolVector<Vector3>::Write(); + w = PoolVector<Face>::Write(); + vw = PoolVector<Vector3>::Write(); - int count=0; - _VolumeSW_BVH *bvh_tree=_volume_sw_build_bvh(bvh_arrayw,src_face_count,count); + int count = 0; + _VolumeSW_BVH *bvh_tree = _volume_sw_build_bvh(bvh_arrayw, src_face_count, count); - bvh.resize( count+1 ); + bvh.resize(count + 1); PoolVector<BVH>::Write bvhw2 = bvh.write(); - BVH*bvh_arrayw2=bvhw2.ptr(); + BVH *bvh_arrayw2 = bvhw2.ptr(); - int idx=0; - _fill_bvh(bvh_tree,bvh_arrayw2,idx); + int idx = 0; + _fill_bvh(bvh_tree, bvh_arrayw2, idx); configure(_aabb); // this type of shape has no margin - #endif } - -void ConcavePolygonShapeSW::set_data(const Variant& p_data) { - +void ConcavePolygonShapeSW::set_data(const Variant &p_data) { _setup(p_data); } @@ -1547,12 +1432,8 @@ Variant ConcavePolygonShapeSW::get_data() const { } ConcavePolygonShapeSW::ConcavePolygonShapeSW() { - - } - - /* HEIGHT MAP SHAPE */ PoolVector<real_t> HeightMapShapeSW::get_heights() const { @@ -1572,114 +1453,94 @@ real_t HeightMapShapeSW::get_cell_size() const { return cell_size; } - -void HeightMapShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { +void HeightMapShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { //not very useful, but not very used either - p_transform.xform(get_aabb()).project_range_in_plane( Plane(p_normal,0),r_min,r_max ); - + p_transform.xform(get_aabb()).project_range_in_plane(Plane(p_normal, 0), r_min, r_max); } -Vector3 HeightMapShapeSW::get_support(const Vector3& p_normal) const { - +Vector3 HeightMapShapeSW::get_support(const Vector3 &p_normal) const { //not very useful, but not very used either return get_aabb().get_support(p_normal); - } -bool HeightMapShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const { - +bool HeightMapShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const { return false; } - -void HeightMapShapeSW::cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const { - - - +void HeightMapShapeSW::cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const { } - Vector3 HeightMapShapeSW::get_moment_of_inertia(real_t p_mass) const { - // use crappy AABB approximation - Vector3 extents=get_aabb().size*0.5; + Vector3 extents = get_aabb().size * 0.5; return Vector3( - (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z), - (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z), - (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y) - ); + (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z), + (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z), + (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y)); } +void HeightMapShapeSW::_setup(PoolVector<real_t> p_heights, int p_width, int p_depth, real_t p_cell_size) { -void HeightMapShapeSW::_setup(PoolVector<real_t> p_heights,int p_width,int p_depth,real_t p_cell_size) { + heights = p_heights; + width = p_width; + depth = p_depth; + cell_size = p_cell_size; - heights=p_heights; - width=p_width; - depth=p_depth; - cell_size=p_cell_size; - - PoolVector<real_t>::Read r = heights. read(); + PoolVector<real_t>::Read r = heights.read(); Rect3 aabb; - for(int i=0;i<depth;i++) { + for (int i = 0; i < depth; i++) { - for(int j=0;j<width;j++) { + for (int j = 0; j < width; j++) { - real_t h = r[i*width+j]; + real_t h = r[i * width + j]; - Vector3 pos( j*cell_size, h, i*cell_size ); - if (i==0 || j==0) - aabb.pos=pos; + Vector3 pos(j * cell_size, h, i * cell_size); + if (i == 0 || j == 0) + aabb.pos = pos; else aabb.expand_to(pos); - } } - configure(aabb); } -void HeightMapShapeSW::set_data(const Variant& p_data) { +void HeightMapShapeSW::set_data(const Variant &p_data) { - ERR_FAIL_COND( p_data.get_type()!=Variant::DICTIONARY ); - Dictionary d=p_data; - ERR_FAIL_COND( !d.has("width") ); - ERR_FAIL_COND( !d.has("depth") ); - ERR_FAIL_COND( !d.has("cell_size") ); - ERR_FAIL_COND( !d.has("heights") ); - - int width=d["width"]; - int depth=d["depth"]; - real_t cell_size=d["cell_size"]; - PoolVector<real_t> heights=d["heights"]; + ERR_FAIL_COND(p_data.get_type() != Variant::DICTIONARY); + Dictionary d = p_data; + ERR_FAIL_COND(!d.has("width")); + ERR_FAIL_COND(!d.has("depth")); + ERR_FAIL_COND(!d.has("cell_size")); + ERR_FAIL_COND(!d.has("heights")); - ERR_FAIL_COND( width<= 0); - ERR_FAIL_COND( depth<= 0); - ERR_FAIL_COND( cell_size<= CMP_EPSILON); - ERR_FAIL_COND( heights.size() != (width*depth) ); - _setup(heights, width, depth, cell_size ); + int width = d["width"]; + int depth = d["depth"]; + real_t cell_size = d["cell_size"]; + PoolVector<real_t> heights = d["heights"]; + ERR_FAIL_COND(width <= 0); + ERR_FAIL_COND(depth <= 0); + ERR_FAIL_COND(cell_size <= CMP_EPSILON); + ERR_FAIL_COND(heights.size() != (width * depth)); + _setup(heights, width, depth, cell_size); } Variant HeightMapShapeSW::get_data() const { ERR_FAIL_V(Variant()); - } HeightMapShapeSW::HeightMapShapeSW() { - width=0; - depth=0; - cell_size=0; + width = 0; + depth = 0; + cell_size = 0; } - - - diff --git a/servers/physics/shape_sw.h b/servers/physics/shape_sw.h index 55daa5856d..442cbc39eb 100644 --- a/servers/physics/shape_sw.h +++ b/servers/physics/shape_sw.h @@ -29,9 +29,9 @@ #ifndef SHAPE_SW_H #define SHAPE_SW_H -#include "servers/physics_server.h" #include "bsp_tree.h" #include "geometry.h" +#include "servers/physics_server.h" /* SHAPE_LINE, ///< plane:"plane" @@ -46,16 +46,14 @@ SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_creat class ShapeSW; -class ShapeOwnerSW : public RID_Data { +class ShapeOwnerSW : public RID_Data { public: - - virtual void _shape_changed()=0; - virtual void remove_shape(ShapeSW *p_shape)=0; + virtual void _shape_changed() = 0; + virtual void remove_shape(ShapeSW *p_shape) = 0; virtual ~ShapeOwnerSW() {} }; - class ShapeSW : public RID_Data { RID self; @@ -63,60 +61,58 @@ class ShapeSW : public RID_Data { bool configured; real_t custom_bias; - Map<ShapeOwnerSW*,int> owners; + Map<ShapeOwnerSW *, int> owners; + protected: + void configure(const Rect3 &p_aabb); - void configure(const Rect3& p_aabb); public: - enum { - MAX_SUPPORTS=8 + MAX_SUPPORTS = 8 }; - virtual real_t get_area() const { return aabb.get_area();} + virtual real_t get_area() const { return aabb.get_area(); } - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } - _FORCE_INLINE_ RID get_self() const {return self; } + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } + _FORCE_INLINE_ RID get_self() const { return self; } - virtual PhysicsServer::ShapeType get_type() const=0; + virtual PhysicsServer::ShapeType get_type() const = 0; _FORCE_INLINE_ Rect3 get_aabb() const { return aabb; } _FORCE_INLINE_ bool is_configured() const { return configured; } virtual bool is_concave() const { return false; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const=0; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const=0; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const = 0; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const = 0; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const=0; - virtual Vector3 get_moment_of_inertia(real_t p_mass) const=0; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const = 0; + virtual Vector3 get_moment_of_inertia(real_t p_mass) const = 0; - virtual void set_data(const Variant& p_data)=0; - virtual Variant get_data() const=0; + virtual void set_data(const Variant &p_data) = 0; + virtual Variant get_data() const = 0; - _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias=p_bias; } + _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias = p_bias; } _FORCE_INLINE_ real_t get_custom_bias() const { return custom_bias; } void add_owner(ShapeOwnerSW *p_owner); void remove_owner(ShapeOwnerSW *p_owner); bool is_owner(ShapeOwnerSW *p_owner) const; - const Map<ShapeOwnerSW*,int>& get_owners() const; + const Map<ShapeOwnerSW *, int> &get_owners() const; ShapeSW(); virtual ~ShapeSW(); }; - class ConcaveShapeSW : public ShapeSW { public: - virtual bool is_concave() const { return true; } - typedef void (*Callback)(void* p_userdata,ShapeSW *p_convex); - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { r_amount=0; } + typedef void (*Callback)(void *p_userdata, ShapeSW *p_convex); + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { r_amount = 0; } - virtual void cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const=0; + virtual void cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const = 0; ConcaveShapeSW() {} }; @@ -125,22 +121,22 @@ class PlaneShapeSW : public ShapeSW { Plane plane; - void _setup(const Plane& p_plane); -public: + void _setup(const Plane &p_plane); +public: Plane get_plane() const; virtual real_t get_area() const { return Math_INF; } virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_PLANE; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { r_amount=0; } + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { r_amount = 0; } - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; PlaneShapeSW(); @@ -151,21 +147,21 @@ class RayShapeSW : public ShapeSW { real_t length; void _setup(real_t p_length); -public: +public: real_t get_length() const; virtual real_t get_area() const { return 0.0; } virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_RAY; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; RayShapeSW(); @@ -176,22 +172,22 @@ class SphereShapeSW : public ShapeSW { real_t radius; void _setup(real_t p_radius); -public: +public: real_t get_radius() const; - virtual real_t get_area() const { return 4.0/3.0 * Math_PI * radius * radius * radius; } + virtual real_t get_area() const { return 4.0 / 3.0 * Math_PI * radius * radius * radius; } virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_SPHERE; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; SphereShapeSW(); @@ -200,22 +196,22 @@ public: class BoxShapeSW : public ShapeSW { Vector3 half_extents; - void _setup(const Vector3& p_half_extents); -public: + void _setup(const Vector3 &p_half_extents); +public: _FORCE_INLINE_ Vector3 get_half_extents() const { return half_extents; } - virtual real_t get_area() const { return 8 * half_extents.x * half_extents.y * half_extents.z; } + virtual real_t get_area() const { return 8 * half_extents.x * half_extents.y * half_extents.z; } virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_BOX; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; BoxShapeSW(); @@ -226,25 +222,24 @@ class CapsuleShapeSW : public ShapeSW { real_t height; real_t radius; + void _setup(real_t p_height, real_t p_radius); - void _setup(real_t p_height,real_t p_radius); public: - _FORCE_INLINE_ real_t get_height() const { return height; } _FORCE_INLINE_ real_t get_radius() const { return radius; } - virtual real_t get_area() { return 4.0/3.0 * Math_PI * radius * radius * radius + height * Math_PI * radius * radius; } + virtual real_t get_area() { return 4.0 / 3.0 * Math_PI * radius * radius * radius + height * Math_PI * radius * radius; } virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CAPSULE; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; CapsuleShapeSW(); @@ -254,28 +249,26 @@ struct ConvexPolygonShapeSW : public ShapeSW { Geometry::MeshData mesh; - void _setup(const Vector<Vector3>& p_vertices); -public: + void _setup(const Vector<Vector3> &p_vertices); - const Geometry::MeshData& get_mesh() const { return mesh; } +public: + const Geometry::MeshData &get_mesh() const { return mesh; } virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONVEX_POLYGON; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; ConvexPolygonShapeSW(); - }; - struct _VolumeSW_BVH; struct FaceShapeSW; @@ -326,39 +319,35 @@ struct ConcavePolygonShapeSW : public ConcaveShapeSW { Vector3 normal; real_t min_d; int collisions; - }; - void _cull_segment(int p_idx,_SegmentCullParams *p_params) const; - void _cull(int p_idx,_CullParams *p_params) const; - - void _fill_bvh(_VolumeSW_BVH* p_bvh_tree,BVH* p_bvh_array,int& p_idx); + void _cull_segment(int p_idx, _SegmentCullParams *p_params) const; + void _cull(int p_idx, _CullParams *p_params) const; + void _fill_bvh(_VolumeSW_BVH *p_bvh_tree, BVH *p_bvh_array, int &p_idx); void _setup(PoolVector<Vector3> p_faces); -public: +public: PoolVector<Vector3> get_faces() const; virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONCAVE_POLYGON; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; - virtual void cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const; + virtual void cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; ConcavePolygonShapeSW(); - }; - struct HeightMapShapeSW : public ConcaveShapeSW { PoolVector<real_t> heights; @@ -369,9 +358,9 @@ struct HeightMapShapeSW : public ConcaveShapeSW { //void _cull_segment(int p_idx,_SegmentCullParams *p_params) const; //void _cull(int p_idx,_CullParams *p_params) const; - void _setup(PoolVector<real_t> p_heights,int p_width,int p_depth,real_t p_cell_size); -public: + void _setup(PoolVector<real_t> p_heights, int p_width, int p_depth, real_t p_cell_size); +public: PoolVector<real_t> get_heights() const; int get_width() const; int get_depth() const; @@ -379,19 +368,18 @@ public: virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_HEIGHTMAP; } - virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - virtual Vector3 get_support(const Vector3& p_normal) const; - virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + virtual Vector3 get_support(const Vector3 &p_normal) const; + virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; - virtual void cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const; + virtual void cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const; virtual Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; HeightMapShapeSW(); - }; //used internally @@ -402,22 +390,21 @@ struct FaceShapeSW : public ShapeSW { virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONCAVE_POLYGON; } - const Vector3& get_vertex(int p_idx) const { return vertex[p_idx]; } + const Vector3 &get_vertex(int p_idx) const { return vertex[p_idx]; } - void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const; - Vector3 get_support(const Vector3& p_normal) const; - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const; - bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const; + void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; + Vector3 get_support(const Vector3 &p_normal) const; + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const; + bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const; Vector3 get_moment_of_inertia(real_t p_mass) const; - virtual void set_data(const Variant& p_data) {} + virtual void set_data(const Variant &p_data) {} virtual Variant get_data() const { return Variant(); } FaceShapeSW(); }; - struct MotionShapeSW : public ShapeSW { ShapeSW *shape; @@ -425,56 +412,48 @@ struct MotionShapeSW : public ShapeSW { virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONVEX_POLYGON; } - - void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const { + void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const { Vector3 cast = p_transform.basis.xform(motion); - real_t mina,maxa; - real_t minb,maxb; + real_t mina, maxa; + real_t minb, maxb; Transform ofsb = p_transform; - ofsb.origin+=cast; - shape->project_range(p_normal,p_transform,mina,maxa); - shape->project_range(p_normal,ofsb,minb,maxb); - r_min=MIN(mina,minb); - r_max=MAX(maxa,maxb); + ofsb.origin += cast; + shape->project_range(p_normal, p_transform, mina, maxa); + shape->project_range(p_normal, ofsb, minb, maxb); + r_min = MIN(mina, minb); + r_max = MAX(maxa, maxb); } - Vector3 get_support(const Vector3& p_normal) const { + Vector3 get_support(const Vector3 &p_normal) const { Vector3 support = shape->get_support(p_normal); - if (p_normal.dot(motion)>0) { - support+=motion; + if (p_normal.dot(motion) > 0) { + support += motion; } return support; } - virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { r_amount=0; } - bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { return false; } + virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { r_amount = 0; } + bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { return false; } Vector3 get_moment_of_inertia(real_t p_mass) const { return Vector3(); } - virtual void set_data(const Variant& p_data) {} + virtual void set_data(const Variant &p_data) {} virtual Variant get_data() const { return Variant(); } - MotionShapeSW() { configure(Rect3()); } + MotionShapeSW() { configure(Rect3()); } }; - - - struct _ShapeTestConvexBSPSW { const BSP_Tree *bsp; const ShapeSW *shape; Transform transform; - _FORCE_INLINE_ void project_range(const Vector3& p_normal, real_t& r_min, real_t& r_max) const { + _FORCE_INLINE_ void project_range(const Vector3 &p_normal, real_t &r_min, real_t &r_max) const { - shape->project_range(p_normal,transform,r_min,r_max); + shape->project_range(p_normal, transform, r_min, r_max); } - }; - - - #endif // SHAPESW_H diff --git a/servers/physics/space_sw.cpp b/servers/physics/space_sw.cpp index 0bc11041de..603c6fa3c4 100644 --- a/servers/physics/space_sw.cpp +++ b/servers/physics/space_sw.cpp @@ -26,66 +26,58 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "global_config.h" #include "space_sw.h" #include "collision_solver_sw.h" +#include "global_config.h" #include "physics_server_sw.h" - _FORCE_INLINE_ static bool _match_object_type_query(CollisionObjectSW *p_object, uint32_t p_layer_mask, uint32_t p_type_mask) { - if (p_object->get_type()==CollisionObjectSW::TYPE_AREA) - return p_type_mask&PhysicsDirectSpaceState::TYPE_MASK_AREA; + if (p_object->get_type() == CollisionObjectSW::TYPE_AREA) + return p_type_mask & PhysicsDirectSpaceState::TYPE_MASK_AREA; - if ((p_object->get_layer_mask()&p_layer_mask)==0) + if ((p_object->get_layer_mask() & p_layer_mask) == 0) return false; - BodySW *body = static_cast<BodySW*>(p_object); - - return (1<<body->get_mode())&p_type_mask; + BodySW *body = static_cast<BodySW *>(p_object); + return (1 << body->get_mode()) & p_type_mask; } +bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_ray) { -bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3& p_from, const Vector3& p_to, RayResult &r_result, const Set<RID>& p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_ray) { - + ERR_FAIL_COND_V(space->locked, false); - ERR_FAIL_COND_V(space->locked,false); - - Vector3 begin,end; + Vector3 begin, end; Vector3 normal; - begin=p_from; - end=p_to; - normal=(end-begin).normalized(); - - - int amount = space->broadphase->cull_segment(begin,end,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + begin = p_from; + end = p_to; + normal = (end - begin).normalized(); + int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); //todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision - bool collided=false; - Vector3 res_point,res_normal; + bool collided = false; + Vector3 res_point, res_normal; int res_shape; const CollisionObjectSW *res_obj; - real_t min_d=1e10; - - + real_t min_d = 1e10; - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - if (p_pick_ray && !(static_cast<CollisionObjectSW*>(space->intersection_query_results[i])->is_ray_pickable())) + if (p_pick_ray && !(static_cast<CollisionObjectSW *>(space->intersection_query_results[i])->is_ray_pickable())) continue; - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; - const CollisionObjectSW *col_obj=space->intersection_query_results[i]; + const CollisionObjectSW *col_obj = space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; Transform inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform(); Vector3 local_from = inv_xform.xform(begin); @@ -93,293 +85,268 @@ bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3& p_from, const Vecto const ShapeSW *shape = col_obj->get_shape(shape_idx); - Vector3 shape_point,shape_normal; - - - if (shape->intersect_segment(local_from,local_to,shape_point,shape_normal)) { - + Vector3 shape_point, shape_normal; + if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) { Transform xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx); - shape_point=xform.xform(shape_point); + shape_point = xform.xform(shape_point); real_t ld = normal.dot(shape_point); + if (ld < min_d) { - if (ld<min_d) { - - min_d=ld; - res_point=shape_point; - res_normal=inv_xform.basis.xform_inv(shape_normal).normalized(); - res_shape=shape_idx; - res_obj=col_obj; - collided=true; + min_d = ld; + res_point = shape_point; + res_normal = inv_xform.basis.xform_inv(shape_normal).normalized(); + res_shape = shape_idx; + res_obj = col_obj; + collided = true; } } - } if (!collided) return false; - - r_result.collider_id=res_obj->get_instance_id(); - if (r_result.collider_id!=0) - r_result.collider=ObjectDB::get_instance(r_result.collider_id); + r_result.collider_id = res_obj->get_instance_id(); + if (r_result.collider_id != 0) + r_result.collider = ObjectDB::get_instance(r_result.collider_id); else - r_result.collider=NULL; - r_result.normal=res_normal; - r_result.position=res_point; - r_result.rid=res_obj->get_self(); - r_result.shape=res_shape; + r_result.collider = NULL; + r_result.normal = res_normal; + r_result.position = res_point; + r_result.rid = res_obj->get_self(); + r_result.shape = res_shape; return true; - } +int PhysicsDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { -int PhysicsDirectSpaceStateSW::intersect_shape(const RID& p_shape, const Transform& p_xform,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - - if (p_result_max<=0) + if (p_result_max <= 0) return 0; - ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); + ERR_FAIL_COND_V(!shape, 0); Rect3 aabb = p_xform.xform(shape->get_aabb()); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); - int cc=0; + int cc = 0; //Transform ai = p_xform.affine_inverse(); - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - if (cc>=p_result_max) + if (cc >= p_result_max) break; - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; //area cant be picked by ray (default) - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; + const CollisionObjectSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - const CollisionObjectSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; - - if (!CollisionSolverSW::solve_static(shape,p_xform,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL,NULL,NULL,p_margin,0)) + if (!CollisionSolverSW::solve_static(shape, p_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL, NULL, NULL, p_margin, 0)) continue; if (r_results) { - r_results[cc].collider_id=col_obj->get_instance_id(); - if (r_results[cc].collider_id!=0) - r_results[cc].collider=ObjectDB::get_instance(r_results[cc].collider_id); + r_results[cc].collider_id = col_obj->get_instance_id(); + if (r_results[cc].collider_id != 0) + r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id); else - r_results[cc].collider=NULL; - r_results[cc].rid=col_obj->get_self(); - r_results[cc].shape=shape_idx; + r_results[cc].collider = NULL; + r_results[cc].rid = col_obj->get_self(); + r_results[cc].shape = shape_idx; } cc++; - } return cc; - } +bool PhysicsDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, ShapeRestInfo *r_info) { -bool PhysicsDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask,ShapeRestInfo *r_info) { - - - - ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,false); + ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); + ERR_FAIL_COND_V(!shape, false); Rect3 aabb = p_xform.xform(shape->get_aabb()); - aabb=aabb.merge(Rect3(aabb.pos+p_motion,aabb.size)); //motion - aabb=aabb.grow(p_margin); + aabb = aabb.merge(Rect3(aabb.pos + p_motion, aabb.size)); //motion + aabb = aabb.grow(p_margin); /* if (p_motion!=Vector3()) print_line(p_motion); */ - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); - real_t best_safe=1; - real_t best_unsafe=1; + real_t best_safe = 1; + real_t best_unsafe = 1; Transform xform_inv = p_xform.affine_inverse(); MotionShapeSW mshape; - mshape.shape=shape; - mshape.motion=xform_inv.basis.xform(p_motion); + mshape.shape = shape; + mshape.motion = xform_inv.basis.xform(p_motion); - bool best_first=true; + bool best_first = true; - Vector3 closest_A,closest_B; + Vector3 closest_A, closest_B; - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; //ignore excluded + const CollisionObjectSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - const CollisionObjectSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; - - Vector3 point_A,point_B; - Vector3 sep_axis=p_motion.normalized(); + Vector3 point_A, point_B; + Vector3 sep_axis = p_motion.normalized(); Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx); //test initial overlap, does it collide if going all the way? - if (CollisionSolverSW::solve_distance(&mshape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,point_A,point_B,aabb,&sep_axis)) { + if (CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) { //print_line("failed motion cast (no collision)"); continue; } - - //test initial overlap +//test initial overlap #if 0 if (CollisionSolverSW::solve_static(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,NULL,NULL,&sep_axis)) { print_line("failed initial cast (collision at begining)"); return false; } #else - sep_axis=p_motion.normalized(); + sep_axis = p_motion.normalized(); - if (!CollisionSolverSW::solve_distance(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,point_A,point_B,aabb,&sep_axis)) { + if (!CollisionSolverSW::solve_distance(shape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) { //print_line("failed motion cast (no collision)"); return false; } #endif - //just do kinematic solving - real_t low=0; - real_t hi=1; - Vector3 mnormal=p_motion.normalized(); + real_t low = 0; + real_t hi = 1; + Vector3 mnormal = p_motion.normalized(); - for(int i=0;i<8;i++) { //steps should be customizable.. + for (int i = 0; i < 8; i++) { //steps should be customizable.. - real_t ofs = (low+hi)*0.5; + real_t ofs = (low + hi) * 0.5; - Vector3 sep=mnormal; //important optimization for this to work fast enough + Vector3 sep = mnormal; //important optimization for this to work fast enough - mshape.motion=xform_inv.basis.xform(p_motion*ofs); + mshape.motion = xform_inv.basis.xform(p_motion * ofs); - Vector3 lA,lB; + Vector3 lA, lB; - bool collided = !CollisionSolverSW::solve_distance(&mshape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,lA,lB,aabb,&sep); + bool collided = !CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, aabb, &sep); if (collided) { //print_line(itos(i)+": "+rtos(ofs)); - hi=ofs; + hi = ofs; } else { - point_A=lA; - point_B=lB; - low=ofs; + point_A = lA; + point_B = lB; + low = ofs; } } - if (low<best_safe) { - best_first=true; //force reset - best_safe=low; - best_unsafe=hi; + if (low < best_safe) { + best_first = true; //force reset + best_safe = low; + best_unsafe = hi; } - if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low<=best_safe))) { - closest_A=point_A; - closest_B=point_B; - r_info->collider_id=col_obj->get_instance_id(); - r_info->rid=col_obj->get_self(); - r_info->shape=shape_idx; - r_info->point=closest_B; - r_info->normal=(closest_A-closest_B).normalized(); - best_first=false; - if (col_obj->get_type()==CollisionObjectSW::TYPE_BODY) { - const BodySW *body=static_cast<const BodySW*>(col_obj); - r_info->linear_velocity= body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B); + if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low <= best_safe))) { + closest_A = point_A; + closest_B = point_B; + r_info->collider_id = col_obj->get_instance_id(); + r_info->rid = col_obj->get_self(); + r_info->shape = shape_idx; + r_info->point = closest_B; + r_info->normal = (closest_A - closest_B).normalized(); + best_first = false; + if (col_obj->get_type() == CollisionObjectSW::TYPE_BODY) { + const BodySW *body = static_cast<const BodySW *>(col_obj); + r_info->linear_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B); } - } - - } - p_closest_safe=best_safe; - p_closest_unsafe=best_unsafe; + p_closest_safe = best_safe; + p_closest_unsafe = best_unsafe; return true; } -bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform& p_shape_xform,real_t p_margin,Vector3 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask){ +bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { - if (p_result_max<=0) + if (p_result_max <= 0) return 0; - ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); + ERR_FAIL_COND_V(!shape, 0); Rect3 aabb = p_shape_xform.xform(shape->get_aabb()); - aabb=aabb.grow(p_margin); + aabb = aabb.grow(p_margin); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); - bool collided=false; - r_result_count=0; + bool collided = false; + r_result_count = 0; PhysicsServerSW::CollCbkData cbk; - cbk.max=p_result_max; - cbk.amount=0; - cbk.ptr=r_results; - CollisionSolverSW::CallbackResult cbkres=NULL; - - PhysicsServerSW::CollCbkData *cbkptr=NULL; - if (p_result_max>0) { - cbkptr=&cbk; - cbkres=PhysicsServerSW::_shape_col_cbk; + cbk.max = p_result_max; + cbk.amount = 0; + cbk.ptr = r_results; + CollisionSolverSW::CallbackResult cbkres = NULL; + + PhysicsServerSW::CollCbkData *cbkptr = NULL; + if (p_result_max > 0) { + cbkptr = &cbk; + cbkres = PhysicsServerSW::_shape_col_cbk; } + for (int i = 0; i < amount; i++) { - for(int i=0;i<amount;i++) { - - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - const CollisionObjectSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; + const CollisionObjectSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - if (p_exclude.has( col_obj->get_self() )) { + if (p_exclude.has(col_obj->get_self())) { continue; } //print_line("AGAINST: "+itos(col_obj->get_self().get_id())+":"+itos(shape_idx)); //print_line("THE ABBB: "+(col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).xform(col_obj->get_shape(shape_idx)->get_aabb())); - if (CollisionSolverSW::solve_static(shape,p_shape_xform,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),cbkres,cbkptr,NULL,p_margin)) { - collided=true; + if (CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) { + collided = true; } - } - r_result_count=cbk.amount; + r_result_count = cbk.amount; return collided; - } - struct _RestCallbackData { const CollisionObjectSW *object; @@ -391,173 +358,147 @@ struct _RestCallbackData { real_t best_len; }; -static void _rest_cbk_result(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata) { - +static void _rest_cbk_result(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) { - _RestCallbackData *rd=(_RestCallbackData*)p_userdata; + _RestCallbackData *rd = (_RestCallbackData *)p_userdata; Vector3 contact_rel = p_point_B - p_point_A; real_t len = contact_rel.length(); if (len <= rd->best_len) return; - rd->best_len=len; - rd->best_contact=p_point_B; - rd->best_normal=contact_rel/len; - rd->best_object=rd->object; - rd->best_shape=rd->shape; - + rd->best_len = len; + rd->best_contact = p_point_B; + rd->best_normal = contact_rel / len; + rd->best_object = rd->object; + rd->best_shape = rd->shape; } -bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform& p_shape_xform,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - +bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { - ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape); + ERR_FAIL_COND_V(!shape, 0); Rect3 aabb = p_shape_xform.xform(shape->get_aabb()); - aabb=aabb.grow(p_margin); + aabb = aabb.grow(p_margin); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); _RestCallbackData rcd; - rcd.best_len=0; - rcd.best_object=NULL; - rcd.best_shape=0; + rcd.best_len = 0; + rcd.best_object = NULL; + rcd.best_shape = 0; - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - const CollisionObjectSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; + const CollisionObjectSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - if (p_exclude.has( col_obj->get_self() )) + if (p_exclude.has(col_obj->get_self())) continue; - rcd.object=col_obj; - rcd.shape=shape_idx; - bool sc = CollisionSolverSW::solve_static(shape,p_shape_xform,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),_rest_cbk_result,&rcd,NULL,p_margin); + rcd.object = col_obj; + rcd.shape = shape_idx; + bool sc = CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin); if (!sc) continue; - - } - if (rcd.best_len==0) + if (rcd.best_len == 0) return false; - r_info->collider_id=rcd.best_object->get_instance_id(); - r_info->shape=rcd.best_shape; - r_info->normal=rcd.best_normal; - r_info->point=rcd.best_contact; - r_info->rid=rcd.best_object->get_self(); - if (rcd.best_object->get_type()==CollisionObjectSW::TYPE_BODY) { + r_info->collider_id = rcd.best_object->get_instance_id(); + r_info->shape = rcd.best_shape; + r_info->normal = rcd.best_normal; + r_info->point = rcd.best_contact; + r_info->rid = rcd.best_object->get_self(); + if (rcd.best_object->get_type() == CollisionObjectSW::TYPE_BODY) { - const BodySW *body = static_cast<const BodySW*>(rcd.best_object); + const BodySW *body = static_cast<const BodySW *>(rcd.best_object); r_info->linear_velocity = body->get_linear_velocity() + - (body->get_angular_velocity()).cross(body->get_transform().origin-rcd.best_contact);// * mPos); - + (body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos); } else { - r_info->linear_velocity=Vector3(); + r_info->linear_velocity = Vector3(); } return true; } - PhysicsDirectSpaceStateSW::PhysicsDirectSpaceStateSW() { - - space=NULL; + space = NULL; } - //////////////////////////////////////////////////////////////////////////////////////////////////////////// +void *SpaceSW::_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self) { + CollisionObjectSW::Type type_A = A->get_type(); + CollisionObjectSW::Type type_B = B->get_type(); + if (type_A > type_B) { - - - - - - - -void* SpaceSW::_broadphase_pair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_self) { - - CollisionObjectSW::Type type_A=A->get_type(); - CollisionObjectSW::Type type_B=B->get_type(); - if (type_A>type_B) { - - SWAP(A,B); - SWAP(p_subindex_A,p_subindex_B); - SWAP(type_A,type_B); + SWAP(A, B); + SWAP(p_subindex_A, p_subindex_B); + SWAP(type_A, type_B); } - SpaceSW *self = (SpaceSW*)p_self; + SpaceSW *self = (SpaceSW *)p_self; self->collision_pairs++; - if (type_A==CollisionObjectSW::TYPE_AREA) { + if (type_A == CollisionObjectSW::TYPE_AREA) { - AreaSW *area=static_cast<AreaSW*>(A); - if (type_B==CollisionObjectSW::TYPE_AREA) { + AreaSW *area = static_cast<AreaSW *>(A); + if (type_B == CollisionObjectSW::TYPE_AREA) { - AreaSW *area_b=static_cast<AreaSW*>(B); - Area2PairSW *area2_pair = memnew(Area2PairSW(area_b,p_subindex_B,area,p_subindex_A) ); + AreaSW *area_b = static_cast<AreaSW *>(B); + Area2PairSW *area2_pair = memnew(Area2PairSW(area_b, p_subindex_B, area, p_subindex_A)); return area2_pair; } else { - BodySW *body=static_cast<BodySW*>(B); - AreaPairSW *area_pair = memnew(AreaPairSW(body,p_subindex_B,area,p_subindex_A) ); + BodySW *body = static_cast<BodySW *>(B); + AreaPairSW *area_pair = memnew(AreaPairSW(body, p_subindex_B, area, p_subindex_A)); return area_pair; } } else { - - BodyPairSW *b = memnew( BodyPairSW((BodySW*)A,p_subindex_A,(BodySW*)B,p_subindex_B) ); + BodyPairSW *b = memnew(BodyPairSW((BodySW *)A, p_subindex_A, (BodySW *)B, p_subindex_B)); return b; - } return NULL; } -void SpaceSW::_broadphase_unpair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_data,void *p_self) { - +void SpaceSW::_broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self) { - - SpaceSW *self = (SpaceSW*)p_self; + SpaceSW *self = (SpaceSW *)p_self; self->collision_pairs--; - ConstraintSW *c = (ConstraintSW*)p_data; + ConstraintSW *c = (ConstraintSW *)p_data; memdelete(c); } - -const SelfList<BodySW>::List& SpaceSW::get_active_body_list() const { +const SelfList<BodySW>::List &SpaceSW::get_active_body_list() const { return active_list; } -void SpaceSW::body_add_to_active_list(SelfList<BodySW>* p_body) { +void SpaceSW::body_add_to_active_list(SelfList<BodySW> *p_body) { active_list.add(p_body); } -void SpaceSW::body_remove_from_active_list(SelfList<BodySW>* p_body) { +void SpaceSW::body_remove_from_active_list(SelfList<BodySW> *p_body) { active_list.remove(p_body); - } -void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW>* p_body) { - +void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW> *p_body) { inertia_update_list.add(p_body); } -void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW>* p_body) { +void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW> *p_body) { inertia_update_list.remove(p_body); } @@ -569,112 +510,103 @@ BroadPhaseSW *SpaceSW::get_broadphase() { void SpaceSW::add_object(CollisionObjectSW *p_object) { - ERR_FAIL_COND( objects.has(p_object) ); + ERR_FAIL_COND(objects.has(p_object)); objects.insert(p_object); } void SpaceSW::remove_object(CollisionObjectSW *p_object) { - ERR_FAIL_COND( !objects.has(p_object) ); + ERR_FAIL_COND(!objects.has(p_object)); objects.erase(p_object); } -const Set<CollisionObjectSW*> &SpaceSW::get_objects() const { +const Set<CollisionObjectSW *> &SpaceSW::get_objects() const { return objects; } -void SpaceSW::body_add_to_state_query_list(SelfList<BodySW>* p_body) { +void SpaceSW::body_add_to_state_query_list(SelfList<BodySW> *p_body) { state_query_list.add(p_body); } -void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW>* p_body) { +void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW> *p_body) { state_query_list.remove(p_body); } -void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW>* p_area) { +void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW> *p_area) { monitor_query_list.add(p_area); } -void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW>* p_area) { +void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area) { monitor_query_list.remove(p_area); } -void SpaceSW::area_add_to_moved_list(SelfList<AreaSW>* p_area) { +void SpaceSW::area_add_to_moved_list(SelfList<AreaSW> *p_area) { area_moved_list.add(p_area); } -void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW>* p_area) { +void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW> *p_area) { area_moved_list.remove(p_area); } -const SelfList<AreaSW>::List& SpaceSW::get_moved_area_list() const { +const SelfList<AreaSW>::List &SpaceSW::get_moved_area_list() const { return area_moved_list; } - - - void SpaceSW::call_queries() { - while(state_query_list.first()) { + while (state_query_list.first()) { - BodySW * b = state_query_list.first()->self(); + BodySW *b = state_query_list.first()->self(); b->call_queries(); state_query_list.remove(state_query_list.first()); } - while(monitor_query_list.first()) { + while (monitor_query_list.first()) { - AreaSW * a = monitor_query_list.first()->self(); + AreaSW *a = monitor_query_list.first()->self(); a->call_queries(); monitor_query_list.remove(monitor_query_list.first()); } - } void SpaceSW::setup() { - contact_debug_count=0; - while(inertia_update_list.first()) { + contact_debug_count = 0; + while (inertia_update_list.first()) { inertia_update_list.first()->self()->update_inertias(); inertia_update_list.remove(inertia_update_list.first()); } - - } void SpaceSW::update() { - broadphase->update(); - } - void SpaceSW::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) { - switch(p_param) { + switch (p_param) { - case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius=p_value; break; - case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation=p_value; break; - case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration=p_value; break; - case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_threshold=p_value; break; - case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_threshold=p_value; break; - case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep=p_value; break; - case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio=p_value; break; - case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias=p_value; break; + case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break; + case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break; + case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break; + case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_threshold = p_value; break; + case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_threshold = p_value; break; + case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break; + case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio = p_value; break; + case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break; } } real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const { - switch(p_param) { + switch (p_param) { case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius; case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation; @@ -690,12 +622,12 @@ real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const { void SpaceSW::lock() { - locked=true; + locked = true; } void SpaceSW::unlock() { - locked=false; + locked = false; } bool SpaceSW::is_locked() const { @@ -710,41 +642,36 @@ PhysicsDirectSpaceStateSW *SpaceSW::get_direct_state() { SpaceSW::SpaceSW() { - collision_pairs=0; - active_objects=0; - island_count=0; - contact_debug_count=0; + collision_pairs = 0; + active_objects = 0; + island_count = 0; + contact_debug_count = 0; - locked=false; - contact_recycle_radius=0.01; - contact_max_separation=0.05; - contact_max_allowed_penetration= 0.01; + locked = false; + contact_recycle_radius = 0.01; + contact_max_separation = 0.05; + contact_max_allowed_penetration = 0.01; constraint_bias = 0.01; - body_linear_velocity_sleep_threshold=GLOBAL_DEF("physics/3d/sleep_threshold_linear",0.1); - body_angular_velocity_sleep_threshold=GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI) ); - body_time_to_sleep=GLOBAL_DEF("physics/3d/time_before_sleep",0.5); - body_angular_velocity_damp_ratio=10; - + body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_linear", 0.1); + body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI)); + body_time_to_sleep = GLOBAL_DEF("physics/3d/time_before_sleep", 0.5); + body_angular_velocity_damp_ratio = 10; broadphase = BroadPhaseSW::create_func(); - broadphase->set_pair_callback(_broadphase_pair,this); - broadphase->set_unpair_callback(_broadphase_unpair,this); - area=NULL; + broadphase->set_pair_callback(_broadphase_pair, this); + broadphase->set_unpair_callback(_broadphase_unpair, this); + area = NULL; - direct_access = memnew( PhysicsDirectSpaceStateSW ); - direct_access->space=this; - - for(int i=0;i<ELAPSED_TIME_MAX;i++) - elapsed_time[i]=0; + direct_access = memnew(PhysicsDirectSpaceStateSW); + direct_access->space = this; + for (int i = 0; i < ELAPSED_TIME_MAX; i++) + elapsed_time[i] = 0; } SpaceSW::~SpaceSW() { memdelete(broadphase); - memdelete( direct_access ); + memdelete(direct_access); } - - - diff --git a/servers/physics/space_sw.h b/servers/physics/space_sw.h index 208831914f..06538265bb 100644 --- a/servers/physics/space_sw.h +++ b/servers/physics/space_sw.h @@ -29,39 +29,35 @@ #ifndef SPACE_SW_H #define SPACE_SW_H -#include "typedefs.h" -#include "hash_map.h" -#include "body_sw.h" +#include "area_pair_sw.h" #include "area_sw.h" #include "body_pair_sw.h" -#include "area_pair_sw.h" +#include "body_sw.h" #include "broad_phase_sw.h" #include "collision_object_sw.h" #include "global_config.h" - +#include "hash_map.h" +#include "typedefs.h" class PhysicsDirectSpaceStateSW : public PhysicsDirectSpaceState { - GDCLASS( PhysicsDirectSpaceStateSW, PhysicsDirectSpaceState ); -public: + GDCLASS(PhysicsDirectSpaceStateSW, PhysicsDirectSpaceState); +public: SpaceSW *space; - virtual bool intersect_ray(const Vector3& p_from, const Vector3& p_to,RayResult &r_result,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,bool p_pick_ray=false); - virtual int intersect_shape(const RID& p_shape, const Transform& p_xform,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - virtual bool cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,ShapeRestInfo *r_info=NULL); - virtual bool collide_shape(RID p_shape, const Transform& p_shape_xform,real_t p_margin,Vector3 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - virtual bool rest_info(RID p_shape, const Transform& p_shape_xform,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); + virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_ray = false); + virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, ShapeRestInfo *r_info = NULL); + virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); PhysicsDirectSpaceStateSW(); }; - - class SpaceSW : public RID_Data { public: - enum ElapsedTime { ELAPSED_TIME_INTEGRATE_FORCES, ELAPSED_TIME_GENERATE_ISLANDS, @@ -71,8 +67,8 @@ public: ELAPSED_TIME_MAX }; -private: +private: uint64_t elapsed_time[ELAPSED_TIME_MAX]; PhysicsDirectSpaceStateSW *direct_access; @@ -85,10 +81,10 @@ private: SelfList<AreaSW>::List monitor_query_list; SelfList<AreaSW>::List area_moved_list; - static void* _broadphase_pair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_self); - static void _broadphase_unpair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_data,void *p_self); + static void *_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self); + static void _broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self); - Set<CollisionObjectSW*> objects; + Set<CollisionObjectSW *> objects; AreaSW *area; @@ -99,7 +95,7 @@ private: enum { - INTERSECTION_QUERY_MAX=2048 + INTERSECTION_QUERY_MAX = 2048 }; CollisionObjectSW *intersection_query_results[INTERSECTION_QUERY_MAX]; @@ -121,36 +117,35 @@ private: Vector<Vector3> contact_debug; int contact_debug_count; -friend class PhysicsDirectSpaceStateSW; + friend class PhysicsDirectSpaceStateSW; public: - - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } _FORCE_INLINE_ RID get_self() const { return self; } - void set_default_area(AreaSW *p_area) { area=p_area; } + void set_default_area(AreaSW *p_area) { area = p_area; } AreaSW *get_default_area() const { return area; } - const SelfList<BodySW>::List& get_active_body_list() const; - void body_add_to_active_list(SelfList<BodySW>* p_body); - void body_remove_from_active_list(SelfList<BodySW>* p_body); - void body_add_to_inertia_update_list(SelfList<BodySW>* p_body); - void body_remove_from_inertia_update_list(SelfList<BodySW>* p_body); + const SelfList<BodySW>::List &get_active_body_list() const; + void body_add_to_active_list(SelfList<BodySW> *p_body); + void body_remove_from_active_list(SelfList<BodySW> *p_body); + void body_add_to_inertia_update_list(SelfList<BodySW> *p_body); + void body_remove_from_inertia_update_list(SelfList<BodySW> *p_body); - void body_add_to_state_query_list(SelfList<BodySW>* p_body); - void body_remove_from_state_query_list(SelfList<BodySW>* p_body); + void body_add_to_state_query_list(SelfList<BodySW> *p_body); + void body_remove_from_state_query_list(SelfList<BodySW> *p_body); - void area_add_to_monitor_query_list(SelfList<AreaSW>* p_area); - void area_remove_from_monitor_query_list(SelfList<AreaSW>* p_area); - void area_add_to_moved_list(SelfList<AreaSW>* p_area); - void area_remove_from_moved_list(SelfList<AreaSW>* p_area); - const SelfList<AreaSW>::List& get_moved_area_list() const; + void area_add_to_monitor_query_list(SelfList<AreaSW> *p_area); + void area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area); + void area_add_to_moved_list(SelfList<AreaSW> *p_area); + void area_remove_from_moved_list(SelfList<AreaSW> *p_area); + const SelfList<AreaSW>::List &get_moved_area_list() const; BroadPhaseSW *get_broadphase(); void add_object(CollisionObjectSW *p_object); void remove_object(CollisionObjectSW *p_object); - const Set<CollisionObjectSW*> &get_objects() const; + const Set<CollisionObjectSW *> &get_objects() const; _FORCE_INLINE_ real_t get_contact_recycle_radius() const { return contact_recycle_radius; } _FORCE_INLINE_ real_t get_contact_max_separation() const { return contact_max_separation; } @@ -161,12 +156,10 @@ public: _FORCE_INLINE_ real_t get_body_time_to_sleep() const { return body_time_to_sleep; } _FORCE_INLINE_ real_t get_body_angular_velocity_damp_ratio() const { return body_angular_velocity_damp_ratio; } - void update(); void setup(); void call_queries(); - bool is_locked() const; void lock(); void unlock(); @@ -174,10 +167,10 @@ public: void set_param(PhysicsServer::SpaceParameter p_param, real_t p_value); real_t get_param(PhysicsServer::SpaceParameter p_param) const; - void set_island_count(int p_island_count) { island_count=p_island_count; } + void set_island_count(int p_island_count) { island_count = p_island_count; } int get_island_count() const { return island_count; } - void set_active_objects(int p_active_objects) { active_objects=p_active_objects; } + void set_active_objects(int p_active_objects) { active_objects = p_active_objects; } int get_active_objects() const { return active_objects; } int get_collision_pairs() const { return collision_pairs; } @@ -186,19 +179,20 @@ public: void set_debug_contacts(int p_amount) { contact_debug.resize(p_amount); } _FORCE_INLINE_ bool is_debugging_contacts() const { return !contact_debug.empty(); } - _FORCE_INLINE_ void add_debug_contact(const Vector3& p_contact) { if (contact_debug_count<contact_debug.size()) contact_debug[contact_debug_count++]=p_contact; } + _FORCE_INLINE_ void add_debug_contact(const Vector3 &p_contact) { + if (contact_debug_count < contact_debug.size()) contact_debug[contact_debug_count++] = p_contact; + } _FORCE_INLINE_ Vector<Vector3> get_debug_contacts() { return contact_debug; } _FORCE_INLINE_ int get_debug_contact_count() { return contact_debug_count; } - void set_static_global_body(RID p_body) { static_global_body=p_body; } + void set_static_global_body(RID p_body) { static_global_body = p_body; } RID get_static_global_body() { return static_global_body; } - void set_elapsed_time(ElapsedTime p_time,uint64_t p_msec) { elapsed_time[p_time]=p_msec; } + void set_elapsed_time(ElapsedTime p_time, uint64_t p_msec) { elapsed_time[p_time] = p_msec; } uint64_t get_elapsed_time(ElapsedTime p_time) const { return elapsed_time[p_time]; } SpaceSW(); ~SpaceSW(); }; - #endif // SPACE__SW_H diff --git a/servers/physics/step_sw.cpp b/servers/physics/step_sw.cpp index 0bd5a874ea..c7b1be7a9b 100644 --- a/servers/physics/step_sw.cpp +++ b/servers/physics/step_sw.cpp @@ -31,279 +31,268 @@ #include "os/os.h" -void StepSW::_populate_island(BodySW* p_body,BodySW** p_island,ConstraintSW **p_constraint_island) { +void StepSW::_populate_island(BodySW *p_body, BodySW **p_island, ConstraintSW **p_constraint_island) { p_body->set_island_step(_step); p_body->set_island_next(*p_island); - *p_island=p_body; + *p_island = p_body; - for(Map<ConstraintSW*,int>::Element *E=p_body->get_constraint_map().front();E;E=E->next()) { + for (Map<ConstraintSW *, int>::Element *E = p_body->get_constraint_map().front(); E; E = E->next()) { - ConstraintSW *c=(ConstraintSW*)E->key(); - if (c->get_island_step()==_step) + ConstraintSW *c = (ConstraintSW *)E->key(); + if (c->get_island_step() == _step) continue; //already processed c->set_island_step(_step); c->set_island_next(*p_constraint_island); - *p_constraint_island=c; + *p_constraint_island = c; - - for(int i=0;i<c->get_body_count();i++) { - if (i==E->get()) + for (int i = 0; i < c->get_body_count(); i++) { + if (i == E->get()) continue; BodySW *b = c->get_body_ptr()[i]; - if (b->get_island_step()==_step || b->get_mode()==PhysicsServer::BODY_MODE_STATIC || b->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC) + if (b->get_island_step() == _step || b->get_mode() == PhysicsServer::BODY_MODE_STATIC || b->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC) continue; //no go - _populate_island(c->get_body_ptr()[i],p_island,p_constraint_island); + _populate_island(c->get_body_ptr()[i], p_island, p_constraint_island); } } } -void StepSW::_setup_island(ConstraintSW *p_island,real_t p_delta) { +void StepSW::_setup_island(ConstraintSW *p_island, real_t p_delta) { - ConstraintSW *ci=p_island; - while(ci) { + ConstraintSW *ci = p_island; + while (ci) { bool process = ci->setup(p_delta); //todo remove from island if process fails - ci=ci->get_island_next(); + ci = ci->get_island_next(); } } -void StepSW::_solve_island(ConstraintSW *p_island,int p_iterations,real_t p_delta){ +void StepSW::_solve_island(ConstraintSW *p_island, int p_iterations, real_t p_delta) { - int at_priority=1; + int at_priority = 1; - while(p_island) { + while (p_island) { - for(int i=0;i<p_iterations;i++) { + for (int i = 0; i < p_iterations; i++) { - ConstraintSW *ci=p_island; - while(ci) { + ConstraintSW *ci = p_island; + while (ci) { ci->solve(p_delta); - ci=ci->get_island_next(); + ci = ci->get_island_next(); } } at_priority++; { - ConstraintSW *ci=p_island; - ConstraintSW *prev=NULL; - while(ci) { - if (ci->get_priority()<at_priority) { + ConstraintSW *ci = p_island; + ConstraintSW *prev = NULL; + while (ci) { + if (ci->get_priority() < at_priority) { if (prev) { prev->set_island_next(ci->get_island_next()); //remove } else { - p_island=ci->get_island_next(); + p_island = ci->get_island_next(); } } else { - prev=ci; + prev = ci; } - ci=ci->get_island_next(); + ci = ci->get_island_next(); } } } - } -void StepSW::_check_suspend(BodySW *p_island,real_t p_delta) { - +void StepSW::_check_suspend(BodySW *p_island, real_t p_delta) { - bool can_sleep=true; + bool can_sleep = true; BodySW *b = p_island; - while(b) { + while (b) { - if (b->get_mode()==PhysicsServer::BODY_MODE_STATIC || b->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC) { - b=b->get_island_next(); + if (b->get_mode() == PhysicsServer::BODY_MODE_STATIC || b->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC) { + b = b->get_island_next(); continue; //ignore for static } if (!b->sleep_test(p_delta)) - can_sleep=false; + can_sleep = false; - b=b->get_island_next(); + b = b->get_island_next(); } //put all to sleep or wake up everyoen b = p_island; - while(b) { + while (b) { - if (b->get_mode()==PhysicsServer::BODY_MODE_STATIC || b->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC) { - b=b->get_island_next(); + if (b->get_mode() == PhysicsServer::BODY_MODE_STATIC || b->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC) { + b = b->get_island_next(); continue; //ignore for static } bool active = b->is_active(); - if (active==can_sleep) + if (active == can_sleep) b->set_active(!can_sleep); - b=b->get_island_next(); + b = b->get_island_next(); } } -void StepSW::step(SpaceSW* p_space,real_t p_delta,int p_iterations) { +void StepSW::step(SpaceSW *p_space, real_t p_delta, int p_iterations) { p_space->lock(); // can't access space during this p_space->setup(); //update inertias, etc - const SelfList<BodySW>::List * body_list = &p_space->get_active_body_list(); + const SelfList<BodySW>::List *body_list = &p_space->get_active_body_list(); /* INTEGRATE FORCES */ uint64_t profile_begtime = OS::get_singleton()->get_ticks_usec(); - uint64_t profile_endtime=0; + uint64_t profile_endtime = 0; - int active_count=0; + int active_count = 0; - const SelfList<BodySW>*b = body_list->first(); - while(b) { + const SelfList<BodySW> *b = body_list->first(); + while (b) { b->self()->integrate_forces(p_delta); - b=b->next(); + b = b->next(); active_count++; } p_space->set_active_objects(active_count); - { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_FORCES,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_FORCES, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* GENERATE CONSTRAINT ISLANDS */ - BodySW *island_list=NULL; - ConstraintSW *constraint_island_list=NULL; + BodySW *island_list = NULL; + ConstraintSW *constraint_island_list = NULL; b = body_list->first(); - int island_count=0; + int island_count = 0; - while(b) { + while (b) { BodySW *body = b->self(); + if (body->get_island_step() != _step) { - if (body->get_island_step()!=_step) { - - BodySW *island=NULL; - ConstraintSW *constraint_island=NULL; - _populate_island(body,&island,&constraint_island); + BodySW *island = NULL; + ConstraintSW *constraint_island = NULL; + _populate_island(body, &island, &constraint_island); island->set_island_list_next(island_list); - island_list=island; + island_list = island; if (constraint_island) { constraint_island->set_island_list_next(constraint_island_list); - constraint_island_list=constraint_island; + constraint_island_list = constraint_island; island_count++; } - } - b=b->next(); + b = b->next(); } p_space->set_island_count(island_count); const SelfList<AreaSW>::List &aml = p_space->get_moved_area_list(); - while(aml.first()) { - for(const Set<ConstraintSW*>::Element *E=aml.first()->self()->get_constraints().front();E;E=E->next()) { + while (aml.first()) { + for (const Set<ConstraintSW *>::Element *E = aml.first()->self()->get_constraints().front(); E; E = E->next()) { - ConstraintSW*c=E->get(); - if (c->get_island_step()==_step) + ConstraintSW *c = E->get(); + if (c->get_island_step() == _step) continue; c->set_island_step(_step); c->set_island_next(NULL); c->set_island_list_next(constraint_island_list); - constraint_island_list=c; + constraint_island_list = c; } - p_space->area_remove_from_moved_list((SelfList<AreaSW>*)aml.first()); //faster to remove here + p_space->area_remove_from_moved_list((SelfList<AreaSW> *)aml.first()); //faster to remove here } { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_GENERATE_ISLANDS,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_GENERATE_ISLANDS, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } - //print_line("island count: "+itos(island_count)+" active count: "+itos(active_count)); /* SETUP CONSTRAINT ISLANDS */ { - ConstraintSW *ci=constraint_island_list; - while(ci) { + ConstraintSW *ci = constraint_island_list; + while (ci) { - _setup_island(ci,p_delta); - ci=ci->get_island_list_next(); + _setup_island(ci, p_delta); + ci = ci->get_island_list_next(); } } { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SETUP_CONSTRAINTS,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SETUP_CONSTRAINTS, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* SOLVE CONSTRAINT ISLANDS */ { - ConstraintSW *ci=constraint_island_list; - while(ci) { + ConstraintSW *ci = constraint_island_list; + while (ci) { //iterating each island separatedly improves cache efficiency - _solve_island(ci,p_iterations,p_delta); - ci=ci->get_island_list_next(); + _solve_island(ci, p_iterations, p_delta); + ci = ci->get_island_list_next(); } } - { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SOLVE_CONSTRAINTS,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SOLVE_CONSTRAINTS, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* INTEGRATE VELOCITIES */ b = body_list->first(); - while(b) { - const SelfList<BodySW>*n=b->next(); + while (b) { + const SelfList<BodySW> *n = b->next(); b->self()->integrate_velocities(p_delta); - b=n; + b = n; } /* SLEEP / WAKE UP ISLANDS */ { - BodySW *bi=island_list; - while(bi) { + BodySW *bi = island_list; + while (bi) { - _check_suspend(bi,p_delta); - bi=bi->get_island_list_next(); + _check_suspend(bi, p_delta); + bi = bi->get_island_list_next(); } } { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_VELOCITIES,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_VELOCITIES, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } p_space->update(); p_space->unlock(); _step++; - - - } StepSW::StepSW() { - _step=1; + _step = 1; } diff --git a/servers/physics/step_sw.h b/servers/physics/step_sw.h index 7048a76937..54f5fe9857 100644 --- a/servers/physics/step_sw.h +++ b/servers/physics/step_sw.h @@ -35,13 +35,13 @@ class StepSW { uint64_t _step; - void _populate_island(BodySW* p_body,BodySW** p_island,ConstraintSW **p_constraint_island); - void _setup_island(ConstraintSW *p_island,real_t p_delta); - void _solve_island(ConstraintSW *p_island,int p_iterations,real_t p_delta); - void _check_suspend(BodySW *p_island,real_t p_delta); -public: + void _populate_island(BodySW *p_body, BodySW **p_island, ConstraintSW **p_constraint_island); + void _setup_island(ConstraintSW *p_island, real_t p_delta); + void _solve_island(ConstraintSW *p_island, int p_iterations, real_t p_delta); + void _check_suspend(BodySW *p_island, real_t p_delta); - void step(SpaceSW* p_space,real_t p_delta,int p_iterations); +public: + void step(SpaceSW *p_space, real_t p_delta, int p_iterations); StepSW(); }; diff --git a/servers/physics_2d/area_2d_sw.cpp b/servers/physics_2d/area_2d_sw.cpp index 2625502717..885ede7cbf 100644 --- a/servers/physics_2d/area_2d_sw.cpp +++ b/servers/physics_2d/area_2d_sw.cpp @@ -27,18 +27,26 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "area_2d_sw.h" -#include "space_2d_sw.h" #include "body_2d_sw.h" +#include "space_2d_sw.h" -Area2DSW::BodyKey::BodyKey(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; } -Area2DSW::BodyKey::BodyKey(Area2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; } +Area2DSW::BodyKey::BodyKey(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { + rid = p_body->get_self(); + instance_id = p_body->get_instance_id(); + body_shape = p_body_shape; + area_shape = p_area_shape; +} +Area2DSW::BodyKey::BodyKey(Area2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { + rid = p_body->get_self(); + instance_id = p_body->get_instance_id(); + body_shape = p_body_shape; + area_shape = p_area_shape; +} void Area2DSW::_shapes_changed() { - - } -void Area2DSW::set_transform(const Transform2D& p_transform) { +void Area2DSW::set_transform(const Transform2D &p_transform) { if (!moved_list.in_list() && get_space()) get_space()->area_add_to_moved_list(&moved_list); @@ -54,7 +62,6 @@ void Area2DSW::set_space(Space2DSW *p_space) { get_space()->area_remove_from_monitor_query_list(&monitor_query_list); if (moved_list.in_list()) get_space()->area_remove_from_moved_list(&moved_list); - } monitored_bodies.clear(); @@ -63,19 +70,17 @@ void Area2DSW::set_space(Space2DSW *p_space) { _set_space(p_space); } +void Area2DSW::set_monitor_callback(ObjectID p_id, const StringName &p_method) { -void Area2DSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) { - - - if (p_id==monitor_callback_id) { - monitor_callback_method=p_method; + if (p_id == monitor_callback_id) { + monitor_callback_method = p_method; return; } _unregister_shapes(); - monitor_callback_id=p_id; - monitor_callback_method=p_method; + monitor_callback_id = p_id; + monitor_callback_method = p_method; monitored_bodies.clear(); monitored_areas.clear(); @@ -84,22 +89,19 @@ void Area2DSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) { if (!moved_list.in_list() && get_space()) get_space()->area_add_to_moved_list(&moved_list); - - } -void Area2DSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_method) { +void Area2DSW::set_area_monitor_callback(ObjectID p_id, const StringName &p_method) { - - if (p_id==area_monitor_callback_id) { - area_monitor_callback_method=p_method; + if (p_id == area_monitor_callback_id) { + area_monitor_callback_method = p_method; return; } _unregister_shapes(); - area_monitor_callback_id=p_id; - area_monitor_callback_method=p_method; + area_monitor_callback_id = p_id; + area_monitor_callback_method = p_method; monitored_bodies.clear(); monitored_areas.clear(); @@ -108,45 +110,39 @@ void Area2DSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_meth if (!moved_list.in_list() && get_space()) get_space()->area_add_to_moved_list(&moved_list); - - } - void Area2DSW::set_space_override_mode(Physics2DServer::AreaSpaceOverrideMode p_mode) { - bool do_override=p_mode!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED; - if (do_override==(space_override_mode!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)) + bool do_override = p_mode != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED; + if (do_override == (space_override_mode != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)) return; _unregister_shapes(); - space_override_mode=p_mode; + space_override_mode = p_mode; _shape_changed(); } -void Area2DSW::set_param(Physics2DServer::AreaParameter p_param, const Variant& p_value) { - - switch(p_param) { - case Physics2DServer::AREA_PARAM_GRAVITY: gravity=p_value; break; - case Physics2DServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector=p_value; break; - case Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point=p_value; break; - case Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale=p_value; break; - case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation=p_value; break; - case Physics2DServer::AREA_PARAM_LINEAR_DAMP: linear_damp=p_value; break; - case Physics2DServer::AREA_PARAM_ANGULAR_DAMP: angular_damp=p_value; break; - case Physics2DServer::AREA_PARAM_PRIORITY: priority=p_value; break; +void Area2DSW::set_param(Physics2DServer::AreaParameter p_param, const Variant &p_value) { + + switch (p_param) { + case Physics2DServer::AREA_PARAM_GRAVITY: gravity = p_value; break; + case Physics2DServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector = p_value; break; + case Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point = p_value; break; + case Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale = p_value; break; + case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation = p_value; break; + case Physics2DServer::AREA_PARAM_LINEAR_DAMP: linear_damp = p_value; break; + case Physics2DServer::AREA_PARAM_ANGULAR_DAMP: angular_damp = p_value; break; + case Physics2DServer::AREA_PARAM_PRIORITY: priority = p_value; break; } - - } Variant Area2DSW::get_param(Physics2DServer::AreaParameter p_param) const { - - switch(p_param) { + switch (p_param) { case Physics2DServer::AREA_PARAM_GRAVITY: return gravity; case Physics2DServer::AREA_PARAM_GRAVITY_VECTOR: return gravity_vector; case Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT: return gravity_is_point; case Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: return gravity_distance_scale; - case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation; + case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation; case Physics2DServer::AREA_PARAM_LINEAR_DAMP: return linear_damp; case Physics2DServer::AREA_PARAM_ANGULAR_DAMP: return angular_damp; case Physics2DServer::AREA_PARAM_PRIORITY: return priority; @@ -155,23 +151,20 @@ Variant Area2DSW::get_param(Physics2DServer::AreaParameter p_param) const { return Variant(); } - void Area2DSW::_queue_monitor_update() { ERR_FAIL_COND(!get_space()); if (!monitor_query_list.in_list()) get_space()->area_add_to_monitor_query_list(&monitor_query_list); - - } void Area2DSW::set_monitorable(bool p_monitorable) { - if (monitorable==p_monitorable) + if (monitorable == p_monitorable) return; - monitorable=p_monitorable; + monitorable = p_monitorable; _set_static(!monitorable); } @@ -181,31 +174,29 @@ void Area2DSW::call_queries() { Variant res[5]; Variant *resptr[5]; - for(int i=0;i<5;i++) - resptr[i]=&res[i]; + for (int i = 0; i < 5; i++) + resptr[i] = &res[i]; Object *obj = ObjectDB::get_instance(monitor_callback_id); if (!obj) { monitored_bodies.clear(); - monitor_callback_id=0; + monitor_callback_id = 0; return; } + for (Map<BodyKey, BodyState>::Element *E = monitored_bodies.front(); E; E = E->next()) { - - for (Map<BodyKey,BodyState>::Element *E=monitored_bodies.front();E;E=E->next()) { - - if (E->get().state==0) + if (E->get().state == 0) continue; //nothing happened - res[0]=E->get().state>0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED; - res[1]=E->key().rid; - res[2]=E->key().instance_id; - res[3]=E->key().body_shape; - res[4]=E->key().area_shape; + res[0] = E->get().state > 0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED; + res[1] = E->key().rid; + res[2] = E->key().instance_id; + res[3] = E->key().body_shape; + res[4] = E->key().area_shape; Variant::CallError ce; - obj->call(monitor_callback_method,(const Variant**)resptr,5,ce); + obj->call(monitor_callback_method, (const Variant **)resptr, 5, ce); } } @@ -213,66 +204,57 @@ void Area2DSW::call_queries() { if (area_monitor_callback_id && !monitored_areas.empty()) { - Variant res[5]; Variant *resptr[5]; - for(int i=0;i<5;i++) - resptr[i]=&res[i]; + for (int i = 0; i < 5; i++) + resptr[i] = &res[i]; Object *obj = ObjectDB::get_instance(area_monitor_callback_id); if (!obj) { monitored_areas.clear(); - area_monitor_callback_id=0; + area_monitor_callback_id = 0; return; } + for (Map<BodyKey, BodyState>::Element *E = monitored_areas.front(); E; E = E->next()) { - - for (Map<BodyKey,BodyState>::Element *E=monitored_areas.front();E;E=E->next()) { - - if (E->get().state==0) + if (E->get().state == 0) continue; //nothing happened - res[0]=E->get().state>0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED; - res[1]=E->key().rid; - res[2]=E->key().instance_id; - res[3]=E->key().body_shape; - res[4]=E->key().area_shape; - + res[0] = E->get().state > 0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED; + res[1] = E->key().rid; + res[2] = E->key().instance_id; + res[3] = E->key().body_shape; + res[4] = E->key().area_shape; Variant::CallError ce; - obj->call(area_monitor_callback_method,(const Variant**)resptr,5,ce); + obj->call(area_monitor_callback_method, (const Variant **)resptr, 5, ce); } } monitored_areas.clear(); //get_space()->area_remove_from_monitor_query_list(&monitor_query_list); - } -Area2DSW::Area2DSW() : CollisionObject2DSW(TYPE_AREA), monitor_query_list(this), moved_list(this) { +Area2DSW::Area2DSW() + : CollisionObject2DSW(TYPE_AREA), monitor_query_list(this), moved_list(this) { _set_static(true); //areas are not active by default - space_override_mode=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED; - gravity=9.80665; - gravity_vector=Vector2(0,-1); - gravity_is_point=false; - gravity_distance_scale=0; - point_attenuation=1; - - angular_damp=1.0; - linear_damp=0.1; - priority=0; - monitor_callback_id=0; - area_monitor_callback_id=0; - monitorable=false; - - + space_override_mode = Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED; + gravity = 9.80665; + gravity_vector = Vector2(0, -1); + gravity_is_point = false; + gravity_distance_scale = 0; + point_attenuation = 1; + + angular_damp = 1.0; + linear_damp = 0.1; + priority = 0; + monitor_callback_id = 0; + area_monitor_callback_id = 0; + monitorable = false; } Area2DSW::~Area2DSW() { - - } - diff --git a/servers/physics_2d/area_2d_sw.h b/servers/physics_2d/area_2d_sw.h index 02a65962e5..8c52c96527 100644 --- a/servers/physics_2d/area_2d_sw.h +++ b/servers/physics_2d/area_2d_sw.h @@ -29,18 +29,16 @@ #ifndef AREA_2D_SW_H #define AREA_2D_SW_H -#include "servers/physics_2d_server.h" #include "collision_object_2d_sw.h" #include "self_list.h" +#include "servers/physics_2d_server.h" //#include "servers/physics/query_sw.h" class Space2DSW; class Body2DSW; class Constraint2DSW; - -class Area2DSW : public CollisionObject2DSW{ - +class Area2DSW : public CollisionObject2DSW { Physics2DServer::AreaSpaceOverrideMode space_override_mode; real_t gravity; @@ -69,23 +67,22 @@ class Area2DSW : public CollisionObject2DSW{ uint32_t body_shape; uint32_t area_shape; - _FORCE_INLINE_ bool operator<( const BodyKey& p_key) const { + _FORCE_INLINE_ bool operator<(const BodyKey &p_key) const { - if (rid==p_key.rid) { + if (rid == p_key.rid) { - if (body_shape==p_key.body_shape) { + if (body_shape == p_key.body_shape) { return area_shape < p_key.area_shape; } else return body_shape < p_key.body_shape; } else return rid < p_key.rid; - } _FORCE_INLINE_ BodyKey() {} - BodyKey(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); - BodyKey(Area2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); + BodyKey(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); + BodyKey(Area2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); }; struct BodyState { @@ -93,122 +90,110 @@ class Area2DSW : public CollisionObject2DSW{ int state; _FORCE_INLINE_ void inc() { state++; } _FORCE_INLINE_ void dec() { state--; } - _FORCE_INLINE_ BodyState() { state=0; } + _FORCE_INLINE_ BodyState() { state = 0; } }; - Map<BodyKey,BodyState> monitored_bodies; - Map<BodyKey,BodyState> monitored_areas; + Map<BodyKey, BodyState> monitored_bodies; + Map<BodyKey, BodyState> monitored_areas; //virtual void shape_changed_notify(Shape2DSW *p_shape); //virtual void shape_deleted_notify(Shape2DSW *p_shape); - Set<Constraint2DSW*> constraints; - + Set<Constraint2DSW *> constraints; virtual void _shapes_changed(); void _queue_monitor_update(); public: - //_FORCE_INLINE_ const Matrix32& get_inverse_transform() const { return inverse_transform; } //_FORCE_INLINE_ SpaceSW* get_owner() { return owner; } - void set_monitor_callback(ObjectID p_id, const StringName& p_method); + void set_monitor_callback(ObjectID p_id, const StringName &p_method); _FORCE_INLINE_ bool has_monitor_callback() const { return monitor_callback_id; } - void set_area_monitor_callback(ObjectID p_id, const StringName& p_method); + void set_area_monitor_callback(ObjectID p_id, const StringName &p_method); _FORCE_INLINE_ bool has_area_monitor_callback() const { return area_monitor_callback_id; } + _FORCE_INLINE_ void add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); + _FORCE_INLINE_ void remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape); - _FORCE_INLINE_ void add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); - _FORCE_INLINE_ void remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape); + _FORCE_INLINE_ void add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape); + _FORCE_INLINE_ void remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape); - _FORCE_INLINE_ void add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape); - _FORCE_INLINE_ void remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape); - - void set_param(Physics2DServer::AreaParameter p_param, const Variant& p_value); + void set_param(Physics2DServer::AreaParameter p_param, const Variant &p_value); Variant get_param(Physics2DServer::AreaParameter p_param) const; void set_space_override_mode(Physics2DServer::AreaSpaceOverrideMode p_mode); Physics2DServer::AreaSpaceOverrideMode get_space_override_mode() const { return space_override_mode; } - _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity=p_gravity; } + _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity = p_gravity; } _FORCE_INLINE_ real_t get_gravity() const { return gravity; } - _FORCE_INLINE_ void set_gravity_vector(const Vector2& p_gravity) { gravity_vector=p_gravity; } + _FORCE_INLINE_ void set_gravity_vector(const Vector2 &p_gravity) { gravity_vector = p_gravity; } _FORCE_INLINE_ Vector2 get_gravity_vector() const { return gravity_vector; } - _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point=p_enable; } + _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point = p_enable; } _FORCE_INLINE_ bool is_gravity_point() const { return gravity_is_point; } - _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale=scale; } + _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale = scale; } _FORCE_INLINE_ real_t get_gravity_distance_scale() const { return gravity_distance_scale; } - _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation=p_point_attenuation; } + _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation = p_point_attenuation; } _FORCE_INLINE_ real_t get_point_attenuation() const { return point_attenuation; } - _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp=p_linear_damp; } + _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp = p_linear_damp; } _FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; } - _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp=p_angular_damp; } + _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp = p_angular_damp; } _FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; } - _FORCE_INLINE_ void set_priority(int p_priority) { priority=p_priority; } + _FORCE_INLINE_ void set_priority(int p_priority) { priority = p_priority; } _FORCE_INLINE_ int get_priority() const { return priority; } - _FORCE_INLINE_ void add_constraint( Constraint2DSW* p_constraint) { constraints.insert(p_constraint); } - _FORCE_INLINE_ void remove_constraint( Constraint2DSW* p_constraint) { constraints.erase(p_constraint); } - _FORCE_INLINE_ const Set<Constraint2DSW*>& get_constraints() const { return constraints; } + _FORCE_INLINE_ void add_constraint(Constraint2DSW *p_constraint) { constraints.insert(p_constraint); } + _FORCE_INLINE_ void remove_constraint(Constraint2DSW *p_constraint) { constraints.erase(p_constraint); } + _FORCE_INLINE_ const Set<Constraint2DSW *> &get_constraints() const { return constraints; } void set_monitorable(bool p_monitorable); _FORCE_INLINE_ bool is_monitorable() const { return monitorable; } - void set_transform(const Transform2D& p_transform); + void set_transform(const Transform2D &p_transform); void set_space(Space2DSW *p_space); - void call_queries(); Area2DSW(); ~Area2DSW(); }; -void Area2DSW::add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { +void Area2DSW::add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { - BodyKey bk(p_body,p_body_shape,p_area_shape); + BodyKey bk(p_body, p_body_shape, p_area_shape); monitored_bodies[bk].inc(); if (!monitor_query_list.in_list()) _queue_monitor_update(); } -void Area2DSW::remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { +void Area2DSW::remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) { - BodyKey bk(p_body,p_body_shape,p_area_shape); + BodyKey bk(p_body, p_body_shape, p_area_shape); monitored_bodies[bk].dec(); if (!monitor_query_list.in_list()) _queue_monitor_update(); } -void Area2DSW::add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) { +void Area2DSW::add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) { - - BodyKey bk(p_area,p_area_shape,p_self_shape); + BodyKey bk(p_area, p_area_shape, p_self_shape); monitored_areas[bk].inc(); if (!monitor_query_list.in_list()) _queue_monitor_update(); - - } -void Area2DSW::remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) { - +void Area2DSW::remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) { - BodyKey bk(p_area,p_area_shape,p_self_shape); + BodyKey bk(p_area, p_area_shape, p_self_shape); monitored_areas[bk].dec(); if (!monitor_query_list.in_list()) _queue_monitor_update(); } - - - - #endif // AREA_2D_SW_H diff --git a/servers/physics_2d/area_pair_2d_sw.cpp b/servers/physics_2d/area_pair_2d_sw.cpp index cb91caf626..769db8eb35 100644 --- a/servers/physics_2d/area_pair_2d_sw.cpp +++ b/servers/physics_2d/area_pair_2d_sw.cpp @@ -29,124 +29,105 @@ #include "area_pair_2d_sw.h" #include "collision_solver_2d_sw.h" - bool AreaPair2DSW::setup(real_t p_step) { - bool result = area->test_collision_mask(body) && CollisionSolver2DSW::solve(body->get_shape(body_shape),body->get_transform() * body->get_shape_transform(body_shape),Vector2(),area->get_shape(area_shape),area->get_transform() * area->get_shape_transform(area_shape),Vector2(),NULL,this); + bool result = area->test_collision_mask(body) && CollisionSolver2DSW::solve(body->get_shape(body_shape), body->get_transform() * body->get_shape_transform(body_shape), Vector2(), area->get_shape(area_shape), area->get_transform() * area->get_shape_transform(area_shape), Vector2(), NULL, this); - if (result!=colliding) { + if (result != colliding) { if (result) { - if (area->get_space_override_mode()!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED) + if (area->get_space_override_mode() != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED) body->add_area(area); if (area->has_monitor_callback()) - area->add_body_to_query(body,body_shape,area_shape); + area->add_body_to_query(body, body_shape, area_shape); } else { - if (area->get_space_override_mode()!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED) + if (area->get_space_override_mode() != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED) body->remove_area(area); if (area->has_monitor_callback()) - area->remove_body_from_query(body,body_shape,area_shape); - + area->remove_body_from_query(body, body_shape, area_shape); } - colliding=result; - + colliding = result; } return false; //never do any post solving } void AreaPair2DSW::solve(real_t p_step) { - - } +AreaPair2DSW::AreaPair2DSW(Body2DSW *p_body, int p_body_shape, Area2DSW *p_area, int p_area_shape) { -AreaPair2DSW::AreaPair2DSW(Body2DSW *p_body,int p_body_shape, Area2DSW *p_area,int p_area_shape) { - - - body=p_body; - area=p_area; - body_shape=p_body_shape; - area_shape=p_area_shape; - colliding=false; - body->add_constraint(this,0); + body = p_body; + area = p_area; + body_shape = p_body_shape; + area_shape = p_area_shape; + colliding = false; + body->add_constraint(this, 0); area->add_constraint(this); - if (p_body->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) //need to be active to process pair + if (p_body->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) //need to be active to process pair p_body->set_active(true); - } AreaPair2DSW::~AreaPair2DSW() { if (colliding) { - if (area->get_space_override_mode()!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED) + if (area->get_space_override_mode() != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED) body->remove_area(area); if (area->has_monitor_callback()) - area->remove_body_from_query(body,body_shape,area_shape); - - + area->remove_body_from_query(body, body_shape, area_shape); } body->remove_constraint(this); area->remove_constraint(this); } - ////////////////////////////////// - - bool Area2Pair2DSW::setup(real_t p_step) { - bool result = area_a->test_collision_mask(area_b) && CollisionSolver2DSW::solve(area_a->get_shape(shape_a),area_a->get_transform() * area_a->get_shape_transform(shape_a),Vector2(),area_b->get_shape(shape_b),area_b->get_transform() * area_b->get_shape_transform(shape_b),Vector2(),NULL,this); + bool result = area_a->test_collision_mask(area_b) && CollisionSolver2DSW::solve(area_a->get_shape(shape_a), area_a->get_transform() * area_a->get_shape_transform(shape_a), Vector2(), area_b->get_shape(shape_b), area_b->get_transform() * area_b->get_shape_transform(shape_b), Vector2(), NULL, this); - if (result!=colliding) { + if (result != colliding) { if (result) { if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) - area_b->add_area_to_query(area_a,shape_a,shape_b); + area_b->add_area_to_query(area_a, shape_a, shape_b); if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) - area_a->add_area_to_query(area_b,shape_b,shape_a); + area_a->add_area_to_query(area_b, shape_b, shape_a); } else { if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) - area_b->remove_area_from_query(area_a,shape_a,shape_b); + area_b->remove_area_from_query(area_a, shape_a, shape_b); if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) - area_a->remove_area_from_query(area_b,shape_b,shape_a); + area_a->remove_area_from_query(area_b, shape_b, shape_a); } - colliding=result; - + colliding = result; } return false; //never do any post solving } void Area2Pair2DSW::solve(real_t p_step) { - - } +Area2Pair2DSW::Area2Pair2DSW(Area2DSW *p_area_a, int p_shape_a, Area2DSW *p_area_b, int p_shape_b) { -Area2Pair2DSW::Area2Pair2DSW(Area2DSW *p_area_a,int p_shape_a, Area2DSW *p_area_b,int p_shape_b) { - - - area_a=p_area_a; - area_b=p_area_b; - shape_a=p_shape_a; - shape_b=p_shape_b; - colliding=false; + area_a = p_area_a; + area_b = p_area_b; + shape_a = p_shape_a; + shape_b = p_shape_b; + colliding = false; area_a->add_constraint(this); area_b->add_constraint(this); - } Area2Pair2DSW::~Area2Pair2DSW() { @@ -154,10 +135,10 @@ Area2Pair2DSW::~Area2Pair2DSW() { if (colliding) { if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) - area_b->remove_area_from_query(area_a,shape_a,shape_b); + area_b->remove_area_from_query(area_a, shape_a, shape_b); if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) - area_a->remove_area_from_query(area_b,shape_b,shape_a); + area_a->remove_area_from_query(area_b, shape_b, shape_a); } area_a->remove_constraint(this); diff --git a/servers/physics_2d/area_pair_2d_sw.h b/servers/physics_2d/area_pair_2d_sw.h index 219ca30c4b..78be9572bf 100644 --- a/servers/physics_2d/area_pair_2d_sw.h +++ b/servers/physics_2d/area_pair_2d_sw.h @@ -29,9 +29,9 @@ #ifndef AREA_PAIR_2D_SW_H #define AREA_PAIR_2D_SW_H -#include "constraint_2d_sw.h" -#include "body_2d_sw.h" #include "area_2d_sw.h" +#include "body_2d_sw.h" +#include "constraint_2d_sw.h" class AreaPair2DSW : public Constraint2DSW { @@ -40,16 +40,15 @@ class AreaPair2DSW : public Constraint2DSW { int body_shape; int area_shape; bool colliding; -public: +public: bool setup(real_t p_step); void solve(real_t p_step); - AreaPair2DSW(Body2DSW *p_body,int p_body_shape, Area2DSW *p_area,int p_area_shape); + AreaPair2DSW(Body2DSW *p_body, int p_body_shape, Area2DSW *p_area, int p_area_shape); ~AreaPair2DSW(); }; - class Area2Pair2DSW : public Constraint2DSW { Area2DSW *area_a; @@ -57,15 +56,13 @@ class Area2Pair2DSW : public Constraint2DSW { int shape_a; int shape_b; bool colliding; -public: +public: bool setup(real_t p_step); void solve(real_t p_step); - Area2Pair2DSW(Area2DSW *p_area_a,int p_shape_a, Area2DSW *p_area_b,int p_shape_b); + Area2Pair2DSW(Area2DSW *p_area_a, int p_shape_a, Area2DSW *p_area_b, int p_shape_b); ~Area2Pair2DSW(); }; - #endif // AREA_PAIR_2D_SW_H - diff --git a/servers/physics_2d/body_2d_sw.cpp b/servers/physics_2d/body_2d_sw.cpp index 0dab534ef9..d49dd35ade 100644 --- a/servers/physics_2d/body_2d_sw.cpp +++ b/servers/physics_2d/body_2d_sw.cpp @@ -27,107 +27,98 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "body_2d_sw.h" -#include "space_2d_sw.h" #include "area_2d_sw.h" #include "physics_2d_server_sw.h" +#include "space_2d_sw.h" void Body2DSW::_update_inertia() { if (!user_inertia && get_space() && !inertia_update_list.in_list()) get_space()->body_add_to_inertia_update_list(&inertia_update_list); - } - - void Body2DSW::update_inertias() { //update shapes and motions - switch(mode) { + switch (mode) { case Physics2DServer::BODY_MODE_RIGID: { - if(user_inertia) break; + if (user_inertia) break; //update tensor for allshapes, not the best way but should be somehow OK. (inspired from bullet) - real_t total_area=0; + real_t total_area = 0; - for (int i=0;i<get_shape_count();i++) { + for (int i = 0; i < get_shape_count(); i++) { - total_area+=get_shape_aabb(i).get_area(); + total_area += get_shape_aabb(i).get_area(); } - real_t _inertia=0; + real_t _inertia = 0; - for (int i=0;i<get_shape_count();i++) { + for (int i = 0; i < get_shape_count(); i++) { - const Shape2DSW* shape=get_shape(i); + const Shape2DSW *shape = get_shape(i); - real_t area=get_shape_aabb(i).get_area(); + real_t area = get_shape_aabb(i).get_area(); real_t mass = area * this->mass / total_area; Transform2D mtx = get_shape_transform(i); Vector2 scale = mtx.get_scale(); - _inertia += shape->get_moment_of_inertia(mass,scale) + mass * mtx.get_origin().length_squared(); + _inertia += shape->get_moment_of_inertia(mass, scale) + mass * mtx.get_origin().length_squared(); //Rect2 ab = get_shape_aabb(i); //_inertia+=mass*ab.size.dot(ab.size)/12.0f; - - - } - if (_inertia!=0) - _inv_inertia=1.0/_inertia; + if (_inertia != 0) + _inv_inertia = 1.0 / _inertia; else - _inv_inertia=0.0; //wathever + _inv_inertia = 0.0; //wathever if (mass) - _inv_mass=1.0/mass; + _inv_mass = 1.0 / mass; else - _inv_mass=0; + _inv_mass = 0; } break; case Physics2DServer::BODY_MODE_KINEMATIC: case Physics2DServer::BODY_MODE_STATIC: { - _inv_inertia=0; - _inv_mass=0; + _inv_inertia = 0; + _inv_mass = 0; } break; case Physics2DServer::BODY_MODE_CHARACTER: { - _inv_inertia=0; - _inv_mass=1.0/mass; + _inv_inertia = 0; + _inv_mass = 1.0 / mass; } break; } //_update_inertia_tensor(); //_update_shapes(); - } - - void Body2DSW::set_active(bool p_active) { - if (active==p_active) + if (active == p_active) return; - active=p_active; + active = p_active; if (!p_active) { if (get_space()) get_space()->body_remove_from_active_list(&active_list); } else { - if (mode==Physics2DServer::BODY_MODE_STATIC) + if (mode == Physics2DServer::BODY_MODE_STATIC) return; //static bodies can't become active if (get_space()) get_space()->body_add_to_active_list(&active_list); //still_time=0; } -/* + /* if (!space) return; @@ -140,27 +131,25 @@ void Body2DSW::set_active(bool p_active) { */ } - - void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, real_t p_value) { - switch(p_param) { + switch (p_param) { case Physics2DServer::BODY_PARAM_BOUNCE: { - bounce=p_value; + bounce = p_value; } break; case Physics2DServer::BODY_PARAM_FRICTION: { - friction=p_value; + friction = p_value; } break; case Physics2DServer::BODY_PARAM_MASS: { - ERR_FAIL_COND(p_value<=0); - mass=p_value; + ERR_FAIL_COND(p_value <= 0); + mass = p_value; _update_inertia(); } break; case Physics2DServer::BODY_PARAM_INERTIA: { - if(p_value<=0) { + if (p_value <= 0) { user_inertia = false; _update_inertia(); } else { @@ -169,23 +158,23 @@ void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, real_t p_value) } } break; case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: { - gravity_scale=p_value; + gravity_scale = p_value; } break; case Physics2DServer::BODY_PARAM_LINEAR_DAMP: { - linear_damp=p_value; + linear_damp = p_value; } break; case Physics2DServer::BODY_PARAM_ANGULAR_DAMP: { - angular_damp=p_value; + angular_damp = p_value; } break; - default:{} + default: {} } } real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const { - switch(p_param) { + switch (p_param) { case Physics2DServer::BODY_PARAM_BOUNCE: { return bounce; @@ -198,7 +187,7 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const { return mass; } break; case Physics2DServer::BODY_PARAM_INERTIA: { - return _inv_inertia==0 ? 0 : 1.0 / _inv_inertia; + return _inv_inertia == 0 ? 0 : 1.0 / _inv_inertia; } break; case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: { return gravity_scale; @@ -211,7 +200,7 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const { return angular_damp; } break; - default:{} + default: {} } return 0; @@ -219,33 +208,33 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const { void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) { - Physics2DServer::BodyMode prev=mode; - mode=p_mode; + Physics2DServer::BodyMode prev = mode; + mode = p_mode; - switch(p_mode) { - //CLEAR UP EVERYTHING IN CASE IT NOT WORKS! + switch (p_mode) { + //CLEAR UP EVERYTHING IN CASE IT NOT WORKS! case Physics2DServer::BODY_MODE_STATIC: case Physics2DServer::BODY_MODE_KINEMATIC: { _set_inv_transform(get_transform().affine_inverse()); - _inv_mass=0; - _set_static(p_mode==Physics2DServer::BODY_MODE_STATIC); - set_active(p_mode==Physics2DServer::BODY_MODE_KINEMATIC && contacts.size()); - linear_velocity=Vector2(); - angular_velocity=0; - if (mode==Physics2DServer::BODY_MODE_KINEMATIC && prev!=mode) { - first_time_kinematic=true; + _inv_mass = 0; + _set_static(p_mode == Physics2DServer::BODY_MODE_STATIC); + set_active(p_mode == Physics2DServer::BODY_MODE_KINEMATIC && contacts.size()); + linear_velocity = Vector2(); + angular_velocity = 0; + if (mode == Physics2DServer::BODY_MODE_KINEMATIC && prev != mode) { + first_time_kinematic = true; } } break; case Physics2DServer::BODY_MODE_RIGID: { - _inv_mass=mass>0?(1.0/mass):0; + _inv_mass = mass > 0 ? (1.0 / mass) : 0; _set_static(false); } break; case Physics2DServer::BODY_MODE_CHARACTER: { - _inv_mass=mass>0?(1.0/mass):0; + _inv_mass = mass > 0 ? (1.0 / mass) : 0; _set_static(false); } break; } @@ -255,7 +244,6 @@ void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) { if (get_space()) _update_queries(); */ - } Physics2DServer::BodyMode Body2DSW::get_mode() const { @@ -268,35 +256,33 @@ void Body2DSW::_shapes_changed() { wakeup_neighbours(); } -void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant& p_variant) { +void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant &p_variant) { - switch(p_state) { + switch (p_state) { case Physics2DServer::BODY_STATE_TRANSFORM: { + if (mode == Physics2DServer::BODY_MODE_KINEMATIC) { - if (mode==Physics2DServer::BODY_MODE_KINEMATIC) { - - new_transform=p_variant; + new_transform = p_variant; //wakeup_neighbours(); set_active(true); if (first_time_kinematic) { _set_transform(p_variant); _set_inv_transform(get_transform().affine_inverse()); - first_time_kinematic=false; + first_time_kinematic = false; } - } else if (mode==Physics2DServer::BODY_MODE_STATIC) { + } else if (mode == Physics2DServer::BODY_MODE_STATIC) { _set_transform(p_variant); _set_inv_transform(get_transform().affine_inverse()); wakeup_neighbours(); } else { Transform2D t = p_variant; t.orthonormalize(); - new_transform=get_transform(); //used as old to compute motion - if (t==new_transform) + new_transform = get_transform(); //used as old to compute motion + if (t == new_transform) break; _set_transform(t); _set_inv_transform(get_transform().inverse()); - } wakeup(); @@ -307,7 +293,7 @@ void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant& p_va if (mode==Physics2DServer::BODY_MODE_STATIC) break; */ - linear_velocity=p_variant; + linear_velocity = p_variant; wakeup(); } break; @@ -316,38 +302,37 @@ void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant& p_va if (mode!=Physics2DServer::BODY_MODE_RIGID) break; */ - angular_velocity=p_variant; + angular_velocity = p_variant; wakeup(); } break; case Physics2DServer::BODY_STATE_SLEEPING: { //? - if (mode==Physics2DServer::BODY_MODE_STATIC || mode==Physics2DServer::BODY_MODE_KINEMATIC) + if (mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC) break; - bool do_sleep=p_variant; + bool do_sleep = p_variant; if (do_sleep) { - linear_velocity=Vector2(); + linear_velocity = Vector2(); //biased_linear_velocity=Vector3(); - angular_velocity=0; + angular_velocity = 0; //biased_angular_velocity=Vector3(); set_active(false); } else { - if (mode!=Physics2DServer::BODY_MODE_STATIC) + if (mode != Physics2DServer::BODY_MODE_STATIC) set_active(true); } } break; case Physics2DServer::BODY_STATE_CAN_SLEEP: { - can_sleep=p_variant; - if (mode==Physics2DServer::BODY_MODE_RIGID && !active && !can_sleep) + can_sleep = p_variant; + if (mode == Physics2DServer::BODY_MODE_RIGID && !active && !can_sleep) set_active(true); } break; } - } Variant Body2DSW::get_state(Physics2DServer::BodyState p_state) const { - switch(p_state) { + switch (p_state) { case Physics2DServer::BODY_STATE_TRANSFORM: { return get_transform(); } break; @@ -368,8 +353,7 @@ Variant Body2DSW::get_state(Physics2DServer::BodyState p_state) const { return Variant(); } - -void Body2DSW::set_space(Space2DSW *p_space){ +void Body2DSW::set_space(Space2DSW *p_space) { if (get_space()) { @@ -381,7 +365,6 @@ void Body2DSW::set_space(Space2DSW *p_space){ get_space()->body_remove_from_active_list(&active_list); if (direct_state_query_list.in_list()) get_space()->body_remove_from_state_query_list(&direct_state_query_list); - } _set_space(p_space); @@ -398,18 +381,17 @@ void Body2DSW::set_space(Space2DSW *p_space){ set_active(true); } */ - } - first_integration=false; + first_integration = false; } void Body2DSW::_compute_area_gravity_and_dampenings(const Area2DSW *p_area) { if (p_area->is_gravity_point()) { - if(p_area->get_gravity_distance_scale() > 0) { + if (p_area->get_gravity_distance_scale() > 0) { Vector2 v = p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin(); - gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale()+1, 2) ); + gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale() + 1, 2)); } else { gravity += (p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin()).normalized() * p_area->get_gravity(); } @@ -423,7 +405,7 @@ void Body2DSW::_compute_area_gravity_and_dampenings(const Area2DSW *p_area) { void Body2DSW::integrate_forces(real_t p_step) { - if (mode==Physics2DServer::BODY_MODE_STATIC) + if (mode == Physics2DServer::BODY_MODE_STATIC) return; Area2DSW *def_area = get_space()->get_default_area(); @@ -432,47 +414,47 @@ void Body2DSW::integrate_forces(real_t p_step) { int ac = areas.size(); bool stopped = false; - gravity = Vector2(0,0); + gravity = Vector2(0, 0); area_angular_damp = 0; area_linear_damp = 0; if (ac) { areas.sort(); const AreaCMP *aa = &areas[0]; // damp_area = aa[ac-1].area; - for(int i=ac-1;i>=0 && !stopped;i--) { - Physics2DServer::AreaSpaceOverrideMode mode=aa[i].area->get_space_override_mode(); + for (int i = ac - 1; i >= 0 && !stopped; i--) { + Physics2DServer::AreaSpaceOverrideMode mode = aa[i].area->get_space_override_mode(); switch (mode) { case Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE: case Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: { _compute_area_gravity_and_dampenings(aa[i].area); - stopped = mode==Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE; + stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE; } break; case Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE: case Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: { - gravity = Vector2(0,0); + gravity = Vector2(0, 0); area_angular_damp = 0; area_linear_damp = 0; _compute_area_gravity_and_dampenings(aa[i].area); - stopped = mode==Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE; + stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE; } break; default: {} } } } - if( !stopped ) { + if (!stopped) { _compute_area_gravity_and_dampenings(def_area); } - gravity*=gravity_scale; + gravity *= gravity_scale; // If less than 0, override dampenings with that of the Body2D - if (angular_damp>=0) + if (angular_damp >= 0) area_angular_damp = angular_damp; /* else area_angular_damp=damp_area->get_angular_damp(); */ - if (linear_damp>=0) + if (linear_damp >= 0) area_linear_damp = linear_damp; /* else @@ -480,19 +462,18 @@ void Body2DSW::integrate_forces(real_t p_step) { */ Vector2 motion; - bool do_motion=false; + bool do_motion = false; - if (mode==Physics2DServer::BODY_MODE_KINEMATIC) { + if (mode == Physics2DServer::BODY_MODE_KINEMATIC) { //compute motion, angular and etc. velocities from prev transform motion = new_transform.get_origin() - get_transform().get_origin(); - linear_velocity = motion/p_step; + linear_velocity = motion / p_step; real_t rot = new_transform.get_rotation() - get_transform().get_rotation(); angular_velocity = rot / p_step; - - do_motion=true; + do_motion = true; /* for(int i=0;i<get_shape_count();i++) { @@ -505,102 +486,96 @@ void Body2DSW::integrate_forces(real_t p_step) { if (!omit_force_integration && !first_integration) { //overriden by direct state query - Vector2 force=gravity*mass; - force+=applied_force; - real_t torque=applied_torque; + Vector2 force = gravity * mass; + force += applied_force; + real_t torque = applied_torque; real_t damp = 1.0 - p_step * area_linear_damp; - if (damp<0) // reached zero in the given time - damp=0; + if (damp < 0) // reached zero in the given time + damp = 0; real_t angular_damp = 1.0 - p_step * area_angular_damp; - if (angular_damp<0) // reached zero in the given time - angular_damp=0; + if (angular_damp < 0) // reached zero in the given time + angular_damp = 0; - linear_velocity*=damp; - angular_velocity*=angular_damp; + linear_velocity *= damp; + angular_velocity *= angular_damp; - linear_velocity+=_inv_mass * force * p_step; - angular_velocity+=_inv_inertia * torque * p_step; + linear_velocity += _inv_mass * force * p_step; + angular_velocity += _inv_inertia * torque * p_step; } - if (continuous_cd_mode!=Physics2DServer::CCD_MODE_DISABLED) { + if (continuous_cd_mode != Physics2DServer::CCD_MODE_DISABLED) { motion = new_transform.get_origin() - get_transform().get_origin(); //linear_velocity*p_step; - do_motion=true; + do_motion = true; } } - //motion=linear_velocity*p_step; - first_integration=false; - biased_angular_velocity=0; - biased_linear_velocity=Vector2(); + first_integration = false; + biased_angular_velocity = 0; + biased_linear_velocity = Vector2(); - if (do_motion) {//shapes temporarily extend for raycast + if (do_motion) { //shapes temporarily extend for raycast _update_shapes_with_motion(motion); } // damp_area=NULL; // clear the area, so it is set in the next frame - def_area=NULL; // clear the area, so it is set in the next frame - contact_count=0; - + def_area = NULL; // clear the area, so it is set in the next frame + contact_count = 0; } void Body2DSW::integrate_velocities(real_t p_step) { - if (mode==Physics2DServer::BODY_MODE_STATIC) + if (mode == Physics2DServer::BODY_MODE_STATIC) return; if (fi_callback) get_space()->body_add_to_state_query_list(&direct_state_query_list); - if (mode==Physics2DServer::BODY_MODE_KINEMATIC) { + if (mode == Physics2DServer::BODY_MODE_KINEMATIC) { - _set_transform(new_transform,false); + _set_transform(new_transform, false); _set_inv_transform(new_transform.affine_inverse()); - if (contacts.size()==0 && linear_velocity==Vector2() && angular_velocity==0) + if (contacts.size() == 0 && linear_velocity == Vector2() && angular_velocity == 0) set_active(false); //stopped moving, deactivate return; } - real_t total_angular_velocity = angular_velocity+biased_angular_velocity; - Vector2 total_linear_velocity=linear_velocity+biased_linear_velocity; + real_t total_angular_velocity = angular_velocity + biased_angular_velocity; + Vector2 total_linear_velocity = linear_velocity + biased_linear_velocity; real_t angle = get_transform().get_rotation() + total_angular_velocity * p_step; Vector2 pos = get_transform().get_origin() + total_linear_velocity * p_step; - _set_transform(Transform2D(angle,pos),continuous_cd_mode==Physics2DServer::CCD_MODE_DISABLED); + _set_transform(Transform2D(angle, pos), continuous_cd_mode == Physics2DServer::CCD_MODE_DISABLED); _set_inv_transform(get_transform().inverse()); - if (continuous_cd_mode!=Physics2DServer::CCD_MODE_DISABLED) - new_transform=get_transform(); + if (continuous_cd_mode != Physics2DServer::CCD_MODE_DISABLED) + new_transform = get_transform(); //_update_inertia_tensor(); } - - void Body2DSW::wakeup_neighbours() { + for (Map<Constraint2DSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) { - - for(Map<Constraint2DSW*,int>::Element *E=constraint_map.front();E;E=E->next()) { - - const Constraint2DSW *c=E->key(); + const Constraint2DSW *c = E->key(); Body2DSW **n = c->get_body_ptr(); - int bc=c->get_body_count(); + int bc = c->get_body_count(); - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { - if (i==E->get()) + if (i == E->get()) continue; Body2DSW *b = n[i]; - if (b->mode!=Physics2DServer::BODY_MODE_RIGID) + if (b->mode != Physics2DServer::BODY_MODE_RIGID) continue; if (!b->is_active()) @@ -611,116 +586,103 @@ void Body2DSW::wakeup_neighbours() { void Body2DSW::call_queries() { - if (fi_callback) { Physics2DDirectBodyStateSW *dbs = Physics2DDirectBodyStateSW::singleton; - dbs->body=this; - - Variant v=dbs; - const Variant *vp[2]={&v,&fi_callback->callback_udata}; + dbs->body = this; + Variant v = dbs; + const Variant *vp[2] = { &v, &fi_callback->callback_udata }; Object *obj = ObjectDB::get_instance(fi_callback->id); if (!obj) { - set_force_integration_callback(0,StringName()); + set_force_integration_callback(0, StringName()); } else { Variant::CallError ce; if (fi_callback->callback_udata.get_type()) { - obj->call(fi_callback->method,vp,2,ce); + obj->call(fi_callback->method, vp, 2, ce); } else { - obj->call(fi_callback->method,vp,1,ce); + obj->call(fi_callback->method, vp, 1, ce); } } - - } - } +bool Body2DSW::sleep_test(real_t p_step) { -bool Body2DSW::sleep_test(real_t p_step) { - - if (mode==Physics2DServer::BODY_MODE_STATIC || mode==Physics2DServer::BODY_MODE_KINEMATIC) + if (mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC) return true; // - else if (mode==Physics2DServer::BODY_MODE_CHARACTER) + else if (mode == Physics2DServer::BODY_MODE_CHARACTER) return !active; // characters and kinematic bodies don't sleep unless asked to sleep else if (!can_sleep) return false; + if (Math::abs(angular_velocity) < get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold() * get_space()->get_body_linear_velocity_sleep_treshold()) { - - - if (Math::abs(angular_velocity)<get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold()*get_space()->get_body_linear_velocity_sleep_treshold()) { - - still_time+=p_step; + still_time += p_step; return still_time > get_space()->get_body_time_to_sleep(); } else { - still_time=0; //maybe this should be set to 0 on set_active? + still_time = 0; //maybe this should be set to 0 on set_active? return false; } } - -void Body2DSW::set_force_integration_callback(ObjectID p_id,const StringName& p_method,const Variant& p_udata) { +void Body2DSW::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) { if (fi_callback) { memdelete(fi_callback); - fi_callback=NULL; + fi_callback = NULL; } + if (p_id != 0) { - if (p_id!=0) { - - fi_callback=memnew(ForceIntegrationCallback); - fi_callback->id=p_id; - fi_callback->method=p_method; - fi_callback->callback_udata=p_udata; + fi_callback = memnew(ForceIntegrationCallback); + fi_callback->id = p_id; + fi_callback->method = p_method; + fi_callback->callback_udata = p_udata; } - } -Body2DSW::Body2DSW() : CollisionObject2DSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) { - - - mode=Physics2DServer::BODY_MODE_RIGID; - active=true; - angular_velocity=0; - biased_angular_velocity=0; - mass=1; - user_inertia=false; - _inv_inertia=0; - _inv_mass=1; - bounce=0; - friction=1; - omit_force_integration=false; - applied_torque=0; - island_step=0; - island_next=NULL; - island_list_next=NULL; +Body2DSW::Body2DSW() + : CollisionObject2DSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) { + + mode = Physics2DServer::BODY_MODE_RIGID; + active = true; + angular_velocity = 0; + biased_angular_velocity = 0; + mass = 1; + user_inertia = false; + _inv_inertia = 0; + _inv_mass = 1; + bounce = 0; + friction = 1; + omit_force_integration = false; + applied_torque = 0; + island_step = 0; + island_next = NULL; + island_list_next = NULL; _set_static(false); - first_time_kinematic=false; - linear_damp=-1; - angular_damp=-1; - area_angular_damp=0; - area_linear_damp=0; - contact_count=0; - gravity_scale=1.0; - using_one_way_cache=false; - one_way_collision_max_depth=0.1; - first_integration=false; - - still_time=0; - continuous_cd_mode=Physics2DServer::CCD_MODE_DISABLED; - can_sleep=false; - fi_callback=NULL; - + first_time_kinematic = false; + linear_damp = -1; + angular_damp = -1; + area_angular_damp = 0; + area_linear_damp = 0; + contact_count = 0; + gravity_scale = 1.0; + using_one_way_cache = false; + one_way_collision_max_depth = 0.1; + first_integration = false; + + still_time = 0; + continuous_cd_mode = Physics2DServer::CCD_MODE_DISABLED; + can_sleep = false; + fi_callback = NULL; } Body2DSW::~Body2DSW() { @@ -729,17 +691,16 @@ Body2DSW::~Body2DSW() { memdelete(fi_callback); } -Physics2DDirectBodyStateSW *Physics2DDirectBodyStateSW::singleton=NULL; +Physics2DDirectBodyStateSW *Physics2DDirectBodyStateSW::singleton = NULL; -Physics2DDirectSpaceState* Physics2DDirectBodyStateSW::get_space_state() { +Physics2DDirectSpaceState *Physics2DDirectBodyStateSW::get_space_state() { return body->get_space()->get_direct_state(); } - Variant Physics2DDirectBodyStateSW::get_contact_collider_shape_metadata(int p_contact_idx) const { - ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Variant()); + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Variant()); if (!Physics2DServerSW::singletonsw->body_owner.owns(body->contacts[p_contact_idx].collider)) { @@ -748,11 +709,10 @@ Variant Physics2DDirectBodyStateSW::get_contact_collider_shape_metadata(int p_co Body2DSW *other = Physics2DServerSW::singletonsw->body_owner.get(body->contacts[p_contact_idx].collider); int sidx = body->contacts[p_contact_idx].collider_shape; - if (sidx<0 || sidx>=other->get_shape_count()) { + if (sidx < 0 || sidx >= other->get_shape_count()) { return Variant(); } - return other->get_shape_metadata(sidx); } diff --git a/servers/physics_2d/body_2d_sw.h b/servers/physics_2d/body_2d_sw.h index 3fb01959a9..7e4fef8df3 100644 --- a/servers/physics_2d/body_2d_sw.h +++ b/servers/physics_2d/body_2d_sw.h @@ -29,16 +29,14 @@ #ifndef BODY_2D_SW_H #define BODY_2D_SW_H +#include "area_2d_sw.h" #include "collision_object_2d_sw.h" #include "vset.h" -#include "area_2d_sw.h" class Constraint2DSW; - class Body2DSW : public CollisionObject2DSW { - Physics2DServer::BodyMode mode; Vector2 biased_linear_velocity; @@ -71,7 +69,6 @@ class Body2DSW : public CollisionObject2DSW { Vector2 one_way_collision_direction; real_t one_way_collision_max_depth; - SelfList<Body2DSW> active_list; SelfList<Body2DSW> inertia_update_list; SelfList<Body2DSW> direct_state_query_list; @@ -88,25 +85,25 @@ class Body2DSW : public CollisionObject2DSW { virtual void _shapes_changed(); Transform2D new_transform; - - Map<Constraint2DSW*,int> constraint_map; + Map<Constraint2DSW *, int> constraint_map; struct AreaCMP { Area2DSW *area; int refCount; - _FORCE_INLINE_ bool operator==(const AreaCMP& p_cmp) const { return area->get_self() == p_cmp.area->get_self();} - _FORCE_INLINE_ bool operator<(const AreaCMP& p_cmp) const { return area->get_priority() < p_cmp.area->get_priority();} + _FORCE_INLINE_ bool operator==(const AreaCMP &p_cmp) const { return area->get_self() == p_cmp.area->get_self(); } + _FORCE_INLINE_ bool operator<(const AreaCMP &p_cmp) const { return area->get_priority() < p_cmp.area->get_priority(); } _FORCE_INLINE_ AreaCMP() {} - _FORCE_INLINE_ AreaCMP(Area2DSW *p_area) { area=p_area; refCount=1;} + _FORCE_INLINE_ AreaCMP(Area2DSW *p_area) { + area = p_area; + refCount = 1; + } }; - Vector<AreaCMP> areas; struct Contact { - Vector2 local_pos; Vector2 local_normal; real_t depth; @@ -130,24 +127,20 @@ class Body2DSW : public CollisionObject2DSW { ForceIntegrationCallback *fi_callback; - uint64_t island_step; Body2DSW *island_next; Body2DSW *island_list_next; _FORCE_INLINE_ void _compute_area_gravity_and_dampenings(const Area2DSW *p_area); -friend class Physics2DDirectBodyStateSW; // i give up, too many functions to expose + friend class Physics2DDirectBodyStateSW; // i give up, too many functions to expose public: - - - void set_force_integration_callback(ObjectID p_id, const StringName& p_method, const Variant &p_udata=Variant()); - + void set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata = Variant()); _FORCE_INLINE_ void add_area(Area2DSW *p_area) { int index = areas.find(AreaCMP(p_area)); - if( index > -1 ) { + if (index > -1) { areas[index].refCount += 1; } else { areas.ordered_insert(AreaCMP(p_area)); @@ -156,62 +149,64 @@ public: _FORCE_INLINE_ void remove_area(Area2DSW *p_area) { int index = areas.find(AreaCMP(p_area)); - if( index > -1 ) { + if (index > -1) { areas[index].refCount -= 1; - if( areas[index].refCount < 1 ) + if (areas[index].refCount < 1) areas.remove(index); } } - _FORCE_INLINE_ void set_max_contacts_reported(int p_size) { contacts.resize(p_size); contact_count=0; if (mode==Physics2DServer::BODY_MODE_KINEMATIC && p_size) set_active(true);} + _FORCE_INLINE_ void set_max_contacts_reported(int p_size) { + contacts.resize(p_size); + contact_count = 0; + if (mode == Physics2DServer::BODY_MODE_KINEMATIC && p_size) set_active(true); + } _FORCE_INLINE_ int get_max_contacts_reported() const { return contacts.size(); } _FORCE_INLINE_ bool can_report_contacts() const { return !contacts.empty(); } - _FORCE_INLINE_ void add_contact(const Vector2& p_local_pos,const Vector2& p_local_normal, real_t p_depth, int p_local_shape, const Vector2& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector2& p_collider_velocity_at_pos); + _FORCE_INLINE_ void add_contact(const Vector2 &p_local_pos, const Vector2 &p_local_normal, real_t p_depth, int p_local_shape, const Vector2 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector2 &p_collider_velocity_at_pos); - - _FORCE_INLINE_ void add_exception(const RID& p_exception) { exceptions.insert(p_exception);} - _FORCE_INLINE_ void remove_exception(const RID& p_exception) { exceptions.erase(p_exception);} - _FORCE_INLINE_ bool has_exception(const RID& p_exception) const { return exceptions.has(p_exception);} - _FORCE_INLINE_ const VSet<RID>& get_exceptions() const { return exceptions;} + _FORCE_INLINE_ void add_exception(const RID &p_exception) { exceptions.insert(p_exception); } + _FORCE_INLINE_ void remove_exception(const RID &p_exception) { exceptions.erase(p_exception); } + _FORCE_INLINE_ bool has_exception(const RID &p_exception) const { return exceptions.has(p_exception); } + _FORCE_INLINE_ const VSet<RID> &get_exceptions() const { return exceptions; } _FORCE_INLINE_ uint64_t get_island_step() const { return island_step; } - _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; } + _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; } - _FORCE_INLINE_ Body2DSW* get_island_next() const { return island_next; } - _FORCE_INLINE_ void set_island_next(Body2DSW* p_next) { island_next=p_next; } + _FORCE_INLINE_ Body2DSW *get_island_next() const { return island_next; } + _FORCE_INLINE_ void set_island_next(Body2DSW *p_next) { island_next = p_next; } - _FORCE_INLINE_ Body2DSW* get_island_list_next() const { return island_list_next; } - _FORCE_INLINE_ void set_island_list_next(Body2DSW* p_next) { island_list_next=p_next; } + _FORCE_INLINE_ Body2DSW *get_island_list_next() const { return island_list_next; } + _FORCE_INLINE_ void set_island_list_next(Body2DSW *p_next) { island_list_next = p_next; } - _FORCE_INLINE_ void add_constraint(Constraint2DSW* p_constraint, int p_pos) { constraint_map[p_constraint]=p_pos; } - _FORCE_INLINE_ void remove_constraint(Constraint2DSW* p_constraint) { constraint_map.erase(p_constraint); } - const Map<Constraint2DSW*,int>& get_constraint_map() const { return constraint_map; } + _FORCE_INLINE_ void add_constraint(Constraint2DSW *p_constraint, int p_pos) { constraint_map[p_constraint] = p_pos; } + _FORCE_INLINE_ void remove_constraint(Constraint2DSW *p_constraint) { constraint_map.erase(p_constraint); } + const Map<Constraint2DSW *, int> &get_constraint_map() const { return constraint_map; } - _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration=p_omit_force_integration; } + _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration = p_omit_force_integration; } _FORCE_INLINE_ bool get_omit_force_integration() const { return omit_force_integration; } - _FORCE_INLINE_ void set_linear_velocity(const Vector2& p_velocity) {linear_velocity=p_velocity; } + _FORCE_INLINE_ void set_linear_velocity(const Vector2 &p_velocity) { linear_velocity = p_velocity; } _FORCE_INLINE_ Vector2 get_linear_velocity() const { return linear_velocity; } - _FORCE_INLINE_ void set_angular_velocity(real_t p_velocity) { angular_velocity=p_velocity; } + _FORCE_INLINE_ void set_angular_velocity(real_t p_velocity) { angular_velocity = p_velocity; } _FORCE_INLINE_ real_t get_angular_velocity() const { return angular_velocity; } - _FORCE_INLINE_ void set_biased_linear_velocity(const Vector2& p_velocity) {biased_linear_velocity=p_velocity; } + _FORCE_INLINE_ void set_biased_linear_velocity(const Vector2 &p_velocity) { biased_linear_velocity = p_velocity; } _FORCE_INLINE_ Vector2 get_biased_linear_velocity() const { return biased_linear_velocity; } - _FORCE_INLINE_ void set_biased_angular_velocity(real_t p_velocity) { biased_angular_velocity=p_velocity; } + _FORCE_INLINE_ void set_biased_angular_velocity(real_t p_velocity) { biased_angular_velocity = p_velocity; } _FORCE_INLINE_ real_t get_biased_angular_velocity() const { return biased_angular_velocity; } - - _FORCE_INLINE_ void apply_impulse(const Vector2& p_offset, const Vector2& p_impulse) { + _FORCE_INLINE_ void apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse) { linear_velocity += p_impulse * _inv_mass; angular_velocity += _inv_inertia * p_offset.cross(p_impulse); } - _FORCE_INLINE_ void apply_bias_impulse(const Vector2& p_pos, const Vector2& p_j) { + _FORCE_INLINE_ void apply_bias_impulse(const Vector2 &p_pos, const Vector2 &p_j) { biased_linear_velocity += p_j * _inv_mass; biased_angular_velocity += _inv_inertia * p_pos.cross(p_j); @@ -221,45 +216,42 @@ public: _FORCE_INLINE_ bool is_active() const { return active; } _FORCE_INLINE_ void wakeup() { - if ((!get_space()) || mode==Physics2DServer::BODY_MODE_STATIC || mode==Physics2DServer::BODY_MODE_KINEMATIC) + if ((!get_space()) || mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC) return; set_active(true); } - - - void set_param(Physics2DServer::BodyParameter p_param, real_t); real_t get_param(Physics2DServer::BodyParameter p_param) const; void set_mode(Physics2DServer::BodyMode p_mode); Physics2DServer::BodyMode get_mode() const; - void set_state(Physics2DServer::BodyState p_state, const Variant& p_variant); + void set_state(Physics2DServer::BodyState p_state, const Variant &p_variant); Variant get_state(Physics2DServer::BodyState p_state) const; - void set_applied_force(const Vector2& p_force) { applied_force=p_force; } + void set_applied_force(const Vector2 &p_force) { applied_force = p_force; } Vector2 get_applied_force() const { return applied_force; } - void set_applied_torque(real_t p_torque) { applied_torque=p_torque; } + void set_applied_torque(real_t p_torque) { applied_torque = p_torque; } real_t get_applied_torque() const { return applied_torque; } - _FORCE_INLINE_ void add_force(const Vector2& p_force, const Vector2& p_offset) { + _FORCE_INLINE_ void add_force(const Vector2 &p_force, const Vector2 &p_offset) { applied_force += p_force; applied_torque += p_offset.cross(p_force); } - _FORCE_INLINE_ void set_continuous_collision_detection_mode(Physics2DServer::CCDMode p_mode) { continuous_cd_mode=p_mode; } + _FORCE_INLINE_ void set_continuous_collision_detection_mode(Physics2DServer::CCDMode p_mode) { continuous_cd_mode = p_mode; } _FORCE_INLINE_ Physics2DServer::CCDMode get_continuous_collision_detection_mode() const { return continuous_cd_mode; } - void set_one_way_collision_direction(const Vector2& p_dir) { - one_way_collision_direction=p_dir; - using_one_way_cache=one_way_collision_direction!=Vector2(); + void set_one_way_collision_direction(const Vector2 &p_dir) { + one_way_collision_direction = p_dir; + using_one_way_cache = one_way_collision_direction != Vector2(); } Vector2 get_one_way_collision_direction() const { return one_way_collision_direction; } - void set_one_way_collision_max_depth(real_t p_depth) { one_way_collision_max_depth=p_depth; } + void set_one_way_collision_max_depth(real_t p_depth) { one_way_collision_max_depth = p_depth; } real_t get_one_way_collision_max_depth() const { return one_way_collision_max_depth; } _FORCE_INLINE_ bool is_using_one_way_collision() const { return using_one_way_cache; } @@ -276,16 +268,15 @@ public: _FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; } _FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; } - void integrate_forces(real_t p_step); void integrate_velocities(real_t p_step); _FORCE_INLINE_ Vector2 get_motion() const { - if (mode>Physics2DServer::BODY_MODE_KINEMATIC) { + if (mode > Physics2DServer::BODY_MODE_KINEMATIC) { return new_transform.get_origin() - get_transform().get_origin(); - } else if (mode==Physics2DServer::BODY_MODE_KINEMATIC) { - return get_transform().get_origin() -new_transform.get_origin(); //kinematic simulates forward + } else if (mode == Physics2DServer::BODY_MODE_KINEMATIC) { + return get_transform().get_origin() - new_transform.get_origin(); //kinematic simulates forward } return Vector2(); } @@ -297,111 +288,127 @@ public: Body2DSW(); ~Body2DSW(); - }; - //add contact inline -void Body2DSW::add_contact(const Vector2& p_local_pos,const Vector2& p_local_normal, real_t p_depth, int p_local_shape, const Vector2& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector2& p_collider_velocity_at_pos) { +void Body2DSW::add_contact(const Vector2 &p_local_pos, const Vector2 &p_local_normal, real_t p_depth, int p_local_shape, const Vector2 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector2 &p_collider_velocity_at_pos) { - int c_max=contacts.size(); + int c_max = contacts.size(); - if (c_max==0) + if (c_max == 0) return; Contact *c = &contacts[0]; + int idx = -1; - int idx=-1; - - if (contact_count<c_max) { - idx=contact_count++; + if (contact_count < c_max) { + idx = contact_count++; } else { - real_t least_depth=1e20; - int least_deep=-1; - for(int i=0;i<c_max;i++) { + real_t least_depth = 1e20; + int least_deep = -1; + for (int i = 0; i < c_max; i++) { - if (i==0 || c[i].depth<least_depth) { - least_deep=i; - least_depth=c[i].depth; + if (i == 0 || c[i].depth < least_depth) { + least_deep = i; + least_depth = c[i].depth; } } - if (least_deep>=0 && least_depth<p_depth) { + if (least_deep >= 0 && least_depth < p_depth) { - idx=least_deep; + idx = least_deep; } - if (idx==-1) + if (idx == -1) return; //none least deepe than this } - c[idx].local_pos=p_local_pos; - c[idx].local_normal=p_local_normal; - c[idx].depth=p_depth; - c[idx].local_shape=p_local_shape; - c[idx].collider_pos=p_collider_pos; - c[idx].collider_shape=p_collider_shape; - c[idx].collider_instance_id=p_collider_instance_id; - c[idx].collider=p_collider; - c[idx].collider_velocity_at_pos=p_collider_velocity_at_pos; - + c[idx].local_pos = p_local_pos; + c[idx].local_normal = p_local_normal; + c[idx].depth = p_depth; + c[idx].local_shape = p_local_shape; + c[idx].collider_pos = p_collider_pos; + c[idx].collider_shape = p_collider_shape; + c[idx].collider_instance_id = p_collider_instance_id; + c[idx].collider = p_collider; + c[idx].collider_velocity_at_pos = p_collider_velocity_at_pos; } - class Physics2DDirectBodyStateSW : public Physics2DDirectBodyState { - GDCLASS( Physics2DDirectBodyStateSW, Physics2DDirectBodyState ); + GDCLASS(Physics2DDirectBodyStateSW, Physics2DDirectBodyState); public: - static Physics2DDirectBodyStateSW *singleton; Body2DSW *body; real_t step; - virtual Vector2 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area - virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area - virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area + virtual Vector2 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area + virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area + virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area - virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass - virtual real_t get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space + virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass + virtual real_t get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space - virtual void set_linear_velocity(const Vector2& p_velocity) { body->set_linear_velocity(p_velocity); } - virtual Vector2 get_linear_velocity() const { return body->get_linear_velocity(); } + virtual void set_linear_velocity(const Vector2 &p_velocity) { body->set_linear_velocity(p_velocity); } + virtual Vector2 get_linear_velocity() const { return body->get_linear_velocity(); } - virtual void set_angular_velocity(real_t p_velocity) { body->set_angular_velocity(p_velocity); } - virtual real_t get_angular_velocity() const { return body->get_angular_velocity(); } + virtual void set_angular_velocity(real_t p_velocity) { body->set_angular_velocity(p_velocity); } + virtual real_t get_angular_velocity() const { return body->get_angular_velocity(); } - virtual void set_transform(const Transform2D& p_transform) { body->set_state(Physics2DServer::BODY_STATE_TRANSFORM,p_transform); } - virtual Transform2D get_transform() const { return body->get_transform(); } + virtual void set_transform(const Transform2D &p_transform) { body->set_state(Physics2DServer::BODY_STATE_TRANSFORM, p_transform); } + virtual Transform2D get_transform() const { return body->get_transform(); } - virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); } - virtual bool is_sleeping() const { return !body->is_active(); } + virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); } + virtual bool is_sleeping() const { return !body->is_active(); } - virtual int get_contact_count() const { return body->contact_count; } + virtual int get_contact_count() const { return body->contact_count; } virtual Vector2 get_contact_local_pos(int p_contact_idx) const { - ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2()); return body->contacts[p_contact_idx].local_pos; } - virtual Vector2 get_contact_local_normal(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); return body->contacts[p_contact_idx].local_normal; } - virtual int get_contact_local_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,-1); return body->contacts[p_contact_idx].local_shape; } + virtual Vector2 get_contact_local_normal(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2()); + return body->contacts[p_contact_idx].local_normal; + } + virtual int get_contact_local_shape(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, -1); + return body->contacts[p_contact_idx].local_shape; + } - virtual RID get_contact_collider(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,RID()); return body->contacts[p_contact_idx].collider; } - virtual Vector2 get_contact_collider_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); return body->contacts[p_contact_idx].collider_pos; } - virtual ObjectID get_contact_collider_id(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_instance_id; } - virtual int get_contact_collider_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_shape; } + virtual RID get_contact_collider(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, RID()); + return body->contacts[p_contact_idx].collider; + } + virtual Vector2 get_contact_collider_pos(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2()); + return body->contacts[p_contact_idx].collider_pos; + } + virtual ObjectID get_contact_collider_id(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0); + return body->contacts[p_contact_idx].collider_instance_id; + } + virtual int get_contact_collider_shape(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0); + return body->contacts[p_contact_idx].collider_shape; + } virtual Variant get_contact_collider_shape_metadata(int p_contact_idx) const; - virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); return body->contacts[p_contact_idx].collider_velocity_at_pos; } - - virtual Physics2DDirectSpaceState* get_space_state(); + virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const { + ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2()); + return body->contacts[p_contact_idx].collider_velocity_at_pos; + } + virtual Physics2DDirectSpaceState *get_space_state(); virtual real_t get_step() const { return step; } - Physics2DDirectBodyStateSW() { singleton=this; body=NULL; } + Physics2DDirectBodyStateSW() { + singleton = this; + body = NULL; + } }; - #endif // BODY_2D_SW_H diff --git a/servers/physics_2d/body_pair_2d_sw.cpp b/servers/physics_2d/body_pair_2d_sw.cpp index c05d61b658..ee94a7acec 100644 --- a/servers/physics_2d/body_pair_2d_sw.cpp +++ b/servers/physics_2d/body_pair_2d_sw.cpp @@ -30,54 +30,52 @@ #include "collision_solver_2d_sw.h" #include "space_2d_sw.h" - #define POSITION_CORRECTION #define ACCUMULATE_IMPULSES -void BodyPair2DSW::_add_contact(const Vector2& p_point_A,const Vector2& p_point_B,void *p_self) { +void BodyPair2DSW::_add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self) { BodyPair2DSW *self = (BodyPair2DSW *)p_self; - self->_contact_added_callback(p_point_A,p_point_B); - + self->_contact_added_callback(p_point_A, p_point_B); } -void BodyPair2DSW::_contact_added_callback(const Vector2& p_point_A,const Vector2& p_point_B) { +void BodyPair2DSW::_contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B) { // check if we already have the contact Vector2 local_A = A->get_inv_transform().basis_xform(p_point_A); - Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B-offset_B); + Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B - offset_B); int new_index = contact_count; - ERR_FAIL_COND( new_index >= (MAX_CONTACTS+1) ); + ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1)); Contact contact; - contact.acc_normal_impulse=0; - contact.acc_bias_impulse=0; - contact.acc_tangent_impulse=0; - contact.local_A=local_A; - contact.local_B=local_B; - contact.reused=true; - contact.normal=(p_point_A-p_point_B).normalized(); + contact.acc_normal_impulse = 0; + contact.acc_bias_impulse = 0; + contact.acc_tangent_impulse = 0; + contact.local_A = local_A; + contact.local_B = local_B; + contact.reused = true; + contact.normal = (p_point_A - p_point_B).normalized(); // attempt to determine if the contact will be reused real_t recycle_radius_2 = space->get_contact_recycle_radius() * space->get_contact_recycle_radius(); - for (int i=0;i<contact_count;i++) { + for (int i = 0; i < contact_count; i++) { - Contact& c = contacts[i]; + Contact &c = contacts[i]; if ( - c.local_A.distance_squared_to( local_A ) < (recycle_radius_2) && - c.local_B.distance_squared_to( local_B ) < (recycle_radius_2) ) { + c.local_A.distance_squared_to(local_A) < (recycle_radius_2) && + c.local_B.distance_squared_to(local_B) < (recycle_radius_2)) { - contact.acc_normal_impulse=c.acc_normal_impulse; - contact.acc_tangent_impulse=c.acc_tangent_impulse; - contact.acc_bias_impulse=c.acc_bias_impulse; - new_index=i; + contact.acc_normal_impulse = c.acc_normal_impulse; + contact.acc_tangent_impulse = c.acc_tangent_impulse; + contact.acc_bias_impulse = c.acc_bias_impulse; + new_index = i; break; } } @@ -88,44 +86,41 @@ void BodyPair2DSW::_contact_added_callback(const Vector2& p_point_A,const Vector // remove the contact with the minimum depth - int least_deep=-1; - real_t min_depth=1e10; + int least_deep = -1; + real_t min_depth = 1e10; + for (int i = 0; i <= contact_count; i++) { - for (int i=0;i<=contact_count;i++) { - - Contact& c = (i==contact_count)?contact:contacts[i]; + Contact &c = (i == contact_count) ? contact : contacts[i]; Vector2 global_A = A->get_transform().basis_xform(c.local_A); - Vector2 global_B = B->get_transform().basis_xform(c.local_B)+offset_B; + Vector2 global_B = B->get_transform().basis_xform(c.local_B) + offset_B; Vector2 axis = global_A - global_B; - real_t depth = axis.dot( c.normal ); - + real_t depth = axis.dot(c.normal); - if (depth<min_depth) { + if (depth < min_depth) { - min_depth=depth; - least_deep=i; + min_depth = depth; + least_deep = i; } } - ERR_FAIL_COND(least_deep==-1); + ERR_FAIL_COND(least_deep == -1); if (least_deep < contact_count) { //replace the last deep contact by the new one - contacts[least_deep]=contact; + contacts[least_deep] = contact; } return; } - contacts[new_index]=contact; + contacts[new_index] = contact; - if (new_index==contact_count) { + if (new_index == contact_count) { contact_count++; } - } void BodyPair2DSW::_validate_contacts() { @@ -133,39 +128,35 @@ void BodyPair2DSW::_validate_contacts() { //make sure to erase contacts that are no longer valid real_t max_separation = space->get_contact_max_separation(); - real_t max_separation2 = max_separation*max_separation; + real_t max_separation2 = max_separation * max_separation; - for (int i=0;i<contact_count;i++) { + for (int i = 0; i < contact_count; i++) { - Contact& c = contacts[i]; + Contact &c = contacts[i]; - bool erase=false; - if (c.reused==false) { + bool erase = false; + if (c.reused == false) { //was left behind in previous frame - erase=true; + erase = true; } else { - c.reused=false; + c.reused = false; Vector2 global_A = A->get_transform().basis_xform(c.local_A); - Vector2 global_B = B->get_transform().basis_xform(c.local_B)+offset_B; + Vector2 global_B = B->get_transform().basis_xform(c.local_B) + offset_B; Vector2 axis = global_A - global_B; - real_t depth = axis.dot( c.normal ); - - + real_t depth = axis.dot(c.normal); if (depth < -max_separation || (global_B + c.normal * depth - global_A).length_squared() > max_separation2) { - erase=true; + erase = true; } } if (erase) { // contact no longer needed, remove - - if ((i+1) < contact_count) { + if ((i + 1) < contact_count) { // swap with the last one - SWAP( contacts[i], contacts[ contact_count-1 ] ); - + SWAP(contacts[i], contacts[contact_count - 1]); } i--; @@ -174,21 +165,18 @@ void BodyPair2DSW::_validate_contacts() { } } +bool BodyPair2DSW::_test_ccd(real_t p_step, Body2DSW *p_A, int p_shape_A, const Transform2D &p_xform_A, Body2DSW *p_B, int p_shape_B, const Transform2D &p_xform_B, bool p_swap_result) { -bool BodyPair2DSW::_test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Transform2D& p_xform_A,Body2DSW *p_B, int p_shape_B,const Transform2D& p_xform_B,bool p_swap_result) { - - - - Vector2 motion = p_A->get_linear_velocity()*p_step; + Vector2 motion = p_A->get_linear_velocity() * p_step; real_t mlen = motion.length(); - if (mlen<CMP_EPSILON) + if (mlen < CMP_EPSILON) return false; Vector2 mnormal = motion / mlen; - real_t min,max; - p_A->get_shape(p_shape_A)->project_rangev(mnormal,p_xform_A,min,max); - bool fast_object = mlen > (max-min)*0.3; //going too fast in that direction + real_t min, max; + p_A->get_shape(p_shape_A)->project_rangev(mnormal, p_xform_A, min, max); + bool fast_object = mlen > (max - min) * 0.3; //going too fast in that direction if (!fast_object) { //did it move enough in this direction to even attempt raycast? let's say it should move more than 1/3 the size of the object in that axis return false; @@ -198,22 +186,21 @@ bool BodyPair2DSW::_test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Tr //support is the worst case collision point, so real collision happened before int a; Vector2 s[2]; - p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform(mnormal).normalized(),s,a); + p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform(mnormal).normalized(), s, a); Vector2 from = p_xform_A.xform(s[0]); Vector2 to = from + motion; Transform2D from_inv = p_xform_B.affine_inverse(); - Vector2 local_from = from_inv.xform(from-mnormal*mlen*0.1); //start from a little inside the bounding box + Vector2 local_from = from_inv.xform(from - mnormal * mlen * 0.1); //start from a little inside the bounding box Vector2 local_to = from_inv.xform(to); - Vector2 rpos,rnorm; - if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from,local_to,rpos,rnorm)) + Vector2 rpos, rnorm; + if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm)) return false; //ray hit something - Vector2 hitpos = p_xform_B.xform(rpos); Vector2 contact_A = to; @@ -222,20 +209,18 @@ bool BodyPair2DSW::_test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Tr //create a contact if (p_swap_result) - _contact_added_callback(contact_B,contact_A); + _contact_added_callback(contact_B, contact_A); else - _contact_added_callback(contact_A,contact_B); - + _contact_added_callback(contact_A, contact_B); return true; } bool BodyPair2DSW::setup(real_t p_step) { - //cannot collide - if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported()==0 && B->get_max_contacts_reported()==0)) { - collided=false; + if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported() == 0 && B->get_max_contacts_reported() == 0)) { + collided = false; return false; } @@ -249,44 +234,43 @@ bool BodyPair2DSW::setup(real_t p_step) { Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A); Transform2D xform_Bu = B->get_transform(); - xform_Bu.elements[2]-=A->get_transform().get_origin(); + xform_Bu.elements[2] -= A->get_transform().get_origin(); Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B); - Shape2DSW *shape_A_ptr=A->get_shape(shape_A); - Shape2DSW *shape_B_ptr=B->get_shape(shape_B); + Shape2DSW *shape_A_ptr = A->get_shape(shape_A); + Shape2DSW *shape_B_ptr = B->get_shape(shape_B); - Vector2 motion_A,motion_B; + Vector2 motion_A, motion_B; - if (A->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_SHAPE) { - motion_A=A->get_motion(); + if (A->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_SHAPE) { + motion_A = A->get_motion(); } - if (B->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_SHAPE) { - motion_B=B->get_motion(); + if (B->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_SHAPE) { + motion_B = B->get_motion(); } //faster to set than to check.. //bool prev_collided=collided; - collided = CollisionSolver2DSW::solve(shape_A_ptr,xform_A,motion_A,shape_B_ptr,xform_B,motion_B,_add_contact,this,&sep_axis); + collided = CollisionSolver2DSW::solve(shape_A_ptr, xform_A, motion_A, shape_B_ptr, xform_B, motion_B, _add_contact, this, &sep_axis); if (!collided) { //test ccd (currently just a raycast) - if (A->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_RAY && A->get_mode()>Physics2DServer::BODY_MODE_KINEMATIC) { - if (_test_ccd(p_step,A,shape_A,xform_A,B,shape_B,xform_B)) - collided=true; + if (A->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_RAY && A->get_mode() > Physics2DServer::BODY_MODE_KINEMATIC) { + if (_test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B)) + collided = true; } - if (B->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_RAY && B->get_mode()>Physics2DServer::BODY_MODE_KINEMATIC) { - if (_test_ccd(p_step,B,shape_B,xform_B,A,shape_A,xform_A,true)) - collided=true; + if (B->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_RAY && B->get_mode() > Physics2DServer::BODY_MODE_KINEMATIC) { + if (_test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A, true)) + collided = true; } if (!collided) { - oneway_disabled=false; + oneway_disabled = false; return false; } - } if (oneway_disabled) @@ -297,45 +281,45 @@ bool BodyPair2DSW::setup(real_t p_step) { if (A->is_using_one_way_collision()) { Vector2 direction = A->get_one_way_collision_direction(); - bool valid=false; - if (B->get_linear_velocity().dot(direction)>=0){ - for(int i=0;i<contact_count;i++) { - Contact& c = contacts[i]; + bool valid = false; + if (B->get_linear_velocity().dot(direction) >= 0) { + for (int i = 0; i < contact_count; i++) { + Contact &c = contacts[i]; if (!c.reused) continue; - if (c.normal.dot(direction)<0) + if (c.normal.dot(direction) < 0) continue; - valid=true; + valid = true; break; } } if (!valid) { - collided=false; - oneway_disabled=true; + collided = false; + oneway_disabled = true; return false; } } if (B->is_using_one_way_collision()) { Vector2 direction = B->get_one_way_collision_direction(); - bool valid=false; - if (A->get_linear_velocity().dot(direction)>=0){ - for(int i=0;i<contact_count;i++) { - Contact& c = contacts[i]; + bool valid = false; + if (A->get_linear_velocity().dot(direction) >= 0) { + for (int i = 0; i < contact_count; i++) { + Contact &c = contacts[i]; if (!c.reused) continue; - if (c.normal.dot(direction)<0) + if (c.normal.dot(direction) < 0) continue; - valid=true; + valid = true; break; } } if (!valid) { - collided=false; - oneway_disabled=true; + collided = false; + oneway_disabled = true; return false; } } @@ -346,72 +330,69 @@ bool BodyPair2DSW::setup(real_t p_step) { real_t bias = 0.3; if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) { - if (shape_A_ptr->get_custom_bias()==0) - bias=shape_B_ptr->get_custom_bias(); - else if (shape_B_ptr->get_custom_bias()==0) - bias=shape_A_ptr->get_custom_bias(); + if (shape_A_ptr->get_custom_bias() == 0) + bias = shape_B_ptr->get_custom_bias(); + else if (shape_B_ptr->get_custom_bias() == 0) + bias = shape_A_ptr->get_custom_bias(); else - bias=(shape_B_ptr->get_custom_bias()+shape_A_ptr->get_custom_bias())*0.5; + bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5; } + cc = 0; - cc=0; - - - real_t inv_dt = 1.0/p_step; + real_t inv_dt = 1.0 / p_step; - bool do_process=false; + bool do_process = false; for (int i = 0; i < contact_count; i++) { - Contact& c = contacts[i]; + Contact &c = contacts[i]; Vector2 global_A = xform_Au.xform(c.local_A); Vector2 global_B = xform_Bu.xform(c.local_B); real_t depth = c.normal.dot(global_A - global_B); - if (depth<=0 || !c.reused) { - c.active=false; + if (depth <= 0 || !c.reused) { + c.active = false; continue; } - c.active=true; + c.active = true; #ifdef DEBUG_ENABLED if (space->is_debugging_contacts()) { - space->add_debug_contact(global_A+offset_A); - space->add_debug_contact(global_B+offset_A); + space->add_debug_contact(global_A + offset_A); + space->add_debug_contact(global_B + offset_A); } #endif int gather_A = A->can_report_contacts(); int gather_B = B->can_report_contacts(); c.rA = global_A; - c.rB = global_B-offset_B; + c.rB = global_B - offset_B; if (gather_A | gather_B) { //Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x ); - global_A+=offset_A; - global_B+=offset_A; + global_A += offset_A; + global_B += offset_A; if (gather_A) { - Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x ); - A->add_contact(global_A,-c.normal,depth,shape_A,global_B,shape_B,B->get_instance_id(),B->get_self(),crB+B->get_linear_velocity()); + Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x); + A->add_contact(global_A, -c.normal, depth, shape_A, global_B, shape_B, B->get_instance_id(), B->get_self(), crB + B->get_linear_velocity()); } if (gather_B) { - Vector2 crA( -A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x ); - B->add_contact(global_B,c.normal,depth,shape_B,global_A,shape_A,A->get_instance_id(),A->get_self(),crA+A->get_linear_velocity()); + Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x); + B->add_contact(global_B, c.normal, depth, shape_B, global_A, shape_A, A->get_instance_id(), A->get_self(), crA + A->get_linear_velocity()); } } - if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC)) { - c.active=false; - collided=false; + if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC)) { + c.active = false; + collided = false; continue; - } // Precompute normal mass, tangent mass, and bias. @@ -426,39 +407,33 @@ bool BodyPair2DSW::setup(real_t p_step) { real_t rtB = c.rB.dot(tangent); real_t kTangent = A->get_inv_mass() + B->get_inv_mass(); kTangent += A->get_inv_inertia() * (c.rA.dot(c.rA) - rtA * rtA) + B->get_inv_inertia() * (c.rB.dot(c.rB) - rtB * rtB); - c.mass_tangent = 1.0f / kTangent; - - + c.mass_tangent = 1.0f / kTangent; c.bias = -bias * inv_dt * MIN(0.0f, -depth + max_penetration); - c.depth=depth; - //c.acc_bias_impulse=0; - + c.depth = depth; +//c.acc_bias_impulse=0; #ifdef ACCUMULATE_IMPULSES { // Apply normal + friction impulse Vector2 P = c.acc_normal_impulse * c.normal + c.acc_tangent_impulse * tangent; - - A->apply_impulse(c.rA,-P); + A->apply_impulse(c.rA, -P); B->apply_impulse(c.rB, P); } #endif - - c.bounce=MAX(A->get_bounce(),B->get_bounce()); + c.bounce = MAX(A->get_bounce(), B->get_bounce()); if (c.bounce) { - Vector2 crA( -A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x ); - Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x ); + Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x); + Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x); Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA; c.bounce = c.bounce * dv.dot(c.normal); } - do_process=true; - + do_process = true; } return do_process; @@ -471,81 +446,71 @@ void BodyPair2DSW::solve(real_t p_step) { for (int i = 0; i < contact_count; ++i) { - Contact& c = contacts[i]; + Contact &c = contacts[i]; cc++; if (!c.active) continue; - // Relative velocity at contact - Vector2 crA( -A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x ); - Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x ); + Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x); + Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x); Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA; - Vector2 crbA( -A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x ); - Vector2 crbB( -B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x ); + Vector2 crbA(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x); + Vector2 crbB(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x); Vector2 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA; - real_t vn = dv.dot(c.normal); real_t vbn = dbv.dot(c.normal); Vector2 tangent = c.normal.tangent(); real_t vt = dv.dot(tangent); - - real_t jbn = (c.bias - vbn)*c.mass_normal; + real_t jbn = (c.bias - vbn) * c.mass_normal; real_t jbnOld = c.acc_bias_impulse; c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f); Vector2 jb = c.normal * (c.acc_bias_impulse - jbnOld); - A->apply_bias_impulse(c.rA,-jb); + A->apply_bias_impulse(c.rA, -jb); B->apply_bias_impulse(c.rB, jb); - real_t jn = -(c.bounce + vn)*c.mass_normal; + real_t jn = -(c.bounce + vn) * c.mass_normal; real_t jnOld = c.acc_normal_impulse; c.acc_normal_impulse = MAX(jnOld + jn, 0.0f); - real_t friction = A->get_friction() * B->get_friction(); - real_t jtMax = friction*c.acc_normal_impulse; - real_t jt = -vt*c.mass_tangent; + real_t jtMax = friction * c.acc_normal_impulse; + real_t jt = -vt * c.mass_tangent; real_t jtOld = c.acc_tangent_impulse; c.acc_tangent_impulse = CLAMP(jtOld + jt, -jtMax, jtMax); - Vector2 j =c.normal * (c.acc_normal_impulse - jnOld) + tangent * ( c.acc_tangent_impulse - jtOld ); + Vector2 j = c.normal * (c.acc_normal_impulse - jnOld) + tangent * (c.acc_tangent_impulse - jtOld); - A->apply_impulse(c.rA,-j); + A->apply_impulse(c.rA, -j); B->apply_impulse(c.rB, j); - - } } - -BodyPair2DSW::BodyPair2DSW(Body2DSW *p_A, int p_shape_A,Body2DSW *p_B, int p_shape_B) : Constraint2DSW(_arr,2) { - - A=p_A; - B=p_B; - shape_A=p_shape_A; - shape_B=p_shape_B; - space=A->get_space(); - A->add_constraint(this,0); - B->add_constraint(this,1); - contact_count=0; - collided=false; - oneway_disabled=false; - +BodyPair2DSW::BodyPair2DSW(Body2DSW *p_A, int p_shape_A, Body2DSW *p_B, int p_shape_B) + : Constraint2DSW(_arr, 2) { + + A = p_A; + B = p_B; + shape_A = p_shape_A; + shape_B = p_shape_B; + space = A->get_space(); + A->add_constraint(this, 0); + B->add_constraint(this, 1); + contact_count = 0; + collided = false; + oneway_disabled = false; } - BodyPair2DSW::~BodyPair2DSW() { - A->remove_constraint(this); B->remove_constraint(this); - } diff --git a/servers/physics_2d/body_pair_2d_sw.h b/servers/physics_2d/body_pair_2d_sw.h index 7a4771782a..023c182c31 100644 --- a/servers/physics_2d/body_pair_2d_sw.h +++ b/servers/physics_2d/body_pair_2d_sw.h @@ -35,7 +35,7 @@ class BodyPair2DSW : public Constraint2DSW { enum { - MAX_CONTACTS=2 + MAX_CONTACTS = 2 }; union { struct { @@ -56,18 +56,17 @@ class BodyPair2DSW : public Constraint2DSW { Vector2 position; Vector2 normal; Vector2 local_A, local_B; - real_t acc_normal_impulse; // accumulated normal impulse (Pn) - real_t acc_tangent_impulse; // accumulated tangent impulse (Pt) - real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb) + real_t acc_normal_impulse; // accumulated normal impulse (Pn) + real_t acc_tangent_impulse; // accumulated tangent impulse (Pt) + real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb) real_t mass_normal, mass_tangent; real_t bias; real_t depth; bool active; - Vector2 rA,rB; + Vector2 rA, rB; bool reused; real_t bounce; - }; Vector2 offset_B; //use local A coordinates to avoid numerical issues on collision detection @@ -79,20 +78,17 @@ class BodyPair2DSW : public Constraint2DSW { bool oneway_disabled; int cc; - - bool _test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Transform2D& p_xform_A,Body2DSW *p_B, int p_shape_B,const Transform2D& p_xform_B,bool p_swap_result=false); + bool _test_ccd(real_t p_step, Body2DSW *p_A, int p_shape_A, const Transform2D &p_xform_A, Body2DSW *p_B, int p_shape_B, const Transform2D &p_xform_B, bool p_swap_result = false); void _validate_contacts(); - static void _add_contact(const Vector2& p_point_A,const Vector2& p_point_B,void *p_self); - _FORCE_INLINE_ void _contact_added_callback(const Vector2& p_point_A,const Vector2& p_point_B); + static void _add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self); + _FORCE_INLINE_ void _contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B); public: - bool setup(real_t p_step); void solve(real_t p_step); - BodyPair2DSW(Body2DSW *p_A, int p_shape_A,Body2DSW *p_B, int p_shape_B); + BodyPair2DSW(Body2DSW *p_A, int p_shape_A, Body2DSW *p_B, int p_shape_B); ~BodyPair2DSW(); - }; #endif // BODY_PAIR_2D_SW_H diff --git a/servers/physics_2d/broad_phase_2d_basic.cpp b/servers/physics_2d/broad_phase_2d_basic.cpp index e1f6f4f92b..c282c0364e 100644 --- a/servers/physics_2d/broad_phase_2d_basic.cpp +++ b/servers/physics_2d/broad_phase_2d_basic.cpp @@ -30,94 +30,87 @@ BroadPhase2DBasic::ID BroadPhase2DBasic::create(CollisionObject2DSW *p_object_, int p_subindex) { - current++; Element e; - e.owner=p_object_; - e._static=false; - e.subindex=p_subindex; + e.owner = p_object_; + e._static = false; + e.subindex = p_subindex; - element_map[current]=e; + element_map[current] = e; return current; } -void BroadPhase2DBasic::move(ID p_id, const Rect2& p_aabb) { +void BroadPhase2DBasic::move(ID p_id, const Rect2 &p_aabb) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - E->get().aabb=p_aabb; - + E->get().aabb = p_aabb; } void BroadPhase2DBasic::set_static(ID p_id, bool p_static) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - E->get()._static=p_static; - + E->get()._static = p_static; } void BroadPhase2DBasic::remove(ID p_id) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); element_map.erase(E); - } CollisionObject2DSW *BroadPhase2DBasic::get_object(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,NULL); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, NULL); return E->get().owner; - } bool BroadPhase2DBasic::is_static(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,false); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, false); return E->get()._static; - } int BroadPhase2DBasic::get_subindex(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,-1); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, -1); return E->get().subindex; } -int BroadPhase2DBasic::cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) { +int BroadPhase2DBasic::cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) { - int rc=0; + int rc = 0; - for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) { + for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) { - const Rect2 aabb=E->get().aabb; - if (aabb.intersects_segment(p_from,p_to)) { + const Rect2 aabb = E->get().aabb; + if (aabb.intersects_segment(p_from, p_to)) { - p_results[rc]=E->get().owner; - p_result_indices[rc]=E->get().subindex; + p_results[rc] = E->get().owner; + p_result_indices[rc] = E->get().subindex; rc++; - if (rc>=p_max_results) + if (rc >= p_max_results) break; } } return rc; - } -int BroadPhase2DBasic::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) { +int BroadPhase2DBasic::cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) { - int rc=0; + int rc = 0; - for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) { + for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) { - const Rect2 aabb=E->get().aabb; + const Rect2 aabb = E->get().aabb; if (aabb.intersects(p_aabb)) { - p_results[rc]=E->get().owner; - p_result_indices[rc]=E->get().subindex; + p_results[rc] = E->get().owner; + p_result_indices[rc] = E->get().subindex; rc++; - if (rc>=p_max_results) + if (rc >= p_max_results) break; } } @@ -125,68 +118,63 @@ int BroadPhase2DBasic::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_res return rc; } -void BroadPhase2DBasic::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) { - - pair_userdata=p_userdata; - pair_callback=p_pair_callback; +void BroadPhase2DBasic::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) { + pair_userdata = p_userdata; + pair_callback = p_pair_callback; } -void BroadPhase2DBasic::set_unpair_callback(UnpairCallback p_pair_callback,void *p_userdata) { - - unpair_userdata=p_userdata; - unpair_callback=p_pair_callback; +void BroadPhase2DBasic::set_unpair_callback(UnpairCallback p_pair_callback, void *p_userdata) { + unpair_userdata = p_userdata; + unpair_callback = p_pair_callback; } void BroadPhase2DBasic::update() { // recompute pairs - for(Map<ID,Element>::Element *I=element_map.front();I;I=I->next()) { + for (Map<ID, Element>::Element *I = element_map.front(); I; I = I->next()) { - for(Map<ID,Element>::Element *J=I->next();J;J=J->next()) { + for (Map<ID, Element>::Element *J = I->next(); J; J = J->next()) { - Element *elem_A=&I->get(); - Element *elem_B=&J->get(); + Element *elem_A = &I->get(); + Element *elem_B = &J->get(); if (elem_A->owner == elem_B->owner) continue; + bool pair_ok = elem_A->aabb.intersects(elem_B->aabb) && (!elem_A->_static || !elem_B->_static); - bool pair_ok=elem_A->aabb.intersects( elem_B->aabb ) && (!elem_A->_static || !elem_B->_static ); + PairKey key(I->key(), J->key()); - PairKey key(I->key(),J->key()); - - Map<PairKey,void*>::Element *E=pair_map.find(key); + Map<PairKey, void *>::Element *E = pair_map.find(key); if (!pair_ok && E) { if (unpair_callback) - unpair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,E->get(),unpair_userdata); + unpair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, E->get(), unpair_userdata); pair_map.erase(key); } if (pair_ok && !E) { - void *data=NULL; + void *data = NULL; if (pair_callback) - data=pair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,unpair_userdata); - pair_map.insert(key,data); + data = pair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, unpair_userdata); + pair_map.insert(key, data); } } } - } BroadPhase2DSW *BroadPhase2DBasic::_create() { - return memnew( BroadPhase2DBasic ); + return memnew(BroadPhase2DBasic); } BroadPhase2DBasic::BroadPhase2DBasic() { - current=1; - unpair_callback=NULL; - unpair_userdata=NULL; - pair_callback=NULL; - pair_userdata=NULL; - + current = 1; + unpair_callback = NULL; + unpair_userdata = NULL; + pair_callback = NULL; + pair_userdata = NULL; } diff --git a/servers/physics_2d/broad_phase_2d_basic.h b/servers/physics_2d/broad_phase_2d_basic.h index 82e91118ce..7c5d799f9a 100644 --- a/servers/physics_2d/broad_phase_2d_basic.h +++ b/servers/physics_2d/broad_phase_2d_basic.h @@ -29,8 +29,8 @@ #ifndef BROAD_PHASE_2D_BASIC_H #define BROAD_PHASE_2D_BASIC_H -#include "space_2d_sw.h" #include "map.h" +#include "space_2d_sw.h" class BroadPhase2DBasic : public BroadPhase2DSW { struct Element { @@ -41,8 +41,7 @@ class BroadPhase2DBasic : public BroadPhase2DSW { int subindex; }; - - Map<ID,Element> element_map; + Map<ID, Element> element_map; ID current; @@ -56,17 +55,23 @@ class BroadPhase2DBasic : public BroadPhase2DSW { uint64_t key; }; - _FORCE_INLINE_ bool operator<(const PairKey& p_key) const { + _FORCE_INLINE_ bool operator<(const PairKey &p_key) const { return key < p_key.key; } - PairKey() { key=0; } - PairKey(ID p_a, ID p_b) { if (p_a>p_b) { a=p_b; b=p_a; } else { a=p_a; b=p_b; }} - + PairKey() { key = 0; } + PairKey(ID p_a, ID p_b) { + if (p_a > p_b) { + a = p_b; + b = p_a; + } else { + a = p_a; + b = p_b; + } + } }; - Map<PairKey,void*> pair_map; - + Map<PairKey, void *> pair_map; PairCallback pair_callback; void *pair_userdata; @@ -74,10 +79,9 @@ class BroadPhase2DBasic : public BroadPhase2DSW { void *unpair_userdata; public: - // 0 is an invalid ID - virtual ID create(CollisionObject2DSW *p_object_, int p_subindex=0); - virtual void move(ID p_id, const Rect2& p_aabb); + virtual ID create(CollisionObject2DSW *p_object_, int p_subindex = 0); + virtual void move(ID p_id, const Rect2 &p_aabb); virtual void set_static(ID p_id, bool p_static); virtual void remove(ID p_id); @@ -85,11 +89,11 @@ public: virtual bool is_static(ID p_id) const; virtual int get_subindex(ID p_id) const; - virtual int cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL); - virtual int cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL); + virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL); + virtual int cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL); - virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata); - virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata); + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata); + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata); virtual void update(); diff --git a/servers/physics_2d/broad_phase_2d_hash_grid.cpp b/servers/physics_2d/broad_phase_2d_hash_grid.cpp index 06eead64cd..74c01e1220 100644 --- a/servers/physics_2d/broad_phase_2d_hash_grid.cpp +++ b/servers/physics_2d/broad_phase_2d_hash_grid.cpp @@ -31,110 +31,100 @@ #define LARGE_ELEMENT_FI 1.01239812 -void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element* p_with) { +void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element *p_with) { - Map<Element*,PairData*>::Element *E=p_elem->paired.find(p_with); + Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with); ERR_FAIL_COND(p_elem->_static && p_with->_static); if (!E) { - PairData *pd = memnew( PairData ); - p_elem->paired[p_with]=pd; - p_with->paired[p_elem]=pd; + PairData *pd = memnew(PairData); + p_elem->paired[p_with] = pd; + p_with->paired[p_elem] = pd; } else { E->get()->rc++; } - } -void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element* p_with) { +void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element *p_with) { - Map<Element*,PairData*>::Element *E=p_elem->paired.find(p_with); + Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with); ERR_FAIL_COND(!E); //this should really be paired.. E->get()->rc--; - if (E->get()->rc==0) { + if (E->get()->rc == 0) { if (E->get()->colliding) { //uncollide if (unpair_callback) { - unpair_callback(p_elem->owner,p_elem->subindex,p_with->owner,p_with->subindex,E->get()->ud,unpair_userdata); + unpair_callback(p_elem->owner, p_elem->subindex, p_with->owner, p_with->subindex, E->get()->ud, unpair_userdata); } - - } memdelete(E->get()); p_elem->paired.erase(E); p_with->paired.erase(p_elem); } - - } void BroadPhase2DHashGrid::_check_motion(Element *p_elem) { - for (Map<Element*,PairData*>::Element *E=p_elem->paired.front();E;E=E->next()) { + for (Map<Element *, PairData *>::Element *E = p_elem->paired.front(); E; E = E->next()) { - bool pairing = p_elem->aabb.intersects( E->key()->aabb ); + bool pairing = p_elem->aabb.intersects(E->key()->aabb); - if (pairing!=E->get()->colliding) { + if (pairing != E->get()->colliding) { if (pairing) { if (pair_callback) { - E->get()->ud=pair_callback(p_elem->owner,p_elem->subindex,E->key()->owner,E->key()->subindex,pair_userdata); + E->get()->ud = pair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, pair_userdata); } } else { if (unpair_callback) { - unpair_callback(p_elem->owner,p_elem->subindex,E->key()->owner,E->key()->subindex,E->get()->ud,unpair_userdata); + unpair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, E->get()->ud, unpair_userdata); } - } - E->get()->colliding=pairing; + E->get()->colliding = pairing; } } } -void BroadPhase2DHashGrid::_enter_grid( Element* p_elem, const Rect2& p_rect,bool p_static) { - - +void BroadPhase2DHashGrid::_enter_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) { - Vector2 sz = (p_rect.size/cell_size*LARGE_ELEMENT_FI); //use magic number to avoid floating point issues - if (sz.width*sz.height > large_object_min_surface) { + Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI); //use magic number to avoid floating point issues + if (sz.width * sz.height > large_object_min_surface) { //large object, do not use grid, must check against all elements - for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) { - if (E->key()==p_elem->self) + for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) { + if (E->key() == p_elem->self) continue; // do not pair against itself if (E->get().owner == p_elem->owner) continue; if (E->get()._static && p_static) continue; - _pair_attempt(p_elem,&E->get()); + _pair_attempt(p_elem, &E->get()); } - large_elements[p_elem].inc(); return; } - Point2i from = (p_rect.pos/cell_size).floor(); - Point2i to = ((p_rect.pos+p_rect.size)/cell_size).floor(); - - for(int i=from.x;i<=to.x;i++) { + Point2i from = (p_rect.pos / cell_size).floor(); + Point2i to = ((p_rect.pos + p_rect.size) / cell_size).floor(); + for (int i = from.x; i <= to.x; i++) { - for(int j=from.y;j<=to.y;j++) { + for (int j = from.y; j <= to.y; j++) { PosKey pk; - pk.x=i; - pk.y=j; + pk.x = i; + pk.y = j; uint32_t idx = pk.hash() % hash_table_size; PosBin *pb = hash_table[idx]; @@ -145,102 +135,94 @@ void BroadPhase2DHashGrid::_enter_grid( Element* p_elem, const Rect2& p_rect,boo break; } - pb=pb->next; + pb = pb->next; } - - bool entered=false; + bool entered = false; if (!pb) { //does not exist, create! - pb = memnew( PosBin ); - pb->key=pk; - pb->next=hash_table[idx]; - hash_table[idx]=pb; + pb = memnew(PosBin); + pb->key = pk; + pb->next = hash_table[idx]; + hash_table[idx] = pb; } - - if (p_static) { - if (pb->static_object_set[p_elem].inc()==1) { - entered=true; + if (pb->static_object_set[p_elem].inc() == 1) { + entered = true; } } else { - if (pb->object_set[p_elem].inc()==1) { + if (pb->object_set[p_elem].inc() == 1) { - entered=true; + entered = true; } } if (entered) { - for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) { - if (E->key()->owner==p_elem->owner) + if (E->key()->owner == p_elem->owner) continue; - _pair_attempt(p_elem,E->key()); + _pair_attempt(p_elem, E->key()); } if (!p_static) { - for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) { - if (E->key()->owner==p_elem->owner) + if (E->key()->owner == p_elem->owner) continue; - _pair_attempt(p_elem,E->key()); + _pair_attempt(p_elem, E->key()); } } } - } - } //pair separatedly with large elements - for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) { - if (E->key()==p_elem) + if (E->key() == p_elem) continue; // do not pair against itself if (E->key()->owner == p_elem->owner) continue; if (E->key()->_static && p_static) continue; - _pair_attempt(E->key(),p_elem); + _pair_attempt(E->key(), p_elem); } - } +void BroadPhase2DHashGrid::_exit_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) { -void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool p_static) { - - Vector2 sz = (p_rect.size/cell_size*LARGE_ELEMENT_FI); - if (sz.width*sz.height > large_object_min_surface) { + Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI); + if (sz.width * sz.height > large_object_min_surface) { //unpair all elements, instead of checking all, just check what is already paired, so we at least save from checking static vs static - for (Map<Element*,PairData*>::Element *E=p_elem->paired.front();E;E=E->next()) { + for (Map<Element *, PairData *>::Element *E = p_elem->paired.front(); E; E = E->next()) { - _unpair_attempt(p_elem,E->key()); + _unpair_attempt(p_elem, E->key()); } - if (large_elements[p_elem].dec()==0) { + if (large_elements[p_elem].dec() == 0) { large_elements.erase(p_elem); } return; } + Point2i from = (p_rect.pos / cell_size).floor(); + Point2i to = ((p_rect.pos + p_rect.size) / cell_size).floor(); - Point2i from = (p_rect.pos/cell_size).floor(); - Point2i to = ((p_rect.pos+p_rect.size)/cell_size).floor(); - - for(int i=from.x;i<=to.x;i++) { + for (int i = from.x; i <= to.x; i++) { - for(int j=from.y;j<=to.y;j++) { + for (int j = from.y; j <= to.y; j++) { PosKey pk; - pk.x=i; - pk.y=j; + pk.x = i; + pk.y = j; uint32_t idx = pk.hash() % hash_table_size; PosBin *pb = hash_table[idx]; @@ -251,82 +233,75 @@ void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool break; } - pb=pb->next; + pb = pb->next; } ERR_CONTINUE(!pb); //should exist!! - bool exited=false; - + bool exited = false; if (p_static) { - if (pb->static_object_set[p_elem].dec()==0) { + if (pb->static_object_set[p_elem].dec() == 0) { pb->static_object_set.erase(p_elem); - exited=true; - + exited = true; } } else { - if (pb->object_set[p_elem].dec()==0) { + if (pb->object_set[p_elem].dec() == 0) { pb->object_set.erase(p_elem); - exited=true; - + exited = true; } } if (exited) { - for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) { - if (E->key()->owner==p_elem->owner) + if (E->key()->owner == p_elem->owner) continue; - _unpair_attempt(p_elem,E->key()); - + _unpair_attempt(p_elem, E->key()); } if (!p_static) { - for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) { - if (E->key()->owner==p_elem->owner) + if (E->key()->owner == p_elem->owner) continue; - _unpair_attempt(p_elem,E->key()); + _unpair_attempt(p_elem, E->key()); } } } if (pb->object_set.empty() && pb->static_object_set.empty()) { - if (hash_table[idx]==pb) { - hash_table[idx]=pb->next; + if (hash_table[idx] == pb) { + hash_table[idx] = pb->next; } else { PosBin *px = hash_table[idx]; while (px) { - if (px->next==pb) { - px->next=pb->next; + if (px->next == pb) { + px->next = pb->next; break; } - px=px->next; + px = px->next; } ERR_CONTINUE(!px); } memdelete(pb); - } } - } - - for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) { - if (E->key()==p_elem) + for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) { + if (E->key() == p_elem) continue; // do not pair against itself if (E->key()->owner == p_elem->owner) continue; @@ -334,121 +309,109 @@ void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool continue; //unpair from large elements - _unpair_attempt(p_elem,E->key()); + _unpair_attempt(p_elem, E->key()); } - - } - BroadPhase2DHashGrid::ID BroadPhase2DHashGrid::create(CollisionObject2DSW *p_object, int p_subindex) { current++; Element e; - e.owner=p_object; - e._static=false; - e.subindex=p_subindex; - e.self=current; - e.pass=0; + e.owner = p_object; + e._static = false; + e.subindex = p_subindex; + e.self = current; + e.pass = 0; - element_map[current]=e; + element_map[current] = e; return current; - } -void BroadPhase2DHashGrid::move(ID p_id, const Rect2& p_aabb) { - +void BroadPhase2DHashGrid::move(ID p_id, const Rect2 &p_aabb) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - Element &e=E->get(); + Element &e = E->get(); - if (p_aabb==e.aabb) + if (p_aabb == e.aabb) return; + if (p_aabb != Rect2()) { - if (p_aabb!=Rect2()) { - - _enter_grid(&e,p_aabb,e._static); + _enter_grid(&e, p_aabb, e._static); } - if (e.aabb!=Rect2()) { + if (e.aabb != Rect2()) { - _exit_grid(&e,e.aabb,e._static); + _exit_grid(&e, e.aabb, e._static); } - e.aabb=p_aabb; + e.aabb = p_aabb; _check_motion(&e); - e.aabb=p_aabb; - + e.aabb = p_aabb; } void BroadPhase2DHashGrid::set_static(ID p_id, bool p_static) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - Element &e=E->get(); + Element &e = E->get(); - if (e._static==p_static) + if (e._static == p_static) return; - if (e.aabb!=Rect2()) - _exit_grid(&e,e.aabb,e._static); + if (e.aabb != Rect2()) + _exit_grid(&e, e.aabb, e._static); - e._static=p_static; + e._static = p_static; - if (e.aabb!=Rect2()) { - _enter_grid(&e,e.aabb,e._static); + if (e.aabb != Rect2()) { + _enter_grid(&e, e.aabb, e._static); _check_motion(&e); } - } void BroadPhase2DHashGrid::remove(ID p_id) { - Map<ID,Element>::Element *E=element_map.find(p_id); + Map<ID, Element>::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); - Element &e=E->get(); + Element &e = E->get(); - if (e.aabb!=Rect2()) - _exit_grid(&e,e.aabb,e._static); + if (e.aabb != Rect2()) + _exit_grid(&e, e.aabb, e._static); element_map.erase(p_id); - } CollisionObject2DSW *BroadPhase2DHashGrid::get_object(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,NULL); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, NULL); return E->get().owner; - } bool BroadPhase2DHashGrid::is_static(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,false); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, false); return E->get()._static; - } int BroadPhase2DHashGrid::get_subindex(ID p_id) const { - const Map<ID,Element>::Element *E=element_map.find(p_id); - ERR_FAIL_COND_V(!E,-1); + const Map<ID, Element>::Element *E = element_map.find(p_id); + ERR_FAIL_COND_V(!E, -1); return E->get().subindex; } -template<bool use_aabb,bool use_segment> -void BroadPhase2DHashGrid::_cull(const Point2i p_cell,const Rect2& p_aabb,const Point2& p_from, const Point2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices,int &index) { - +template <bool use_aabb, bool use_segment> +void BroadPhase2DHashGrid::_cull(const Point2i p_cell, const Rect2 &p_aabb, const Point2 &p_from, const Point2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices, int &index) { PosKey pk; - pk.x=p_cell.x; - pk.y=p_cell.y; + pk.x = p_cell.x; + pk.y = p_cell.y; uint32_t idx = pk.hash() % hash_table_size; PosBin *pb = hash_table[idx]; @@ -459,190 +422,177 @@ void BroadPhase2DHashGrid::_cull(const Point2i p_cell,const Rect2& p_aabb,const break; } - pb=pb->next; + pb = pb->next; } if (!pb) return; + for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) { - - for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) { - - - if (index>=p_max_results) + if (index >= p_max_results) break; - if (E->key()->pass==pass) + if (E->key()->pass == pass) continue; - E->key()->pass=pass; + E->key()->pass = pass; if (use_aabb && !p_aabb.intersects(E->key()->aabb)) continue; - if (use_segment && !E->key()->aabb.intersects_segment(p_from,p_to)) + if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to)) continue; - p_results[index]=E->key()->owner; - p_result_indices[index]=E->key()->subindex; + p_results[index] = E->key()->owner; + p_result_indices[index] = E->key()->subindex; index++; - - } - for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) { - + for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) { - if (index>=p_max_results) + if (index >= p_max_results) break; - if (E->key()->pass==pass) + if (E->key()->pass == pass) continue; if (use_aabb && !p_aabb.intersects(E->key()->aabb)) { continue; } - if (use_segment && !E->key()->aabb.intersects_segment(p_from,p_to)) + if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to)) continue; - E->key()->pass=pass; - p_results[index]=E->key()->owner; - p_result_indices[index]=E->key()->subindex; + E->key()->pass = pass; + p_results[index] = E->key()->owner; + p_result_indices[index] = E->key()->subindex; index++; - } } -int BroadPhase2DHashGrid::cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) { +int BroadPhase2DHashGrid::cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) { pass++; - Vector2 dir = (p_to-p_from); - if (dir==Vector2()) + Vector2 dir = (p_to - p_from); + if (dir == Vector2()) return 0; //avoid divisions by zero dir.normalize(); - if (dir.x==0.0) - dir.x=0.000001; - if (dir.y==0.0) - dir.y=0.000001; + if (dir.x == 0.0) + dir.x = 0.000001; + if (dir.y == 0.0) + dir.y = 0.000001; Vector2 delta = dir.abs(); - delta.x=cell_size/delta.x; - delta.y=cell_size/delta.y; + delta.x = cell_size / delta.x; + delta.y = cell_size / delta.y; - Point2i pos = (p_from/cell_size).floor(); - Point2i end = (p_to/cell_size).floor(); + Point2i pos = (p_from / cell_size).floor(); + Point2i end = (p_to / cell_size).floor(); - Point2i step = Vector2( SGN(dir.x), SGN(dir.y) ); + Point2i step = Vector2(SGN(dir.x), SGN(dir.y)); Vector2 max; - if (dir.x<0) - max.x= (Math::floor((double)pos.x)*cell_size - p_from.x) / dir.x; + if (dir.x < 0) + max.x = (Math::floor((double)pos.x) * cell_size - p_from.x) / dir.x; else - max.x= (Math::floor((double)pos.x + 1)*cell_size - p_from.x) / dir.x; + max.x = (Math::floor((double)pos.x + 1) * cell_size - p_from.x) / dir.x; - if (dir.y<0) - max.y= (Math::floor((double)pos.y)*cell_size - p_from.y) / dir.y; + if (dir.y < 0) + max.y = (Math::floor((double)pos.y) * cell_size - p_from.y) / dir.y; else - max.y= (Math::floor((double)pos.y + 1)*cell_size - p_from.y) / dir.y; + max.y = (Math::floor((double)pos.y + 1) * cell_size - p_from.y) / dir.y; - int cullcount=0; - _cull<false,true>(pos,Rect2(),p_from,p_to,p_results,p_max_results,p_result_indices,cullcount); + int cullcount = 0; + _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount); - bool reached_x=false; - bool reached_y=false; + bool reached_x = false; + bool reached_y = false; - while(true) { + while (true) { if (max.x < max.y) { - max.x+=delta.x; - pos.x+=step.x; + max.x += delta.x; + pos.x += step.x; } else { - max.y+=delta.y; - pos.y+=step.y; - + max.y += delta.y; + pos.y += step.y; } - if (step.x>0) { - if (pos.x>=end.x) - reached_x=true; - } else if (pos.x<=end.x) { + if (step.x > 0) { + if (pos.x >= end.x) + reached_x = true; + } else if (pos.x <= end.x) { - reached_x=true; + reached_x = true; } - if (step.y>0) { - if (pos.y>=end.y) - reached_y=true; - } else if (pos.y<=end.y) { + if (step.y > 0) { + if (pos.y >= end.y) + reached_y = true; + } else if (pos.y <= end.y) { - reached_y=true; + reached_y = true; } - _cull<false,true>(pos,Rect2(),p_from,p_to,p_results,p_max_results,p_result_indices,cullcount); + _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount); if (reached_x && reached_y) break; - } - for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) { - if (cullcount>=p_max_results) + if (cullcount >= p_max_results) break; - if (E->key()->pass==pass) + if (E->key()->pass == pass) continue; - E->key()->pass=pass; + E->key()->pass = pass; /* if (use_aabb && !p_aabb.intersects(E->key()->aabb)) continue; */ - if (!E->key()->aabb.intersects_segment(p_from,p_to)) + if (!E->key()->aabb.intersects_segment(p_from, p_to)) continue; - p_results[cullcount]=E->key()->owner; - p_result_indices[cullcount]=E->key()->subindex; + p_results[cullcount] = E->key()->owner; + p_result_indices[cullcount] = E->key()->subindex; cullcount++; - - } return cullcount; } - -int BroadPhase2DHashGrid::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) { +int BroadPhase2DHashGrid::cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) { pass++; - Point2i from = (p_aabb.pos/cell_size).floor(); - Point2i to = ((p_aabb.pos+p_aabb.size)/cell_size).floor(); - int cullcount=0; + Point2i from = (p_aabb.pos / cell_size).floor(); + Point2i to = ((p_aabb.pos + p_aabb.size) / cell_size).floor(); + int cullcount = 0; - for(int i=from.x;i<=to.x;i++) { + for (int i = from.x; i <= to.x; i++) { - for(int j=from.y;j<=to.y;j++) { + for (int j = from.y; j <= to.y; j++) { - _cull<true,false>(Point2i(i,j),p_aabb,Point2(),Point2(),p_results,p_max_results,p_result_indices,cullcount); + _cull<true, false>(Point2i(i, j), p_aabb, Point2(), Point2(), p_results, p_max_results, p_result_indices, cullcount); } - } - for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) { + for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) { - if (cullcount>=p_max_results) + if (cullcount >= p_max_results) break; - if (E->key()->pass==pass) + if (E->key()->pass == pass) continue; - E->key()->pass=pass; + E->key()->pass = pass; if (!p_aabb.intersects(E->key()->aabb)) continue; @@ -652,72 +602,61 @@ int BroadPhase2DHashGrid::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_ continue; */ - p_results[cullcount]=E->key()->owner; - p_result_indices[cullcount]=E->key()->subindex; + p_results[cullcount] = E->key()->owner; + p_result_indices[cullcount] = E->key()->subindex; cullcount++; - - } return cullcount; } -void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) { - - pair_callback=p_pair_callback; - pair_userdata=p_userdata; +void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) { + pair_callback = p_pair_callback; + pair_userdata = p_userdata; } -void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata) { - - unpair_callback=p_unpair_callback; - unpair_userdata=p_userdata; +void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) { + unpair_callback = p_unpair_callback; + unpair_userdata = p_userdata; } void BroadPhase2DHashGrid::update() { - - } BroadPhase2DSW *BroadPhase2DHashGrid::_create() { - return memnew( BroadPhase2DHashGrid ); + return memnew(BroadPhase2DHashGrid); } - BroadPhase2DHashGrid::BroadPhase2DHashGrid() { - hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size",4096); + hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size", 4096); hash_table_size = Math::larger_prime(hash_table_size); - hash_table = memnew_arr( PosBin*, hash_table_size); + hash_table = memnew_arr(PosBin *, hash_table_size); - cell_size = GLOBAL_DEF("physics/2d/cell_size",128); - large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_treshold_in_cells",512); + cell_size = GLOBAL_DEF("physics/2d/cell_size", 128); + large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_treshold_in_cells", 512); - for(int i=0;i<hash_table_size;i++) - hash_table[i]=NULL; - pass=1; + for (int i = 0; i < hash_table_size; i++) + hash_table[i] = NULL; + pass = 1; - current=0; + current = 0; } BroadPhase2DHashGrid::~BroadPhase2DHashGrid() { - for(int i=0;i<hash_table_size;i++) { - while(hash_table[i]) { - PosBin *pb=hash_table[i]; - hash_table[i]=pb->next; + for (int i = 0; i < hash_table_size; i++) { + while (hash_table[i]) { + PosBin *pb = hash_table[i]; + hash_table[i] = pb->next; memdelete(pb); } } - memdelete_arr( hash_table ); - - + memdelete_arr(hash_table); } - - /* 3D version of voxel traversal: public IEnumerable<Point3D> GetCellsOnRay(Ray ray, int maxDepth) diff --git a/servers/physics_2d/broad_phase_2d_hash_grid.h b/servers/physics_2d/broad_phase_2d_hash_grid.h index 857053ccf0..f30f72d6db 100644 --- a/servers/physics_2d/broad_phase_2d_hash_grid.h +++ b/servers/physics_2d/broad_phase_2d_hash_grid.h @@ -34,13 +34,16 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { - struct PairData { bool colliding; int rc; void *ud; - PairData() { colliding=false; rc=1; ud=NULL; } + PairData() { + colliding = false; + rc = 1; + ud = NULL; + } }; struct Element { @@ -51,8 +54,7 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { Rect2 aabb; int subindex; uint64_t pass; - Map<Element*,PairData*> paired; - + Map<Element *, PairData *> paired; }; struct RC { @@ -69,18 +71,17 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { } _FORCE_INLINE_ RC() { - ref=0; + ref = 0; } }; - Map<ID,Element> element_map; - Map<Element*,RC> large_elements; + Map<ID, Element> element_map; + Map<Element *, RC> large_elements; ID current; uint64_t pass; - struct PairKey { union { @@ -91,17 +92,23 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { uint64_t key; }; - _FORCE_INLINE_ bool operator<(const PairKey& p_key) const { + _FORCE_INLINE_ bool operator<(const PairKey &p_key) const { return key < p_key.key; } - PairKey() { key=0; } - PairKey(ID p_a, ID p_b) { if (p_a>p_b) { a=p_b; b=p_a; } else { a=p_a; b=p_b; }} - + PairKey() { key = 0; } + PairKey(ID p_a, ID p_b) { + if (p_a > p_b) { + a = p_b; + b = p_a; + } else { + a = p_a; + b = p_b; + } + } }; - - Map<PairKey,PairData> pair_map; + Map<PairKey, PairData> pair_map; int cell_size; int large_object_min_surface; @@ -111,11 +118,10 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { UnpairCallback unpair_callback; void *unpair_userdata; - void _enter_grid(Element* p_elem, const Rect2& p_rect,bool p_static); - void _exit_grid(Element* p_elem, const Rect2& p_rect,bool p_static); - template<bool use_aabb,bool use_segment> - _FORCE_INLINE_ void _cull(const Point2i p_cell,const Rect2& p_aabb,const Point2& p_from, const Point2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices,int &index); - + void _enter_grid(Element *p_elem, const Rect2 &p_rect, bool p_static); + void _exit_grid(Element *p_elem, const Rect2 &p_rect, bool p_static); + template <bool use_aabb, bool use_segment> + _FORCE_INLINE_ void _cull(const Point2i p_cell, const Rect2 &p_aabb, const Point2 &p_from, const Point2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices, int &index); struct PosKey { @@ -127,9 +133,8 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { uint64_t key; }; - _FORCE_INLINE_ uint32_t hash() const { - uint64_t k=key; + uint64_t k = key; k = (~k) + (k << 18); // k = (k << 18) - k - 1; k = k ^ (k >> 31); k = k * 21; // k = (k + (k << 2)) + (k << 4); @@ -139,36 +144,30 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW { return k; } - bool operator==(const PosKey& p_key) const { return key==p_key.key; } - _FORCE_INLINE_ bool operator<(const PosKey& p_key) const { + bool operator==(const PosKey &p_key) const { return key == p_key.key; } + _FORCE_INLINE_ bool operator<(const PosKey &p_key) const { return key < p_key.key; } - }; - - struct PosBin { PosKey key; - Map<Element*,RC> object_set; - Map<Element*,RC> static_object_set; + Map<Element *, RC> object_set; + Map<Element *, RC> static_object_set; PosBin *next; }; - uint32_t hash_table_size; PosBin **hash_table; - void _pair_attempt(Element *p_elem, Element* p_with); - void _unpair_attempt(Element *p_elem, Element* p_with); + void _pair_attempt(Element *p_elem, Element *p_with); + void _unpair_attempt(Element *p_elem, Element *p_with); void _check_motion(Element *p_elem); - public: - - virtual ID create(CollisionObject2DSW *p_object_, int p_subindex=0); - virtual void move(ID p_id, const Rect2& p_aabb); + virtual ID create(CollisionObject2DSW *p_object_, int p_subindex = 0); + virtual void move(ID p_id, const Rect2 &p_aabb); virtual void set_static(ID p_id, bool p_static); virtual void remove(ID p_id); @@ -176,21 +175,18 @@ public: virtual bool is_static(ID p_id) const; virtual int get_subindex(ID p_id) const; - virtual int cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL); - virtual int cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL); + virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL); + virtual int cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL); - virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata); - virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata); + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata); + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata); virtual void update(); - static BroadPhase2DSW *_create(); BroadPhase2DHashGrid(); ~BroadPhase2DHashGrid(); - - }; #endif // BROAD_PHASE_2D_HASH_GRID_H diff --git a/servers/physics_2d/broad_phase_2d_sw.cpp b/servers/physics_2d/broad_phase_2d_sw.cpp index 4347155c2c..8cde46217b 100644 --- a/servers/physics_2d/broad_phase_2d_sw.cpp +++ b/servers/physics_2d/broad_phase_2d_sw.cpp @@ -28,8 +28,7 @@ /*************************************************************************/ #include "broad_phase_2d_sw.h" -BroadPhase2DSW::CreateFunction BroadPhase2DSW::create_func=NULL; +BroadPhase2DSW::CreateFunction BroadPhase2DSW::create_func = NULL; -BroadPhase2DSW::~BroadPhase2DSW() -{ +BroadPhase2DSW::~BroadPhase2DSW() { } diff --git a/servers/physics_2d/broad_phase_2d_sw.h b/servers/physics_2d/broad_phase_2d_sw.h index b9ec434ae9..a255cc6ba7 100644 --- a/servers/physics_2d/broad_phase_2d_sw.h +++ b/servers/physics_2d/broad_phase_2d_sw.h @@ -29,45 +29,42 @@ #ifndef BROAD_PHASE_2D_SW_H #define BROAD_PHASE_2D_SW_H -#include "math_funcs.h" #include "math_2d.h" +#include "math_funcs.h" class CollisionObject2DSW; - class BroadPhase2DSW { public: - typedef BroadPhase2DSW* (*CreateFunction)(); + typedef BroadPhase2DSW *(*CreateFunction)(); static CreateFunction create_func; typedef uint32_t ID; - - typedef void* (*PairCallback)(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_userdata); - typedef void (*UnpairCallback)(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_data,void *p_userdata); + typedef void *(*PairCallback)(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_userdata); + typedef void (*UnpairCallback)(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_userdata); // 0 is an invalid ID - virtual ID create(CollisionObject2DSW *p_object_, int p_subindex=0)=0; - virtual void move(ID p_id, const Rect2& p_aabb)=0; - virtual void set_static(ID p_id, bool p_static)=0; - virtual void remove(ID p_id)=0; + virtual ID create(CollisionObject2DSW *p_object_, int p_subindex = 0) = 0; + virtual void move(ID p_id, const Rect2 &p_aabb) = 0; + virtual void set_static(ID p_id, bool p_static) = 0; + virtual void remove(ID p_id) = 0; - virtual CollisionObject2DSW *get_object(ID p_id) const=0; - virtual bool is_static(ID p_id) const=0; - virtual int get_subindex(ID p_id) const=0; + virtual CollisionObject2DSW *get_object(ID p_id) const = 0; + virtual bool is_static(ID p_id) const = 0; + virtual int get_subindex(ID p_id) const = 0; - virtual int cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL)=0; - virtual int cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL)=0; + virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0; + virtual int cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0; - virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata)=0; - virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata)=0; + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata) = 0; + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) = 0; - virtual void update()=0; + virtual void update() = 0; virtual ~BroadPhase2DSW(); - }; #endif // BROAD_PHASE_2D_SW_H diff --git a/servers/physics_2d/collision_object_2d_sw.cpp b/servers/physics_2d/collision_object_2d_sw.cpp index 9ae0e40417..30bb9f6b52 100644 --- a/servers/physics_2d/collision_object_2d_sw.cpp +++ b/servers/physics_2d/collision_object_2d_sw.cpp @@ -29,46 +29,43 @@ #include "collision_object_2d_sw.h" #include "space_2d_sw.h" -void CollisionObject2DSW::add_shape(Shape2DSW *p_shape,const Transform2D& p_transform) { +void CollisionObject2DSW::add_shape(Shape2DSW *p_shape, const Transform2D &p_transform) { Shape s; - s.shape=p_shape; - s.xform=p_transform; - s.xform_inv=s.xform.affine_inverse(); - s.bpid=0; //needs update - s.trigger=false; + s.shape = p_shape; + s.xform = p_transform; + s.xform_inv = s.xform.affine_inverse(); + s.bpid = 0; //needs update + s.trigger = false; shapes.push_back(s); p_shape->add_owner(this); _update_shapes(); _shapes_changed(); - } -void CollisionObject2DSW::set_shape(int p_index,Shape2DSW *p_shape){ +void CollisionObject2DSW::set_shape(int p_index, Shape2DSW *p_shape) { - ERR_FAIL_INDEX(p_index,shapes.size()); + ERR_FAIL_INDEX(p_index, shapes.size()); shapes[p_index].shape->remove_owner(this); - shapes[p_index].shape=p_shape; + shapes[p_index].shape = p_shape; p_shape->add_owner(this); _update_shapes(); _shapes_changed(); - } -void CollisionObject2DSW::set_shape_metadata(int p_index,const Variant& p_metadata) { - - ERR_FAIL_INDEX(p_index,shapes.size()); - shapes[p_index].metadata=p_metadata; +void CollisionObject2DSW::set_shape_metadata(int p_index, const Variant &p_metadata) { + ERR_FAIL_INDEX(p_index, shapes.size()); + shapes[p_index].metadata = p_metadata; } -void CollisionObject2DSW::set_shape_transform(int p_index,const Transform2D& p_transform){ +void CollisionObject2DSW::set_shape_transform(int p_index, const Transform2D &p_transform) { - ERR_FAIL_INDEX(p_index,shapes.size()); + ERR_FAIL_INDEX(p_index, shapes.size()); - shapes[p_index].xform=p_transform; - shapes[p_index].xform_inv=p_transform.affine_inverse(); + shapes[p_index].xform = p_transform; + shapes[p_index].xform_inv = p_transform.affine_inverse(); _update_shapes(); _shapes_changed(); } @@ -76,61 +73,58 @@ void CollisionObject2DSW::set_shape_transform(int p_index,const Transform2D& p_t void CollisionObject2DSW::remove_shape(Shape2DSW *p_shape) { //remove a shape, all the times it appears - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - if (shapes[i].shape==p_shape) { + if (shapes[i].shape == p_shape) { remove_shape(i); i--; } } } -void CollisionObject2DSW::remove_shape(int p_index){ +void CollisionObject2DSW::remove_shape(int p_index) { //remove anything from shape to be erased to end, so subindices don't change - ERR_FAIL_INDEX(p_index,shapes.size()); - for(int i=p_index;i<shapes.size();i++) { + ERR_FAIL_INDEX(p_index, shapes.size()); + for (int i = p_index; i < shapes.size(); i++) { - if (shapes[i].bpid==0) + if (shapes[i].bpid == 0) continue; //should never get here with a null owner space->get_broadphase()->remove(shapes[i].bpid); - shapes[i].bpid=0; + shapes[i].bpid = 0; } shapes[p_index].shape->remove_owner(this); shapes.remove(p_index); _shapes_changed(); - } void CollisionObject2DSW::_set_static(bool p_static) { - if (_static==p_static) + if (_static == p_static) return; - _static=p_static; + _static = p_static; if (!space) return; - for(int i=0;i<get_shape_count();i++) { - Shape &s=shapes[i]; - if (s.bpid>0) { - space->get_broadphase()->set_static(s.bpid,_static); + for (int i = 0; i < get_shape_count(); i++) { + Shape &s = shapes[i]; + if (s.bpid > 0) { + space->get_broadphase()->set_static(s.bpid, _static); } } - } void CollisionObject2DSW::_unregister_shapes() { - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; - if (s.bpid>0) { + Shape &s = shapes[i]; + if (s.bpid > 0) { space->get_broadphase()->remove(s.bpid); - s.bpid=0; + s.bpid = 0; } } - } void CollisionObject2DSW::_update_shapes() { @@ -138,53 +132,47 @@ void CollisionObject2DSW::_update_shapes() { if (!space) return; + for (int i = 0; i < shapes.size(); i++) { - for(int i=0;i<shapes.size();i++) { - - Shape &s=shapes[i]; - if (s.bpid==0) { - s.bpid=space->get_broadphase()->create(this,i); - space->get_broadphase()->set_static(s.bpid,_static); + Shape &s = shapes[i]; + if (s.bpid == 0) { + s.bpid = space->get_broadphase()->create(this, i); + space->get_broadphase()->set_static(s.bpid, _static); } //not quite correct, should compute the next matrix.. - Rect2 shape_aabb=s.shape->get_aabb(); + Rect2 shape_aabb = s.shape->get_aabb(); Transform2D xform = transform * s.xform; - shape_aabb=xform.xform(shape_aabb); - s.aabb_cache=shape_aabb; - s.aabb_cache=s.aabb_cache.grow( (s.aabb_cache.size.x + s.aabb_cache.size.y)*0.5*0.05 ); + shape_aabb = xform.xform(shape_aabb); + s.aabb_cache = shape_aabb; + s.aabb_cache = s.aabb_cache.grow((s.aabb_cache.size.x + s.aabb_cache.size.y) * 0.5 * 0.05); - - space->get_broadphase()->move(s.bpid,s.aabb_cache); + space->get_broadphase()->move(s.bpid, s.aabb_cache); } - } -void CollisionObject2DSW::_update_shapes_with_motion(const Vector2& p_motion) { - +void CollisionObject2DSW::_update_shapes_with_motion(const Vector2 &p_motion) { if (!space) return; - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; - if (s.bpid==0) { - s.bpid=space->get_broadphase()->create(this,i); - space->get_broadphase()->set_static(s.bpid,_static); + Shape &s = shapes[i]; + if (s.bpid == 0) { + s.bpid = space->get_broadphase()->create(this, i); + space->get_broadphase()->set_static(s.bpid, _static); } //not quite correct, should compute the next matrix.. - Rect2 shape_aabb=s.shape->get_aabb(); + Rect2 shape_aabb = s.shape->get_aabb(); Transform2D xform = transform * s.xform; - shape_aabb=xform.xform(shape_aabb); - shape_aabb=shape_aabb.merge(Rect2( shape_aabb.pos+p_motion,shape_aabb.size)); //use motion - s.aabb_cache=shape_aabb; + shape_aabb = xform.xform(shape_aabb); + shape_aabb = shape_aabb.merge(Rect2(shape_aabb.pos + p_motion, shape_aabb.size)); //use motion + s.aabb_cache = shape_aabb; - space->get_broadphase()->move(s.bpid,shape_aabb); + space->get_broadphase()->move(s.bpid, shape_aabb); } - - } void CollisionObject2DSW::_set_space(Space2DSW *p_space) { @@ -193,25 +181,23 @@ void CollisionObject2DSW::_set_space(Space2DSW *p_space) { space->remove_object(this); - for(int i=0;i<shapes.size();i++) { + for (int i = 0; i < shapes.size(); i++) { - Shape &s=shapes[i]; + Shape &s = shapes[i]; if (s.bpid) { space->get_broadphase()->remove(s.bpid); - s.bpid=0; + s.bpid = 0; } } - } - space=p_space; + space = p_space; if (space) { space->add_object(this); _update_shapes(); } - } void CollisionObject2DSW::_shape_changed() { @@ -222,11 +208,11 @@ void CollisionObject2DSW::_shape_changed() { CollisionObject2DSW::CollisionObject2DSW(Type p_type) { - _static=true; - type=p_type; - space=NULL; - instance_id=0; - collision_mask=1; - layer_mask=1; - pickable=true; + _static = true; + type = p_type; + space = NULL; + instance_id = 0; + collision_mask = 1; + layer_mask = 1; + pickable = true; } diff --git a/servers/physics_2d/collision_object_2d_sw.h b/servers/physics_2d/collision_object_2d_sw.h index 0f77e9b426..e6eec05f3d 100644 --- a/servers/physics_2d/collision_object_2d_sw.h +++ b/servers/physics_2d/collision_object_2d_sw.h @@ -29,10 +29,10 @@ #ifndef COLLISION_OBJECT_2D_SW_H #define COLLISION_OBJECT_2D_SW_H -#include "shape_2d_sw.h" -#include "servers/physics_2d_server.h" -#include "self_list.h" #include "broad_phase_2d_sw.h" +#include "self_list.h" +#include "servers/physics_2d_server.h" +#include "shape_2d_sw.h" class Space2DSW; @@ -42,8 +42,8 @@ public: TYPE_AREA, TYPE_BODY }; -private: +private: Type type; RID self; ObjectID instance_id; @@ -58,7 +58,7 @@ private: Shape2DSW *shape; Variant metadata; bool trigger; - Shape() { trigger=false; } + Shape() { trigger = false; } }; Vector<Shape> shapes; @@ -72,74 +72,74 @@ private: void _update_shapes(); protected: - - - void _update_shapes_with_motion(const Vector2& p_motion); + void _update_shapes_with_motion(const Vector2 &p_motion); void _unregister_shapes(); - _FORCE_INLINE_ void _set_transform(const Transform2D& p_transform, bool p_update_shapes=true) { transform=p_transform; if (p_update_shapes) {_update_shapes();} } - _FORCE_INLINE_ void _set_inv_transform(const Transform2D& p_transform) { inv_transform=p_transform; } + _FORCE_INLINE_ void _set_transform(const Transform2D &p_transform, bool p_update_shapes = true) { + transform = p_transform; + if (p_update_shapes) { + _update_shapes(); + } + } + _FORCE_INLINE_ void _set_inv_transform(const Transform2D &p_transform) { inv_transform = p_transform; } void _set_static(bool p_static); - virtual void _shapes_changed()=0; + virtual void _shapes_changed() = 0; void _set_space(Space2DSW *space); CollisionObject2DSW(Type p_type); -public: - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } +public: + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } _FORCE_INLINE_ RID get_self() const { return self; } - _FORCE_INLINE_ void set_instance_id(const ObjectID& p_instance_id) { instance_id=p_instance_id; } + _FORCE_INLINE_ void set_instance_id(const ObjectID &p_instance_id) { instance_id = p_instance_id; } _FORCE_INLINE_ ObjectID get_instance_id() const { return instance_id; } void _shape_changed(); _FORCE_INLINE_ Type get_type() const { return type; } - void add_shape(Shape2DSW *p_shape,const Transform2D& p_transform=Transform2D()); - void set_shape(int p_index,Shape2DSW *p_shape); - void set_shape_transform(int p_index,const Transform2D& p_transform); - void set_shape_metadata(int p_index,const Variant& p_metadata); - + void add_shape(Shape2DSW *p_shape, const Transform2D &p_transform = Transform2D()); + void set_shape(int p_index, Shape2DSW *p_shape); + void set_shape_transform(int p_index, const Transform2D &p_transform); + void set_shape_metadata(int p_index, const Variant &p_metadata); _FORCE_INLINE_ int get_shape_count() const { return shapes.size(); } _FORCE_INLINE_ Shape2DSW *get_shape(int p_index) const { return shapes[p_index].shape; } - _FORCE_INLINE_ const Transform2D& get_shape_transform(int p_index) const { return shapes[p_index].xform; } - _FORCE_INLINE_ const Transform2D& get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; } - _FORCE_INLINE_ const Rect2& get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; } - _FORCE_INLINE_ const Variant& get_shape_metadata(int p_index) const { return shapes[p_index].metadata; } + _FORCE_INLINE_ const Transform2D &get_shape_transform(int p_index) const { return shapes[p_index].xform; } + _FORCE_INLINE_ const Transform2D &get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; } + _FORCE_INLINE_ const Rect2 &get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; } + _FORCE_INLINE_ const Variant &get_shape_metadata(int p_index) const { return shapes[p_index].metadata; } _FORCE_INLINE_ Transform2D get_transform() const { return transform; } _FORCE_INLINE_ Transform2D get_inv_transform() const { return inv_transform; } - _FORCE_INLINE_ Space2DSW* get_space() const { return space; } + _FORCE_INLINE_ Space2DSW *get_space() const { return space; } - _FORCE_INLINE_ void set_shape_as_trigger(int p_idx,bool p_enable) { shapes[p_idx].trigger=p_enable; } + _FORCE_INLINE_ void set_shape_as_trigger(int p_idx, bool p_enable) { shapes[p_idx].trigger = p_enable; } _FORCE_INLINE_ bool is_shape_set_as_trigger(int p_idx) const { return shapes[p_idx].trigger; } - - void set_collision_mask(uint32_t p_mask) {collision_mask=p_mask;} + void set_collision_mask(uint32_t p_mask) { collision_mask = p_mask; } _FORCE_INLINE_ uint32_t get_collision_mask() const { return collision_mask; } - void set_layer_mask(uint32_t p_mask) {layer_mask=p_mask;} + void set_layer_mask(uint32_t p_mask) { layer_mask = p_mask; } _FORCE_INLINE_ uint32_t get_layer_mask() const { return layer_mask; } void remove_shape(Shape2DSW *p_shape); void remove_shape(int p_index); - virtual void set_space(Space2DSW *p_space)=0; + virtual void set_space(Space2DSW *p_space) = 0; - _FORCE_INLINE_ bool is_static() const { return _static; } + _FORCE_INLINE_ bool is_static() const { return _static; } - void set_pickable(bool p_pickable) { pickable=p_pickable; } + void set_pickable(bool p_pickable) { pickable = p_pickable; } _FORCE_INLINE_ bool is_pickable() const { return pickable; } - _FORCE_INLINE_ bool test_collision_mask(CollisionObject2DSW* p_other) const { + _FORCE_INLINE_ bool test_collision_mask(CollisionObject2DSW *p_other) const { - return layer_mask&p_other->collision_mask || p_other->layer_mask&collision_mask; + return layer_mask & p_other->collision_mask || p_other->layer_mask & collision_mask; } virtual ~CollisionObject2DSW() {} - }; #endif // COLLISION_OBJECT_2D_SW_H diff --git a/servers/physics_2d/collision_solver_2d_sat.cpp b/servers/physics_2d/collision_solver_2d_sat.cpp index 4c116cee3f..f72a7ef0e4 100644 --- a/servers/physics_2d/collision_solver_2d_sat.cpp +++ b/servers/physics_2d/collision_solver_2d_sat.cpp @@ -38,61 +38,57 @@ struct _CollectorCallback2D { Vector2 normal; Vector2 *sep_axis; - _FORCE_INLINE_ void call(const Vector2& p_point_A, const Vector2& p_point_B) { + _FORCE_INLINE_ void call(const Vector2 &p_point_A, const Vector2 &p_point_B) { /* if (normal.dot(p_point_A) >= normal.dot(p_point_B)) return; */ if (swap) - callback(p_point_B,p_point_A,userdata); + callback(p_point_B, p_point_A, userdata); else - callback(p_point_A,p_point_B,userdata); + callback(p_point_A, p_point_B, userdata); } - }; -typedef void (*GenerateContactsFunc)(const Vector2 *,int, const Vector2 *,int ,_CollectorCallback2D *); - +typedef void (*GenerateContactsFunc)(const Vector2 *, int, const Vector2 *, int, _CollectorCallback2D *); -_FORCE_INLINE_ static void _generate_contacts_point_point(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) { +_FORCE_INLINE_ static void _generate_contacts_point_point(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 1 ); - ERR_FAIL_COND( p_point_count_B != 1 ); + ERR_FAIL_COND(p_point_count_A != 1); + ERR_FAIL_COND(p_point_count_B != 1); #endif - p_collector->call(*p_points_A,*p_points_B); + p_collector->call(*p_points_A, *p_points_B); } -_FORCE_INLINE_ static void _generate_contacts_point_edge(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) { +_FORCE_INLINE_ static void _generate_contacts_point_edge(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 1 ); - ERR_FAIL_COND( p_point_count_B != 2 ); + ERR_FAIL_COND(p_point_count_A != 1); + ERR_FAIL_COND(p_point_count_B != 2); #endif - Vector2 closest_B = Geometry::get_closest_point_to_segment_uncapped_2d(*p_points_A, p_points_B ); - p_collector->call(*p_points_A,closest_B); - + Vector2 closest_B = Geometry::get_closest_point_to_segment_uncapped_2d(*p_points_A, p_points_B); + p_collector->call(*p_points_A, closest_B); } - struct _generate_contacts_Pair { bool a; int idx; real_t d; - _FORCE_INLINE_ bool operator <(const _generate_contacts_Pair& l) const { return d< l.d; } + _FORCE_INLINE_ bool operator<(const _generate_contacts_Pair &l) const { return d < l.d; } }; -_FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) { +_FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A != 2 ); - ERR_FAIL_COND( p_point_count_B != 2 ); // circle is actually a 4x3 matrix + ERR_FAIL_COND(p_point_count_A != 2); + ERR_FAIL_COND(p_point_count_B != 2); // circle is actually a 4x3 matrix #endif -# if 0 +#if 0 Vector2 rel_A=p_points_A[1]-p_points_A[0]; Vector2 rel_B=p_points_B[1]-p_points_B[0]; @@ -210,9 +206,6 @@ _FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 * p_points #if 1 - - - Vector2 n = p_collector->normal; Vector2 t = n.tangent(); real_t dA = n.dot(p_points_A[0]); @@ -220,90 +213,87 @@ _FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 * p_points _generate_contacts_Pair dvec[4]; - dvec[0].d=t.dot(p_points_A[0]); - dvec[0].a=true; - dvec[0].idx=0; - dvec[1].d=t.dot(p_points_A[1]); - dvec[1].a=true; - dvec[1].idx=1; - dvec[2].d=t.dot(p_points_B[0]); - dvec[2].a=false; - dvec[2].idx=0; - dvec[3].d=t.dot(p_points_B[1]); - dvec[3].a=false; - dvec[3].idx=1; + dvec[0].d = t.dot(p_points_A[0]); + dvec[0].a = true; + dvec[0].idx = 0; + dvec[1].d = t.dot(p_points_A[1]); + dvec[1].a = true; + dvec[1].idx = 1; + dvec[2].d = t.dot(p_points_B[0]); + dvec[2].a = false; + dvec[2].idx = 0; + dvec[3].d = t.dot(p_points_B[1]); + dvec[3].a = false; + dvec[3].idx = 1; SortArray<_generate_contacts_Pair> sa; - sa.sort(dvec,4); + sa.sort(dvec, 4); - for(int i=1;i<=2;i++) { + for (int i = 1; i <= 2; i++) { if (dvec[i].a) { Vector2 a = p_points_A[dvec[i].idx]; - Vector2 b = n.plane_project(dB,a); - if (n.dot(a) > n.dot(b)-CMP_EPSILON) + Vector2 b = n.plane_project(dB, a); + if (n.dot(a) > n.dot(b) - CMP_EPSILON) continue; - p_collector->call(a,b); + p_collector->call(a, b); } else { Vector2 b = p_points_B[dvec[i].idx]; - Vector2 a = n.plane_project(dA,b); - if (n.dot(a) > n.dot(b)-CMP_EPSILON) + Vector2 a = n.plane_project(dA, b); + if (n.dot(a) > n.dot(b) - CMP_EPSILON) continue; - p_collector->call(a,b); + p_collector->call(a, b); } } - - #elif 0 Vector2 axis = rel_A.normalized(); //make an axis Vector2 axis_B = rel_B.normalized(); - if (axis.dot(axis_B)<0) - axis_B=-axis_B; - axis=(axis+axis_B)*0.5; + if (axis.dot(axis_B) < 0) + axis_B = -axis_B; + axis = (axis + axis_B) * 0.5; Vector2 base_A = p_points_A[0] - axis * axis.dot(p_points_A[0]); Vector2 base_B = p_points_B[0] - axis * axis.dot(p_points_B[0]); //sort all 4 points in axis - real_t dvec[4]={ axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) }; + real_t dvec[4] = { axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) }; //todo , find max/min and then use 2 central points SortArray<real_t> sa; - sa.sort(dvec,4); + sa.sort(dvec, 4); //use the middle ones as contacts - for (int i=1;i<=2;i++) { + for (int i = 1; i <= 2; i++) { - Vector2 a = base_A+axis*dvec[i]; - Vector2 b = base_B+axis*dvec[i]; - if (p_collector->normal.dot(a) > p_collector->normal.dot(b)-0.01) { - print_line("fail a: "+a); - print_line("fail b: "+b); + Vector2 a = base_A + axis * dvec[i]; + Vector2 b = base_B + axis * dvec[i]; + if (p_collector->normal.dot(a) > p_collector->normal.dot(b) - 0.01) { + print_line("fail a: " + a); + print_line("fail b: " + b); continue; } - print_line("res a: "+a); - print_line("res b: "+b); - p_collector->call(a,b); + print_line("res a: " + a); + print_line("res b: " + b); + p_collector->call(a, b); } #endif } -static void _generate_contacts_from_supports(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) { - +static void _generate_contacts_from_supports(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) { #ifdef DEBUG_ENABLED - ERR_FAIL_COND( p_point_count_A <1 ); - ERR_FAIL_COND( p_point_count_B <1 ); + ERR_FAIL_COND(p_point_count_A < 1); + ERR_FAIL_COND(p_point_count_B < 1); #endif - - static const GenerateContactsFunc generate_contacts_func_table[2][2]={ + static const GenerateContactsFunc generate_contacts_func_table[2][2] = { { - _generate_contacts_point_point, - _generate_contacts_point_edge, - },{ - 0, - _generate_contacts_edge_edge, + _generate_contacts_point_point, + _generate_contacts_point_edge, + }, + { + 0, + _generate_contacts_edge_edge, } }; @@ -319,28 +309,25 @@ static void _generate_contacts_from_supports(const Vector2 * p_points_A,int p_po pointcount_B = p_point_count_A; pointcount_A = p_point_count_B; - points_A=p_points_B; - points_B=p_points_A; + points_A = p_points_B; + points_B = p_points_A; } else { pointcount_B = p_point_count_B; pointcount_A = p_point_count_A; - points_A=p_points_A; - points_B=p_points_B; + points_A = p_points_A; + points_B = p_points_B; } - int version_A = (pointcount_A > 3 ? 3 : pointcount_A) -1; - int version_B = (pointcount_B > 3 ? 3 : pointcount_B) -1; + int version_A = (pointcount_A > 3 ? 3 : pointcount_A) - 1; + int version_B = (pointcount_B > 3 ? 3 : pointcount_B) - 1; GenerateContactsFunc contacts_func = generate_contacts_func_table[version_A][version_B]; ERR_FAIL_COND(!contacts_func); - contacts_func(points_A,pointcount_A,points_B,pointcount_B,p_collector); - + contacts_func(points_A, pointcount_A, points_B, pointcount_B, p_collector); } - - -template<class ShapeA, class ShapeB,bool castA=false,bool castB=false, bool withMargin=false> +template <class ShapeA, class ShapeB, bool castA = false, bool castB = false, bool withMargin = false> class SeparatorAxisTest2D { const ShapeA *shape_A; @@ -358,16 +345,14 @@ class SeparatorAxisTest2D { _CollectorCallback2D *callback; public: - _FORCE_INLINE_ bool test_previous_axis() { - if (callback && callback->sep_axis && *callback->sep_axis!=Vector2()) { + if (callback && callback->sep_axis && *callback->sep_axis != Vector2()) { return test_axis(*callback->sep_axis); } else { #ifdef DEBUG_ENABLED best_axis_count++; #endif - } return true; } @@ -395,45 +380,44 @@ public: return true; } - _FORCE_INLINE_ bool test_axis(const Vector2& p_axis) { + _FORCE_INLINE_ bool test_axis(const Vector2 &p_axis) { - Vector2 axis=p_axis; + Vector2 axis = p_axis; - - if ( Math::abs(axis.x)<CMP_EPSILON && - Math::abs(axis.y)<CMP_EPSILON) { + if (Math::abs(axis.x) < CMP_EPSILON && + Math::abs(axis.y) < CMP_EPSILON) { // strange case, try an upwards separator - axis=Vector2(0.0,1.0); + axis = Vector2(0.0, 1.0); } - real_t min_A,max_A,min_B,max_B; + real_t min_A, max_A, min_B, max_B; if (castA) - shape_A->project_range_cast(motion_A,axis,*transform_A,min_A,max_A); + shape_A->project_range_cast(motion_A, axis, *transform_A, min_A, max_A); else - shape_A->project_range(axis,*transform_A,min_A,max_A); + shape_A->project_range(axis, *transform_A, min_A, max_A); if (castB) - shape_B->project_range_cast(motion_B,axis,*transform_B,min_B,max_B); + shape_B->project_range_cast(motion_B, axis, *transform_B, min_B, max_B); else - shape_B->project_range(axis,*transform_B,min_B,max_B); + shape_B->project_range(axis, *transform_B, min_B, max_B); if (withMargin) { - min_A-=margin_A; - max_A+=margin_A; - min_B-=margin_B; - max_B+=margin_B; + min_A -= margin_A; + max_A += margin_A; + min_B -= margin_B; + max_B += margin_B; } - min_B -= ( max_A - min_A ) * 0.5; - max_B += ( max_A - min_A ) * 0.5; + min_B -= (max_A - min_A) * 0.5; + max_B += (max_A - min_A) * 0.5; - real_t dmin = min_B - ( min_A + max_A ) * 0.5; - real_t dmax = max_B - ( min_A + max_A ) * 0.5; + real_t dmin = min_B - (min_A + max_A) * 0.5; + real_t dmax = max_B - (min_A + max_A) * 0.5; if (dmin > 0.0 || dmax < 0.0) { if (callback && callback->sep_axis) - *callback->sep_axis=axis; + *callback->sep_axis = axis; #ifdef DEBUG_ENABLED best_axis_count++; #endif @@ -445,26 +429,25 @@ public: dmin = Math::abs(dmin); - if ( dmax < dmin ) { - if ( dmax < best_depth ) { - best_depth=dmax; - best_axis=axis; + if (dmax < dmin) { + if (dmax < best_depth) { + best_depth = dmax; + best_axis = axis; #ifdef DEBUG_ENABLED - best_axis_index=best_axis_count; + best_axis_index = best_axis_count; #endif - } } else { - if ( dmin < best_depth ) { - best_depth=dmin; - best_axis=-axis; // keep it as A axis + if (dmin < best_depth) { + best_depth = dmin; + best_axis = -axis; // keep it as A axis #ifdef DEBUG_ENABLED - best_axis_index=best_axis_count; + best_axis_index = best_axis_count; #endif } } - //print_line("test axis: "+p_axis+" depth: "+rtos(best_depth)); +//print_line("test axis: "+p_axis+" depth: "+rtos(best_depth)); #ifdef DEBUG_ENABLED best_axis_count++; #endif @@ -472,60 +455,55 @@ public: return true; } - _FORCE_INLINE_ void generate_contacts() { // nothing to do, don't generate - if (best_axis==Vector2(0.0,0.0)) + if (best_axis == Vector2(0.0, 0.0)) return; - callback->collided=true; + callback->collided = true; if (!callback->callback) return; //only collide, no callback - static const int max_supports=2; + static const int max_supports = 2; Vector2 supports_A[max_supports]; int support_count_A; if (castA) { - shape_A->get_supports_transformed_cast(motion_A,-best_axis,*transform_A,supports_A,support_count_A); + shape_A->get_supports_transformed_cast(motion_A, -best_axis, *transform_A, supports_A, support_count_A); } else { - shape_A->get_supports(transform_A->basis_xform_inv(-best_axis).normalized(),supports_A,support_count_A); - for(int i=0;i<support_count_A;i++) { + shape_A->get_supports(transform_A->basis_xform_inv(-best_axis).normalized(), supports_A, support_count_A); + for (int i = 0; i < support_count_A; i++) { supports_A[i] = transform_A->xform(supports_A[i]); } } if (withMargin) { - for(int i=0;i<support_count_A;i++) { - supports_A[i]+=-best_axis*margin_A; + for (int i = 0; i < support_count_A; i++) { + supports_A[i] += -best_axis * margin_A; } - } - - Vector2 supports_B[max_supports]; int support_count_B; if (castB) { - shape_B->get_supports_transformed_cast(motion_B,best_axis,*transform_B,supports_B,support_count_B); + shape_B->get_supports_transformed_cast(motion_B, best_axis, *transform_B, supports_B, support_count_B); } else { - shape_B->get_supports(transform_B->basis_xform_inv(best_axis).normalized(),supports_B,support_count_B); - for(int i=0;i<support_count_B;i++) { + shape_B->get_supports(transform_B->basis_xform_inv(best_axis).normalized(), supports_B, support_count_B); + for (int i = 0; i < support_count_B; i++) { supports_B[i] = transform_B->xform(supports_B[i]); } } if (withMargin) { - for(int i=0;i<support_count_B;i++) { - supports_B[i]+=best_axis*margin_B; + for (int i = 0; i < support_count_B; i++) { + supports_B[i] += best_axis * margin_B; } - } -/* + /* print_line("**************************"); @@ -549,38 +527,33 @@ public: } //*/ + callback->normal = best_axis; + _generate_contacts_from_supports(supports_A, support_count_A, supports_B, support_count_B, callback); - - - callback->normal=best_axis; - _generate_contacts_from_supports(supports_A,support_count_A,supports_B,support_count_B,callback); - - if (callback && callback->sep_axis && *callback->sep_axis!=Vector2()) - *callback->sep_axis=Vector2(); //invalidate previous axis (no test) + if (callback && callback->sep_axis && *callback->sep_axis != Vector2()) + *callback->sep_axis = Vector2(); //invalidate previous axis (no test) //CollisionSolver2DSW::CallbackResult cbk=NULL; //cbk(Vector2(),Vector2(),NULL); - } - _FORCE_INLINE_ SeparatorAxisTest2D(const ShapeA *p_shape_A,const Transform2D& p_transform_a, const ShapeB *p_shape_B,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_A=Vector2(), const Vector2& p_motion_B=Vector2(),real_t p_margin_A=0,real_t p_margin_B=0) { + _FORCE_INLINE_ SeparatorAxisTest2D(const ShapeA *p_shape_A, const Transform2D &p_transform_a, const ShapeB *p_shape_B, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_A = Vector2(), const Vector2 &p_motion_B = Vector2(), real_t p_margin_A = 0, real_t p_margin_B = 0) { - margin_A=p_margin_A; - margin_B=p_margin_B; - best_depth=1e15; - shape_A=p_shape_A; - shape_B=p_shape_B; - transform_A=&p_transform_a; - transform_B=&p_transform_b; - motion_A=p_motion_A; - motion_B=p_motion_B; + margin_A = p_margin_A; + margin_B = p_margin_B; + best_depth = 1e15; + shape_A = p_shape_A; + shape_B = p_shape_B; + transform_A = &p_transform_a; + transform_B = &p_transform_b; + motion_A = p_motion_A; + motion_B = p_motion_B; - callback=p_collector; + callback = p_collector; #ifdef DEBUG_ENABLED - best_axis_count=0; - best_axis_index=-1; + best_axis_count = 0; + best_axis_index = -1; #endif } - }; /****** SAT TESTS *******/ @@ -588,30 +561,26 @@ public: /****** SAT TESTS *******/ /****** SAT TESTS *******/ +#define TEST_POINT(m_a, m_b) \ + ((!separator.test_axis(((m_a) - (m_b)).normalized())) || \ + (castA && !separator.test_axis(((m_a) + p_motion_a - (m_b)).normalized())) || \ + (castB && !separator.test_axis(((m_a) - ((m_b) + p_motion_b)).normalized())) || \ + (castA && castB && !separator.test_axis(((m_a) + p_motion_a - ((m_b) + p_motion_b)).normalized()))) -#define TEST_POINT(m_a,m_b) \ - ( (!separator.test_axis(((m_a)-(m_b)).normalized())) ||\ - (castA && !separator.test_axis(((m_a)+p_motion_a-(m_b)).normalized())) ||\ - (castB && !separator.test_axis(((m_a)-((m_b)+p_motion_b)).normalized())) ||\ - (castA && castB && !separator.test_axis(((m_a)+p_motion_a-((m_b)+p_motion_b)).normalized())) ) - - -typedef void (*CollisionFunc)(const Shape2DSW*,const Transform2D&,const Shape2DSW*,const Transform2D&,_CollectorCallback2D *p_collector,const Vector2&,const Vector2&,real_t,real_t); - +typedef void (*CollisionFunc)(const Shape2DSW *, const Transform2D &, const Shape2DSW *, const Transform2D &, _CollectorCallback2D *p_collector, const Vector2 &, const Vector2 &, real_t, real_t); -template<bool castA, bool castB,bool withMargin> -static void _collision_segment_segment(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { +template <bool castA, bool castB, bool withMargin> +static void _collision_segment_segment(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a); - const SegmentShape2DSW *segment_B = static_cast<const SegmentShape2DSW*>(p_b); + const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a); + const SegmentShape2DSW *segment_B = static_cast<const SegmentShape2DSW *>(p_b); - SeparatorAxisTest2D<SegmentShape2DSW,SegmentShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,segment_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<SegmentShape2DSW, SegmentShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, segment_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; //this collision is kind of pointless - /* if (!separator.test_previous_axis()) return; @@ -620,7 +589,6 @@ static void _collision_segment_segment(const Shape2DSW* p_a,const Transform2D& p if (!separator.test_cast()) return; - if (!separator.test_axis(segment_A->get_xformed_normal(p_transform_a))) return; if (!separator.test_axis(segment_B->get_xformed_normal(p_transform_b))) @@ -629,30 +597,26 @@ static void _collision_segment_segment(const Shape2DSW* p_a,const Transform2D& p if (withMargin) { //points grow to circles - - if (TEST_POINT( p_transform_a.xform(segment_A->get_a()),p_transform_b.xform(segment_B->get_a())) ) + if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.xform(segment_B->get_a()))) return; - if (TEST_POINT( p_transform_a.xform(segment_A->get_a()),p_transform_b.xform(segment_B->get_b())) ) + if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.xform(segment_B->get_b()))) return; - if (TEST_POINT( p_transform_a.xform(segment_A->get_b()),p_transform_b.xform(segment_B->get_a())) ) + if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.xform(segment_B->get_a()))) return; - if (TEST_POINT( p_transform_a.xform(segment_A->get_b()),p_transform_b.xform(segment_B->get_b())) ) + if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.xform(segment_B->get_b()))) return; } separator.generate_contacts(); - } -template<bool castA, bool castB,bool withMargin> -static void _collision_segment_circle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - - const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a); - const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_segment_circle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a); + const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW *>(p_b); - SeparatorAxisTest2D<SegmentShape2DSW,CircleShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,circle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<SegmentShape2DSW, CircleShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, circle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -662,28 +626,26 @@ static void _collision_segment_circle(const Shape2DSW* p_a,const Transform2D& p_ //segment normal if (!separator.test_axis( - (p_transform_a.xform(segment_A->get_b())-p_transform_a.xform(segment_A->get_a())).normalized().tangent() - )) + (p_transform_a.xform(segment_A->get_b()) - p_transform_a.xform(segment_A->get_a())).normalized().tangent())) return; //endpoint a vs circle - if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),p_transform_b.get_origin())) + if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.get_origin())) return; //endpoint b vs circle - if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),p_transform_b.get_origin())) + if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.get_origin())) return; - separator.generate_contacts(); } -template<bool castA, bool castB,bool withMargin> -static void _collision_segment_rectangle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { +template <bool castA, bool castB, bool withMargin> +static void _collision_segment_rectangle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a); - const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW*>(p_b); + const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a); + const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW *>(p_b); - SeparatorAxisTest2D<SegmentShape2DSW,RectangleShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,rectangle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<SegmentShape2DSW, RectangleShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, rectangle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -707,48 +669,46 @@ static void _collision_segment_rectangle(const Shape2DSW* p_a,const Transform2D& Vector2 a = p_transform_a.xform(segment_A->get_a()); Vector2 b = p_transform_a.xform(segment_A->get_b()); - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a))) return; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b))) return; if (castA) { - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a+p_motion_a))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a + p_motion_a))) return; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b+p_motion_a))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b + p_motion_a))) return; } if (castB) { - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a-p_motion_b))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a - p_motion_b))) return; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b-p_motion_b))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b - p_motion_b))) return; } if (castA && castB) { - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a-p_motion_b+p_motion_a))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a - p_motion_b + p_motion_a))) return; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b-p_motion_b+p_motion_a))) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b - p_motion_b + p_motion_a))) return; } - } separator.generate_contacts(); - } -template<bool castA, bool castB,bool withMargin> -static void _collision_segment_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { +template <bool castA, bool castB, bool withMargin> +static void _collision_segment_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a); - const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b); + const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a); + const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b); - SeparatorAxisTest2D<SegmentShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<SegmentShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -762,25 +722,25 @@ static void _collision_segment_capsule(const Shape2DSW* p_a,const Transform2D& p if (!separator.test_axis(p_transform_b.elements[0].normalized())) return; - if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*0.5))) + if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * 0.5))) return; - if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*-0.5))) + if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * -0.5))) return; - if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*0.5))) + if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * 0.5))) return; - if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*-0.5))) + if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * -0.5))) return; separator.generate_contacts(); } -template<bool castA, bool castB,bool withMargin> -static void _collision_segment_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { +template <bool castA, bool castB, bool withMargin> +static void _collision_segment_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a); - const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b); + const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a); + const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b); - SeparatorAxisTest2D<SegmentShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<SegmentShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -791,37 +751,32 @@ static void _collision_segment_convex_polygon(const Shape2DSW* p_a,const Transfo if (!separator.test_axis(segment_A->get_xformed_normal(p_transform_a))) return; - for(int i=0;i<convex_B->get_point_count();i++) { + for (int i = 0; i < convex_B->get_point_count(); i++) { - if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i))) + if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i))) return; if (withMargin) { - if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),p_transform_b.xform(convex_B->get_point(i) ))) + if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.xform(convex_B->get_point(i)))) return; - if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),p_transform_b.xform(convex_B->get_point(i) ))) + if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.xform(convex_B->get_point(i)))) return; - } - } separator.generate_contacts(); - } - ///////// -template<bool castA, bool castB,bool withMargin> -static void _collision_circle_circle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a); - const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_circle_circle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a); + const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW *>(p_b); - SeparatorAxisTest2D<CircleShape2DSW,CircleShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,circle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<CircleShape2DSW, CircleShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, circle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -829,22 +784,19 @@ static void _collision_circle_circle(const Shape2DSW* p_a,const Transform2D& p_t if (!separator.test_cast()) return; - if (TEST_POINT(p_transform_a.get_origin(),p_transform_b.get_origin())) + if (TEST_POINT(p_transform_a.get_origin(), p_transform_b.get_origin())) return; - separator.generate_contacts(); - } -template<bool castA, bool castB,bool withMargin> -static void _collision_circle_rectangle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a); - const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_circle_rectangle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a); + const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW *>(p_b); - SeparatorAxisTest2D<CircleShape2DSW,RectangleShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,rectangle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<CircleShape2DSW, RectangleShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, rectangle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -852,8 +804,8 @@ static void _collision_circle_rectangle(const Shape2DSW* p_a,const Transform2D& if (!separator.test_cast()) return; - const Vector2 &sphere=p_transform_a.elements[2]; - const Vector2 *axis=&p_transform_b.elements[0]; + const Vector2 &sphere = p_transform_a.elements[2]; + const Vector2 *axis = &p_transform_b.elements[0]; //const Vector2& half_extents = rectangle_B->get_half_extents(); if (!separator.test_axis(axis[0].normalized())) @@ -865,42 +817,41 @@ static void _collision_circle_rectangle(const Shape2DSW* p_a,const Transform2D& Transform2D binv = p_transform_b.affine_inverse(); { - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv,sphere ) ) ) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphere))) return; } if (castA) { Vector2 sphereofs = sphere + p_motion_a; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv, sphereofs) ) ) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphereofs))) return; } if (castB) { Vector2 sphereofs = sphere - p_motion_b; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv, sphereofs) ) ) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphereofs))) return; } if (castA && castB) { Vector2 sphereofs = sphere - p_motion_b + p_motion_a; - if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv, sphereofs) ) ) + if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphereofs))) return; } separator.generate_contacts(); } -template<bool castA, bool castB,bool withMargin> -static void _collision_circle_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { +template <bool castA, bool castB, bool withMargin> +static void _collision_circle_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a); - const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b); + const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a); + const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b); - - SeparatorAxisTest2D<CircleShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<CircleShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -913,24 +864,21 @@ static void _collision_circle_capsule(const Shape2DSW* p_a,const Transform2D& p_ return; //capsule endpoints - if (TEST_POINT(p_transform_a.get_origin(),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*0.5))) + if (TEST_POINT(p_transform_a.get_origin(), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * 0.5))) return; - if (TEST_POINT(p_transform_a.get_origin(),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*-0.5))) + if (TEST_POINT(p_transform_a.get_origin(), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * -0.5))) return; separator.generate_contacts(); - - } -template<bool castA, bool castB,bool withMargin> -static void _collision_circle_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { +template <bool castA, bool castB, bool withMargin> +static void _collision_circle_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a); - const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b); + const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a); + const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b); - - SeparatorAxisTest2D<CircleShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<CircleShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -938,31 +886,28 @@ static void _collision_circle_convex_polygon(const Shape2DSW* p_a,const Transfor if (!separator.test_cast()) return; - //poly faces and poly points vs circle - for(int i=0;i<convex_B->get_point_count();i++) { + for (int i = 0; i < convex_B->get_point_count(); i++) { - if (TEST_POINT( p_transform_a.get_origin(),p_transform_b.xform(convex_B->get_point(i)) )) + if (TEST_POINT(p_transform_a.get_origin(), p_transform_b.xform(convex_B->get_point(i)))) return; - if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i))) + if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i))) return; } separator.generate_contacts(); } - ///////// -template<bool castA, bool castB,bool withMargin> -static void _collision_rectangle_rectangle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW*>(p_a); - const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_rectangle_rectangle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW *>(p_a); + const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW *>(p_b); - SeparatorAxisTest2D<RectangleShape2DSW,RectangleShape2DSW,castA,castB,withMargin> separator(rectangle_A,p_transform_a,rectangle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<RectangleShape2DSW, RectangleShape2DSW, castA, castB, withMargin> separator(rectangle_A, p_transform_a, rectangle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -986,38 +931,38 @@ static void _collision_rectangle_rectangle(const Shape2DSW* p_a,const Transform2 if (withMargin) { - Transform2D invA=p_transform_a.affine_inverse(); - Transform2D invB=p_transform_b.affine_inverse(); + Transform2D invA = p_transform_a.affine_inverse(); + Transform2D invB = p_transform_b.affine_inverse(); - if (!separator.test_axis( rectangle_A->get_box_axis(p_transform_a,invA,rectangle_B,p_transform_b,invB) ) ) + if (!separator.test_axis(rectangle_A->get_box_axis(p_transform_a, invA, rectangle_B, p_transform_b, invB))) return; if (castA || castB) { Transform2D aofs = p_transform_a; - aofs.elements[2]+=p_motion_a; + aofs.elements[2] += p_motion_a; Transform2D bofs = p_transform_b; - bofs.elements[2]+=p_motion_b; + bofs.elements[2] += p_motion_b; Transform2D aofsinv = aofs.affine_inverse(); Transform2D bofsinv = bofs.affine_inverse(); if (castA) { - if (!separator.test_axis( rectangle_A->get_box_axis(aofs,aofsinv,rectangle_B,p_transform_b,invB) ) ) + if (!separator.test_axis(rectangle_A->get_box_axis(aofs, aofsinv, rectangle_B, p_transform_b, invB))) return; } if (castB) { - if (!separator.test_axis( rectangle_A->get_box_axis(p_transform_a,invA,rectangle_B,bofs,bofsinv) ) ) + if (!separator.test_axis(rectangle_A->get_box_axis(p_transform_a, invA, rectangle_B, bofs, bofsinv))) return; } if (castA && castB) { - if (!separator.test_axis( rectangle_A->get_box_axis(aofs,aofsinv,rectangle_B,bofs,bofsinv) ) ) + if (!separator.test_axis(rectangle_A->get_box_axis(aofs, aofsinv, rectangle_B, bofs, bofsinv))) return; } } @@ -1026,14 +971,13 @@ static void _collision_rectangle_rectangle(const Shape2DSW* p_a,const Transform2 separator.generate_contacts(); } -template<bool castA, bool castB,bool withMargin> -static void _collision_rectangle_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW*>(p_a); - const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_rectangle_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW *>(p_a); + const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b); - SeparatorAxisTest2D<RectangleShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(rectangle_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<RectangleShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(rectangle_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -1052,61 +996,55 @@ static void _collision_rectangle_capsule(const Shape2DSW* p_a,const Transform2D& if (!separator.test_axis(p_transform_b.elements[0].normalized())) return; - //box endpoints to capsule circles Transform2D boxinv = p_transform_a.affine_inverse(); - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { { - Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5); + Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5); - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint))) return; } - if (castA) { - Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5); - capsule_endpoint-=p_motion_a; + Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5); + capsule_endpoint -= p_motion_a; - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint))) return; } if (castB) { - Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5); - capsule_endpoint+=p_motion_b; + Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5); + capsule_endpoint += p_motion_b; - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint))) return; } if (castA && castB) { - Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5); - capsule_endpoint-=p_motion_a; - capsule_endpoint+=p_motion_b; - + Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5); + capsule_endpoint -= p_motion_a; + capsule_endpoint += p_motion_b; - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint))) return; } - } - separator.generate_contacts(); } -template<bool castA, bool castB,bool withMargin> -static void _collision_rectangle_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW*>(p_a); - const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_rectangle_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { - SeparatorAxisTest2D<RectangleShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(rectangle_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW *>(p_a); + const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b); + SeparatorAxisTest2D<RectangleShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(rectangle_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -1124,51 +1062,47 @@ static void _collision_rectangle_convex_polygon(const Shape2DSW* p_a,const Trans //convex faces Transform2D boxinv; if (withMargin) { - boxinv=p_transform_a.affine_inverse(); + boxinv = p_transform_a.affine_inverse(); } - for(int i=0;i<convex_B->get_point_count();i++) { + for (int i = 0; i < convex_B->get_point_count(); i++) { - if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i))) + if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i))) return; if (withMargin) { //all points vs all points need to be tested if margin exist - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i))))) return; if (castA) { - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))-p_motion_a))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)) - p_motion_a))) return; } if (castB) { - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))+p_motion_b))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)) + p_motion_b))) return; } if (castA && castB) { - if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))+p_motion_b-p_motion_a))) + if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)) + p_motion_b - p_motion_a))) return; } - } } separator.generate_contacts(); - } - ///////// -template<bool castA, bool castB,bool withMargin> -static void _collision_capsule_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW*>(p_a); - const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_capsule_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW *>(p_a); + const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b); - SeparatorAxisTest2D<CapsuleShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(capsule_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<CapsuleShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(capsule_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -1186,32 +1120,29 @@ static void _collision_capsule_capsule(const Shape2DSW* p_a,const Transform2D& p //capsule endpoints - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - Vector2 capsule_endpoint_A = p_transform_a.get_origin()+p_transform_a.elements[1]*capsule_A->get_height()*(i==0?0.5:-0.5); + Vector2 capsule_endpoint_A = p_transform_a.get_origin() + p_transform_a.elements[1] * capsule_A->get_height() * (i == 0 ? 0.5 : -0.5); - for(int j=0;j<2;j++) { + for (int j = 0; j < 2; j++) { - Vector2 capsule_endpoint_B = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(j==0?0.5:-0.5); + Vector2 capsule_endpoint_B = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (j == 0 ? 0.5 : -0.5); - if (TEST_POINT(capsule_endpoint_A,capsule_endpoint_B) ) + if (TEST_POINT(capsule_endpoint_A, capsule_endpoint_B)) return; - } } separator.generate_contacts(); - } -template<bool castA, bool castB,bool withMargin> -static void _collision_capsule_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - - const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW*>(p_a); - const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b); +template <bool castA, bool castB, bool withMargin> +static void _collision_capsule_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { + const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW *>(p_a); + const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b); - SeparatorAxisTest2D<CapsuleShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(capsule_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<CapsuleShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(capsule_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -1224,40 +1155,35 @@ static void _collision_capsule_convex_polygon(const Shape2DSW* p_a,const Transfo if (!separator.test_axis(p_transform_a.elements[0].normalized())) return; - //poly vs capsule - for(int i=0;i<convex_B->get_point_count();i++) { + for (int i = 0; i < convex_B->get_point_count(); i++) { Vector2 cpoint = p_transform_b.xform(convex_B->get_point(i)); - for(int j=0;j<2;j++) { + for (int j = 0; j < 2; j++) { - Vector2 capsule_endpoint_A = p_transform_a.get_origin()+p_transform_a.elements[1]*capsule_A->get_height()*(j==0?0.5:-0.5); + Vector2 capsule_endpoint_A = p_transform_a.get_origin() + p_transform_a.elements[1] * capsule_A->get_height() * (j == 0 ? 0.5 : -0.5); - if (TEST_POINT(capsule_endpoint_A,cpoint )) + if (TEST_POINT(capsule_endpoint_A, cpoint)) return; - } - if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i))) + if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i))) return; } separator.generate_contacts(); } - ///////// +template <bool castA, bool castB, bool withMargin> +static void _collision_convex_polygon_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) { -template<bool castA, bool castB,bool withMargin> -static void _collision_convex_polygon_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) { - + const ConvexPolygonShape2DSW *convex_A = static_cast<const ConvexPolygonShape2DSW *>(p_a); + const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b); - const ConvexPolygonShape2DSW *convex_A = static_cast<const ConvexPolygonShape2DSW*>(p_a); - const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b); - - SeparatorAxisTest2D<ConvexPolygonShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(convex_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B); + SeparatorAxisTest2D<ConvexPolygonShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(convex_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B); if (!separator.test_previous_axis()) return; @@ -1265,345 +1191,332 @@ static void _collision_convex_polygon_convex_polygon(const Shape2DSW* p_a,const if (!separator.test_cast()) return; + for (int i = 0; i < convex_A->get_point_count(); i++) { - for(int i=0;i<convex_A->get_point_count();i++) { - - if (!separator.test_axis( convex_A->get_xformed_segment_normal(p_transform_a,i))) + if (!separator.test_axis(convex_A->get_xformed_segment_normal(p_transform_a, i))) return; } - for(int i=0;i<convex_B->get_point_count();i++) { + for (int i = 0; i < convex_B->get_point_count(); i++) { - if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i))) + if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i))) return; - } if (withMargin) { - for(int i=0;i<convex_A->get_point_count();i++) { - for(int j=0;j<convex_B->get_point_count();j++) { + for (int i = 0; i < convex_A->get_point_count(); i++) { + for (int j = 0; j < convex_B->get_point_count(); j++) { - if (TEST_POINT(p_transform_a.xform(convex_A->get_point(i)) , p_transform_b.xform(convex_B->get_point(j)))) + if (TEST_POINT(p_transform_a.xform(convex_A->get_point(i)), p_transform_b.xform(convex_B->get_point(j)))) return; } } - } separator.generate_contacts(); - } - //////// -bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D& p_transform_A, const Vector2& p_motion_A, const Shape2DSW *p_shape_B, const Transform2D& p_transform_B,const Vector2& p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap,Vector2 *sep_axis,real_t p_margin_A,real_t p_margin_B) { +bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { - Physics2DServer::ShapeType type_A=p_shape_A->get_type(); + Physics2DServer::ShapeType type_A = p_shape_A->get_type(); - ERR_FAIL_COND_V(type_A==Physics2DServer::SHAPE_LINE,false); + ERR_FAIL_COND_V(type_A == Physics2DServer::SHAPE_LINE, false); //ERR_FAIL_COND_V(type_A==Physics2DServer::SHAPE_RAY,false); - ERR_FAIL_COND_V(p_shape_A->is_concave(),false); + ERR_FAIL_COND_V(p_shape_A->is_concave(), false); - Physics2DServer::ShapeType type_B=p_shape_B->get_type(); + Physics2DServer::ShapeType type_B = p_shape_B->get_type(); - ERR_FAIL_COND_V(type_B==Physics2DServer::SHAPE_LINE,false); + ERR_FAIL_COND_V(type_B == Physics2DServer::SHAPE_LINE, false); //ERR_FAIL_COND_V(type_B==Physics2DServer::SHAPE_RAY,false); - ERR_FAIL_COND_V(p_shape_B->is_concave(),false); - - - static const CollisionFunc collision_table[5][5]={ - {_collision_segment_segment<false,false,false>, - _collision_segment_circle<false,false,false>, - _collision_segment_rectangle<false,false,false>, - _collision_segment_capsule<false,false,false>, - _collision_segment_convex_polygon<false,false,false>}, - {0, - _collision_circle_circle<false,false,false>, - _collision_circle_rectangle<false,false,false>, - _collision_circle_capsule<false,false,false>, - _collision_circle_convex_polygon<false,false,false>}, - {0, - 0, - _collision_rectangle_rectangle<false,false,false>, - _collision_rectangle_capsule<false,false,false>, - _collision_rectangle_convex_polygon<false,false,false>}, - {0, - 0, - 0, - _collision_capsule_capsule<false,false,false>, - _collision_capsule_convex_polygon<false,false,false>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<false,false,false>} + ERR_FAIL_COND_V(p_shape_B->is_concave(), false); + + static const CollisionFunc collision_table[5][5] = { + { _collision_segment_segment<false, false, false>, + _collision_segment_circle<false, false, false>, + _collision_segment_rectangle<false, false, false>, + _collision_segment_capsule<false, false, false>, + _collision_segment_convex_polygon<false, false, false> }, + { 0, + _collision_circle_circle<false, false, false>, + _collision_circle_rectangle<false, false, false>, + _collision_circle_capsule<false, false, false>, + _collision_circle_convex_polygon<false, false, false> }, + { 0, + 0, + _collision_rectangle_rectangle<false, false, false>, + _collision_rectangle_capsule<false, false, false>, + _collision_rectangle_convex_polygon<false, false, false> }, + { 0, + 0, + 0, + _collision_capsule_capsule<false, false, false>, + _collision_capsule_convex_polygon<false, false, false> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<false, false, false> } }; - static const CollisionFunc collision_table_castA[5][5]={ - {_collision_segment_segment<true,false,false>, - _collision_segment_circle<true,false,false>, - _collision_segment_rectangle<true,false,false>, - _collision_segment_capsule<true,false,false>, - _collision_segment_convex_polygon<true,false,false>}, - {0, - _collision_circle_circle<true,false,false>, - _collision_circle_rectangle<true,false,false>, - _collision_circle_capsule<true,false,false>, - _collision_circle_convex_polygon<true,false,false>}, - {0, - 0, - _collision_rectangle_rectangle<true,false,false>, - _collision_rectangle_capsule<true,false,false>, - _collision_rectangle_convex_polygon<true,false,false>}, - {0, - 0, - 0, - _collision_capsule_capsule<true,false,false>, - _collision_capsule_convex_polygon<true,false,false>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<true,false,false>} + static const CollisionFunc collision_table_castA[5][5] = { + { _collision_segment_segment<true, false, false>, + _collision_segment_circle<true, false, false>, + _collision_segment_rectangle<true, false, false>, + _collision_segment_capsule<true, false, false>, + _collision_segment_convex_polygon<true, false, false> }, + { 0, + _collision_circle_circle<true, false, false>, + _collision_circle_rectangle<true, false, false>, + _collision_circle_capsule<true, false, false>, + _collision_circle_convex_polygon<true, false, false> }, + { 0, + 0, + _collision_rectangle_rectangle<true, false, false>, + _collision_rectangle_capsule<true, false, false>, + _collision_rectangle_convex_polygon<true, false, false> }, + { 0, + 0, + 0, + _collision_capsule_capsule<true, false, false>, + _collision_capsule_convex_polygon<true, false, false> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<true, false, false> } }; - static const CollisionFunc collision_table_castB[5][5]={ - {_collision_segment_segment<false,true,false>, - _collision_segment_circle<false,true,false>, - _collision_segment_rectangle<false,true,false>, - _collision_segment_capsule<false,true,false>, - _collision_segment_convex_polygon<false,true,false>}, - {0, - _collision_circle_circle<false,true,false>, - _collision_circle_rectangle<false,true,false>, - _collision_circle_capsule<false,true,false>, - _collision_circle_convex_polygon<false,true,false>}, - {0, - 0, - _collision_rectangle_rectangle<false,true,false>, - _collision_rectangle_capsule<false,true,false>, - _collision_rectangle_convex_polygon<false,true,false>}, - {0, - 0, - 0, - _collision_capsule_capsule<false,true,false>, - _collision_capsule_convex_polygon<false,true,false>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<false,true,false>} + static const CollisionFunc collision_table_castB[5][5] = { + { _collision_segment_segment<false, true, false>, + _collision_segment_circle<false, true, false>, + _collision_segment_rectangle<false, true, false>, + _collision_segment_capsule<false, true, false>, + _collision_segment_convex_polygon<false, true, false> }, + { 0, + _collision_circle_circle<false, true, false>, + _collision_circle_rectangle<false, true, false>, + _collision_circle_capsule<false, true, false>, + _collision_circle_convex_polygon<false, true, false> }, + { 0, + 0, + _collision_rectangle_rectangle<false, true, false>, + _collision_rectangle_capsule<false, true, false>, + _collision_rectangle_convex_polygon<false, true, false> }, + { 0, + 0, + 0, + _collision_capsule_capsule<false, true, false>, + _collision_capsule_convex_polygon<false, true, false> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<false, true, false> } }; - static const CollisionFunc collision_table_castA_castB[5][5]={ - {_collision_segment_segment<true,true,false>, - _collision_segment_circle<true,true,false>, - _collision_segment_rectangle<true,true,false>, - _collision_segment_capsule<true,true,false>, - _collision_segment_convex_polygon<true,true,false>}, - {0, - _collision_circle_circle<true,true,false>, - _collision_circle_rectangle<true,true,false>, - _collision_circle_capsule<true,true,false>, - _collision_circle_convex_polygon<true,true,false>}, - {0, - 0, - _collision_rectangle_rectangle<true,true,false>, - _collision_rectangle_capsule<true,true,false>, - _collision_rectangle_convex_polygon<true,true,false>}, - {0, - 0, - 0, - _collision_capsule_capsule<true,true,false>, - _collision_capsule_convex_polygon<true,true,false>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<true,true,false>} + static const CollisionFunc collision_table_castA_castB[5][5] = { + { _collision_segment_segment<true, true, false>, + _collision_segment_circle<true, true, false>, + _collision_segment_rectangle<true, true, false>, + _collision_segment_capsule<true, true, false>, + _collision_segment_convex_polygon<true, true, false> }, + { 0, + _collision_circle_circle<true, true, false>, + _collision_circle_rectangle<true, true, false>, + _collision_circle_capsule<true, true, false>, + _collision_circle_convex_polygon<true, true, false> }, + { 0, + 0, + _collision_rectangle_rectangle<true, true, false>, + _collision_rectangle_capsule<true, true, false>, + _collision_rectangle_convex_polygon<true, true, false> }, + { 0, + 0, + 0, + _collision_capsule_capsule<true, true, false>, + _collision_capsule_convex_polygon<true, true, false> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<true, true, false> } }; - static const CollisionFunc collision_table_margin[5][5]={ - {_collision_segment_segment<false,false,true>, - _collision_segment_circle<false,false,true>, - _collision_segment_rectangle<false,false,true>, - _collision_segment_capsule<false,false,true>, - _collision_segment_convex_polygon<false,false,true>}, - {0, - _collision_circle_circle<false,false,true>, - _collision_circle_rectangle<false,false,true>, - _collision_circle_capsule<false,false,true>, - _collision_circle_convex_polygon<false,false,true>}, - {0, - 0, - _collision_rectangle_rectangle<false,false,true>, - _collision_rectangle_capsule<false,false,true>, - _collision_rectangle_convex_polygon<false,false,true>}, - {0, - 0, - 0, - _collision_capsule_capsule<false,false,true>, - _collision_capsule_convex_polygon<false,false,true>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<false,false,true>} + static const CollisionFunc collision_table_margin[5][5] = { + { _collision_segment_segment<false, false, true>, + _collision_segment_circle<false, false, true>, + _collision_segment_rectangle<false, false, true>, + _collision_segment_capsule<false, false, true>, + _collision_segment_convex_polygon<false, false, true> }, + { 0, + _collision_circle_circle<false, false, true>, + _collision_circle_rectangle<false, false, true>, + _collision_circle_capsule<false, false, true>, + _collision_circle_convex_polygon<false, false, true> }, + { 0, + 0, + _collision_rectangle_rectangle<false, false, true>, + _collision_rectangle_capsule<false, false, true>, + _collision_rectangle_convex_polygon<false, false, true> }, + { 0, + 0, + 0, + _collision_capsule_capsule<false, false, true>, + _collision_capsule_convex_polygon<false, false, true> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<false, false, true> } }; - static const CollisionFunc collision_table_castA_margin[5][5]={ - {_collision_segment_segment<true,false,true>, - _collision_segment_circle<true,false,true>, - _collision_segment_rectangle<true,false,true>, - _collision_segment_capsule<true,false,true>, - _collision_segment_convex_polygon<true,false,true>}, - {0, - _collision_circle_circle<true,false,true>, - _collision_circle_rectangle<true,false,true>, - _collision_circle_capsule<true,false,true>, - _collision_circle_convex_polygon<true,false,true>}, - {0, - 0, - _collision_rectangle_rectangle<true,false,true>, - _collision_rectangle_capsule<true,false,true>, - _collision_rectangle_convex_polygon<true,false,true>}, - {0, - 0, - 0, - _collision_capsule_capsule<true,false,true>, - _collision_capsule_convex_polygon<true,false,true>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<true,false,true>} + static const CollisionFunc collision_table_castA_margin[5][5] = { + { _collision_segment_segment<true, false, true>, + _collision_segment_circle<true, false, true>, + _collision_segment_rectangle<true, false, true>, + _collision_segment_capsule<true, false, true>, + _collision_segment_convex_polygon<true, false, true> }, + { 0, + _collision_circle_circle<true, false, true>, + _collision_circle_rectangle<true, false, true>, + _collision_circle_capsule<true, false, true>, + _collision_circle_convex_polygon<true, false, true> }, + { 0, + 0, + _collision_rectangle_rectangle<true, false, true>, + _collision_rectangle_capsule<true, false, true>, + _collision_rectangle_convex_polygon<true, false, true> }, + { 0, + 0, + 0, + _collision_capsule_capsule<true, false, true>, + _collision_capsule_convex_polygon<true, false, true> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<true, false, true> } }; - static const CollisionFunc collision_table_castB_margin[5][5]={ - {_collision_segment_segment<false,true,true>, - _collision_segment_circle<false,true,true>, - _collision_segment_rectangle<false,true,true>, - _collision_segment_capsule<false,true,true>, - _collision_segment_convex_polygon<false,true,true>}, - {0, - _collision_circle_circle<false,true,true>, - _collision_circle_rectangle<false,true,true>, - _collision_circle_capsule<false,true,true>, - _collision_circle_convex_polygon<false,true,true>}, - {0, - 0, - _collision_rectangle_rectangle<false,true,true>, - _collision_rectangle_capsule<false,true,true>, - _collision_rectangle_convex_polygon<false,true,true>}, - {0, - 0, - 0, - _collision_capsule_capsule<false,true,true>, - _collision_capsule_convex_polygon<false,true,true>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<false,true,true>} + static const CollisionFunc collision_table_castB_margin[5][5] = { + { _collision_segment_segment<false, true, true>, + _collision_segment_circle<false, true, true>, + _collision_segment_rectangle<false, true, true>, + _collision_segment_capsule<false, true, true>, + _collision_segment_convex_polygon<false, true, true> }, + { 0, + _collision_circle_circle<false, true, true>, + _collision_circle_rectangle<false, true, true>, + _collision_circle_capsule<false, true, true>, + _collision_circle_convex_polygon<false, true, true> }, + { 0, + 0, + _collision_rectangle_rectangle<false, true, true>, + _collision_rectangle_capsule<false, true, true>, + _collision_rectangle_convex_polygon<false, true, true> }, + { 0, + 0, + 0, + _collision_capsule_capsule<false, true, true>, + _collision_capsule_convex_polygon<false, true, true> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<false, true, true> } }; - static const CollisionFunc collision_table_castA_castB_margin[5][5]={ - {_collision_segment_segment<true,true,true>, - _collision_segment_circle<true,true,true>, - _collision_segment_rectangle<true,true,true>, - _collision_segment_capsule<true,true,true>, - _collision_segment_convex_polygon<true,true,true>}, - {0, - _collision_circle_circle<true,true,true>, - _collision_circle_rectangle<true,true,true>, - _collision_circle_capsule<true,true,true>, - _collision_circle_convex_polygon<true,true,true>}, - {0, - 0, - _collision_rectangle_rectangle<true,true,true>, - _collision_rectangle_capsule<true,true,true>, - _collision_rectangle_convex_polygon<true,true,true>}, - {0, - 0, - 0, - _collision_capsule_capsule<true,true,true>, - _collision_capsule_convex_polygon<true,true,true>}, - {0, - 0, - 0, - 0, - _collision_convex_polygon_convex_polygon<true,true,true>} + static const CollisionFunc collision_table_castA_castB_margin[5][5] = { + { _collision_segment_segment<true, true, true>, + _collision_segment_circle<true, true, true>, + _collision_segment_rectangle<true, true, true>, + _collision_segment_capsule<true, true, true>, + _collision_segment_convex_polygon<true, true, true> }, + { 0, + _collision_circle_circle<true, true, true>, + _collision_circle_rectangle<true, true, true>, + _collision_circle_capsule<true, true, true>, + _collision_circle_convex_polygon<true, true, true> }, + { 0, + 0, + _collision_rectangle_rectangle<true, true, true>, + _collision_rectangle_capsule<true, true, true>, + _collision_rectangle_convex_polygon<true, true, true> }, + { 0, + 0, + 0, + _collision_capsule_capsule<true, true, true>, + _collision_capsule_convex_polygon<true, true, true> }, + { 0, + 0, + 0, + 0, + _collision_convex_polygon_convex_polygon<true, true, true> } }; - _CollectorCallback2D callback; - callback.callback=p_result_callback; - callback.swap=p_swap; - callback.userdata=p_userdata; - callback.collided=false; - callback.sep_axis=sep_axis; - - const Shape2DSW *A=p_shape_A; - const Shape2DSW *B=p_shape_B; - const Transform2D *transform_A=&p_transform_A; - const Transform2D *transform_B=&p_transform_B; - const Vector2 *motion_A=&p_motion_A; - const Vector2 *motion_B=&p_motion_B; - real_t margin_A=p_margin_A,margin_B=p_margin_B; + callback.callback = p_result_callback; + callback.swap = p_swap; + callback.userdata = p_userdata; + callback.collided = false; + callback.sep_axis = sep_axis; + + const Shape2DSW *A = p_shape_A; + const Shape2DSW *B = p_shape_B; + const Transform2D *transform_A = &p_transform_A; + const Transform2D *transform_B = &p_transform_B; + const Vector2 *motion_A = &p_motion_A; + const Vector2 *motion_B = &p_motion_B; + real_t margin_A = p_margin_A, margin_B = p_margin_B; if (type_A > type_B) { - SWAP(A,B); - SWAP(transform_A,transform_B); - SWAP(type_A,type_B); - SWAP(motion_A,motion_B); - SWAP(margin_A,margin_B); + SWAP(A, B); + SWAP(transform_A, transform_B); + SWAP(type_A, type_B); + SWAP(motion_A, motion_B); + SWAP(margin_A, margin_B); callback.swap = !callback.swap; } - CollisionFunc collision_func; if (p_margin_A || p_margin_B) { - if (*motion_A==Vector2() && *motion_B==Vector2()) { - collision_func = collision_table_margin[type_A-2][type_B-2]; - } else if (*motion_A!=Vector2() && *motion_B==Vector2()) { - collision_func = collision_table_castA_margin[type_A-2][type_B-2]; - } else if (*motion_A==Vector2() && *motion_B!=Vector2()) { - collision_func = collision_table_castB_margin[type_A-2][type_B-2]; + if (*motion_A == Vector2() && *motion_B == Vector2()) { + collision_func = collision_table_margin[type_A - 2][type_B - 2]; + } else if (*motion_A != Vector2() && *motion_B == Vector2()) { + collision_func = collision_table_castA_margin[type_A - 2][type_B - 2]; + } else if (*motion_A == Vector2() && *motion_B != Vector2()) { + collision_func = collision_table_castB_margin[type_A - 2][type_B - 2]; } else { - collision_func = collision_table_castA_castB_margin[type_A-2][type_B-2]; + collision_func = collision_table_castA_castB_margin[type_A - 2][type_B - 2]; } } else { - if (*motion_A==Vector2() && *motion_B==Vector2()) { - collision_func = collision_table[type_A-2][type_B-2]; - } else if (*motion_A!=Vector2() && *motion_B==Vector2()) { - collision_func = collision_table_castA[type_A-2][type_B-2]; - } else if (*motion_A==Vector2() && *motion_B!=Vector2()) { - collision_func = collision_table_castB[type_A-2][type_B-2]; + if (*motion_A == Vector2() && *motion_B == Vector2()) { + collision_func = collision_table[type_A - 2][type_B - 2]; + } else if (*motion_A != Vector2() && *motion_B == Vector2()) { + collision_func = collision_table_castA[type_A - 2][type_B - 2]; + } else if (*motion_A == Vector2() && *motion_B != Vector2()) { + collision_func = collision_table_castB[type_A - 2][type_B - 2]; } else { - collision_func = collision_table_castA_castB[type_A-2][type_B-2]; + collision_func = collision_table_castA_castB[type_A - 2][type_B - 2]; } - } + ERR_FAIL_COND_V(!collision_func, false); - - ERR_FAIL_COND_V(!collision_func,false); - - collision_func(A,*transform_A,B,*transform_B,&callback,*motion_A,*motion_B,margin_A,margin_B); + collision_func(A, *transform_A, B, *transform_B, &callback, *motion_A, *motion_B, margin_A, margin_B); return callback.collided; - - } diff --git a/servers/physics_2d/collision_solver_2d_sat.h b/servers/physics_2d/collision_solver_2d_sat.h index 6b698a09f2..a13c3dd14d 100644 --- a/servers/physics_2d/collision_solver_2d_sat.h +++ b/servers/physics_2d/collision_solver_2d_sat.h @@ -31,7 +31,6 @@ #include "collision_solver_2d_sw.h" - -bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D& p_transform_A, const Vector2& p_motion_A,const Shape2DSW *p_shape_B, const Transform2D& p_transform_B,const Vector2& p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap=false,Vector2 *sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0); +bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap = false, Vector2 *sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0); #endif // COLLISION_SOLVER_2D_SAT_H diff --git a/servers/physics_2d/collision_solver_2d_sw.cpp b/servers/physics_2d/collision_solver_2d_sw.cpp index 3fdecdf413..6218af72a1 100644 --- a/servers/physics_2d/collision_solver_2d_sw.cpp +++ b/servers/physics_2d/collision_solver_2d_sw.cpp @@ -29,89 +29,78 @@ #include "collision_solver_2d_sw.h" #include "collision_solver_2d_sat.h" - #define collision_solver sat_2d_calculate_penetration //#define collision_solver gjk_epa_calculate_penetration +bool CollisionSolver2DSW::solve_static_line(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) { -bool CollisionSolver2DSW::solve_static_line(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result) { - - - const LineShape2DSW *line = static_cast<const LineShape2DSW*>(p_shape_A); - if (p_shape_B->get_type()==Physics2DServer::SHAPE_LINE) + const LineShape2DSW *line = static_cast<const LineShape2DSW *>(p_shape_A); + if (p_shape_B->get_type() == Physics2DServer::SHAPE_LINE) return false; - Vector2 n = p_transform_A.basis_xform(line->get_normal()).normalized(); - Vector2 p = p_transform_A.xform(line->get_normal()*line->get_d()); + Vector2 p = p_transform_A.xform(line->get_normal() * line->get_d()); real_t d = n.dot(p); Vector2 supports[2]; int support_count; - p_shape_B->get_supports(p_transform_A.affine_inverse().basis_xform(-n).normalized(),supports,support_count); - - bool found=false; + p_shape_B->get_supports(p_transform_A.affine_inverse().basis_xform(-n).normalized(), supports, support_count); + bool found = false; - for(int i=0;i<support_count;i++) { + for (int i = 0; i < support_count; i++) { - supports[i] = p_transform_B.xform( supports[i] ); + supports[i] = p_transform_B.xform(supports[i]); real_t pd = n.dot(supports[i]); - if (pd>=d) + if (pd >= d) continue; - found=true; + found = true; - Vector2 support_A = supports[i] - n*(pd-d); + Vector2 support_A = supports[i] - n * (pd - d); if (p_result_callback) { if (p_swap_result) - p_result_callback(supports[i],support_A,p_userdata); + p_result_callback(supports[i], support_A, p_userdata); else - p_result_callback(support_A,supports[i],p_userdata); + p_result_callback(support_A, supports[i], p_userdata); } - } - return found; } -bool CollisionSolver2DSW::solve_raycast(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis) { - +bool CollisionSolver2DSW::solve_raycast(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis) { - - const RayShape2DSW *ray = static_cast<const RayShape2DSW*>(p_shape_A); - if (p_shape_B->get_type()==Physics2DServer::SHAPE_RAY) + const RayShape2DSW *ray = static_cast<const RayShape2DSW *>(p_shape_A); + if (p_shape_B->get_type() == Physics2DServer::SHAPE_RAY) return false; Vector2 from = p_transform_A.get_origin(); - Vector2 to = from+p_transform_A[1]*ray->get_length(); - Vector2 support_A=to; + Vector2 to = from + p_transform_A[1] * ray->get_length(); + Vector2 support_A = to; Transform2D invb = p_transform_B.affine_inverse(); from = invb.xform(from); to = invb.xform(to); - Vector2 p,n; - if (!p_shape_B->intersect_segment(from,to,p,n)) { + Vector2 p, n; + if (!p_shape_B->intersect_segment(from, to, p, n)) { if (sep_axis) - *sep_axis=p_transform_A[1].normalized(); + *sep_axis = p_transform_A[1].normalized(); return false; } - - Vector2 support_B=p_transform_B.xform(p); + Vector2 support_B = p_transform_B.xform(p); if (p_result_callback) { if (p_swap_result) - p_result_callback(support_B,support_A,p_userdata); + p_result_callback(support_B, support_A, p_userdata); else - p_result_callback(support_A,support_B,p_userdata); + p_result_callback(support_A, support_B, p_userdata); } return true; - } /* @@ -159,101 +148,90 @@ struct _ConcaveCollisionInfo2D { int aabb_tests; int collisions; Vector2 *sep_axis; - }; void CollisionSolver2DSW::concave_callback(void *p_userdata, Shape2DSW *p_convex) { - - - _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D*)(p_userdata); + _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D *)(p_userdata); cinfo.aabb_tests++; if (!cinfo.result_callback && cinfo.collided) return; //already collided and no contacts requested, don't test anymore - bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex,*cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result,cinfo.sep_axis,cinfo.margin_A,cinfo.margin_B ); + bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex, *cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, cinfo.sep_axis, cinfo.margin_A, cinfo.margin_B); if (!collided) return; - - cinfo.collided=true; + cinfo.collided = true; cinfo.collisions++; - } -bool CollisionSolver2DSW::solve_concave(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis,real_t p_margin_A,real_t p_margin_B) { +bool CollisionSolver2DSW::solve_concave(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { - - const ConcaveShape2DSW *concave_B=static_cast<const ConcaveShape2DSW*>(p_shape_B); + const ConcaveShape2DSW *concave_B = static_cast<const ConcaveShape2DSW *>(p_shape_B); _ConcaveCollisionInfo2D cinfo; - cinfo.transform_A=&p_transform_A; - cinfo.shape_A=p_shape_A; - cinfo.transform_B=&p_transform_B; - cinfo.motion_A=p_motion_A; - cinfo.result_callback=p_result_callback; - cinfo.userdata=p_userdata; - cinfo.swap_result=p_swap_result; - cinfo.collided=false; - cinfo.collisions=0; - cinfo.sep_axis=sep_axis; - cinfo.margin_A=p_margin_A; - cinfo.margin_B=p_margin_B; - - cinfo.aabb_tests=0; + cinfo.transform_A = &p_transform_A; + cinfo.shape_A = p_shape_A; + cinfo.transform_B = &p_transform_B; + cinfo.motion_A = p_motion_A; + cinfo.result_callback = p_result_callback; + cinfo.userdata = p_userdata; + cinfo.swap_result = p_swap_result; + cinfo.collided = false; + cinfo.collisions = 0; + cinfo.sep_axis = sep_axis; + cinfo.margin_A = p_margin_A; + cinfo.margin_B = p_margin_B; + + cinfo.aabb_tests = 0; Transform2D rel_transform = p_transform_A; - rel_transform.elements[2]-=p_transform_B.get_origin(); + rel_transform.elements[2] -= p_transform_B.get_origin(); //quickly compute a local Rect2 Rect2 local_aabb; - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - Vector2 axis( p_transform_B.elements[i] ); - real_t axis_scale = 1.0/axis.length(); - axis*=axis_scale; + Vector2 axis(p_transform_B.elements[i]); + real_t axis_scale = 1.0 / axis.length(); + axis *= axis_scale; - real_t smin,smax; - p_shape_A->project_rangev(axis,rel_transform,smin,smax); - smin*=axis_scale; - smax*=axis_scale; + real_t smin, smax; + p_shape_A->project_rangev(axis, rel_transform, smin, smax); + smin *= axis_scale; + smax *= axis_scale; - local_aabb.pos[i]=smin; - local_aabb.size[i]=smax-smin; + local_aabb.pos[i] = smin; + local_aabb.size[i] = smax - smin; } - concave_B->cull(local_aabb,concave_callback,&cinfo); - + concave_B->cull(local_aabb, concave_callback, &cinfo); //print_line("Rect2 TESTS: "+itos(cinfo.aabb_tests)); return cinfo.collided; } +bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { -bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,Vector2 *sep_axis,real_t p_margin_A,real_t p_margin_B) { - - - - - Physics2DServer::ShapeType type_A=p_shape_A->get_type(); - Physics2DServer::ShapeType type_B=p_shape_B->get_type(); - bool concave_A=p_shape_A->is_concave(); - bool concave_B=p_shape_B->is_concave(); - real_t margin_A=p_margin_A,margin_B=p_margin_B; + Physics2DServer::ShapeType type_A = p_shape_A->get_type(); + Physics2DServer::ShapeType type_B = p_shape_B->get_type(); + bool concave_A = p_shape_A->is_concave(); + bool concave_B = p_shape_B->is_concave(); + real_t margin_A = p_margin_A, margin_B = p_margin_B; bool swap = false; - if (type_A>type_B) { - SWAP(type_A,type_B); - SWAP(concave_A,concave_B); - SWAP(margin_A,margin_B); - swap=true; + if (type_A > type_B) { + SWAP(type_A, type_B); + SWAP(concave_A, concave_B); + SWAP(margin_A, margin_B); + swap = true; } - if (type_A==Physics2DServer::SHAPE_LINE) { + if (type_A == Physics2DServer::SHAPE_LINE) { - if (type_B==Physics2DServer::SHAPE_LINE || type_B==Physics2DServer::SHAPE_RAY) { + if (type_B == Physics2DServer::SHAPE_LINE || type_B == Physics2DServer::SHAPE_RAY) { return false; } /* @@ -262,12 +240,12 @@ bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A,const Transform2D& p_ */ if (swap) { - return solve_static_line(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true); + return solve_static_line(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true); } else { - return solve_static_line(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false); + return solve_static_line(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false); } - /*} else if (type_A==Physics2DServer::SHAPE_RAY) { + /*} else if (type_A==Physics2DServer::SHAPE_RAY) { if (type_B==Physics2DServer::SHAPE_RAY) return false; @@ -278,41 +256,33 @@ bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A,const Transform2D& p_ return solve_ray(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_inverse_B,p_result_callback,p_userdata,false); } */ - } else if (type_A==Physics2DServer::SHAPE_RAY) { + } else if (type_A == Physics2DServer::SHAPE_RAY) { - if (type_B==Physics2DServer::SHAPE_RAY) { + if (type_B == Physics2DServer::SHAPE_RAY) { return false; //no ray-ray } - if (swap) { - return solve_raycast(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true,sep_axis); + return solve_raycast(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true, sep_axis); } else { - return solve_raycast(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false,sep_axis); + return solve_raycast(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, sep_axis); } - } else if (concave_B) { - if (concave_A) return false; if (!swap) - return solve_concave(p_shape_A,p_transform_A,p_motion_A,p_shape_B,p_transform_B,p_motion_B,p_result_callback,p_userdata,false,sep_axis,margin_A,margin_B); + return solve_concave(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B); else - return solve_concave(p_shape_B,p_transform_B,p_motion_B,p_shape_A,p_transform_A,p_motion_A,p_result_callback,p_userdata,true,sep_axis,margin_A,margin_B); - - + return solve_concave(p_shape_B, p_transform_B, p_motion_B, p_shape_A, p_transform_A, p_motion_A, p_result_callback, p_userdata, true, sep_axis, margin_A, margin_B); } else { - - return collision_solver(p_shape_A, p_transform_A,p_motion_A, p_shape_B, p_transform_B, p_motion_B,p_result_callback,p_userdata,false,sep_axis,margin_A,margin_B); + return collision_solver(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B); } - return false; } - diff --git a/servers/physics_2d/collision_solver_2d_sw.h b/servers/physics_2d/collision_solver_2d_sw.h index 2a5fc9fe1d..886cb90ace 100644 --- a/servers/physics_2d/collision_solver_2d_sw.h +++ b/servers/physics_2d/collision_solver_2d_sw.h @@ -33,20 +33,16 @@ class CollisionSolver2DSW { public: - typedef void (*CallbackResult)(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata); + typedef void (*CallbackResult)(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata); + private: - static bool solve_static_line(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result); + static bool solve_static_line(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result); static void concave_callback(void *p_userdata, Shape2DSW *p_convex); - static bool solve_concave(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0); - static bool solve_raycast(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis=NULL); - - + static bool solve_concave(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0); + static bool solve_raycast(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis = NULL); public: - - static bool solve(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,Vector2 *sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0); - - + static bool solve(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, Vector2 *sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0); }; #endif // COLLISION_SOLVER_2D_SW_H diff --git a/servers/physics_2d/constraint_2d_sw.h b/servers/physics_2d/constraint_2d_sw.h index cce668405c..659b5b3219 100644 --- a/servers/physics_2d/constraint_2d_sw.h +++ b/servers/physics_2d/constraint_2d_sw.h @@ -39,32 +39,33 @@ class Constraint2DSW : public RID_Data { Constraint2DSW *island_next; Constraint2DSW *island_list_next; - RID self; protected: - Constraint2DSW(Body2DSW **p_body_ptr=NULL,int p_body_count=0) { _body_ptr=p_body_ptr; _body_count=p_body_count; island_step=0; } -public: + Constraint2DSW(Body2DSW **p_body_ptr = NULL, int p_body_count = 0) { + _body_ptr = p_body_ptr; + _body_count = p_body_count; + island_step = 0; + } - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } +public: + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } _FORCE_INLINE_ RID get_self() const { return self; } _FORCE_INLINE_ uint64_t get_island_step() const { return island_step; } - _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; } + _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; } + _FORCE_INLINE_ Constraint2DSW *get_island_next() const { return island_next; } + _FORCE_INLINE_ void set_island_next(Constraint2DSW *p_next) { island_next = p_next; } - _FORCE_INLINE_ Constraint2DSW* get_island_next() const { return island_next; } - _FORCE_INLINE_ void set_island_next(Constraint2DSW* p_next) { island_next=p_next; } - - _FORCE_INLINE_ Constraint2DSW* get_island_list_next() const { return island_list_next; } - _FORCE_INLINE_ void set_island_list_next(Constraint2DSW* p_next) { island_list_next=p_next; } + _FORCE_INLINE_ Constraint2DSW *get_island_list_next() const { return island_list_next; } + _FORCE_INLINE_ void set_island_list_next(Constraint2DSW *p_next) { island_list_next = p_next; } _FORCE_INLINE_ Body2DSW **get_body_ptr() const { return _body_ptr; } _FORCE_INLINE_ int get_body_count() const { return _body_count; } - - virtual bool setup(real_t p_step)=0; - virtual void solve(real_t p_step)=0; + virtual bool setup(real_t p_step) = 0; + virtual void solve(real_t p_step) = 0; virtual ~Constraint2DSW() {} }; diff --git a/servers/physics_2d/joints_2d_sw.cpp b/servers/physics_2d/joints_2d_sw.cpp index 76adf06429..0277586495 100644 --- a/servers/physics_2d/joints_2d_sw.cpp +++ b/servers/physics_2d/joints_2d_sw.cpp @@ -52,40 +52,37 @@ * SOFTWARE. */ -static inline real_t k_scalar(Body2DSW *a,Body2DSW *b,const Vector2& rA, const Vector2& rB, const Vector2& n) { - - - real_t value=0; +static inline real_t k_scalar(Body2DSW *a, Body2DSW *b, const Vector2 &rA, const Vector2 &rB, const Vector2 &n) { + real_t value = 0; { - value+=a->get_inv_mass(); + value += a->get_inv_mass(); real_t rcn = rA.cross(n); - value+=a->get_inv_inertia() * rcn * rcn; + value += a->get_inv_inertia() * rcn * rcn; } if (b) { - value+=b->get_inv_mass(); + value += b->get_inv_mass(); real_t rcn = rB.cross(n); - value+=b->get_inv_inertia() * rcn * rcn; + value += b->get_inv_inertia() * rcn * rcn; } return value; - } static inline Vector2 -relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB){ - Vector2 sum = a->get_linear_velocity() -rA.tangent() * a->get_angular_velocity(); +relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB) { + Vector2 sum = a->get_linear_velocity() - rA.tangent() * a->get_angular_velocity(); if (b) - return (b->get_linear_velocity() -rB.tangent() * b->get_angular_velocity()) - sum; + return (b->get_linear_velocity() - rB.tangent() * b->get_angular_velocity()) - sum; else return -sum; } static inline real_t -normal_relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB, Vector2 n){ +normal_relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB, Vector2 n) { return relative_velocity(a, b, rA, rB).dot(n); } @@ -188,13 +185,12 @@ PinJoint2DSW::~PinJoint2DSW() { #else - bool PinJoint2DSW::setup(real_t p_step) { Space2DSW *space = A->get_space(); - ERR_FAIL_COND_V(!space,false;) + ERR_FAIL_COND_V(!space, false;) rA = A->get_transform().basis_xform(anchor_A); - rB = B?B->get_transform().basis_xform(anchor_B):anchor_B; + rB = B ? B->get_transform().basis_xform(anchor_B) : anchor_B; #if 0 Vector2 gA = rA+A->get_transform().get_origin(); Vector2 gB = B?rB+B->get_transform().get_origin():rB; @@ -212,29 +208,34 @@ bool PinJoint2DSW::setup(real_t p_step) { // = [1/m1+1/m2 0 ] + invI1 * [rA.y*rA.y -rA.x*rA.y] + invI2 * [rA.y*rA.y -rA.x*rA.y] // [ 0 1/m1+1/m2] [-rA.x*rA.y rA.x*rA.x] [-rA.x*rA.y rA.x*rA.x] - real_t B_inv_mass = B?B->get_inv_mass():0.0; - + real_t B_inv_mass = B ? B->get_inv_mass() : 0.0; Transform2D K1; - K1[0].x = A->get_inv_mass() + B_inv_mass; K1[1].x = 0.0f; - K1[0].y = 0.0f; K1[1].y = A->get_inv_mass() + B_inv_mass; + K1[0].x = A->get_inv_mass() + B_inv_mass; + K1[1].x = 0.0f; + K1[0].y = 0.0f; + K1[1].y = A->get_inv_mass() + B_inv_mass; Transform2D K2; - K2[0].x = A->get_inv_inertia() * rA.y * rA.y; K2[1].x = -A->get_inv_inertia() * rA.x * rA.y; - K2[0].y = -A->get_inv_inertia() * rA.x * rA.y; K2[1].y = A->get_inv_inertia() * rA.x * rA.x; + K2[0].x = A->get_inv_inertia() * rA.y * rA.y; + K2[1].x = -A->get_inv_inertia() * rA.x * rA.y; + K2[0].y = -A->get_inv_inertia() * rA.x * rA.y; + K2[1].y = A->get_inv_inertia() * rA.x * rA.x; Transform2D K; - K[0]= K1[0] + K2[0]; - K[1]= K1[1] + K2[1]; + K[0] = K1[0] + K2[0]; + K[1] = K1[1] + K2[1]; if (B) { Transform2D K3; - K3[0].x = B->get_inv_inertia() * rB.y * rB.y; K3[1].x = -B->get_inv_inertia() * rB.x * rB.y; - K3[0].y = -B->get_inv_inertia() * rB.x * rB.y; K3[1].y = B->get_inv_inertia() * rB.x * rB.x; + K3[0].x = B->get_inv_inertia() * rB.y * rB.y; + K3[1].x = -B->get_inv_inertia() * rB.x * rB.y; + K3[0].y = -B->get_inv_inertia() * rB.x * rB.y; + K3[1].y = B->get_inv_inertia() * rB.x * rB.x; - K[0]+=K3[0]; - K[1]+=K3[1]; + K[0] += K3[0]; + K[1] += K3[1]; } K[0].x += softness; @@ -242,23 +243,22 @@ bool PinJoint2DSW::setup(real_t p_step) { M = K.affine_inverse(); - Vector2 gA = rA+A->get_transform().get_origin(); - Vector2 gB = B?rB+B->get_transform().get_origin():rB; + Vector2 gA = rA + A->get_transform().get_origin(); + Vector2 gB = B ? rB + B->get_transform().get_origin() : rB; Vector2 delta = gB - gA; - bias = delta*-(get_bias()==0?space->get_constraint_bias():get_bias())*(1.0/p_step); + bias = delta * -(get_bias() == 0 ? space->get_constraint_bias() : get_bias()) * (1.0 / p_step); // apply accumulated impulse - A->apply_impulse(rA,-P); + A->apply_impulse(rA, -P); if (B) - B->apply_impulse(rB,P); + B->apply_impulse(rB, P); return true; } -void PinJoint2DSW::solve(real_t p_step){ - +void PinJoint2DSW::solve(real_t p_step) { // compute relative velocity Vector2 vA = A->get_linear_velocity() - rA.cross(A->get_angular_velocity()); @@ -269,114 +269,110 @@ void PinJoint2DSW::solve(real_t p_step){ else rel_vel = -vA; - Vector2 impulse = M.basis_xform(bias - rel_vel - Vector2(softness,softness) * P); + Vector2 impulse = M.basis_xform(bias - rel_vel - Vector2(softness, softness) * P); - A->apply_impulse(rA,-impulse); + A->apply_impulse(rA, -impulse); if (B) - B->apply_impulse(rB,impulse); - + B->apply_impulse(rB, impulse); P += impulse; } void PinJoint2DSW::set_param(Physics2DServer::PinJointParam p_param, real_t p_value) { - if(p_param == Physics2DServer::PIN_JOINT_SOFTNESS) + if (p_param == Physics2DServer::PIN_JOINT_SOFTNESS) softness = p_value; } real_t PinJoint2DSW::get_param(Physics2DServer::PinJointParam p_param) const { - if(p_param == Physics2DServer::PIN_JOINT_SOFTNESS) + if (p_param == Physics2DServer::PIN_JOINT_SOFTNESS) return softness; ERR_FAIL_V(0); } -PinJoint2DSW::PinJoint2DSW(const Vector2& p_pos,Body2DSW* p_body_a,Body2DSW* p_body_b) : Joint2DSW(_arr,p_body_b?2:1) { +PinJoint2DSW::PinJoint2DSW(const Vector2 &p_pos, Body2DSW *p_body_a, Body2DSW *p_body_b) + : Joint2DSW(_arr, p_body_b ? 2 : 1) { - A=p_body_a; - B=p_body_b; + A = p_body_a; + B = p_body_b; anchor_A = p_body_a->get_inv_transform().xform(p_pos); - anchor_B = p_body_b?p_body_b->get_inv_transform().xform(p_pos):p_pos; + anchor_B = p_body_b ? p_body_b->get_inv_transform().xform(p_pos) : p_pos; - softness=0; + softness = 0; - p_body_a->add_constraint(this,0); + p_body_a->add_constraint(this, 0); if (p_body_b) - p_body_b->add_constraint(this,1); - + p_body_b->add_constraint(this, 1); } - - PinJoint2DSW::~PinJoint2DSW() { if (A) A->remove_constraint(this); if (B) B->remove_constraint(this); - } - - #endif ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////////////////////////////////////// - static inline void -k_tensor(Body2DSW *a, Body2DSW *b, Vector2 r1, Vector2 r2, Vector2 *k1, Vector2 *k2) -{ +k_tensor(Body2DSW *a, Body2DSW *b, Vector2 r1, Vector2 r2, Vector2 *k1, Vector2 *k2) { // calculate mass matrix // If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross... real_t k11, k12, k21, k22; real_t m_sum = a->get_inv_mass() + b->get_inv_mass(); // start with I*m_sum - k11 = m_sum; k12 = 0.0f; - k21 = 0.0f; k22 = m_sum; + k11 = m_sum; + k12 = 0.0f; + k21 = 0.0f; + k22 = m_sum; // add the influence from r1 real_t a_i_inv = a->get_inv_inertia(); - real_t r1xsq = r1.x * r1.x * a_i_inv; - real_t r1ysq = r1.y * r1.y * a_i_inv; + real_t r1xsq = r1.x * r1.x * a_i_inv; + real_t r1ysq = r1.y * r1.y * a_i_inv; real_t r1nxy = -r1.x * r1.y * a_i_inv; - k11 += r1ysq; k12 += r1nxy; - k21 += r1nxy; k22 += r1xsq; + k11 += r1ysq; + k12 += r1nxy; + k21 += r1nxy; + k22 += r1xsq; // add the influnce from r2 real_t b_i_inv = b->get_inv_inertia(); - real_t r2xsq = r2.x * r2.x * b_i_inv; - real_t r2ysq = r2.y * r2.y * b_i_inv; + real_t r2xsq = r2.x * r2.x * b_i_inv; + real_t r2ysq = r2.y * r2.y * b_i_inv; real_t r2nxy = -r2.x * r2.y * b_i_inv; - k11 += r2ysq; k12 += r2nxy; - k21 += r2nxy; k22 += r2xsq; + k11 += r2ysq; + k12 += r2nxy; + k21 += r2nxy; + k22 += r2xsq; // invert - real_t determinant = k11*k22 - k12*k21; - ERR_FAIL_COND(determinant== 0.0); + real_t determinant = k11 * k22 - k12 * k21; + ERR_FAIL_COND(determinant == 0.0); - real_t det_inv = 1.0f/determinant; - *k1 = Vector2( k22*det_inv, -k12*det_inv); - *k2 = Vector2(-k21*det_inv, k11*det_inv); + real_t det_inv = 1.0f / determinant; + *k1 = Vector2(k22 * det_inv, -k12 * det_inv); + *k2 = Vector2(-k21 * det_inv, k11 * det_inv); } static _FORCE_INLINE_ Vector2 -mult_k(const Vector2& vr, const Vector2 &k1, const Vector2 &k2) -{ +mult_k(const Vector2 &vr, const Vector2 &k1, const Vector2 &k2) { return Vector2(vr.dot(k1), vr.dot(k2)); } bool GrooveJoint2DSW::setup(real_t p_step) { - // calculate endpoints in worldspace Vector2 ta = A->get_transform().xform(A_groove_1); Vector2 tb = A->get_transform().xform(A_groove_2); - Space2DSW *space=A->get_space(); + Space2DSW *space = A->get_space(); // calculate axis Vector2 n = -(tb - ta).tangent().normalized(); @@ -388,16 +384,16 @@ bool GrooveJoint2DSW::setup(real_t p_step) { // calculate tangential distance along the axis of rB real_t td = (B->get_transform().get_origin() + rB).cross(n); // calculate clamping factor and rB - if(td <= ta.cross(n)){ + if (td <= ta.cross(n)) { clamp = 1.0f; rA = ta - A->get_transform().get_origin(); - } else if(td >= tb.cross(n)){ + } else if (td >= tb.cross(n)) { clamp = -1.0f; rA = tb - A->get_transform().get_origin(); } else { clamp = 0.0f; //joint->r1 = cpvsub(cpvadd(cpvmult(cpvperp(n), -td), cpvmult(n, d)), a->p); - rA = ((-n.tangent() * -td) + n*d) - A->get_transform().get_origin(); + rA = ((-n.tangent() * -td) + n * d) - A->get_transform().get_origin(); } // Calculate mass tensor @@ -410,52 +406,49 @@ bool GrooveJoint2DSW::setup(real_t p_step) { //cpVect delta = cpvsub(cpvadd(b->p, joint->r2), cpvadd(a->p, joint->r1)); //joint->bias = cpvclamp(cpvmult(delta, -joint->constraint.biasCoef*dt_inv), joint->constraint.maxBias); - - Vector2 delta = (B->get_transform().get_origin() +rB) - (A->get_transform().get_origin() + rA); + Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA); real_t _b = get_bias(); - _b=0.001; - gbias=(delta*-(_b==0?space->get_constraint_bias():_b)*(1.0/p_step)).clamped(get_max_bias()); + _b = 0.001; + gbias = (delta * -(_b == 0 ? space->get_constraint_bias() : _b) * (1.0 / p_step)).clamped(get_max_bias()); // apply accumulated impulse - A->apply_impulse(rA,-jn_acc); - B->apply_impulse(rB,jn_acc); + A->apply_impulse(rA, -jn_acc); + B->apply_impulse(rB, jn_acc); - correct=true; + correct = true; return true; } -void GrooveJoint2DSW::solve(real_t p_step){ - +void GrooveJoint2DSW::solve(real_t p_step) { // compute impulse - Vector2 vr = relative_velocity(A, B, rA,rB); + Vector2 vr = relative_velocity(A, B, rA, rB); - Vector2 j = mult_k(gbias-vr, k1, k2); + Vector2 j = mult_k(gbias - vr, k1, k2); Vector2 jOld = jn_acc; - j+=jOld; + j += jOld; jn_acc = (((clamp * j.cross(xf_normal)) > 0) ? j : xf_normal.project(j)).clamped(jn_max); j = jn_acc - jOld; - A->apply_impulse(rA,-j); - B->apply_impulse(rB,j); + A->apply_impulse(rA, -j); + B->apply_impulse(rB, j); } +GrooveJoint2DSW::GrooveJoint2DSW(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, Body2DSW *p_body_a, Body2DSW *p_body_b) + : Joint2DSW(_arr, 2) { -GrooveJoint2DSW::GrooveJoint2DSW(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, Body2DSW* p_body_a,Body2DSW* p_body_b) : Joint2DSW(_arr,2) { - - A=p_body_a; - B=p_body_b; + A = p_body_a; + B = p_body_b; A_groove_1 = A->get_inv_transform().xform(p_a_groove1); A_groove_2 = A->get_inv_transform().xform(p_a_groove2); - B_anchor=B->get_inv_transform().xform(p_b_anchor); + B_anchor = B->get_inv_transform().xform(p_b_anchor); A_groove_normal = -(A_groove_2 - A_groove_1).normalized().tangent(); - A->add_constraint(this,0); - B->add_constraint(this,1); - + A->add_constraint(this, 0); + B->add_constraint(this, 1); } GrooveJoint2DSW::~GrooveJoint2DSW() { @@ -464,38 +457,35 @@ GrooveJoint2DSW::~GrooveJoint2DSW() { B->remove_constraint(this); } - ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////////////////////////////////////// - bool DampedSpringJoint2DSW::setup(real_t p_step) { rA = A->get_transform().basis_xform(anchor_A); rB = B->get_transform().basis_xform(anchor_B); - Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA) ; + Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA); real_t dist = delta.length(); if (dist) - n=delta/dist; + n = delta / dist; else - n=Vector2(); + n = Vector2(); real_t k = k_scalar(A, B, rA, rB, n); - n_mass = 1.0f/k; + n_mass = 1.0f / k; target_vrn = 0.0f; - v_coef = 1.0f - Math::exp(-damping*(p_step)*k); + v_coef = 1.0f - Math::exp(-damping * (p_step)*k); // apply spring force real_t f_spring = (rest_length - dist) * stiffness; - Vector2 j = n * f_spring*(p_step); - - A->apply_impulse(rA,-j); - B->apply_impulse(rB,j); + Vector2 j = n * f_spring * (p_step); + A->apply_impulse(rA, -j); + B->apply_impulse(rB, j); return true; } @@ -507,38 +497,36 @@ void DampedSpringJoint2DSW::solve(real_t p_step) { // compute velocity loss from drag // not 100% certain this is derived correctly, though it makes sense - real_t v_damp = -vrn*v_coef; + real_t v_damp = -vrn * v_coef; target_vrn = vrn + v_damp; - Vector2 j=n*v_damp*n_mass; - - A->apply_impulse(rA,-j); - B->apply_impulse(rB,j); + Vector2 j = n * v_damp * n_mass; + A->apply_impulse(rA, -j); + B->apply_impulse(rB, j); } void DampedSpringJoint2DSW::set_param(Physics2DServer::DampedStringParam p_param, real_t p_value) { - switch(p_param) { + switch (p_param) { case Physics2DServer::DAMPED_STRING_REST_LENGTH: { - rest_length=p_value; + rest_length = p_value; } break; case Physics2DServer::DAMPED_STRING_DAMPING: { - damping=p_value; + damping = p_value; } break; case Physics2DServer::DAMPED_STRING_STIFFNESS: { - stiffness=p_value; + stiffness = p_value; } break; } - } -real_t DampedSpringJoint2DSW::get_param(Physics2DServer::DampedStringParam p_param) const{ +real_t DampedSpringJoint2DSW::get_param(Physics2DServer::DampedStringParam p_param) const { - switch(p_param) { + switch (p_param) { case Physics2DServer::DAMPED_STRING_REST_LENGTH: { @@ -557,30 +545,24 @@ real_t DampedSpringJoint2DSW::get_param(Physics2DServer::DampedStringParam p_par ERR_FAIL_V(0); } +DampedSpringJoint2DSW::DampedSpringJoint2DSW(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, Body2DSW *p_body_a, Body2DSW *p_body_b) + : Joint2DSW(_arr, 2) { -DampedSpringJoint2DSW::DampedSpringJoint2DSW(const Vector2& p_anchor_a,const Vector2& p_anchor_b, Body2DSW* p_body_a,Body2DSW* p_body_b) : Joint2DSW(_arr,2) { - - - A=p_body_a; - B=p_body_b; + A = p_body_a; + B = p_body_b; anchor_A = A->get_inv_transform().xform(p_anchor_a); anchor_B = B->get_inv_transform().xform(p_anchor_b); - rest_length=p_anchor_a.distance_to(p_anchor_b); - stiffness=20; - damping=1.5; - - - A->add_constraint(this,0); - B->add_constraint(this,1); + rest_length = p_anchor_a.distance_to(p_anchor_b); + stiffness = 20; + damping = 1.5; + A->add_constraint(this, 0); + B->add_constraint(this, 1); } DampedSpringJoint2DSW::~DampedSpringJoint2DSW() { A->remove_constraint(this); B->remove_constraint(this); - } - - diff --git a/servers/physics_2d/joints_2d_sw.h b/servers/physics_2d/joints_2d_sw.h index 1be15e4edc..8fe38f365a 100644 --- a/servers/physics_2d/joints_2d_sw.h +++ b/servers/physics_2d/joints_2d_sw.h @@ -29,30 +29,31 @@ #ifndef JOINTS_2D_SW_H #define JOINTS_2D_SW_H -#include "constraint_2d_sw.h" #include "body_2d_sw.h" - - +#include "constraint_2d_sw.h" class Joint2DSW : public Constraint2DSW { real_t max_force; real_t bias; real_t max_bias; -public: - _FORCE_INLINE_ void set_max_force(real_t p_force) { max_force=p_force; } +public: + _FORCE_INLINE_ void set_max_force(real_t p_force) { max_force = p_force; } _FORCE_INLINE_ real_t get_max_force() const { return max_force; } - _FORCE_INLINE_ void set_bias(real_t p_bias) { bias=p_bias; } + _FORCE_INLINE_ void set_bias(real_t p_bias) { bias = p_bias; } _FORCE_INLINE_ real_t get_bias() const { return bias; } - _FORCE_INLINE_ void set_max_bias(real_t p_bias) { max_bias=p_bias; } + _FORCE_INLINE_ void set_max_bias(real_t p_bias) { max_bias = p_bias; } _FORCE_INLINE_ real_t get_max_bias() const { return max_bias; } - virtual Physics2DServer::JointType get_type() const=0; - Joint2DSW(Body2DSW **p_body_ptr=NULL,int p_body_count=0) : Constraint2DSW(p_body_ptr,p_body_count) { bias=0; max_force=max_bias=3.40282e+38; }; - + virtual Physics2DServer::JointType get_type() const = 0; + Joint2DSW(Body2DSW **p_body_ptr = NULL, int p_body_count = 0) + : Constraint2DSW(p_body_ptr, p_body_count) { + bias = 0; + max_force = max_bias = 3.40282e+38; + }; }; #if 0 @@ -107,7 +108,7 @@ class PinJoint2DSW : public Joint2DSW { }; Transform2D M; - Vector2 rA,rB; + Vector2 rA, rB; Vector2 anchor_A; Vector2 anchor_B; Vector2 bias; @@ -115,7 +116,6 @@ class PinJoint2DSW : public Joint2DSW { real_t softness; public: - virtual Physics2DServer::JointType get_type() const { return Physics2DServer::JOINT_PIN; } virtual bool setup(real_t p_step); @@ -124,11 +124,10 @@ public: void set_param(Physics2DServer::PinJointParam p_param, real_t p_value); real_t get_param(Physics2DServer::PinJointParam p_param) const; - PinJoint2DSW(const Vector2& p_pos,Body2DSW* p_body_a,Body2DSW* p_body_b=NULL); + PinJoint2DSW(const Vector2 &p_pos, Body2DSW *p_body_a, Body2DSW *p_body_b = NULL); ~PinJoint2DSW(); }; - #endif class GrooveJoint2DSW : public Joint2DSW { @@ -150,25 +149,21 @@ class GrooveJoint2DSW : public Joint2DSW { real_t jn_max; real_t clamp; Vector2 xf_normal; - Vector2 rA,rB; - Vector2 k1,k2; - + Vector2 rA, rB; + Vector2 k1, k2; bool correct; public: - virtual Physics2DServer::JointType get_type() const { return Physics2DServer::JOINT_GROOVE; } virtual bool setup(real_t p_step); virtual void solve(real_t p_step); - - GrooveJoint2DSW(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, Body2DSW* p_body_a,Body2DSW* p_body_b); + GrooveJoint2DSW(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, Body2DSW *p_body_a, Body2DSW *p_body_b); ~GrooveJoint2DSW(); }; - class DampedSpringJoint2DSW : public Joint2DSW { union { @@ -180,7 +175,6 @@ class DampedSpringJoint2DSW : public Joint2DSW { Body2DSW *_arr[2]; }; - Vector2 anchor_A; Vector2 anchor_B; @@ -188,14 +182,13 @@ class DampedSpringJoint2DSW : public Joint2DSW { real_t damping; real_t stiffness; - Vector2 rA,rB; + Vector2 rA, rB; Vector2 n; real_t n_mass; real_t target_vrn; real_t v_coef; public: - virtual Physics2DServer::JointType get_type() const { return Physics2DServer::JOINT_DAMPED_SPRING; } virtual bool setup(real_t p_step); @@ -204,9 +197,8 @@ public: void set_param(Physics2DServer::DampedStringParam p_param, real_t p_value); real_t get_param(Physics2DServer::DampedStringParam p_param) const; - DampedSpringJoint2DSW(const Vector2& p_anchor_a,const Vector2& p_anchor_b, Body2DSW* p_body_a,Body2DSW* p_body_b); + DampedSpringJoint2DSW(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, Body2DSW *p_body_a, Body2DSW *p_body_b); ~DampedSpringJoint2DSW(); }; - #endif // JOINTS_2D_SW_H diff --git a/servers/physics_2d/physics_2d_server_sw.cpp b/servers/physics_2d/physics_2d_server_sw.cpp index 920742ea0b..0a56683c5d 100644 --- a/servers/physics_2d/physics_2d_server_sw.cpp +++ b/servers/physics_2d/physics_2d_server_sw.cpp @@ -31,52 +31,51 @@ #include "broad_phase_2d_hash_grid.h" #include "collision_solver_2d_sw.h" #include "global_config.h" -#include "script_language.h" #include "os/os.h" +#include "script_language.h" RID Physics2DServerSW::shape_create(ShapeType p_shape) { - Shape2DSW *shape=NULL; - switch(p_shape) { + Shape2DSW *shape = NULL; + switch (p_shape) { case SHAPE_LINE: { - shape=memnew( LineShape2DSW ); + shape = memnew(LineShape2DSW); } break; case SHAPE_RAY: { - shape=memnew( RayShape2DSW ); + shape = memnew(RayShape2DSW); } break; case SHAPE_SEGMENT: { - shape=memnew( SegmentShape2DSW); + shape = memnew(SegmentShape2DSW); } break; case SHAPE_CIRCLE: { - shape=memnew( CircleShape2DSW); + shape = memnew(CircleShape2DSW); } break; case SHAPE_RECTANGLE: { - shape=memnew( RectangleShape2DSW); + shape = memnew(RectangleShape2DSW); } break; case SHAPE_CAPSULE: { - shape=memnew( CapsuleShape2DSW ); + shape = memnew(CapsuleShape2DSW); } break; case SHAPE_CONVEX_POLYGON: { - shape=memnew( ConvexPolygonShape2DSW ); + shape = memnew(ConvexPolygonShape2DSW); } break; case SHAPE_CONCAVE_POLYGON: { - shape=memnew( ConcavePolygonShape2DSW ); + shape = memnew(ConcavePolygonShape2DSW); } break; case SHAPE_CUSTOM: { ERR_FAIL_V(RID()); } break; - } RID id = shape_owner.make_rid(shape); @@ -85,68 +84,55 @@ RID Physics2DServerSW::shape_create(ShapeType p_shape) { return id; }; - - - -void Physics2DServerSW::shape_set_data(RID p_shape, const Variant& p_data) { +void Physics2DServerSW::shape_set_data(RID p_shape, const Variant &p_data) { Shape2DSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); shape->set_data(p_data); - - }; - void Physics2DServerSW::shape_set_custom_solver_bias(RID p_shape, real_t p_bias) { Shape2DSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); shape->set_custom_bias(p_bias); - } - Physics2DServer::ShapeType Physics2DServerSW::shape_get_type(RID p_shape) const { const Shape2DSW *shape = shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,SHAPE_CUSTOM); + ERR_FAIL_COND_V(!shape, SHAPE_CUSTOM); return shape->get_type(); - }; Variant Physics2DServerSW::shape_get_data(RID p_shape) const { const Shape2DSW *shape = shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,Variant()); - ERR_FAIL_COND_V(!shape->is_configured(),Variant()); + ERR_FAIL_COND_V(!shape, Variant()); + ERR_FAIL_COND_V(!shape->is_configured(), Variant()); return shape->get_data(); - }; real_t Physics2DServerSW::shape_get_custom_solver_bias(RID p_shape) const { const Shape2DSW *shape = shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ERR_FAIL_COND_V(!shape, 0); return shape->get_custom_bias(); - } +void Physics2DServerSW::_shape_col_cbk(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) { -void Physics2DServerSW::_shape_col_cbk(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata) { - + CollCbkData *cbk = (CollCbkData *)p_userdata; - CollCbkData *cbk=(CollCbkData *)p_userdata; - - if (cbk->max==0) + if (cbk->max == 0) return; - if (cbk->valid_dir!=Vector2()) { - if (p_point_A.distance_squared_to(p_point_B)>cbk->valid_depth*cbk->valid_depth) { + if (cbk->valid_dir != Vector2()) { + if (p_point_A.distance_squared_to(p_point_B) > cbk->valid_depth * cbk->valid_depth) { return; } - if (cbk->valid_dir.dot((p_point_A-p_point_B).normalized())<0.7071) { -/* print_line("A: "+p_point_A); + if (cbk->valid_dir.dot((p_point_A - p_point_B).normalized()) < 0.7071) { + /* print_line("A: "+p_point_A); print_line("B: "+p_point_B); print_line("discard too angled "+rtos(cbk->valid_dir.dot((p_point_A-p_point_B)))); print_line("resnorm: "+(p_point_A-p_point_B).normalized()); @@ -158,66 +144,61 @@ void Physics2DServerSW::_shape_col_cbk(const Vector2& p_point_A,const Vector2& p if (cbk->amount == cbk->max) { //find least deep - real_t min_depth=1e20; - int min_depth_idx=0; - for(int i=0;i<cbk->amount;i++) { - - real_t d = cbk->ptr[i*2+0].distance_squared_to(cbk->ptr[i*2+1]); - if (d<min_depth) { - min_depth=d; - min_depth_idx=i; + real_t min_depth = 1e20; + int min_depth_idx = 0; + for (int i = 0; i < cbk->amount; i++) { + + real_t d = cbk->ptr[i * 2 + 0].distance_squared_to(cbk->ptr[i * 2 + 1]); + if (d < min_depth) { + min_depth = d; + min_depth_idx = i; } - } real_t d = p_point_A.distance_squared_to(p_point_B); - if (d<min_depth) + if (d < min_depth) return; - cbk->ptr[min_depth_idx*2+0]=p_point_A; - cbk->ptr[min_depth_idx*2+1]=p_point_B; - + cbk->ptr[min_depth_idx * 2 + 0] = p_point_A; + cbk->ptr[min_depth_idx * 2 + 1] = p_point_B; } else { - cbk->ptr[cbk->amount*2+0]=p_point_A; - cbk->ptr[cbk->amount*2+1]=p_point_B; + cbk->ptr[cbk->amount * 2 + 0] = p_point_A; + cbk->ptr[cbk->amount * 2 + 1] = p_point_B; cbk->amount++; } } -bool Physics2DServerSW::shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count) { - +bool Physics2DServerSW::shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) { Shape2DSW *shape_A = shape_owner.get(p_shape_A); - ERR_FAIL_COND_V(!shape_A,false); + ERR_FAIL_COND_V(!shape_A, false); Shape2DSW *shape_B = shape_owner.get(p_shape_B); - ERR_FAIL_COND_V(!shape_B,false); + ERR_FAIL_COND_V(!shape_B, false); - if (p_result_max==0) { + if (p_result_max == 0) { - return CollisionSolver2DSW::solve(shape_A,p_xform_A,p_motion_A,shape_B,p_xform_B,p_motion_B,NULL,NULL); + return CollisionSolver2DSW::solve(shape_A, p_xform_A, p_motion_A, shape_B, p_xform_B, p_motion_B, NULL, NULL); } CollCbkData cbk; - cbk.max=p_result_max; - cbk.amount=0; - cbk.ptr=r_results; + cbk.max = p_result_max; + cbk.amount = 0; + cbk.ptr = r_results; - bool res= CollisionSolver2DSW::solve(shape_A,p_xform_A,p_motion_A,shape_B,p_xform_B,p_motion_B,_shape_col_cbk,&cbk); - r_result_count=cbk.amount; + bool res = CollisionSolver2DSW::solve(shape_A, p_xform_A, p_motion_A, shape_B, p_xform_B, p_motion_B, _shape_col_cbk, &cbk); + r_result_count = cbk.amount; return res; - } - RID Physics2DServerSW::space_create() { - Space2DSW *space = memnew( Space2DSW ); + Space2DSW *space = memnew(Space2DSW); RID id = space_owner.make_rid(space); space->set_self(id); RID area_id = area_create(); Area2DSW *area = area_owner.get(area_id); - ERR_FAIL_COND_V(!area,RID()); + ERR_FAIL_COND_V(!area, RID()); space->set_default_area(area); area->set_space(space); area->set_priority(-1); @@ -225,7 +206,7 @@ RID Physics2DServerSW::space_create() { return id; }; -void Physics2DServerSW::space_set_active(RID p_space,bool p_active) { +void Physics2DServerSW::space_set_active(RID p_space, bool p_active) { Space2DSW *space = space_owner.get(p_space); ERR_FAIL_COND(!space); @@ -238,56 +219,51 @@ void Physics2DServerSW::space_set_active(RID p_space,bool p_active) { bool Physics2DServerSW::space_is_active(RID p_space) const { const Space2DSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,false); + ERR_FAIL_COND_V(!space, false); return active_spaces.has(space); - } -void Physics2DServerSW::space_set_param(RID p_space,SpaceParameter p_param, real_t p_value) { +void Physics2DServerSW::space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) { Space2DSW *space = space_owner.get(p_space); ERR_FAIL_COND(!space); - space->set_param(p_param,p_value); - + space->set_param(p_param, p_value); } -real_t Physics2DServerSW::space_get_param(RID p_space,SpaceParameter p_param) const { +real_t Physics2DServerSW::space_get_param(RID p_space, SpaceParameter p_param) const { const Space2DSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,0); + ERR_FAIL_COND_V(!space, 0); return space->get_param(p_param); } -void Physics2DServerSW::space_set_debug_contacts(RID p_space,int p_max_contacts) { +void Physics2DServerSW::space_set_debug_contacts(RID p_space, int p_max_contacts) { Space2DSW *space = space_owner.get(p_space); ERR_FAIL_COND(!space); space->set_debug_contacts(p_max_contacts); - } Vector<Vector2> Physics2DServerSW::space_get_contacts(RID p_space) const { Space2DSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,Vector<Vector2>()); + ERR_FAIL_COND_V(!space, Vector<Vector2>()); return space->get_debug_contacts(); - } int Physics2DServerSW::space_get_contact_count(RID p_space) const { Space2DSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,0); + ERR_FAIL_COND_V(!space, 0); return space->get_debug_contact_count(); - } -Physics2DDirectSpaceState* Physics2DServerSW::space_get_direct_state(RID p_space) { +Physics2DDirectSpaceState *Physics2DServerSW::space_get_direct_state(RID p_space) { Space2DSW *space = space_owner.get(p_space); - ERR_FAIL_COND_V(!space,NULL); + ERR_FAIL_COND_V(!space, NULL); if ((using_threads && !doing_sync) || space->is_locked()) { ERR_EXPLAIN("Space state is inaccesible right now, wait for iteration or fixed process notification."); @@ -299,7 +275,7 @@ Physics2DDirectSpaceState* Physics2DServerSW::space_get_direct_state(RID p_space RID Physics2DServerSW::area_create() { - Area2DSW *area = memnew( Area2DSW ); + Area2DSW *area = memnew(Area2DSW); RID rid = area_owner.make_rid(area); area->set_self(rid); return rid; @@ -309,20 +285,19 @@ void Physics2DServerSW::area_set_space(RID p_area, RID p_space) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - Space2DSW *space=NULL; + Space2DSW *space = NULL; if (p_space.is_valid()) { space = space_owner.get(p_space); ERR_FAIL_COND(!space); } area->set_space(space); - }; RID Physics2DServerSW::area_get_space(RID p_area) const { Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,RID()); + ERR_FAIL_COND_V(!area, RID()); Space2DSW *space = area->get_space(); if (!space) @@ -332,7 +307,6 @@ RID Physics2DServerSW::area_get_space(RID p_area) const { void Physics2DServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) { - Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -342,13 +316,12 @@ void Physics2DServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverri Physics2DServer::AreaSpaceOverrideMode Physics2DServerSW::area_get_space_override_mode(RID p_area) const { const Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,AREA_SPACE_OVERRIDE_DISABLED); + ERR_FAIL_COND_V(!area, AREA_SPACE_OVERRIDE_DISABLED); return area->get_space_override_mode(); } - -void Physics2DServerSW::area_add_shape(RID p_area, RID p_shape, const Transform2D& p_transform) { +void Physics2DServerSW::area_add_shape(RID p_area, RID p_shape, const Transform2D &p_transform) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -356,11 +329,10 @@ void Physics2DServerSW::area_add_shape(RID p_area, RID p_shape, const Transform2 Shape2DSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); - area->add_shape(shape,p_transform); - + area->add_shape(shape, p_transform); } -void Physics2DServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) { +void Physics2DServerSW::area_set_shape(RID p_area, int p_shape_idx, RID p_shape) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -369,39 +341,37 @@ void Physics2DServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) ERR_FAIL_COND(!shape); ERR_FAIL_COND(!shape->is_configured()); - area->set_shape(p_shape_idx,shape); - + area->set_shape(p_shape_idx, shape); } -void Physics2DServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D& p_transform) { +void Physics2DServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D &p_transform) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_shape_transform(p_shape_idx,p_transform); + area->set_shape_transform(p_shape_idx, p_transform); } int Physics2DServerSW::area_get_shape_count(RID p_area) const { Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,-1); + ERR_FAIL_COND_V(!area, -1); return area->get_shape_count(); - } RID Physics2DServerSW::area_get_shape(RID p_area, int p_shape_idx) const { Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,RID()); + ERR_FAIL_COND_V(!area, RID()); Shape2DSW *shape = area->get_shape(p_shape_idx); - ERR_FAIL_COND_V(!shape,RID()); + ERR_FAIL_COND_V(!shape, RID()); return shape->get_self(); } Transform2D Physics2DServerSW::area_get_shape_transform(RID p_area, int p_shape_idx) const { Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,Transform2D()); + ERR_FAIL_COND_V(!area, Transform2D()); return area->get_shape_transform(p_shape_idx); } @@ -419,65 +389,57 @@ void Physics2DServerSW::area_clear_shapes(RID p_area) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - while(area->get_shape_count()) + while (area->get_shape_count()) area->remove_shape(0); - } -void Physics2DServerSW::area_attach_object_instance_ID(RID p_area,ObjectID p_ID) { +void Physics2DServerSW::area_attach_object_instance_ID(RID p_area, ObjectID p_ID) { if (space_owner.owns(p_area)) { - Space2DSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + Space2DSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_instance_id(p_ID); - } ObjectID Physics2DServerSW::area_get_object_instance_ID(RID p_area) const { if (space_owner.owns(p_area)) { - Space2DSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + Space2DSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,0); + ERR_FAIL_COND_V(!area, 0); return area->get_instance_id(); - - } - -void Physics2DServerSW::area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value) { +void Physics2DServerSW::area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) { if (space_owner.owns(p_area)) { - Space2DSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + Space2DSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_param(p_param,p_value); - + area->set_param(p_param, p_value); }; - -void Physics2DServerSW::area_set_transform(RID p_area, const Transform2D& p_transform) { +void Physics2DServerSW::area_set_transform(RID p_area, const Transform2D &p_transform) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_transform(p_transform); - }; -Variant Physics2DServerSW::area_get_param(RID p_area,AreaParameter p_param) const { +Variant Physics2DServerSW::area_get_param(RID p_area, AreaParameter p_param) const { if (space_owner.owns(p_area)) { - Space2DSW *space=space_owner.get(p_area); - p_area=space->get_default_area()->get_self(); + Space2DSW *space = space_owner.get(p_area); + p_area = space->get_default_area()->get_self(); } Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,Variant()); + ERR_FAIL_COND_V(!area, Variant()); return area->get_param(p_param); }; @@ -485,29 +447,27 @@ Variant Physics2DServerSW::area_get_param(RID p_area,AreaParameter p_param) cons Transform2D Physics2DServerSW::area_get_transform(RID p_area) const { Area2DSW *area = area_owner.get(p_area); - ERR_FAIL_COND_V(!area,Transform2D()); + ERR_FAIL_COND_V(!area, Transform2D()); return area->get_transform(); }; -void Physics2DServerSW::area_set_pickable(RID p_area,bool p_pickable) { +void Physics2DServerSW::area_set_pickable(RID p_area, bool p_pickable) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_pickable(p_pickable); - } -void Physics2DServerSW::area_set_monitorable(RID p_area,bool p_monitorable) { +void Physics2DServerSW::area_set_monitorable(RID p_area, bool p_monitorable) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); area->set_monitorable(p_monitorable); - } -void Physics2DServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) { +void Physics2DServerSW::area_set_collision_mask(RID p_area, uint32_t p_mask) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -515,7 +475,7 @@ void Physics2DServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) { area->set_collision_mask(p_mask); } -void Physics2DServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) { +void Physics2DServerSW::area_set_layer_mask(RID p_area, uint32_t p_mask) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); @@ -523,59 +483,53 @@ void Physics2DServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) { area->set_layer_mask(p_mask); } - -void Physics2DServerSW::area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) { +void Physics2DServerSW::area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method); - - + area->set_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method); } -void Physics2DServerSW::area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) { - +void Physics2DServerSW::area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) { Area2DSW *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_area_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method); + area->set_area_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method); } /* BODY API */ -RID Physics2DServerSW::body_create(BodyMode p_mode,bool p_init_sleeping) { +RID Physics2DServerSW::body_create(BodyMode p_mode, bool p_init_sleeping) { - Body2DSW *body = memnew( Body2DSW ); - if (p_mode!=BODY_MODE_RIGID) + Body2DSW *body = memnew(Body2DSW); + if (p_mode != BODY_MODE_RIGID) body->set_mode(p_mode); if (p_init_sleeping) - body->set_state(BODY_STATE_SLEEPING,p_init_sleeping); + body->set_state(BODY_STATE_SLEEPING, p_init_sleeping); RID rid = body_owner.make_rid(body); body->set_self(rid); return rid; }; - void Physics2DServerSW::body_set_space(RID p_body, RID p_space) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - Space2DSW *space=NULL; + Space2DSW *space = NULL; if (p_space.is_valid()) { space = space_owner.get(p_space); ERR_FAIL_COND(!space); } body->set_space(space); - }; RID Physics2DServerSW::body_get_space(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,RID()); + ERR_FAIL_COND_V(!body, RID()); Space2DSW *space = body->get_space(); if (!space) @@ -583,7 +537,6 @@ RID Physics2DServerSW::body_get_space(RID p_body) const { return space->get_self(); }; - void Physics2DServerSW::body_set_mode(RID p_body, BodyMode p_mode) { Body2DSW *body = body_owner.get(p_body); @@ -595,12 +548,12 @@ void Physics2DServerSW::body_set_mode(RID p_body, BodyMode p_mode) { Physics2DServer::BodyMode Physics2DServerSW::body_get_mode(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,BODY_MODE_STATIC); + ERR_FAIL_COND_V(!body, BODY_MODE_STATIC); return body->get_mode(); }; -void Physics2DServerSW::body_add_shape(RID p_body, RID p_shape, const Transform2D& p_transform) { +void Physics2DServerSW::body_add_shape(RID p_body, RID p_shape, const Transform2D &p_transform) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -608,11 +561,10 @@ void Physics2DServerSW::body_add_shape(RID p_body, RID p_shape, const Transform2 Shape2DSW *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); - body->add_shape(shape,p_transform); - + body->add_shape(shape, p_transform); } -void Physics2DServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) { +void Physics2DServerSW::body_set_shape(RID p_body, int p_shape_idx, RID p_shape) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -621,55 +573,51 @@ void Physics2DServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) ERR_FAIL_COND(!shape); ERR_FAIL_COND(!shape->is_configured()); - body->set_shape(p_shape_idx,shape); - + body->set_shape(p_shape_idx, shape); } -void Physics2DServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D& p_transform) { +void Physics2DServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D &p_transform) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_shape_transform(p_shape_idx,p_transform); + body->set_shape_transform(p_shape_idx, p_transform); } -void Physics2DServerSW::body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata) { +void Physics2DServerSW::body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant &p_metadata) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_shape_metadata(p_shape_idx,p_metadata); + body->set_shape_metadata(p_shape_idx, p_metadata); } - Variant Physics2DServerSW::body_get_shape_metadata(RID p_body, int p_shape_idx) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Variant()); + ERR_FAIL_COND_V(!body, Variant()); return body->get_shape_metadata(p_shape_idx); } - int Physics2DServerSW::body_get_shape_count(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,-1); + ERR_FAIL_COND_V(!body, -1); return body->get_shape_count(); - } RID Physics2DServerSW::body_get_shape(RID p_body, int p_shape_idx) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,RID()); + ERR_FAIL_COND_V(!body, RID()); Shape2DSW *shape = body->get_shape(p_shape_idx); - ERR_FAIL_COND_V(!shape,RID()); + ERR_FAIL_COND_V(!shape, RID()); return shape->get_self(); } Transform2D Physics2DServerSW::body_get_shape_transform(RID p_body, int p_shape_idx) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Transform2D()); + ERR_FAIL_COND_V(!body, Transform2D()); return body->get_shape_transform(p_shape_idx); } @@ -687,67 +635,57 @@ void Physics2DServerSW::body_clear_shapes(RID p_body) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - while(body->get_shape_count()) + while (body->get_shape_count()) body->remove_shape(0); - } - -void Physics2DServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable) { +void Physics2DServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - ERR_FAIL_INDEX(p_shape_idx,body->get_shape_count()); - - body->set_shape_as_trigger(p_shape_idx,p_enable); + ERR_FAIL_INDEX(p_shape_idx, body->get_shape_count()); + body->set_shape_as_trigger(p_shape_idx, p_enable); } bool Physics2DServerSW::body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const { const Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); + ERR_FAIL_COND_V(!body, false); - ERR_FAIL_INDEX_V(p_shape_idx,body->get_shape_count(),false); + ERR_FAIL_INDEX_V(p_shape_idx, body->get_shape_count(), false); return body->is_shape_set_as_trigger(p_shape_idx); - } - -void Physics2DServerSW::body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode) { +void Physics2DServerSW::body_set_continuous_collision_detection_mode(RID p_body, CCDMode p_mode) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_continuous_collision_detection_mode(p_mode); - } -Physics2DServerSW::CCDMode Physics2DServerSW::body_get_continuous_collision_detection_mode(RID p_body) const{ +Physics2DServerSW::CCDMode Physics2DServerSW::body_get_continuous_collision_detection_mode(RID p_body) const { const Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,CCD_MODE_DISABLED); + ERR_FAIL_COND_V(!body, CCD_MODE_DISABLED); return body->get_continuous_collision_detection_mode(); - } - - -void Physics2DServerSW::body_attach_object_instance_ID(RID p_body,uint32_t p_ID) { +void Physics2DServerSW::body_attach_object_instance_ID(RID p_body, uint32_t p_ID) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_instance_id(p_ID); - }; uint32_t Physics2DServerSW::body_get_object_instance_ID(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_instance_id(); }; @@ -757,30 +695,27 @@ void Physics2DServerSW::body_set_layer_mask(RID p_body, uint32_t p_flags) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_layer_mask(p_flags); - }; uint32_t Physics2DServerSW::body_get_layer_mask(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_layer_mask(); }; - void Physics2DServerSW::body_set_collision_mask(RID p_body, uint32_t p_flags) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_collision_mask(p_flags); - }; uint32_t Physics2DServerSW::body_get_collision_mask(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_collision_mask(); }; @@ -790,50 +725,46 @@ void Physics2DServerSW::body_set_param(RID p_body, BodyParameter p_param, real_t Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_param(p_param,p_value); + body->set_param(p_param, p_value); }; real_t Physics2DServerSW::body_get_param(RID p_body, BodyParameter p_param) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_param(p_param); }; - - -void Physics2DServerSW::body_set_state(RID p_body, BodyState p_state, const Variant& p_variant) { +void Physics2DServerSW::body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_state(p_state,p_variant); + body->set_state(p_state, p_variant); }; Variant Physics2DServerSW::body_get_state(RID p_body, BodyState p_state) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Variant()); + ERR_FAIL_COND_V(!body, Variant()); return body->get_state(p_state); }; - -void Physics2DServerSW::body_set_applied_force(RID p_body, const Vector2& p_force) { +void Physics2DServerSW::body_set_applied_force(RID p_body, const Vector2 &p_force) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_applied_force(p_force); body->wakeup(); - }; Vector2 Physics2DServerSW::body_get_applied_force(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Vector2()); + ERR_FAIL_COND_V(!body, Vector2()); return body->get_applied_force(); }; @@ -849,38 +780,38 @@ void Physics2DServerSW::body_set_applied_torque(RID p_body, real_t p_torque) { real_t Physics2DServerSW::body_get_applied_torque(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_applied_torque(); }; -void Physics2DServerSW::body_apply_impulse(RID p_body, const Vector2& p_pos, const Vector2& p_impulse) { +void Physics2DServerSW::body_apply_impulse(RID p_body, const Vector2 &p_pos, const Vector2 &p_impulse) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->apply_impulse(p_pos,p_impulse); + body->apply_impulse(p_pos, p_impulse); body->wakeup(); }; -void Physics2DServerSW::body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force) { +void Physics2DServerSW::body_add_force(RID p_body, const Vector2 &p_offset, const Vector2 &p_force) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->add_force(p_force,p_offset); + body->add_force(p_force, p_offset); body->wakeup(); }; -void Physics2DServerSW::body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity) { +void Physics2DServerSW::body_set_axis_velocity(RID p_body, const Vector2 &p_axis_velocity) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); Vector2 v = body->get_linear_velocity(); Vector2 axis = p_axis_velocity.normalized(); - v-=axis*axis.dot(v); - v+=p_axis_velocity; + v -= axis * axis.dot(v); + v += p_axis_velocity; body->set_linear_velocity(v); body->wakeup(); }; @@ -901,7 +832,6 @@ void Physics2DServerSW::body_remove_collision_exception(RID p_body, RID p_body_b body->remove_exception(p_body_b); body->wakeup(); - }; void Physics2DServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) { @@ -909,27 +839,25 @@ void Physics2DServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_e Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - for(int i=0;i<body->get_exceptions().size();i++) { + for (int i = 0; i < body->get_exceptions().size(); i++) { p_exceptions->push_back(body->get_exceptions()[i]); } - }; void Physics2DServerSW::body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - }; real_t Physics2DServerSW::body_get_contacts_reported_depth_treshold(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return 0; }; -void Physics2DServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) { +void Physics2DServerSW::body_set_omit_force_integration(RID p_body, bool p_omit) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -940,7 +868,7 @@ void Physics2DServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) bool Physics2DServerSW::body_is_omitting_force_integration(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); + ERR_FAIL_COND_V(!body, false); return body->get_omit_force_integration(); }; @@ -954,80 +882,71 @@ void Physics2DServerSW::body_set_max_contacts_reported(RID p_body, int p_contact int Physics2DServerSW::body_get_max_contacts_reported(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,-1); + ERR_FAIL_COND_V(!body, -1); return body->get_max_contacts_reported(); } -void Physics2DServerSW::body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction) { +void Physics2DServerSW::body_set_one_way_collision_direction(RID p_body, const Vector2 &p_direction) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_one_way_collision_direction(p_direction); } -Vector2 Physics2DServerSW::body_get_one_way_collision_direction(RID p_body) const{ +Vector2 Physics2DServerSW::body_get_one_way_collision_direction(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,Vector2()); + ERR_FAIL_COND_V(!body, Vector2()); return body->get_one_way_collision_direction(); - } -void Physics2DServerSW::body_set_one_way_collision_max_depth(RID p_body,real_t p_max_depth) { +void Physics2DServerSW::body_set_one_way_collision_max_depth(RID p_body, real_t p_max_depth) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_one_way_collision_max_depth(p_max_depth); - } real_t Physics2DServerSW::body_get_one_way_collision_max_depth(RID p_body) const { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,0); + ERR_FAIL_COND_V(!body, 0); return body->get_one_way_collision_max_depth(); - } -void Physics2DServerSW::body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata) { - +void Physics2DServerSW::body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_force_integration_callback(p_receiver?p_receiver->get_instance_ID():ObjectID(0),p_method,p_udata); - + body->set_force_integration_callback(p_receiver ? p_receiver->get_instance_ID() : ObjectID(0), p_method, p_udata); } -bool Physics2DServerSW::body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count) { +bool Physics2DServerSW::body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); - ERR_FAIL_INDEX_V(p_body_shape,body->get_shape_count(),false); - - return shape_collide(body->get_shape(p_body_shape)->get_self(),body->get_transform() * body->get_shape_transform(p_body_shape),Vector2(),p_shape,p_shape_xform,p_motion,r_results,p_result_max,r_result_count); + ERR_FAIL_COND_V(!body, false); + ERR_FAIL_INDEX_V(p_body_shape, body->get_shape_count(), false); + return shape_collide(body->get_shape(p_body_shape)->get_self(), body->get_transform() * body->get_shape_transform(p_body_shape), Vector2(), p_shape, p_shape_xform, p_motion, r_results, p_result_max, r_result_count); } -void Physics2DServerSW::body_set_pickable(RID p_body,bool p_pickable) { +void Physics2DServerSW::body_set_pickable(RID p_body, bool p_pickable) { Body2DSW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); body->set_pickable(p_pickable); - } -bool Physics2DServerSW::body_test_motion(RID p_body, const Transform2D &p_from, const Vector2& p_motion, real_t p_margin, MotionResult *r_result) { +bool Physics2DServerSW::body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, MotionResult *r_result) { Body2DSW *body = body_owner.get(p_body); - ERR_FAIL_COND_V(!body,false); - ERR_FAIL_COND_V(!body->get_space(),false); - ERR_FAIL_COND_V(body->get_space()->is_locked(),false); - - return body->get_space()->test_body_motion(body,p_from,p_motion,p_margin,r_result); + ERR_FAIL_COND_V(!body, false); + ERR_FAIL_COND_V(!body->get_space(), false); + ERR_FAIL_COND_V(body->get_space()->is_locked(), false); + return body->get_space()->test_body_motion(body, p_from, p_motion, p_margin, r_result); } - /* JOINT API */ void Physics2DServerSW::joint_set_param(RID p_joint, JointParam p_param, real_t p_value) { @@ -1035,21 +954,19 @@ void Physics2DServerSW::joint_set_param(RID p_joint, JointParam p_param, real_t Joint2DSW *joint = joint_owner.get(p_joint); ERR_FAIL_COND(!joint); - switch(p_param) { + switch (p_param) { case JOINT_PARAM_BIAS: joint->set_bias(p_value); break; case JOINT_PARAM_MAX_BIAS: joint->set_max_bias(p_value); break; case JOINT_PARAM_MAX_FORCE: joint->set_max_force(p_value); break; } - - } -real_t Physics2DServerSW::joint_get_param(RID p_joint,JointParam p_param) const { +real_t Physics2DServerSW::joint_get_param(RID p_joint, JointParam p_param) const { const Joint2DSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,-1); + ERR_FAIL_COND_V(!joint, -1); - switch(p_param) { + switch (p_param) { case JOINT_PARAM_BIAS: return joint->get_bias(); break; case JOINT_PARAM_MAX_BIAS: return joint->get_max_bias(); break; case JOINT_PARAM_MAX_FORCE: return joint->get_max_force(); break; @@ -1058,115 +975,106 @@ real_t Physics2DServerSW::joint_get_param(RID p_joint,JointParam p_param) const return 0; } +RID Physics2DServerSW::pin_joint_create(const Vector2 &p_pos, RID p_body_a, RID p_body_b) { -RID Physics2DServerSW::pin_joint_create(const Vector2& p_pos,RID p_body_a,RID p_body_b) { - - Body2DSW *A=body_owner.get(p_body_a); - ERR_FAIL_COND_V(!A,RID()); - Body2DSW *B=NULL; + Body2DSW *A = body_owner.get(p_body_a); + ERR_FAIL_COND_V(!A, RID()); + Body2DSW *B = NULL; if (body_owner.owns(p_body_b)) { - B=body_owner.get(p_body_b); - ERR_FAIL_COND_V(!B,RID()); + B = body_owner.get(p_body_b); + ERR_FAIL_COND_V(!B, RID()); } - Joint2DSW *joint = memnew( PinJoint2DSW(p_pos,A,B) ); + Joint2DSW *joint = memnew(PinJoint2DSW(p_pos, A, B)); RID self = joint_owner.make_rid(joint); joint->set_self(self); return self; } -RID Physics2DServerSW::groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b) { - +RID Physics2DServerSW::groove_joint_create(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b) { - Body2DSW *A=body_owner.get(p_body_a); - ERR_FAIL_COND_V(!A,RID()); + Body2DSW *A = body_owner.get(p_body_a); + ERR_FAIL_COND_V(!A, RID()); - Body2DSW *B=body_owner.get(p_body_b); - ERR_FAIL_COND_V(!B,RID()); + Body2DSW *B = body_owner.get(p_body_b); + ERR_FAIL_COND_V(!B, RID()); - Joint2DSW *joint = memnew( GrooveJoint2DSW(p_a_groove1,p_a_groove2,p_b_anchor,A,B) ); + Joint2DSW *joint = memnew(GrooveJoint2DSW(p_a_groove1, p_a_groove2, p_b_anchor, A, B)); RID self = joint_owner.make_rid(joint); joint->set_self(self); return self; - - } -RID Physics2DServerSW::damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b) { +RID Physics2DServerSW::damped_spring_joint_create(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, RID p_body_a, RID p_body_b) { - Body2DSW *A=body_owner.get(p_body_a); - ERR_FAIL_COND_V(!A,RID()); + Body2DSW *A = body_owner.get(p_body_a); + ERR_FAIL_COND_V(!A, RID()); - Body2DSW *B=body_owner.get(p_body_b); - ERR_FAIL_COND_V(!B,RID()); + Body2DSW *B = body_owner.get(p_body_b); + ERR_FAIL_COND_V(!B, RID()); - Joint2DSW *joint = memnew( DampedSpringJoint2DSW(p_anchor_a,p_anchor_b,A,B) ); + Joint2DSW *joint = memnew(DampedSpringJoint2DSW(p_anchor_a, p_anchor_b, A, B)); RID self = joint_owner.make_rid(joint); joint->set_self(self); return self; - } void Physics2DServerSW::pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) { Joint2DSW *j = joint_owner.get(p_joint); ERR_FAIL_COND(!j); - ERR_FAIL_COND(j->get_type()!=JOINT_PIN); + ERR_FAIL_COND(j->get_type() != JOINT_PIN); - PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW*>(j); + PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW *>(j); pin_joint->set_param(p_param, p_value); } real_t Physics2DServerSW::pin_joint_get_param(RID p_joint, PinJointParam p_param) const { Joint2DSW *j = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!j,0); - ERR_FAIL_COND_V(j->get_type()!=JOINT_PIN,0); + ERR_FAIL_COND_V(!j, 0); + ERR_FAIL_COND_V(j->get_type() != JOINT_PIN, 0); - PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW*>(j); + PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW *>(j); return pin_joint->get_param(p_param); } void Physics2DServerSW::damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value) { - Joint2DSW *j = joint_owner.get(p_joint); ERR_FAIL_COND(!j); - ERR_FAIL_COND(j->get_type()!=JOINT_DAMPED_SPRING); + ERR_FAIL_COND(j->get_type() != JOINT_DAMPED_SPRING); - DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW*>(j); - dsj->set_param(p_param,p_value); + DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW *>(j); + dsj->set_param(p_param, p_value); } real_t Physics2DServerSW::damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const { Joint2DSW *j = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!j,0); - ERR_FAIL_COND_V(j->get_type()!=JOINT_DAMPED_SPRING,0); + ERR_FAIL_COND_V(!j, 0); + ERR_FAIL_COND_V(j->get_type() != JOINT_DAMPED_SPRING, 0); - DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW*>(j); + DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW *>(j); return dsj->get_param(p_param); } Physics2DServer::JointType Physics2DServerSW::joint_get_type(RID p_joint) const { - Joint2DSW *joint = joint_owner.get(p_joint); - ERR_FAIL_COND_V(!joint,JOINT_PIN); + ERR_FAIL_COND_V(!joint, JOINT_PIN); return joint->get_type(); } - - void Physics2DServerSW::free(RID p_rid) { if (shape_owner.owns(p_rid)) { Shape2DSW *shape = shape_owner.get(p_rid); - while(shape->get_owners().size()) { - ShapeOwner2DSW *so=shape->get_owners().front()->key(); + while (shape->get_owners().size()) { + ShapeOwner2DSW *so = shape->get_owners().front()->key(); so->remove_shape(shape); } @@ -1186,8 +1094,7 @@ void Physics2DServerSW::free(RID p_rid) { body->set_space(NULL); - - while( body->get_shape_count() ) { + while (body->get_shape_count()) { body->remove_shape(0); } @@ -1212,7 +1119,7 @@ void Physics2DServerSW::free(RID p_rid) { area->set_space(NULL); - while( area->get_shape_count() ) { + while (area->get_shape_count()) { area->remove_shape(0); } @@ -1223,7 +1130,7 @@ void Physics2DServerSW::free(RID p_rid) { Space2DSW *space = space_owner.get(p_rid); - while(space->get_objects().size()) { + while (space->get_objects().size()) { CollisionObject2DSW *co = (CollisionObject2DSW *)space->get_objects().front()->get(); co->set_space(NULL); } @@ -1244,52 +1151,46 @@ void Physics2DServerSW::free(RID p_rid) { ERR_EXPLAIN("Invalid ID"); ERR_FAIL(); } - - }; void Physics2DServerSW::set_active(bool p_active) { - active=p_active; + active = p_active; }; void Physics2DServerSW::init() { - doing_sync=false; - last_step=0.001; - iterations=8;// 8? - stepper = memnew( Step2DSW ); - direct_state = memnew( Physics2DDirectBodyStateSW ); + doing_sync = false; + last_step = 0.001; + iterations = 8; // 8? + stepper = memnew(Step2DSW); + direct_state = memnew(Physics2DDirectBodyStateSW); }; - void Physics2DServerSW::step(real_t p_step) { - if (!active) return; - doing_sync=false; + doing_sync = false; - last_step=p_step; - Physics2DDirectBodyStateSW::singleton->step=p_step; - island_count=0; - active_objects=0; - collision_pairs=0; - for( Set<const Space2DSW*>::Element *E=active_spaces.front();E;E=E->next()) { + last_step = p_step; + Physics2DDirectBodyStateSW::singleton->step = p_step; + island_count = 0; + active_objects = 0; + collision_pairs = 0; + for (Set<const Space2DSW *>::Element *E = active_spaces.front(); E; E = E->next()) { - stepper->step((Space2DSW*)E->get(),p_step,iterations); - island_count+=E->get()->get_island_count(); - active_objects+=E->get()->get_active_objects(); - collision_pairs+=E->get()->get_collision_pairs(); + stepper->step((Space2DSW *)E->get(), p_step, iterations); + island_count += E->get()->get_island_count(); + active_objects += E->get()->get_active_objects(); + collision_pairs += E->get()->get_collision_pairs(); } - - }; void Physics2DServerSW::sync() { - doing_sync=true; + doing_sync = true; }; void Physics2DServerSW::flush_queries() { @@ -1299,17 +1200,16 @@ void Physics2DServerSW::flush_queries() { uint64_t time_beg = OS::get_singleton()->get_ticks_usec(); - for( Set<const Space2DSW*>::Element *E=active_spaces.front();E;E=E->next()) { + for (Set<const Space2DSW *>::Element *E = active_spaces.front(); E; E = E->next()) { - Space2DSW *space=(Space2DSW *)E->get(); + Space2DSW *space = (Space2DSW *)E->get(); space->call_queries(); } - if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_profiling()) { uint64_t total_time[Space2DSW::ELAPSED_TIME_MAX]; - static const char* time_name[Space2DSW::ELAPSED_TIME_MAX]={ + static const char *time_name[Space2DSW::ELAPSED_TIME_MAX] = { "integrate_forces", "generate_islands", "setup_constraints", @@ -1317,39 +1217,34 @@ void Physics2DServerSW::flush_queries() { "integrate_velocities" }; - for(int i=0;i<Space2DSW::ELAPSED_TIME_MAX;i++) { - total_time[i]=0; + for (int i = 0; i < Space2DSW::ELAPSED_TIME_MAX; i++) { + total_time[i] = 0; } - for( Set<const Space2DSW*>::Element *E=active_spaces.front();E;E=E->next()) { + for (Set<const Space2DSW *>::Element *E = active_spaces.front(); E; E = E->next()) { - for(int i=0;i<Space2DSW::ELAPSED_TIME_MAX;i++) { - total_time[i]+=E->get()->get_elapsed_time(Space2DSW::ElapsedTime(i)); + for (int i = 0; i < Space2DSW::ELAPSED_TIME_MAX; i++) { + total_time[i] += E->get()->get_elapsed_time(Space2DSW::ElapsedTime(i)); } - } Array values; - values.resize(Space2DSW::ELAPSED_TIME_MAX*2); - for(int i=0;i<Space2DSW::ELAPSED_TIME_MAX;i++) { - values[i*2+0]=time_name[i]; - values[i*2+1]=USEC_TO_SEC(total_time[i]); + values.resize(Space2DSW::ELAPSED_TIME_MAX * 2); + for (int i = 0; i < Space2DSW::ELAPSED_TIME_MAX; i++) { + values[i * 2 + 0] = time_name[i]; + values[i * 2 + 1] = USEC_TO_SEC(total_time[i]); } values.push_back("flush_queries"); - values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec()-time_beg)); - - ScriptDebugger::get_singleton()->add_profiling_frame_data("physics_2d",values); + values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec() - time_beg)); + ScriptDebugger::get_singleton()->add_profiling_frame_data("physics_2d", values); } - } void Physics2DServerSW::end_sync() { - doing_sync=false; + doing_sync = false; } - - void Physics2DServerSW::finish() { memdelete(stepper); @@ -1358,7 +1253,7 @@ void Physics2DServerSW::finish() { int Physics2DServerSW::get_process_info(ProcessInfo p_info) { - switch(p_info) { + switch (p_info) { case INFO_ACTIVE_OBJECTS: { @@ -1371,32 +1266,26 @@ int Physics2DServerSW::get_process_info(ProcessInfo p_info) { return island_count; } break; - } return 0; } - -Physics2DServerSW *Physics2DServerSW::singletonsw=NULL; +Physics2DServerSW *Physics2DServerSW::singletonsw = NULL; Physics2DServerSW::Physics2DServerSW() { - singletonsw=this; - BroadPhase2DSW::create_func=BroadPhase2DHashGrid::_create; + singletonsw = this; + BroadPhase2DSW::create_func = BroadPhase2DHashGrid::_create; //BroadPhase2DSW::create_func=BroadPhase2DBasic::_create; - active=true; - island_count=0; - active_objects=0; - collision_pairs=0; - using_threads=int(GlobalConfig::get_singleton()->get("physics/2d/thread_model"))==2; - + active = true; + island_count = 0; + active_objects = 0; + collision_pairs = 0; + using_threads = int(GlobalConfig::get_singleton()->get("physics/2d/thread_model")) == 2; }; - -Physics2DServerSW::~Physics2DServerSW() { +Physics2DServerSW::~Physics2DServerSW(){ }; - - diff --git a/servers/physics_2d/physics_2d_server_sw.h b/servers/physics_2d/physics_2d_server_sw.h index e33e2d78c7..b49c37ab21 100644 --- a/servers/physics_2d/physics_2d_server_sw.h +++ b/servers/physics_2d/physics_2d_server_sw.h @@ -29,20 +29,18 @@ #ifndef PHYSICS_2D_SERVER_SW #define PHYSICS_2D_SERVER_SW - +#include "joints_2d_sw.h" #include "servers/physics_2d_server.h" #include "shape_2d_sw.h" #include "space_2d_sw.h" #include "step_2d_sw.h" -#include "joints_2d_sw.h" - class Physics2DServerSW : public Physics2DServer { - GDCLASS( Physics2DServerSW, Physics2DServer ); + GDCLASS(Physics2DServerSW, Physics2DServer); -friend class Physics2DDirectSpaceStateSW; -friend class Physics2DDirectBodyStateSW; + friend class Physics2DDirectSpaceStateSW; + friend class Physics2DDirectBodyStateSW; bool active; int iterations; bool doing_sync; @@ -54,10 +52,8 @@ friend class Physics2DDirectBodyStateSW; bool using_threads; - - Step2DSW *stepper; - Set<const Space2DSW*> active_spaces; + Set<const Space2DSW *> active_spaces; Physics2DDirectBodyStateSW *direct_state; @@ -69,10 +65,8 @@ friend class Physics2DDirectBodyStateSW; static Physics2DServerSW *singletonsw; - //void _clear_query(Query2DSW *p_query); public: - struct CollCbkData { Vector2 valid_dir; @@ -82,36 +76,33 @@ public: Vector2 *ptr; }; - static void _shape_col_cbk(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata); - + static void _shape_col_cbk(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata); virtual RID shape_create(ShapeType p_shape); - virtual void shape_set_data(RID p_shape, const Variant& p_data); + virtual void shape_set_data(RID p_shape, const Variant &p_data); virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias); virtual ShapeType shape_get_type(RID p_shape) const; virtual Variant shape_get_data(RID p_shape) const; virtual real_t shape_get_custom_solver_bias(RID p_shape) const; - virtual bool shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count); + virtual bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count); /* SPACE API */ virtual RID space_create(); - virtual void space_set_active(RID p_space,bool p_active); + virtual void space_set_active(RID p_space, bool p_active); virtual bool space_is_active(RID p_space) const; - virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value); - virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const; + virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value); + virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const; - virtual void space_set_debug_contacts(RID p_space,int p_max_contacts); + virtual void space_set_debug_contacts(RID p_space, int p_max_contacts); virtual Vector<Vector2> space_get_contacts(RID p_space) const; virtual int space_get_contact_count(RID p_space) const; - // this function only works on fixed process, errors and returns null otherwise - virtual Physics2DDirectSpaceState* space_get_direct_state(RID p_space); - + virtual Physics2DDirectSpaceState *space_get_direct_state(RID p_space); /* AREA API */ @@ -123,9 +114,9 @@ public: virtual void area_set_space(RID p_area, RID p_space); virtual RID area_get_space(RID p_area) const; - virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D& p_transform=Transform2D()); - virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape); - virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D& p_transform); + virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D &p_transform = Transform2D()); + virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape); + virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D &p_transform); virtual int area_get_shape_count(RID p_area) const; virtual RID area_get_shape(RID p_area, int p_shape_idx) const; @@ -134,28 +125,27 @@ public: virtual void area_remove_shape(RID p_area, int p_shape_idx); virtual void area_clear_shapes(RID p_area); - virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID); + virtual void area_attach_object_instance_ID(RID p_area, ObjectID p_ID); virtual ObjectID area_get_object_instance_ID(RID p_area) const; - virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value); - virtual void area_set_transform(RID p_area, const Transform2D& p_transform); + virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value); + virtual void area_set_transform(RID p_area, const Transform2D &p_transform); - virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const; + virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const; virtual Transform2D area_get_transform(RID p_area) const; - virtual void area_set_monitorable(RID p_area,bool p_monitorable); - virtual void area_set_collision_mask(RID p_area,uint32_t p_mask); - virtual void area_set_layer_mask(RID p_area,uint32_t p_mask); - - virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method); - virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method); + virtual void area_set_monitorable(RID p_area, bool p_monitorable); + virtual void area_set_collision_mask(RID p_area, uint32_t p_mask); + virtual void area_set_layer_mask(RID p_area, uint32_t p_mask); - virtual void area_set_pickable(RID p_area,bool p_pickable); + virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method); + virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method); + virtual void area_set_pickable(RID p_area, bool p_pickable); /* BODY API */ // create a body of a given type - virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false); + virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false); virtual void body_set_space(RID p_body, RID p_space); virtual RID body_get_space(RID p_body) const; @@ -163,28 +153,26 @@ public: virtual void body_set_mode(RID p_body, BodyMode p_mode); virtual BodyMode body_get_mode(RID p_body) const; - virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D& p_transform=Transform2D()); - virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape); - virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D& p_transform); - virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata); - + virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D &p_transform = Transform2D()); + virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape); + virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D &p_transform); + virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant &p_metadata); virtual int body_get_shape_count(RID p_body) const; virtual RID body_get_shape(RID p_body, int p_shape_idx) const; virtual Transform2D body_get_shape_transform(RID p_body, int p_shape_idx) const; virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const; - virtual void body_remove_shape(RID p_body, int p_shape_idx); virtual void body_clear_shapes(RID p_body); - virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable); + virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable); virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const; - virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID); + virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID); virtual uint32_t body_get_object_instance_ID(RID p_body) const; - virtual void body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode); + virtual void body_set_continuous_collision_detection_mode(RID p_body, CCDMode p_mode); virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const; virtual void body_set_layer_mask(RID p_body, uint32_t p_mask); @@ -196,20 +184,19 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value); virtual real_t body_get_param(RID p_body, BodyParameter p_param) const; - - virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant); + virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant); virtual Variant body_get_state(RID p_body, BodyState p_state) const; - virtual void body_set_applied_force(RID p_body, const Vector2& p_force); + virtual void body_set_applied_force(RID p_body, const Vector2 &p_force); virtual Vector2 body_get_applied_force(RID p_body) const; virtual void body_set_applied_torque(RID p_body, real_t p_torque); virtual real_t body_get_applied_torque(RID p_body) const; - virtual void body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force); + virtual void body_add_force(RID p_body, const Vector2 &p_offset, const Vector2 &p_force); - virtual void body_apply_impulse(RID p_body, const Vector2& p_pos, const Vector2& p_impulse); - virtual void body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity); + virtual void body_apply_impulse(RID p_body, const Vector2 &p_pos, const Vector2 &p_impulse); + virtual void body_set_axis_velocity(RID p_body, const Vector2 &p_axis_velocity); virtual void body_add_collision_exception(RID p_body, RID p_body_b); virtual void body_remove_collision_exception(RID p_body, RID p_body_b); @@ -218,35 +205,33 @@ public: virtual void body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold); virtual real_t body_get_contacts_reported_depth_treshold(RID p_body) const; - virtual void body_set_omit_force_integration(RID p_body,bool p_omit); + virtual void body_set_omit_force_integration(RID p_body, bool p_omit); virtual bool body_is_omitting_force_integration(RID p_body) const; virtual void body_set_max_contacts_reported(RID p_body, int p_contacts); virtual int body_get_max_contacts_reported(RID p_body) const; - virtual void body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction); + virtual void body_set_one_way_collision_direction(RID p_body, const Vector2 &p_direction); virtual Vector2 body_get_one_way_collision_direction(RID p_body) const; - virtual void body_set_one_way_collision_max_depth(RID p_body,real_t p_max_depth); + virtual void body_set_one_way_collision_max_depth(RID p_body, real_t p_max_depth); virtual real_t body_get_one_way_collision_max_depth(RID p_body) const; + virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()); + virtual bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count); - virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant()); - virtual bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count); - - virtual void body_set_pickable(RID p_body,bool p_pickable); - - virtual bool body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,real_t p_margin=0.001,MotionResult *r_result=NULL); + virtual void body_set_pickable(RID p_body, bool p_pickable); + virtual bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = NULL); /* JOINT API */ virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value); - virtual real_t joint_get_param(RID p_joint,JointParam p_param) const; + virtual real_t joint_get_param(RID p_joint, JointParam p_param) const; - virtual RID pin_joint_create(const Vector2& p_pos,RID p_body_a,RID p_body_b=RID()); - virtual RID groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b); - virtual RID damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b=RID()); + virtual RID pin_joint_create(const Vector2 &p_pos, RID p_body_a, RID p_body_b = RID()); + virtual RID groove_joint_create(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b); + virtual RID damped_spring_joint_create(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, RID p_body_a, RID p_body_b = RID()); virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value); virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const; virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value); @@ -270,8 +255,6 @@ public: Physics2DServerSW(); ~Physics2DServerSW(); - }; #endif - diff --git a/servers/physics_2d/physics_2d_server_wrap_mt.cpp b/servers/physics_2d/physics_2d_server_wrap_mt.cpp index 34ba149d23..ef1a5b333c 100644 --- a/servers/physics_2d/physics_2d_server_wrap_mt.cpp +++ b/servers/physics_2d/physics_2d_server_wrap_mt.cpp @@ -32,35 +32,33 @@ void Physics2DServerWrapMT::thread_exit() { - exit=true; + exit = true; } void Physics2DServerWrapMT::thread_step(real_t p_delta) { physics_2d_server->step(p_delta); step_sem->post(); - } void Physics2DServerWrapMT::_thread_callback(void *_instance) { - Physics2DServerWrapMT *vsmt = reinterpret_cast<Physics2DServerWrapMT*>(_instance); - + Physics2DServerWrapMT *vsmt = reinterpret_cast<Physics2DServerWrapMT *>(_instance); vsmt->thread_loop(); } void Physics2DServerWrapMT::thread_loop() { - server_thread=Thread::get_caller_ID(); + server_thread = Thread::get_caller_ID(); OS::get_singleton()->make_rendering_thread(); physics_2d_server->init(); - exit=false; - step_thread_up=true; - while(!exit) { + exit = false; + step_thread_up = true; + while (!exit) { // flush commands one by one, until exit is requested command_queue.wait_and_flush_one(); } @@ -68,18 +66,15 @@ void Physics2DServerWrapMT::thread_loop() { command_queue.flush_all(); // flush all physics_2d_server->finish(); - } - /* EVENT QUEUING */ - void Physics2DServerWrapMT::step(real_t p_step) { if (create_thread) { - command_queue.push( this, &Physics2DServerWrapMT::thread_step,p_step); + command_queue.push(this, &Physics2DServerWrapMT::thread_step, p_step); } else { command_queue.flush_all(); //flush all pending from other threads @@ -91,14 +86,14 @@ void Physics2DServerWrapMT::sync() { if (step_sem) { if (first_frame) - first_frame=false; + first_frame = false; else step_sem->wait(); //must not wait if a step was not issued } physics_2d_server->sync(); } -void Physics2DServerWrapMT::flush_queries(){ +void Physics2DServerWrapMT::flush_queries() { physics_2d_server->flush_queries(); } @@ -116,10 +111,10 @@ void Physics2DServerWrapMT::init() { print_line("CREATING PHYSICS 2D THREAD"); //OS::get_singleton()->release_rendering_thread(); if (create_thread) { - thread = Thread::create( _thread_callback, this ); + thread = Thread::create(_thread_callback, this); print_line("STARTING PHYISICS 2D THREAD"); } - while(!step_thread_up) { + while (!step_thread_up) { OS::get_singleton()->delay_usec(1000); } print_line("DONE PHYSICS 2D THREAD"); @@ -127,19 +122,17 @@ void Physics2DServerWrapMT::init() { physics_2d_server->init(); } - } void Physics2DServerWrapMT::finish() { - if (thread) { - command_queue.push( this, &Physics2DServerWrapMT::thread_exit); - Thread::wait_to_finish( thread ); + command_queue.push(this, &Physics2DServerWrapMT::thread_exit); + Thread::wait_to_finish(thread); memdelete(thread); -/* + /* shape_free_cached_ids(); area_free_cached_ids(); body_free_cached_ids(); @@ -147,51 +140,46 @@ void Physics2DServerWrapMT::finish() { groove_joint_free_cached_ids(); damped_string_free_cached_ids(); */ - thread=NULL; + thread = NULL; } else { physics_2d_server->finish(); } if (step_sem) memdelete(step_sem); - } +Physics2DServerWrapMT::Physics2DServerWrapMT(Physics2DServer *p_contained, bool p_create_thread) + : command_queue(p_create_thread) { -Physics2DServerWrapMT::Physics2DServerWrapMT(Physics2DServer* p_contained,bool p_create_thread) : command_queue(p_create_thread) { - - physics_2d_server=p_contained; - create_thread=p_create_thread; - thread=NULL; - step_sem=NULL; - step_pending=0; - step_thread_up=false; - alloc_mutex=Mutex::create(); + physics_2d_server = p_contained; + create_thread = p_create_thread; + thread = NULL; + step_sem = NULL; + step_pending = 0; + step_thread_up = false; + alloc_mutex = Mutex::create(); - shape_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); - area_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); - body_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); - pin_joint_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); - groove_joint_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); - damped_spring_joint_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); + shape_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); + area_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); + body_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); + pin_joint_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); + groove_joint_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); + damped_spring_joint_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc"); if (!p_create_thread) { - server_thread=Thread::get_caller_ID(); + server_thread = Thread::get_caller_ID(); } else { - server_thread=0; + server_thread = 0; } main_thread = Thread::get_caller_ID(); - first_frame=true; + first_frame = true; } - Physics2DServerWrapMT::~Physics2DServerWrapMT() { memdelete(physics_2d_server); memdelete(alloc_mutex); //finish(); - } - - diff --git a/servers/physics_2d/physics_2d_server_wrap_mt.h b/servers/physics_2d/physics_2d_server_wrap_mt.h index f8b533080e..ff30b2df09 100644 --- a/servers/physics_2d/physics_2d_server_wrap_mt.h +++ b/servers/physics_2d/physics_2d_server_wrap_mt.h @@ -29,19 +29,17 @@ #ifndef PHYSICS2DSERVERWRAPMT_H #define PHYSICS2DSERVERWRAPMT_H - -#include "servers/physics_2d_server.h" #include "command_queue_mt.h" -#include "os/thread.h" #include "global_config.h" +#include "os/thread.h" +#include "servers/physics_2d_server.h" #ifdef DEBUG_SYNC -#define SYNC_DEBUG print_line("sync on: "+String(__FUNCTION__)); +#define SYNC_DEBUG print_line("sync on: " + String(__FUNCTION__)); #else #define SYNC_DEBUG #endif - class Physics2DServerWrapMT : public Physics2DServer { mutable Physics2DServer *physics_2d_server; @@ -65,7 +63,7 @@ class Physics2DServerWrapMT : public Physics2DServer { void thread_exit(); - Mutex*alloc_mutex; + Mutex *alloc_mutex; bool first_frame; int shape_pool_max_size; @@ -81,226 +79,209 @@ class Physics2DServerWrapMT : public Physics2DServer { int damped_spring_joint_pool_max_size; List<RID> damped_spring_joint_id_pool; - public: - #define ServerName Physics2DServer #define ServerNameWrapMT Physics2DServerWrapMT #define server_name physics_2d_server #include "servers/server_wrap_mt_common.h" //FUNC1RID(shape,ShapeType); todo fix - FUNC1R(RID,shape_create,ShapeType); - FUNC2(shape_set_data,RID,const Variant& ); - FUNC2(shape_set_custom_solver_bias,RID,real_t ); - - FUNC1RC(ShapeType,shape_get_type,RID ); - FUNC1RC(Variant,shape_get_data,RID); - FUNC1RC(real_t,shape_get_custom_solver_bias,RID); + FUNC1R(RID, shape_create, ShapeType); + FUNC2(shape_set_data, RID, const Variant &); + FUNC2(shape_set_custom_solver_bias, RID, real_t); + FUNC1RC(ShapeType, shape_get_type, RID); + FUNC1RC(Variant, shape_get_data, RID); + FUNC1RC(real_t, shape_get_custom_solver_bias, RID); //these work well, but should be used from the main thread only - bool shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count) { + bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) { - ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),false); - return physics_2d_server->shape_collide(p_shape_A,p_xform_A,p_motion_A,p_shape_B,p_xform_B,p_motion_B,r_results,p_result_max,r_result_count); + ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), false); + return physics_2d_server->shape_collide(p_shape_A, p_xform_A, p_motion_A, p_shape_B, p_xform_B, p_motion_B, r_results, p_result_max, r_result_count); } /* SPACE API */ - FUNC0R(RID,space_create); - FUNC2(space_set_active,RID,bool); - FUNC1RC(bool,space_is_active,RID); + FUNC0R(RID, space_create); + FUNC2(space_set_active, RID, bool); + FUNC1RC(bool, space_is_active, RID); - FUNC3(space_set_param,RID,SpaceParameter,real_t); - FUNC2RC(real_t,space_get_param,RID,SpaceParameter); + FUNC3(space_set_param, RID, SpaceParameter, real_t); + FUNC2RC(real_t, space_get_param, RID, SpaceParameter); // this function only works on fixed process, errors and returns null otherwise - Physics2DDirectSpaceState* space_get_direct_state(RID p_space) { + Physics2DDirectSpaceState *space_get_direct_state(RID p_space) { - ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),NULL); + ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), NULL); return physics_2d_server->space_get_direct_state(p_space); } - FUNC2(space_set_debug_contacts,RID,int); + FUNC2(space_set_debug_contacts, RID, int); virtual Vector<Vector2> space_get_contacts(RID p_space) const { - ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),Vector<Vector2>()); + ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), Vector<Vector2>()); return physics_2d_server->space_get_contacts(p_space); - } virtual int space_get_contact_count(RID p_space) const { - ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),0); + ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), 0); return physics_2d_server->space_get_contact_count(p_space); - } - - /* AREA API */ //FUNC0RID(area); - FUNC0R(RID,area_create); - - FUNC2(area_set_space,RID,RID); - FUNC1RC(RID,area_get_space,RID); + FUNC0R(RID, area_create); - FUNC2(area_set_space_override_mode,RID,AreaSpaceOverrideMode); - FUNC1RC(AreaSpaceOverrideMode,area_get_space_override_mode,RID); + FUNC2(area_set_space, RID, RID); + FUNC1RC(RID, area_get_space, RID); - FUNC3(area_add_shape,RID,RID,const Transform2D&); - FUNC3(area_set_shape,RID,int,RID); - FUNC3(area_set_shape_transform,RID,int,const Transform2D&); + FUNC2(area_set_space_override_mode, RID, AreaSpaceOverrideMode); + FUNC1RC(AreaSpaceOverrideMode, area_get_space_override_mode, RID); - FUNC1RC(int,area_get_shape_count,RID); - FUNC2RC(RID,area_get_shape,RID,int); - FUNC2RC(Transform2D,area_get_shape_transform,RID,int); - FUNC2(area_remove_shape,RID,int); - FUNC1(area_clear_shapes,RID); + FUNC3(area_add_shape, RID, RID, const Transform2D &); + FUNC3(area_set_shape, RID, int, RID); + FUNC3(area_set_shape_transform, RID, int, const Transform2D &); - FUNC2(area_attach_object_instance_ID,RID,ObjectID); - FUNC1RC(ObjectID,area_get_object_instance_ID,RID); + FUNC1RC(int, area_get_shape_count, RID); + FUNC2RC(RID, area_get_shape, RID, int); + FUNC2RC(Transform2D, area_get_shape_transform, RID, int); + FUNC2(area_remove_shape, RID, int); + FUNC1(area_clear_shapes, RID); - FUNC3(area_set_param,RID,AreaParameter,const Variant&); - FUNC2(area_set_transform,RID,const Transform2D&); + FUNC2(area_attach_object_instance_ID, RID, ObjectID); + FUNC1RC(ObjectID, area_get_object_instance_ID, RID); - FUNC2RC(Variant,area_get_param,RID,AreaParameter); - FUNC1RC(Transform2D,area_get_transform,RID); + FUNC3(area_set_param, RID, AreaParameter, const Variant &); + FUNC2(area_set_transform, RID, const Transform2D &); - FUNC2(area_set_collision_mask,RID,uint32_t); - FUNC2(area_set_layer_mask,RID,uint32_t); + FUNC2RC(Variant, area_get_param, RID, AreaParameter); + FUNC1RC(Transform2D, area_get_transform, RID); - FUNC2(area_set_monitorable,RID,bool); - FUNC2(area_set_pickable,RID,bool); + FUNC2(area_set_collision_mask, RID, uint32_t); + FUNC2(area_set_layer_mask, RID, uint32_t); - FUNC3(area_set_monitor_callback,RID,Object*,const StringName&); - FUNC3(area_set_area_monitor_callback,RID,Object*,const StringName&); + FUNC2(area_set_monitorable, RID, bool); + FUNC2(area_set_pickable, RID, bool); + FUNC3(area_set_monitor_callback, RID, Object *, const StringName &); + FUNC3(area_set_area_monitor_callback, RID, Object *, const StringName &); /* BODY API */ //FUNC2RID(body,BodyMode,bool); - FUNC2R(RID,body_create,BodyMode,bool) + FUNC2R(RID, body_create, BodyMode, bool) - FUNC2(body_set_space,RID,RID); - FUNC1RC(RID,body_get_space,RID); + FUNC2(body_set_space, RID, RID); + FUNC1RC(RID, body_get_space, RID); - FUNC2(body_set_mode,RID,BodyMode); - FUNC1RC(BodyMode,body_get_mode,RID); + FUNC2(body_set_mode, RID, BodyMode); + FUNC1RC(BodyMode, body_get_mode, RID); + FUNC3(body_add_shape, RID, RID, const Transform2D &); + FUNC3(body_set_shape, RID, int, RID); + FUNC3(body_set_shape_transform, RID, int, const Transform2D &); + FUNC3(body_set_shape_metadata, RID, int, const Variant &); - FUNC3(body_add_shape,RID,RID,const Transform2D&); - FUNC3(body_set_shape,RID,int,RID); - FUNC3(body_set_shape_transform,RID,int,const Transform2D&); - FUNC3(body_set_shape_metadata,RID,int,const Variant&); + FUNC1RC(int, body_get_shape_count, RID); + FUNC2RC(Transform2D, body_get_shape_transform, RID, int); + FUNC2RC(Variant, body_get_shape_metadata, RID, int); + FUNC2RC(RID, body_get_shape, RID, int); - FUNC1RC(int,body_get_shape_count,RID); - FUNC2RC(Transform2D,body_get_shape_transform,RID,int); - FUNC2RC(Variant,body_get_shape_metadata,RID,int); - FUNC2RC(RID,body_get_shape,RID,int); + FUNC3(body_set_shape_as_trigger, RID, int, bool); + FUNC2RC(bool, body_is_shape_set_as_trigger, RID, int); - FUNC3(body_set_shape_as_trigger,RID,int,bool); - FUNC2RC(bool,body_is_shape_set_as_trigger,RID,int); + FUNC2(body_remove_shape, RID, int); + FUNC1(body_clear_shapes, RID); - FUNC2(body_remove_shape,RID,int); - FUNC1(body_clear_shapes,RID); + FUNC2(body_attach_object_instance_ID, RID, uint32_t); + FUNC1RC(uint32_t, body_get_object_instance_ID, RID); - FUNC2(body_attach_object_instance_ID,RID,uint32_t); - FUNC1RC(uint32_t,body_get_object_instance_ID,RID); + FUNC2(body_set_continuous_collision_detection_mode, RID, CCDMode); + FUNC1RC(CCDMode, body_get_continuous_collision_detection_mode, RID); - FUNC2(body_set_continuous_collision_detection_mode,RID,CCDMode); - FUNC1RC(CCDMode,body_get_continuous_collision_detection_mode,RID); + FUNC2(body_set_layer_mask, RID, uint32_t); + FUNC1RC(uint32_t, body_get_layer_mask, RID); - FUNC2(body_set_layer_mask,RID,uint32_t); - FUNC1RC(uint32_t,body_get_layer_mask,RID); + FUNC2(body_set_collision_mask, RID, uint32_t); + FUNC1RC(uint32_t, body_get_collision_mask, RID); - FUNC2(body_set_collision_mask,RID,uint32_t); - FUNC1RC(uint32_t,body_get_collision_mask,RID); + FUNC3(body_set_param, RID, BodyParameter, real_t); + FUNC2RC(real_t, body_get_param, RID, BodyParameter); + FUNC3(body_set_state, RID, BodyState, const Variant &); + FUNC2RC(Variant, body_get_state, RID, BodyState); - FUNC3(body_set_param,RID,BodyParameter,real_t); - FUNC2RC(real_t,body_get_param,RID,BodyParameter); + FUNC2(body_set_applied_force, RID, const Vector2 &); + FUNC1RC(Vector2, body_get_applied_force, RID); + FUNC2(body_set_applied_torque, RID, real_t); + FUNC1RC(real_t, body_get_applied_torque, RID); - FUNC3(body_set_state,RID,BodyState,const Variant&); - FUNC2RC(Variant,body_get_state,RID,BodyState); + FUNC3(body_add_force, RID, const Vector2 &, const Vector2 &); + FUNC3(body_apply_impulse, RID, const Vector2 &, const Vector2 &); + FUNC2(body_set_axis_velocity, RID, const Vector2 &); - FUNC2(body_set_applied_force,RID,const Vector2&); - FUNC1RC(Vector2,body_get_applied_force,RID); + FUNC2(body_add_collision_exception, RID, RID); + FUNC2(body_remove_collision_exception, RID, RID); + FUNC2S(body_get_collision_exceptions, RID, List<RID> *); - FUNC2(body_set_applied_torque,RID,real_t); - FUNC1RC(real_t,body_get_applied_torque,RID); + FUNC2(body_set_max_contacts_reported, RID, int); + FUNC1RC(int, body_get_max_contacts_reported, RID); - FUNC3(body_add_force,RID,const Vector2&,const Vector2&); - FUNC3(body_apply_impulse,RID,const Vector2&,const Vector2&); - FUNC2(body_set_axis_velocity,RID,const Vector2&); + FUNC2(body_set_one_way_collision_direction, RID, const Vector2 &); + FUNC1RC(Vector2, body_get_one_way_collision_direction, RID); - FUNC2(body_add_collision_exception,RID,RID); - FUNC2(body_remove_collision_exception,RID,RID); - FUNC2S(body_get_collision_exceptions,RID,List<RID>*); + FUNC2(body_set_one_way_collision_max_depth, RID, real_t); + FUNC1RC(real_t, body_get_one_way_collision_max_depth, RID); - FUNC2(body_set_max_contacts_reported,RID,int); - FUNC1RC(int,body_get_max_contacts_reported,RID); + FUNC2(body_set_contacts_reported_depth_treshold, RID, real_t); + FUNC1RC(real_t, body_get_contacts_reported_depth_treshold, RID); - FUNC2(body_set_one_way_collision_direction,RID,const Vector2&); - FUNC1RC(Vector2,body_get_one_way_collision_direction,RID); + FUNC2(body_set_omit_force_integration, RID, bool); + FUNC1RC(bool, body_is_omitting_force_integration, RID); - FUNC2(body_set_one_way_collision_max_depth,RID,real_t); - FUNC1RC(real_t,body_get_one_way_collision_max_depth,RID); + FUNC4(body_set_force_integration_callback, RID, Object *, const StringName &, const Variant &); - - FUNC2(body_set_contacts_reported_depth_treshold,RID,real_t); - FUNC1RC(real_t,body_get_contacts_reported_depth_treshold,RID); - - FUNC2(body_set_omit_force_integration,RID,bool); - FUNC1RC(bool,body_is_omitting_force_integration,RID); - - FUNC4(body_set_force_integration_callback,RID ,Object *,const StringName& ,const Variant& ); - - - bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count) { - return physics_2d_server->body_collide_shape(p_body,p_body_shape,p_shape,p_shape_xform,p_motion,r_results,p_result_max,r_result_count); + bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) { + return physics_2d_server->body_collide_shape(p_body, p_body_shape, p_shape, p_shape_xform, p_motion, r_results, p_result_max, r_result_count); } - FUNC2(body_set_pickable,RID,bool); + FUNC2(body_set_pickable, RID, bool); - bool body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,real_t p_margin=0.001,MotionResult *r_result=NULL) { + bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = NULL) { - ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),false); - return physics_2d_server->body_test_motion(p_body,p_from,p_motion,p_margin,r_result); + ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), false); + return physics_2d_server->body_test_motion(p_body, p_from, p_motion, p_margin, r_result); } /* JOINT API */ - - FUNC3(joint_set_param,RID,JointParam,real_t); - FUNC2RC(real_t,joint_get_param,RID,JointParam); - + FUNC3(joint_set_param, RID, JointParam, real_t); + FUNC2RC(real_t, joint_get_param, RID, JointParam); ///FUNC3RID(pin_joint,const Vector2&,RID,RID); ///FUNC5RID(groove_joint,const Vector2&,const Vector2&,const Vector2&,RID,RID); ///FUNC4RID(damped_spring_joint,const Vector2&,const Vector2&,RID,RID); - FUNC3R(RID,pin_joint_create,const Vector2&,RID,RID); - FUNC5R(RID,groove_joint_create,const Vector2&,const Vector2&,const Vector2&,RID,RID); - FUNC4R(RID,damped_spring_joint_create,const Vector2&,const Vector2&,RID,RID); + FUNC3R(RID, pin_joint_create, const Vector2 &, RID, RID); + FUNC5R(RID, groove_joint_create, const Vector2 &, const Vector2 &, const Vector2 &, RID, RID); + FUNC4R(RID, damped_spring_joint_create, const Vector2 &, const Vector2 &, RID, RID); - FUNC3(pin_joint_set_param,RID,PinJointParam,real_t); - FUNC2RC(real_t,pin_joint_get_param,RID,PinJointParam); + FUNC3(pin_joint_set_param, RID, PinJointParam, real_t); + FUNC2RC(real_t, pin_joint_get_param, RID, PinJointParam); - FUNC3(damped_string_joint_set_param,RID,DampedStringParam,real_t); - FUNC2RC(real_t,damped_string_joint_get_param,RID,DampedStringParam); - - FUNC1RC(JointType,joint_get_type,RID); + FUNC3(damped_string_joint_set_param, RID, DampedStringParam, real_t); + FUNC2RC(real_t, damped_string_joint_get_param, RID, DampedStringParam); + FUNC1RC(JointType, joint_get_type, RID); /* MISC */ - - FUNC1(free,RID); - FUNC1(set_active,bool); + FUNC1(free, RID); + FUNC1(set_active, bool); virtual void init(); virtual void step(real_t p_step); @@ -313,28 +294,24 @@ public: return physics_2d_server->get_process_info(p_info); } - Physics2DServerWrapMT(Physics2DServer* p_contained,bool p_create_thread); + Physics2DServerWrapMT(Physics2DServer *p_contained, bool p_create_thread); ~Physics2DServerWrapMT(); + template <class T> + static Physics2DServer *init_server() { - template<class T> - static Physics2DServer* init_server() { - - int tm = GLOBAL_DEF("physics/2d/thread_model",1); - if (tm==0) //single unsafe - return memnew( T ); - else if (tm==1) //single saef - return memnew( Physics2DServerWrapMT( memnew( T ), false )); + int tm = GLOBAL_DEF("physics/2d/thread_model", 1); + if (tm == 0) //single unsafe + return memnew(T); + else if (tm == 1) //single saef + return memnew(Physics2DServerWrapMT(memnew(T), false)); else //single unsafe - return memnew( Physics2DServerWrapMT( memnew( T ), true )); - - + return memnew(Physics2DServerWrapMT(memnew(T), true)); } #undef ServerNameWrapMT #undef ServerName #undef server_name - }; #ifdef DEBUG_SYNC diff --git a/servers/physics_2d/shape_2d_sw.cpp b/servers/physics_2d/shape_2d_sw.cpp index b6eb427131..32d632453a 100644 --- a/servers/physics_2d/shape_2d_sw.cpp +++ b/servers/physics_2d/shape_2d_sw.cpp @@ -30,108 +30,98 @@ #include "geometry.h" #include "sort.h" - - -void Shape2DSW::configure(const Rect2& p_aabb) { - aabb=p_aabb; - configured=true; - for (Map<ShapeOwner2DSW*,int>::Element *E=owners.front();E;E=E->next()) { - ShapeOwner2DSW* co=(ShapeOwner2DSW*)E->key(); +void Shape2DSW::configure(const Rect2 &p_aabb) { + aabb = p_aabb; + configured = true; + for (Map<ShapeOwner2DSW *, int>::Element *E = owners.front(); E; E = E->next()) { + ShapeOwner2DSW *co = (ShapeOwner2DSW *)E->key(); co->_shape_changed(); } } - -Vector2 Shape2DSW::get_support(const Vector2& p_normal) const { +Vector2 Shape2DSW::get_support(const Vector2 &p_normal) const { Vector2 res[2]; int amnt; - get_supports(p_normal,res,amnt); + get_supports(p_normal, res, amnt); return res[0]; } void Shape2DSW::add_owner(ShapeOwner2DSW *p_owner) { - Map<ShapeOwner2DSW*,int>::Element *E=owners.find(p_owner); + Map<ShapeOwner2DSW *, int>::Element *E = owners.find(p_owner); if (E) { E->get()++; } else { - owners[p_owner]=1; + owners[p_owner] = 1; } } -void Shape2DSW::remove_owner(ShapeOwner2DSW *p_owner){ +void Shape2DSW::remove_owner(ShapeOwner2DSW *p_owner) { - Map<ShapeOwner2DSW*,int>::Element *E=owners.find(p_owner); + Map<ShapeOwner2DSW *, int>::Element *E = owners.find(p_owner); ERR_FAIL_COND(!E); E->get()--; - if (E->get()==0) { + if (E->get() == 0) { owners.erase(E); } - } -bool Shape2DSW::is_owner(ShapeOwner2DSW *p_owner) const{ +bool Shape2DSW::is_owner(ShapeOwner2DSW *p_owner) const { return owners.has(p_owner); - } -const Map<ShapeOwner2DSW*,int>& Shape2DSW::get_owners() const{ +const Map<ShapeOwner2DSW *, int> &Shape2DSW::get_owners() const { return owners; } - Shape2DSW::Shape2DSW() { - custom_bias=0; - configured=false; + custom_bias = 0; + configured = false; } - Shape2DSW::~Shape2DSW() { ERR_FAIL_COND(owners.size()); } - /*********************************************************/ /*********************************************************/ /*********************************************************/ +void LineShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { - -void LineShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - r_amount=0; + r_amount = 0; } -bool LineShape2DSW::contains_point(const Vector2& p_point) const { +bool LineShape2DSW::contains_point(const Vector2 &p_point) const { return normal.dot(p_point) < d; } -bool LineShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { +bool LineShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { - Vector2 segment= p_begin - p_end; - real_t den=normal.dot( segment ); + Vector2 segment = p_begin - p_end; + real_t den = normal.dot(segment); //printf("den is %i\n",den); - if (Math::abs(den)<=CMP_EPSILON) { + if (Math::abs(den) <= CMP_EPSILON) { return false; } - real_t dist=(normal.dot( p_begin ) - d) / den; + real_t dist = (normal.dot(p_begin) - d) / den; //printf("dist is %i\n",dist); - if (dist<-CMP_EPSILON || dist > (1.0 +CMP_EPSILON)) { + if (dist < -CMP_EPSILON || dist > (1.0 + CMP_EPSILON)) { return false; } r_point = p_begin + segment * -dist; - r_normal=normal; + r_normal = normal; return true; } @@ -141,24 +131,22 @@ real_t LineShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) return 0; } +void LineShape2DSW::set_data(const Variant &p_data) { -void LineShape2DSW::set_data(const Variant& p_data) { - - ERR_FAIL_COND(p_data.get_type()!=Variant::ARRAY); + ERR_FAIL_COND(p_data.get_type() != Variant::ARRAY); Array arr = p_data; - ERR_FAIL_COND(arr.size()!=2); - normal=arr[0]; - d=arr[1]; - configure(Rect2(Vector2(-1e4,-1e4),Vector2(1e4*2,1e4*2))); - + ERR_FAIL_COND(arr.size() != 2); + normal = arr[0]; + d = arr[1]; + configure(Rect2(Vector2(-1e4, -1e4), Vector2(1e4 * 2, 1e4 * 2))); } Variant LineShape2DSW::get_data() const { Array arr; arr.resize(2); - arr[0]=normal; - arr[1]=d; + arr[0] = normal; + arr[1] = d; return arr; } @@ -166,29 +154,24 @@ Variant LineShape2DSW::get_data() const { /*********************************************************/ /*********************************************************/ +void RayShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { + r_amount = 1; -void RayShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - - r_amount=1; - - if (p_normal.y>0) - *r_supports=Vector2(0,length); + if (p_normal.y > 0) + *r_supports = Vector2(0, length); else - *r_supports=Vector2(); - + *r_supports = Vector2(); } -bool RayShape2DSW::contains_point(const Vector2& p_point) const { +bool RayShape2DSW::contains_point(const Vector2 &p_point) const { return false; } -bool RayShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { +bool RayShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { return false; //rays can't be intersected - } real_t RayShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { @@ -196,10 +179,10 @@ real_t RayShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) return 0; //rays are mass-less } -void RayShape2DSW::set_data(const Variant& p_data) { +void RayShape2DSW::set_data(const Variant &p_data) { - length=p_data; - configure(Rect2(0,0,0.001,length)); + length = p_data; + configure(Rect2(0, 0, 0.001, length)); } Variant RayShape2DSW::get_data() const { @@ -207,46 +190,41 @@ Variant RayShape2DSW::get_data() const { return length; } - /*********************************************************/ /*********************************************************/ /*********************************************************/ +void SegmentShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { - -void SegmentShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - if (Math::abs(p_normal.dot(n))>_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) { - r_supports[0]=a; - r_supports[1]=b; - r_amount=2; + if (Math::abs(p_normal.dot(n)) > _SEGMENT_IS_VALID_SUPPORT_TRESHOLD) { + r_supports[0] = a; + r_supports[1] = b; + r_amount = 2; return; - } - real_t dp=p_normal.dot(b-a); - if (dp>0) - *r_supports=b; + real_t dp = p_normal.dot(b - a); + if (dp > 0) + *r_supports = b; else - *r_supports=a; - r_amount=1; - + *r_supports = a; + r_amount = 1; } -bool SegmentShape2DSW::contains_point(const Vector2& p_point) const { +bool SegmentShape2DSW::contains_point(const Vector2 &p_point) const { return false; } -bool SegmentShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { +bool SegmentShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { - if (!Geometry::segment_intersects_segment_2d(p_begin,p_end,a,b,&r_point)) + if (!Geometry::segment_intersects_segment_2d(p_begin, p_end, a, b, &r_point)) return false; if (n.dot(p_begin) > n.dot(a)) { - r_normal=n; + r_normal = n; } else { - r_normal=-n; + r_normal = -n; } return true; @@ -254,38 +232,38 @@ bool SegmentShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p real_t SegmentShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { - Vector2 s[2]={a*p_scale,b*p_scale}; + Vector2 s[2] = { a * p_scale, b * p_scale }; real_t l = s[1].distance_to(s[0]); - Vector2 ofs = (s[0]+s[1])*0.5; + Vector2 ofs = (s[0] + s[1]) * 0.5; - return p_mass*(l*l/12.0 + ofs.length_squared()); + return p_mass * (l * l / 12.0 + ofs.length_squared()); } -void SegmentShape2DSW::set_data(const Variant& p_data) { +void SegmentShape2DSW::set_data(const Variant &p_data) { - ERR_FAIL_COND(p_data.get_type()!=Variant::RECT2); + ERR_FAIL_COND(p_data.get_type() != Variant::RECT2); Rect2 r = p_data; - a=r.pos; - b=r.size; - n=(b-a).tangent(); + a = r.pos; + b = r.size; + n = (b - a).tangent(); Rect2 aabb; - aabb.pos=a; + aabb.pos = a; aabb.expand_to(b); - if (aabb.size.x==0) - aabb.size.x=0.001; - if (aabb.size.y==0) - aabb.size.y=0.001; + if (aabb.size.x == 0) + aabb.size.x = 0.001; + if (aabb.size.y == 0) + aabb.size.y = 0.001; configure(aabb); } Variant SegmentShape2DSW::get_data() const { Rect2 r; - r.pos=a; - r.size=b; + r.pos = a; + r.size = b; return r; } @@ -293,24 +271,18 @@ Variant SegmentShape2DSW::get_data() const { /*********************************************************/ /*********************************************************/ +void CircleShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { - -void CircleShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - r_amount=1; - *r_supports=p_normal*radius; - + r_amount = 1; + *r_supports = p_normal * radius; } +bool CircleShape2DSW::contains_point(const Vector2 &p_point) const { -bool CircleShape2DSW::contains_point(const Vector2& p_point) const { - - return p_point.length_squared() < radius*radius; + return p_point.length_squared() < radius * radius; } - -bool CircleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { - +bool CircleShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { Vector2 line_vec = p_end - p_begin; @@ -320,33 +292,32 @@ bool CircleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_ b = 2 * p_begin.dot(line_vec); c = p_begin.dot(p_begin) - radius * radius; - real_t sqrtterm = b*b - 4*a*c; + real_t sqrtterm = b * b - 4 * a * c; - if(sqrtterm < 0) + if (sqrtterm < 0) return false; sqrtterm = Math::sqrt(sqrtterm); - real_t res = ( -b - sqrtterm ) / (2 * a); + real_t res = (-b - sqrtterm) / (2 * a); - if (res <0 || res >1+CMP_EPSILON) { + if (res < 0 || res > 1 + CMP_EPSILON) { return false; } - r_point=p_begin+line_vec*res; - r_normal=r_point.normalized(); + r_point = p_begin + line_vec * res; + r_normal = r_point.normalized(); return true; } real_t CircleShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { - return (radius*radius)*(p_scale.x*0.5+p_scale.y*0.5); - + return (radius * radius) * (p_scale.x * 0.5 + p_scale.y * 0.5); } -void CircleShape2DSW::set_data(const Variant& p_data) { +void CircleShape2DSW::set_data(const Variant &p_data) { ERR_FAIL_COND(!p_data.is_num()); - radius=p_data; - configure(Rect2(-radius,-radius,radius*2,radius*2)); + radius = p_data; + configure(Rect2(-radius, -radius, radius * 2, radius * 2)); } Variant CircleShape2DSW::get_data() const { @@ -354,71 +325,63 @@ Variant CircleShape2DSW::get_data() const { return radius; } - /*********************************************************/ /*********************************************************/ /*********************************************************/ +void RectangleShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { - -void RectangleShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { Vector2 ag; - ag[i]=1.0; + ag[i] = 1.0; real_t dp = ag.dot(p_normal); - if (Math::abs(dp)<_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) + if (Math::abs(dp) < _SEGMENT_IS_VALID_SUPPORT_TRESHOLD) continue; - real_t sgn = dp>0 ? 1.0 : -1.0; + real_t sgn = dp > 0 ? 1.0 : -1.0; - r_amount=2; + r_amount = 2; - r_supports[0][i]=half_extents[i]*sgn; - r_supports[0][i^1]=half_extents[i^1]; + r_supports[0][i] = half_extents[i] * sgn; + r_supports[0][i ^ 1] = half_extents[i ^ 1]; - r_supports[1][i]=half_extents[i]*sgn; - r_supports[1][i^1]=-half_extents[i^1]; + r_supports[1][i] = half_extents[i] * sgn; + r_supports[1][i ^ 1] = -half_extents[i ^ 1]; return; - - } /* USE POINT */ - r_amount=1; - r_supports[0]=Vector2( - (p_normal.x<0) ? -half_extents.x : half_extents.x, - (p_normal.y<0) ? -half_extents.y : half_extents.y - ); - + r_amount = 1; + r_supports[0] = Vector2( + (p_normal.x < 0) ? -half_extents.x : half_extents.x, + (p_normal.y < 0) ? -half_extents.y : half_extents.y); } -bool RectangleShape2DSW::contains_point(const Vector2& p_point) const { +bool RectangleShape2DSW::contains_point(const Vector2 &p_point) const { - return Math::abs(p_point.x)<half_extents.x && Math::abs(p_point.y)<half_extents.y; + return Math::abs(p_point.x) < half_extents.x && Math::abs(p_point.y) < half_extents.y; } -bool RectangleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { - +bool RectangleShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { - return get_aabb().intersects_segment(p_begin,p_end,&r_point,&r_normal); + return get_aabb().intersects_segment(p_begin, p_end, &r_point, &r_normal); } -real_t RectangleShape2DSW::get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const { +real_t RectangleShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { - Vector2 he2=half_extents*2*p_scale; - return p_mass*he2.dot(he2)/12.0; + Vector2 he2 = half_extents * 2 * p_scale; + return p_mass * he2.dot(he2) / 12.0; } -void RectangleShape2DSW::set_data(const Variant& p_data) { +void RectangleShape2DSW::set_data(const Variant &p_data) { - ERR_FAIL_COND(p_data.get_type()!=Variant::VECTOR2); + ERR_FAIL_COND(p_data.get_type() != Variant::VECTOR2); - half_extents=p_data; - configure(Rect2(-half_extents,half_extents*2.0)); + half_extents = p_data; + configure(Rect2(-half_extents, half_extents * 2.0)); } Variant RectangleShape2DSW::get_data() const { @@ -426,71 +389,65 @@ Variant RectangleShape2DSW::get_data() const { return half_extents; } - - /*********************************************************/ /*********************************************************/ /*********************************************************/ +void CapsuleShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { - -void CapsuleShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - Vector2 n=p_normal; + Vector2 n = p_normal; real_t d = n.y; - if (Math::abs( d )<(1.0-_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) ) { + if (Math::abs(d) < (1.0 - _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)) { // make it flat - n.y=0.0; + n.y = 0.0; n.normalize(); - n*=radius; + n *= radius; - r_amount=2; - r_supports[0]=n; - r_supports[0].y+=height*0.5; - r_supports[1]=n; - r_supports[1].y-=height*0.5; + r_amount = 2; + r_supports[0] = n; + r_supports[0].y += height * 0.5; + r_supports[1] = n; + r_supports[1].y -= height * 0.5; } else { real_t h = (d > 0) ? height : -height; - n*=radius; - n.y += h*0.5; - r_amount=1; - *r_supports=n; - + n *= radius; + n.y += h * 0.5; + r_amount = 1; + *r_supports = n; } } -bool CapsuleShape2DSW::contains_point(const Vector2& p_point) const { +bool CapsuleShape2DSW::contains_point(const Vector2 &p_point) const { Vector2 p = p_point; - p.y=Math::abs(p.y); - p.y-=height*0.5; - if (p.y<0) - p.y=0; + p.y = Math::abs(p.y); + p.y -= height * 0.5; + if (p.y < 0) + p.y = 0; - return p.length_squared() < radius*radius; + return p.length_squared() < radius * radius; } -bool CapsuleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { - +bool CapsuleShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { real_t d = 1e10; - Vector2 n = (p_end-p_begin).normalized(); - bool collided=false; + Vector2 n = (p_end - p_begin).normalized(); + bool collided = false; //try spheres - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { Vector2 begin = p_begin; Vector2 end = p_end; - real_t ofs = (i==0)?-height*0.5:height*0.5; - begin.y+=ofs; - end.y+=ofs; + real_t ofs = (i == 0) ? -height * 0.5 : height * 0.5; + begin.y += ofs; + end.y += ofs; Vector2 line_vec = end - begin; @@ -500,39 +457,38 @@ bool CapsuleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p b = 2 * begin.dot(line_vec); c = begin.dot(begin) - radius * radius; - real_t sqrtterm = b*b - 4*a*c; + real_t sqrtterm = b * b - 4 * a * c; - if(sqrtterm < 0) + if (sqrtterm < 0) continue; sqrtterm = Math::sqrt(sqrtterm); - real_t res = ( -b - sqrtterm ) / (2 * a); + real_t res = (-b - sqrtterm) / (2 * a); - if (res <0 || res >1+CMP_EPSILON) { + if (res < 0 || res > 1 + CMP_EPSILON) { continue; } - Vector2 point = begin+line_vec*res; - Vector2 pointf(point.x,point.y-ofs); + Vector2 point = begin + line_vec * res; + Vector2 pointf(point.x, point.y - ofs); real_t pd = n.dot(pointf); - if (pd<d) { - r_point=pointf; - r_normal=point.normalized(); - d=pd; - collided=true; + if (pd < d) { + r_point = pointf; + r_normal = point.normalized(); + d = pd; + collided = true; } } - - Vector2 rpos,rnorm; - if (Rect2( Point2(-radius,-height*0.5), Size2(radius*2.0,height) ).intersects_segment(p_begin,p_end,&rpos,&rnorm)) { + Vector2 rpos, rnorm; + if (Rect2(Point2(-radius, -height * 0.5), Size2(radius * 2.0, height)).intersects_segment(p_begin, p_end, &rpos, &rnorm)) { real_t pd = n.dot(rpos); - if (pd<d) { - r_point=rpos; - r_normal=rnorm; - d=pd; - collided=true; + if (pd < d) { + r_point = rpos; + r_normal = rnorm; + d = pd; + collided = true; } } @@ -542,101 +498,93 @@ bool CapsuleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p real_t CapsuleShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { - Vector2 he2=Vector2(radius*2,height+radius*2)*p_scale; - return p_mass*he2.dot(he2)/12.0; + Vector2 he2 = Vector2(radius * 2, height + radius * 2) * p_scale; + return p_mass * he2.dot(he2) / 12.0; } -void CapsuleShape2DSW::set_data(const Variant& p_data) { +void CapsuleShape2DSW::set_data(const Variant &p_data) { - ERR_FAIL_COND(p_data.get_type()!=Variant::ARRAY && p_data.get_type()!=Variant::VECTOR2); + ERR_FAIL_COND(p_data.get_type() != Variant::ARRAY && p_data.get_type() != Variant::VECTOR2); - if (p_data.get_type()==Variant::ARRAY) { - Array arr=p_data; - ERR_FAIL_COND(arr.size()!=2); - height=arr[0]; - radius=arr[1]; + if (p_data.get_type() == Variant::ARRAY) { + Array arr = p_data; + ERR_FAIL_COND(arr.size() != 2); + height = arr[0]; + radius = arr[1]; } else { Point2 p = p_data; - radius=p.x; - height=p.y; + radius = p.x; + height = p.y; } - Point2 he(radius,height*0.5+radius); - configure(Rect2(-he,he*2)); - + Point2 he(radius, height * 0.5 + radius); + configure(Rect2(-he, he * 2)); } Variant CapsuleShape2DSW::get_data() const { - return Point2(height,radius); + return Point2(height, radius); } - - /*********************************************************/ /*********************************************************/ /*********************************************************/ +void ConvexPolygonShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { + int support_idx = -1; + real_t d = -1e10; -void ConvexPolygonShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - int support_idx=-1; - real_t d=-1e10; - - for(int i=0;i<point_count;i++) { + for (int i = 0; i < point_count; i++) { //test point real_t ld = p_normal.dot(points[i].pos); - if (ld>d) { - support_idx=i; - d=ld; + if (ld > d) { + support_idx = i; + d = ld; } //test segment - if (points[i].normal.dot(p_normal)>_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) { + if (points[i].normal.dot(p_normal) > _SEGMENT_IS_VALID_SUPPORT_TRESHOLD) { - r_amount=2; - r_supports[0]=points[i].pos; - r_supports[1]=points[(i+1)%point_count].pos; + r_amount = 2; + r_supports[0] = points[i].pos; + r_supports[1] = points[(i + 1) % point_count].pos; return; } } - ERR_FAIL_COND(support_idx==-1); - - r_amount=1; - r_supports[0]=points[support_idx].pos; + ERR_FAIL_COND(support_idx == -1); + r_amount = 1; + r_supports[0] = points[support_idx].pos; } +bool ConvexPolygonShape2DSW::contains_point(const Vector2 &p_point) const { -bool ConvexPolygonShape2DSW::contains_point(const Vector2& p_point) const { - - bool out=false; - bool in=false; + bool out = false; + bool in = false; - for(int i=0;i<point_count;i++) { + for (int i = 0; i < point_count; i++) { real_t d = points[i].normal.dot(p_point) - points[i].normal.dot(points[i].pos); - if (d>0) - out=true; + if (d > 0) + out = true; else - in=true; + in = true; } return (in && !out) || (!in && out); } +bool ConvexPolygonShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { -bool ConvexPolygonShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const { - - Vector2 n = (p_end-p_begin).normalized(); - real_t d=1e10; - bool inters=false; + Vector2 n = (p_end - p_begin).normalized(); + real_t d = 1e10; + bool inters = false; - for(int i=0;i<point_count;i++) { + for (int i = 0; i < point_count; i++) { //hmm crap.. no can do.. /* @@ -644,98 +592,92 @@ bool ConvexPolygonShape2DSW::intersect_segment(const Vector2& p_begin,const Vect continue; */ - Vector2 res; - if (!Geometry::segment_intersects_segment_2d(p_begin,p_end,points[i].pos,points[(i+1)%point_count].pos,&res)) + if (!Geometry::segment_intersects_segment_2d(p_begin, p_end, points[i].pos, points[(i + 1) % point_count].pos, &res)) continue; real_t nd = n.dot(res); - if (nd<d) { + if (nd < d) { - d=nd; - r_point=res; - r_normal=points[i].normal; - inters=true; + d = nd; + r_point = res; + r_normal = points[i].normal; + inters = true; } - } - if (inters) { - if (n.dot(r_normal)>0) - r_normal=-r_normal; + if (n.dot(r_normal) > 0) + r_normal = -r_normal; } //return get_aabb().intersects_segment(p_begin,p_end,&r_point,&r_normal); return inters; //todo } -real_t ConvexPolygonShape2DSW::get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const { +real_t ConvexPolygonShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { Rect2 aabb; - aabb.pos=points[0].pos*p_scale; - for(int i=0;i<point_count;i++) { + aabb.pos = points[0].pos * p_scale; + for (int i = 0; i < point_count; i++) { - aabb.expand_to(points[i].pos*p_scale); + aabb.expand_to(points[i].pos * p_scale); } - return p_mass*aabb.size.dot(aabb.size)/12.0 + p_mass * (aabb.pos+aabb.size*0.5).length_squared(); + return p_mass * aabb.size.dot(aabb.size) / 12.0 + p_mass * (aabb.pos + aabb.size * 0.5).length_squared(); } -void ConvexPolygonShape2DSW::set_data(const Variant& p_data) { - - ERR_FAIL_COND(p_data.get_type()!=Variant::POOL_VECTOR2_ARRAY && p_data.get_type()!=Variant::POOL_REAL_ARRAY); +void ConvexPolygonShape2DSW::set_data(const Variant &p_data) { + ERR_FAIL_COND(p_data.get_type() != Variant::POOL_VECTOR2_ARRAY && p_data.get_type() != Variant::POOL_REAL_ARRAY); if (points) memdelete_arr(points); - points=NULL; - point_count=0; - - if (p_data.get_type()==Variant::POOL_VECTOR2_ARRAY) { - PoolVector<Vector2> arr=p_data; - ERR_FAIL_COND(arr.size()==0); - point_count=arr.size(); - points = memnew_arr(Point,point_count); + points = NULL; + point_count = 0; + + if (p_data.get_type() == Variant::POOL_VECTOR2_ARRAY) { + PoolVector<Vector2> arr = p_data; + ERR_FAIL_COND(arr.size() == 0); + point_count = arr.size(); + points = memnew_arr(Point, point_count); PoolVector<Vector2>::Read r = arr.read(); - for(int i=0;i<point_count;i++) { - points[i].pos=r[i]; + for (int i = 0; i < point_count; i++) { + points[i].pos = r[i]; } - for(int i=0;i<point_count;i++) { + for (int i = 0; i < point_count; i++) { Vector2 p = points[i].pos; - Vector2 pn = points[(i+1)%point_count].pos; - points[i].normal=(pn-p).tangent().normalized(); + Vector2 pn = points[(i + 1) % point_count].pos; + points[i].normal = (pn - p).tangent().normalized(); } } else { PoolVector<real_t> dvr = p_data; - point_count=dvr.size()/4; - ERR_FAIL_COND(point_count==0); + point_count = dvr.size() / 4; + ERR_FAIL_COND(point_count == 0); - points = memnew_arr(Point,point_count); + points = memnew_arr(Point, point_count); PoolVector<real_t>::Read r = dvr.read(); - for(int i=0;i<point_count;i++) { - - int idx=i<<2; - points[i].pos.x=r[idx+0]; - points[i].pos.y=r[idx+1]; - points[i].normal.x=r[idx+2]; - points[i].normal.y=r[idx+3]; + for (int i = 0; i < point_count; i++) { + int idx = i << 2; + points[i].pos.x = r[idx + 0]; + points[i].pos.y = r[idx + 1]; + points[i].normal.x = r[idx + 2]; + points[i].normal.y = r[idx + 3]; } } - - ERR_FAIL_COND(point_count==0); + ERR_FAIL_COND(point_count == 0); Rect2 aabb; - aabb.pos=points[0].pos; - for(int i=1;i<point_count;i++) + aabb.pos = points[0].pos; + for (int i = 1; i < point_count; i++) aabb.expand_to(points[i].pos); configure(aabb); @@ -747,337 +689,312 @@ Variant ConvexPolygonShape2DSW::get_data() const { dvr.resize(point_count); - for(int i=0;i<point_count;i++) { - dvr.set(i,points[i].pos); + for (int i = 0; i < point_count; i++) { + dvr.set(i, points[i].pos); } return dvr; } - ConvexPolygonShape2DSW::ConvexPolygonShape2DSW() { - points=NULL; - point_count=0; - + points = NULL; + point_count = 0; } -ConvexPolygonShape2DSW::~ConvexPolygonShape2DSW(){ +ConvexPolygonShape2DSW::~ConvexPolygonShape2DSW() { if (points) memdelete_arr(points); - } ////////////////////////////////////////////////// +void ConcavePolygonShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const { -void ConcavePolygonShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const { - - real_t d=-1e10; - int idx=-1; - for(int i=0;i<points.size();i++) { + real_t d = -1e10; + int idx = -1; + for (int i = 0; i < points.size(); i++) { real_t ld = p_normal.dot(points[i]); - if (ld>d) { - d=ld; - idx=i; + if (ld > d) { + d = ld; + idx = i; } } - - r_amount=1; - ERR_FAIL_COND(idx==-1); - *r_supports=points[idx]; - + r_amount = 1; + ERR_FAIL_COND(idx == -1); + *r_supports = points[idx]; } -bool ConcavePolygonShape2DSW::contains_point(const Vector2& p_point) const { +bool ConcavePolygonShape2DSW::contains_point(const Vector2 &p_point) const { return false; //sorry } +bool ConcavePolygonShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const { -bool ConcavePolygonShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const{ - - uint32_t* stack = (uint32_t*)alloca(sizeof(int)*bvh_depth); + uint32_t *stack = (uint32_t *)alloca(sizeof(int) * bvh_depth); enum { - TEST_AABB_BIT=0, - VISIT_LEFT_BIT=1, - VISIT_RIGHT_BIT=2, - VISIT_DONE_BIT=3, - VISITED_BIT_SHIFT=29, - NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1, - VISITED_BIT_MASK=~NODE_IDX_MASK, - + TEST_AABB_BIT = 0, + VISIT_LEFT_BIT = 1, + VISIT_RIGHT_BIT = 2, + VISIT_DONE_BIT = 3, + VISITED_BIT_SHIFT = 29, + NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1, + VISITED_BIT_MASK = ~NODE_IDX_MASK, }; - Vector2 n = (p_end-p_begin).normalized(); - real_t d=1e10; - bool inters=false; + Vector2 n = (p_end - p_begin).normalized(); + real_t d = 1e10; + bool inters = false; /* for(int i=0;i<bvh_depth;i++) stack[i]=0; */ - int level=0; + int level = 0; - const Segment *segmentptr=&segments[0]; - const Vector2 *pointptr=&points[0]; + const Segment *segmentptr = &segments[0]; + const Vector2 *pointptr = &points[0]; const BVH *bvhptr = &bvh[0]; + stack[0] = 0; + while (true) { - stack[0]=0; - while(true) { - - uint32_t node = stack[level]&NODE_IDX_MASK; - const BVH &b = bvhptr[ node ]; - bool done=false; + uint32_t node = stack[level] & NODE_IDX_MASK; + const BVH &b = bvhptr[node]; + bool done = false; - switch(stack[level]>>VISITED_BIT_SHIFT) { + switch (stack[level] >> VISITED_BIT_SHIFT) { case TEST_AABB_BIT: { - - bool valid = b.aabb.intersects_segment(p_begin,p_end); + bool valid = b.aabb.intersects_segment(p_begin, p_end); if (!valid) { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - if (b.left<0) { - - const Segment &s=segmentptr[ b.right ]; - Vector2 a = pointptr[ s.points[0] ]; - Vector2 b = pointptr[ s.points[1] ]; + if (b.left < 0) { + const Segment &s = segmentptr[b.right]; + Vector2 a = pointptr[s.points[0]]; + Vector2 b = pointptr[s.points[1]]; Vector2 res; - if (Geometry::segment_intersects_segment_2d(p_begin,p_end,a,b,&res)) { + if (Geometry::segment_intersects_segment_2d(p_begin, p_end, a, b, &res)) { real_t nd = n.dot(res); - if (nd<d) { + if (nd < d) { - d=nd; - r_point=res; - r_normal=(b-a).tangent().normalized(); - inters=true; + d = nd; + r_point = res; + r_normal = (b - a).tangent().normalized(); + inters = true; } - } - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node; } } - - } continue; + } + continue; case VISIT_LEFT_BIT: { - stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.left|TEST_AABB_BIT; + stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.left | TEST_AABB_BIT; level++; - - } continue; + } + continue; case VISIT_RIGHT_BIT: { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.right|TEST_AABB_BIT; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.right | TEST_AABB_BIT; level++; - } continue; + } + continue; case VISIT_DONE_BIT: { - if (level==0) { - done=true; + if (level == 0) { + done = true; break; } else level--; - - } continue; + } + continue; } - if (done) break; } - if (inters) { - if (n.dot(r_normal)>0) - r_normal=-r_normal; + if (n.dot(r_normal) > 0) + r_normal = -r_normal; } return inters; - } +int ConcavePolygonShape2DSW::_generate_bvh(BVH *p_bvh, int p_len, int p_depth) { + if (p_len == 1) { -int ConcavePolygonShape2DSW::_generate_bvh(BVH *p_bvh,int p_len,int p_depth) { - - if (p_len==1) { - - bvh_depth=MAX(p_depth,bvh_depth); + bvh_depth = MAX(p_depth, bvh_depth); bvh.push_back(*p_bvh); - return bvh.size()-1; + return bvh.size() - 1; } //else sort best - Rect2 global_aabb=p_bvh[0].aabb; - for(int i=1;i<p_len;i++) { - global_aabb=global_aabb.merge(p_bvh[i].aabb); + Rect2 global_aabb = p_bvh[0].aabb; + for (int i = 1; i < p_len; i++) { + global_aabb = global_aabb.merge(p_bvh[i].aabb); } if (global_aabb.size.x > global_aabb.size.y) { - SortArray<BVH,BVH_CompareX> sort; - sort.sort(p_bvh,p_len); + SortArray<BVH, BVH_CompareX> sort; + sort.sort(p_bvh, p_len); } else { - SortArray<BVH,BVH_CompareY> sort; - sort.sort(p_bvh,p_len); - + SortArray<BVH, BVH_CompareY> sort; + sort.sort(p_bvh, p_len); } - int median = p_len/2; - + int median = p_len / 2; BVH node; - node.aabb=global_aabb; + node.aabb = global_aabb; int node_idx = bvh.size(); bvh.push_back(node); - int l = _generate_bvh(p_bvh,median,p_depth+1); - int r = _generate_bvh(&p_bvh[median],p_len-median,p_depth+1); - bvh[node_idx].left=l; - bvh[node_idx].right=r; + int l = _generate_bvh(p_bvh, median, p_depth + 1); + int r = _generate_bvh(&p_bvh[median], p_len - median, p_depth + 1); + bvh[node_idx].left = l; + bvh[node_idx].right = r; return node_idx; - } -void ConcavePolygonShape2DSW::set_data(const Variant& p_data) { +void ConcavePolygonShape2DSW::set_data(const Variant &p_data) { - ERR_FAIL_COND(p_data.get_type()!=Variant::POOL_VECTOR2_ARRAY && p_data.get_type()!=Variant::POOL_REAL_ARRAY); + ERR_FAIL_COND(p_data.get_type() != Variant::POOL_VECTOR2_ARRAY && p_data.get_type() != Variant::POOL_REAL_ARRAY); Rect2 aabb; - if (p_data.get_type()==Variant::POOL_VECTOR2_ARRAY) { + if (p_data.get_type() == Variant::POOL_VECTOR2_ARRAY) { PoolVector<Vector2> p2arr = p_data; int len = p2arr.size(); - ERR_FAIL_COND(len%2); + ERR_FAIL_COND(len % 2); segments.clear(); points.clear(); bvh.clear(); - bvh_depth=1; + bvh_depth = 1; - if (len==0) { + if (len == 0) { configure(aabb); return; } PoolVector<Vector2>::Read arr = p2arr.read(); - Map<Point2,int> pointmap; - for(int i=0;i<len;i+=2) { + Map<Point2, int> pointmap; + for (int i = 0; i < len; i += 2) { - Point2 p1 =arr[i]; - Point2 p2 =arr[i+1]; - int idx_p1,idx_p2; + Point2 p1 = arr[i]; + Point2 p2 = arr[i + 1]; + int idx_p1, idx_p2; if (pointmap.has(p1)) { - idx_p1=pointmap[p1]; + idx_p1 = pointmap[p1]; } else { - idx_p1=pointmap.size(); - pointmap[p1]=idx_p1; + idx_p1 = pointmap.size(); + pointmap[p1] = idx_p1; } if (pointmap.has(p2)) { - idx_p2=pointmap[p2]; + idx_p2 = pointmap[p2]; } else { - idx_p2=pointmap.size(); - pointmap[p2]=idx_p2; + idx_p2 = pointmap.size(); + pointmap[p2] = idx_p2; } Segment s; - s.points[0]=idx_p1; - s.points[1]=idx_p2; + s.points[0] = idx_p1; + s.points[1] = idx_p2; segments.push_back(s); } points.resize(pointmap.size()); - aabb.pos=pointmap.front()->key(); - for(Map<Point2,int>::Element *E=pointmap.front();E;E=E->next()) { + aabb.pos = pointmap.front()->key(); + for (Map<Point2, int>::Element *E = pointmap.front(); E; E = E->next()) { aabb.expand_to(E->key()); - points[E->get()]=E->key(); + points[E->get()] = E->key(); } Vector<BVH> main_vbh; main_vbh.resize(segments.size()); - for(int i=0;i<main_vbh.size();i++) { + for (int i = 0; i < main_vbh.size(); i++) { - - main_vbh[i].aabb.pos=points[segments[i].points[0]]; + main_vbh[i].aabb.pos = points[segments[i].points[0]]; main_vbh[i].aabb.expand_to(points[segments[i].points[1]]); - main_vbh[i].left=-1; - main_vbh[i].right=i; + main_vbh[i].left = -1; + main_vbh[i].right = i; } - _generate_bvh(&main_vbh[0],main_vbh.size(),1); - + _generate_bvh(&main_vbh[0], main_vbh.size(), 1); } else { //dictionary with arrays - } - configure(aabb); } Variant ConcavePolygonShape2DSW::get_data() const { - PoolVector<Vector2> rsegments; int len = segments.size(); - rsegments.resize(len*2); + rsegments.resize(len * 2); PoolVector<Vector2>::Write w = rsegments.write(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - w[(i<<1)+0]=points[segments[i].points[0]]; - w[(i<<1)+1]=points[segments[i].points[1]]; + w[(i << 1) + 0] = points[segments[i].points[0]]; + w[(i << 1) + 1] = points[segments[i].points[1]]; } - w=PoolVector<Vector2>::Write(); + w = PoolVector<Vector2>::Write(); return rsegments; } -void ConcavePolygonShape2DSW::cull(const Rect2& p_local_aabb,Callback p_callback,void* p_userdata) const { +void ConcavePolygonShape2DSW::cull(const Rect2 &p_local_aabb, Callback p_callback, void *p_userdata) const { - uint32_t* stack = (uint32_t*)alloca(sizeof(int)*bvh_depth); + uint32_t *stack = (uint32_t *)alloca(sizeof(int) * bvh_depth); enum { - TEST_AABB_BIT=0, - VISIT_LEFT_BIT=1, - VISIT_RIGHT_BIT=2, - VISIT_DONE_BIT=3, - VISITED_BIT_SHIFT=29, - NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1, - VISITED_BIT_MASK=~NODE_IDX_MASK, - + TEST_AABB_BIT = 0, + VISIT_LEFT_BIT = 1, + VISIT_RIGHT_BIT = 2, + VISIT_DONE_BIT = 3, + VISITED_BIT_SHIFT = 29, + NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1, + VISITED_BIT_MASK = ~NODE_IDX_MASK, }; @@ -1086,73 +1003,68 @@ void ConcavePolygonShape2DSW::cull(const Rect2& p_local_aabb,Callback p_callback stack[i]=0; */ + int level = 0; - int level=0; - - const Segment *segmentptr=&segments[0]; - const Vector2 *pointptr=&points[0]; + const Segment *segmentptr = &segments[0]; + const Vector2 *pointptr = &points[0]; const BVH *bvhptr = &bvh[0]; + stack[0] = 0; + while (true) { - stack[0]=0; - while(true) { - - uint32_t node = stack[level]&NODE_IDX_MASK; - const BVH &b = bvhptr[ node ]; + uint32_t node = stack[level] & NODE_IDX_MASK; + const BVH &b = bvhptr[node]; - switch(stack[level]>>VISITED_BIT_SHIFT) { + switch (stack[level] >> VISITED_BIT_SHIFT) { case TEST_AABB_BIT: { - bool valid = p_local_aabb.intersects(b.aabb); if (!valid) { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - if (b.left<0) { + if (b.left < 0) { - const Segment &s=segmentptr[ b.right ]; - Vector2 a = pointptr[ s.points[0] ]; - Vector2 b = pointptr[ s.points[1] ]; + const Segment &s = segmentptr[b.right]; + Vector2 a = pointptr[s.points[0]]; + Vector2 b = pointptr[s.points[1]]; - SegmentShape2DSW ss(a,b,(b-a).tangent().normalized()); + SegmentShape2DSW ss(a, b, (b - a).tangent().normalized()); - p_callback(p_userdata,&ss); - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; + p_callback(p_userdata, &ss); + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; } else { - stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node; + stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node; } } - - } continue; + } + continue; case VISIT_LEFT_BIT: { - stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.left|TEST_AABB_BIT; + stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.left | TEST_AABB_BIT; level++; - - } continue; + } + continue; case VISIT_RIGHT_BIT: { - stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node; - stack[level+1]=b.right|TEST_AABB_BIT; + stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; + stack[level + 1] = b.right | TEST_AABB_BIT; level++; - } continue; + } + continue; case VISIT_DONE_BIT: { - if (level==0) + if (level == 0) return; else level--; - - } continue; + } + continue; } } - } - - diff --git a/servers/physics_2d/shape_2d_sw.h b/servers/physics_2d/shape_2d_sw.h index c04cdfa456..00d86da7fb 100644 --- a/servers/physics_2d/shape_2d_sw.h +++ b/servers/physics_2d/shape_2d_sw.h @@ -46,11 +46,10 @@ SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_creat class Shape2DSW; -class ShapeOwner2DSW : public RID_Data{ +class ShapeOwner2DSW : public RID_Data { public: - - virtual void _shape_changed()=0; - virtual void remove_shape(Shape2DSW *p_shape)=0; + virtual void _shape_changed() = 0; + virtual void remove_shape(Shape2DSW *p_shape) = 0; virtual ~ShapeOwner2DSW() {} }; @@ -62,77 +61,75 @@ class Shape2DSW : public RID_Data { bool configured; real_t custom_bias; - Map<ShapeOwner2DSW*,int> owners; + Map<ShapeOwner2DSW *, int> owners; + protected: + void configure(const Rect2 &p_aabb); - void configure(const Rect2& p_aabb); public: + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } + _FORCE_INLINE_ RID get_self() const { return self; } - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } - _FORCE_INLINE_ RID get_self() const {return self; } - - virtual Physics2DServer::ShapeType get_type() const=0; + virtual Physics2DServer::ShapeType get_type() const = 0; _FORCE_INLINE_ Rect2 get_aabb() const { return aabb; } _FORCE_INLINE_ bool is_configured() const { return configured; } virtual bool is_concave() const { return false; } - virtual bool contains_point(const Vector2& p_point) const=0; + virtual bool contains_point(const Vector2 &p_point) const = 0; - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const=0; - virtual void project_range_castv(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const=0; - virtual Vector2 get_support(const Vector2& p_normal) const; - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const=0; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const = 0; + virtual void project_range_castv(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const = 0; + virtual Vector2 get_support(const Vector2 &p_normal) const; + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const = 0; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const=0; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const=0; - virtual void set_data(const Variant& p_data)=0; - virtual Variant get_data() const=0; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const = 0; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const = 0; + virtual void set_data(const Variant &p_data) = 0; + virtual Variant get_data() const = 0; - _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias=p_bias; } + _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias = p_bias; } _FORCE_INLINE_ real_t get_custom_bias() const { return custom_bias; } void add_owner(ShapeOwner2DSW *p_owner); void remove_owner(ShapeOwner2DSW *p_owner); bool is_owner(ShapeOwner2DSW *p_owner) const; - const Map<ShapeOwner2DSW*,int>& get_owners() const; - + const Map<ShapeOwner2DSW *, int> &get_owners() const; - _FORCE_INLINE_ void get_supports_transformed_cast(const Vector2& p_cast,const Vector2& p_normal,const Transform2D& p_xform,Vector2 *r_supports,int & r_amount) const { + _FORCE_INLINE_ void get_supports_transformed_cast(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_xform, Vector2 *r_supports, int &r_amount) const { - get_supports(p_xform.basis_xform_inv(p_normal).normalized(),r_supports,r_amount); - for(int i=0;i<r_amount;i++) - r_supports[i]=p_xform.xform(r_supports[i]); + get_supports(p_xform.basis_xform_inv(p_normal).normalized(), r_supports, r_amount); + for (int i = 0; i < r_amount; i++) + r_supports[i] = p_xform.xform(r_supports[i]); - if (r_amount==1) { + if (r_amount == 1) { - if (Math::abs( p_normal.dot(p_cast.normalized()) )<(1.0-_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) ) { + if (Math::abs(p_normal.dot(p_cast.normalized())) < (1.0 - _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)) { //make line because they are parallel - r_amount=2; - r_supports[1]=r_supports[0]+p_cast; - } else if (p_cast.dot(p_normal)>0) { + r_amount = 2; + r_supports[1] = r_supports[0] + p_cast; + } else if (p_cast.dot(p_normal) > 0) { //normal points towards cast, add cast - r_supports[0]+=p_cast; + r_supports[0] += p_cast; } } else { - if (Math::abs( p_normal.dot(p_cast.normalized()) )<(1.0-_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) ) { + if (Math::abs(p_normal.dot(p_cast.normalized())) < (1.0 - _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)) { //optimize line and make it larger because they are parallel - if ((r_supports[1]-r_supports[0]).dot(p_cast)>0) { + if ((r_supports[1] - r_supports[0]).dot(p_cast) > 0) { //larger towards 1 - r_supports[1]+=p_cast; + r_supports[1] += p_cast; } else { //larger towards 0 - r_supports[0]+=p_cast; + r_supports[0] += p_cast; } - } else if (p_cast.dot(p_normal)>0) { + } else if (p_cast.dot(p_normal) > 0) { //normal points towards cast, add cast - r_supports[0]+=p_cast; - r_supports[1]+=p_cast; + r_supports[0] += p_cast; + r_supports[1] += p_cast; } - } } @@ -141,305 +138,274 @@ public: }; //let the optimizer do the magic -#define DEFAULT_PROJECT_RANGE_CAST \ -virtual void project_range_castv(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {\ - project_range_cast(p_cast,p_normal,p_transform,r_min,r_max);\ -}\ -_FORCE_INLINE_ void project_range_cast(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {\ -\ - real_t mina,maxa;\ - real_t minb,maxb;\ - Transform2D ofsb=p_transform;\ - ofsb.elements[2]+=p_cast;\ - project_range(p_normal,p_transform,mina,maxa);\ - project_range(p_normal,ofsb,minb,maxb); \ - r_min=MIN(mina,minb);\ - r_max=MAX(maxa,maxb);\ -} +#define DEFAULT_PROJECT_RANGE_CAST \ + virtual void project_range_castv(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { \ + project_range_cast(p_cast, p_normal, p_transform, r_min, r_max); \ + } \ + _FORCE_INLINE_ void project_range_cast(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { \ + \ + real_t mina, maxa; \ + real_t minb, maxb; \ + Transform2D ofsb = p_transform; \ + ofsb.elements[2] += p_cast; \ + project_range(p_normal, p_transform, mina, maxa); \ + project_range(p_normal, ofsb, minb, maxb); \ + r_min = MIN(mina, minb); \ + r_max = MAX(maxa, maxb); \ + } class LineShape2DSW : public Shape2DSW { - Vector2 normal; real_t d; public: - _FORCE_INLINE_ Vector2 get_normal() const { return normal; } _FORCE_INLINE_ real_t get_d() const { return d; } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_LINE; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { //real large - r_min=-1e10; - r_max=1e10; + r_min = -1e10; + r_max = 1e10; } - virtual void project_range_castv(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { - project_range_cast(p_cast,p_normal,p_transform,r_min,r_max); + virtual void project_range_castv(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { + project_range_cast(p_cast, p_normal, p_transform, r_min, r_max); } - _FORCE_INLINE_ void project_range_cast(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range_cast(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { //real large - r_min=-1e10; - r_max=1e10; + r_min = -1e10; + r_max = 1e10; } - - - }; - class RayShape2DSW : public Shape2DSW { - real_t length; public: - - - _FORCE_INLINE_ real_t get_length() const { return length; } + _FORCE_INLINE_ real_t get_length() const { return length; } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_RAY; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { //real large r_max = p_normal.dot(p_transform.get_origin()); - r_min = p_normal.dot(p_transform.xform(Vector2(0,length))); - if (r_max<r_min) { + r_min = p_normal.dot(p_transform.xform(Vector2(0, length))); + if (r_max < r_min) { - SWAP(r_max,r_min); + SWAP(r_max, r_min); } } DEFAULT_PROJECT_RANGE_CAST - _FORCE_INLINE_ RayShape2DSW() {} - _FORCE_INLINE_ RayShape2DSW(real_t p_length) { length=p_length; } + _FORCE_INLINE_ RayShape2DSW(real_t p_length) { length = p_length; } }; - class SegmentShape2DSW : public Shape2DSW { - Vector2 a; Vector2 b; Vector2 n; public: - - - _FORCE_INLINE_ const Vector2& get_a() const { return a; } - _FORCE_INLINE_ const Vector2& get_b() const { return b; } - _FORCE_INLINE_ const Vector2& get_normal() const { return n; } + _FORCE_INLINE_ const Vector2 &get_a() const { return a; } + _FORCE_INLINE_ const Vector2 &get_b() const { return b; } + _FORCE_INLINE_ const Vector2 &get_normal() const { return n; } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_SEGMENT; } - _FORCE_INLINE_ Vector2 get_xformed_normal(const Transform2D& p_xform) const { + _FORCE_INLINE_ Vector2 get_xformed_normal(const Transform2D &p_xform) const { return (p_xform.xform(b) - p_xform.xform(a)).normalized().tangent(); } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { //real large r_max = p_normal.dot(p_transform.xform(a)); r_min = p_normal.dot(p_transform.xform(b)); - if (r_max<r_min) { + if (r_max < r_min) { - SWAP(r_max,r_min); + SWAP(r_max, r_min); } } DEFAULT_PROJECT_RANGE_CAST _FORCE_INLINE_ SegmentShape2DSW() {} - _FORCE_INLINE_ SegmentShape2DSW(const Vector2& p_a,const Vector2& p_b,const Vector2& p_n) { a=p_a; b=p_b; n=p_n; } + _FORCE_INLINE_ SegmentShape2DSW(const Vector2 &p_a, const Vector2 &p_b, const Vector2 &p_n) { + a = p_a; + b = p_b; + n = p_n; + } }; - class CircleShape2DSW : public Shape2DSW { - real_t radius; public: - - _FORCE_INLINE_ const real_t& get_radius() const { return radius; } + _FORCE_INLINE_ const real_t &get_radius() const { return radius; } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CIRCLE; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { //real large - real_t d = p_normal.dot( p_transform.get_origin() ); + real_t d = p_normal.dot(p_transform.get_origin()); // figure out scale at point Vector2 local_normal = p_transform.basis_xform_inv(p_normal); real_t scale = local_normal.length(); - r_min = d - (radius) * scale; - r_max = d + (radius) * scale; + r_min = d - (radius)*scale; + r_max = d + (radius)*scale; } - DEFAULT_PROJECT_RANGE_CAST - }; - - class RectangleShape2DSW : public Shape2DSW { - Vector2 half_extents; public: - - _FORCE_INLINE_ const Vector2& get_half_extents() const { return half_extents; } + _FORCE_INLINE_ const Vector2 &get_half_extents() const { return half_extents; } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_RECTANGLE; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { // no matter the angle, the box is mirrored anyway - r_max=-1e20; - r_min=1e20; - for(int i=0;i<4;i++) { - - real_t d=p_normal.dot(p_transform.xform(Vector2( ((i&1)*2-1)*half_extents.x, ((i>>1)*2-1)*half_extents.y ))); + r_max = -1e20; + r_min = 1e20; + for (int i = 0; i < 4; i++) { - if (d>r_max) - r_max=d; - if (d<r_min) - r_min=d; + real_t d = p_normal.dot(p_transform.xform(Vector2(((i & 1) * 2 - 1) * half_extents.x, ((i >> 1) * 2 - 1) * half_extents.y))); + if (d > r_max) + r_max = d; + if (d < r_min) + r_min = d; } } - - - _FORCE_INLINE_ Vector2 get_circle_axis(const Transform2D& p_xform, const Transform2D& p_xform_inv,const Vector2& p_circle) const { + _FORCE_INLINE_ Vector2 get_circle_axis(const Transform2D &p_xform, const Transform2D &p_xform_inv, const Vector2 &p_circle) const { Vector2 local_v = p_xform_inv.xform(p_circle); Vector2 he( - (local_v.x<0) ? -half_extents.x : half_extents.x, - (local_v.y<0) ? -half_extents.y : half_extents.y - ); + (local_v.x < 0) ? -half_extents.x : half_extents.x, + (local_v.y < 0) ? -half_extents.y : half_extents.y); - return (p_xform.xform(he)-p_circle).normalized(); + return (p_xform.xform(he) - p_circle).normalized(); } - _FORCE_INLINE_ Vector2 get_box_axis(const Transform2D& p_xform, const Transform2D& p_xform_inv,const RectangleShape2DSW *p_B,const Transform2D& p_B_xform, const Transform2D& p_B_xform_inv) const { + _FORCE_INLINE_ Vector2 get_box_axis(const Transform2D &p_xform, const Transform2D &p_xform_inv, const RectangleShape2DSW *p_B, const Transform2D &p_B_xform, const Transform2D &p_B_xform_inv) const { - Vector2 a,b; + Vector2 a, b; { Vector2 local_v = p_xform_inv.xform(p_B_xform.get_origin()); Vector2 he( - (local_v.x<0) ? -half_extents.x : half_extents.x, - (local_v.y<0) ? -half_extents.y : half_extents.y - ); - - a=p_xform.xform(he); + (local_v.x < 0) ? -half_extents.x : half_extents.x, + (local_v.y < 0) ? -half_extents.y : half_extents.y); + a = p_xform.xform(he); } { Vector2 local_v = p_B_xform_inv.xform(p_xform.get_origin()); Vector2 he( - (local_v.x<0) ? -p_B->half_extents.x : p_B->half_extents.x, - (local_v.y<0) ? -p_B->half_extents.y : p_B->half_extents.y - ); - - b=p_B_xform.xform(he); + (local_v.x < 0) ? -p_B->half_extents.x : p_B->half_extents.x, + (local_v.y < 0) ? -p_B->half_extents.y : p_B->half_extents.y); + b = p_B_xform.xform(he); } - return (a-b).normalized(); + return (a - b).normalized(); } - DEFAULT_PROJECT_RANGE_CAST - }; class CapsuleShape2DSW : public Shape2DSW { - real_t radius; real_t height; public: - - _FORCE_INLINE_ const real_t& get_radius() const { return radius; } - _FORCE_INLINE_ const real_t& get_height() const { return height; } + _FORCE_INLINE_ const real_t &get_radius() const { return radius; } + _FORCE_INLINE_ const real_t &get_height() const { return height; } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CAPSULE; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { // no matter the angle, the box is mirrored anyway - Vector2 n=p_transform.basis_xform_inv(p_normal).normalized(); + Vector2 n = p_transform.basis_xform_inv(p_normal).normalized(); real_t h = (n.y > 0) ? height : -height; n *= radius; @@ -448,24 +414,19 @@ public: r_max = p_normal.dot(p_transform.xform(n)); r_min = p_normal.dot(p_transform.xform(-n)); - if (r_max<r_min) { + if (r_max < r_min) { - SWAP(r_max,r_min); + SWAP(r_max, r_min); } //ERR_FAIL_COND( r_max < r_min ); } DEFAULT_PROJECT_RANGE_CAST - }; - - - class ConvexPolygonShape2DSW : public Shape2DSW { - struct Point { Vector2 pos; @@ -476,44 +437,41 @@ class ConvexPolygonShape2DSW : public Shape2DSW { int point_count; public: - _FORCE_INLINE_ int get_point_count() const { return point_count; } - _FORCE_INLINE_ const Vector2& get_point(int p_idx) const { return points[p_idx].pos; } - _FORCE_INLINE_ const Vector2& get_segment_normal(int p_idx) const { return points[p_idx].normal; } - _FORCE_INLINE_ Vector2 get_xformed_segment_normal(const Transform2D& p_xform, int p_idx) const { + _FORCE_INLINE_ const Vector2 &get_point(int p_idx) const { return points[p_idx].pos; } + _FORCE_INLINE_ const Vector2 &get_segment_normal(int p_idx) const { return points[p_idx].normal; } + _FORCE_INLINE_ Vector2 get_xformed_segment_normal(const Transform2D &p_xform, int p_idx) const { Vector2 a = points[p_idx].pos; p_idx++; - Vector2 b = points[p_idx==point_count?0:p_idx].pos; - return (p_xform.xform(b)-p_xform.xform(a)).normalized().tangent(); + Vector2 b = points[p_idx == point_count ? 0 : p_idx].pos; + return (p_xform.xform(b) - p_xform.xform(a)).normalized().tangent(); } virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CONVEX_POLYGON; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const; - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { + _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { // no matter the angle, the box is mirrored anyway r_min = r_max = p_normal.dot(p_transform.xform(points[0].pos)); - for(int i=1;i<point_count;i++) { + for (int i = 1; i < point_count; i++) { real_t d = p_normal.dot(p_transform.xform(points[i].pos)); - if (d>r_max) - r_max=d; - if (d<r_min) - r_min=d; - + if (d > r_max) + r_max = d; + if (d < r_min) + r_min = d; } - } DEFAULT_PROJECT_RANGE_CAST @@ -522,16 +480,13 @@ public: ~ConvexPolygonShape2DSW(); }; - class ConcaveShape2DSW : public Shape2DSW { public: - virtual bool is_concave() const { return true; } - typedef void (*Callback)(void* p_userdata,Shape2DSW *p_convex); - - virtual void cull(const Rect2& p_local_aabb,Callback p_callback,void* p_userdata) const=0; + typedef void (*Callback)(void *p_userdata, Shape2DSW *p_convex); + virtual void cull(const Rect2 &p_local_aabb, Callback p_callback, void *p_userdata) const = 0; }; class ConcavePolygonShape2DSW : public ConcaveShape2DSW { @@ -547,53 +502,50 @@ class ConcavePolygonShape2DSW : public ConcaveShape2DSW { struct BVH { Rect2 aabb; - int left,right; + int left, right; }; - Vector<BVH> bvh; int bvh_depth; - struct BVH_CompareX { - _FORCE_INLINE_ bool operator ()(const BVH& a, const BVH& b) const { + _FORCE_INLINE_ bool operator()(const BVH &a, const BVH &b) const { - return (a.aabb.pos.x+a.aabb.size.x*0.5) < (b.aabb.pos.x+b.aabb.size.x*0.5); + return (a.aabb.pos.x + a.aabb.size.x * 0.5) < (b.aabb.pos.x + b.aabb.size.x * 0.5); } }; struct BVH_CompareY { - _FORCE_INLINE_ bool operator ()(const BVH& a, const BVH& b) const { + _FORCE_INLINE_ bool operator()(const BVH &a, const BVH &b) const { - return (a.aabb.pos.y+a.aabb.size.y*0.5) < (b.aabb.pos.y+b.aabb.size.y*0.5); + return (a.aabb.pos.y + a.aabb.size.y * 0.5) < (b.aabb.pos.y + b.aabb.size.y * 0.5); } }; - int _generate_bvh(BVH *p_bvh,int p_len,int p_depth); + int _generate_bvh(BVH *p_bvh, int p_len, int p_depth); public: - virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CONCAVE_POLYGON; } - virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/ } - virtual void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/ } - virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const; + virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/ + } + virtual void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/ + } + virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const; - virtual bool contains_point(const Vector2& p_point) const; - virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const; + virtual bool contains_point(const Vector2 &p_point) const; + virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const; - virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const { return 0; } + virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { return 0; } - virtual void set_data(const Variant& p_data); + virtual void set_data(const Variant &p_data); virtual Variant get_data() const; - virtual void cull(const Rect2& p_local_aabb,Callback p_callback,void* p_userdata) const; - + virtual void cull(const Rect2 &p_local_aabb, Callback p_callback, void *p_userdata) const; DEFAULT_PROJECT_RANGE_CAST - }; #undef DEFAULT_PROJECT_RANGE_CAST diff --git a/servers/physics_2d/space_2d_sw.cpp b/servers/physics_2d/space_2d_sw.cpp index 9bced50061..93df0a00f6 100644 --- a/servers/physics_2d/space_2d_sw.cpp +++ b/servers/physics_2d/space_2d_sw.cpp @@ -30,109 +30,101 @@ #include "collision_solver_2d_sw.h" #include "physics_2d_server_sw.h" - _FORCE_INLINE_ static bool _match_object_type_query(CollisionObject2DSW *p_object, uint32_t p_layer_mask, uint32_t p_type_mask) { - if ((p_object->get_layer_mask()&p_layer_mask)==0) + if ((p_object->get_layer_mask() & p_layer_mask) == 0) return false; - if (p_object->get_type()==CollisionObject2DSW::TYPE_AREA) - return p_type_mask&Physics2DDirectSpaceState::TYPE_MASK_AREA; - - Body2DSW *body = static_cast<Body2DSW*>(p_object); + if (p_object->get_type() == CollisionObject2DSW::TYPE_AREA) + return p_type_mask & Physics2DDirectSpaceState::TYPE_MASK_AREA; - return (1<<body->get_mode())&p_type_mask; + Body2DSW *body = static_cast<Body2DSW *>(p_object); + return (1 << body->get_mode()) & p_type_mask; } +int Physics2DDirectSpaceStateSW::intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_point) { -int Physics2DDirectSpaceStateSW::intersect_point(const Vector2& p_point,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask,bool p_pick_point) { - - if (p_result_max<=0) + if (p_result_max <= 0) return 0; Rect2 aabb; - aabb.pos=p_point-Vector2(0.00001,0.00001); - aabb.size=Vector2(0.00002,0.00002); + aabb.pos = p_point - Vector2(0.00001, 0.00001); + aabb.size = Vector2(0.00002, 0.00002); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); - int cc=0; + int cc = 0; - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; - const CollisionObject2DSW *col_obj=space->intersection_query_results[i]; + const CollisionObject2DSW *col_obj = space->intersection_query_results[i]; if (p_pick_point && !col_obj->is_pickable()) continue; - int shape_idx=space->intersection_query_subindex_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - Shape2DSW * shape = col_obj->get_shape(shape_idx); + Shape2DSW *shape = col_obj->get_shape(shape_idx); Vector2 local_point = (col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).affine_inverse().xform(p_point); if (!shape->contains_point(local_point)) continue; - if (cc>=p_result_max) + if (cc >= p_result_max) continue; - r_results[cc].collider_id=col_obj->get_instance_id(); - if (r_results[cc].collider_id!=0) - r_results[cc].collider=ObjectDB::get_instance(r_results[cc].collider_id); - r_results[cc].rid=col_obj->get_self(); - r_results[cc].shape=shape_idx; - r_results[cc].metadata=col_obj->get_shape_metadata(shape_idx); + r_results[cc].collider_id = col_obj->get_instance_id(); + if (r_results[cc].collider_id != 0) + r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id); + r_results[cc].rid = col_obj->get_self(); + r_results[cc].shape = shape_idx; + r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx); cc++; } return cc; - - } -bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2& p_from, const Vector2& p_to,RayResult &r_result,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - +bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { + ERR_FAIL_COND_V(space->locked, false); - ERR_FAIL_COND_V(space->locked,false); - - Vector2 begin,end; + Vector2 begin, end; Vector2 normal; - begin=p_from; - end=p_to; - normal=(end-begin).normalized(); + begin = p_from; + end = p_to; + normal = (end - begin).normalized(); - int amount = space->broadphase->cull_segment(begin,end,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); //todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision - bool collided=false; - Vector2 res_point,res_normal; + bool collided = false; + Vector2 res_point, res_normal; int res_shape; const CollisionObject2DSW *res_obj; - real_t min_d=1e10; + real_t min_d = 1e10; + for (int i = 0; i < amount; i++) { - for(int i=0;i<amount;i++) { - - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; - const CollisionObject2DSW *col_obj=space->intersection_query_results[i]; + const CollisionObject2DSW *col_obj = space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; Transform2D inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform(); Vector2 local_from = inv_xform.xform(begin); @@ -146,131 +138,113 @@ bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2& p_from, const Vec const Shape2DSW *shape = col_obj->get_shape(shape_idx); - Vector2 shape_point,shape_normal; - - - if (shape->intersect_segment(local_from,local_to,shape_point,shape_normal)) { - + Vector2 shape_point, shape_normal; + if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) { Transform2D xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx); - shape_point=xform.xform(shape_point); + shape_point = xform.xform(shape_point); real_t ld = normal.dot(shape_point); + if (ld < min_d) { - if (ld<min_d) { - - min_d=ld; - res_point=shape_point; - res_normal=inv_xform.basis_xform_inv(shape_normal).normalized(); - res_shape=shape_idx; - res_obj=col_obj; - collided=true; + min_d = ld; + res_point = shape_point; + res_normal = inv_xform.basis_xform_inv(shape_normal).normalized(); + res_shape = shape_idx; + res_obj = col_obj; + collided = true; } } - } if (!collided) return false; - - r_result.collider_id=res_obj->get_instance_id(); - if (r_result.collider_id!=0) - r_result.collider=ObjectDB::get_instance(r_result.collider_id); - r_result.normal=res_normal; - r_result.metadata=res_obj->get_shape_metadata(res_shape); - r_result.position=res_point; - r_result.rid=res_obj->get_self(); - r_result.shape=res_shape; + r_result.collider_id = res_obj->get_instance_id(); + if (r_result.collider_id != 0) + r_result.collider = ObjectDB::get_instance(r_result.collider_id); + r_result.normal = res_normal; + r_result.metadata = res_obj->get_shape_metadata(res_shape); + r_result.position = res_point; + r_result.rid = res_obj->get_self(); + r_result.shape = res_shape; return true; - } +int Physics2DDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { -int Physics2DDirectSpaceStateSW::intersect_shape(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - - if (p_result_max<=0) + if (p_result_max <= 0) return 0; Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ERR_FAIL_COND_V(!shape, 0); Rect2 aabb = p_xform.xform(shape->get_aabb()); - aabb=aabb.grow(p_margin); + aabb = aabb.grow(p_margin); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,p_result_max,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, p_result_max, space->intersection_query_subindex_results); - int cc=0; + int cc = 0; - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; + const CollisionObject2DSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - const CollisionObject2DSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; - - if (!CollisionSolver2DSW::solve(shape,p_xform,p_motion,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2(),NULL,NULL,NULL,p_margin)) + if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), NULL, NULL, NULL, p_margin)) continue; - r_results[cc].collider_id=col_obj->get_instance_id(); - if (r_results[cc].collider_id!=0) - r_results[cc].collider=ObjectDB::get_instance(r_results[cc].collider_id); - r_results[cc].rid=col_obj->get_self(); - r_results[cc].shape=shape_idx; - r_results[cc].metadata=col_obj->get_shape_metadata(shape_idx); + r_results[cc].collider_id = col_obj->get_instance_id(); + if (r_results[cc].collider_id != 0) + r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id); + r_results[cc].rid = col_obj->get_self(); + r_results[cc].shape = shape_idx; + r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx); cc++; - } return cc; - } - - -bool Physics2DDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - - +bool Physics2DDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,false); + ERR_FAIL_COND_V(!shape, false); Rect2 aabb = p_xform.xform(shape->get_aabb()); - aabb=aabb.merge(Rect2(aabb.pos+p_motion,aabb.size)); //motion - aabb=aabb.grow(p_margin); + aabb = aabb.merge(Rect2(aabb.pos + p_motion, aabb.size)); //motion + aabb = aabb.grow(p_margin); /* if (p_motion!=Vector2()) print_line(p_motion); */ - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); - - real_t best_safe=1; - real_t best_unsafe=1; + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); - for(int i=0;i<amount;i++) { + real_t best_safe = 1; + real_t best_unsafe = 1; + for (int i = 0; i < amount; i++) { - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - if (p_exclude.has( space->intersection_query_results[i]->get_self())) + if (p_exclude.has(space->intersection_query_results[i]->get_self())) continue; //ignore excluded - - const CollisionObject2DSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; - + const CollisionObject2DSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; /*if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { @@ -281,21 +255,19 @@ bool Physics2DDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transfor } }*/ - Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx); //test initial overlap, does it collide if going all the way? - if (!CollisionSolver2DSW::solve(shape,p_xform,p_motion,col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,p_margin)) { + if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, p_margin)) { continue; } - //test initial overlap - if (CollisionSolver2DSW::solve(shape,p_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,p_margin)) { + if (CollisionSolver2DSW::solve(shape, p_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, p_margin)) { - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { //if one way collision direction ignore initial overlap - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - if (body->get_one_way_collision_direction()!=Vector2()) { + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + if (body->get_one_way_collision_direction() != Vector2()) { continue; } } @@ -303,131 +275,119 @@ bool Physics2DDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transfor return false; } - //just do kinematic solving - real_t low=0; - real_t hi=1; - Vector2 mnormal=p_motion.normalized(); + real_t low = 0; + real_t hi = 1; + Vector2 mnormal = p_motion.normalized(); - for(int i=0;i<8;i++) { //steps should be customizable.. + for (int i = 0; i < 8; i++) { //steps should be customizable.. - real_t ofs = (low+hi)*0.5; + real_t ofs = (low + hi) * 0.5; - Vector2 sep=mnormal; //important optimization for this to work fast enough - bool collided = CollisionSolver2DSW::solve(shape,p_xform,p_motion*ofs,col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),NULL,NULL,&sep,p_margin); + Vector2 sep = mnormal; //important optimization for this to work fast enough + bool collided = CollisionSolver2DSW::solve(shape, p_xform, p_motion * ofs, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, &sep, p_margin); if (collided) { - hi=ofs; + hi = ofs; } else { - low=ofs; + low = ofs; } } - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - if (body->get_one_way_collision_direction()!=Vector2()) { + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + if (body->get_one_way_collision_direction() != Vector2()) { Vector2 cd[2]; Physics2DServerSW::CollCbkData cbk; - cbk.max=1; - cbk.amount=0; - cbk.ptr=cd; - cbk.valid_dir=body->get_one_way_collision_direction(); - cbk.valid_depth=body->get_one_way_collision_max_depth(); - - Vector2 sep=mnormal; //important optimization for this to work fast enough - bool collided = CollisionSolver2DSW::solve(shape,p_xform,p_motion*(hi+space->contact_max_allowed_penetration),col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),Physics2DServerSW::_shape_col_cbk,&cbk,&sep,p_margin); - if (!collided || cbk.amount==0) { + cbk.max = 1; + cbk.amount = 0; + cbk.ptr = cd; + cbk.valid_dir = body->get_one_way_collision_direction(); + cbk.valid_depth = body->get_one_way_collision_max_depth(); + + Vector2 sep = mnormal; //important optimization for this to work fast enough + bool collided = CollisionSolver2DSW::solve(shape, p_xform, p_motion * (hi + space->contact_max_allowed_penetration), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), Physics2DServerSW::_shape_col_cbk, &cbk, &sep, p_margin); + if (!collided || cbk.amount == 0) { continue; } - } } - - if (low<best_safe) { - best_safe=low; - best_unsafe=hi; + if (low < best_safe) { + best_safe = low; + best_unsafe = hi; } - } - p_closest_safe=best_safe; - p_closest_unsafe=best_unsafe; + p_closest_safe = best_safe; + p_closest_unsafe = best_unsafe; return true; - - } +bool Physics2DDirectSpaceStateSW::collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { -bool Physics2DDirectSpaceStateSW::collide_shape(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,Vector2 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - - - if (p_result_max<=0) + if (p_result_max <= 0) return 0; Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ERR_FAIL_COND_V(!shape, 0); Rect2 aabb = p_shape_xform.xform(shape->get_aabb()); - aabb=aabb.merge(Rect2(aabb.pos+p_motion,aabb.size)); //motion - aabb=aabb.grow(p_margin); + aabb = aabb.merge(Rect2(aabb.pos + p_motion, aabb.size)); //motion + aabb = aabb.grow(p_margin); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); - bool collided=false; - r_result_count=0; + bool collided = false; + r_result_count = 0; Physics2DServerSW::CollCbkData cbk; - cbk.max=p_result_max; - cbk.amount=0; - cbk.ptr=r_results; - CollisionSolver2DSW::CallbackResult cbkres=NULL; - - Physics2DServerSW::CollCbkData *cbkptr=NULL; - if (p_result_max>0) { - cbkptr=&cbk; - cbkres=Physics2DServerSW::_shape_col_cbk; + cbk.max = p_result_max; + cbk.amount = 0; + cbk.ptr = r_results; + CollisionSolver2DSW::CallbackResult cbkres = NULL; + + Physics2DServerSW::CollCbkData *cbkptr = NULL; + if (p_result_max > 0) { + cbkptr = &cbk; + cbkres = Physics2DServerSW::_shape_col_cbk; } + for (int i = 0; i < amount; i++) { - for(int i=0;i<amount;i++) { - - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - const CollisionObject2DSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; + const CollisionObject2DSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - if (p_exclude.has( col_obj->get_self() )) + if (p_exclude.has(col_obj->get_self())) continue; - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - cbk.valid_dir=body->get_one_way_collision_direction(); - cbk.valid_depth=body->get_one_way_collision_max_depth(); + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + cbk.valid_dir = body->get_one_way_collision_direction(); + cbk.valid_depth = body->get_one_way_collision_max_depth(); } else { - cbk.valid_dir=Vector2(); - cbk.valid_depth=0; + cbk.valid_dir = Vector2(); + cbk.valid_depth = 0; } - if (CollisionSolver2DSW::solve(shape,p_shape_xform,p_motion,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2(),cbkres,cbkptr,NULL,p_margin)) { - collided=p_result_max==0 || cbk.amount>0; + if (CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, NULL, p_margin)) { + collided = p_result_max == 0 || cbk.amount > 0; } - } - - r_result_count=cbk.amount; + r_result_count = cbk.amount; return collided; } - struct _RestCallbackData2D { const CollisionObject2DSW *object; @@ -441,20 +401,18 @@ struct _RestCallbackData2D { real_t valid_depth; }; -static void _rest_cbk_result(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata) { - +static void _rest_cbk_result(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) { - _RestCallbackData2D *rd=(_RestCallbackData2D*)p_userdata; + _RestCallbackData2D *rd = (_RestCallbackData2D *)p_userdata; - if (rd->valid_dir!=Vector2()) { + if (rd->valid_dir != Vector2()) { - if (rd->valid_dir!=Vector2()) { - if (p_point_A.distance_squared_to(p_point_B)>rd->valid_depth*rd->valid_depth) + if (rd->valid_dir != Vector2()) { + if (p_point_A.distance_squared_to(p_point_B) > rd->valid_depth * rd->valid_depth) return; - if (rd->valid_dir.dot((p_point_A-p_point_B).normalized())<Math_PI*0.25) + if (rd->valid_dir.dot((p_point_A - p_point_B).normalized()) < Math_PI * 0.25) return; } - } Vector2 contact_rel = p_point_B - p_point_A; @@ -462,139 +420,121 @@ static void _rest_cbk_result(const Vector2& p_point_A,const Vector2& p_point_B,v if (len <= rd->best_len) return; - - rd->best_len=len; - rd->best_contact=p_point_B; - rd->best_normal=contact_rel/len; - rd->best_object=rd->object; - rd->best_shape=rd->shape; - - + rd->best_len = len; + rd->best_contact = p_point_B; + rd->best_normal = contact_rel / len; + rd->best_object = rd->object; + rd->best_shape = rd->shape; } - -bool Physics2DDirectSpaceStateSW::rest_info(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) { - +bool Physics2DDirectSpaceStateSW::rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) { Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape); - ERR_FAIL_COND_V(!shape,0); + ERR_FAIL_COND_V(!shape, 0); Rect2 aabb = p_shape_xform.xform(shape->get_aabb()); - aabb=aabb.merge(Rect2(aabb.pos+p_motion,aabb.size)); //motion - aabb=aabb.grow(p_margin); + aabb = aabb.merge(Rect2(aabb.pos + p_motion, aabb.size)); //motion + aabb = aabb.grow(p_margin); - int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results); + int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results); _RestCallbackData2D rcd; - rcd.best_len=0; - rcd.best_object=NULL; - rcd.best_shape=0; - - for(int i=0;i<amount;i++) { + rcd.best_len = 0; + rcd.best_object = NULL; + rcd.best_shape = 0; + for (int i = 0; i < amount; i++) { - if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask)) + if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask)) continue; - const CollisionObject2DSW *col_obj=space->intersection_query_results[i]; - int shape_idx=space->intersection_query_subindex_results[i]; + const CollisionObject2DSW *col_obj = space->intersection_query_results[i]; + int shape_idx = space->intersection_query_subindex_results[i]; - if (p_exclude.has( col_obj->get_self() )) + if (p_exclude.has(col_obj->get_self())) continue; - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - rcd.valid_dir=body->get_one_way_collision_direction(); - rcd.valid_depth=body->get_one_way_collision_max_depth(); + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + rcd.valid_dir = body->get_one_way_collision_direction(); + rcd.valid_depth = body->get_one_way_collision_max_depth(); } else { - rcd.valid_dir=Vector2(); - rcd.valid_depth=0; + rcd.valid_dir = Vector2(); + rcd.valid_depth = 0; } - - rcd.object=col_obj; - rcd.shape=shape_idx; - bool sc = CollisionSolver2DSW::solve(shape,p_shape_xform,p_motion,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2() ,_rest_cbk_result,&rcd,NULL,p_margin); + rcd.object = col_obj; + rcd.shape = shape_idx; + bool sc = CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), _rest_cbk_result, &rcd, NULL, p_margin); if (!sc) continue; - - } - if (rcd.best_len==0) + if (rcd.best_len == 0) return false; - r_info->collider_id=rcd.best_object->get_instance_id(); - r_info->shape=rcd.best_shape; - r_info->normal=rcd.best_normal; - r_info->point=rcd.best_contact; - r_info->rid=rcd.best_object->get_self(); - r_info->metadata=rcd.best_object->get_shape_metadata(rcd.best_shape); - if (rcd.best_object->get_type()==CollisionObject2DSW::TYPE_BODY) { + r_info->collider_id = rcd.best_object->get_instance_id(); + r_info->shape = rcd.best_shape; + r_info->normal = rcd.best_normal; + r_info->point = rcd.best_contact; + r_info->rid = rcd.best_object->get_self(); + r_info->metadata = rcd.best_object->get_shape_metadata(rcd.best_shape); + if (rcd.best_object->get_type() == CollisionObject2DSW::TYPE_BODY) { - const Body2DSW *body = static_cast<const Body2DSW*>(rcd.best_object); - Vector2 rel_vec = r_info->point-body->get_transform().get_origin(); + const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object); + Vector2 rel_vec = r_info->point - body->get_transform().get_origin(); r_info->linear_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity(); } else { - r_info->linear_velocity=Vector2(); + r_info->linear_velocity = Vector2(); } return true; } - Physics2DDirectSpaceStateSW::Physics2DDirectSpaceStateSW() { - - space=NULL; + space = NULL; } - //////////////////////////////////////////////////////////////////////////////////////////////////////////// +int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb) { + int amount = broadphase->cull_aabb(p_aabb, intersection_query_results, INTERSECTION_QUERY_MAX, intersection_query_subindex_results); + for (int i = 0; i < amount; i++) { -int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body,const Rect2& p_aabb) { - - - int amount = broadphase->cull_aabb(p_aabb,intersection_query_results,INTERSECTION_QUERY_MAX,intersection_query_subindex_results); + bool keep = true; - for(int i=0;i<amount;i++) { - - bool keep=true; - - if (intersection_query_results[i]==p_body) - keep=false; - else if (intersection_query_results[i]->get_type()==CollisionObject2DSW::TYPE_AREA) - keep=false; - else if ((static_cast<Body2DSW*>(intersection_query_results[i])->test_collision_mask(p_body))==0) - keep=false; - else if (static_cast<Body2DSW*>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self())) - keep=false; - else if (static_cast<Body2DSW*>(intersection_query_results[i])->is_shape_set_as_trigger(intersection_query_subindex_results[i])) - keep=false; + if (intersection_query_results[i] == p_body) + keep = false; + else if (intersection_query_results[i]->get_type() == CollisionObject2DSW::TYPE_AREA) + keep = false; + else if ((static_cast<Body2DSW *>(intersection_query_results[i])->test_collision_mask(p_body)) == 0) + keep = false; + else if (static_cast<Body2DSW *>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self())) + keep = false; + else if (static_cast<Body2DSW *>(intersection_query_results[i])->is_shape_set_as_trigger(intersection_query_subindex_results[i])) + keep = false; if (!keep) { - if (i<amount-1) { - SWAP(intersection_query_results[i],intersection_query_results[amount-1]); - SWAP(intersection_query_subindex_results[i],intersection_query_subindex_results[amount-1]); - + if (i < amount - 1) { + SWAP(intersection_query_results[i], intersection_query_results[amount - 1]); + SWAP(intersection_query_subindex_results[i], intersection_query_subindex_results[amount - 1]); } amount--; i--; - } } return amount; } -bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2&p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result) { +bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result) { //give me back regular physics engine logic //this is madness @@ -604,65 +544,61 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co //but is it right? who knows at this point.. if (r_result) { - r_result->collider_id=0; - r_result->collider_shape=0; - + r_result->collider_id = 0; + r_result->collider_shape = 0; } Rect2 body_aabb; - for(int i=0;i<p_body->get_shape_count();i++) { + for (int i = 0; i < p_body->get_shape_count(); i++) { - if (i==0) - body_aabb=p_body->get_shape_aabb(i); + if (i == 0) + body_aabb = p_body->get_shape_aabb(i); else - body_aabb=body_aabb.merge(p_body->get_shape_aabb(i)); + body_aabb = body_aabb.merge(p_body->get_shape_aabb(i)); } - body_aabb=body_aabb.grow(p_margin); + body_aabb = body_aabb.grow(p_margin); Transform2D body_transform = p_from; - { //STEP 1, FREE BODY IF STUCK const int max_results = 32; - int recover_attempts=4; - Vector2 sr[max_results*2]; + int recover_attempts = 4; + Vector2 sr[max_results * 2]; do { Physics2DServerSW::CollCbkData cbk; - cbk.max=max_results; - cbk.amount=0; - cbk.ptr=sr; - - - CollisionSolver2DSW::CallbackResult cbkres=NULL; + cbk.max = max_results; + cbk.amount = 0; + cbk.ptr = sr; - Physics2DServerSW::CollCbkData *cbkptr=NULL; - cbkptr=&cbk; - cbkres=Physics2DServerSW::_shape_col_cbk; + CollisionSolver2DSW::CallbackResult cbkres = NULL; - bool collided=false; + Physics2DServerSW::CollCbkData *cbkptr = NULL; + cbkptr = &cbk; + cbkres = Physics2DServerSW::_shape_col_cbk; + bool collided = false; - int amount = _cull_aabb_for_body(p_body,body_aabb); + int amount = _cull_aabb_for_body(p_body, body_aabb); - for(int j=0;j<p_body->get_shape_count();j++) { + for (int j = 0; j < p_body->get_shape_count(); j++) { if (p_body->is_shape_set_as_trigger(j)) continue; Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j); Shape2DSW *body_shape = p_body->get_shape(j); - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { - const CollisionObject2DSW *col_obj=intersection_query_results[i]; - int shape_idx=intersection_query_subindex_results[i]; + const CollisionObject2DSW *col_obj = intersection_query_results[i]; + int shape_idx = intersection_query_subindex_results[i]; - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); Vector2 cdir = body->get_one_way_collision_direction(); /* @@ -670,31 +606,29 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co continue; */ - cbk.valid_dir=cdir; - cbk.valid_depth=body->get_one_way_collision_max_depth(); + cbk.valid_dir = cdir; + cbk.valid_depth = body->get_one_way_collision_max_depth(); } else { - cbk.valid_dir=Vector2(); - cbk.valid_depth=0; + cbk.valid_dir = Vector2(); + cbk.valid_depth = 0; } - if (CollisionSolver2DSW::solve(body_shape,body_shape_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2(),cbkres,cbkptr,NULL,p_margin)) { - collided=cbk.amount>0; + if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, NULL, p_margin)) { + collided = cbk.amount > 0; } } } - if (!collided) { break; } Vector2 recover_motion; + for (int i = 0; i < cbk.amount; i++) { - for(int i=0;i<cbk.amount;i++) { - - Vector2 a = sr[i*2+0]; - Vector2 b = sr[i*2+1]; + Vector2 a = sr[i * 2 + 0]; + Vector2 b = sr[i * 2 + 1]; #if 0 Vector2 rel = b-a; @@ -710,38 +644,36 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co if (d<margin) continue; #endif - recover_motion+=(b-a)*0.4; + recover_motion += (b - a) * 0.4; } - if (recover_motion==Vector2()) { - collided=false; + if (recover_motion == Vector2()) { + collided = false; break; } - body_transform.elements[2]+=recover_motion; - body_aabb.pos+=recover_motion; + body_transform.elements[2] += recover_motion; + body_aabb.pos += recover_motion; recover_attempts--; } while (recover_attempts); } - - real_t safe = 1.0; real_t unsafe = 1.0; - int best_shape=-1; + int best_shape = -1; { // STEP 2 ATTEMPT MOTION - Rect2 motion_aabb=body_aabb; - motion_aabb.pos+=p_motion; - motion_aabb=motion_aabb.merge(body_aabb); + Rect2 motion_aabb = body_aabb; + motion_aabb.pos += p_motion; + motion_aabb = motion_aabb.merge(body_aabb); - int amount = _cull_aabb_for_body(p_body,motion_aabb); + int amount = _cull_aabb_for_body(p_body, motion_aabb); - for(int j=0;j<p_body->get_shape_count();j++) { + for (int j = 0; j < p_body->get_shape_count(); j++) { if (p_body->is_shape_set_as_trigger(j)) continue; @@ -749,201 +681,189 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j); Shape2DSW *body_shape = p_body->get_shape(j); - bool stuck=false; + bool stuck = false; - real_t best_safe=1; - real_t best_unsafe=1; + real_t best_safe = 1; + real_t best_unsafe = 1; - for(int i=0;i<amount;i++) { - - const CollisionObject2DSW *col_obj=intersection_query_results[i]; - int shape_idx=intersection_query_subindex_results[i]; + for (int i = 0; i < amount; i++) { + const CollisionObject2DSW *col_obj = intersection_query_results[i]; + int shape_idx = intersection_query_subindex_results[i]; Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx); //test initial overlap, does it collide if going all the way? - if (!CollisionSolver2DSW::solve(body_shape,body_shape_xform,p_motion,col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,0)) { + if (!CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, 0)) { continue; } - //test initial overlap - if (CollisionSolver2DSW::solve(body_shape,body_shape_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,0)) { + if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, 0)) { - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { //if one way collision direction ignore initial overlap - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - if (body->get_one_way_collision_direction()!=Vector2()) { + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + if (body->get_one_way_collision_direction() != Vector2()) { continue; } } - stuck=true; + stuck = true; break; } - //just do kinematic solving - real_t low=0; - real_t hi=1; - Vector2 mnormal=p_motion.normalized(); + real_t low = 0; + real_t hi = 1; + Vector2 mnormal = p_motion.normalized(); - for(int i=0;i<8;i++) { //steps should be customizable.. + for (int i = 0; i < 8; i++) { //steps should be customizable.. - real_t ofs = (low+hi)*0.5; + real_t ofs = (low + hi) * 0.5; - Vector2 sep=mnormal; //important optimization for this to work fast enough - bool collided = CollisionSolver2DSW::solve(body_shape,body_shape_xform,p_motion*ofs,col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),NULL,NULL,&sep,0); + Vector2 sep = mnormal; //important optimization for this to work fast enough + bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * ofs, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, &sep, 0); if (collided) { - hi=ofs; + hi = ofs; } else { - low=ofs; + low = ofs; } } - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - if (body->get_one_way_collision_direction()!=Vector2()) { + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + if (body->get_one_way_collision_direction() != Vector2()) { Vector2 cd[2]; Physics2DServerSW::CollCbkData cbk; - cbk.max=1; - cbk.amount=0; - cbk.ptr=cd; - cbk.valid_dir=body->get_one_way_collision_direction(); - cbk.valid_depth=body->get_one_way_collision_max_depth(); - - Vector2 sep=mnormal; //important optimization for this to work fast enough - bool collided = CollisionSolver2DSW::solve(body_shape,body_shape_xform,p_motion*(hi+contact_max_allowed_penetration),col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),Physics2DServerSW::_shape_col_cbk,&cbk,&sep,0); - if (!collided || cbk.amount==0) { + cbk.max = 1; + cbk.amount = 0; + cbk.ptr = cd; + cbk.valid_dir = body->get_one_way_collision_direction(); + cbk.valid_depth = body->get_one_way_collision_max_depth(); + + Vector2 sep = mnormal; //important optimization for this to work fast enough + bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), Physics2DServerSW::_shape_col_cbk, &cbk, &sep, 0); + if (!collided || cbk.amount == 0) { continue; } - } } - - if (low<best_safe) { - best_safe=low; - best_unsafe=hi; + if (low < best_safe) { + best_safe = low; + best_unsafe = hi; } } if (stuck) { - safe=0; - unsafe=0; - best_shape=j; //sadly it's the best + safe = 0; + unsafe = 0; + best_shape = j; //sadly it's the best break; } - if (best_safe==1.0) { + if (best_safe == 1.0) { continue; } if (best_safe < safe) { - safe=best_safe; - unsafe=best_unsafe; - best_shape=j; + safe = best_safe; + unsafe = best_unsafe; + best_shape = j; } } } - bool collided=false; - if (safe>=1) { + bool collided = false; + if (safe >= 1) { //not collided - collided=false; + collided = false; if (r_result) { - r_result->motion=p_motion; - r_result->remainder=Vector2(); - r_result->motion+=(body_transform.get_origin()-p_from.get_origin()); + r_result->motion = p_motion; + r_result->remainder = Vector2(); + r_result->motion += (body_transform.get_origin() - p_from.get_origin()); } } else { //it collided, let's get the rest info in unsafe advance Transform2D ugt = body_transform; - ugt.elements[2]+=p_motion*unsafe; + ugt.elements[2] += p_motion * unsafe; _RestCallbackData2D rcd; - rcd.best_len=0; - rcd.best_object=NULL; - rcd.best_shape=0; + rcd.best_len = 0; + rcd.best_object = NULL; + rcd.best_shape = 0; Transform2D body_shape_xform = ugt * p_body->get_shape_transform(best_shape); Shape2DSW *body_shape = p_body->get_shape(best_shape); - body_aabb.pos+=p_motion*unsafe; - - int amount = _cull_aabb_for_body(p_body,body_aabb); + body_aabb.pos += p_motion * unsafe; + int amount = _cull_aabb_for_body(p_body, body_aabb); - for(int i=0;i<amount;i++) { + for (int i = 0; i < amount; i++) { + const CollisionObject2DSW *col_obj = intersection_query_results[i]; + int shape_idx = intersection_query_subindex_results[i]; - const CollisionObject2DSW *col_obj=intersection_query_results[i]; - int shape_idx=intersection_query_subindex_results[i]; + if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { - if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) { - - const Body2DSW *body=static_cast<const Body2DSW*>(col_obj); - rcd.valid_dir=body->get_one_way_collision_direction(); - rcd.valid_depth=body->get_one_way_collision_max_depth(); + const Body2DSW *body = static_cast<const Body2DSW *>(col_obj); + rcd.valid_dir = body->get_one_way_collision_direction(); + rcd.valid_depth = body->get_one_way_collision_max_depth(); } else { - rcd.valid_dir=Vector2(); - rcd.valid_depth=0; + rcd.valid_dir = Vector2(); + rcd.valid_depth = 0; } - - rcd.object=col_obj; - rcd.shape=shape_idx; - bool sc = CollisionSolver2DSW::solve(body_shape,body_shape_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2() ,_rest_cbk_result,&rcd,NULL,p_margin); + rcd.object = col_obj; + rcd.shape = shape_idx; + bool sc = CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), _rest_cbk_result, &rcd, NULL, p_margin); if (!sc) continue; - } - if (rcd.best_len!=0) { + if (rcd.best_len != 0) { if (r_result) { - r_result->collider=rcd.best_object->get_self(); - r_result->collider_id=rcd.best_object->get_instance_id(); - r_result->collider_shape=rcd.best_shape; - r_result->collision_normal=rcd.best_normal; - r_result->collision_point=rcd.best_contact; - r_result->collider_metadata=rcd.best_object->get_shape_metadata(rcd.best_shape); - - const Body2DSW *body = static_cast<const Body2DSW*>(rcd.best_object); - Vector2 rel_vec = r_result->collision_point-body->get_transform().get_origin(); + r_result->collider = rcd.best_object->get_self(); + r_result->collider_id = rcd.best_object->get_instance_id(); + r_result->collider_shape = rcd.best_shape; + r_result->collision_normal = rcd.best_normal; + r_result->collision_point = rcd.best_contact; + r_result->collider_metadata = rcd.best_object->get_shape_metadata(rcd.best_shape); + + const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object); + Vector2 rel_vec = r_result->collision_point - body->get_transform().get_origin(); r_result->collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity(); - r_result->motion=safe*p_motion; - r_result->remainder=p_motion - safe * p_motion; - r_result->motion+=(body_transform.get_origin()-p_from.get_origin()); - + r_result->motion = safe * p_motion; + r_result->remainder = p_motion - safe * p_motion; + r_result->motion += (body_transform.get_origin() - p_from.get_origin()); } - collided=true; + collided = true; } else { if (r_result) { - r_result->motion=p_motion; - r_result->remainder=Vector2(); - r_result->motion+=(body_transform.get_origin()-p_from.get_origin()); + r_result->motion = p_motion; + r_result->remainder = Vector2(); + r_result->motion += (body_transform.get_origin() - p_from.get_origin()); } - collided=false; - + collided = false; } } return collided; - #if 0 //give me back regular physics engine logic //this is madness @@ -1101,82 +1021,71 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co return false; } +void *Space2DSW::_broadphase_pair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_self) { + CollisionObject2DSW::Type type_A = A->get_type(); + CollisionObject2DSW::Type type_B = B->get_type(); + if (type_A > type_B) { - -void* Space2DSW::_broadphase_pair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_self) { - - - CollisionObject2DSW::Type type_A=A->get_type(); - CollisionObject2DSW::Type type_B=B->get_type(); - if (type_A>type_B) { - - SWAP(A,B); - SWAP(p_subindex_A,p_subindex_B); - SWAP(type_A,type_B); + SWAP(A, B); + SWAP(p_subindex_A, p_subindex_B); + SWAP(type_A, type_B); } - Space2DSW *self = (Space2DSW*)p_self; + Space2DSW *self = (Space2DSW *)p_self; self->collision_pairs++; - if (type_A==CollisionObject2DSW::TYPE_AREA) { + if (type_A == CollisionObject2DSW::TYPE_AREA) { - Area2DSW *area=static_cast<Area2DSW*>(A); - if (type_B==CollisionObject2DSW::TYPE_AREA) { + Area2DSW *area = static_cast<Area2DSW *>(A); + if (type_B == CollisionObject2DSW::TYPE_AREA) { - Area2DSW *area_b=static_cast<Area2DSW*>(B); - Area2Pair2DSW *area2_pair = memnew(Area2Pair2DSW(area_b,p_subindex_B,area,p_subindex_A) ); + Area2DSW *area_b = static_cast<Area2DSW *>(B); + Area2Pair2DSW *area2_pair = memnew(Area2Pair2DSW(area_b, p_subindex_B, area, p_subindex_A)); return area2_pair; } else { - Body2DSW *body=static_cast<Body2DSW*>(B); - AreaPair2DSW *area_pair = memnew(AreaPair2DSW(body,p_subindex_B,area,p_subindex_A) ); + Body2DSW *body = static_cast<Body2DSW *>(B); + AreaPair2DSW *area_pair = memnew(AreaPair2DSW(body, p_subindex_B, area, p_subindex_A)); return area_pair; } - } else { - - BodyPair2DSW *b = memnew( BodyPair2DSW((Body2DSW*)A,p_subindex_A,(Body2DSW*)B,p_subindex_B) ); + BodyPair2DSW *b = memnew(BodyPair2DSW((Body2DSW *)A, p_subindex_A, (Body2DSW *)B, p_subindex_B)); return b; - } return NULL; } -void Space2DSW::_broadphase_unpair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_data,void *p_self) { +void Space2DSW::_broadphase_unpair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_self) { - - Space2DSW *self = (Space2DSW*)p_self; + Space2DSW *self = (Space2DSW *)p_self; self->collision_pairs--; - Constraint2DSW *c = (Constraint2DSW*)p_data; + Constraint2DSW *c = (Constraint2DSW *)p_data; memdelete(c); } - -const SelfList<Body2DSW>::List& Space2DSW::get_active_body_list() const { +const SelfList<Body2DSW>::List &Space2DSW::get_active_body_list() const { return active_list; } -void Space2DSW::body_add_to_active_list(SelfList<Body2DSW>* p_body) { +void Space2DSW::body_add_to_active_list(SelfList<Body2DSW> *p_body) { active_list.add(p_body); } -void Space2DSW::body_remove_from_active_list(SelfList<Body2DSW>* p_body) { +void Space2DSW::body_remove_from_active_list(SelfList<Body2DSW> *p_body) { active_list.remove(p_body); - } -void Space2DSW::body_add_to_inertia_update_list(SelfList<Body2DSW>* p_body) { - +void Space2DSW::body_add_to_inertia_update_list(SelfList<Body2DSW> *p_body) { inertia_update_list.add(p_body); } -void Space2DSW::body_remove_from_inertia_update_list(SelfList<Body2DSW>* p_body) { +void Space2DSW::body_remove_from_inertia_update_list(SelfList<Body2DSW> *p_body) { inertia_update_list.remove(p_body); } @@ -1188,109 +1097,103 @@ BroadPhase2DSW *Space2DSW::get_broadphase() { void Space2DSW::add_object(CollisionObject2DSW *p_object) { - ERR_FAIL_COND( objects.has(p_object) ); + ERR_FAIL_COND(objects.has(p_object)); objects.insert(p_object); } void Space2DSW::remove_object(CollisionObject2DSW *p_object) { - ERR_FAIL_COND( !objects.has(p_object) ); + ERR_FAIL_COND(!objects.has(p_object)); objects.erase(p_object); } -const Set<CollisionObject2DSW*> &Space2DSW::get_objects() const { +const Set<CollisionObject2DSW *> &Space2DSW::get_objects() const { return objects; } -void Space2DSW::body_add_to_state_query_list(SelfList<Body2DSW>* p_body) { +void Space2DSW::body_add_to_state_query_list(SelfList<Body2DSW> *p_body) { state_query_list.add(p_body); } -void Space2DSW::body_remove_from_state_query_list(SelfList<Body2DSW>* p_body) { +void Space2DSW::body_remove_from_state_query_list(SelfList<Body2DSW> *p_body) { state_query_list.remove(p_body); } -void Space2DSW::area_add_to_monitor_query_list(SelfList<Area2DSW>* p_area) { +void Space2DSW::area_add_to_monitor_query_list(SelfList<Area2DSW> *p_area) { monitor_query_list.add(p_area); } -void Space2DSW::area_remove_from_monitor_query_list(SelfList<Area2DSW>* p_area) { +void Space2DSW::area_remove_from_monitor_query_list(SelfList<Area2DSW> *p_area) { monitor_query_list.remove(p_area); } -void Space2DSW::area_add_to_moved_list(SelfList<Area2DSW>* p_area) { +void Space2DSW::area_add_to_moved_list(SelfList<Area2DSW> *p_area) { area_moved_list.add(p_area); } -void Space2DSW::area_remove_from_moved_list(SelfList<Area2DSW>* p_area) { +void Space2DSW::area_remove_from_moved_list(SelfList<Area2DSW> *p_area) { area_moved_list.remove(p_area); } -const SelfList<Area2DSW>::List& Space2DSW::get_moved_area_list() const { +const SelfList<Area2DSW>::List &Space2DSW::get_moved_area_list() const { return area_moved_list; } - void Space2DSW::call_queries() { - while(state_query_list.first()) { + while (state_query_list.first()) { - Body2DSW * b = state_query_list.first()->self(); + Body2DSW *b = state_query_list.first()->self(); b->call_queries(); state_query_list.remove(state_query_list.first()); } - while(monitor_query_list.first()) { + while (monitor_query_list.first()) { - Area2DSW * a = monitor_query_list.first()->self(); + Area2DSW *a = monitor_query_list.first()->self(); a->call_queries(); monitor_query_list.remove(monitor_query_list.first()); } - } void Space2DSW::setup() { - contact_debug_count=0; + contact_debug_count = 0; - while(inertia_update_list.first()) { + while (inertia_update_list.first()) { inertia_update_list.first()->self()->update_inertias(); inertia_update_list.remove(inertia_update_list.first()); } - - } void Space2DSW::update() { broadphase->update(); - } - void Space2DSW::set_param(Physics2DServer::SpaceParameter p_param, real_t p_value) { - switch(p_param) { + switch (p_param) { - case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius=p_value; break; - case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation=p_value; break; - case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration=p_value; break; - case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_treshold=p_value; break; - case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_treshold=p_value; break; - case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep=p_value; break; - case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias=p_value; break; + case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break; + case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break; + case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break; + case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_treshold = p_value; break; + case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_treshold = p_value; break; + case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break; + case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break; } } real_t Space2DSW::get_param(Physics2DServer::SpaceParameter p_param) const { - switch(p_param) { + switch (p_param) { case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius; case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation; @@ -1305,12 +1208,12 @@ real_t Space2DSW::get_param(Physics2DServer::SpaceParameter p_param) const { void Space2DSW::lock() { - locked=true; + locked = true; } void Space2DSW::unlock() { - locked=false; + locked = false; } bool Space2DSW::is_locked() const { @@ -1325,43 +1228,36 @@ Physics2DDirectSpaceStateSW *Space2DSW::get_direct_state() { Space2DSW::Space2DSW() { + collision_pairs = 0; + active_objects = 0; + island_count = 0; - collision_pairs=0; - active_objects=0; - island_count=0; + contact_debug_count = 0; - contact_debug_count=0; - - locked=false; - contact_recycle_radius=1.0; - contact_max_separation=1.5; - contact_max_allowed_penetration= 0.3; + locked = false; + contact_recycle_radius = 1.0; + contact_max_separation = 1.5; + contact_max_allowed_penetration = 0.3; constraint_bias = 0.2; - body_linear_velocity_sleep_treshold=GLOBAL_DEF("physics/2d/sleep_threashold_linear",2.0); - body_angular_velocity_sleep_treshold=GLOBAL_DEF("physics/2d/sleep_threshold_angular",(8.0 / 180.0 * Math_PI)); - body_time_to_sleep=GLOBAL_DEF("physics/2d/time_before_sleep",0.5); - + body_linear_velocity_sleep_treshold = GLOBAL_DEF("physics/2d/sleep_threashold_linear", 2.0); + body_angular_velocity_sleep_treshold = GLOBAL_DEF("physics/2d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI)); + body_time_to_sleep = GLOBAL_DEF("physics/2d/time_before_sleep", 0.5); broadphase = BroadPhase2DSW::create_func(); - broadphase->set_pair_callback(_broadphase_pair,this); - broadphase->set_unpair_callback(_broadphase_unpair,this); - area=NULL; - - direct_access = memnew( Physics2DDirectSpaceStateSW ); - direct_access->space=this; - + broadphase->set_pair_callback(_broadphase_pair, this); + broadphase->set_unpair_callback(_broadphase_unpair, this); + area = NULL; - for(int i=0;i<ELAPSED_TIME_MAX;i++) - elapsed_time[i]=0; + direct_access = memnew(Physics2DDirectSpaceStateSW); + direct_access->space = this; + for (int i = 0; i < ELAPSED_TIME_MAX; i++) + elapsed_time[i] = 0; } Space2DSW::~Space2DSW() { memdelete(broadphase); - memdelete( direct_access ); + memdelete(direct_access); } - - - diff --git a/servers/physics_2d/space_2d_sw.h b/servers/physics_2d/space_2d_sw.h index 071aa7bdfb..103f328ed2 100644 --- a/servers/physics_2d/space_2d_sw.h +++ b/servers/physics_2d/space_2d_sw.h @@ -29,40 +29,36 @@ #ifndef SPACE_2D_SW_H #define SPACE_2D_SW_H -#include "typedefs.h" -#include "hash_map.h" -#include "body_2d_sw.h" #include "area_2d_sw.h" -#include "body_pair_2d_sw.h" #include "area_pair_2d_sw.h" +#include "body_2d_sw.h" +#include "body_pair_2d_sw.h" #include "broad_phase_2d_sw.h" #include "collision_object_2d_sw.h" #include "global_config.h" - +#include "hash_map.h" +#include "typedefs.h" class Physics2DDirectSpaceStateSW : public Physics2DDirectSpaceState { - GDCLASS( Physics2DDirectSpaceStateSW, Physics2DDirectSpaceState ); -public: + GDCLASS(Physics2DDirectSpaceStateSW, Physics2DDirectSpaceState); +public: Space2DSW *space; - virtual int intersect_point(const Vector2& p_point,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION, bool p_pick_point=false); - virtual bool intersect_ray(const Vector2& p_from, const Vector2& p_to,RayResult &r_result,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - virtual int intersect_shape(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - virtual bool cast_motion(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - virtual bool collide_shape(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,Vector2 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - virtual bool rest_info(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); + virtual int intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_point = false); + virtual bool intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + virtual int intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + virtual bool cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + virtual bool collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + virtual bool rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); Physics2DDirectSpaceStateSW(); }; - - class Space2DSW : public RID_Data { public: - enum ElapsedTime { ELAPSED_TIME_INTEGRATE_FORCES, ELAPSED_TIME_GENERATE_ISLANDS, @@ -72,8 +68,8 @@ public: ELAPSED_TIME_MAX }; -private: +private: uint64_t elapsed_time[ELAPSED_TIME_MAX]; Physics2DDirectSpaceStateSW *direct_access; @@ -86,10 +82,10 @@ private: SelfList<Area2DSW>::List monitor_query_list; SelfList<Area2DSW>::List area_moved_list; - static void* _broadphase_pair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_self); - static void _broadphase_unpair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_data,void *p_self); + static void *_broadphase_pair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_self); + static void _broadphase_unpair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_self); - Set<CollisionObject2DSW*> objects; + Set<CollisionObject2DSW *> objects; Area2DSW *area; @@ -100,7 +96,7 @@ private: enum { - INTERSECTION_QUERY_MAX=2048 + INTERSECTION_QUERY_MAX = 2048 }; CollisionObject2DSW *intersection_query_results[INTERSECTION_QUERY_MAX]; @@ -116,44 +112,40 @@ private: int active_objects; int collision_pairs; - int _cull_aabb_for_body(Body2DSW *p_body,const Rect2& p_aabb); + int _cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb); Vector<Vector2> contact_debug; int contact_debug_count; -friend class Physics2DDirectSpaceStateSW; + friend class Physics2DDirectSpaceStateSW; public: - - _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; } + _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; } _FORCE_INLINE_ RID get_self() const { return self; } - void set_default_area(Area2DSW *p_area) { area=p_area; } + void set_default_area(Area2DSW *p_area) { area = p_area; } Area2DSW *get_default_area() const { return area; } - const SelfList<Body2DSW>::List& get_active_body_list() const; - void body_add_to_active_list(SelfList<Body2DSW>* p_body); - void body_remove_from_active_list(SelfList<Body2DSW>* p_body); - void body_add_to_inertia_update_list(SelfList<Body2DSW>* p_body); - void body_remove_from_inertia_update_list(SelfList<Body2DSW>* p_body); - void area_add_to_moved_list(SelfList<Area2DSW>* p_area); - void area_remove_from_moved_list(SelfList<Area2DSW>* p_area); - const SelfList<Area2DSW>::List& get_moved_area_list() const; - - - + const SelfList<Body2DSW>::List &get_active_body_list() const; + void body_add_to_active_list(SelfList<Body2DSW> *p_body); + void body_remove_from_active_list(SelfList<Body2DSW> *p_body); + void body_add_to_inertia_update_list(SelfList<Body2DSW> *p_body); + void body_remove_from_inertia_update_list(SelfList<Body2DSW> *p_body); + void area_add_to_moved_list(SelfList<Area2DSW> *p_area); + void area_remove_from_moved_list(SelfList<Area2DSW> *p_area); + const SelfList<Area2DSW>::List &get_moved_area_list() const; - void body_add_to_state_query_list(SelfList<Body2DSW>* p_body); - void body_remove_from_state_query_list(SelfList<Body2DSW>* p_body); + void body_add_to_state_query_list(SelfList<Body2DSW> *p_body); + void body_remove_from_state_query_list(SelfList<Body2DSW> *p_body); - void area_add_to_monitor_query_list(SelfList<Area2DSW>* p_area); - void area_remove_from_monitor_query_list(SelfList<Area2DSW>* p_area); + void area_add_to_monitor_query_list(SelfList<Area2DSW> *p_area); + void area_remove_from_monitor_query_list(SelfList<Area2DSW> *p_area); BroadPhase2DSW *get_broadphase(); void add_object(CollisionObject2DSW *p_object); void remove_object(CollisionObject2DSW *p_object); - const Set<CollisionObject2DSW*> &get_objects() const; + const Set<CollisionObject2DSW *> &get_objects() const; _FORCE_INLINE_ real_t get_contact_recycle_radius() const { return contact_recycle_radius; } _FORCE_INLINE_ real_t get_contact_max_separation() const { return contact_max_separation; } @@ -163,13 +155,10 @@ public: _FORCE_INLINE_ real_t get_body_angular_velocity_sleep_treshold() const { return body_angular_velocity_sleep_treshold; } _FORCE_INLINE_ real_t get_body_time_to_sleep() const { return body_time_to_sleep; } - - void update(); void setup(); void call_queries(); - bool is_locked() const; void lock(); void unlock(); @@ -177,32 +166,31 @@ public: void set_param(Physics2DServer::SpaceParameter p_param, real_t p_value); real_t get_param(Physics2DServer::SpaceParameter p_param) const; - void set_island_count(int p_island_count) { island_count=p_island_count; } + void set_island_count(int p_island_count) { island_count = p_island_count; } int get_island_count() const { return island_count; } - void set_active_objects(int p_active_objects) { active_objects=p_active_objects; } + void set_active_objects(int p_active_objects) { active_objects = p_active_objects; } int get_active_objects() const { return active_objects; } int get_collision_pairs() const { return collision_pairs; } - bool test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2&p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result); - + bool test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result); void set_debug_contacts(int p_amount) { contact_debug.resize(p_amount); } _FORCE_INLINE_ bool is_debugging_contacts() const { return !contact_debug.empty(); } - _FORCE_INLINE_ void add_debug_contact(const Vector2& p_contact) { if (contact_debug_count<contact_debug.size()) contact_debug[contact_debug_count++]=p_contact; } + _FORCE_INLINE_ void add_debug_contact(const Vector2 &p_contact) { + if (contact_debug_count < contact_debug.size()) contact_debug[contact_debug_count++] = p_contact; + } _FORCE_INLINE_ Vector<Vector2> get_debug_contacts() { return contact_debug; } _FORCE_INLINE_ int get_debug_contact_count() { return contact_debug_count; } - Physics2DDirectSpaceStateSW *get_direct_state(); - void set_elapsed_time(ElapsedTime p_time,uint64_t p_msec) { elapsed_time[p_time]=p_msec; } + void set_elapsed_time(ElapsedTime p_time, uint64_t p_msec) { elapsed_time[p_time] = p_msec; } uint64_t get_elapsed_time(ElapsedTime p_time) const { return elapsed_time[p_time]; } Space2DSW(); ~Space2DSW(); }; - #endif // SPACE_2D_SW_H diff --git a/servers/physics_2d/step_2d_sw.cpp b/servers/physics_2d/step_2d_sw.cpp index 355cc25a69..55bc62975f 100644 --- a/servers/physics_2d/step_2d_sw.cpp +++ b/servers/physics_2d/step_2d_sw.cpp @@ -29,39 +29,38 @@ #include "step_2d_sw.h" #include "os/os.h" -void Step2DSW::_populate_island(Body2DSW* p_body,Body2DSW** p_island,Constraint2DSW **p_constraint_island) { +void Step2DSW::_populate_island(Body2DSW *p_body, Body2DSW **p_island, Constraint2DSW **p_constraint_island) { p_body->set_island_step(_step); p_body->set_island_next(*p_island); - *p_island=p_body; + *p_island = p_body; - for(Map<Constraint2DSW*,int>::Element *E=p_body->get_constraint_map().front();E;E=E->next()) { + for (Map<Constraint2DSW *, int>::Element *E = p_body->get_constraint_map().front(); E; E = E->next()) { - Constraint2DSW *c=(Constraint2DSW*)E->key(); - if (c->get_island_step()==_step) + Constraint2DSW *c = (Constraint2DSW *)E->key(); + if (c->get_island_step() == _step) continue; //already processed c->set_island_step(_step); c->set_island_next(*p_constraint_island); - *p_constraint_island=c; + *p_constraint_island = c; - - for(int i=0;i<c->get_body_count();i++) { - if (i==E->get()) + for (int i = 0; i < c->get_body_count(); i++) { + if (i == E->get()) continue; Body2DSW *b = c->get_body_ptr()[i]; - if (b->get_island_step()==_step || b->get_mode()==Physics2DServer::BODY_MODE_STATIC || b->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) + if (b->get_island_step() == _step || b->get_mode() == Physics2DServer::BODY_MODE_STATIC || b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) continue; //no go - _populate_island(c->get_body_ptr()[i],p_island,p_constraint_island); + _populate_island(c->get_body_ptr()[i], p_island, p_constraint_island); } } } -bool Step2DSW::_setup_island(Constraint2DSW *p_island,real_t p_delta) { +bool Step2DSW::_setup_island(Constraint2DSW *p_island, real_t p_delta) { - Constraint2DSW *ci=p_island; - Constraint2DSW *prev_ci=NULL; - bool removed_root=false; - while(ci) { + Constraint2DSW *ci = p_island; + Constraint2DSW *prev_ci = NULL; + bool removed_root = false; + while (ci) { bool process = ci->setup(p_delta); if (!process) { @@ -69,169 +68,161 @@ bool Step2DSW::_setup_island(Constraint2DSW *p_island,real_t p_delta) { if (prev_ci) { prev_ci->set_island_next(ci->get_island_next()); } else { - removed_root=true; - prev_ci=ci; + removed_root = true; + prev_ci = ci; } } else { - prev_ci=ci; + prev_ci = ci; } - ci=ci->get_island_next(); + ci = ci->get_island_next(); } return removed_root; } -void Step2DSW::_solve_island(Constraint2DSW *p_island,int p_iterations,real_t p_delta){ - +void Step2DSW::_solve_island(Constraint2DSW *p_island, int p_iterations, real_t p_delta) { - for(int i=0;i<p_iterations;i++) { + for (int i = 0; i < p_iterations; i++) { - Constraint2DSW *ci=p_island; - while(ci) { + Constraint2DSW *ci = p_island; + while (ci) { ci->solve(p_delta); - ci=ci->get_island_next(); + ci = ci->get_island_next(); } } } -void Step2DSW::_check_suspend(Body2DSW *p_island,real_t p_delta) { +void Step2DSW::_check_suspend(Body2DSW *p_island, real_t p_delta) { - - bool can_sleep=true; + bool can_sleep = true; Body2DSW *b = p_island; - while(b) { + while (b) { - if (b->get_mode()==Physics2DServer::BODY_MODE_STATIC || b->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) { - b=b->get_island_next(); + if (b->get_mode() == Physics2DServer::BODY_MODE_STATIC || b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) { + b = b->get_island_next(); continue; //ignore for static } if (!b->sleep_test(p_delta)) - can_sleep=false; + can_sleep = false; - b=b->get_island_next(); + b = b->get_island_next(); } //put all to sleep or wake up everyoen b = p_island; - while(b) { + while (b) { - if (b->get_mode()==Physics2DServer::BODY_MODE_STATIC || b->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) { - b=b->get_island_next(); + if (b->get_mode() == Physics2DServer::BODY_MODE_STATIC || b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) { + b = b->get_island_next(); continue; //ignore for static } bool active = b->is_active(); - if (active==can_sleep) + if (active == can_sleep) b->set_active(!can_sleep); - b=b->get_island_next(); + b = b->get_island_next(); } } -void Step2DSW::step(Space2DSW* p_space,real_t p_delta,int p_iterations) { - +void Step2DSW::step(Space2DSW *p_space, real_t p_delta, int p_iterations) { p_space->lock(); // can't access space during this p_space->setup(); //update inertias, etc - const SelfList<Body2DSW>::List * body_list = &p_space->get_active_body_list(); + const SelfList<Body2DSW>::List *body_list = &p_space->get_active_body_list(); /* INTEGRATE FORCES */ uint64_t profile_begtime = OS::get_singleton()->get_ticks_usec(); - uint64_t profile_endtime=0; + uint64_t profile_endtime = 0; + int active_count = 0; - int active_count=0; - - const SelfList<Body2DSW>*b = body_list->first(); - while(b) { + const SelfList<Body2DSW> *b = body_list->first(); + while (b) { b->self()->integrate_forces(p_delta); - b=b->next(); + b = b->next(); active_count++; } p_space->set_active_objects(active_count); - { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_FORCES,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_FORCES, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* GENERATE CONSTRAINT ISLANDS */ - Body2DSW *island_list=NULL; - Constraint2DSW *constraint_island_list=NULL; + Body2DSW *island_list = NULL; + Constraint2DSW *constraint_island_list = NULL; b = body_list->first(); - int island_count=0; + int island_count = 0; - while(b) { + while (b) { Body2DSW *body = b->self(); + if (body->get_island_step() != _step) { - if (body->get_island_step()!=_step) { - - Body2DSW *island=NULL; - Constraint2DSW *constraint_island=NULL; - _populate_island(body,&island,&constraint_island); + Body2DSW *island = NULL; + Constraint2DSW *constraint_island = NULL; + _populate_island(body, &island, &constraint_island); island->set_island_list_next(island_list); - island_list=island; + island_list = island; if (constraint_island) { constraint_island->set_island_list_next(constraint_island_list); - constraint_island_list=constraint_island; + constraint_island_list = constraint_island; island_count++; } - } - b=b->next(); + b = b->next(); } p_space->set_island_count(island_count); const SelfList<Area2DSW>::List &aml = p_space->get_moved_area_list(); + while (aml.first()) { + for (const Set<Constraint2DSW *>::Element *E = aml.first()->self()->get_constraints().front(); E; E = E->next()) { - while(aml.first()) { - for(const Set<Constraint2DSW*>::Element *E=aml.first()->self()->get_constraints().front();E;E=E->next()) { - - Constraint2DSW*c=E->get(); - if (c->get_island_step()==_step) + Constraint2DSW *c = E->get(); + if (c->get_island_step() == _step) continue; c->set_island_step(_step); c->set_island_next(NULL); c->set_island_list_next(constraint_island_list); - constraint_island_list=c; + constraint_island_list = c; } - p_space->area_remove_from_moved_list((SelfList<Area2DSW>*)aml.first()); //faster to remove here + p_space->area_remove_from_moved_list((SelfList<Area2DSW> *)aml.first()); //faster to remove here } //print_line("island count: "+itos(island_count)+" active count: "+itos(active_count)); { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_GENERATE_ISLANDS,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_GENERATE_ISLANDS, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* SETUP CONSTRAINT ISLANDS */ { - Constraint2DSW *ci=constraint_island_list; - Constraint2DSW *prev_ci=NULL; - while(ci) { + Constraint2DSW *ci = constraint_island_list; + Constraint2DSW *prev_ci = NULL; + while (ci) { - if (_setup_island(ci,p_delta)==true) { + if (_setup_island(ci, p_delta) == true) { //removed the root from the island graph because it is not to be processed @@ -243,10 +234,9 @@ void Step2DSW::step(Space2DSW* p_space,real_t p_delta,int p_iterations) { if (prev_ci) { prev_ci->set_island_list_next(next); } else { - constraint_island_list=next; - + constraint_island_list = next; } - prev_ci=next; + prev_ci = next; } else { //list is empty, just skip @@ -254,77 +244,73 @@ void Step2DSW::step(Space2DSW* p_space,real_t p_delta,int p_iterations) { prev_ci->set_island_list_next(ci->get_island_list_next()); } else { - constraint_island_list=ci->get_island_list_next(); + constraint_island_list = ci->get_island_list_next(); } - } } else { - prev_ci=ci; + prev_ci = ci; } - ci=ci->get_island_list_next(); + ci = ci->get_island_list_next(); } } { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SETUP_CONSTRAINTS,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SETUP_CONSTRAINTS, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* SOLVE CONSTRAINT ISLANDS */ { - Constraint2DSW *ci=constraint_island_list; - while(ci) { + Constraint2DSW *ci = constraint_island_list; + while (ci) { //iterating each island separatedly improves cache efficiency - _solve_island(ci,p_iterations,p_delta); - ci=ci->get_island_list_next(); + _solve_island(ci, p_iterations, p_delta); + ci = ci->get_island_list_next(); } } { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SOLVE_CONSTRAINTS,profile_endtime-profile_begtime); - profile_begtime=profile_endtime; + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SOLVE_CONSTRAINTS, profile_endtime - profile_begtime); + profile_begtime = profile_endtime; } /* INTEGRATE VELOCITIES */ b = body_list->first(); - while(b) { + while (b) { - const SelfList<Body2DSW>*n=b->next(); + const SelfList<Body2DSW> *n = b->next(); b->self()->integrate_velocities(p_delta); - b=n; // in case it shuts itself down + b = n; // in case it shuts itself down } /* SLEEP / WAKE UP ISLANDS */ { - Body2DSW *bi=island_list; - while(bi) { + Body2DSW *bi = island_list; + while (bi) { - _check_suspend(bi,p_delta); - bi=bi->get_island_list_next(); + _check_suspend(bi, p_delta); + bi = bi->get_island_list_next(); } } { //profile - profile_endtime=OS::get_singleton()->get_ticks_usec(); - p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_VELOCITIES,profile_endtime-profile_begtime); + profile_endtime = OS::get_singleton()->get_ticks_usec(); + p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_VELOCITIES, profile_endtime - profile_begtime); //profile_begtime=profile_endtime; } p_space->update(); p_space->unlock(); _step++; - - - } Step2DSW::Step2DSW() { - _step=1; + _step = 1; } diff --git a/servers/physics_2d/step_2d_sw.h b/servers/physics_2d/step_2d_sw.h index 0896e1016d..c743358b6a 100644 --- a/servers/physics_2d/step_2d_sw.h +++ b/servers/physics_2d/step_2d_sw.h @@ -35,13 +35,13 @@ class Step2DSW { uint64_t _step; - void _populate_island(Body2DSW* p_body,Body2DSW** p_island,Constraint2DSW **p_constraint_island); - bool _setup_island(Constraint2DSW *p_island,real_t p_delta); - void _solve_island(Constraint2DSW *p_island,int p_iterations,real_t p_delta); - void _check_suspend(Body2DSW *p_island,real_t p_delta); -public: + void _populate_island(Body2DSW *p_body, Body2DSW **p_island, Constraint2DSW **p_constraint_island); + bool _setup_island(Constraint2DSW *p_island, real_t p_delta); + void _solve_island(Constraint2DSW *p_island, int p_iterations, real_t p_delta); + void _check_suspend(Body2DSW *p_island, real_t p_delta); - void step(Space2DSW* p_space,real_t p_delta,int p_iterations); +public: + void step(Space2DSW *p_space, real_t p_delta, int p_iterations); Step2DSW(); }; diff --git a/servers/physics_2d_server.cpp b/servers/physics_2d_server.cpp index bdbe85612f..f922b8f7a1 100644 --- a/servers/physics_2d_server.cpp +++ b/servers/physics_2d_server.cpp @@ -28,103 +28,97 @@ /*************************************************************************/ #include "physics_2d_server.h" #include "print_string.h" -Physics2DServer * Physics2DServer::singleton=NULL; - +Physics2DServer *Physics2DServer::singleton = NULL; void Physics2DDirectBodyState::integrate_forces() { real_t step = get_step(); Vector2 lv = get_linear_velocity(); - lv+=get_total_gravity() * step; + lv += get_total_gravity() * step; real_t av = get_angular_velocity(); float damp = 1.0 - step * get_total_linear_damp(); - if (damp<0) // reached zero in the given time - damp=0; + if (damp < 0) // reached zero in the given time + damp = 0; - lv*=damp; + lv *= damp; damp = 1.0 - step * get_total_angular_damp(); - if (damp<0) // reached zero in the given time - damp=0; + if (damp < 0) // reached zero in the given time + damp = 0; - av*=damp; + av *= damp; set_linear_velocity(lv); set_angular_velocity(av); - - } -Object* Physics2DDirectBodyState::get_contact_collider_object(int p_contact_idx) const { +Object *Physics2DDirectBodyState::get_contact_collider_object(int p_contact_idx) const { ObjectID objid = get_contact_collider_id(p_contact_idx); - Object *obj = ObjectDB::get_instance( objid ); + Object *obj = ObjectDB::get_instance(objid); return obj; } -Physics2DServer * Physics2DServer::get_singleton() { +Physics2DServer *Physics2DServer::get_singleton() { return singleton; } void Physics2DDirectBodyState::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_total_gravity"),&Physics2DDirectBodyState::get_total_gravity); - ClassDB::bind_method(D_METHOD("get_total_linear_damp"),&Physics2DDirectBodyState::get_total_linear_damp); - ClassDB::bind_method(D_METHOD("get_total_angular_damp"),&Physics2DDirectBodyState::get_total_angular_damp); + ClassDB::bind_method(D_METHOD("get_total_gravity"), &Physics2DDirectBodyState::get_total_gravity); + ClassDB::bind_method(D_METHOD("get_total_linear_damp"), &Physics2DDirectBodyState::get_total_linear_damp); + ClassDB::bind_method(D_METHOD("get_total_angular_damp"), &Physics2DDirectBodyState::get_total_angular_damp); - ClassDB::bind_method(D_METHOD("get_inverse_mass"),&Physics2DDirectBodyState::get_inverse_mass); - ClassDB::bind_method(D_METHOD("get_inverse_inertia"),&Physics2DDirectBodyState::get_inverse_inertia); + ClassDB::bind_method(D_METHOD("get_inverse_mass"), &Physics2DDirectBodyState::get_inverse_mass); + ClassDB::bind_method(D_METHOD("get_inverse_inertia"), &Physics2DDirectBodyState::get_inverse_inertia); - ClassDB::bind_method(D_METHOD("set_linear_velocity","velocity"),&Physics2DDirectBodyState::set_linear_velocity); - ClassDB::bind_method(D_METHOD("get_linear_velocity"),&Physics2DDirectBodyState::get_linear_velocity); + ClassDB::bind_method(D_METHOD("set_linear_velocity", "velocity"), &Physics2DDirectBodyState::set_linear_velocity); + ClassDB::bind_method(D_METHOD("get_linear_velocity"), &Physics2DDirectBodyState::get_linear_velocity); - ClassDB::bind_method(D_METHOD("set_angular_velocity","velocity"),&Physics2DDirectBodyState::set_angular_velocity); - ClassDB::bind_method(D_METHOD("get_angular_velocity"),&Physics2DDirectBodyState::get_angular_velocity); + ClassDB::bind_method(D_METHOD("set_angular_velocity", "velocity"), &Physics2DDirectBodyState::set_angular_velocity); + ClassDB::bind_method(D_METHOD("get_angular_velocity"), &Physics2DDirectBodyState::get_angular_velocity); - ClassDB::bind_method(D_METHOD("set_transform","transform"),&Physics2DDirectBodyState::set_transform); - ClassDB::bind_method(D_METHOD("get_transform"),&Physics2DDirectBodyState::get_transform); + ClassDB::bind_method(D_METHOD("set_transform", "transform"), &Physics2DDirectBodyState::set_transform); + ClassDB::bind_method(D_METHOD("get_transform"), &Physics2DDirectBodyState::get_transform); - ClassDB::bind_method(D_METHOD("set_sleep_state","enabled"),&Physics2DDirectBodyState::set_sleep_state); - ClassDB::bind_method(D_METHOD("is_sleeping"),&Physics2DDirectBodyState::is_sleeping); + ClassDB::bind_method(D_METHOD("set_sleep_state", "enabled"), &Physics2DDirectBodyState::set_sleep_state); + ClassDB::bind_method(D_METHOD("is_sleeping"), &Physics2DDirectBodyState::is_sleeping); - ClassDB::bind_method(D_METHOD("get_contact_count"),&Physics2DDirectBodyState::get_contact_count); - - ClassDB::bind_method(D_METHOD("get_contact_local_pos","contact_idx"),&Physics2DDirectBodyState::get_contact_local_pos); - ClassDB::bind_method(D_METHOD("get_contact_local_normal","contact_idx"),&Physics2DDirectBodyState::get_contact_local_normal); - ClassDB::bind_method(D_METHOD("get_contact_local_shape","contact_idx"),&Physics2DDirectBodyState::get_contact_local_shape); - ClassDB::bind_method(D_METHOD("get_contact_collider","contact_idx"),&Physics2DDirectBodyState::get_contact_collider); - ClassDB::bind_method(D_METHOD("get_contact_collider_pos","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_pos); - ClassDB::bind_method(D_METHOD("get_contact_collider_id","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_id); - ClassDB::bind_method(D_METHOD("get_contact_collider_object","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_object); - ClassDB::bind_method(D_METHOD("get_contact_collider_shape","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_shape); - ClassDB::bind_method(D_METHOD("get_contact_collider_shape_metadata:Variant","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_shape_metadata); - ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_velocity_at_pos); - ClassDB::bind_method(D_METHOD("get_step"),&Physics2DDirectBodyState::get_step); - ClassDB::bind_method(D_METHOD("integrate_forces"),&Physics2DDirectBodyState::integrate_forces); - ClassDB::bind_method(D_METHOD("get_space_state:Physics2DDirectSpaceState"),&Physics2DDirectBodyState::get_space_state); + ClassDB::bind_method(D_METHOD("get_contact_count"), &Physics2DDirectBodyState::get_contact_count); + ClassDB::bind_method(D_METHOD("get_contact_local_pos", "contact_idx"), &Physics2DDirectBodyState::get_contact_local_pos); + ClassDB::bind_method(D_METHOD("get_contact_local_normal", "contact_idx"), &Physics2DDirectBodyState::get_contact_local_normal); + ClassDB::bind_method(D_METHOD("get_contact_local_shape", "contact_idx"), &Physics2DDirectBodyState::get_contact_local_shape); + ClassDB::bind_method(D_METHOD("get_contact_collider", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider); + ClassDB::bind_method(D_METHOD("get_contact_collider_pos", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_pos); + ClassDB::bind_method(D_METHOD("get_contact_collider_id", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_id); + ClassDB::bind_method(D_METHOD("get_contact_collider_object", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_object); + ClassDB::bind_method(D_METHOD("get_contact_collider_shape", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_shape); + ClassDB::bind_method(D_METHOD("get_contact_collider_shape_metadata:Variant", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_shape_metadata); + ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_velocity_at_pos); + ClassDB::bind_method(D_METHOD("get_step"), &Physics2DDirectBodyState::get_step); + ClassDB::bind_method(D_METHOD("integrate_forces"), &Physics2DDirectBodyState::integrate_forces); + ClassDB::bind_method(D_METHOD("get_space_state:Physics2DDirectSpaceState"), &Physics2DDirectBodyState::get_space_state); } Physics2DDirectBodyState::Physics2DDirectBodyState() {} /////////////////////////////////////////////////////// - - void Physics2DShapeQueryParameters::set_shape(const RES &p_shape) { ERR_FAIL_COND(p_shape.is_null()); - shape=p_shape->get_rid(); + shape = p_shape->get_rid(); } -void Physics2DShapeQueryParameters::set_shape_rid(const RID& p_shape) { +void Physics2DShapeQueryParameters::set_shape_rid(const RID &p_shape) { - shape=p_shape; + shape = p_shape; } RID Physics2DShapeQueryParameters::get_shape_rid() const { @@ -132,125 +126,120 @@ RID Physics2DShapeQueryParameters::get_shape_rid() const { return shape; } -void Physics2DShapeQueryParameters::set_transform(const Transform2D& p_transform){ +void Physics2DShapeQueryParameters::set_transform(const Transform2D &p_transform) { - transform=p_transform; + transform = p_transform; } -Transform2D Physics2DShapeQueryParameters::get_transform() const{ +Transform2D Physics2DShapeQueryParameters::get_transform() const { return transform; } -void Physics2DShapeQueryParameters::set_motion(const Vector2& p_motion){ +void Physics2DShapeQueryParameters::set_motion(const Vector2 &p_motion) { - motion=p_motion; + motion = p_motion; } -Vector2 Physics2DShapeQueryParameters::get_motion() const{ +Vector2 Physics2DShapeQueryParameters::get_motion() const { return motion; } -void Physics2DShapeQueryParameters::set_margin(float p_margin){ +void Physics2DShapeQueryParameters::set_margin(float p_margin) { - margin=p_margin; + margin = p_margin; } -float Physics2DShapeQueryParameters::get_margin() const{ +float Physics2DShapeQueryParameters::get_margin() const { return margin; } -void Physics2DShapeQueryParameters::set_layer_mask(int p_layer_mask){ +void Physics2DShapeQueryParameters::set_layer_mask(int p_layer_mask) { - layer_mask=p_layer_mask; + layer_mask = p_layer_mask; } -int Physics2DShapeQueryParameters::get_layer_mask() const{ +int Physics2DShapeQueryParameters::get_layer_mask() const { return layer_mask; } +void Physics2DShapeQueryParameters::set_object_type_mask(int p_object_type_mask) { -void Physics2DShapeQueryParameters::set_object_type_mask(int p_object_type_mask){ - - object_type_mask=p_object_type_mask; + object_type_mask = p_object_type_mask; } -int Physics2DShapeQueryParameters::get_object_type_mask() const{ +int Physics2DShapeQueryParameters::get_object_type_mask() const { return object_type_mask; } -void Physics2DShapeQueryParameters::set_exclude(const Vector<RID>& p_exclude) { +void Physics2DShapeQueryParameters::set_exclude(const Vector<RID> &p_exclude) { exclude.clear(); - for(int i=0;i<p_exclude.size();i++) + for (int i = 0; i < p_exclude.size(); i++) exclude.insert(p_exclude[i]); - } -Vector<RID> Physics2DShapeQueryParameters::get_exclude() const{ +Vector<RID> Physics2DShapeQueryParameters::get_exclude() const { Vector<RID> ret; ret.resize(exclude.size()); - int idx=0; - for(Set<RID>::Element *E=exclude.front();E;E=E->next()) { - ret[idx]=E->get(); + int idx = 0; + for (Set<RID>::Element *E = exclude.front(); E; E = E->next()) { + ret[idx] = E->get(); } return ret; } void Physics2DShapeQueryParameters::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_shape","shape:Shape2D"),&Physics2DShapeQueryParameters::set_shape); - ClassDB::bind_method(D_METHOD("set_shape_rid","shape"),&Physics2DShapeQueryParameters::set_shape_rid); - ClassDB::bind_method(D_METHOD("get_shape_rid"),&Physics2DShapeQueryParameters::get_shape_rid); - - ClassDB::bind_method(D_METHOD("set_transform","transform"),&Physics2DShapeQueryParameters::set_transform); - ClassDB::bind_method(D_METHOD("get_transform"),&Physics2DShapeQueryParameters::get_transform); + ClassDB::bind_method(D_METHOD("set_shape", "shape:Shape2D"), &Physics2DShapeQueryParameters::set_shape); + ClassDB::bind_method(D_METHOD("set_shape_rid", "shape"), &Physics2DShapeQueryParameters::set_shape_rid); + ClassDB::bind_method(D_METHOD("get_shape_rid"), &Physics2DShapeQueryParameters::get_shape_rid); - ClassDB::bind_method(D_METHOD("set_motion","motion"),&Physics2DShapeQueryParameters::set_motion); - ClassDB::bind_method(D_METHOD("get_motion"),&Physics2DShapeQueryParameters::get_motion); + ClassDB::bind_method(D_METHOD("set_transform", "transform"), &Physics2DShapeQueryParameters::set_transform); + ClassDB::bind_method(D_METHOD("get_transform"), &Physics2DShapeQueryParameters::get_transform); - ClassDB::bind_method(D_METHOD("set_margin","margin"),&Physics2DShapeQueryParameters::set_margin); - ClassDB::bind_method(D_METHOD("get_margin"),&Physics2DShapeQueryParameters::get_margin); + ClassDB::bind_method(D_METHOD("set_motion", "motion"), &Physics2DShapeQueryParameters::set_motion); + ClassDB::bind_method(D_METHOD("get_motion"), &Physics2DShapeQueryParameters::get_motion); - ClassDB::bind_method(D_METHOD("set_layer_mask","layer_mask"),&Physics2DShapeQueryParameters::set_layer_mask); - ClassDB::bind_method(D_METHOD("get_layer_mask"),&Physics2DShapeQueryParameters::get_layer_mask); + ClassDB::bind_method(D_METHOD("set_margin", "margin"), &Physics2DShapeQueryParameters::set_margin); + ClassDB::bind_method(D_METHOD("get_margin"), &Physics2DShapeQueryParameters::get_margin); - ClassDB::bind_method(D_METHOD("set_object_type_mask","object_type_mask"),&Physics2DShapeQueryParameters::set_object_type_mask); - ClassDB::bind_method(D_METHOD("get_object_type_mask"),&Physics2DShapeQueryParameters::get_object_type_mask); - - ClassDB::bind_method(D_METHOD("set_exclude","exclude"),&Physics2DShapeQueryParameters::set_exclude); - ClassDB::bind_method(D_METHOD("get_exclude"),&Physics2DShapeQueryParameters::get_exclude); + ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &Physics2DShapeQueryParameters::set_layer_mask); + ClassDB::bind_method(D_METHOD("get_layer_mask"), &Physics2DShapeQueryParameters::get_layer_mask); + ClassDB::bind_method(D_METHOD("set_object_type_mask", "object_type_mask"), &Physics2DShapeQueryParameters::set_object_type_mask); + ClassDB::bind_method(D_METHOD("get_object_type_mask"), &Physics2DShapeQueryParameters::get_object_type_mask); + ClassDB::bind_method(D_METHOD("set_exclude", "exclude"), &Physics2DShapeQueryParameters::set_exclude); + ClassDB::bind_method(D_METHOD("get_exclude"), &Physics2DShapeQueryParameters::get_exclude); } Physics2DShapeQueryParameters::Physics2DShapeQueryParameters() { - margin=0; - layer_mask=0x7FFFFFFF; - object_type_mask=Physics2DDirectSpaceState::TYPE_MASK_COLLISION; + margin = 0; + layer_mask = 0x7FFFFFFF; + object_type_mask = Physics2DDirectSpaceState::TYPE_MASK_COLLISION; } - -Dictionary Physics2DDirectSpaceState::_intersect_ray(const Vector2& p_from, const Vector2& p_to,const Vector<RID>& p_exclude,uint32_t p_layers,uint32_t p_object_type_mask) { +Dictionary Physics2DDirectSpaceState::_intersect_ray(const Vector2 &p_from, const Vector2 &p_to, const Vector<RID> &p_exclude, uint32_t p_layers, uint32_t p_object_type_mask) { RayResult inters; Set<RID> exclude; - for(int i=0;i<p_exclude.size();i++) + for (int i = 0; i < p_exclude.size(); i++) exclude.insert(p_exclude[i]); - bool res = intersect_ray(p_from,p_to,inters,exclude,p_layers,p_object_type_mask); + bool res = intersect_ray(p_from, p_to, inters, exclude, p_layers, p_object_type_mask); if (!res) return Dictionary(); Dictionary d; - d["position"]=inters.position; - d["normal"]=inters.normal; - d["collider_id"]=inters.collider_id; - d["collider"]=inters.collider; - d["shape"]=inters.shape; - d["rid"]=inters.rid; - d["metadata"]=inters.metadata; + d["position"] = inters.position; + d["normal"] = inters.normal; + d["collider_id"] = inters.collider_id; + d["collider"] = inters.collider; + d["shape"] = inters.shape; + d["rid"] = inters.rid; + d["metadata"] = inters.metadata; return d; } @@ -259,131 +248,119 @@ Array Physics2DDirectSpaceState::_intersect_shape(const Ref<Physics2DShapeQueryP Vector<ShapeResult> sr; sr.resize(p_max_results); - int rc = intersect_shape(psq->shape,psq->transform,psq->motion,psq->margin,sr.ptr(),sr.size(),psq->exclude,psq->layer_mask,psq->object_type_mask); + int rc = intersect_shape(psq->shape, psq->transform, psq->motion, psq->margin, sr.ptr(), sr.size(), psq->exclude, psq->layer_mask, psq->object_type_mask); Array ret; ret.resize(rc); - for(int i=0;i<rc;i++) { + for (int i = 0; i < rc; i++) { Dictionary d; - d["rid"]=sr[i].rid; - d["collider_id"]=sr[i].collider_id; - d["collider"]=sr[i].collider; - d["shape"]=sr[i].shape; - d["metadata"]=sr[i].metadata; - ret[i]=d; + d["rid"] = sr[i].rid; + d["collider_id"] = sr[i].collider_id; + d["collider"] = sr[i].collider; + d["shape"] = sr[i].shape; + d["metadata"] = sr[i].metadata; + ret[i] = d; } return ret; } -Array Physics2DDirectSpaceState::_cast_motion(const Ref<Physics2DShapeQueryParameters> &psq){ +Array Physics2DDirectSpaceState::_cast_motion(const Ref<Physics2DShapeQueryParameters> &psq) { - float closest_safe,closest_unsafe; - bool res = cast_motion(psq->shape,psq->transform,psq->motion,psq->margin,closest_safe,closest_unsafe,psq->exclude,psq->layer_mask,psq->object_type_mask); + float closest_safe, closest_unsafe; + bool res = cast_motion(psq->shape, psq->transform, psq->motion, psq->margin, closest_safe, closest_unsafe, psq->exclude, psq->layer_mask, psq->object_type_mask); if (!res) return Array(); Array ret; ret.resize(2); - ret[0]=closest_safe; - ret[1]=closest_unsafe; + ret[0] = closest_safe; + ret[1] = closest_unsafe; return ret; - } -Array Physics2DDirectSpaceState::_intersect_point(const Vector2& p_point,int p_max_results,const Vector<RID>& p_exclude,uint32_t p_layers,uint32_t p_object_type_mask) { +Array Physics2DDirectSpaceState::_intersect_point(const Vector2 &p_point, int p_max_results, const Vector<RID> &p_exclude, uint32_t p_layers, uint32_t p_object_type_mask) { Set<RID> exclude; - for(int i=0;i<p_exclude.size();i++) + for (int i = 0; i < p_exclude.size(); i++) exclude.insert(p_exclude[i]); Vector<ShapeResult> ret; ret.resize(p_max_results); - int rc = intersect_point(p_point,ret.ptr(),ret.size(),exclude,p_layers,p_object_type_mask); - if (rc==0) + int rc = intersect_point(p_point, ret.ptr(), ret.size(), exclude, p_layers, p_object_type_mask); + if (rc == 0) return Array(); Array r; r.resize(rc); - for(int i=0;i<rc;i++) { + for (int i = 0; i < rc; i++) { Dictionary d; - d["rid"]=ret[i].rid; - d["collider_id"]=ret[i].collider_id; - d["collider"]=ret[i].collider; - d["shape"]=ret[i].shape; - d["metadata"]=ret[i].metadata; - r[i]=d; + d["rid"] = ret[i].rid; + d["collider_id"] = ret[i].collider_id; + d["collider"] = ret[i].collider; + d["shape"] = ret[i].shape; + d["metadata"] = ret[i].metadata; + r[i] = d; } return r; - } -Array Physics2DDirectSpaceState::_collide_shape(const Ref<Physics2DShapeQueryParameters> &psq, int p_max_results){ +Array Physics2DDirectSpaceState::_collide_shape(const Ref<Physics2DShapeQueryParameters> &psq, int p_max_results) { Vector<Vector2> ret; - ret.resize(p_max_results*2); - int rc=0; - bool res = collide_shape(psq->shape,psq->transform,psq->motion,psq->margin,ret.ptr(),p_max_results,rc,psq->exclude,psq->layer_mask,psq->object_type_mask); + ret.resize(p_max_results * 2); + int rc = 0; + bool res = collide_shape(psq->shape, psq->transform, psq->motion, psq->margin, ret.ptr(), p_max_results, rc, psq->exclude, psq->layer_mask, psq->object_type_mask); if (!res) return Array(); Array r; - r.resize(rc*2); - for(int i=0;i<rc*2;i++) - r[i]=ret[i]; + r.resize(rc * 2); + for (int i = 0; i < rc * 2; i++) + r[i] = ret[i]; return r; - } -Dictionary Physics2DDirectSpaceState::_get_rest_info(const Ref<Physics2DShapeQueryParameters> &psq){ +Dictionary Physics2DDirectSpaceState::_get_rest_info(const Ref<Physics2DShapeQueryParameters> &psq) { ShapeRestInfo sri; - bool res = rest_info(psq->shape,psq->transform,psq->motion,psq->margin,&sri,psq->exclude,psq->layer_mask,psq->object_type_mask); + bool res = rest_info(psq->shape, psq->transform, psq->motion, psq->margin, &sri, psq->exclude, psq->layer_mask, psq->object_type_mask); Dictionary r; if (!res) return r; - r["point"]=sri.point; - r["normal"]=sri.normal; - r["rid"]=sri.rid; - r["collider_id"]=sri.collider_id; - r["shape"]=sri.shape; - r["linear_velocity"]=sri.linear_velocity; - r["metadata"]=sri.metadata; + r["point"] = sri.point; + r["normal"] = sri.normal; + r["rid"] = sri.rid; + r["collider_id"] = sri.collider_id; + r["shape"] = sri.shape; + r["linear_velocity"] = sri.linear_velocity; + r["metadata"] = sri.metadata; return r; } - - Physics2DDirectSpaceState::Physics2DDirectSpaceState() { - - - } - void Physics2DDirectSpaceState::_bind_methods() { - - ClassDB::bind_method(D_METHOD("intersect_point","point","max_results","exclude","layer_mask","type_mask"),&Physics2DDirectSpaceState::_intersect_point,DEFVAL(32),DEFVAL(Array()),DEFVAL(0x7FFFFFFF),DEFVAL(TYPE_MASK_COLLISION)); - ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary","from","to","exclude","layer_mask","type_mask"),&Physics2DDirectSpaceState::_intersect_ray,DEFVAL(Array()),DEFVAL(0x7FFFFFFF),DEFVAL(TYPE_MASK_COLLISION)); - ClassDB::bind_method(D_METHOD("intersect_shape","shape:Physics2DShapeQueryParameters","max_results"),&Physics2DDirectSpaceState::_intersect_shape,DEFVAL(32)); - ClassDB::bind_method(D_METHOD("cast_motion","shape:Physics2DShapeQueryParameters"),&Physics2DDirectSpaceState::_cast_motion); - ClassDB::bind_method(D_METHOD("collide_shape","shape:Physics2DShapeQueryParameters","max_results"),&Physics2DDirectSpaceState::_collide_shape,DEFVAL(32)); - ClassDB::bind_method(D_METHOD("get_rest_info","shape:Physics2DShapeQueryParameters"),&Physics2DDirectSpaceState::_get_rest_info); + ClassDB::bind_method(D_METHOD("intersect_point", "point", "max_results", "exclude", "layer_mask", "type_mask"), &Physics2DDirectSpaceState::_intersect_point, DEFVAL(32), DEFVAL(Array()), DEFVAL(0x7FFFFFFF), DEFVAL(TYPE_MASK_COLLISION)); + ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary", "from", "to", "exclude", "layer_mask", "type_mask"), &Physics2DDirectSpaceState::_intersect_ray, DEFVAL(Array()), DEFVAL(0x7FFFFFFF), DEFVAL(TYPE_MASK_COLLISION)); + ClassDB::bind_method(D_METHOD("intersect_shape", "shape:Physics2DShapeQueryParameters", "max_results"), &Physics2DDirectSpaceState::_intersect_shape, DEFVAL(32)); + ClassDB::bind_method(D_METHOD("cast_motion", "shape:Physics2DShapeQueryParameters"), &Physics2DDirectSpaceState::_cast_motion); + ClassDB::bind_method(D_METHOD("collide_shape", "shape:Physics2DShapeQueryParameters", "max_results"), &Physics2DDirectSpaceState::_collide_shape, DEFVAL(32)); + ClassDB::bind_method(D_METHOD("get_rest_info", "shape:Physics2DShapeQueryParameters"), &Physics2DDirectSpaceState::_get_rest_info); //ClassDB::bind_method(D_METHOD("cast_motion","shape","xform","motion","exclude","umask"),&Physics2DDirectSpaceState::_intersect_shape,DEFVAL(Array()),DEFVAL(0)); - BIND_CONSTANT( TYPE_MASK_STATIC_BODY ); - BIND_CONSTANT( TYPE_MASK_KINEMATIC_BODY ); - BIND_CONSTANT( TYPE_MASK_RIGID_BODY ); - BIND_CONSTANT( TYPE_MASK_CHARACTER_BODY ); - BIND_CONSTANT( TYPE_MASK_AREA ); - BIND_CONSTANT( TYPE_MASK_COLLISION ); - + BIND_CONSTANT(TYPE_MASK_STATIC_BODY); + BIND_CONSTANT(TYPE_MASK_KINEMATIC_BODY); + BIND_CONSTANT(TYPE_MASK_RIGID_BODY); + BIND_CONSTANT(TYPE_MASK_CHARACTER_BODY); + BIND_CONSTANT(TYPE_MASK_AREA); + BIND_CONSTANT(TYPE_MASK_COLLISION); } - int Physics2DShapeQueryResult::get_result_count() const { return result.size(); @@ -396,7 +373,7 @@ ObjectID Physics2DShapeQueryResult::get_result_object_id(int p_idx) const { return result[p_idx].collider_id; } -Object* Physics2DShapeQueryResult::get_result_object(int p_idx) const { +Object *Physics2DShapeQueryResult::get_result_object(int p_idx) const { return result[p_idx].collider; } @@ -406,19 +383,15 @@ int Physics2DShapeQueryResult::get_result_object_shape(int p_idx) const { } Physics2DShapeQueryResult::Physics2DShapeQueryResult() { - - } void Physics2DShapeQueryResult::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_result_count"),&Physics2DShapeQueryResult::get_result_count); - ClassDB::bind_method(D_METHOD("get_result_rid","idx"),&Physics2DShapeQueryResult::get_result_rid); - ClassDB::bind_method(D_METHOD("get_result_object_id","idx"),&Physics2DShapeQueryResult::get_result_object_id); - ClassDB::bind_method(D_METHOD("get_result_object","idx"),&Physics2DShapeQueryResult::get_result_object); - ClassDB::bind_method(D_METHOD("get_result_object_shape","idx"),&Physics2DShapeQueryResult::get_result_object_shape); - - + ClassDB::bind_method(D_METHOD("get_result_count"), &Physics2DShapeQueryResult::get_result_count); + ClassDB::bind_method(D_METHOD("get_result_rid", "idx"), &Physics2DShapeQueryResult::get_result_rid); + ClassDB::bind_method(D_METHOD("get_result_object_id", "idx"), &Physics2DShapeQueryResult::get_result_object_id); + ClassDB::bind_method(D_METHOD("get_result_object", "idx"), &Physics2DShapeQueryResult::get_result_object); + ClassDB::bind_method(D_METHOD("get_result_object_shape", "idx"), &Physics2DShapeQueryResult::get_result_object_shape); } /////////////////////////////// @@ -427,41 +400,41 @@ void Physics2DShapeQueryResult::_bind_methods() { return colliding; }*/ -Vector2 Physics2DTestMotionResult::get_motion() const{ +Vector2 Physics2DTestMotionResult::get_motion() const { return result.motion; } -Vector2 Physics2DTestMotionResult::get_motion_remainder() const{ +Vector2 Physics2DTestMotionResult::get_motion_remainder() const { return result.remainder; } -Vector2 Physics2DTestMotionResult::get_collision_point() const{ +Vector2 Physics2DTestMotionResult::get_collision_point() const { return result.collision_point; } -Vector2 Physics2DTestMotionResult::get_collision_normal() const{ +Vector2 Physics2DTestMotionResult::get_collision_normal() const { return result.collision_normal; } -Vector2 Physics2DTestMotionResult::get_collider_velocity() const{ +Vector2 Physics2DTestMotionResult::get_collider_velocity() const { return result.collider_velocity; } -ObjectID Physics2DTestMotionResult::get_collider_id() const{ +ObjectID Physics2DTestMotionResult::get_collider_id() const { return result.collider_id; } -RID Physics2DTestMotionResult::get_collider_rid() const{ +RID Physics2DTestMotionResult::get_collider_rid() const { return result.collider; } -Object* Physics2DTestMotionResult::get_collider() const { +Object *Physics2DTestMotionResult::get_collider() const { return ObjectDB::get_instance(result.collider_id); } -int Physics2DTestMotionResult::get_collider_shape() const{ +int Physics2DTestMotionResult::get_collider_shape() const { return result.collider_shape; } @@ -469,269 +442,254 @@ int Physics2DTestMotionResult::get_collider_shape() const{ void Physics2DTestMotionResult::_bind_methods() { //ClassDB::bind_method(D_METHOD("is_colliding"),&Physics2DTestMotionResult::is_colliding); - ClassDB::bind_method(D_METHOD("get_motion"),&Physics2DTestMotionResult::get_motion); - ClassDB::bind_method(D_METHOD("get_motion_remainder"),&Physics2DTestMotionResult::get_motion_remainder); - ClassDB::bind_method(D_METHOD("get_collision_point"),&Physics2DTestMotionResult::get_collision_point); - ClassDB::bind_method(D_METHOD("get_collision_normal"),&Physics2DTestMotionResult::get_collision_normal); - ClassDB::bind_method(D_METHOD("get_collider_velocity"),&Physics2DTestMotionResult::get_collider_velocity); - ClassDB::bind_method(D_METHOD("get_collider_id"),&Physics2DTestMotionResult::get_collider_id); - ClassDB::bind_method(D_METHOD("get_collider_rid"),&Physics2DTestMotionResult::get_collider_rid); - ClassDB::bind_method(D_METHOD("get_collider"),&Physics2DTestMotionResult::get_collider); - ClassDB::bind_method(D_METHOD("get_collider_shape"),&Physics2DTestMotionResult::get_collider_shape); - + ClassDB::bind_method(D_METHOD("get_motion"), &Physics2DTestMotionResult::get_motion); + ClassDB::bind_method(D_METHOD("get_motion_remainder"), &Physics2DTestMotionResult::get_motion_remainder); + ClassDB::bind_method(D_METHOD("get_collision_point"), &Physics2DTestMotionResult::get_collision_point); + ClassDB::bind_method(D_METHOD("get_collision_normal"), &Physics2DTestMotionResult::get_collision_normal); + ClassDB::bind_method(D_METHOD("get_collider_velocity"), &Physics2DTestMotionResult::get_collider_velocity); + ClassDB::bind_method(D_METHOD("get_collider_id"), &Physics2DTestMotionResult::get_collider_id); + ClassDB::bind_method(D_METHOD("get_collider_rid"), &Physics2DTestMotionResult::get_collider_rid); + ClassDB::bind_method(D_METHOD("get_collider"), &Physics2DTestMotionResult::get_collider); + ClassDB::bind_method(D_METHOD("get_collider_shape"), &Physics2DTestMotionResult::get_collider_shape); } -Physics2DTestMotionResult::Physics2DTestMotionResult(){ +Physics2DTestMotionResult::Physics2DTestMotionResult() { - colliding=false; - result.collider_id=0; - result.collider_shape=0; + colliding = false; + result.collider_id = 0; + result.collider_shape = 0; } - /////////////////////////////////////// +bool Physics2DServer::_body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, float p_margin, const Ref<Physics2DTestMotionResult> &p_result) { - -bool Physics2DServer::_body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,float p_margin,const Ref<Physics2DTestMotionResult>& p_result) { - - MotionResult *r=NULL; + MotionResult *r = NULL; if (p_result.is_valid()) - r=p_result->get_result_ptr(); - return body_test_motion(p_body,p_from,p_motion,p_margin,r); + r = p_result->get_result_ptr(); + return body_test_motion(p_body, p_from, p_motion, p_margin, r); } void Physics2DServer::_bind_methods() { + ClassDB::bind_method(D_METHOD("shape_create", "type"), &Physics2DServer::shape_create); + ClassDB::bind_method(D_METHOD("shape_set_data", "shape", "data"), &Physics2DServer::shape_set_data); - ClassDB::bind_method(D_METHOD("shape_create","type"),&Physics2DServer::shape_create); - ClassDB::bind_method(D_METHOD("shape_set_data","shape","data"),&Physics2DServer::shape_set_data); - - ClassDB::bind_method(D_METHOD("shape_get_type","shape"),&Physics2DServer::shape_get_type); - ClassDB::bind_method(D_METHOD("shape_get_data","shape"),&Physics2DServer::shape_get_data); + ClassDB::bind_method(D_METHOD("shape_get_type", "shape"), &Physics2DServer::shape_get_type); + ClassDB::bind_method(D_METHOD("shape_get_data", "shape"), &Physics2DServer::shape_get_data); + ClassDB::bind_method(D_METHOD("space_create"), &Physics2DServer::space_create); + ClassDB::bind_method(D_METHOD("space_set_active", "space", "active"), &Physics2DServer::space_set_active); + ClassDB::bind_method(D_METHOD("space_is_active", "space"), &Physics2DServer::space_is_active); + ClassDB::bind_method(D_METHOD("space_set_param", "space", "param", "value"), &Physics2DServer::space_set_param); + ClassDB::bind_method(D_METHOD("space_get_param", "space", "param"), &Physics2DServer::space_get_param); + ClassDB::bind_method(D_METHOD("space_get_direct_state:Physics2DDirectSpaceState", "space"), &Physics2DServer::space_get_direct_state); - ClassDB::bind_method(D_METHOD("space_create"),&Physics2DServer::space_create); - ClassDB::bind_method(D_METHOD("space_set_active","space","active"),&Physics2DServer::space_set_active); - ClassDB::bind_method(D_METHOD("space_is_active","space"),&Physics2DServer::space_is_active); - ClassDB::bind_method(D_METHOD("space_set_param","space","param","value"),&Physics2DServer::space_set_param); - ClassDB::bind_method(D_METHOD("space_get_param","space","param"),&Physics2DServer::space_get_param); - ClassDB::bind_method(D_METHOD("space_get_direct_state:Physics2DDirectSpaceState","space"),&Physics2DServer::space_get_direct_state); + ClassDB::bind_method(D_METHOD("area_create"), &Physics2DServer::area_create); + ClassDB::bind_method(D_METHOD("area_set_space", "area", "space"), &Physics2DServer::area_set_space); + ClassDB::bind_method(D_METHOD("area_get_space", "area"), &Physics2DServer::area_get_space); - ClassDB::bind_method(D_METHOD("area_create"),&Physics2DServer::area_create); - ClassDB::bind_method(D_METHOD("area_set_space","area","space"),&Physics2DServer::area_set_space); - ClassDB::bind_method(D_METHOD("area_get_space","area"),&Physics2DServer::area_get_space); + ClassDB::bind_method(D_METHOD("area_set_space_override_mode", "area", "mode"), &Physics2DServer::area_set_space_override_mode); + ClassDB::bind_method(D_METHOD("area_get_space_override_mode", "area"), &Physics2DServer::area_get_space_override_mode); - ClassDB::bind_method(D_METHOD("area_set_space_override_mode","area","mode"),&Physics2DServer::area_set_space_override_mode); - ClassDB::bind_method(D_METHOD("area_get_space_override_mode","area"),&Physics2DServer::area_get_space_override_mode); + ClassDB::bind_method(D_METHOD("area_add_shape", "area", "shape", "transform"), &Physics2DServer::area_add_shape, DEFVAL(Transform2D())); + ClassDB::bind_method(D_METHOD("area_set_shape", "area", "shape_idx", "shape"), &Physics2DServer::area_set_shape); + ClassDB::bind_method(D_METHOD("area_set_shape_transform", "area", "shape_idx", "transform"), &Physics2DServer::area_set_shape_transform); - ClassDB::bind_method(D_METHOD("area_add_shape","area","shape","transform"),&Physics2DServer::area_add_shape,DEFVAL(Transform2D())); - ClassDB::bind_method(D_METHOD("area_set_shape","area","shape_idx","shape"),&Physics2DServer::area_set_shape); - ClassDB::bind_method(D_METHOD("area_set_shape_transform","area","shape_idx","transform"),&Physics2DServer::area_set_shape_transform); + ClassDB::bind_method(D_METHOD("area_get_shape_count", "area"), &Physics2DServer::area_get_shape_count); + ClassDB::bind_method(D_METHOD("area_get_shape", "area", "shape_idx"), &Physics2DServer::area_get_shape); + ClassDB::bind_method(D_METHOD("area_get_shape_transform", "area", "shape_idx"), &Physics2DServer::area_get_shape_transform); - ClassDB::bind_method(D_METHOD("area_get_shape_count","area"),&Physics2DServer::area_get_shape_count); - ClassDB::bind_method(D_METHOD("area_get_shape","area","shape_idx"),&Physics2DServer::area_get_shape); - ClassDB::bind_method(D_METHOD("area_get_shape_transform","area","shape_idx"),&Physics2DServer::area_get_shape_transform); + ClassDB::bind_method(D_METHOD("area_remove_shape", "area", "shape_idx"), &Physics2DServer::area_remove_shape); + ClassDB::bind_method(D_METHOD("area_clear_shapes", "area"), &Physics2DServer::area_clear_shapes); - ClassDB::bind_method(D_METHOD("area_remove_shape","area","shape_idx"),&Physics2DServer::area_remove_shape); - ClassDB::bind_method(D_METHOD("area_clear_shapes","area"),&Physics2DServer::area_clear_shapes); + ClassDB::bind_method(D_METHOD("area_set_layer_mask", "area", "mask"), &Physics2DServer::area_set_layer_mask); + ClassDB::bind_method(D_METHOD("area_set_collision_mask", "area", "mask"), &Physics2DServer::area_set_collision_mask); - ClassDB::bind_method(D_METHOD("area_set_layer_mask","area","mask"),&Physics2DServer::area_set_layer_mask); - ClassDB::bind_method(D_METHOD("area_set_collision_mask","area","mask"),&Physics2DServer::area_set_collision_mask); + ClassDB::bind_method(D_METHOD("area_set_param", "area", "param", "value"), &Physics2DServer::area_set_param); + ClassDB::bind_method(D_METHOD("area_set_transform", "area", "transform"), &Physics2DServer::area_set_transform); - ClassDB::bind_method(D_METHOD("area_set_param","area","param","value"),&Physics2DServer::area_set_param); - ClassDB::bind_method(D_METHOD("area_set_transform","area","transform"),&Physics2DServer::area_set_transform); + ClassDB::bind_method(D_METHOD("area_get_param", "area", "param"), &Physics2DServer::area_get_param); + ClassDB::bind_method(D_METHOD("area_get_transform", "area"), &Physics2DServer::area_get_transform); - ClassDB::bind_method(D_METHOD("area_get_param","area","param"),&Physics2DServer::area_get_param); - ClassDB::bind_method(D_METHOD("area_get_transform","area"),&Physics2DServer::area_get_transform); + ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID", "area", "id"), &Physics2DServer::area_attach_object_instance_ID); + ClassDB::bind_method(D_METHOD("area_get_object_instance_ID", "area"), &Physics2DServer::area_get_object_instance_ID); - ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID","area","id"),&Physics2DServer::area_attach_object_instance_ID); - ClassDB::bind_method(D_METHOD("area_get_object_instance_ID","area"),&Physics2DServer::area_get_object_instance_ID); + ClassDB::bind_method(D_METHOD("area_set_monitor_callback", "area", "receiver", "method"), &Physics2DServer::area_set_monitor_callback); - ClassDB::bind_method(D_METHOD("area_set_monitor_callback","area","receiver","method"),&Physics2DServer::area_set_monitor_callback); + ClassDB::bind_method(D_METHOD("body_create", "mode", "init_sleeping"), &Physics2DServer::body_create, DEFVAL(BODY_MODE_RIGID), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("body_create","mode","init_sleeping"),&Physics2DServer::body_create,DEFVAL(BODY_MODE_RIGID),DEFVAL(false)); + ClassDB::bind_method(D_METHOD("body_set_space", "body", "space"), &Physics2DServer::body_set_space); + ClassDB::bind_method(D_METHOD("body_get_space", "body"), &Physics2DServer::body_get_space); - ClassDB::bind_method(D_METHOD("body_set_space","body","space"),&Physics2DServer::body_set_space); - ClassDB::bind_method(D_METHOD("body_get_space","body"),&Physics2DServer::body_get_space); + ClassDB::bind_method(D_METHOD("body_set_mode", "body", "mode"), &Physics2DServer::body_set_mode); + ClassDB::bind_method(D_METHOD("body_get_mode", "body"), &Physics2DServer::body_get_mode); - ClassDB::bind_method(D_METHOD("body_set_mode","body","mode"),&Physics2DServer::body_set_mode); - ClassDB::bind_method(D_METHOD("body_get_mode","body"),&Physics2DServer::body_get_mode); + ClassDB::bind_method(D_METHOD("body_add_shape", "body", "shape", "transform"), &Physics2DServer::body_add_shape, DEFVAL(Transform2D())); + ClassDB::bind_method(D_METHOD("body_set_shape", "body", "shape_idx", "shape"), &Physics2DServer::body_set_shape); + ClassDB::bind_method(D_METHOD("body_set_shape_transform", "body", "shape_idx", "transform"), &Physics2DServer::body_set_shape_transform); + ClassDB::bind_method(D_METHOD("body_set_shape_metadata", "body", "shape_idx", "metadata"), &Physics2DServer::body_set_shape_metadata); - ClassDB::bind_method(D_METHOD("body_add_shape","body","shape","transform"),&Physics2DServer::body_add_shape,DEFVAL(Transform2D())); - ClassDB::bind_method(D_METHOD("body_set_shape","body","shape_idx","shape"),&Physics2DServer::body_set_shape); - ClassDB::bind_method(D_METHOD("body_set_shape_transform","body","shape_idx","transform"),&Physics2DServer::body_set_shape_transform); - ClassDB::bind_method(D_METHOD("body_set_shape_metadata","body","shape_idx","metadata"),&Physics2DServer::body_set_shape_metadata); + ClassDB::bind_method(D_METHOD("body_get_shape_count", "body"), &Physics2DServer::body_get_shape_count); + ClassDB::bind_method(D_METHOD("body_get_shape", "body", "shape_idx"), &Physics2DServer::body_get_shape); + ClassDB::bind_method(D_METHOD("body_get_shape_transform", "body", "shape_idx"), &Physics2DServer::body_get_shape_transform); + ClassDB::bind_method(D_METHOD("body_get_shape_metadata", "body", "shape_idx"), &Physics2DServer::body_get_shape_metadata); - ClassDB::bind_method(D_METHOD("body_get_shape_count","body"),&Physics2DServer::body_get_shape_count); - ClassDB::bind_method(D_METHOD("body_get_shape","body","shape_idx"),&Physics2DServer::body_get_shape); - ClassDB::bind_method(D_METHOD("body_get_shape_transform","body","shape_idx"),&Physics2DServer::body_get_shape_transform); - ClassDB::bind_method(D_METHOD("body_get_shape_metadata","body","shape_idx"),&Physics2DServer::body_get_shape_metadata); + ClassDB::bind_method(D_METHOD("body_remove_shape", "body", "shape_idx"), &Physics2DServer::body_remove_shape); + ClassDB::bind_method(D_METHOD("body_clear_shapes", "body"), &Physics2DServer::body_clear_shapes); - ClassDB::bind_method(D_METHOD("body_remove_shape","body","shape_idx"),&Physics2DServer::body_remove_shape); - ClassDB::bind_method(D_METHOD("body_clear_shapes","body"),&Physics2DServer::body_clear_shapes); + ClassDB::bind_method(D_METHOD("body_set_shape_as_trigger", "body", "shape_idx", "enable"), &Physics2DServer::body_set_shape_as_trigger); + ClassDB::bind_method(D_METHOD("body_is_shape_set_as_trigger", "body", "shape_idx"), &Physics2DServer::body_is_shape_set_as_trigger); + ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID", "body", "id"), &Physics2DServer::body_attach_object_instance_ID); + ClassDB::bind_method(D_METHOD("body_get_object_instance_ID", "body"), &Physics2DServer::body_get_object_instance_ID); - ClassDB::bind_method(D_METHOD("body_set_shape_as_trigger","body","shape_idx","enable"),&Physics2DServer::body_set_shape_as_trigger); - ClassDB::bind_method(D_METHOD("body_is_shape_set_as_trigger","body","shape_idx"),&Physics2DServer::body_is_shape_set_as_trigger); + ClassDB::bind_method(D_METHOD("body_set_continuous_collision_detection_mode", "body", "mode"), &Physics2DServer::body_set_continuous_collision_detection_mode); + ClassDB::bind_method(D_METHOD("body_get_continuous_collision_detection_mode", "body"), &Physics2DServer::body_get_continuous_collision_detection_mode); - ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID","body","id"),&Physics2DServer::body_attach_object_instance_ID); - ClassDB::bind_method(D_METHOD("body_get_object_instance_ID","body"),&Physics2DServer::body_get_object_instance_ID); + ClassDB::bind_method(D_METHOD("body_set_layer_mask", "body", "mask"), &Physics2DServer::body_set_layer_mask); + ClassDB::bind_method(D_METHOD("body_get_layer_mask", "body"), &Physics2DServer::body_get_layer_mask); + ClassDB::bind_method(D_METHOD("body_set_collision_mask", "body", "mask"), &Physics2DServer::body_set_collision_mask); + ClassDB::bind_method(D_METHOD("body_get_collision_mask", "body"), &Physics2DServer::body_get_collision_mask); - ClassDB::bind_method(D_METHOD("body_set_continuous_collision_detection_mode","body","mode"),&Physics2DServer::body_set_continuous_collision_detection_mode); - ClassDB::bind_method(D_METHOD("body_get_continuous_collision_detection_mode","body"),&Physics2DServer::body_get_continuous_collision_detection_mode); + ClassDB::bind_method(D_METHOD("body_set_param", "body", "param", "value"), &Physics2DServer::body_set_param); + ClassDB::bind_method(D_METHOD("body_get_param", "body", "param"), &Physics2DServer::body_get_param); + ClassDB::bind_method(D_METHOD("body_set_state", "body", "state", "value"), &Physics2DServer::body_set_state); + ClassDB::bind_method(D_METHOD("body_get_state", "body", "state"), &Physics2DServer::body_get_state); - ClassDB::bind_method(D_METHOD("body_set_layer_mask","body","mask"),&Physics2DServer::body_set_layer_mask); - ClassDB::bind_method(D_METHOD("body_get_layer_mask","body"),&Physics2DServer::body_get_layer_mask); + ClassDB::bind_method(D_METHOD("body_apply_impulse", "body", "pos", "impulse"), &Physics2DServer::body_apply_impulse); + ClassDB::bind_method(D_METHOD("body_add_force", "body", "offset", "force"), &Physics2DServer::body_add_force); + ClassDB::bind_method(D_METHOD("body_set_axis_velocity", "body", "axis_velocity"), &Physics2DServer::body_set_axis_velocity); - ClassDB::bind_method(D_METHOD("body_set_collision_mask","body","mask"),&Physics2DServer::body_set_collision_mask); - ClassDB::bind_method(D_METHOD("body_get_collision_mask","body"),&Physics2DServer::body_get_collision_mask); - - - ClassDB::bind_method(D_METHOD("body_set_param","body","param","value"),&Physics2DServer::body_set_param); - ClassDB::bind_method(D_METHOD("body_get_param","body","param"),&Physics2DServer::body_get_param); - - ClassDB::bind_method(D_METHOD("body_set_state","body","state","value"),&Physics2DServer::body_set_state); - ClassDB::bind_method(D_METHOD("body_get_state","body","state"),&Physics2DServer::body_get_state); - - ClassDB::bind_method(D_METHOD("body_apply_impulse","body","pos","impulse"),&Physics2DServer::body_apply_impulse); - ClassDB::bind_method(D_METHOD("body_add_force","body","offset","force"),&Physics2DServer::body_add_force); - ClassDB::bind_method(D_METHOD("body_set_axis_velocity","body","axis_velocity"),&Physics2DServer::body_set_axis_velocity); - - ClassDB::bind_method(D_METHOD("body_add_collision_exception","body","excepted_body"),&Physics2DServer::body_add_collision_exception); - ClassDB::bind_method(D_METHOD("body_remove_collision_exception","body","excepted_body"),&Physics2DServer::body_remove_collision_exception); + ClassDB::bind_method(D_METHOD("body_add_collision_exception", "body", "excepted_body"), &Physics2DServer::body_add_collision_exception); + ClassDB::bind_method(D_METHOD("body_remove_collision_exception", "body", "excepted_body"), &Physics2DServer::body_remove_collision_exception); //virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0; - ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported","body","amount"),&Physics2DServer::body_set_max_contacts_reported); - ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported","body"),&Physics2DServer::body_get_max_contacts_reported); + ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported", "body", "amount"), &Physics2DServer::body_set_max_contacts_reported); + ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported", "body"), &Physics2DServer::body_get_max_contacts_reported); - ClassDB::bind_method(D_METHOD("body_set_one_way_collision_direction","body","normal"),&Physics2DServer::body_set_one_way_collision_direction); - ClassDB::bind_method(D_METHOD("body_get_one_way_collision_direction","body"),&Physics2DServer::body_get_one_way_collision_direction); + ClassDB::bind_method(D_METHOD("body_set_one_way_collision_direction", "body", "normal"), &Physics2DServer::body_set_one_way_collision_direction); + ClassDB::bind_method(D_METHOD("body_get_one_way_collision_direction", "body"), &Physics2DServer::body_get_one_way_collision_direction); - ClassDB::bind_method(D_METHOD("body_set_one_way_collision_max_depth","body","depth"),&Physics2DServer::body_set_one_way_collision_max_depth); - ClassDB::bind_method(D_METHOD("body_get_one_way_collision_max_depth","body"),&Physics2DServer::body_get_one_way_collision_max_depth); + ClassDB::bind_method(D_METHOD("body_set_one_way_collision_max_depth", "body", "depth"), &Physics2DServer::body_set_one_way_collision_max_depth); + ClassDB::bind_method(D_METHOD("body_get_one_way_collision_max_depth", "body"), &Physics2DServer::body_get_one_way_collision_max_depth); + ClassDB::bind_method(D_METHOD("body_set_omit_force_integration", "body", "enable"), &Physics2DServer::body_set_omit_force_integration); + ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration", "body"), &Physics2DServer::body_is_omitting_force_integration); - ClassDB::bind_method(D_METHOD("body_set_omit_force_integration","body","enable"),&Physics2DServer::body_set_omit_force_integration); - ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration","body"),&Physics2DServer::body_is_omitting_force_integration); + ClassDB::bind_method(D_METHOD("body_set_force_integration_callback", "body", "receiver", "method", "userdata"), &Physics2DServer::body_set_force_integration_callback, DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("body_set_force_integration_callback","body","receiver","method","userdata"),&Physics2DServer::body_set_force_integration_callback,DEFVAL(Variant())); - - ClassDB::bind_method(D_METHOD("body_test_motion","body","from","motion","margin","result:Physics2DTestMotionResult"),&Physics2DServer::_body_test_motion,DEFVAL(0.08),DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("body_test_motion", "body", "from", "motion", "margin", "result:Physics2DTestMotionResult"), &Physics2DServer::_body_test_motion, DEFVAL(0.08), DEFVAL(Variant())); /* JOINT API */ - ClassDB::bind_method(D_METHOD("joint_set_param","joint","param","value"),&Physics2DServer::joint_set_param); - ClassDB::bind_method(D_METHOD("joint_get_param","joint","param"),&Physics2DServer::joint_get_param); + ClassDB::bind_method(D_METHOD("joint_set_param", "joint", "param", "value"), &Physics2DServer::joint_set_param); + ClassDB::bind_method(D_METHOD("joint_get_param", "joint", "param"), &Physics2DServer::joint_get_param); - ClassDB::bind_method(D_METHOD("pin_joint_create","anchor","body_a","body_b"),&Physics2DServer::pin_joint_create,DEFVAL(RID())); - ClassDB::bind_method(D_METHOD("groove_joint_create","groove1_a","groove2_a","anchor_b","body_a","body_b"),&Physics2DServer::groove_joint_create,DEFVAL(RID()),DEFVAL(RID())); - ClassDB::bind_method(D_METHOD("damped_spring_joint_create","anchor_a","anchor_b","body_a","body_b"),&Physics2DServer::damped_spring_joint_create,DEFVAL(RID())); + ClassDB::bind_method(D_METHOD("pin_joint_create", "anchor", "body_a", "body_b"), &Physics2DServer::pin_joint_create, DEFVAL(RID())); + ClassDB::bind_method(D_METHOD("groove_joint_create", "groove1_a", "groove2_a", "anchor_b", "body_a", "body_b"), &Physics2DServer::groove_joint_create, DEFVAL(RID()), DEFVAL(RID())); + ClassDB::bind_method(D_METHOD("damped_spring_joint_create", "anchor_a", "anchor_b", "body_a", "body_b"), &Physics2DServer::damped_spring_joint_create, DEFVAL(RID())); - ClassDB::bind_method(D_METHOD("damped_string_joint_set_param","joint","param","value"),&Physics2DServer::damped_string_joint_set_param); - ClassDB::bind_method(D_METHOD("damped_string_joint_get_param","joint","param"),&Physics2DServer::damped_string_joint_get_param); + ClassDB::bind_method(D_METHOD("damped_string_joint_set_param", "joint", "param", "value"), &Physics2DServer::damped_string_joint_set_param); + ClassDB::bind_method(D_METHOD("damped_string_joint_get_param", "joint", "param"), &Physics2DServer::damped_string_joint_get_param); - ClassDB::bind_method(D_METHOD("joint_get_type","joint"),&Physics2DServer::joint_get_type); + ClassDB::bind_method(D_METHOD("joint_get_type", "joint"), &Physics2DServer::joint_get_type); - ClassDB::bind_method(D_METHOD("free_rid","rid"),&Physics2DServer::free); + ClassDB::bind_method(D_METHOD("free_rid", "rid"), &Physics2DServer::free); - ClassDB::bind_method(D_METHOD("set_active","active"),&Physics2DServer::set_active); + ClassDB::bind_method(D_METHOD("set_active", "active"), &Physics2DServer::set_active); - ClassDB::bind_method(D_METHOD("get_process_info","process_info"),&Physics2DServer::get_process_info); + ClassDB::bind_method(D_METHOD("get_process_info", "process_info"), &Physics2DServer::get_process_info); //ClassDB::bind_method(D_METHOD("init"),&Physics2DServer::init); //ClassDB::bind_method(D_METHOD("step"),&Physics2DServer::step); //ClassDB::bind_method(D_METHOD("sync"),&Physics2DServer::sync); //ClassDB::bind_method(D_METHOD("flush_queries"),&Physics2DServer::flush_queries); - BIND_CONSTANT( SPACE_PARAM_CONTACT_RECYCLE_RADIUS ); - BIND_CONSTANT( SPACE_PARAM_CONTACT_MAX_SEPARATION ); - BIND_CONSTANT( SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION ); - BIND_CONSTANT( SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD ); - BIND_CONSTANT( SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD ); - BIND_CONSTANT( SPACE_PARAM_BODY_TIME_TO_SLEEP ); - BIND_CONSTANT( SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS ); - - BIND_CONSTANT( SHAPE_LINE ); - BIND_CONSTANT( SHAPE_SEGMENT ); - BIND_CONSTANT( SHAPE_CIRCLE ); - BIND_CONSTANT( SHAPE_RECTANGLE ); - BIND_CONSTANT( SHAPE_CAPSULE ); - BIND_CONSTANT( SHAPE_CONVEX_POLYGON ); - BIND_CONSTANT( SHAPE_CONCAVE_POLYGON ); - BIND_CONSTANT( SHAPE_CUSTOM ); - - BIND_CONSTANT( AREA_PARAM_GRAVITY ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_VECTOR ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_IS_POINT ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_DISTANCE_SCALE ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_POINT_ATTENUATION ); - BIND_CONSTANT( AREA_PARAM_LINEAR_DAMP); - BIND_CONSTANT( AREA_PARAM_ANGULAR_DAMP); - BIND_CONSTANT( AREA_PARAM_PRIORITY ); - - BIND_CONSTANT( AREA_SPACE_OVERRIDE_DISABLED ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE_REPLACE ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE_COMBINE ); - - BIND_CONSTANT( BODY_MODE_STATIC ); - BIND_CONSTANT( BODY_MODE_KINEMATIC ); - BIND_CONSTANT( BODY_MODE_RIGID ); - BIND_CONSTANT( BODY_MODE_CHARACTER ); - - BIND_CONSTANT( BODY_PARAM_BOUNCE ); - BIND_CONSTANT( BODY_PARAM_FRICTION ); - BIND_CONSTANT( BODY_PARAM_MASS ); - BIND_CONSTANT( BODY_PARAM_INERTIA ); - BIND_CONSTANT( BODY_PARAM_GRAVITY_SCALE ); - BIND_CONSTANT( BODY_PARAM_LINEAR_DAMP); - BIND_CONSTANT( BODY_PARAM_ANGULAR_DAMP); - BIND_CONSTANT( BODY_PARAM_MAX ); - - BIND_CONSTANT( BODY_STATE_TRANSFORM ); - BIND_CONSTANT( BODY_STATE_LINEAR_VELOCITY ); - BIND_CONSTANT( BODY_STATE_ANGULAR_VELOCITY ); - BIND_CONSTANT( BODY_STATE_SLEEPING ); - BIND_CONSTANT( BODY_STATE_CAN_SLEEP ); - - BIND_CONSTANT( JOINT_PIN ); - BIND_CONSTANT( JOINT_GROOVE ); - BIND_CONSTANT( JOINT_DAMPED_SPRING ); - - BIND_CONSTANT( DAMPED_STRING_REST_LENGTH ); - BIND_CONSTANT( DAMPED_STRING_STIFFNESS ); - BIND_CONSTANT( DAMPED_STRING_DAMPING ); - - BIND_CONSTANT( CCD_MODE_DISABLED ); - BIND_CONSTANT( CCD_MODE_CAST_RAY ); - BIND_CONSTANT( CCD_MODE_CAST_SHAPE ); + BIND_CONSTANT(SPACE_PARAM_CONTACT_RECYCLE_RADIUS); + BIND_CONSTANT(SPACE_PARAM_CONTACT_MAX_SEPARATION); + BIND_CONSTANT(SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION); + BIND_CONSTANT(SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD); + BIND_CONSTANT(SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD); + BIND_CONSTANT(SPACE_PARAM_BODY_TIME_TO_SLEEP); + BIND_CONSTANT(SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS); + + BIND_CONSTANT(SHAPE_LINE); + BIND_CONSTANT(SHAPE_SEGMENT); + BIND_CONSTANT(SHAPE_CIRCLE); + BIND_CONSTANT(SHAPE_RECTANGLE); + BIND_CONSTANT(SHAPE_CAPSULE); + BIND_CONSTANT(SHAPE_CONVEX_POLYGON); + BIND_CONSTANT(SHAPE_CONCAVE_POLYGON); + BIND_CONSTANT(SHAPE_CUSTOM); + + BIND_CONSTANT(AREA_PARAM_GRAVITY); + BIND_CONSTANT(AREA_PARAM_GRAVITY_VECTOR); + BIND_CONSTANT(AREA_PARAM_GRAVITY_IS_POINT); + BIND_CONSTANT(AREA_PARAM_GRAVITY_DISTANCE_SCALE); + BIND_CONSTANT(AREA_PARAM_GRAVITY_POINT_ATTENUATION); + BIND_CONSTANT(AREA_PARAM_LINEAR_DAMP); + BIND_CONSTANT(AREA_PARAM_ANGULAR_DAMP); + BIND_CONSTANT(AREA_PARAM_PRIORITY); + + BIND_CONSTANT(AREA_SPACE_OVERRIDE_DISABLED); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE_REPLACE); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE_COMBINE); + + BIND_CONSTANT(BODY_MODE_STATIC); + BIND_CONSTANT(BODY_MODE_KINEMATIC); + BIND_CONSTANT(BODY_MODE_RIGID); + BIND_CONSTANT(BODY_MODE_CHARACTER); + + BIND_CONSTANT(BODY_PARAM_BOUNCE); + BIND_CONSTANT(BODY_PARAM_FRICTION); + BIND_CONSTANT(BODY_PARAM_MASS); + BIND_CONSTANT(BODY_PARAM_INERTIA); + BIND_CONSTANT(BODY_PARAM_GRAVITY_SCALE); + BIND_CONSTANT(BODY_PARAM_LINEAR_DAMP); + BIND_CONSTANT(BODY_PARAM_ANGULAR_DAMP); + BIND_CONSTANT(BODY_PARAM_MAX); + + BIND_CONSTANT(BODY_STATE_TRANSFORM); + BIND_CONSTANT(BODY_STATE_LINEAR_VELOCITY); + BIND_CONSTANT(BODY_STATE_ANGULAR_VELOCITY); + BIND_CONSTANT(BODY_STATE_SLEEPING); + BIND_CONSTANT(BODY_STATE_CAN_SLEEP); + + BIND_CONSTANT(JOINT_PIN); + BIND_CONSTANT(JOINT_GROOVE); + BIND_CONSTANT(JOINT_DAMPED_SPRING); + + BIND_CONSTANT(DAMPED_STRING_REST_LENGTH); + BIND_CONSTANT(DAMPED_STRING_STIFFNESS); + BIND_CONSTANT(DAMPED_STRING_DAMPING); + + BIND_CONSTANT(CCD_MODE_DISABLED); + BIND_CONSTANT(CCD_MODE_CAST_RAY); + BIND_CONSTANT(CCD_MODE_CAST_SHAPE); //BIND_CONSTANT( TYPE_BODY ); //BIND_CONSTANT( TYPE_AREA ); - BIND_CONSTANT( AREA_BODY_ADDED ); - BIND_CONSTANT( AREA_BODY_REMOVED ); - - BIND_CONSTANT( INFO_ACTIVE_OBJECTS ); - BIND_CONSTANT( INFO_COLLISION_PAIRS ); - BIND_CONSTANT( INFO_ISLAND_COUNT ); - + BIND_CONSTANT(AREA_BODY_ADDED); + BIND_CONSTANT(AREA_BODY_REMOVED); + BIND_CONSTANT(INFO_ACTIVE_OBJECTS); + BIND_CONSTANT(INFO_COLLISION_PAIRS); + BIND_CONSTANT(INFO_ISLAND_COUNT); } - Physics2DServer::Physics2DServer() { //ERR_FAIL_COND( singleton!=NULL ); - singleton=this; + singleton = this; } Physics2DServer::~Physics2DServer() { - singleton=NULL; + singleton = NULL; } - diff --git a/servers/physics_2d_server.h b/servers/physics_2d_server.h index 424d2fa7ce..3c64d3df6a 100644 --- a/servers/physics_2d_server.h +++ b/servers/physics_2d_server.h @@ -37,61 +37,60 @@ class Physics2DDirectSpaceState; class Physics2DDirectBodyState : public Object { - GDCLASS( Physics2DDirectBodyState, Object ); + GDCLASS(Physics2DDirectBodyState, Object); + protected: static void _bind_methods(); -public: - virtual Vector2 get_total_gravity() const=0; // get gravity vector working on this body space/area - virtual float get_total_linear_damp() const=0; // get density of this body space/area - virtual float get_total_angular_damp() const=0; // get density of this body space/area +public: + virtual Vector2 get_total_gravity() const = 0; // get gravity vector working on this body space/area + virtual float get_total_linear_damp() const = 0; // get density of this body space/area + virtual float get_total_angular_damp() const = 0; // get density of this body space/area - virtual float get_inverse_mass() const=0; // get the mass - virtual real_t get_inverse_inertia() const=0; // get density of this body space + virtual float get_inverse_mass() const = 0; // get the mass + virtual real_t get_inverse_inertia() const = 0; // get density of this body space - virtual void set_linear_velocity(const Vector2& p_velocity)=0; - virtual Vector2 get_linear_velocity() const=0; + virtual void set_linear_velocity(const Vector2 &p_velocity) = 0; + virtual Vector2 get_linear_velocity() const = 0; - virtual void set_angular_velocity(real_t p_velocity)=0; - virtual real_t get_angular_velocity() const=0; + virtual void set_angular_velocity(real_t p_velocity) = 0; + virtual real_t get_angular_velocity() const = 0; - virtual void set_transform(const Transform2D& p_transform)=0; - virtual Transform2D get_transform() const=0; + virtual void set_transform(const Transform2D &p_transform) = 0; + virtual Transform2D get_transform() const = 0; - virtual void set_sleep_state(bool p_enable)=0; - virtual bool is_sleeping() const=0; + virtual void set_sleep_state(bool p_enable) = 0; + virtual bool is_sleeping() const = 0; - virtual int get_contact_count() const=0; + virtual int get_contact_count() const = 0; - virtual Vector2 get_contact_local_pos(int p_contact_idx) const=0; - virtual Vector2 get_contact_local_normal(int p_contact_idx) const=0; - virtual int get_contact_local_shape(int p_contact_idx) const=0; + virtual Vector2 get_contact_local_pos(int p_contact_idx) const = 0; + virtual Vector2 get_contact_local_normal(int p_contact_idx) const = 0; + virtual int get_contact_local_shape(int p_contact_idx) const = 0; - virtual RID get_contact_collider(int p_contact_idx) const=0; - virtual Vector2 get_contact_collider_pos(int p_contact_idx) const=0; - virtual ObjectID get_contact_collider_id(int p_contact_idx) const=0; - virtual Object* get_contact_collider_object(int p_contact_idx) const; - virtual int get_contact_collider_shape(int p_contact_idx) const=0; - virtual Variant get_contact_collider_shape_metadata(int p_contact_idx) const=0; - virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const=0; + virtual RID get_contact_collider(int p_contact_idx) const = 0; + virtual Vector2 get_contact_collider_pos(int p_contact_idx) const = 0; + virtual ObjectID get_contact_collider_id(int p_contact_idx) const = 0; + virtual Object *get_contact_collider_object(int p_contact_idx) const; + virtual int get_contact_collider_shape(int p_contact_idx) const = 0; + virtual Variant get_contact_collider_shape_metadata(int p_contact_idx) const = 0; + virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const = 0; - virtual real_t get_step() const=0; + virtual real_t get_step() const = 0; virtual void integrate_forces(); - virtual Physics2DDirectSpaceState* get_space_state()=0; + virtual Physics2DDirectSpaceState *get_space_state() = 0; Physics2DDirectBodyState(); }; - class Physics2DShapeQueryResult; - //used for script class Physics2DShapeQueryParameters : public Reference { GDCLASS(Physics2DShapeQueryParameters, Reference); -friend class Physics2DDirectSpaceState; + friend class Physics2DDirectSpaceState; RID shape; Transform2D transform; Vector2 motion; @@ -99,19 +98,19 @@ friend class Physics2DDirectSpaceState; Set<RID> exclude; uint32_t layer_mask; uint32_t object_type_mask; + protected: static void _bind_methods(); -public: - - void set_shape(const RES& p_shape); - void set_shape_rid(const RID& p_shape); +public: + void set_shape(const RES &p_shape); + void set_shape_rid(const RID &p_shape); RID get_shape_rid() const; - void set_transform(const Transform2D& p_transform); + void set_transform(const Transform2D &p_transform); Transform2D get_transform() const; - void set_motion(const Vector2& p_motion); + void set_motion(const Vector2 &p_motion); Vector2 get_motion() const; void set_margin(float p_margin); @@ -123,38 +122,35 @@ public: void set_object_type_mask(int p_object_type_mask); int get_object_type_mask() const; - void set_exclude(const Vector<RID>& p_exclude); + void set_exclude(const Vector<RID> &p_exclude); Vector<RID> get_exclude() const; Physics2DShapeQueryParameters(); - }; - class Physics2DDirectSpaceState : public Object { - GDCLASS( Physics2DDirectSpaceState, Object ); + GDCLASS(Physics2DDirectSpaceState, Object); - Dictionary _intersect_ray(const Vector2& p_from, const Vector2& p_to,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_layers=0,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); + Dictionary _intersect_ray(const Vector2 &p_from, const Vector2 &p_to, const Vector<RID> &p_exclude = Vector<RID>(), uint32_t p_layers = 0, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); - Array _intersect_point(const Vector2& p_point,int p_max_results=32,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_layers=0,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - Array _intersect_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query,int p_max_results=32); + Array _intersect_point(const Vector2 &p_point, int p_max_results = 32, const Vector<RID> &p_exclude = Vector<RID>(), uint32_t p_layers = 0, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + Array _intersect_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query, int p_max_results = 32); Array _cast_motion(const Ref<Physics2DShapeQueryParameters> &p_shape_query); - Array _collide_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query,int p_max_results=32); + Array _collide_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query, int p_max_results = 32); Dictionary _get_rest_info(const Ref<Physics2DShapeQueryParameters> &p_shape_query); protected: static void _bind_methods(); public: - enum ObjectTypeMask { - TYPE_MASK_STATIC_BODY=1<<0, - TYPE_MASK_KINEMATIC_BODY=1<<1, - TYPE_MASK_RIGID_BODY=1<<2, - TYPE_MASK_CHARACTER_BODY=1<<3, - TYPE_MASK_AREA=1<<4, - TYPE_MASK_COLLISION=TYPE_MASK_STATIC_BODY|TYPE_MASK_CHARACTER_BODY|TYPE_MASK_KINEMATIC_BODY|TYPE_MASK_RIGID_BODY + TYPE_MASK_STATIC_BODY = 1 << 0, + TYPE_MASK_KINEMATIC_BODY = 1 << 1, + TYPE_MASK_RIGID_BODY = 1 << 2, + TYPE_MASK_CHARACTER_BODY = 1 << 3, + TYPE_MASK_AREA = 1 << 4, + TYPE_MASK_COLLISION = TYPE_MASK_STATIC_BODY | TYPE_MASK_CHARACTER_BODY | TYPE_MASK_KINEMATIC_BODY | TYPE_MASK_RIGID_BODY }; @@ -169,7 +165,7 @@ public: Variant metadata; }; - virtual bool intersect_ray(const Vector2& p_from, const Vector2& p_to,RayResult &r_result,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual bool intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; struct ShapeResult { @@ -178,17 +174,15 @@ public: Object *collider; int shape; Variant metadata; - - }; - virtual int intersect_point(const Vector2& p_point,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,bool p_pick_point=false)=0; + virtual int intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_point = false) = 0; - virtual int intersect_shape(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,float p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual int intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; - virtual bool cast_motion(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,float p_margin,float &p_closest_safe,float &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual bool cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, float p_margin, float &p_closest_safe, float &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; - virtual bool collide_shape(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,float p_margin,Vector2 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual bool collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, float p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; struct ShapeRestInfo { @@ -199,32 +193,29 @@ public: int shape; Vector2 linear_velocity; //velocity at contact point Variant metadata; - }; - virtual bool rest_info(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,float p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; - + virtual bool rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; Physics2DDirectSpaceState(); }; - class Physics2DShapeQueryResult : public Reference { - GDCLASS( Physics2DShapeQueryResult, Reference ); + GDCLASS(Physics2DShapeQueryResult, Reference); Vector<Physics2DDirectSpaceState::ShapeResult> result; -friend class Physics2DDirectSpaceState; + friend class Physics2DDirectSpaceState; protected: static void _bind_methods(); -public: +public: int get_result_count() const; RID get_result_rid(int p_idx) const; ObjectID get_result_object_id(int p_idx) const; - Object* get_result_object(int p_idx) const; + Object *get_result_object(int p_idx) const; int get_result_object_shape(int p_idx) const; Physics2DShapeQueryResult(); @@ -234,18 +225,17 @@ class Physics2DTestMotionResult; class Physics2DServer : public Object { - GDCLASS( Physics2DServer, Object ); + GDCLASS(Physics2DServer, Object); - static Physics2DServer * singleton; + static Physics2DServer *singleton; - virtual bool _body_test_motion(RID p_body, const Transform2D &p_from, const Vector2& p_motion, float p_margin=0.08, const Ref<Physics2DTestMotionResult>& p_result=Ref<Physics2DTestMotionResult>()); + virtual bool _body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, float p_margin = 0.08, const Ref<Physics2DTestMotionResult> &p_result = Ref<Physics2DTestMotionResult>()); protected: static void _bind_methods(); public: - - static Physics2DServer * get_singleton(); + static Physics2DServer *get_singleton(); enum ShapeType { SHAPE_LINE, ///< plane:"plane" @@ -259,22 +249,22 @@ public: SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_create() with this value will result in an error }; - virtual RID shape_create(ShapeType p_shape)=0; - virtual void shape_set_data(RID p_shape, const Variant& p_data)=0; - virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias)=0; + virtual RID shape_create(ShapeType p_shape) = 0; + virtual void shape_set_data(RID p_shape, const Variant &p_data) = 0; + virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias) = 0; - virtual ShapeType shape_get_type(RID p_shape) const=0; - virtual Variant shape_get_data(RID p_shape) const=0; - virtual real_t shape_get_custom_solver_bias(RID p_shape) const=0; + virtual ShapeType shape_get_type(RID p_shape) const = 0; + virtual Variant shape_get_data(RID p_shape) const = 0; + virtual real_t shape_get_custom_solver_bias(RID p_shape) const = 0; //these work well, but should be used from the main thread only - virtual bool shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count)=0; + virtual bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) = 0; /* SPACE API */ - virtual RID space_create()=0; - virtual void space_set_active(RID p_space,bool p_active)=0; - virtual bool space_is_active(RID p_space) const=0; + virtual RID space_create() = 0; + virtual void space_set_active(RID p_space, bool p_active) = 0; + virtual bool space_is_active(RID p_space) const = 0; enum SpaceParameter { @@ -287,15 +277,15 @@ public: SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS, }; - virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value)=0; - virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const=0; + virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) = 0; + virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const = 0; // this function only works on fixed process, errors and returns null otherwise - virtual Physics2DDirectSpaceState* space_get_direct_state(RID p_space)=0; + virtual Physics2DDirectSpaceState *space_get_direct_state(RID p_space) = 0; - virtual void space_set_debug_contacts(RID p_space,int p_max_contacts)=0; - virtual Vector<Vector2> space_get_contacts(RID p_space) const=0; - virtual int space_get_contact_count(RID p_space) const=0; + virtual void space_set_debug_contacts(RID p_space, int p_max_contacts) = 0; + virtual Vector<Vector2> space_get_contacts(RID p_space) const = 0; + virtual int space_get_contact_count(RID p_space) const = 0; //missing space parameters @@ -303,8 +293,6 @@ public: //missing attenuation? missing better override? - - enum AreaParameter { AREA_PARAM_GRAVITY, AREA_PARAM_GRAVITY_VECTOR, @@ -316,11 +304,10 @@ public: AREA_PARAM_PRIORITY }; - virtual RID area_create()=0; - - virtual void area_set_space(RID p_area, RID p_space)=0; - virtual RID area_get_space(RID p_area) const=0; + virtual RID area_create() = 0; + virtual void area_set_space(RID p_area, RID p_space) = 0; + virtual RID area_get_space(RID p_area) const = 0; enum AreaSpaceOverrideMode { AREA_SPACE_OVERRIDE_DISABLED, @@ -330,37 +317,37 @@ public: AREA_SPACE_OVERRIDE_REPLACE_COMBINE // Discards all previous calculations, then keeps combining }; - virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode)=0; - virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const=0; + virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) = 0; + virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const = 0; - virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D& p_transform=Transform2D())=0; - virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape)=0; - virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D& p_transform)=0; + virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D &p_transform = Transform2D()) = 0; + virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) = 0; + virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D &p_transform) = 0; - virtual int area_get_shape_count(RID p_area) const=0; - virtual RID area_get_shape(RID p_area, int p_shape_idx) const=0; - virtual Transform2D area_get_shape_transform(RID p_area, int p_shape_idx) const=0; + virtual int area_get_shape_count(RID p_area) const = 0; + virtual RID area_get_shape(RID p_area, int p_shape_idx) const = 0; + virtual Transform2D area_get_shape_transform(RID p_area, int p_shape_idx) const = 0; - virtual void area_remove_shape(RID p_area, int p_shape_idx)=0; - virtual void area_clear_shapes(RID p_area)=0; + virtual void area_remove_shape(RID p_area, int p_shape_idx) = 0; + virtual void area_clear_shapes(RID p_area) = 0; - virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID)=0; - virtual ObjectID area_get_object_instance_ID(RID p_area) const=0; + virtual void area_attach_object_instance_ID(RID p_area, ObjectID p_ID) = 0; + virtual ObjectID area_get_object_instance_ID(RID p_area) const = 0; - virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value)=0; - virtual void area_set_transform(RID p_area, const Transform2D& p_transform)=0; + virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) = 0; + virtual void area_set_transform(RID p_area, const Transform2D &p_transform) = 0; - virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const=0; - virtual Transform2D area_get_transform(RID p_area) const=0; + virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const = 0; + virtual Transform2D area_get_transform(RID p_area) const = 0; - virtual void area_set_collision_mask(RID p_area,uint32_t p_mask)=0; - virtual void area_set_layer_mask(RID p_area,uint32_t p_mask)=0; + virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) = 0; + virtual void area_set_layer_mask(RID p_area, uint32_t p_mask) = 0; - virtual void area_set_monitorable(RID p_area,bool p_monitorable)=0; - virtual void area_set_pickable(RID p_area,bool p_pickable)=0; + virtual void area_set_monitorable(RID p_area, bool p_monitorable) = 0; + virtual void area_set_pickable(RID p_area, bool p_pickable) = 0; - virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0; - virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0; + virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0; + virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0; /* BODY API */ @@ -374,32 +361,32 @@ public: //BODY_MODE_SOFT ?? }; - virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false)=0; + virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false) = 0; - virtual void body_set_space(RID p_body, RID p_space)=0; - virtual RID body_get_space(RID p_body) const=0; + virtual void body_set_space(RID p_body, RID p_space) = 0; + virtual RID body_get_space(RID p_body) const = 0; - virtual void body_set_mode(RID p_body, BodyMode p_mode)=0; - virtual BodyMode body_get_mode(RID p_body) const=0; + virtual void body_set_mode(RID p_body, BodyMode p_mode) = 0; + virtual BodyMode body_get_mode(RID p_body) const = 0; - virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D& p_transform=Transform2D())=0; - virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape)=0; - virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D& p_transform)=0; - virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata)=0; + virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D &p_transform = Transform2D()) = 0; + virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) = 0; + virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D &p_transform) = 0; + virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant &p_metadata) = 0; - virtual int body_get_shape_count(RID p_body) const=0; - virtual RID body_get_shape(RID p_body, int p_shape_idx) const=0; - virtual Transform2D body_get_shape_transform(RID p_body, int p_shape_idx) const=0; - virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const=0; + virtual int body_get_shape_count(RID p_body) const = 0; + virtual RID body_get_shape(RID p_body, int p_shape_idx) const = 0; + virtual Transform2D body_get_shape_transform(RID p_body, int p_shape_idx) const = 0; + virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const = 0; - virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable)=0; - virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const=0; + virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) = 0; + virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const = 0; - virtual void body_remove_shape(RID p_body, int p_shape_idx)=0; - virtual void body_clear_shapes(RID p_body)=0; + virtual void body_remove_shape(RID p_body, int p_shape_idx) = 0; + virtual void body_clear_shapes(RID p_body) = 0; - virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID)=0; - virtual uint32_t body_get_object_instance_ID(RID p_body) const=0; + virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID) = 0; + virtual uint32_t body_get_object_instance_ID(RID p_body) const = 0; enum CCDMode { CCD_MODE_DISABLED, @@ -407,30 +394,29 @@ public: CCD_MODE_CAST_SHAPE, }; - virtual void body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode)=0; - virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const=0; + virtual void body_set_continuous_collision_detection_mode(RID p_body, CCDMode p_mode) = 0; + virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const = 0; - virtual void body_set_layer_mask(RID p_body, uint32_t p_mask)=0; - virtual uint32_t body_get_layer_mask(RID p_body) const=0; + virtual void body_set_layer_mask(RID p_body, uint32_t p_mask) = 0; + virtual uint32_t body_get_layer_mask(RID p_body) const = 0; - virtual void body_set_collision_mask(RID p_body, uint32_t p_mask)=0; - virtual uint32_t body_get_collision_mask(RID p_body) const=0; + virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) = 0; + virtual uint32_t body_get_collision_mask(RID p_body) const = 0; // common body variables enum BodyParameter { BODY_PARAM_BOUNCE, BODY_PARAM_FRICTION, BODY_PARAM_MASS, ///< unused for static, always infinite - BODY_PARAM_INERTIA, // read-only: computed from mass & shapes + BODY_PARAM_INERTIA, // read-only: computed from mass & shapes BODY_PARAM_GRAVITY_SCALE, BODY_PARAM_LINEAR_DAMP, BODY_PARAM_ANGULAR_DAMP, BODY_PARAM_MAX, }; - virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value)=0; - virtual float body_get_param(RID p_body, BodyParameter p_param) const=0; - + virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) = 0; + virtual float body_get_param(RID p_body, BodyParameter p_param) const = 0; //state enum BodyState { @@ -441,47 +427,47 @@ public: BODY_STATE_CAN_SLEEP, }; - virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant)=0; - virtual Variant body_get_state(RID p_body, BodyState p_state) const=0; + virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) = 0; + virtual Variant body_get_state(RID p_body, BodyState p_state) const = 0; //do something about it - virtual void body_set_applied_force(RID p_body, const Vector2& p_force)=0; - virtual Vector2 body_get_applied_force(RID p_body) const=0; + virtual void body_set_applied_force(RID p_body, const Vector2 &p_force) = 0; + virtual Vector2 body_get_applied_force(RID p_body) const = 0; - virtual void body_set_applied_torque(RID p_body, float p_torque)=0; - virtual float body_get_applied_torque(RID p_body) const=0; + virtual void body_set_applied_torque(RID p_body, float p_torque) = 0; + virtual float body_get_applied_torque(RID p_body) const = 0; - virtual void body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force)=0; + virtual void body_add_force(RID p_body, const Vector2 &p_offset, const Vector2 &p_force) = 0; - virtual void body_apply_impulse(RID p_body, const Vector2& p_offset, const Vector2& p_impulse)=0; - virtual void body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity)=0; + virtual void body_apply_impulse(RID p_body, const Vector2 &p_offset, const Vector2 &p_impulse) = 0; + virtual void body_set_axis_velocity(RID p_body, const Vector2 &p_axis_velocity) = 0; //fix - virtual void body_add_collision_exception(RID p_body, RID p_body_b)=0; - virtual void body_remove_collision_exception(RID p_body, RID p_body_b)=0; - virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0; + virtual void body_add_collision_exception(RID p_body, RID p_body_b) = 0; + virtual void body_remove_collision_exception(RID p_body, RID p_body_b) = 0; + virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) = 0; - virtual void body_set_max_contacts_reported(RID p_body, int p_contacts)=0; - virtual int body_get_max_contacts_reported(RID p_body) const=0; + virtual void body_set_max_contacts_reported(RID p_body, int p_contacts) = 0; + virtual int body_get_max_contacts_reported(RID p_body) const = 0; - virtual void body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction)=0; - virtual Vector2 body_get_one_way_collision_direction(RID p_body) const=0; + virtual void body_set_one_way_collision_direction(RID p_body, const Vector2 &p_direction) = 0; + virtual Vector2 body_get_one_way_collision_direction(RID p_body) const = 0; - virtual void body_set_one_way_collision_max_depth(RID p_body,float p_max_depth)=0; - virtual float body_get_one_way_collision_max_depth(RID p_body) const=0; + virtual void body_set_one_way_collision_max_depth(RID p_body, float p_max_depth) = 0; + virtual float body_get_one_way_collision_max_depth(RID p_body) const = 0; //missing remove - virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold)=0; - virtual float body_get_contacts_reported_depth_treshold(RID p_body) const=0; + virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold) = 0; + virtual float body_get_contacts_reported_depth_treshold(RID p_body) const = 0; - virtual void body_set_omit_force_integration(RID p_body,bool p_omit)=0; - virtual bool body_is_omitting_force_integration(RID p_body) const=0; + virtual void body_set_omit_force_integration(RID p_body, bool p_omit) = 0; + virtual bool body_is_omitting_force_integration(RID p_body) const = 0; - virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant())=0; + virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()) = 0; - virtual bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count)=0; + virtual bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) = 0; - virtual void body_set_pickable(RID p_body,bool p_pickable)=0; + virtual void body_set_pickable(RID p_body, bool p_pickable) = 0; struct MotionResult { @@ -497,7 +483,7 @@ public: Variant collider_metadata; }; - virtual bool body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,float p_margin=0.001,MotionResult *r_result=NULL)=0; + virtual bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, float p_margin = 0.001, MotionResult *r_result = NULL) = 0; /* JOINT API */ @@ -514,29 +500,29 @@ public: JOINT_PARAM_MAX_FORCE, }; - virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value)=0; - virtual real_t joint_get_param(RID p_joint,JointParam p_param) const=0; + virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value) = 0; + virtual real_t joint_get_param(RID p_joint, JointParam p_param) const = 0; - virtual RID pin_joint_create(const Vector2& p_anchor,RID p_body_a,RID p_body_b=RID())=0; - virtual RID groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b)=0; - virtual RID damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b=RID())=0; + virtual RID pin_joint_create(const Vector2 &p_anchor, RID p_body_a, RID p_body_b = RID()) = 0; + virtual RID groove_joint_create(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b) = 0; + virtual RID damped_spring_joint_create(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, RID p_body_a, RID p_body_b = RID()) = 0; enum PinJointParam { PIN_JOINT_SOFTNESS }; - virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value)=0; - virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const=0; + virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) = 0; + virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const = 0; enum DampedStringParam { DAMPED_STRING_REST_LENGTH, DAMPED_STRING_STIFFNESS, DAMPED_STRING_DAMPING }; - virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value)=0; - virtual real_t damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const=0; + virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value) = 0; + virtual real_t damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const = 0; - virtual JointType joint_get_type(RID p_joint) const=0; + virtual JointType joint_get_type(RID p_joint) const = 0; /* QUERY API */ @@ -545,18 +531,17 @@ public: AREA_BODY_REMOVED }; - /* MISC */ - virtual void free(RID p_rid)=0; + virtual void free(RID p_rid) = 0; - virtual void set_active(bool p_active)=0; - virtual void init()=0; - virtual void step(float p_step)=0; - virtual void sync()=0; - virtual void flush_queries()=0; - virtual void end_sync()=0; - virtual void finish()=0; + virtual void set_active(bool p_active) = 0; + virtual void init() = 0; + virtual void step(float p_step) = 0; + virtual void sync() = 0; + virtual void flush_queries() = 0; + virtual void end_sync() = 0; + virtual void finish() = 0; enum ProcessInfo { @@ -567,26 +552,25 @@ public: INFO_BROAD_PHASE_TIME }; - virtual int get_process_info(ProcessInfo p_info)=0; + virtual int get_process_info(ProcessInfo p_info) = 0; Physics2DServer(); ~Physics2DServer(); }; - class Physics2DTestMotionResult : public Reference { - GDCLASS( Physics2DTestMotionResult, Reference ); + GDCLASS(Physics2DTestMotionResult, Reference); Physics2DServer::MotionResult result; bool colliding; -friend class Physics2DServer; + friend class Physics2DServer; protected: static void _bind_methods(); -public: - Physics2DServer::MotionResult* get_result_ptr() const { return const_cast<Physics2DServer::MotionResult*>(&result); } +public: + Physics2DServer::MotionResult *get_result_ptr() const { return const_cast<Physics2DServer::MotionResult *>(&result); } //bool is_colliding() const; Vector2 get_motion() const; @@ -597,26 +581,25 @@ public: Vector2 get_collider_velocity() const; ObjectID get_collider_id() const; RID get_collider_rid() const; - Object* get_collider() const; + Object *get_collider() const; int get_collider_shape() const; Physics2DTestMotionResult(); }; - -VARIANT_ENUM_CAST( Physics2DServer::ShapeType ); -VARIANT_ENUM_CAST( Physics2DServer::SpaceParameter ); -VARIANT_ENUM_CAST( Physics2DServer::AreaParameter ); -VARIANT_ENUM_CAST( Physics2DServer::AreaSpaceOverrideMode ); -VARIANT_ENUM_CAST( Physics2DServer::BodyMode ); -VARIANT_ENUM_CAST( Physics2DServer::BodyParameter ); -VARIANT_ENUM_CAST( Physics2DServer::BodyState ); -VARIANT_ENUM_CAST( Physics2DServer::CCDMode ); -VARIANT_ENUM_CAST( Physics2DServer::JointParam ); -VARIANT_ENUM_CAST( Physics2DServer::JointType ); -VARIANT_ENUM_CAST( Physics2DServer::DampedStringParam ); +VARIANT_ENUM_CAST(Physics2DServer::ShapeType); +VARIANT_ENUM_CAST(Physics2DServer::SpaceParameter); +VARIANT_ENUM_CAST(Physics2DServer::AreaParameter); +VARIANT_ENUM_CAST(Physics2DServer::AreaSpaceOverrideMode); +VARIANT_ENUM_CAST(Physics2DServer::BodyMode); +VARIANT_ENUM_CAST(Physics2DServer::BodyParameter); +VARIANT_ENUM_CAST(Physics2DServer::BodyState); +VARIANT_ENUM_CAST(Physics2DServer::CCDMode); +VARIANT_ENUM_CAST(Physics2DServer::JointParam); +VARIANT_ENUM_CAST(Physics2DServer::JointType); +VARIANT_ENUM_CAST(Physics2DServer::DampedStringParam); //VARIANT_ENUM_CAST( Physics2DServer::ObjectType ); -VARIANT_ENUM_CAST( Physics2DServer::AreaBodyStatus ); -VARIANT_ENUM_CAST( Physics2DServer::ProcessInfo ); +VARIANT_ENUM_CAST(Physics2DServer::AreaBodyStatus); +VARIANT_ENUM_CAST(Physics2DServer::ProcessInfo); #endif diff --git a/servers/physics_server.cpp b/servers/physics_server.cpp index e76bfd113c..d8f77fbe0d 100644 --- a/servers/physics_server.cpp +++ b/servers/physics_server.cpp @@ -28,110 +28,102 @@ /*************************************************************************/ #include "physics_server.h" #include "print_string.h" -PhysicsServer * PhysicsServer::singleton=NULL; - +PhysicsServer *PhysicsServer::singleton = NULL; void PhysicsDirectBodyState::integrate_forces() { real_t step = get_step(); Vector3 lv = get_linear_velocity(); - lv+=get_total_gravity() * step; + lv += get_total_gravity() * step; Vector3 av = get_angular_velocity(); float linear_damp = 1.0 - step * get_total_linear_damp(); - if (linear_damp<0) // reached zero in the given time - linear_damp=0; + if (linear_damp < 0) // reached zero in the given time + linear_damp = 0; float angular_damp = 1.0 - step * get_total_angular_damp(); - if (angular_damp<0) // reached zero in the given time - angular_damp=0; + if (angular_damp < 0) // reached zero in the given time + angular_damp = 0; - lv*=linear_damp; - av*=angular_damp; + lv *= linear_damp; + av *= angular_damp; set_linear_velocity(lv); set_angular_velocity(av); - - - - } -Object* PhysicsDirectBodyState::get_contact_collider_object(int p_contact_idx) const { +Object *PhysicsDirectBodyState::get_contact_collider_object(int p_contact_idx) const { ObjectID objid = get_contact_collider_id(p_contact_idx); - Object *obj = ObjectDB::get_instance( objid ); + Object *obj = ObjectDB::get_instance(objid); return obj; } -PhysicsServer * PhysicsServer::get_singleton() { +PhysicsServer *PhysicsServer::get_singleton() { return singleton; } void PhysicsDirectBodyState::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_total_gravity"),&PhysicsDirectBodyState::get_total_gravity); - ClassDB::bind_method(D_METHOD("get_total_linear_damp"),&PhysicsDirectBodyState::get_total_linear_damp); - ClassDB::bind_method(D_METHOD("get_total_angular_damp"),&PhysicsDirectBodyState::get_total_angular_damp); - - ClassDB::bind_method(D_METHOD("get_center_of_mass"),&PhysicsDirectBodyState::get_center_of_mass); - ClassDB::bind_method(D_METHOD("get_principal_inetria_axes"),&PhysicsDirectBodyState::get_principal_inertia_axes); + ClassDB::bind_method(D_METHOD("get_total_gravity"), &PhysicsDirectBodyState::get_total_gravity); + ClassDB::bind_method(D_METHOD("get_total_linear_damp"), &PhysicsDirectBodyState::get_total_linear_damp); + ClassDB::bind_method(D_METHOD("get_total_angular_damp"), &PhysicsDirectBodyState::get_total_angular_damp); - ClassDB::bind_method(D_METHOD("get_inverse_mass"),&PhysicsDirectBodyState::get_inverse_mass); - ClassDB::bind_method(D_METHOD("get_inverse_inertia"),&PhysicsDirectBodyState::get_inverse_inertia); + ClassDB::bind_method(D_METHOD("get_center_of_mass"), &PhysicsDirectBodyState::get_center_of_mass); + ClassDB::bind_method(D_METHOD("get_principal_inetria_axes"), &PhysicsDirectBodyState::get_principal_inertia_axes); - ClassDB::bind_method(D_METHOD("set_linear_velocity","velocity"),&PhysicsDirectBodyState::set_linear_velocity); - ClassDB::bind_method(D_METHOD("get_linear_velocity"),&PhysicsDirectBodyState::get_linear_velocity); + ClassDB::bind_method(D_METHOD("get_inverse_mass"), &PhysicsDirectBodyState::get_inverse_mass); + ClassDB::bind_method(D_METHOD("get_inverse_inertia"), &PhysicsDirectBodyState::get_inverse_inertia); - ClassDB::bind_method(D_METHOD("set_angular_velocity","velocity"),&PhysicsDirectBodyState::set_angular_velocity); - ClassDB::bind_method(D_METHOD("get_angular_velocity"),&PhysicsDirectBodyState::get_angular_velocity); + ClassDB::bind_method(D_METHOD("set_linear_velocity", "velocity"), &PhysicsDirectBodyState::set_linear_velocity); + ClassDB::bind_method(D_METHOD("get_linear_velocity"), &PhysicsDirectBodyState::get_linear_velocity); - ClassDB::bind_method(D_METHOD("set_transform","transform"),&PhysicsDirectBodyState::set_transform); - ClassDB::bind_method(D_METHOD("get_transform"),&PhysicsDirectBodyState::get_transform); + ClassDB::bind_method(D_METHOD("set_angular_velocity", "velocity"), &PhysicsDirectBodyState::set_angular_velocity); + ClassDB::bind_method(D_METHOD("get_angular_velocity"), &PhysicsDirectBodyState::get_angular_velocity); - ClassDB::bind_method(D_METHOD("add_force","force","pos"),&PhysicsDirectBodyState::add_force); - ClassDB::bind_method(D_METHOD("apply_impulse","pos","j"),&PhysicsDirectBodyState::apply_impulse); - ClassDB::bind_method(D_METHOD("apply_torqe_impulse","j"),&PhysicsDirectBodyState::apply_torque_impulse); + ClassDB::bind_method(D_METHOD("set_transform", "transform"), &PhysicsDirectBodyState::set_transform); + ClassDB::bind_method(D_METHOD("get_transform"), &PhysicsDirectBodyState::get_transform); - ClassDB::bind_method(D_METHOD("set_sleep_state","enabled"),&PhysicsDirectBodyState::set_sleep_state); - ClassDB::bind_method(D_METHOD("is_sleeping"),&PhysicsDirectBodyState::is_sleeping); + ClassDB::bind_method(D_METHOD("add_force", "force", "pos"), &PhysicsDirectBodyState::add_force); + ClassDB::bind_method(D_METHOD("apply_impulse", "pos", "j"), &PhysicsDirectBodyState::apply_impulse); + ClassDB::bind_method(D_METHOD("apply_torqe_impulse", "j"), &PhysicsDirectBodyState::apply_torque_impulse); - ClassDB::bind_method(D_METHOD("get_contact_count"),&PhysicsDirectBodyState::get_contact_count); + ClassDB::bind_method(D_METHOD("set_sleep_state", "enabled"), &PhysicsDirectBodyState::set_sleep_state); + ClassDB::bind_method(D_METHOD("is_sleeping"), &PhysicsDirectBodyState::is_sleeping); - ClassDB::bind_method(D_METHOD("get_contact_local_pos","contact_idx"),&PhysicsDirectBodyState::get_contact_local_pos); - ClassDB::bind_method(D_METHOD("get_contact_local_normal","contact_idx"),&PhysicsDirectBodyState::get_contact_local_normal); - ClassDB::bind_method(D_METHOD("get_contact_local_shape","contact_idx"),&PhysicsDirectBodyState::get_contact_local_shape); - ClassDB::bind_method(D_METHOD("get_contact_collider","contact_idx"),&PhysicsDirectBodyState::get_contact_collider); - ClassDB::bind_method(D_METHOD("get_contact_collider_pos","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_pos); - ClassDB::bind_method(D_METHOD("get_contact_collider_id","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_id); - ClassDB::bind_method(D_METHOD("get_contact_collider_object","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_object); - ClassDB::bind_method(D_METHOD("get_contact_collider_shape","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_shape); - ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_velocity_at_pos); - ClassDB::bind_method(D_METHOD("get_step"),&PhysicsDirectBodyState::get_step); - ClassDB::bind_method(D_METHOD("integrate_forces"),&PhysicsDirectBodyState::integrate_forces); - ClassDB::bind_method(D_METHOD("get_space_state:PhysicsDirectSpaceState"),&PhysicsDirectBodyState::get_space_state); + ClassDB::bind_method(D_METHOD("get_contact_count"), &PhysicsDirectBodyState::get_contact_count); + ClassDB::bind_method(D_METHOD("get_contact_local_pos", "contact_idx"), &PhysicsDirectBodyState::get_contact_local_pos); + ClassDB::bind_method(D_METHOD("get_contact_local_normal", "contact_idx"), &PhysicsDirectBodyState::get_contact_local_normal); + ClassDB::bind_method(D_METHOD("get_contact_local_shape", "contact_idx"), &PhysicsDirectBodyState::get_contact_local_shape); + ClassDB::bind_method(D_METHOD("get_contact_collider", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider); + ClassDB::bind_method(D_METHOD("get_contact_collider_pos", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_pos); + ClassDB::bind_method(D_METHOD("get_contact_collider_id", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_id); + ClassDB::bind_method(D_METHOD("get_contact_collider_object", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_object); + ClassDB::bind_method(D_METHOD("get_contact_collider_shape", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_shape); + ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_velocity_at_pos); + ClassDB::bind_method(D_METHOD("get_step"), &PhysicsDirectBodyState::get_step); + ClassDB::bind_method(D_METHOD("integrate_forces"), &PhysicsDirectBodyState::integrate_forces); + ClassDB::bind_method(D_METHOD("get_space_state:PhysicsDirectSpaceState"), &PhysicsDirectBodyState::get_space_state); } PhysicsDirectBodyState::PhysicsDirectBodyState() {} /////////////////////////////////////////////////////// - - void PhysicsShapeQueryParameters::set_shape(const RES &p_shape) { ERR_FAIL_COND(p_shape.is_null()); - shape=p_shape->get_rid(); + shape = p_shape->get_rid(); } -void PhysicsShapeQueryParameters::set_shape_rid(const RID& p_shape) { +void PhysicsShapeQueryParameters::set_shape_rid(const RID &p_shape) { - shape=p_shape; + shape = p_shape; } RID PhysicsShapeQueryParameters::get_shape_rid() const { @@ -139,95 +131,89 @@ RID PhysicsShapeQueryParameters::get_shape_rid() const { return shape; } -void PhysicsShapeQueryParameters::set_transform(const Transform& p_transform){ +void PhysicsShapeQueryParameters::set_transform(const Transform &p_transform) { - transform=p_transform; + transform = p_transform; } -Transform PhysicsShapeQueryParameters::get_transform() const{ +Transform PhysicsShapeQueryParameters::get_transform() const { return transform; } -void PhysicsShapeQueryParameters::set_margin(float p_margin){ +void PhysicsShapeQueryParameters::set_margin(float p_margin) { - margin=p_margin; + margin = p_margin; } -float PhysicsShapeQueryParameters::get_margin() const{ +float PhysicsShapeQueryParameters::get_margin() const { return margin; } -void PhysicsShapeQueryParameters::set_layer_mask(int p_layer_mask){ +void PhysicsShapeQueryParameters::set_layer_mask(int p_layer_mask) { - layer_mask=p_layer_mask; + layer_mask = p_layer_mask; } -int PhysicsShapeQueryParameters::get_layer_mask() const{ +int PhysicsShapeQueryParameters::get_layer_mask() const { return layer_mask; } +void PhysicsShapeQueryParameters::set_object_type_mask(int p_object_type_mask) { -void PhysicsShapeQueryParameters::set_object_type_mask(int p_object_type_mask){ - - object_type_mask=p_object_type_mask; + object_type_mask = p_object_type_mask; } -int PhysicsShapeQueryParameters::get_object_type_mask() const{ +int PhysicsShapeQueryParameters::get_object_type_mask() const { return object_type_mask; } -void PhysicsShapeQueryParameters::set_exclude(const Vector<RID>& p_exclude) { +void PhysicsShapeQueryParameters::set_exclude(const Vector<RID> &p_exclude) { exclude.clear(); - for(int i=0;i<p_exclude.size();i++) + for (int i = 0; i < p_exclude.size(); i++) exclude.insert(p_exclude[i]); - } -Vector<RID> PhysicsShapeQueryParameters::get_exclude() const{ +Vector<RID> PhysicsShapeQueryParameters::get_exclude() const { Vector<RID> ret; ret.resize(exclude.size()); - int idx=0; - for(Set<RID>::Element *E=exclude.front();E;E=E->next()) { - ret[idx]=E->get(); + int idx = 0; + for (Set<RID>::Element *E = exclude.front(); E; E = E->next()) { + ret[idx] = E->get(); } return ret; } void PhysicsShapeQueryParameters::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_shape","shape:Shape"),&PhysicsShapeQueryParameters::set_shape); - ClassDB::bind_method(D_METHOD("set_shape_rid","shape"),&PhysicsShapeQueryParameters::set_shape_rid); - ClassDB::bind_method(D_METHOD("get_shape_rid"),&PhysicsShapeQueryParameters::get_shape_rid); - - ClassDB::bind_method(D_METHOD("set_transform","transform"),&PhysicsShapeQueryParameters::set_transform); - ClassDB::bind_method(D_METHOD("get_transform"),&PhysicsShapeQueryParameters::get_transform); + ClassDB::bind_method(D_METHOD("set_shape", "shape:Shape"), &PhysicsShapeQueryParameters::set_shape); + ClassDB::bind_method(D_METHOD("set_shape_rid", "shape"), &PhysicsShapeQueryParameters::set_shape_rid); + ClassDB::bind_method(D_METHOD("get_shape_rid"), &PhysicsShapeQueryParameters::get_shape_rid); - ClassDB::bind_method(D_METHOD("set_margin","margin"),&PhysicsShapeQueryParameters::set_margin); - ClassDB::bind_method(D_METHOD("get_margin"),&PhysicsShapeQueryParameters::get_margin); + ClassDB::bind_method(D_METHOD("set_transform", "transform"), &PhysicsShapeQueryParameters::set_transform); + ClassDB::bind_method(D_METHOD("get_transform"), &PhysicsShapeQueryParameters::get_transform); - ClassDB::bind_method(D_METHOD("set_layer_mask","layer_mask"),&PhysicsShapeQueryParameters::set_layer_mask); - ClassDB::bind_method(D_METHOD("get_layer_mask"),&PhysicsShapeQueryParameters::get_layer_mask); + ClassDB::bind_method(D_METHOD("set_margin", "margin"), &PhysicsShapeQueryParameters::set_margin); + ClassDB::bind_method(D_METHOD("get_margin"), &PhysicsShapeQueryParameters::get_margin); - ClassDB::bind_method(D_METHOD("set_object_type_mask","object_type_mask"),&PhysicsShapeQueryParameters::set_object_type_mask); - ClassDB::bind_method(D_METHOD("get_object_type_mask"),&PhysicsShapeQueryParameters::get_object_type_mask); - - ClassDB::bind_method(D_METHOD("set_exclude","exclude"),&PhysicsShapeQueryParameters::set_exclude); - ClassDB::bind_method(D_METHOD("get_exclude"),&PhysicsShapeQueryParameters::get_exclude); + ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &PhysicsShapeQueryParameters::set_layer_mask); + ClassDB::bind_method(D_METHOD("get_layer_mask"), &PhysicsShapeQueryParameters::get_layer_mask); + ClassDB::bind_method(D_METHOD("set_object_type_mask", "object_type_mask"), &PhysicsShapeQueryParameters::set_object_type_mask); + ClassDB::bind_method(D_METHOD("get_object_type_mask"), &PhysicsShapeQueryParameters::get_object_type_mask); + ClassDB::bind_method(D_METHOD("set_exclude", "exclude"), &PhysicsShapeQueryParameters::set_exclude); + ClassDB::bind_method(D_METHOD("get_exclude"), &PhysicsShapeQueryParameters::get_exclude); } PhysicsShapeQueryParameters::PhysicsShapeQueryParameters() { - margin=0; - layer_mask=0x7FFFFFFF; - object_type_mask=PhysicsDirectSpaceState::TYPE_MASK_COLLISION; + margin = 0; + layer_mask = 0x7FFFFFFF; + object_type_mask = PhysicsDirectSpaceState::TYPE_MASK_COLLISION; } - - ///////////////////////////////////// /* @@ -260,26 +246,25 @@ Variant PhysicsDirectSpaceState::_intersect_shape(const RID& p_shape, const Tran } */ - -Dictionary PhysicsDirectSpaceState::_intersect_ray(const Vector3& p_from, const Vector3& p_to,const Vector<RID>& p_exclude,uint32_t p_layers,uint32_t p_object_type_mask) { +Dictionary PhysicsDirectSpaceState::_intersect_ray(const Vector3 &p_from, const Vector3 &p_to, const Vector<RID> &p_exclude, uint32_t p_layers, uint32_t p_object_type_mask) { RayResult inters; Set<RID> exclude; - for(int i=0;i<p_exclude.size();i++) + for (int i = 0; i < p_exclude.size(); i++) exclude.insert(p_exclude[i]); - bool res = intersect_ray(p_from,p_to,inters,exclude,p_layers,p_object_type_mask); + bool res = intersect_ray(p_from, p_to, inters, exclude, p_layers, p_object_type_mask); if (!res) return Dictionary(); Dictionary d; - d["position"]=inters.position; - d["normal"]=inters.normal; - d["collider_id"]=inters.collider_id; - d["collider"]=inters.collider; - d["shape"]=inters.shape; - d["rid"]=inters.rid; + d["position"] = inters.position; + d["normal"] = inters.normal; + d["collider_id"] = inters.collider_id; + d["collider"] = inters.collider; + d["shape"] = inters.shape; + d["rid"] = inters.rid; return d; } @@ -288,101 +273,89 @@ Array PhysicsDirectSpaceState::_intersect_shape(const Ref<PhysicsShapeQueryParam Vector<ShapeResult> sr; sr.resize(p_max_results); - int rc = intersect_shape(psq->shape,psq->transform,psq->margin,sr.ptr(),sr.size(),psq->exclude,psq->layer_mask,psq->object_type_mask); + int rc = intersect_shape(psq->shape, psq->transform, psq->margin, sr.ptr(), sr.size(), psq->exclude, psq->layer_mask, psq->object_type_mask); Array ret; ret.resize(rc); - for(int i=0;i<rc;i++) { + for (int i = 0; i < rc; i++) { Dictionary d; - d["rid"]=sr[i].rid; - d["collider_id"]=sr[i].collider_id; - d["collider"]=sr[i].collider; - d["shape"]=sr[i].shape; - ret[i]=d; + d["rid"] = sr[i].rid; + d["collider_id"] = sr[i].collider_id; + d["collider"] = sr[i].collider; + d["shape"] = sr[i].shape; + ret[i] = d; } return ret; } -Array PhysicsDirectSpaceState::_cast_motion(const Ref<PhysicsShapeQueryParameters> &psq,const Vector3& p_motion){ +Array PhysicsDirectSpaceState::_cast_motion(const Ref<PhysicsShapeQueryParameters> &psq, const Vector3 &p_motion) { - float closest_safe,closest_unsafe; - bool res = cast_motion(psq->shape,psq->transform,p_motion,psq->margin,closest_safe,closest_unsafe,psq->exclude,psq->layer_mask,psq->object_type_mask); + float closest_safe, closest_unsafe; + bool res = cast_motion(psq->shape, psq->transform, p_motion, psq->margin, closest_safe, closest_unsafe, psq->exclude, psq->layer_mask, psq->object_type_mask); if (!res) return Array(); Array ret; ret.resize(2); - ret[0]=closest_safe; - ret[1]=closest_unsafe; + ret[0] = closest_safe; + ret[1] = closest_unsafe; return ret; - } -Array PhysicsDirectSpaceState::_collide_shape(const Ref<PhysicsShapeQueryParameters> &psq, int p_max_results){ +Array PhysicsDirectSpaceState::_collide_shape(const Ref<PhysicsShapeQueryParameters> &psq, int p_max_results) { Vector<Vector3> ret; - ret.resize(p_max_results*2); - int rc=0; - bool res = collide_shape(psq->shape,psq->transform,psq->margin,ret.ptr(),p_max_results,rc,psq->exclude,psq->layer_mask,psq->object_type_mask); + ret.resize(p_max_results * 2); + int rc = 0; + bool res = collide_shape(psq->shape, psq->transform, psq->margin, ret.ptr(), p_max_results, rc, psq->exclude, psq->layer_mask, psq->object_type_mask); if (!res) return Array(); Array r; - r.resize(rc*2); - for(int i=0;i<rc*2;i++) - r[i]=ret[i]; + r.resize(rc * 2); + for (int i = 0; i < rc * 2; i++) + r[i] = ret[i]; return r; - } -Dictionary PhysicsDirectSpaceState::_get_rest_info(const Ref<PhysicsShapeQueryParameters> &psq){ +Dictionary PhysicsDirectSpaceState::_get_rest_info(const Ref<PhysicsShapeQueryParameters> &psq) { ShapeRestInfo sri; - bool res = rest_info(psq->shape,psq->transform,psq->margin,&sri,psq->exclude,psq->layer_mask,psq->object_type_mask); + bool res = rest_info(psq->shape, psq->transform, psq->margin, &sri, psq->exclude, psq->layer_mask, psq->object_type_mask); Dictionary r; if (!res) return r; - r["point"]=sri.point; - r["normal"]=sri.normal; - r["rid"]=sri.rid; - r["collider_id"]=sri.collider_id; - r["shape"]=sri.shape; - r["linear_velocity"]=sri.linear_velocity; + r["point"] = sri.point; + r["normal"] = sri.normal; + r["rid"] = sri.rid; + r["collider_id"] = sri.collider_id; + r["shape"] = sri.shape; + r["linear_velocity"] = sri.linear_velocity; return r; } - - PhysicsDirectSpaceState::PhysicsDirectSpaceState() { - - - } - void PhysicsDirectSpaceState::_bind_methods() { - //ClassDB::bind_method(D_METHOD("intersect_ray","from","to","exclude","umask"),&PhysicsDirectSpaceState::_intersect_ray,DEFVAL(Array()),DEFVAL(0)); //ClassDB::bind_method(D_METHOD("intersect_shape:PhysicsShapeQueryResult","shape","xform","result_max","exclude","umask"),&PhysicsDirectSpaceState::_intersect_shape,DEFVAL(Array()),DEFVAL(0)); - ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary","from","to","exclude","layer_mask","type_mask"),&PhysicsDirectSpaceState::_intersect_ray,DEFVAL(Array()),DEFVAL(0x7FFFFFFF),DEFVAL(TYPE_MASK_COLLISION)); - ClassDB::bind_method(D_METHOD("intersect_shape","shape:PhysicsShapeQueryParameters","max_results"),&PhysicsDirectSpaceState::_intersect_shape,DEFVAL(32)); - ClassDB::bind_method(D_METHOD("cast_motion","shape:PhysicsShapeQueryParameters","motion"),&PhysicsDirectSpaceState::_cast_motion); - ClassDB::bind_method(D_METHOD("collide_shape","shape:PhysicsShapeQueryParameters","max_results"),&PhysicsDirectSpaceState::_collide_shape,DEFVAL(32)); - ClassDB::bind_method(D_METHOD("get_rest_info","shape:PhysicsShapeQueryParameters"),&PhysicsDirectSpaceState::_get_rest_info); - - - BIND_CONSTANT( TYPE_MASK_STATIC_BODY ); - BIND_CONSTANT( TYPE_MASK_KINEMATIC_BODY ); - BIND_CONSTANT( TYPE_MASK_RIGID_BODY ); - BIND_CONSTANT( TYPE_MASK_CHARACTER_BODY ); - BIND_CONSTANT( TYPE_MASK_AREA ); - BIND_CONSTANT( TYPE_MASK_COLLISION ); + ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary", "from", "to", "exclude", "layer_mask", "type_mask"), &PhysicsDirectSpaceState::_intersect_ray, DEFVAL(Array()), DEFVAL(0x7FFFFFFF), DEFVAL(TYPE_MASK_COLLISION)); + ClassDB::bind_method(D_METHOD("intersect_shape", "shape:PhysicsShapeQueryParameters", "max_results"), &PhysicsDirectSpaceState::_intersect_shape, DEFVAL(32)); + ClassDB::bind_method(D_METHOD("cast_motion", "shape:PhysicsShapeQueryParameters", "motion"), &PhysicsDirectSpaceState::_cast_motion); + ClassDB::bind_method(D_METHOD("collide_shape", "shape:PhysicsShapeQueryParameters", "max_results"), &PhysicsDirectSpaceState::_collide_shape, DEFVAL(32)); + ClassDB::bind_method(D_METHOD("get_rest_info", "shape:PhysicsShapeQueryParameters"), &PhysicsDirectSpaceState::_get_rest_info); + BIND_CONSTANT(TYPE_MASK_STATIC_BODY); + BIND_CONSTANT(TYPE_MASK_KINEMATIC_BODY); + BIND_CONSTANT(TYPE_MASK_RIGID_BODY); + BIND_CONSTANT(TYPE_MASK_CHARACTER_BODY); + BIND_CONSTANT(TYPE_MASK_AREA); + BIND_CONSTANT(TYPE_MASK_COLLISION); } - int PhysicsShapeQueryResult::get_result_count() const { return result.size(); @@ -395,7 +368,7 @@ ObjectID PhysicsShapeQueryResult::get_result_object_id(int p_idx) const { return result[p_idx].collider_id; } -Object* PhysicsShapeQueryResult::get_result_object(int p_idx) const { +Object *PhysicsShapeQueryResult::get_result_object(int p_idx) const { return result[p_idx].collider; } @@ -405,165 +378,152 @@ int PhysicsShapeQueryResult::get_result_object_shape(int p_idx) const { } PhysicsShapeQueryResult::PhysicsShapeQueryResult() { - - } void PhysicsShapeQueryResult::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_result_count"),&PhysicsShapeQueryResult::get_result_count); - ClassDB::bind_method(D_METHOD("get_result_rid","idx"),&PhysicsShapeQueryResult::get_result_rid); - ClassDB::bind_method(D_METHOD("get_result_object_id","idx"),&PhysicsShapeQueryResult::get_result_object_id); - ClassDB::bind_method(D_METHOD("get_result_object","idx"),&PhysicsShapeQueryResult::get_result_object); - ClassDB::bind_method(D_METHOD("get_result_object_shape","idx"),&PhysicsShapeQueryResult::get_result_object_shape); - - + ClassDB::bind_method(D_METHOD("get_result_count"), &PhysicsShapeQueryResult::get_result_count); + ClassDB::bind_method(D_METHOD("get_result_rid", "idx"), &PhysicsShapeQueryResult::get_result_rid); + ClassDB::bind_method(D_METHOD("get_result_object_id", "idx"), &PhysicsShapeQueryResult::get_result_object_id); + ClassDB::bind_method(D_METHOD("get_result_object", "idx"), &PhysicsShapeQueryResult::get_result_object); + ClassDB::bind_method(D_METHOD("get_result_object_shape", "idx"), &PhysicsShapeQueryResult::get_result_object_shape); } - - - - /////////////////////////////////////// void PhysicsServer::_bind_methods() { + ClassDB::bind_method(D_METHOD("shape_create", "type"), &PhysicsServer::shape_create); + ClassDB::bind_method(D_METHOD("shape_set_data", "shape", "data"), &PhysicsServer::shape_set_data); - ClassDB::bind_method(D_METHOD("shape_create","type"),&PhysicsServer::shape_create); - ClassDB::bind_method(D_METHOD("shape_set_data","shape","data"),&PhysicsServer::shape_set_data); - - ClassDB::bind_method(D_METHOD("shape_get_type","shape"),&PhysicsServer::shape_get_type); - ClassDB::bind_method(D_METHOD("shape_get_data","shape"),&PhysicsServer::shape_get_data); + ClassDB::bind_method(D_METHOD("shape_get_type", "shape"), &PhysicsServer::shape_get_type); + ClassDB::bind_method(D_METHOD("shape_get_data", "shape"), &PhysicsServer::shape_get_data); + ClassDB::bind_method(D_METHOD("space_create"), &PhysicsServer::space_create); + ClassDB::bind_method(D_METHOD("space_set_active", "space", "active"), &PhysicsServer::space_set_active); + ClassDB::bind_method(D_METHOD("space_is_active", "space"), &PhysicsServer::space_is_active); + ClassDB::bind_method(D_METHOD("space_set_param", "space", "param", "value"), &PhysicsServer::space_set_param); + ClassDB::bind_method(D_METHOD("space_get_param", "space", "param"), &PhysicsServer::space_get_param); + ClassDB::bind_method(D_METHOD("space_get_direct_state:PhysicsDirectSpaceState", "space"), &PhysicsServer::space_get_direct_state); - ClassDB::bind_method(D_METHOD("space_create"),&PhysicsServer::space_create); - ClassDB::bind_method(D_METHOD("space_set_active","space","active"),&PhysicsServer::space_set_active); - ClassDB::bind_method(D_METHOD("space_is_active","space"),&PhysicsServer::space_is_active); - ClassDB::bind_method(D_METHOD("space_set_param","space","param","value"),&PhysicsServer::space_set_param); - ClassDB::bind_method(D_METHOD("space_get_param","space","param"),&PhysicsServer::space_get_param); - ClassDB::bind_method(D_METHOD("space_get_direct_state:PhysicsDirectSpaceState","space"),&PhysicsServer::space_get_direct_state); + ClassDB::bind_method(D_METHOD("area_create"), &PhysicsServer::area_create); + ClassDB::bind_method(D_METHOD("area_set_space", "area", "space"), &PhysicsServer::area_set_space); + ClassDB::bind_method(D_METHOD("area_get_space", "area"), &PhysicsServer::area_get_space); - ClassDB::bind_method(D_METHOD("area_create"),&PhysicsServer::area_create); - ClassDB::bind_method(D_METHOD("area_set_space","area","space"),&PhysicsServer::area_set_space); - ClassDB::bind_method(D_METHOD("area_get_space","area"),&PhysicsServer::area_get_space); + ClassDB::bind_method(D_METHOD("area_set_space_override_mode", "area", "mode"), &PhysicsServer::area_set_space_override_mode); + ClassDB::bind_method(D_METHOD("area_get_space_override_mode", "area"), &PhysicsServer::area_get_space_override_mode); - ClassDB::bind_method(D_METHOD("area_set_space_override_mode","area","mode"),&PhysicsServer::area_set_space_override_mode); - ClassDB::bind_method(D_METHOD("area_get_space_override_mode","area"),&PhysicsServer::area_get_space_override_mode); + ClassDB::bind_method(D_METHOD("area_add_shape", "area", "shape", "transform"), &PhysicsServer::area_add_shape, DEFVAL(Transform())); + ClassDB::bind_method(D_METHOD("area_set_shape", "area", "shape_idx", "shape"), &PhysicsServer::area_set_shape); + ClassDB::bind_method(D_METHOD("area_set_shape_transform", "area", "shape_idx", "transform"), &PhysicsServer::area_set_shape_transform); - ClassDB::bind_method(D_METHOD("area_add_shape","area","shape","transform"),&PhysicsServer::area_add_shape,DEFVAL(Transform())); - ClassDB::bind_method(D_METHOD("area_set_shape","area","shape_idx","shape"),&PhysicsServer::area_set_shape); - ClassDB::bind_method(D_METHOD("area_set_shape_transform","area","shape_idx","transform"),&PhysicsServer::area_set_shape_transform); + ClassDB::bind_method(D_METHOD("area_get_shape_count", "area"), &PhysicsServer::area_get_shape_count); + ClassDB::bind_method(D_METHOD("area_get_shape", "area", "shape_idx"), &PhysicsServer::area_get_shape); + ClassDB::bind_method(D_METHOD("area_get_shape_transform", "area", "shape_idx"), &PhysicsServer::area_get_shape_transform); - ClassDB::bind_method(D_METHOD("area_get_shape_count","area"),&PhysicsServer::area_get_shape_count); - ClassDB::bind_method(D_METHOD("area_get_shape","area","shape_idx"),&PhysicsServer::area_get_shape); - ClassDB::bind_method(D_METHOD("area_get_shape_transform","area","shape_idx"),&PhysicsServer::area_get_shape_transform); + ClassDB::bind_method(D_METHOD("area_remove_shape", "area", "shape_idx"), &PhysicsServer::area_remove_shape); + ClassDB::bind_method(D_METHOD("area_clear_shapes", "area"), &PhysicsServer::area_clear_shapes); - ClassDB::bind_method(D_METHOD("area_remove_shape","area","shape_idx"),&PhysicsServer::area_remove_shape); - ClassDB::bind_method(D_METHOD("area_clear_shapes","area"),&PhysicsServer::area_clear_shapes); + ClassDB::bind_method(D_METHOD("area_set_layer_mask", "area", "mask"), &PhysicsServer::area_set_layer_mask); + ClassDB::bind_method(D_METHOD("area_set_collision_mask", "area", "mask"), &PhysicsServer::area_set_collision_mask); - ClassDB::bind_method(D_METHOD("area_set_layer_mask","area","mask"),&PhysicsServer::area_set_layer_mask); - ClassDB::bind_method(D_METHOD("area_set_collision_mask","area","mask"),&PhysicsServer::area_set_collision_mask); + ClassDB::bind_method(D_METHOD("area_set_param", "area", "param", "value"), &PhysicsServer::area_set_param); + ClassDB::bind_method(D_METHOD("area_set_transform", "area", "transform"), &PhysicsServer::area_set_transform); - ClassDB::bind_method(D_METHOD("area_set_param","area","param","value"),&PhysicsServer::area_set_param); - ClassDB::bind_method(D_METHOD("area_set_transform","area","transform"),&PhysicsServer::area_set_transform); + ClassDB::bind_method(D_METHOD("area_get_param", "area", "param"), &PhysicsServer::area_get_param); + ClassDB::bind_method(D_METHOD("area_get_transform", "area"), &PhysicsServer::area_get_transform); - ClassDB::bind_method(D_METHOD("area_get_param","area","param"),&PhysicsServer::area_get_param); - ClassDB::bind_method(D_METHOD("area_get_transform","area"),&PhysicsServer::area_get_transform); + ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID", "area", "id"), &PhysicsServer::area_attach_object_instance_ID); + ClassDB::bind_method(D_METHOD("area_get_object_instance_ID", "area"), &PhysicsServer::area_get_object_instance_ID); - ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID","area","id"),&PhysicsServer::area_attach_object_instance_ID); - ClassDB::bind_method(D_METHOD("area_get_object_instance_ID","area"),&PhysicsServer::area_get_object_instance_ID); + ClassDB::bind_method(D_METHOD("area_set_monitor_callback", "area", "receiver", "method"), &PhysicsServer::area_set_monitor_callback); - ClassDB::bind_method(D_METHOD("area_set_monitor_callback","area","receiver","method"),&PhysicsServer::area_set_monitor_callback); + ClassDB::bind_method(D_METHOD("area_set_ray_pickable", "area", "enable"), &PhysicsServer::area_set_ray_pickable); + ClassDB::bind_method(D_METHOD("area_is_ray_pickable", "area"), &PhysicsServer::area_is_ray_pickable); - ClassDB::bind_method(D_METHOD("area_set_ray_pickable","area","enable"),&PhysicsServer::area_set_ray_pickable); - ClassDB::bind_method(D_METHOD("area_is_ray_pickable","area"),&PhysicsServer::area_is_ray_pickable); + ClassDB::bind_method(D_METHOD("body_create", "mode", "init_sleeping"), &PhysicsServer::body_create, DEFVAL(BODY_MODE_RIGID), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("body_create","mode","init_sleeping"),&PhysicsServer::body_create,DEFVAL(BODY_MODE_RIGID),DEFVAL(false)); + ClassDB::bind_method(D_METHOD("body_set_space", "body", "space"), &PhysicsServer::body_set_space); + ClassDB::bind_method(D_METHOD("body_get_space", "body"), &PhysicsServer::body_get_space); - ClassDB::bind_method(D_METHOD("body_set_space","body","space"),&PhysicsServer::body_set_space); - ClassDB::bind_method(D_METHOD("body_get_space","body"),&PhysicsServer::body_get_space); + ClassDB::bind_method(D_METHOD("body_set_mode", "body", "mode"), &PhysicsServer::body_set_mode); + ClassDB::bind_method(D_METHOD("body_get_mode", "body"), &PhysicsServer::body_get_mode); - ClassDB::bind_method(D_METHOD("body_set_mode","body","mode"),&PhysicsServer::body_set_mode); - ClassDB::bind_method(D_METHOD("body_get_mode","body"),&PhysicsServer::body_get_mode); + ClassDB::bind_method(D_METHOD("body_set_layer_mask", "body", "mask"), &PhysicsServer::body_set_layer_mask); + ClassDB::bind_method(D_METHOD("body_get_layer_mask", "body"), &PhysicsServer::body_get_layer_mask); - ClassDB::bind_method(D_METHOD("body_set_layer_mask","body","mask"),&PhysicsServer::body_set_layer_mask); - ClassDB::bind_method(D_METHOD("body_get_layer_mask","body"),&PhysicsServer::body_get_layer_mask); + ClassDB::bind_method(D_METHOD("body_set_collision_mask", "body", "mask"), &PhysicsServer::body_set_collision_mask); + ClassDB::bind_method(D_METHOD("body_get_collision_mask", "body"), &PhysicsServer::body_get_collision_mask); - ClassDB::bind_method(D_METHOD("body_set_collision_mask","body","mask"),&PhysicsServer::body_set_collision_mask); - ClassDB::bind_method(D_METHOD("body_get_collision_mask","body"),&PhysicsServer::body_get_collision_mask); + ClassDB::bind_method(D_METHOD("body_add_shape", "body", "shape", "transform"), &PhysicsServer::body_add_shape, DEFVAL(Transform())); + ClassDB::bind_method(D_METHOD("body_set_shape", "body", "shape_idx", "shape"), &PhysicsServer::body_set_shape); + ClassDB::bind_method(D_METHOD("body_set_shape_transform", "body", "shape_idx", "transform"), &PhysicsServer::body_set_shape_transform); - ClassDB::bind_method(D_METHOD("body_add_shape","body","shape","transform"),&PhysicsServer::body_add_shape,DEFVAL(Transform())); - ClassDB::bind_method(D_METHOD("body_set_shape","body","shape_idx","shape"),&PhysicsServer::body_set_shape); - ClassDB::bind_method(D_METHOD("body_set_shape_transform","body","shape_idx","transform"),&PhysicsServer::body_set_shape_transform); + ClassDB::bind_method(D_METHOD("body_get_shape_count", "body"), &PhysicsServer::body_get_shape_count); + ClassDB::bind_method(D_METHOD("body_get_shape", "body", "shape_idx"), &PhysicsServer::body_get_shape); + ClassDB::bind_method(D_METHOD("body_get_shape_transform", "body", "shape_idx"), &PhysicsServer::body_get_shape_transform); - ClassDB::bind_method(D_METHOD("body_get_shape_count","body"),&PhysicsServer::body_get_shape_count); - ClassDB::bind_method(D_METHOD("body_get_shape","body","shape_idx"),&PhysicsServer::body_get_shape); - ClassDB::bind_method(D_METHOD("body_get_shape_transform","body","shape_idx"),&PhysicsServer::body_get_shape_transform); + ClassDB::bind_method(D_METHOD("body_remove_shape", "body", "shape_idx"), &PhysicsServer::body_remove_shape); + ClassDB::bind_method(D_METHOD("body_clear_shapes", "body"), &PhysicsServer::body_clear_shapes); - ClassDB::bind_method(D_METHOD("body_remove_shape","body","shape_idx"),&PhysicsServer::body_remove_shape); - ClassDB::bind_method(D_METHOD("body_clear_shapes","body"),&PhysicsServer::body_clear_shapes); - - ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID","body","id"),&PhysicsServer::body_attach_object_instance_ID); - ClassDB::bind_method(D_METHOD("body_get_object_instance_ID","body"),&PhysicsServer::body_get_object_instance_ID); - - - ClassDB::bind_method(D_METHOD("body_set_enable_continuous_collision_detection","body","enable"),&PhysicsServer::body_set_enable_continuous_collision_detection); - ClassDB::bind_method(D_METHOD("body_is_continuous_collision_detection_enabled","body"),&PhysicsServer::body_is_continuous_collision_detection_enabled); + ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID", "body", "id"), &PhysicsServer::body_attach_object_instance_ID); + ClassDB::bind_method(D_METHOD("body_get_object_instance_ID", "body"), &PhysicsServer::body_get_object_instance_ID); + ClassDB::bind_method(D_METHOD("body_set_enable_continuous_collision_detection", "body", "enable"), &PhysicsServer::body_set_enable_continuous_collision_detection); + ClassDB::bind_method(D_METHOD("body_is_continuous_collision_detection_enabled", "body"), &PhysicsServer::body_is_continuous_collision_detection_enabled); //ClassDB::bind_method(D_METHOD("body_set_user_flags","flags""),&PhysicsServer::body_set_shape,DEFVAL(Transform)); //ClassDB::bind_method(D_METHOD("body_get_user_flags","body","shape_idx","shape"),&PhysicsServer::body_get_shape); - ClassDB::bind_method(D_METHOD("body_set_param","body","param","value"),&PhysicsServer::body_set_param); - ClassDB::bind_method(D_METHOD("body_get_param","body","param"),&PhysicsServer::body_get_param); + ClassDB::bind_method(D_METHOD("body_set_param", "body", "param", "value"), &PhysicsServer::body_set_param); + ClassDB::bind_method(D_METHOD("body_get_param", "body", "param"), &PhysicsServer::body_get_param); - ClassDB::bind_method(D_METHOD("body_set_state","body","state","value"),&PhysicsServer::body_set_state); - ClassDB::bind_method(D_METHOD("body_get_state","body","state"),&PhysicsServer::body_get_state); + ClassDB::bind_method(D_METHOD("body_set_state", "body", "state", "value"), &PhysicsServer::body_set_state); + ClassDB::bind_method(D_METHOD("body_get_state", "body", "state"), &PhysicsServer::body_get_state); - ClassDB::bind_method(D_METHOD("body_apply_impulse","body","pos","impulse"),&PhysicsServer::body_apply_impulse); - ClassDB::bind_method(D_METHOD("body_apply_torque_impulse","body","impulse"),&PhysicsServer::body_apply_torque_impulse); - ClassDB::bind_method(D_METHOD("body_set_axis_velocity","body","axis_velocity"),&PhysicsServer::body_set_axis_velocity); + ClassDB::bind_method(D_METHOD("body_apply_impulse", "body", "pos", "impulse"), &PhysicsServer::body_apply_impulse); + ClassDB::bind_method(D_METHOD("body_apply_torque_impulse", "body", "impulse"), &PhysicsServer::body_apply_torque_impulse); + ClassDB::bind_method(D_METHOD("body_set_axis_velocity", "body", "axis_velocity"), &PhysicsServer::body_set_axis_velocity); - ClassDB::bind_method(D_METHOD("body_set_axis_lock","body","axis"),&PhysicsServer::body_set_axis_lock); - ClassDB::bind_method(D_METHOD("body_get_axis_lock","body"),&PhysicsServer::body_get_axis_lock); + ClassDB::bind_method(D_METHOD("body_set_axis_lock", "body", "axis"), &PhysicsServer::body_set_axis_lock); + ClassDB::bind_method(D_METHOD("body_get_axis_lock", "body"), &PhysicsServer::body_get_axis_lock); - ClassDB::bind_method(D_METHOD("body_add_collision_exception","body","excepted_body"),&PhysicsServer::body_add_collision_exception); - ClassDB::bind_method(D_METHOD("body_remove_collision_exception","body","excepted_body"),&PhysicsServer::body_remove_collision_exception); + ClassDB::bind_method(D_METHOD("body_add_collision_exception", "body", "excepted_body"), &PhysicsServer::body_add_collision_exception); + ClassDB::bind_method(D_METHOD("body_remove_collision_exception", "body", "excepted_body"), &PhysicsServer::body_remove_collision_exception); //virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0; - ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported","body","amount"),&PhysicsServer::body_set_max_contacts_reported); - ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported","body"),&PhysicsServer::body_get_max_contacts_reported); + ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported", "body", "amount"), &PhysicsServer::body_set_max_contacts_reported); + ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported", "body"), &PhysicsServer::body_get_max_contacts_reported); - ClassDB::bind_method(D_METHOD("body_set_omit_force_integration","body","enable"),&PhysicsServer::body_set_omit_force_integration); - ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration","body"),&PhysicsServer::body_is_omitting_force_integration); + ClassDB::bind_method(D_METHOD("body_set_omit_force_integration", "body", "enable"), &PhysicsServer::body_set_omit_force_integration); + ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration", "body"), &PhysicsServer::body_is_omitting_force_integration); - ClassDB::bind_method(D_METHOD("body_set_force_integration_callback","body","receiver","method","userdata"),&PhysicsServer::body_set_force_integration_callback,DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("body_set_force_integration_callback", "body", "receiver", "method", "userdata"), &PhysicsServer::body_set_force_integration_callback, DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("body_set_ray_pickable","body","enable"),&PhysicsServer::body_set_ray_pickable); - ClassDB::bind_method(D_METHOD("body_is_ray_pickable","body"),&PhysicsServer::body_is_ray_pickable); + ClassDB::bind_method(D_METHOD("body_set_ray_pickable", "body", "enable"), &PhysicsServer::body_set_ray_pickable); + ClassDB::bind_method(D_METHOD("body_is_ray_pickable", "body"), &PhysicsServer::body_is_ray_pickable); /* JOINT API */ - BIND_CONSTANT( JOINT_PIN ); - BIND_CONSTANT( JOINT_HINGE ); - BIND_CONSTANT( JOINT_SLIDER ); - BIND_CONSTANT( JOINT_CONE_TWIST ); - BIND_CONSTANT( JOINT_6DOF ); + BIND_CONSTANT(JOINT_PIN); + BIND_CONSTANT(JOINT_HINGE); + BIND_CONSTANT(JOINT_SLIDER); + BIND_CONSTANT(JOINT_CONE_TWIST); + BIND_CONSTANT(JOINT_6DOF); - ClassDB::bind_method(D_METHOD("joint_create_pin","body_A","local_A","body_B","local_B"),&PhysicsServer::joint_create_pin); - ClassDB::bind_method(D_METHOD("pin_joint_set_param","joint","param","value"),&PhysicsServer::pin_joint_set_param); - ClassDB::bind_method(D_METHOD("pin_joint_get_param","joint","param"),&PhysicsServer::pin_joint_get_param); + ClassDB::bind_method(D_METHOD("joint_create_pin", "body_A", "local_A", "body_B", "local_B"), &PhysicsServer::joint_create_pin); + ClassDB::bind_method(D_METHOD("pin_joint_set_param", "joint", "param", "value"), &PhysicsServer::pin_joint_set_param); + ClassDB::bind_method(D_METHOD("pin_joint_get_param", "joint", "param"), &PhysicsServer::pin_joint_get_param); - ClassDB::bind_method(D_METHOD("pin_joint_set_local_A","joint","local_A"),&PhysicsServer::pin_joint_set_local_A); - ClassDB::bind_method(D_METHOD("pin_joint_get_local_A","joint"),&PhysicsServer::pin_joint_get_local_A); + ClassDB::bind_method(D_METHOD("pin_joint_set_local_A", "joint", "local_A"), &PhysicsServer::pin_joint_set_local_A); + ClassDB::bind_method(D_METHOD("pin_joint_get_local_A", "joint"), &PhysicsServer::pin_joint_get_local_A); - ClassDB::bind_method(D_METHOD("pin_joint_set_local_B","joint","local_B"),&PhysicsServer::pin_joint_set_local_B); - ClassDB::bind_method(D_METHOD("pin_joint_get_local_B","joint"),&PhysicsServer::pin_joint_get_local_B); - - BIND_CONSTANT(PIN_JOINT_BIAS ); - BIND_CONSTANT(PIN_JOINT_DAMPING ); - BIND_CONSTANT(PIN_JOINT_IMPULSE_CLAMP ); + ClassDB::bind_method(D_METHOD("pin_joint_set_local_B", "joint", "local_B"), &PhysicsServer::pin_joint_set_local_B); + ClassDB::bind_method(D_METHOD("pin_joint_get_local_B", "joint"), &PhysicsServer::pin_joint_get_local_B); + BIND_CONSTANT(PIN_JOINT_BIAS); + BIND_CONSTANT(PIN_JOINT_DAMPING); + BIND_CONSTANT(PIN_JOINT_IMPULSE_CLAMP); BIND_CONSTANT(HINGE_JOINT_BIAS); BIND_CONSTANT(HINGE_JOINT_LIMIT_UPPER); @@ -576,92 +536,88 @@ void PhysicsServer::_bind_methods() { BIND_CONSTANT(HINGE_JOINT_FLAG_USE_LIMIT); BIND_CONSTANT(HINGE_JOINT_FLAG_ENABLE_MOTOR); - ClassDB::bind_method(D_METHOD("joint_create_hinge","body_A","hinge_A","body_B","hinge_B"),&PhysicsServer::joint_create_hinge); - - ClassDB::bind_method(D_METHOD("hinge_joint_set_param","joint","param","value"),&PhysicsServer::hinge_joint_set_param); - ClassDB::bind_method(D_METHOD("hinge_joint_get_param","joint","param"),&PhysicsServer::hinge_joint_get_param); - - ClassDB::bind_method(D_METHOD("hinge_joint_set_flag","joint","flag","enabled"),&PhysicsServer::hinge_joint_set_flag); - ClassDB::bind_method(D_METHOD("hinge_joint_get_flag","joint","flag"),&PhysicsServer::hinge_joint_get_flag); - - ClassDB::bind_method(D_METHOD("joint_create_slider","body_A","local_ref_A","body_B","local_ref_B"),&PhysicsServer::joint_create_slider); - - ClassDB::bind_method(D_METHOD("slider_joint_set_param","joint","param","value"),&PhysicsServer::slider_joint_set_param); - ClassDB::bind_method(D_METHOD("slider_joint_get_param","joint","param"),&PhysicsServer::slider_joint_get_param); - - BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_UPPER ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_LOWER ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_DAMPING ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_MOTION_SOFTNESS ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_MOTION_RESTITUTION ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_MOTION_DAMPING ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION ); - BIND_CONSTANT( SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING ); - - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_UPPER ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_LOWER ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_DAMPING ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_MOTION_DAMPING ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION ); - BIND_CONSTANT( SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING ); - BIND_CONSTANT( SLIDER_JOINT_MAX ); - - - ClassDB::bind_method(D_METHOD("joint_create_cone_twist","body_A","local_ref_A","body_B","local_ref_B"),&PhysicsServer::joint_create_cone_twist); - - ClassDB::bind_method(D_METHOD("cone_twist_joint_set_param","joint","param","value"),&PhysicsServer::cone_twist_joint_set_param); - ClassDB::bind_method(D_METHOD("cone_twist_joint_get_param","joint","param"),&PhysicsServer::cone_twist_joint_get_param); - - BIND_CONSTANT( CONE_TWIST_JOINT_SWING_SPAN ); - BIND_CONSTANT( CONE_TWIST_JOINT_TWIST_SPAN ); - BIND_CONSTANT( CONE_TWIST_JOINT_BIAS ); - BIND_CONSTANT( CONE_TWIST_JOINT_SOFTNESS ); - BIND_CONSTANT( CONE_TWIST_JOINT_RELAXATION ); - - - BIND_CONSTANT( G6DOF_JOINT_LINEAR_LOWER_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_LINEAR_UPPER_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS ); - BIND_CONSTANT( G6DOF_JOINT_LINEAR_RESTITUTION ); - BIND_CONSTANT( G6DOF_JOINT_LINEAR_DAMPING ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_LOWER_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_UPPER_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_DAMPING ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_RESTITUTION ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_FORCE_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_ERP ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY ); - BIND_CONSTANT( G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT ); - - - BIND_CONSTANT( G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT ); - BIND_CONSTANT( G6DOF_JOINT_FLAG_ENABLE_MOTOR ); - - ClassDB::bind_method(D_METHOD("joint_get_type","joint"),&PhysicsServer::joint_get_type); - - ClassDB::bind_method(D_METHOD("joint_set_solver_priority","joint","priority"),&PhysicsServer::joint_set_solver_priority); - ClassDB::bind_method(D_METHOD("joint_get_solver_priority","joint"),&PhysicsServer::joint_get_solver_priority); - - ClassDB::bind_method(D_METHOD("joint_create_generic_6dof","body_A","local_ref_A","body_B","local_ref_B"),&PhysicsServer::joint_create_generic_6dof); - - ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_param","joint","axis","param","value"),&PhysicsServer::generic_6dof_joint_set_param); - ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_param","joint","axis","param"),&PhysicsServer::generic_6dof_joint_get_param); - - ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_flag","joint","axis","flag","enable"),&PhysicsServer::generic_6dof_joint_set_flag); - ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_flag","joint","axis","flag"),&PhysicsServer::generic_6dof_joint_get_flag); - - -/* + ClassDB::bind_method(D_METHOD("joint_create_hinge", "body_A", "hinge_A", "body_B", "hinge_B"), &PhysicsServer::joint_create_hinge); + + ClassDB::bind_method(D_METHOD("hinge_joint_set_param", "joint", "param", "value"), &PhysicsServer::hinge_joint_set_param); + ClassDB::bind_method(D_METHOD("hinge_joint_get_param", "joint", "param"), &PhysicsServer::hinge_joint_get_param); + + ClassDB::bind_method(D_METHOD("hinge_joint_set_flag", "joint", "flag", "enabled"), &PhysicsServer::hinge_joint_set_flag); + ClassDB::bind_method(D_METHOD("hinge_joint_get_flag", "joint", "flag"), &PhysicsServer::hinge_joint_get_flag); + + ClassDB::bind_method(D_METHOD("joint_create_slider", "body_A", "local_ref_A", "body_B", "local_ref_B"), &PhysicsServer::joint_create_slider); + + ClassDB::bind_method(D_METHOD("slider_joint_set_param", "joint", "param", "value"), &PhysicsServer::slider_joint_set_param); + ClassDB::bind_method(D_METHOD("slider_joint_get_param", "joint", "param"), &PhysicsServer::slider_joint_get_param); + + BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_UPPER); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_LOWER); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_DAMPING); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_MOTION_SOFTNESS); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_MOTION_RESTITUTION); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_MOTION_DAMPING); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION); + BIND_CONSTANT(SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING); + + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_UPPER); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_LOWER); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_DAMPING); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_MOTION_DAMPING); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION); + BIND_CONSTANT(SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING); + BIND_CONSTANT(SLIDER_JOINT_MAX); + + ClassDB::bind_method(D_METHOD("joint_create_cone_twist", "body_A", "local_ref_A", "body_B", "local_ref_B"), &PhysicsServer::joint_create_cone_twist); + + ClassDB::bind_method(D_METHOD("cone_twist_joint_set_param", "joint", "param", "value"), &PhysicsServer::cone_twist_joint_set_param); + ClassDB::bind_method(D_METHOD("cone_twist_joint_get_param", "joint", "param"), &PhysicsServer::cone_twist_joint_get_param); + + BIND_CONSTANT(CONE_TWIST_JOINT_SWING_SPAN); + BIND_CONSTANT(CONE_TWIST_JOINT_TWIST_SPAN); + BIND_CONSTANT(CONE_TWIST_JOINT_BIAS); + BIND_CONSTANT(CONE_TWIST_JOINT_SOFTNESS); + BIND_CONSTANT(CONE_TWIST_JOINT_RELAXATION); + + BIND_CONSTANT(G6DOF_JOINT_LINEAR_LOWER_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_LINEAR_UPPER_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS); + BIND_CONSTANT(G6DOF_JOINT_LINEAR_RESTITUTION); + BIND_CONSTANT(G6DOF_JOINT_LINEAR_DAMPING); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_LOWER_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_UPPER_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_DAMPING); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_RESTITUTION); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_FORCE_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_ERP); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY); + BIND_CONSTANT(G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT); + + BIND_CONSTANT(G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT); + BIND_CONSTANT(G6DOF_JOINT_FLAG_ENABLE_MOTOR); + + ClassDB::bind_method(D_METHOD("joint_get_type", "joint"), &PhysicsServer::joint_get_type); + + ClassDB::bind_method(D_METHOD("joint_set_solver_priority", "joint", "priority"), &PhysicsServer::joint_set_solver_priority); + ClassDB::bind_method(D_METHOD("joint_get_solver_priority", "joint"), &PhysicsServer::joint_get_solver_priority); + + ClassDB::bind_method(D_METHOD("joint_create_generic_6dof", "body_A", "local_ref_A", "body_B", "local_ref_B"), &PhysicsServer::joint_create_generic_6dof); + + ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_param", "joint", "axis", "param", "value"), &PhysicsServer::generic_6dof_joint_set_param); + ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_param", "joint", "axis", "param"), &PhysicsServer::generic_6dof_joint_get_param); + + ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_flag", "joint", "axis", "flag", "enable"), &PhysicsServer::generic_6dof_joint_set_flag); + ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_flag", "joint", "axis", "flag"), &PhysicsServer::generic_6dof_joint_get_flag); + + /* ClassDB::bind_method(D_METHOD("joint_set_param","joint","param","value"),&PhysicsServer::joint_set_param); ClassDB::bind_method(D_METHOD("joint_get_param","joint","param"),&PhysicsServer::joint_get_param); @@ -674,63 +630,61 @@ void PhysicsServer::_bind_methods() { ClassDB::bind_method(D_METHOD("joint_get_type","joint"),&PhysicsServer::joint_get_type); */ - ClassDB::bind_method(D_METHOD("free_rid","rid"),&PhysicsServer::free); + ClassDB::bind_method(D_METHOD("free_rid", "rid"), &PhysicsServer::free); - ClassDB::bind_method(D_METHOD("set_active","active"),&PhysicsServer::set_active); + ClassDB::bind_method(D_METHOD("set_active", "active"), &PhysicsServer::set_active); //ClassDB::bind_method(D_METHOD("init"),&PhysicsServer::init); //ClassDB::bind_method(D_METHOD("step"),&PhysicsServer::step); //ClassDB::bind_method(D_METHOD("sync"),&PhysicsServer::sync); //ClassDB::bind_method(D_METHOD("flush_queries"),&PhysicsServer::flush_queries); - - ClassDB::bind_method(D_METHOD("get_process_info","process_info"),&PhysicsServer::get_process_info); - - BIND_CONSTANT( SHAPE_PLANE ); - BIND_CONSTANT( SHAPE_RAY ); - BIND_CONSTANT( SHAPE_SPHERE ); - BIND_CONSTANT( SHAPE_BOX ); - BIND_CONSTANT( SHAPE_CAPSULE ); - BIND_CONSTANT( SHAPE_CONVEX_POLYGON ); - BIND_CONSTANT( SHAPE_CONCAVE_POLYGON ); - BIND_CONSTANT( SHAPE_HEIGHTMAP ); - BIND_CONSTANT( SHAPE_CUSTOM ); - - - BIND_CONSTANT( AREA_PARAM_GRAVITY ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_VECTOR ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_IS_POINT ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_DISTANCE_SCALE ); - BIND_CONSTANT( AREA_PARAM_GRAVITY_POINT_ATTENUATION ); - BIND_CONSTANT( AREA_PARAM_LINEAR_DAMP ); - BIND_CONSTANT( AREA_PARAM_ANGULAR_DAMP ); - BIND_CONSTANT( AREA_PARAM_PRIORITY ); - - BIND_CONSTANT( AREA_SPACE_OVERRIDE_DISABLED ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE_REPLACE ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE ); - BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE_COMBINE ); - - BIND_CONSTANT( BODY_MODE_STATIC ); - BIND_CONSTANT( BODY_MODE_KINEMATIC ); - BIND_CONSTANT( BODY_MODE_RIGID ); - BIND_CONSTANT( BODY_MODE_CHARACTER ); - - BIND_CONSTANT( BODY_PARAM_BOUNCE ); - BIND_CONSTANT( BODY_PARAM_FRICTION ); - BIND_CONSTANT( BODY_PARAM_MASS ); - BIND_CONSTANT( BODY_PARAM_GRAVITY_SCALE ); - BIND_CONSTANT( BODY_PARAM_ANGULAR_DAMP ); - BIND_CONSTANT( BODY_PARAM_LINEAR_DAMP ); - BIND_CONSTANT( BODY_PARAM_MAX ); - - BIND_CONSTANT( BODY_STATE_TRANSFORM ); - BIND_CONSTANT( BODY_STATE_LINEAR_VELOCITY ); - BIND_CONSTANT( BODY_STATE_ANGULAR_VELOCITY ); - BIND_CONSTANT( BODY_STATE_SLEEPING ); - BIND_CONSTANT( BODY_STATE_CAN_SLEEP ); -/* + ClassDB::bind_method(D_METHOD("get_process_info", "process_info"), &PhysicsServer::get_process_info); + + BIND_CONSTANT(SHAPE_PLANE); + BIND_CONSTANT(SHAPE_RAY); + BIND_CONSTANT(SHAPE_SPHERE); + BIND_CONSTANT(SHAPE_BOX); + BIND_CONSTANT(SHAPE_CAPSULE); + BIND_CONSTANT(SHAPE_CONVEX_POLYGON); + BIND_CONSTANT(SHAPE_CONCAVE_POLYGON); + BIND_CONSTANT(SHAPE_HEIGHTMAP); + BIND_CONSTANT(SHAPE_CUSTOM); + + BIND_CONSTANT(AREA_PARAM_GRAVITY); + BIND_CONSTANT(AREA_PARAM_GRAVITY_VECTOR); + BIND_CONSTANT(AREA_PARAM_GRAVITY_IS_POINT); + BIND_CONSTANT(AREA_PARAM_GRAVITY_DISTANCE_SCALE); + BIND_CONSTANT(AREA_PARAM_GRAVITY_POINT_ATTENUATION); + BIND_CONSTANT(AREA_PARAM_LINEAR_DAMP); + BIND_CONSTANT(AREA_PARAM_ANGULAR_DAMP); + BIND_CONSTANT(AREA_PARAM_PRIORITY); + + BIND_CONSTANT(AREA_SPACE_OVERRIDE_DISABLED); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE_REPLACE); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE); + BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE_COMBINE); + + BIND_CONSTANT(BODY_MODE_STATIC); + BIND_CONSTANT(BODY_MODE_KINEMATIC); + BIND_CONSTANT(BODY_MODE_RIGID); + BIND_CONSTANT(BODY_MODE_CHARACTER); + + BIND_CONSTANT(BODY_PARAM_BOUNCE); + BIND_CONSTANT(BODY_PARAM_FRICTION); + BIND_CONSTANT(BODY_PARAM_MASS); + BIND_CONSTANT(BODY_PARAM_GRAVITY_SCALE); + BIND_CONSTANT(BODY_PARAM_ANGULAR_DAMP); + BIND_CONSTANT(BODY_PARAM_LINEAR_DAMP); + BIND_CONSTANT(BODY_PARAM_MAX); + + BIND_CONSTANT(BODY_STATE_TRANSFORM); + BIND_CONSTANT(BODY_STATE_LINEAR_VELOCITY); + BIND_CONSTANT(BODY_STATE_ANGULAR_VELOCITY); + BIND_CONSTANT(BODY_STATE_SLEEPING); + BIND_CONSTANT(BODY_STATE_CAN_SLEEP); + /* BIND_CONSTANT( JOINT_PIN ); BIND_CONSTANT( JOINT_GROOVE ); BIND_CONSTANT( JOINT_DAMPED_SPRING ); @@ -742,26 +696,21 @@ void PhysicsServer::_bind_methods() { //BIND_CONSTANT( TYPE_BODY ); //BIND_CONSTANT( TYPE_AREA ); - BIND_CONSTANT( AREA_BODY_ADDED ); - BIND_CONSTANT( AREA_BODY_REMOVED ); - - BIND_CONSTANT( INFO_ACTIVE_OBJECTS ); - BIND_CONSTANT( INFO_COLLISION_PAIRS ); - BIND_CONSTANT( INFO_ISLAND_COUNT ); - - + BIND_CONSTANT(AREA_BODY_ADDED); + BIND_CONSTANT(AREA_BODY_REMOVED); + BIND_CONSTANT(INFO_ACTIVE_OBJECTS); + BIND_CONSTANT(INFO_COLLISION_PAIRS); + BIND_CONSTANT(INFO_ISLAND_COUNT); } - PhysicsServer::PhysicsServer() { - ERR_FAIL_COND( singleton!=NULL ); - singleton=this; + ERR_FAIL_COND(singleton != NULL); + singleton = this; } PhysicsServer::~PhysicsServer() { - singleton=NULL; + singleton = NULL; } - diff --git a/servers/physics_server.h b/servers/physics_server.h index 653959be45..dbd0c79f06 100644 --- a/servers/physics_server.h +++ b/servers/physics_server.h @@ -36,81 +36,81 @@ class PhysicsDirectSpaceState; class PhysicsDirectBodyState : public Object { - GDCLASS( PhysicsDirectBodyState, Object ); + GDCLASS(PhysicsDirectBodyState, Object); + protected: static void _bind_methods(); -public: - virtual Vector3 get_total_gravity() const=0; - virtual float get_total_angular_damp() const=0; - virtual float get_total_linear_damp() const=0; +public: + virtual Vector3 get_total_gravity() const = 0; + virtual float get_total_angular_damp() const = 0; + virtual float get_total_linear_damp() const = 0; - virtual Vector3 get_center_of_mass() const=0; - virtual Basis get_principal_inertia_axes() const=0; - virtual float get_inverse_mass() const=0; // get the mass - virtual Vector3 get_inverse_inertia() const=0; // get density of this body space - virtual Basis get_inverse_inertia_tensor() const=0; // get density of this body space + virtual Vector3 get_center_of_mass() const = 0; + virtual Basis get_principal_inertia_axes() const = 0; + virtual float get_inverse_mass() const = 0; // get the mass + virtual Vector3 get_inverse_inertia() const = 0; // get density of this body space + virtual Basis get_inverse_inertia_tensor() const = 0; // get density of this body space - virtual void set_linear_velocity(const Vector3& p_velocity)=0; - virtual Vector3 get_linear_velocity() const=0; + virtual void set_linear_velocity(const Vector3 &p_velocity) = 0; + virtual Vector3 get_linear_velocity() const = 0; - virtual void set_angular_velocity(const Vector3& p_velocity)=0; - virtual Vector3 get_angular_velocity() const=0; + virtual void set_angular_velocity(const Vector3 &p_velocity) = 0; + virtual Vector3 get_angular_velocity() const = 0; - virtual void set_transform(const Transform& p_transform)=0; - virtual Transform get_transform() const=0; + virtual void set_transform(const Transform &p_transform) = 0; + virtual Transform get_transform() const = 0; - virtual void add_force(const Vector3& p_force, const Vector3& p_pos)=0; - virtual void apply_impulse(const Vector3& p_pos, const Vector3& p_j)=0; - virtual void apply_torque_impulse(const Vector3& p_j)=0; + virtual void add_force(const Vector3 &p_force, const Vector3 &p_pos) = 0; + virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) = 0; + virtual void apply_torque_impulse(const Vector3 &p_j) = 0; - virtual void set_sleep_state(bool p_enable)=0; - virtual bool is_sleeping() const=0; + virtual void set_sleep_state(bool p_enable) = 0; + virtual bool is_sleeping() const = 0; - virtual int get_contact_count() const=0; + virtual int get_contact_count() const = 0; - virtual Vector3 get_contact_local_pos(int p_contact_idx) const=0; - virtual Vector3 get_contact_local_normal(int p_contact_idx) const=0; - virtual int get_contact_local_shape(int p_contact_idx) const=0; + virtual Vector3 get_contact_local_pos(int p_contact_idx) const = 0; + virtual Vector3 get_contact_local_normal(int p_contact_idx) const = 0; + virtual int get_contact_local_shape(int p_contact_idx) const = 0; - virtual RID get_contact_collider(int p_contact_idx) const=0; - virtual Vector3 get_contact_collider_pos(int p_contact_idx) const=0; - virtual ObjectID get_contact_collider_id(int p_contact_idx) const=0; - virtual Object* get_contact_collider_object(int p_contact_idx) const; - virtual int get_contact_collider_shape(int p_contact_idx) const=0; - virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const=0; + virtual RID get_contact_collider(int p_contact_idx) const = 0; + virtual Vector3 get_contact_collider_pos(int p_contact_idx) const = 0; + virtual ObjectID get_contact_collider_id(int p_contact_idx) const = 0; + virtual Object *get_contact_collider_object(int p_contact_idx) const; + virtual int get_contact_collider_shape(int p_contact_idx) const = 0; + virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const = 0; - virtual real_t get_step() const=0; + virtual real_t get_step() const = 0; virtual void integrate_forces(); - virtual PhysicsDirectSpaceState* get_space_state()=0; + virtual PhysicsDirectSpaceState *get_space_state() = 0; PhysicsDirectBodyState(); }; - class PhysicsShapeQueryResult; class PhysicsShapeQueryParameters : public Reference { GDCLASS(PhysicsShapeQueryParameters, Reference); -friend class PhysicsDirectSpaceState; + friend class PhysicsDirectSpaceState; RID shape; Transform transform; float margin; Set<RID> exclude; uint32_t layer_mask; uint32_t object_type_mask; + protected: static void _bind_methods(); -public: - - void set_shape(const RES& p_shape); - void set_shape_rid(const RID& p_shape); +public: + void set_shape(const RES &p_shape); + void set_shape_rid(const RID &p_shape); RID get_shape_rid() const; - void set_transform(const Transform& p_transform); + void set_transform(const Transform &p_transform); Transform get_transform() const; void set_margin(float p_margin); @@ -122,47 +122,39 @@ public: void set_object_type_mask(int p_object_type_mask); int get_object_type_mask() const; - void set_exclude(const Vector<RID>& p_exclude); + void set_exclude(const Vector<RID> &p_exclude); Vector<RID> get_exclude() const; PhysicsShapeQueryParameters(); - }; - - class PhysicsDirectSpaceState : public Object { - GDCLASS( PhysicsDirectSpaceState, Object ); + GDCLASS(PhysicsDirectSpaceState, Object); //Variant _intersect_ray(const Vector3& p_from, const Vector3& p_to,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_collision_mask=0); //Variant _intersect_shape(const RID& p_shape, const Transform& p_xform,int p_result_max=64,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_collision_mask=0); public: - enum ObjectTypeMask { - TYPE_MASK_STATIC_BODY=1<<0, - TYPE_MASK_KINEMATIC_BODY=1<<1, - TYPE_MASK_RIGID_BODY=1<<2, - TYPE_MASK_CHARACTER_BODY=1<<3, - TYPE_MASK_AREA=1<<4, - TYPE_MASK_COLLISION=TYPE_MASK_STATIC_BODY|TYPE_MASK_CHARACTER_BODY|TYPE_MASK_KINEMATIC_BODY|TYPE_MASK_RIGID_BODY + TYPE_MASK_STATIC_BODY = 1 << 0, + TYPE_MASK_KINEMATIC_BODY = 1 << 1, + TYPE_MASK_RIGID_BODY = 1 << 2, + TYPE_MASK_CHARACTER_BODY = 1 << 3, + TYPE_MASK_AREA = 1 << 4, + TYPE_MASK_COLLISION = TYPE_MASK_STATIC_BODY | TYPE_MASK_CHARACTER_BODY | TYPE_MASK_KINEMATIC_BODY | TYPE_MASK_RIGID_BODY }; - private: - Dictionary _intersect_ray(const Vector3& p_from, const Vector3& p_to,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_layers=0,uint32_t p_object_type_mask=TYPE_MASK_COLLISION); - Array _intersect_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query,int p_max_results=32); - Array _cast_motion(const Ref<PhysicsShapeQueryParameters> &p_shape_query,const Vector3& p_motion); - Array _collide_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query,int p_max_results=32); + Dictionary _intersect_ray(const Vector3 &p_from, const Vector3 &p_to, const Vector<RID> &p_exclude = Vector<RID>(), uint32_t p_layers = 0, uint32_t p_object_type_mask = TYPE_MASK_COLLISION); + Array _intersect_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query, int p_max_results = 32); + Array _cast_motion(const Ref<PhysicsShapeQueryParameters> &p_shape_query, const Vector3 &p_motion); + Array _collide_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query, int p_max_results = 32); Dictionary _get_rest_info(const Ref<PhysicsShapeQueryParameters> &p_shape_query); - protected: static void _bind_methods(); public: - - struct RayResult { Vector3 position; @@ -173,7 +165,7 @@ public: int shape; }; - virtual bool intersect_ray(const Vector3& p_from, const Vector3& p_to,RayResult &r_result,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,bool p_pick_ray=false)=0; + virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_ray = false) = 0; struct ShapeResult { @@ -181,10 +173,9 @@ public: ObjectID collider_id; Object *collider; int shape; - }; - virtual int intersect_shape(const RID& p_shape, const Transform& p_xform,float p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; struct ShapeRestInfo { @@ -194,55 +185,49 @@ public: ObjectID collider_id; int shape; Vector3 linear_velocity; //velocity at contact point - }; - virtual bool cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,float p_margin,float &p_closest_safe,float &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,ShapeRestInfo *r_info=NULL)=0; - - virtual bool collide_shape(RID p_shape, const Transform& p_shape_xform,float p_margin,Vector3 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &p_closest_safe, float &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, ShapeRestInfo *r_info = NULL) = 0; - virtual bool rest_info(RID p_shape, const Transform& p_shape_xform,float p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0; + virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; + virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0; PhysicsDirectSpaceState(); }; - class PhysicsShapeQueryResult : public Reference { - GDCLASS( PhysicsShapeQueryResult, Reference ); + GDCLASS(PhysicsShapeQueryResult, Reference); Vector<PhysicsDirectSpaceState::ShapeResult> result; -friend class PhysicsDirectSpaceState; + friend class PhysicsDirectSpaceState; protected: static void _bind_methods(); -public: +public: int get_result_count() const; RID get_result_rid(int p_idx) const; ObjectID get_result_object_id(int p_idx) const; - Object* get_result_object(int p_idx) const; + Object *get_result_object(int p_idx) const; int get_result_object_shape(int p_idx) const; PhysicsShapeQueryResult(); }; - class PhysicsServer : public Object { - GDCLASS( PhysicsServer, Object ); - - static PhysicsServer * singleton; + GDCLASS(PhysicsServer, Object); + static PhysicsServer *singleton; protected: static void _bind_methods(); public: - - static PhysicsServer * get_singleton(); + static PhysicsServer *get_singleton(); enum ShapeType { SHAPE_PLANE, ///< plane:"plane" @@ -256,20 +241,19 @@ public: SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_create() with this value will result in an error }; - virtual RID shape_create(ShapeType p_shape)=0; - virtual void shape_set_data(RID p_shape, const Variant& p_data)=0; - virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias)=0; - - virtual ShapeType shape_get_type(RID p_shape) const=0; - virtual Variant shape_get_data(RID p_shape) const=0; - virtual real_t shape_get_custom_solver_bias(RID p_shape) const=0; + virtual RID shape_create(ShapeType p_shape) = 0; + virtual void shape_set_data(RID p_shape, const Variant &p_data) = 0; + virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias) = 0; + virtual ShapeType shape_get_type(RID p_shape) const = 0; + virtual Variant shape_get_data(RID p_shape) const = 0; + virtual real_t shape_get_custom_solver_bias(RID p_shape) const = 0; /* SPACE API */ - virtual RID space_create()=0; - virtual void space_set_active(RID p_space,bool p_active)=0; - virtual bool space_is_active(RID p_space) const=0; + virtual RID space_create() = 0; + virtual void space_set_active(RID p_space, bool p_active) = 0; + virtual bool space_is_active(RID p_space) const = 0; enum SpaceParameter { @@ -283,15 +267,15 @@ public: SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS, }; - virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value)=0; - virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const=0; + virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) = 0; + virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const = 0; // this function only works on fixed process, errors and returns null otherwise - virtual PhysicsDirectSpaceState* space_get_direct_state(RID p_space)=0; + virtual PhysicsDirectSpaceState *space_get_direct_state(RID p_space) = 0; - virtual void space_set_debug_contacts(RID p_space,int p_max_contacts)=0; - virtual Vector<Vector3> space_get_contacts(RID p_space) const=0; - virtual int space_get_contact_count(RID p_space) const=0; + virtual void space_set_debug_contacts(RID p_space, int p_max_contacts) = 0; + virtual Vector<Vector3> space_get_contacts(RID p_space) const = 0; + virtual int space_get_contact_count(RID p_space) const = 0; //missing space parameters @@ -299,8 +283,6 @@ public: //missing attenuation? missing better override? - - enum AreaParameter { AREA_PARAM_GRAVITY, AREA_PARAM_GRAVITY_VECTOR, @@ -312,11 +294,10 @@ public: AREA_PARAM_PRIORITY }; - virtual RID area_create()=0; - - virtual void area_set_space(RID p_area, RID p_space)=0; - virtual RID area_get_space(RID p_area) const=0; + virtual RID area_create() = 0; + virtual void area_set_space(RID p_area, RID p_space) = 0; + virtual RID area_get_space(RID p_area) const = 0; enum AreaSpaceOverrideMode { AREA_SPACE_OVERRIDE_DISABLED, @@ -326,39 +307,39 @@ public: AREA_SPACE_OVERRIDE_REPLACE_COMBINE }; - virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode)=0; - virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const=0; + virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) = 0; + virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const = 0; - virtual void area_add_shape(RID p_area, RID p_shape, const Transform& p_transform=Transform())=0; - virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape)=0; - virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform& p_transform)=0; + virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform()) = 0; + virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) = 0; + virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) = 0; - virtual int area_get_shape_count(RID p_area) const=0; - virtual RID area_get_shape(RID p_area, int p_shape_idx) const=0; - virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const=0; + virtual int area_get_shape_count(RID p_area) const = 0; + virtual RID area_get_shape(RID p_area, int p_shape_idx) const = 0; + virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const = 0; - virtual void area_remove_shape(RID p_area, int p_shape_idx)=0; - virtual void area_clear_shapes(RID p_area)=0; + virtual void area_remove_shape(RID p_area, int p_shape_idx) = 0; + virtual void area_clear_shapes(RID p_area) = 0; - virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID)=0; - virtual ObjectID area_get_object_instance_ID(RID p_area) const=0; + virtual void area_attach_object_instance_ID(RID p_area, ObjectID p_ID) = 0; + virtual ObjectID area_get_object_instance_ID(RID p_area) const = 0; - virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value)=0; - virtual void area_set_transform(RID p_area, const Transform& p_transform)=0; + virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) = 0; + virtual void area_set_transform(RID p_area, const Transform &p_transform) = 0; - virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const=0; - virtual Transform area_get_transform(RID p_area) const=0; + virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const = 0; + virtual Transform area_get_transform(RID p_area) const = 0; - virtual void area_set_collision_mask(RID p_area,uint32_t p_mask)=0; - virtual void area_set_layer_mask(RID p_area,uint32_t p_mask)=0; + virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) = 0; + virtual void area_set_layer_mask(RID p_area, uint32_t p_mask) = 0; - virtual void area_set_monitorable(RID p_area,bool p_monitorable)=0; + virtual void area_set_monitorable(RID p_area, bool p_monitorable) = 0; - virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0; - virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0; + virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0; + virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0; - virtual void area_set_ray_pickable(RID p_area,bool p_enable)=0; - virtual bool area_is_ray_pickable(RID p_area) const=0; + virtual void area_set_ray_pickable(RID p_area, bool p_enable) = 0; + virtual bool area_is_ray_pickable(RID p_area) const = 0; /* BODY API */ @@ -372,42 +353,42 @@ public: BODY_MODE_CHARACTER }; - virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false)=0; + virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false) = 0; - virtual void body_set_space(RID p_body, RID p_space)=0; - virtual RID body_get_space(RID p_body) const=0; + virtual void body_set_space(RID p_body, RID p_space) = 0; + virtual RID body_get_space(RID p_body) const = 0; - virtual void body_set_mode(RID p_body, BodyMode p_mode)=0; - virtual BodyMode body_get_mode(RID p_body) const=0; + virtual void body_set_mode(RID p_body, BodyMode p_mode) = 0; + virtual BodyMode body_get_mode(RID p_body) const = 0; - virtual void body_add_shape(RID p_body, RID p_shape, const Transform& p_transform=Transform())=0; - virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape)=0; - virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform& p_transform)=0; + virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform()) = 0; + virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) = 0; + virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) = 0; - virtual int body_get_shape_count(RID p_body) const=0; - virtual RID body_get_shape(RID p_body, int p_shape_idx) const=0; - virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const=0; + virtual int body_get_shape_count(RID p_body) const = 0; + virtual RID body_get_shape(RID p_body, int p_shape_idx) const = 0; + virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const = 0; - virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable)=0; - virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const=0; + virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) = 0; + virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const = 0; - virtual void body_remove_shape(RID p_body, int p_shape_idx)=0; - virtual void body_clear_shapes(RID p_body)=0; + virtual void body_remove_shape(RID p_body, int p_shape_idx) = 0; + virtual void body_clear_shapes(RID p_body) = 0; - virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID)=0; - virtual uint32_t body_get_object_instance_ID(RID p_body) const=0; + virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID) = 0; + virtual uint32_t body_get_object_instance_ID(RID p_body) const = 0; - virtual void body_set_enable_continuous_collision_detection(RID p_body,bool p_enable)=0; - virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const=0; + virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) = 0; + virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const = 0; - virtual void body_set_layer_mask(RID p_body, uint32_t p_mask)=0; - virtual uint32_t body_get_layer_mask(RID p_body, uint32_t p_mask) const=0; + virtual void body_set_layer_mask(RID p_body, uint32_t p_mask) = 0; + virtual uint32_t body_get_layer_mask(RID p_body, uint32_t p_mask) const = 0; - virtual void body_set_collision_mask(RID p_body, uint32_t p_mask)=0; - virtual uint32_t body_get_collision_mask(RID p_body, uint32_t p_mask) const=0; + virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) = 0; + virtual uint32_t body_get_collision_mask(RID p_body, uint32_t p_mask) const = 0; - virtual void body_set_user_flags(RID p_body, uint32_t p_flags)=0; - virtual uint32_t body_get_user_flags(RID p_body, uint32_t p_flags) const=0; + virtual void body_set_user_flags(RID p_body, uint32_t p_flags) = 0; + virtual uint32_t body_get_user_flags(RID p_body, uint32_t p_flags) const = 0; // common body variables enum BodyParameter { @@ -420,9 +401,8 @@ public: BODY_PARAM_MAX, }; - virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value)=0; - virtual float body_get_param(RID p_body, BodyParameter p_param) const=0; - + virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) = 0; + virtual float body_get_param(RID p_body, BodyParameter p_param) const = 0; //state enum BodyState { @@ -433,19 +413,19 @@ public: BODY_STATE_CAN_SLEEP }; - virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant)=0; - virtual Variant body_get_state(RID p_body, BodyState p_state) const=0; + virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) = 0; + virtual Variant body_get_state(RID p_body, BodyState p_state) const = 0; //do something about it - virtual void body_set_applied_force(RID p_body, const Vector3& p_force)=0; - virtual Vector3 body_get_applied_force(RID p_body) const=0; + virtual void body_set_applied_force(RID p_body, const Vector3 &p_force) = 0; + virtual Vector3 body_get_applied_force(RID p_body) const = 0; - virtual void body_set_applied_torque(RID p_body, const Vector3& p_torque)=0; - virtual Vector3 body_get_applied_torque(RID p_body) const=0; + virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque) = 0; + virtual Vector3 body_get_applied_torque(RID p_body) const = 0; - virtual void body_apply_impulse(RID p_body, const Vector3& p_pos, const Vector3& p_impulse)=0; - virtual void body_apply_torque_impulse(RID p_body, const Vector3& p_impulse)=0; - virtual void body_set_axis_velocity(RID p_body, const Vector3& p_axis_velocity)=0; + virtual void body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse) = 0; + virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) = 0; + virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) = 0; enum BodyAxisLock { BODY_AXIS_LOCK_DISABLED, @@ -454,29 +434,28 @@ public: BODY_AXIS_LOCK_Z, }; - virtual void body_set_axis_lock(RID p_body,BodyAxisLock p_lock)=0; - virtual BodyAxisLock body_get_axis_lock(RID p_body) const=0; + virtual void body_set_axis_lock(RID p_body, BodyAxisLock p_lock) = 0; + virtual BodyAxisLock body_get_axis_lock(RID p_body) const = 0; //fix - virtual void body_add_collision_exception(RID p_body, RID p_body_b)=0; - virtual void body_remove_collision_exception(RID p_body, RID p_body_b)=0; - virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0; + virtual void body_add_collision_exception(RID p_body, RID p_body_b) = 0; + virtual void body_remove_collision_exception(RID p_body, RID p_body_b) = 0; + virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) = 0; - virtual void body_set_max_contacts_reported(RID p_body, int p_contacts)=0; - virtual int body_get_max_contacts_reported(RID p_body) const=0; + virtual void body_set_max_contacts_reported(RID p_body, int p_contacts) = 0; + virtual int body_get_max_contacts_reported(RID p_body) const = 0; //missing remove - virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold)=0; - virtual float body_get_contacts_reported_depth_treshold(RID p_body) const=0; - - virtual void body_set_omit_force_integration(RID p_body,bool p_omit)=0; - virtual bool body_is_omitting_force_integration(RID p_body) const=0; + virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold) = 0; + virtual float body_get_contacts_reported_depth_treshold(RID p_body) const = 0; - virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant())=0; + virtual void body_set_omit_force_integration(RID p_body, bool p_omit) = 0; + virtual bool body_is_omitting_force_integration(RID p_body) const = 0; - virtual void body_set_ray_pickable(RID p_body,bool p_enable)=0; - virtual bool body_is_ray_pickable(RID p_body) const=0; + virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()) = 0; + virtual void body_set_ray_pickable(RID p_body, bool p_enable) = 0; + virtual bool body_is_ray_pickable(RID p_body) const = 0; /* JOINT API */ @@ -490,13 +469,12 @@ public: }; - virtual JointType joint_get_type(RID p_joint) const=0; - - virtual void joint_set_solver_priority(RID p_joint,int p_priority)=0; - virtual int joint_get_solver_priority(RID p_joint) const=0; + virtual JointType joint_get_type(RID p_joint) const = 0; + virtual void joint_set_solver_priority(RID p_joint, int p_priority) = 0; + virtual int joint_get_solver_priority(RID p_joint) const = 0; - virtual RID joint_create_pin(RID p_body_A,const Vector3& p_local_A,RID p_body_B,const Vector3& p_local_B)=0; + virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) = 0; enum PinJointParam { PIN_JOINT_BIAS, @@ -504,14 +482,14 @@ public: PIN_JOINT_IMPULSE_CLAMP }; - virtual void pin_joint_set_param(RID p_joint,PinJointParam p_param, float p_value)=0; - virtual float pin_joint_get_param(RID p_joint,PinJointParam p_param) const=0; + virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, float p_value) = 0; + virtual float pin_joint_get_param(RID p_joint, PinJointParam p_param) const = 0; - virtual void pin_joint_set_local_A(RID p_joint, const Vector3& p_A)=0; - virtual Vector3 pin_joint_get_local_A(RID p_joint) const=0; + virtual void pin_joint_set_local_A(RID p_joint, const Vector3 &p_A) = 0; + virtual Vector3 pin_joint_get_local_A(RID p_joint) const = 0; - virtual void pin_joint_set_local_B(RID p_joint, const Vector3& p_B)=0; - virtual Vector3 pin_joint_get_local_B(RID p_joint) const=0; + virtual void pin_joint_set_local_B(RID p_joint, const Vector3 &p_B) = 0; + virtual Vector3 pin_joint_get_local_B(RID p_joint) const = 0; enum HingeJointParam { @@ -532,15 +510,14 @@ public: HINGE_JOINT_FLAG_MAX }; - virtual RID joint_create_hinge(RID p_body_A,const Transform& p_hinge_A,RID p_body_B,const Transform& p_hinge_B)=0; - virtual RID joint_create_hinge_simple(RID p_body_A,const Vector3& p_pivot_A,const Vector3& p_axis_A,RID p_body_B,const Vector3& p_pivot_B,const Vector3& p_axis_B)=0; - + virtual RID joint_create_hinge(RID p_body_A, const Transform &p_hinge_A, RID p_body_B, const Transform &p_hinge_B) = 0; + virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B) = 0; - virtual void hinge_joint_set_param(RID p_joint,HingeJointParam p_param, float p_value)=0; - virtual float hinge_joint_get_param(RID p_joint,HingeJointParam p_param) const=0; + virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, float p_value) = 0; + virtual float hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const = 0; - virtual void hinge_joint_set_flag(RID p_joint,HingeJointFlag p_flag, bool p_value)=0; - virtual bool hinge_joint_get_flag(RID p_joint,HingeJointFlag p_flag) const=0; + virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) = 0; + virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const = 0; enum SliderJointParam { SLIDER_JOINT_LINEAR_LIMIT_UPPER, @@ -568,13 +545,12 @@ public: SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING, SLIDER_JOINT_MAX - }; - virtual RID joint_create_slider(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B)=0; //reference frame is A + virtual RID joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) = 0; //reference frame is A - virtual void slider_joint_set_param(RID p_joint,SliderJointParam p_param, float p_value)=0; - virtual float slider_joint_get_param(RID p_joint,SliderJointParam p_param) const=0; + virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, float p_value) = 0; + virtual float slider_joint_get_param(RID p_joint, SliderJointParam p_param) const = 0; enum ConeTwistJointParam { CONE_TWIST_JOINT_SWING_SPAN, @@ -585,12 +561,10 @@ public: CONE_TWIST_MAX }; + virtual RID joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) = 0; //reference frame is A - virtual RID joint_create_cone_twist(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B)=0; //reference frame is A - - virtual void cone_twist_joint_set_param(RID p_joint,ConeTwistJointParam p_param, float p_value)=0; - virtual float cone_twist_joint_get_param(RID p_joint,ConeTwistJointParam p_param) const=0; - + virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, float p_value) = 0; + virtual float cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const = 0; enum G6DOFJointAxisParam { G6DOF_JOINT_LINEAR_LOWER_LIMIT, @@ -618,16 +592,13 @@ public: G6DOF_JOINT_FLAG_MAX }; + virtual RID joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) = 0; //reference frame is A + virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param, float p_value) = 0; + virtual float generic_6dof_joint_get_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param) = 0; - virtual RID joint_create_generic_6dof(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B)=0; //reference frame is A - - virtual void generic_6dof_joint_set_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param, float p_value)=0; - virtual float generic_6dof_joint_get_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param)=0; - - virtual void generic_6dof_joint_set_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag, bool p_enable)=0; - virtual bool generic_6dof_joint_get_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag)=0; - + virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag, bool p_enable) = 0; + virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag) = 0; #if 0 enum JointType { @@ -667,17 +638,16 @@ public: AREA_BODY_REMOVED }; - /* MISC */ - virtual void free(RID p_rid)=0; + virtual void free(RID p_rid) = 0; - virtual void set_active(bool p_active)=0; - virtual void init()=0; - virtual void step(float p_step)=0; - virtual void sync()=0; - virtual void flush_queries()=0; - virtual void finish()=0; + virtual void set_active(bool p_active) = 0; + virtual void init() = 0; + virtual void step(float p_step) = 0; + virtual void sync() = 0; + virtual void flush_queries() = 0; + virtual void finish() = 0; enum ProcessInfo { @@ -686,30 +656,30 @@ public: INFO_ISLAND_COUNT }; - virtual int get_process_info(ProcessInfo p_info)=0; + virtual int get_process_info(ProcessInfo p_info) = 0; PhysicsServer(); ~PhysicsServer(); }; -VARIANT_ENUM_CAST( PhysicsServer::ShapeType ); -VARIANT_ENUM_CAST( PhysicsServer::SpaceParameter ); -VARIANT_ENUM_CAST( PhysicsServer::AreaParameter ); -VARIANT_ENUM_CAST( PhysicsServer::AreaSpaceOverrideMode ); -VARIANT_ENUM_CAST( PhysicsServer::BodyMode ); -VARIANT_ENUM_CAST( PhysicsServer::BodyParameter ); -VARIANT_ENUM_CAST( PhysicsServer::BodyState ); -VARIANT_ENUM_CAST( PhysicsServer::BodyAxisLock ); -VARIANT_ENUM_CAST( PhysicsServer::PinJointParam ); -VARIANT_ENUM_CAST( PhysicsServer::JointType ); -VARIANT_ENUM_CAST( PhysicsServer::HingeJointParam ); -VARIANT_ENUM_CAST( PhysicsServer::HingeJointFlag ); -VARIANT_ENUM_CAST( PhysicsServer::SliderJointParam ); -VARIANT_ENUM_CAST( PhysicsServer::ConeTwistJointParam ); -VARIANT_ENUM_CAST( PhysicsServer::G6DOFJointAxisParam ); -VARIANT_ENUM_CAST( PhysicsServer::G6DOFJointAxisFlag); +VARIANT_ENUM_CAST(PhysicsServer::ShapeType); +VARIANT_ENUM_CAST(PhysicsServer::SpaceParameter); +VARIANT_ENUM_CAST(PhysicsServer::AreaParameter); +VARIANT_ENUM_CAST(PhysicsServer::AreaSpaceOverrideMode); +VARIANT_ENUM_CAST(PhysicsServer::BodyMode); +VARIANT_ENUM_CAST(PhysicsServer::BodyParameter); +VARIANT_ENUM_CAST(PhysicsServer::BodyState); +VARIANT_ENUM_CAST(PhysicsServer::BodyAxisLock); +VARIANT_ENUM_CAST(PhysicsServer::PinJointParam); +VARIANT_ENUM_CAST(PhysicsServer::JointType); +VARIANT_ENUM_CAST(PhysicsServer::HingeJointParam); +VARIANT_ENUM_CAST(PhysicsServer::HingeJointFlag); +VARIANT_ENUM_CAST(PhysicsServer::SliderJointParam); +VARIANT_ENUM_CAST(PhysicsServer::ConeTwistJointParam); +VARIANT_ENUM_CAST(PhysicsServer::G6DOFJointAxisParam); +VARIANT_ENUM_CAST(PhysicsServer::G6DOFJointAxisFlag); //VARIANT_ENUM_CAST( PhysicsServer::ObjectType ); -VARIANT_ENUM_CAST( PhysicsServer::AreaBodyStatus ); -VARIANT_ENUM_CAST( PhysicsServer::ProcessInfo ); +VARIANT_ENUM_CAST(PhysicsServer::AreaBodyStatus); +VARIANT_ENUM_CAST(PhysicsServer::ProcessInfo); #endif diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp index 0d0619e880..06bcb642ad 100644 --- a/servers/register_server_types.cpp +++ b/servers/register_server_types.cpp @@ -29,58 +29,57 @@ #include "register_server_types.h" #include "global_config.h" -#include "visual_server.h" -#include "audio_server.h" -#include "physics_server.h" -#include "physics_2d_server.h" -#include "script_debugger_remote.h" -#include "visual/shader_types.h" -#include "audio/audio_stream.h" #include "audio/audio_effect.h" +#include "audio/audio_stream.h" #include "audio/effects/audio_effect_amplify.h" -#include "audio/effects/audio_effect_reverb.h" -#include "audio/effects/audio_effect_filter.h" -#include "audio/effects/audio_effect_eq.h" -#include "audio/effects/audio_effect_distortion.h" -#include "audio/effects/audio_effect_stereo_enhance.h" -#include "audio/effects/audio_effect_panner.h" #include "audio/effects/audio_effect_chorus.h" -#include "audio/effects/audio_effect_delay.h" #include "audio/effects/audio_effect_compressor.h" +#include "audio/effects/audio_effect_delay.h" +#include "audio/effects/audio_effect_distortion.h" +#include "audio/effects/audio_effect_eq.h" +#include "audio/effects/audio_effect_filter.h" #include "audio/effects/audio_effect_limiter.h" -#include "audio/effects/audio_effect_pitch_shift.h" +#include "audio/effects/audio_effect_panner.h" #include "audio/effects/audio_effect_phaser.h" +#include "audio/effects/audio_effect_pitch_shift.h" +#include "audio/effects/audio_effect_reverb.h" +#include "audio/effects/audio_effect_stereo_enhance.h" +#include "audio_server.h" +#include "physics_2d_server.h" +#include "physics_server.h" +#include "script_debugger_remote.h" +#include "visual/shader_types.h" +#include "visual_server.h" -static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage>* r_usage) { +static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage> *r_usage) { List<VS::TextureInfo> tinfo; VS::get_singleton()->texture_debug_usage(&tinfo); - for (List<VS::TextureInfo>::Element *E=tinfo.front();E;E=E->next()) { + for (List<VS::TextureInfo>::Element *E = tinfo.front(); E; E = E->next()) { ScriptDebuggerRemote::ResourceUsage usage; - usage.path=E->get().path; - usage.vram=E->get().bytes; - usage.id=E->get().texture; - usage.type="Texture"; - usage.format=itos(E->get().size.width)+"x"+itos(E->get().size.height)+" "+Image::get_format_name(E->get().format); + usage.path = E->get().path; + usage.vram = E->get().bytes; + usage.id = E->get().texture; + usage.type = "Texture"; + usage.format = itos(E->get().size.width) + "x" + itos(E->get().size.height) + " " + Image::get_format_name(E->get().format); r_usage->push_back(usage); } - } -ShaderTypes *shader_types=NULL; +ShaderTypes *shader_types = NULL; void register_server_types() { - GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc",20); + GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc", 20); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("VisualServer",VisualServer::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("AudioServer",AudioServer::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("PhysicsServer",PhysicsServer::get_singleton()) ); - GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Physics2DServer",Physics2DServer::get_singleton()) ); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("VisualServer", VisualServer::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("AudioServer", AudioServer::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("PhysicsServer", PhysicsServer::get_singleton())); + GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Physics2DServer", Physics2DServer::get_singleton())); - shader_types = memnew( ShaderTypes ); + shader_types = memnew(ShaderTypes); ClassDB::register_virtual_class<AudioStream>(); ClassDB::register_virtual_class<AudioStreamPlayback>(); @@ -118,7 +117,6 @@ void register_server_types() { ClassDB::register_class<AudioEffectPhaser>(); } - ClassDB::register_virtual_class<Physics2DDirectBodyState>(); ClassDB::register_virtual_class<Physics2DDirectSpaceState>(); ClassDB::register_virtual_class<Physics2DShapeQueryResult>(); @@ -130,10 +128,10 @@ void register_server_types() { ClassDB::register_virtual_class<PhysicsDirectSpaceState>(); ClassDB::register_virtual_class<PhysicsShapeQueryResult>(); - ScriptDebuggerRemote::resource_usage_func=_debugger_get_resource_usage; + ScriptDebuggerRemote::resource_usage_func = _debugger_get_resource_usage; } -void unregister_server_types(){ +void unregister_server_types() { - memdelete( shader_types ); + memdelete(shader_types); } diff --git a/servers/server_wrap_mt_common.h b/servers/server_wrap_mt_common.h index fbc68fc879..cfb65cf161 100644 --- a/servers/server_wrap_mt_common.h +++ b/servers/server_wrap_mt_common.h @@ -27,763 +27,722 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#define FUNC0R(m_r,m_type)\ - virtual m_r m_type() { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type();\ - }\ - } - - -#define FUNCRID(m_type)\ - int m_type##allocn() {\ - for(int i=0;i<m_type##_pool_max_size;i++) {\ - m_type##_id_pool.push_back( server_name->m_type##_create() );\ - }\ - return 0;\ - }\ - void m_type##_free_cached_ids() {\ - while (m_type##_id_pool.size()) {\ - free(m_type##_id_pool.front()->get());\ - m_type##_id_pool.pop_front();\ - }\ - }\ - virtual RID m_type##_create() { \ - if (Thread::get_caller_ID()!=server_thread) {\ - RID rid;\ - alloc_mutex->lock();\ - if (m_type##_id_pool.size()==0) {\ - int ret;\ - command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,&ret);\ - }\ - rid=m_type##_id_pool.front()->get();\ - m_type##_id_pool.pop_front();\ - alloc_mutex->unlock();\ - return rid;\ - } else {\ - return server_name->m_type##_create();\ - }\ - } - -#define FUNC1RID(m_type,m_arg1)\ - int m_type##allocn() {\ - for(int i=0;i<m_type##_pool_max_size;i++) {\ - m_type##_id_pool.push_back( server_name->m_type##_create() );\ - }\ - return 0;\ - }\ - void m_type##_free_cached_ids() {\ - while (m_type##_id_pool.size()) {\ - free(m_type##_id_pool.front()->get());\ - m_type##_id_pool.pop_front();\ - }\ - }\ - virtual RID m_type##_create(m_arg1 p1) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - RID rid;\ - alloc_mutex->lock();\ - if (m_type##_id_pool.size()==0) {\ - int ret;\ - command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,&ret);\ - }\ - rid=m_type##_id_pool.front()->get();\ - m_type##_id_pool.pop_front();\ - alloc_mutex->unlock();\ - return rid;\ - } else {\ - return server_name->m_type##_create(p1);\ - }\ - } - -#define FUNC2RID(m_type,m_arg1,m_arg2)\ - int m_type##allocn() {\ - for(int i=0;i<m_type##_pool_max_size;i++) {\ - m_type##_id_pool.push_back( server_name->m_type##_create() );\ - }\ - return 0;\ - }\ - void m_type##_free_cached_ids() {\ - while (m_type##_id_pool.size()) {\ - free(m_type##_id_pool.front()->get());\ - m_type##_id_pool.pop_front();\ - }\ - }\ - virtual RID m_type##_create(m_arg1 p1,m_arg2 p2) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - RID rid;\ - alloc_mutex->lock();\ - if (m_type##_id_pool.size()==0) {\ - int ret;\ - command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,&ret);\ - }\ - rid=m_type##_id_pool.front()->get();\ - m_type##_id_pool.pop_front();\ - alloc_mutex->unlock();\ - return rid;\ - } else {\ - return server_name->m_type##_create(p1,p2);\ - }\ - } - -#define FUNC3RID(m_type,m_arg1,m_arg2,m_arg3)\ - int m_type##allocn() {\ - for(int i=0;i<m_type##_pool_max_size;i++) {\ - m_type##_id_pool.push_back( server_name->m_type##_create() );\ - }\ - return 0;\ - }\ - void m_type##_free_cached_ids() {\ - while (m_type##_id_pool.size()) {\ - free(m_type##_id_pool.front()->get());\ - m_type##_id_pool.pop_front();\ - }\ - }\ - virtual RID m_type##_create(m_arg1 p1,m_arg2 p2,m_arg3 p3) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - RID rid;\ - alloc_mutex->lock();\ - if (m_type##_id_pool.size()==0) {\ - int ret;\ - command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,p3,&ret);\ - }\ - rid=m_type##_id_pool.front()->get();\ - m_type##_id_pool.pop_front();\ - alloc_mutex->unlock();\ - return rid;\ - } else {\ - return server_name->m_type##_create(p1,p2,p3);\ - }\ - } - - -#define FUNC4RID(m_type,m_arg1,m_arg2,m_arg3,m_arg4)\ - int m_type##allocn() {\ - for(int i=0;i<m_type##_pool_max_size;i++) {\ - m_type##_id_pool.push_back( server_name->m_type##_create() );\ - }\ - return 0;\ - }\ - void m_type##_free_cached_ids() {\ - while (m_type##_id_pool.size()) {\ - free(m_type##_id_pool.front()->get());\ - m_type##_id_pool.pop_front();\ - }\ - }\ - virtual RID m_type##_create(m_arg1 p1,m_arg2 p2,m_arg3 p3,m_arg4 p4) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - RID rid;\ - alloc_mutex->lock();\ - if (m_type##_id_pool.size()==0) {\ - int ret;\ - command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,p3,p4,&ret);\ - }\ - rid=m_type##_id_pool.front()->get();\ - m_type##_id_pool.pop_front();\ - alloc_mutex->unlock();\ - return rid;\ - } else {\ - return server_name->m_type##_create(p1,p2,p3,p4);\ - }\ - } - - -#define FUNC5RID(m_type,m_arg1,m_arg2,m_arg3,m_arg4,m_arg5)\ - int m_type##allocn() {\ - for(int i=0;i<m_type##_pool_max_size;i++) {\ - m_type##_id_pool.push_back( server_name->m_type##_create() );\ - }\ - return 0;\ - }\ - void m_type##_free_cached_ids() {\ - while (m_type##_id_pool.size()) {\ - free(m_type##_id_pool.front()->get());\ - m_type##_id_pool.pop_front();\ - }\ - }\ - virtual RID m_type##_create(m_arg1 p1,m_arg2 p2,m_arg3 p3,m_arg4 p4,m_arg5 p5) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - RID rid;\ - alloc_mutex->lock();\ - if (m_type##_id_pool.size()==0) {\ - int ret;\ - command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,p3,p4,p5,&ret);\ - }\ - rid=m_type##_id_pool.front()->get();\ - m_type##_id_pool.pop_front();\ - alloc_mutex->unlock();\ - return rid;\ - } else {\ - return server_name->m_type##_create(p1,p2,p3,p4,p5);\ - }\ - } - -#define FUNC0RC(m_r,m_type)\ - virtual m_r m_type() const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type();\ - }\ - } - - -#define FUNC0(m_type)\ - virtual void m_type() { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type);\ - } else {\ - server_name->m_type();\ - }\ - } - -#define FUNC0C(m_type)\ - virtual void m_type() const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type);\ - } else {\ - server_name->m_type();\ - }\ - } - - -#define FUNC0S(m_type)\ - virtual void m_type() { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type);\ - } else {\ - server_name->m_type();\ - }\ - } - -#define FUNC0SC(m_type)\ - virtual void m_type() const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type);\ - } else {\ - server_name->m_type();\ - }\ +#define FUNC0R(m_r, m_type) \ + virtual m_r m_type() { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(); \ + } \ + } + +#define FUNCRID(m_type) \ + int m_type##allocn() { \ + for (int i = 0; i < m_type##_pool_max_size; i++) { \ + m_type##_id_pool.push_back(server_name->m_type##_create()); \ + } \ + return 0; \ + } \ + void m_type##_free_cached_ids() { \ + while (m_type##_id_pool.size()) { \ + free(m_type##_id_pool.front()->get()); \ + m_type##_id_pool.pop_front(); \ + } \ + } \ + virtual RID m_type##_create() { \ + if (Thread::get_caller_ID() != server_thread) { \ + RID rid; \ + alloc_mutex->lock(); \ + if (m_type##_id_pool.size() == 0) { \ + int ret; \ + command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, &ret); \ + } \ + rid = m_type##_id_pool.front()->get(); \ + m_type##_id_pool.pop_front(); \ + alloc_mutex->unlock(); \ + return rid; \ + } else { \ + return server_name->m_type##_create(); \ + } \ + } + +#define FUNC1RID(m_type, m_arg1) \ + int m_type##allocn() { \ + for (int i = 0; i < m_type##_pool_max_size; i++) { \ + m_type##_id_pool.push_back(server_name->m_type##_create()); \ + } \ + return 0; \ + } \ + void m_type##_free_cached_ids() { \ + while (m_type##_id_pool.size()) { \ + free(m_type##_id_pool.front()->get()); \ + m_type##_id_pool.pop_front(); \ + } \ + } \ + virtual RID m_type##_create(m_arg1 p1) { \ + if (Thread::get_caller_ID() != server_thread) { \ + RID rid; \ + alloc_mutex->lock(); \ + if (m_type##_id_pool.size() == 0) { \ + int ret; \ + command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, &ret); \ + } \ + rid = m_type##_id_pool.front()->get(); \ + m_type##_id_pool.pop_front(); \ + alloc_mutex->unlock(); \ + return rid; \ + } else { \ + return server_name->m_type##_create(p1); \ + } \ + } + +#define FUNC2RID(m_type, m_arg1, m_arg2) \ + int m_type##allocn() { \ + for (int i = 0; i < m_type##_pool_max_size; i++) { \ + m_type##_id_pool.push_back(server_name->m_type##_create()); \ + } \ + return 0; \ + } \ + void m_type##_free_cached_ids() { \ + while (m_type##_id_pool.size()) { \ + free(m_type##_id_pool.front()->get()); \ + m_type##_id_pool.pop_front(); \ + } \ + } \ + virtual RID m_type##_create(m_arg1 p1, m_arg2 p2) { \ + if (Thread::get_caller_ID() != server_thread) { \ + RID rid; \ + alloc_mutex->lock(); \ + if (m_type##_id_pool.size() == 0) { \ + int ret; \ + command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, &ret); \ + } \ + rid = m_type##_id_pool.front()->get(); \ + m_type##_id_pool.pop_front(); \ + alloc_mutex->unlock(); \ + return rid; \ + } else { \ + return server_name->m_type##_create(p1, p2); \ + } \ + } + +#define FUNC3RID(m_type, m_arg1, m_arg2, m_arg3) \ + int m_type##allocn() { \ + for (int i = 0; i < m_type##_pool_max_size; i++) { \ + m_type##_id_pool.push_back(server_name->m_type##_create()); \ + } \ + return 0; \ + } \ + void m_type##_free_cached_ids() { \ + while (m_type##_id_pool.size()) { \ + free(m_type##_id_pool.front()->get()); \ + m_type##_id_pool.pop_front(); \ + } \ + } \ + virtual RID m_type##_create(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ + if (Thread::get_caller_ID() != server_thread) { \ + RID rid; \ + alloc_mutex->lock(); \ + if (m_type##_id_pool.size() == 0) { \ + int ret; \ + command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, p3, &ret); \ + } \ + rid = m_type##_id_pool.front()->get(); \ + m_type##_id_pool.pop_front(); \ + alloc_mutex->unlock(); \ + return rid; \ + } else { \ + return server_name->m_type##_create(p1, p2, p3); \ + } \ + } + +#define FUNC4RID(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + int m_type##allocn() { \ + for (int i = 0; i < m_type##_pool_max_size; i++) { \ + m_type##_id_pool.push_back(server_name->m_type##_create()); \ + } \ + return 0; \ + } \ + void m_type##_free_cached_ids() { \ + while (m_type##_id_pool.size()) { \ + free(m_type##_id_pool.front()->get()); \ + m_type##_id_pool.pop_front(); \ + } \ + } \ + virtual RID m_type##_create(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ + if (Thread::get_caller_ID() != server_thread) { \ + RID rid; \ + alloc_mutex->lock(); \ + if (m_type##_id_pool.size() == 0) { \ + int ret; \ + command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, p3, p4, &ret); \ + } \ + rid = m_type##_id_pool.front()->get(); \ + m_type##_id_pool.pop_front(); \ + alloc_mutex->unlock(); \ + return rid; \ + } else { \ + return server_name->m_type##_create(p1, p2, p3, p4); \ + } \ + } + +#define FUNC5RID(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ + int m_type##allocn() { \ + for (int i = 0; i < m_type##_pool_max_size; i++) { \ + m_type##_id_pool.push_back(server_name->m_type##_create()); \ + } \ + return 0; \ + } \ + void m_type##_free_cached_ids() { \ + while (m_type##_id_pool.size()) { \ + free(m_type##_id_pool.front()->get()); \ + m_type##_id_pool.pop_front(); \ + } \ + } \ + virtual RID m_type##_create(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ + if (Thread::get_caller_ID() != server_thread) { \ + RID rid; \ + alloc_mutex->lock(); \ + if (m_type##_id_pool.size() == 0) { \ + int ret; \ + command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, p3, p4, p5, &ret); \ + } \ + rid = m_type##_id_pool.front()->get(); \ + m_type##_id_pool.pop_front(); \ + alloc_mutex->unlock(); \ + return rid; \ + } else { \ + return server_name->m_type##_create(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC0RC(m_r, m_type) \ + virtual m_r m_type() const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(); \ + } \ + } + +#define FUNC0(m_type) \ + virtual void m_type() { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type); \ + } else { \ + server_name->m_type(); \ + } \ + } + +#define FUNC0C(m_type) \ + virtual void m_type() const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type); \ + } else { \ + server_name->m_type(); \ + } \ + } + +#define FUNC0S(m_type) \ + virtual void m_type() { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type); \ + } else { \ + server_name->m_type(); \ + } \ + } + +#define FUNC0SC(m_type) \ + virtual void m_type() const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type); \ + } else { \ + server_name->m_type(); \ + } \ } - /////////////////////////////////////////////// - -#define FUNC1R(m_r,m_type,m_arg1)\ - virtual m_r m_type(m_arg1 p1) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1);\ - }\ - } - -#define FUNC1RC(m_r,m_type,m_arg1)\ - virtual m_r m_type(m_arg1 p1) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1);\ - }\ - } - - -#define FUNC1S(m_type,m_arg1)\ - virtual void m_type(m_arg1 p1) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1);\ - } else {\ - server_name->m_type(p1);\ - }\ - } - -#define FUNC1SC(m_type,m_arg1)\ - virtual void m_type(m_arg1 p1) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1);\ - } else {\ - server_name->m_type(p1);\ - }\ - } - - -#define FUNC1(m_type,m_arg1)\ - virtual void m_type(m_arg1 p1) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1);\ - } else {\ - server_name->m_type(p1);\ - }\ - } - -#define FUNC1C(m_type,m_arg1)\ - virtual void m_type(m_arg1 p1) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1);\ - } else {\ - server_name->m_type(p1);\ - }\ - } - - - - -#define FUNC2R(m_r,m_type,m_arg1, m_arg2)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2);\ - }\ - } - -#define FUNC2RC(m_r,m_type,m_arg1, m_arg2)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2);\ - }\ - } - - -#define FUNC2S(m_type,m_arg1, m_arg2)\ - virtual void m_type(m_arg1 p1, m_arg2 p2) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2);\ - } else {\ - server_name->m_type(p1, p2);\ - }\ - } - -#define FUNC2SC(m_type,m_arg1, m_arg2)\ - virtual void m_type(m_arg1 p1, m_arg2 p2) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2);\ - } else {\ - server_name->m_type(p1, p2);\ - }\ - } - - -#define FUNC2(m_type,m_arg1, m_arg2)\ - virtual void m_type(m_arg1 p1, m_arg2 p2) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2);\ - } else {\ - server_name->m_type(p1, p2);\ - }\ - } - -#define FUNC2C(m_type,m_arg1, m_arg2)\ - virtual void m_type(m_arg1 p1, m_arg2 p2) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2);\ - } else {\ - server_name->m_type(p1, p2);\ - }\ - } - - - - -#define FUNC3R(m_r,m_type,m_arg1, m_arg2, m_arg3)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3);\ - }\ - } - -#define FUNC3RC(m_r,m_type,m_arg1, m_arg2, m_arg3)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3,&ret);\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3);\ - }\ - } - - -#define FUNC3S(m_type,m_arg1, m_arg2, m_arg3)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3);\ - } else {\ - server_name->m_type(p1, p2, p3);\ - }\ - } - -#define FUNC3SC(m_type,m_arg1, m_arg2, m_arg3)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3);\ - } else {\ - server_name->m_type(p1, p2, p3);\ - }\ - } - - -#define FUNC3(m_type,m_arg1, m_arg2, m_arg3)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3);\ - } else {\ - server_name->m_type(p1, p2, p3);\ - }\ - } - -#define FUNC3C(m_type,m_arg1, m_arg2, m_arg3)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3);\ - } else {\ - server_name->m_type(p1, p2, p3);\ - }\ - } - - - - -#define FUNC4R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4);\ - }\ - } - -#define FUNC4RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4);\ - }\ - } - - -#define FUNC4S(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4);\ - } else {\ - server_name->m_type(p1, p2, p3, p4);\ - }\ - } - -#define FUNC4SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4);\ - } else {\ - server_name->m_type(p1, p2, p3, p4);\ - }\ - } - - -#define FUNC4(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4);\ - } else {\ - server_name->m_type(p1, p2, p3, p4);\ - }\ - } - -#define FUNC4C(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4);\ - } else {\ - server_name->m_type(p1, p2, p3, p4);\ - }\ - } - - - - -#define FUNC5R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5);\ - }\ - } - -#define FUNC5RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5);\ - }\ - } - - -#define FUNC5S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5);\ - }\ - } - -#define FUNC5SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\ +#define FUNC1R(m_r, m_type, m_arg1) \ + virtual m_r m_type(m_arg1 p1) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1); \ + } \ + } + +#define FUNC1RC(m_r, m_type, m_arg1) \ + virtual m_r m_type(m_arg1 p1) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1); \ + } \ + } + +#define FUNC1S(m_type, m_arg1) \ + virtual void m_type(m_arg1 p1) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1); \ + } else { \ + server_name->m_type(p1); \ + } \ + } + +#define FUNC1SC(m_type, m_arg1) \ + virtual void m_type(m_arg1 p1) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1); \ + } else { \ + server_name->m_type(p1); \ + } \ + } + +#define FUNC1(m_type, m_arg1) \ + virtual void m_type(m_arg1 p1) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1); \ + } else { \ + server_name->m_type(p1); \ + } \ + } + +#define FUNC1C(m_type, m_arg1) \ + virtual void m_type(m_arg1 p1) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1); \ + } else { \ + server_name->m_type(p1); \ + } \ + } + +#define FUNC2R(m_r, m_type, m_arg1, m_arg2) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2); \ + } \ + } + +#define FUNC2RC(m_r, m_type, m_arg1, m_arg2) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2); \ + } \ + } + +#define FUNC2S(m_type, m_arg1, m_arg2) \ + virtual void m_type(m_arg1 p1, m_arg2 p2) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2); \ + } else { \ + server_name->m_type(p1, p2); \ + } \ + } + +#define FUNC2SC(m_type, m_arg1, m_arg2) \ + virtual void m_type(m_arg1 p1, m_arg2 p2) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2); \ + } else { \ + server_name->m_type(p1, p2); \ + } \ + } + +#define FUNC2(m_type, m_arg1, m_arg2) \ + virtual void m_type(m_arg1 p1, m_arg2 p2) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2); \ + } else { \ + server_name->m_type(p1, p2); \ + } \ + } + +#define FUNC2C(m_type, m_arg1, m_arg2) \ + virtual void m_type(m_arg1 p1, m_arg2 p2) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2); \ + } else { \ + server_name->m_type(p1, p2); \ + } \ + } + +#define FUNC3R(m_r, m_type, m_arg1, m_arg2, m_arg3) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3); \ + } \ + } + +#define FUNC3RC(m_r, m_type, m_arg1, m_arg2, m_arg3) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, &ret); \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3); \ + } \ + } + +#define FUNC3S(m_type, m_arg1, m_arg2, m_arg3) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3); \ + } else { \ + server_name->m_type(p1, p2, p3); \ + } \ + } + +#define FUNC3SC(m_type, m_arg1, m_arg2, m_arg3) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3); \ + } else { \ + server_name->m_type(p1, p2, p3); \ + } \ + } + +#define FUNC3(m_type, m_arg1, m_arg2, m_arg3) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3); \ + } else { \ + server_name->m_type(p1, p2, p3); \ + } \ + } + +#define FUNC3C(m_type, m_arg1, m_arg2, m_arg3) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3); \ + } else { \ + server_name->m_type(p1, p2, p3); \ + } \ + } + +#define FUNC4R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4); \ + } \ + } + +#define FUNC4RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4); \ + } \ + } + +#define FUNC4S(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4); \ + } else { \ + server_name->m_type(p1, p2, p3, p4); \ + } \ + } + +#define FUNC4SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4); \ + } else { \ + server_name->m_type(p1, p2, p3, p4); \ + } \ + } + +#define FUNC4(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4); \ + } else { \ + server_name->m_type(p1, p2, p3, p4); \ + } \ + } + +#define FUNC4C(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4); \ + } else { \ + server_name->m_type(p1, p2, p3, p4); \ + } \ + } + +#define FUNC5R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC5RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC5S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC5SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC5(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC5C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5);\ - }\ - } - - -#define FUNC5(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5);\ - }\ - } - -#define FUNC5C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5);\ - }\ - } - - - - -#define FUNC6R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5, p6);\ - }\ - } - -#define FUNC6RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6,&ret);\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5, p6);\ - }\ - } - - -#define FUNC6S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5); \ + } \ + } + +#define FUNC6R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5, p6); \ + } \ + } + +#define FUNC6RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, &ret); \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5, p6); \ + } \ + } + +#define FUNC6S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6); \ + } \ + } + +#define FUNC6SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \ + virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6); \ + } \ + } + +#define FUNC6(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6); \ + } \ } -#define FUNC6SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\ +#define FUNC6C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6);\ - }\ - } - - -#define FUNC6(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6);\ - }\ - } - -#define FUNC6C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\ - virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6);\ - }\ - } - - - - -#define FUNC7R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\ - virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\ - }\ - } - -#define FUNC7RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6); \ + } \ + } + +#define FUNC7R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \ + virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \ + } \ + } + +#define FUNC7RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7,&ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \ + } \ } - -#define FUNC7S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\ +#define FUNC7S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \ + } \ } -#define FUNC7SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\ +#define FUNC7SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \ + } \ } - -#define FUNC7(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\ +#define FUNC7(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \ + } \ } -#define FUNC7C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\ +#define FUNC7C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \ + } \ } -#define FUNC8R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\ +#define FUNC8R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8, &ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ } -#define FUNC8RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\ +#define FUNC8RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - m_r ret;\ - command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8, &ret);\ - SYNC_DEBUG\ - return ret;\ - } else {\ - return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + m_r ret; \ + command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8, &ret); \ + SYNC_DEBUG \ + return ret; \ + } else { \ + return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ } - -#define FUNC8S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\ +#define FUNC8S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ } -#define FUNC8SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\ +#define FUNC8SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ } - -#define FUNC8(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\ +#define FUNC8(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ } -#define FUNC8C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\ +#define FUNC8C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) const { \ - if (Thread::get_caller_ID()!=server_thread) {\ - command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\ - } else {\ - server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\ - }\ + if (Thread::get_caller_ID() != server_thread) { \ + command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \ + } else { \ + server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ } diff --git a/servers/visual/rasterizer.cpp b/servers/visual/rasterizer.cpp index ba85f92e37..fdcc4f5633 100644 --- a/servers/visual/rasterizer.cpp +++ b/servers/visual/rasterizer.cpp @@ -27,22 +27,21 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "rasterizer.h" -#include "print_string.h" #include "os/os.h" +#include "print_string.h" - -Rasterizer* (*Rasterizer::_create_func)()=NULL; +Rasterizer *(*Rasterizer::_create_func)() = NULL; Rasterizer *Rasterizer::create() { return _create_func(); } -RasterizerStorage*RasterizerStorage::base_signleton=NULL; +RasterizerStorage *RasterizerStorage::base_signleton = NULL; RasterizerStorage::RasterizerStorage() { - base_signleton=this; + base_signleton = this; } #if 0 @@ -78,7 +77,7 @@ RID Rasterizer::_create_shader(const FixedSpatialMaterialShaderKey& p_key) { String code; static const char* _uv_str[4]={"UV","uv_xform","UV2","uv_sphere"}; -#define _TEXUVSTR(m_idx) String( _uv_str[(p_key.texcoord_mask>>(m_idx*2))&0x3] ) +#define _TEXUVSTR(m_idx) String(_uv_str[(p_key.texcoord_mask >> (m_idx * 2)) & 0x3]) if (p_key.use_pointsize) { diff --git a/servers/visual/rasterizer.h b/servers/visual/rasterizer.h index dd22986865..527230895c 100644 --- a/servers/visual/rasterizer.h +++ b/servers/visual/rasterizer.h @@ -29,49 +29,46 @@ #ifndef RASTERIZER_H #define RASTERIZER_H - -#include "servers/visual_server.h" #include "camera_matrix.h" +#include "servers/visual_server.h" #include "self_list.h" - class RasterizerScene { public: - /* SHADOW ATLAS API */ - virtual RID shadow_atlas_create()=0; - virtual void shadow_atlas_set_size(RID p_atlas,int p_size)=0; - virtual void shadow_atlas_set_quadrant_subdivision(RID p_atlas,int p_quadrant,int p_subdivision)=0; - virtual bool shadow_atlas_update_light(RID p_atlas,RID p_light_intance,float p_coverage,uint64_t p_light_version)=0; + virtual RID shadow_atlas_create() = 0; + virtual void shadow_atlas_set_size(RID p_atlas, int p_size) = 0; + virtual void shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) = 0; + virtual bool shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) = 0; - virtual int get_directional_light_shadow_size(RID p_light_intance)=0; - virtual void set_directional_shadow_count(int p_count)=0; + virtual int get_directional_light_shadow_size(RID p_light_intance) = 0; + virtual void set_directional_shadow_count(int p_count) = 0; /* ENVIRONMENT API */ - virtual RID environment_create()=0; + virtual RID environment_create() = 0; - virtual void environment_set_background(RID p_env,VS::EnvironmentBG p_bg)=0; - virtual void environment_set_skybox(RID p_env,RID p_skybox)=0; - virtual void environment_set_skybox_scale(RID p_env,float p_scale)=0; - virtual void environment_set_bg_color(RID p_env,const Color& p_color)=0; - virtual void environment_set_bg_energy(RID p_env,float p_energy)=0; - virtual void environment_set_canvas_max_layer(RID p_env,int p_max_layer)=0; - virtual void environment_set_ambient_light(RID p_env,const Color& p_color,float p_energy=1.0,float p_skybox_contribution=0.0)=0; + virtual void environment_set_background(RID p_env, VS::EnvironmentBG p_bg) = 0; + virtual void environment_set_skybox(RID p_env, RID p_skybox) = 0; + virtual void environment_set_skybox_scale(RID p_env, float p_scale) = 0; + virtual void environment_set_bg_color(RID p_env, const Color &p_color) = 0; + virtual void environment_set_bg_energy(RID p_env, float p_energy) = 0; + virtual void environment_set_canvas_max_layer(RID p_env, int p_max_layer) = 0; + virtual void environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy = 1.0, float p_skybox_contribution = 0.0) = 0; - virtual void environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,VS::EnvironmentDOFBlurQuality p_quality)=0; - virtual void environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,VS::EnvironmentDOFBlurQuality p_quality)=0; - virtual void environment_set_glow(RID p_env,bool p_enable,int p_level_flags,float p_intensity,float p_strength,float p_bloom_treshold,VS::EnvironmentGlowBlendMode p_blend_mode,float p_hdr_bleed_treshold,float p_hdr_bleed_scale,bool p_bicubic_upscale)=0; - virtual void environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture)=0; + virtual void environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, VS::EnvironmentDOFBlurQuality p_quality) = 0; + virtual void environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, VS::EnvironmentDOFBlurQuality p_quality) = 0; + virtual void environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale) = 0; + virtual void environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) = 0; - virtual void environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness)=0; - virtual void environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect,const Color &p_color,bool p_blur)=0; + virtual void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_accel, float p_fade, float p_depth_tolerance, bool p_smooth, bool p_roughness) = 0; + virtual void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, const Color &p_color, bool p_blur) = 0; - virtual void environment_set_tonemap(RID p_env,VS::EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_scale)=0; + virtual void environment_set_tonemap(RID p_env, VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) = 0; - virtual void environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp)=0; + virtual void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) = 0; struct InstanceBase : RID_Data { @@ -100,10 +97,10 @@ public: //Transform *baked_light_octree_xform; //int baked_lightmap_id; - bool mirror :8; - bool depth_scale :8; - bool billboard :8; - bool billboard_y :8; + bool mirror : 8; + bool depth_scale : 8; + bool billboard : 8; + bool billboard_y : 8; bool receive_shadows : 8; bool visible : 8; @@ -113,338 +110,323 @@ public: InstanceBase *baked_light; //baked light to use SelfList<InstanceBase> baked_light_item; - virtual void base_removed()=0; - virtual void base_changed()=0; - virtual void base_material_changed()=0; - - InstanceBase() : dependency_item(this), baked_light_item(this) { - - base_type=VS::INSTANCE_NONE; - cast_shadows=VS::SHADOW_CASTING_SETTING_ON; - receive_shadows=true; - depth_scale=false; - billboard=false; - billboard_y=false; - visible=true; - depth_layer=0; - layer_mask=1; - baked_light=NULL; - - + virtual void base_removed() = 0; + virtual void base_changed() = 0; + virtual void base_material_changed() = 0; + + InstanceBase() + : dependency_item(this), baked_light_item(this) { + + base_type = VS::INSTANCE_NONE; + cast_shadows = VS::SHADOW_CASTING_SETTING_ON; + receive_shadows = true; + depth_scale = false; + billboard = false; + billboard_y = false; + visible = true; + depth_layer = 0; + layer_mask = 1; + baked_light = NULL; } }; - virtual RID light_instance_create(RID p_light)=0; - virtual void light_instance_set_transform(RID p_light_instance,const Transform& p_transform)=0; - virtual void light_instance_set_shadow_transform(RID p_light_instance,const CameraMatrix& p_projection,const Transform& p_transform,float p_far,float p_split,int p_pass)=0; - virtual void light_instance_mark_visible(RID p_light_instance)=0; + virtual RID light_instance_create(RID p_light) = 0; + virtual void light_instance_set_transform(RID p_light_instance, const Transform &p_transform) = 0; + virtual void light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass) = 0; + virtual void light_instance_mark_visible(RID p_light_instance) = 0; - virtual RID reflection_atlas_create()=0; - virtual void reflection_atlas_set_size(RID p_ref_atlas,int p_size)=0; - virtual void reflection_atlas_set_subdivision(RID p_ref_atlas,int p_subdiv)=0; + virtual RID reflection_atlas_create() = 0; + virtual void reflection_atlas_set_size(RID p_ref_atlas, int p_size) = 0; + virtual void reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv) = 0; - virtual RID reflection_probe_instance_create(RID p_probe)=0; - virtual void reflection_probe_instance_set_transform(RID p_instance,const Transform& p_transform)=0; - virtual void reflection_probe_release_atlas_index(RID p_instance)=0; - virtual bool reflection_probe_instance_needs_redraw(RID p_instance)=0; - virtual bool reflection_probe_instance_has_reflection(RID p_instance)=0; - virtual bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas)=0; - virtual bool reflection_probe_instance_postprocess_step(RID p_instance)=0; + virtual RID reflection_probe_instance_create(RID p_probe) = 0; + virtual void reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) = 0; + virtual void reflection_probe_release_atlas_index(RID p_instance) = 0; + virtual bool reflection_probe_instance_needs_redraw(RID p_instance) = 0; + virtual bool reflection_probe_instance_has_reflection(RID p_instance) = 0; + virtual bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) = 0; + virtual bool reflection_probe_instance_postprocess_step(RID p_instance) = 0; - virtual RID gi_probe_instance_create()=0; - virtual void gi_probe_instance_set_light_data(RID p_probe,RID p_base,RID p_data)=0; - virtual void gi_probe_instance_set_transform_to_data(RID p_probe,const Transform& p_xform)=0; - virtual void gi_probe_instance_set_bounds(RID p_probe,const Vector3& p_bounds)=0; + virtual RID gi_probe_instance_create() = 0; + virtual void gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data) = 0; + virtual void gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) = 0; + virtual void gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds) = 0; - virtual void render_scene(const Transform& p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_ortogonal,InstanceBase** p_cull_result,int p_cull_count,RID* p_light_cull_result,int p_light_cull_count,RID* p_reflection_probe_cull_result,int p_reflection_probe_cull_count,RID p_environment,RID p_shadow_atlas,RID p_reflection_atlas,RID p_reflection_probe,int p_reflection_probe_pass)=0; - virtual void render_shadow(RID p_light,RID p_shadow_atlas,int p_pass,InstanceBase** p_cull_result,int p_cull_count)=0; + virtual void render_scene(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) = 0; + virtual void render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) = 0; - virtual void set_scene_pass(uint64_t p_pass)=0; + virtual void set_scene_pass(uint64_t p_pass) = 0; - virtual bool free(RID p_rid)=0; + virtual bool free(RID p_rid) = 0; virtual ~RasterizerScene() {} }; - - - - - - class RasterizerStorage { public: /* TEXTURE API */ - virtual RID texture_create()=0; - virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=VS::TEXTURE_FLAGS_DEFAULT)=0; - virtual void texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT)=0; - virtual Image texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT) const=0; - virtual void texture_set_flags(RID p_texture,uint32_t p_flags)=0; - virtual uint32_t texture_get_flags(RID p_texture) const=0; - virtual Image::Format texture_get_format(RID p_texture) const=0; - virtual uint32_t texture_get_width(RID p_texture) const=0; - virtual uint32_t texture_get_height(RID p_texture) const=0; - virtual void texture_set_size_override(RID p_texture,int p_width, int p_height)=0; + virtual RID texture_create() = 0; + virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = VS::TEXTURE_FLAGS_DEFAULT) = 0; + virtual void texture_set_data(RID p_texture, const Image &p_image, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) = 0; + virtual Image texture_get_data(RID p_texture, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) const = 0; + virtual void texture_set_flags(RID p_texture, uint32_t p_flags) = 0; + virtual uint32_t texture_get_flags(RID p_texture) const = 0; + virtual Image::Format texture_get_format(RID p_texture) const = 0; + virtual uint32_t texture_get_width(RID p_texture) const = 0; + virtual uint32_t texture_get_height(RID p_texture) const = 0; + virtual void texture_set_size_override(RID p_texture, int p_width, int p_height) = 0; - virtual void texture_set_path(RID p_texture,const String& p_path)=0; - virtual String texture_get_path(RID p_texture) const=0; + virtual void texture_set_path(RID p_texture, const String &p_path) = 0; + virtual String texture_get_path(RID p_texture) const = 0; - virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable)=0; + virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable) = 0; - virtual void texture_debug_usage(List<VS::TextureInfo> *r_info)=0; + virtual void texture_debug_usage(List<VS::TextureInfo> *r_info) = 0; - virtual RID texture_create_radiance_cubemap(RID p_source,int p_resolution=-1) const=0; + virtual RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const = 0; - virtual void texture_set_detect_3d_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata)=0; - virtual void texture_set_detect_srgb_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata)=0; + virtual void texture_set_detect_3d_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) = 0; + virtual void texture_set_detect_srgb_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) = 0; - virtual void textures_keep_original(bool p_enable)=0; + virtual void textures_keep_original(bool p_enable) = 0; /* SKYBOX API */ - virtual RID skybox_create()=0; - virtual void skybox_set_texture(RID p_skybox,RID p_cube_map,int p_radiance_size)=0; + virtual RID skybox_create() = 0; + virtual void skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size) = 0; /* SHADER API */ + virtual RID shader_create(VS::ShaderMode p_mode = VS::SHADER_SPATIAL) = 0; - virtual RID shader_create(VS::ShaderMode p_mode=VS::SHADER_SPATIAL)=0; - - virtual void shader_set_mode(RID p_shader,VS::ShaderMode p_mode)=0; - virtual VS::ShaderMode shader_get_mode(RID p_shader) const=0; + virtual void shader_set_mode(RID p_shader, VS::ShaderMode p_mode) = 0; + virtual VS::ShaderMode shader_get_mode(RID p_shader) const = 0; - virtual void shader_set_code(RID p_shader, const String& p_code)=0; - virtual String shader_get_code(RID p_shader) const=0; - virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const=0; - - virtual void shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture)=0; - virtual RID shader_get_default_texture_param(RID p_shader, const StringName& p_name) const=0; + virtual void shader_set_code(RID p_shader, const String &p_code) = 0; + virtual String shader_get_code(RID p_shader) const = 0; + virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const = 0; + virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) = 0; + virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const = 0; /* COMMON MATERIAL API */ - virtual RID material_create()=0; + virtual RID material_create() = 0; - virtual void material_set_shader(RID p_shader_material, RID p_shader)=0; - virtual RID material_get_shader(RID p_shader_material) const=0; + virtual void material_set_shader(RID p_shader_material, RID p_shader) = 0; + virtual RID material_get_shader(RID p_shader_material) const = 0; - virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value)=0; - virtual Variant material_get_param(RID p_material, const StringName& p_param) const=0; + virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) = 0; + virtual Variant material_get_param(RID p_material, const StringName &p_param) const = 0; - virtual void material_set_line_width(RID p_material, float p_width)=0; + virtual void material_set_line_width(RID p_material, float p_width) = 0; - virtual bool material_is_animated(RID p_material)=0; - virtual bool material_casts_shadows(RID p_material)=0; + virtual bool material_is_animated(RID p_material) = 0; + virtual bool material_casts_shadows(RID p_material) = 0; - virtual void material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance)=0; - virtual void material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance)=0; + virtual void material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) = 0; + virtual void material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) = 0; /* MESH API */ - virtual RID mesh_create()=0; + virtual RID mesh_create() = 0; - virtual void mesh_add_surface(RID p_mesh,uint32_t p_format,VS::PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>())=0; + virtual void mesh_add_surface(RID p_mesh, uint32_t p_format, VS::PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>()) = 0; - virtual void mesh_set_blend_shape_count(RID p_mesh,int p_amount)=0; - virtual int mesh_get_blend_shape_count(RID p_mesh) const=0; + virtual void mesh_set_blend_shape_count(RID p_mesh, int p_amount) = 0; + virtual int mesh_get_blend_shape_count(RID p_mesh) const = 0; + virtual void mesh_set_blend_shape_mode(RID p_mesh, VS::BlendShapeMode p_mode) = 0; + virtual VS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const = 0; - virtual void mesh_set_blend_shape_mode(RID p_mesh,VS::BlendShapeMode p_mode)=0; - virtual VS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const=0; + virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) = 0; + virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const = 0; - virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material)=0; - virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const=0; + virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const = 0; + virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const = 0; - virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const=0; - virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const=0; + virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const = 0; + virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const = 0; - virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const=0; - virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const=0; + virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const = 0; + virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const = 0; + virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const = 0; + virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const = 0; + virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const = 0; - virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const=0; - virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const=0; + virtual void mesh_remove_surface(RID p_mesh, int p_index) = 0; + virtual int mesh_get_surface_count(RID p_mesh) const = 0; - virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const=0; - virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const=0; - virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const=0; + virtual void mesh_set_custom_aabb(RID p_mesh, const Rect3 &p_aabb) = 0; + virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const = 0; - virtual void mesh_remove_surface(RID p_mesh,int p_index)=0; - virtual int mesh_get_surface_count(RID p_mesh) const=0; - - virtual void mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb)=0; - virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const=0; - - virtual Rect3 mesh_get_aabb(RID p_mesh, RID p_skeleton) const=0; - virtual void mesh_clear(RID p_mesh)=0; + virtual Rect3 mesh_get_aabb(RID p_mesh, RID p_skeleton) const = 0; + virtual void mesh_clear(RID p_mesh) = 0; /* MULTIMESH API */ + virtual RID multimesh_create() = 0; - virtual RID multimesh_create()=0; + virtual void multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format) = 0; + virtual int multimesh_get_instance_count(RID p_multimesh) const = 0; - virtual void multimesh_allocate(RID p_multimesh,int p_instances,VS::MultimeshTransformFormat p_transform_format,VS::MultimeshColorFormat p_color_format)=0; - virtual int multimesh_get_instance_count(RID p_multimesh) const=0; - - virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh)=0; - virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform)=0; - virtual void multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform)=0; - virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color)=0; + virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) = 0; + virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) = 0; + virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) = 0; + virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) = 0; - virtual RID multimesh_get_mesh(RID p_multimesh) const=0; + virtual RID multimesh_get_mesh(RID p_multimesh) const = 0; - virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const=0; - virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const=0; - virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const=0; + virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const = 0; + virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const = 0; + virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const = 0; - virtual void multimesh_set_visible_instances(RID p_multimesh,int p_visible)=0; - virtual int multimesh_get_visible_instances(RID p_multimesh) const=0; + virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) = 0; + virtual int multimesh_get_visible_instances(RID p_multimesh) const = 0; - virtual Rect3 multimesh_get_aabb(RID p_multimesh) const=0; + virtual Rect3 multimesh_get_aabb(RID p_multimesh) const = 0; /* IMMEDIATE API */ - virtual RID immediate_create()=0; - virtual void immediate_begin(RID p_immediate,VS::PrimitiveType p_rimitive,RID p_texture=RID())=0; - virtual void immediate_vertex(RID p_immediate,const Vector3& p_vertex)=0; - virtual void immediate_normal(RID p_immediate,const Vector3& p_normal)=0; - virtual void immediate_tangent(RID p_immediate,const Plane& p_tangent)=0; - virtual void immediate_color(RID p_immediate,const Color& p_color)=0; - virtual void immediate_uv(RID p_immediate,const Vector2& tex_uv)=0; - virtual void immediate_uv2(RID p_immediate,const Vector2& tex_uv)=0; - virtual void immediate_end(RID p_immediate)=0; - virtual void immediate_clear(RID p_immediate)=0; - virtual void immediate_set_material(RID p_immediate,RID p_material)=0; - virtual RID immediate_get_material(RID p_immediate) const=0; - virtual Rect3 immediate_get_aabb(RID p_immediate) const=0; - + virtual RID immediate_create() = 0; + virtual void immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture = RID()) = 0; + virtual void immediate_vertex(RID p_immediate, const Vector3 &p_vertex) = 0; + virtual void immediate_normal(RID p_immediate, const Vector3 &p_normal) = 0; + virtual void immediate_tangent(RID p_immediate, const Plane &p_tangent) = 0; + virtual void immediate_color(RID p_immediate, const Color &p_color) = 0; + virtual void immediate_uv(RID p_immediate, const Vector2 &tex_uv) = 0; + virtual void immediate_uv2(RID p_immediate, const Vector2 &tex_uv) = 0; + virtual void immediate_end(RID p_immediate) = 0; + virtual void immediate_clear(RID p_immediate) = 0; + virtual void immediate_set_material(RID p_immediate, RID p_material) = 0; + virtual RID immediate_get_material(RID p_immediate) const = 0; + virtual Rect3 immediate_get_aabb(RID p_immediate) const = 0; /* SKELETON API */ - virtual RID skeleton_create()=0; - virtual void skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton=false)=0; - virtual int skeleton_get_bone_count(RID p_skeleton) const=0; - virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform)=0; - virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone) const =0; - virtual void skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform)=0; - virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone) const=0; + virtual RID skeleton_create() = 0; + virtual void skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) = 0; + virtual int skeleton_get_bone_count(RID p_skeleton) const = 0; + virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) = 0; + virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone) const = 0; + virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) = 0; + virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const = 0; /* Light API */ - virtual RID light_create(VS::LightType p_type)=0; + virtual RID light_create(VS::LightType p_type) = 0; - virtual void light_set_color(RID p_light,const Color& p_color)=0; - virtual void light_set_param(RID p_light,VS::LightParam p_param,float p_value)=0; - virtual void light_set_shadow(RID p_light,bool p_enabled)=0; - virtual void light_set_shadow_color(RID p_light,const Color& p_color)=0; - virtual void light_set_projector(RID p_light,RID p_texture)=0; - virtual void light_set_negative(RID p_light,bool p_enable)=0; - virtual void light_set_cull_mask(RID p_light,uint32_t p_mask)=0; + virtual void light_set_color(RID p_light, const Color &p_color) = 0; + virtual void light_set_param(RID p_light, VS::LightParam p_param, float p_value) = 0; + virtual void light_set_shadow(RID p_light, bool p_enabled) = 0; + virtual void light_set_shadow_color(RID p_light, const Color &p_color) = 0; + virtual void light_set_projector(RID p_light, RID p_texture) = 0; + virtual void light_set_negative(RID p_light, bool p_enable) = 0; + virtual void light_set_cull_mask(RID p_light, uint32_t p_mask) = 0; - virtual void light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode)=0; - virtual void light_omni_set_shadow_detail(RID p_light,VS::LightOmniShadowDetail p_detail)=0; - - virtual void light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode)=0; - virtual void light_directional_set_blend_splits(RID p_light,bool p_enable)=0; - virtual bool light_directional_get_blend_splits(RID p_light) const=0; + virtual void light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode) = 0; + virtual void light_omni_set_shadow_detail(RID p_light, VS::LightOmniShadowDetail p_detail) = 0; - virtual VS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light)=0; - virtual VS::LightOmniShadowMode light_omni_get_shadow_mode(RID p_light)=0; + virtual void light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode) = 0; + virtual void light_directional_set_blend_splits(RID p_light, bool p_enable) = 0; + virtual bool light_directional_get_blend_splits(RID p_light) const = 0; - virtual bool light_has_shadow(RID p_light) const=0; + virtual VS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light) = 0; + virtual VS::LightOmniShadowMode light_omni_get_shadow_mode(RID p_light) = 0; - virtual VS::LightType light_get_type(RID p_light) const=0; - virtual Rect3 light_get_aabb(RID p_light) const=0; - virtual float light_get_param(RID p_light,VS::LightParam p_param)=0; - virtual Color light_get_color(RID p_light)=0; - virtual uint64_t light_get_version(RID p_light) const=0; + virtual bool light_has_shadow(RID p_light) const = 0; + virtual VS::LightType light_get_type(RID p_light) const = 0; + virtual Rect3 light_get_aabb(RID p_light) const = 0; + virtual float light_get_param(RID p_light, VS::LightParam p_param) = 0; + virtual Color light_get_color(RID p_light) = 0; + virtual uint64_t light_get_version(RID p_light) const = 0; /* PROBE API */ - virtual RID reflection_probe_create()=0; - - virtual void reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode)=0; - virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity)=0; - virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color& p_ambient)=0; - virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy)=0; - virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib)=0; - virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance)=0; - virtual void reflection_probe_set_extents(RID p_probe, const Vector3& p_extents)=0; - virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset)=0; - virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable)=0; - virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable)=0; - virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable)=0; - virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers)=0; - - virtual Rect3 reflection_probe_get_aabb(RID p_probe) const=0; - virtual VS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const=0; - virtual uint32_t reflection_probe_get_cull_mask(RID p_probe) const=0; - virtual Vector3 reflection_probe_get_extents(RID p_probe) const=0; - virtual Vector3 reflection_probe_get_origin_offset(RID p_probe) const=0; - virtual float reflection_probe_get_origin_max_distance(RID p_probe) const=0; - virtual bool reflection_probe_renders_shadows(RID p_probe) const=0; - + virtual RID reflection_probe_create() = 0; + + virtual void reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode) = 0; + virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity) = 0; + virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color &p_ambient) = 0; + virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) = 0; + virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) = 0; + virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance) = 0; + virtual void reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) = 0; + virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) = 0; + virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable) = 0; + virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) = 0; + virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) = 0; + virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) = 0; + + virtual Rect3 reflection_probe_get_aabb(RID p_probe) const = 0; + virtual VS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const = 0; + virtual uint32_t reflection_probe_get_cull_mask(RID p_probe) const = 0; + virtual Vector3 reflection_probe_get_extents(RID p_probe) const = 0; + virtual Vector3 reflection_probe_get_origin_offset(RID p_probe) const = 0; + virtual float reflection_probe_get_origin_max_distance(RID p_probe) const = 0; + virtual bool reflection_probe_renders_shadows(RID p_probe) const = 0; /* ROOM API */ - virtual RID room_create()=0; - virtual void room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform)=0; - virtual void room_clear_bounds(RID p_room)=0; + virtual RID room_create() = 0; + virtual void room_add_bounds(RID p_room, const PoolVector<Vector2> &p_convex_polygon, float p_height, const Transform &p_transform) = 0; + virtual void room_clear_bounds(RID p_room) = 0; /* PORTAL API */ // portals are only (x/y) points, forming a convex shape, which its clockwise // order points outside. (z is 0)=0; - virtual RID portal_create()=0; - virtual void portal_set_shape(RID p_portal, const Vector<Point2>& p_shape)=0; - virtual void portal_set_enabled(RID p_portal, bool p_enabled)=0; - virtual void portal_set_disable_distance(RID p_portal, float p_distance)=0; - virtual void portal_set_disabled_color(RID p_portal, const Color& p_color)=0; + virtual RID portal_create() = 0; + virtual void portal_set_shape(RID p_portal, const Vector<Point2> &p_shape) = 0; + virtual void portal_set_enabled(RID p_portal, bool p_enabled) = 0; + virtual void portal_set_disable_distance(RID p_portal, float p_distance) = 0; + virtual void portal_set_disabled_color(RID p_portal, const Color &p_color) = 0; - virtual void instance_add_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance)=0; - virtual void instance_remove_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance)=0; + virtual void instance_add_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) = 0; + virtual void instance_remove_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) = 0; - virtual void instance_add_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance)=0; - virtual void instance_remove_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance)=0; + virtual void instance_add_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) = 0; + virtual void instance_remove_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) = 0; /* GI PROBE API */ - virtual RID gi_probe_create()=0; + virtual RID gi_probe_create() = 0; - virtual void gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds)=0; - virtual Rect3 gi_probe_get_bounds(RID p_probe) const=0; + virtual void gi_probe_set_bounds(RID p_probe, const Rect3 &p_bounds) = 0; + virtual Rect3 gi_probe_get_bounds(RID p_probe) const = 0; - virtual void gi_probe_set_cell_size(RID p_probe,float p_range)=0; - virtual float gi_probe_get_cell_size(RID p_probe) const=0; + virtual void gi_probe_set_cell_size(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_cell_size(RID p_probe) const = 0; - virtual void gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform)=0; - virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const=0; + virtual void gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform) = 0; + virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const = 0; - virtual void gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data)=0; - virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const=0; + virtual void gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data) = 0; + virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const = 0; - virtual void gi_probe_set_dynamic_range(RID p_probe,int p_range)=0; - virtual int gi_probe_get_dynamic_range(RID p_probe) const=0; + virtual void gi_probe_set_dynamic_range(RID p_probe, int p_range) = 0; + virtual int gi_probe_get_dynamic_range(RID p_probe) const = 0; - virtual void gi_probe_set_energy(RID p_probe,float p_range)=0; - virtual float gi_probe_get_energy(RID p_probe) const=0; + virtual void gi_probe_set_energy(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_energy(RID p_probe) const = 0; - virtual void gi_probe_set_bias(RID p_probe,float p_range)=0; - virtual float gi_probe_get_bias(RID p_probe) const=0; + virtual void gi_probe_set_bias(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_bias(RID p_probe) const = 0; - virtual void gi_probe_set_propagation(RID p_probe,float p_range)=0; - virtual float gi_probe_get_propagation(RID p_probe) const=0; + virtual void gi_probe_set_propagation(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_propagation(RID p_probe) const = 0; - virtual void gi_probe_set_interior(RID p_probe,bool p_enable)=0; - virtual bool gi_probe_is_interior(RID p_probe) const=0; + virtual void gi_probe_set_interior(RID p_probe, bool p_enable) = 0; + virtual bool gi_probe_is_interior(RID p_probe) const = 0; - virtual void gi_probe_set_compress(RID p_probe,bool p_enable)=0; - virtual bool gi_probe_is_compressed(RID p_probe) const=0; + virtual void gi_probe_set_compress(RID p_probe, bool p_enable) = 0; + virtual bool gi_probe_is_compressed(RID p_probe) const = 0; - virtual uint32_t gi_probe_get_version(RID p_probe)=0; + virtual uint32_t gi_probe_get_version(RID p_probe) = 0; enum GIProbeCompression { GI_PROBE_UNCOMPRESSED, @@ -452,41 +434,37 @@ public: GI_PROBE_ETC2 }; - virtual GIProbeCompression gi_probe_get_dynamic_data_get_preferred_compression() const=0; - virtual RID gi_probe_dynamic_data_create(int p_width,int p_height,int p_depth,GIProbeCompression p_compression)=0; - virtual void gi_probe_dynamic_data_update(RID p_gi_probe_data,int p_depth_slice,int p_slice_count,int p_mipmap,const void* p_data)=0; - + virtual GIProbeCompression gi_probe_get_dynamic_data_get_preferred_compression() const = 0; + virtual RID gi_probe_dynamic_data_create(int p_width, int p_height, int p_depth, GIProbeCompression p_compression) = 0; + virtual void gi_probe_dynamic_data_update(RID p_gi_probe_data, int p_depth_slice, int p_slice_count, int p_mipmap, const void *p_data) = 0; /* PARTICLES */ - virtual RID particles_create()=0; - - virtual void particles_set_emitting(RID p_particles,bool p_emitting)=0; - virtual void particles_set_amount(RID p_particles,int p_amount)=0; - virtual void particles_set_lifetime(RID p_particles,float p_lifetime)=0; - virtual void particles_set_pre_process_time(RID p_particles,float p_time)=0; - virtual void particles_set_explosiveness_ratio(RID p_particles,float p_ratio)=0; - virtual void particles_set_randomness_ratio(RID p_particles,float p_ratio)=0; - virtual void particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb)=0; - virtual void particles_set_gravity(RID p_particles,const Vector3& p_gravity)=0; - virtual void particles_set_use_local_coordinates(RID p_particles,bool p_enable)=0; - virtual void particles_set_process_material(RID p_particles,RID p_material)=0; - - virtual void particles_set_emission_shape(RID p_particles,VS::ParticlesEmissionShape p_shape)=0; - virtual void particles_set_emission_sphere_radius(RID p_particles,float p_radius)=0; - virtual void particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents)=0; - virtual void particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points)=0; + virtual RID particles_create() = 0; + virtual void particles_set_emitting(RID p_particles, bool p_emitting) = 0; + virtual void particles_set_amount(RID p_particles, int p_amount) = 0; + virtual void particles_set_lifetime(RID p_particles, float p_lifetime) = 0; + virtual void particles_set_pre_process_time(RID p_particles, float p_time) = 0; + virtual void particles_set_explosiveness_ratio(RID p_particles, float p_ratio) = 0; + virtual void particles_set_randomness_ratio(RID p_particles, float p_ratio) = 0; + virtual void particles_set_custom_aabb(RID p_particles, const Rect3 &p_aabb) = 0; + virtual void particles_set_gravity(RID p_particles, const Vector3 &p_gravity) = 0; + virtual void particles_set_use_local_coordinates(RID p_particles, bool p_enable) = 0; + virtual void particles_set_process_material(RID p_particles, RID p_material) = 0; - virtual void particles_set_draw_order(RID p_particles,VS::ParticlesDrawOrder p_order)=0; + virtual void particles_set_emission_shape(RID p_particles, VS::ParticlesEmissionShape p_shape) = 0; + virtual void particles_set_emission_sphere_radius(RID p_particles, float p_radius) = 0; + virtual void particles_set_emission_box_extents(RID p_particles, const Vector3 &p_extents) = 0; + virtual void particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points) = 0; - virtual void particles_set_draw_passes(RID p_particles,int p_count)=0; - virtual void particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material)=0; - virtual void particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh)=0; - - virtual Rect3 particles_get_current_aabb(RID p_particles)=0; + virtual void particles_set_draw_order(RID p_particles, VS::ParticlesDrawOrder p_order) = 0; + virtual void particles_set_draw_passes(RID p_particles, int p_count) = 0; + virtual void particles_set_draw_pass_material(RID p_particles, int p_pass, RID p_material) = 0; + virtual void particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) = 0; + virtual Rect3 particles_get_current_aabb(RID p_particles) = 0; /* RENDER TARGET */ @@ -499,57 +477,47 @@ public: RENDER_TARGET_FLAG_MAX }; - virtual RID render_target_create()=0; - virtual void render_target_set_size(RID p_render_target,int p_width, int p_height)=0; - virtual RID render_target_get_texture(RID p_render_target) const=0; - virtual void render_target_set_flag(RID p_render_target,RenderTargetFlags p_flag,bool p_value)=0; - virtual bool render_target_renedered_in_frame(RID p_render_target)=0; - virtual void render_target_set_msaa(RID p_render_target,VS::ViewportMSAA p_msaa)=0; - + virtual RID render_target_create() = 0; + virtual void render_target_set_size(RID p_render_target, int p_width, int p_height) = 0; + virtual RID render_target_get_texture(RID p_render_target) const = 0; + virtual void render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) = 0; + virtual bool render_target_renedered_in_frame(RID p_render_target) = 0; + virtual void render_target_set_msaa(RID p_render_target, VS::ViewportMSAA p_msaa) = 0; /* CANVAS SHADOW */ - virtual RID canvas_light_shadow_buffer_create(int p_width)=0; + virtual RID canvas_light_shadow_buffer_create(int p_width) = 0; /* LIGHT SHADOW MAPPING */ - virtual RID canvas_light_occluder_create()=0; - virtual void canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2>& p_lines)=0; - + virtual RID canvas_light_occluder_create() = 0; + virtual void canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2> &p_lines) = 0; - virtual VS::InstanceType get_base_type(RID p_rid) const=0; - virtual bool free(RID p_rid)=0; + virtual VS::InstanceType get_base_type(RID p_rid) const = 0; + virtual bool free(RID p_rid) = 0; - virtual bool has_os_feature(const String& p_feature) const=0; + virtual bool has_os_feature(const String &p_feature) const = 0; - virtual void update_dirty_resources()=0; + virtual void update_dirty_resources() = 0; - static RasterizerStorage*base_signleton; + static RasterizerStorage *base_signleton; RasterizerStorage(); virtual ~RasterizerStorage() {} }; - - - - class RasterizerCanvas { public: - enum CanvasRectFlags { - CANVAS_RECT_REGION=1, - CANVAS_RECT_TILE=2, - CANVAS_RECT_FLIP_H=4, - CANVAS_RECT_FLIP_V=8, - CANVAS_RECT_TRANSPOSE=16 + CANVAS_RECT_REGION = 1, + CANVAS_RECT_TILE = 2, + CANVAS_RECT_FLIP_H = 4, + CANVAS_RECT_FLIP_V = 8, + CANVAS_RECT_TRANSPOSE = 16 }; - struct Light : public RID_Data { - - bool enabled; Color color; Transform2D xform; @@ -572,7 +540,6 @@ public: VS::CanvasLightShadowFilter shadow_filter; Color shadow_color; - void *texture_cache; // implementation dependent Rect2 rect_cache; Transform2D xform_cache; @@ -590,33 +557,32 @@ public: RID light_internal; Light() { - enabled=true; - color=Color(1,1,1); - shadow_color=Color(0,0,0,0); - height=0; - z_min=-1024; - z_max=1024; - layer_min=0; - layer_max=0; - item_mask=1; - scale=1.0; - energy=1.0; - item_shadow_mask=-1; - mode=VS::CANVAS_LIGHT_MODE_ADD; - texture_cache=NULL; - next_ptr=NULL; - mask_next_ptr=NULL; - filter_next_ptr=NULL; - shadow_buffer_size=256; - shadow_gradient_length=0; - shadow_filter=VS::CANVAS_LIGHT_FILTER_NONE; - + enabled = true; + color = Color(1, 1, 1); + shadow_color = Color(0, 0, 0, 0); + height = 0; + z_min = -1024; + z_max = 1024; + layer_min = 0; + layer_max = 0; + item_mask = 1; + scale = 1.0; + energy = 1.0; + item_shadow_mask = -1; + mode = VS::CANVAS_LIGHT_MODE_ADD; + texture_cache = NULL; + next_ptr = NULL; + mask_next_ptr = NULL; + filter_next_ptr = NULL; + shadow_buffer_size = 256; + shadow_gradient_length = 0; + shadow_filter = VS::CANVAS_LIGHT_FILTER_NONE; } }; - virtual RID light_internal_create()=0; - virtual void light_internal_update(RID p_rid, Light* p_light)=0; - virtual void light_internal_free(RID p_rid)=0; + virtual RID light_internal_create() = 0; + virtual void light_internal_update(RID p_rid, Light *p_light) = 0; + virtual void light_internal_free(RID p_rid) = 0; struct Item : public RID_Data { @@ -637,12 +603,12 @@ public: }; Type type; - virtual ~Command(){} + virtual ~Command() {} }; struct CommandLine : public Command { - Point2 from,to; + Point2 from, to; Color color; float width; bool antialiased; @@ -657,7 +623,10 @@ public: Rect2 source; uint8_t flags; - CommandRect() { flags=0; type = TYPE_RECT; } + CommandRect() { + flags = 0; + type = TYPE_RECT; + } }; struct CommandNinePatch : public Command { @@ -670,7 +639,10 @@ public: Color color; VS::NinePatchAxisMode axis_x; VS::NinePatchAxisMode axis_y; - CommandNinePatch() { draw_center=true; type = TYPE_NINEPATCH; } + CommandNinePatch() { + draw_center = true; + type = TYPE_NINEPATCH; + } }; struct CommandPrimitive : public Command { @@ -681,7 +653,10 @@ public: RID texture; float width; - CommandPrimitive() { type = TYPE_PRIMITIVE; width=1;} + CommandPrimitive() { + type = TYPE_PRIMITIVE; + width = 1; + } }; struct CommandPolygon : public Command { @@ -693,22 +668,24 @@ public: RID texture; int count; - CommandPolygon() { type = TYPE_POLYGON; count = 0; } + CommandPolygon() { + type = TYPE_POLYGON; + count = 0; + } }; - struct CommandMesh : public Command { RID mesh; RID skeleton; - CommandMesh() { type = TYPE_MESH; } + CommandMesh() { type = TYPE_MESH; } }; struct CommandMultiMesh : public Command { RID multimesh; RID skeleton; - CommandMultiMesh() { type = TYPE_MULTIMESH; } + CommandMultiMesh() { type = TYPE_MULTIMESH; } }; struct CommandCircle : public Command { @@ -725,17 +702,18 @@ public: CommandTransform() { type = TYPE_TRANSFORM; } }; - struct CommandClipIgnore : public Command { bool ignore; - CommandClipIgnore() { type = TYPE_CLIP_IGNORE; ignore=false; } + CommandClipIgnore() { + type = TYPE_CLIP_IGNORE; + ignore = false; + } }; - struct ViewportRender { - VisualServer*owner; - void* udata; + VisualServer *owner; + void *udata; Rect2 rect; }; @@ -745,12 +723,12 @@ public: bool behind; //VS::MaterialBlendMode blend_mode; int light_mask; - Vector<Command*> commands; + Vector<Command *> commands; mutable bool custom_rect; mutable bool rect_dirty; mutable Rect2 rect; RID material; - Item*next; + Item *next; struct CopyBackBuffer { Rect2 rect; @@ -759,110 +737,106 @@ public: }; CopyBackBuffer *copy_back_buffer; - Color final_modulate; Transform2D final_transform; Rect2 final_clip_rect; - Item* final_clip_owner; - Item* material_owner; + Item *final_clip_owner; + Item *material_owner; ViewportRender *vp_render; bool distance_field; bool light_masked; Rect2 global_rect_cache; - const Rect2& get_rect() const { + const Rect2 &get_rect() const { if (custom_rect || !rect_dirty) return rect; //must update rect - int s=commands.size(); - if (s==0) { + int s = commands.size(); + if (s == 0) { - rect=Rect2(); - rect_dirty=false; + rect = Rect2(); + rect_dirty = false; return rect; } Transform2D xf; - bool found_xform=false; - bool first=true; - - const Item::Command * const *cmd = &commands[0]; + bool found_xform = false; + bool first = true; + const Item::Command *const *cmd = &commands[0]; - for (int i=0;i<s;i++) { + for (int i = 0; i < s; i++) { - const Item::Command *c=cmd[i]; + const Item::Command *c = cmd[i]; Rect2 r; - switch(c->type) { + switch (c->type) { case Item::Command::TYPE_LINE: { - const Item::CommandLine* line = static_cast< const Item::CommandLine*>(c); - r.pos=line->from; + const Item::CommandLine *line = static_cast<const Item::CommandLine *>(c); + r.pos = line->from; r.expand_to(line->to); } break; case Item::Command::TYPE_RECT: { - const Item::CommandRect* crect = static_cast< const Item::CommandRect*>(c); - r=crect->rect; + const Item::CommandRect *crect = static_cast<const Item::CommandRect *>(c); + r = crect->rect; } break; case Item::Command::TYPE_NINEPATCH: { - const Item::CommandNinePatch* style = static_cast< const Item::CommandNinePatch*>(c); - r=style->rect; + const Item::CommandNinePatch *style = static_cast<const Item::CommandNinePatch *>(c); + r = style->rect; } break; case Item::Command::TYPE_PRIMITIVE: { - const Item::CommandPrimitive* primitive = static_cast< const Item::CommandPrimitive*>(c); - r.pos=primitive->points[0]; - for(int i=1;i<primitive->points.size();i++) { + const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c); + r.pos = primitive->points[0]; + for (int i = 1; i < primitive->points.size(); i++) { r.expand_to(primitive->points[i]); - } } break; case Item::Command::TYPE_POLYGON: { - const Item::CommandPolygon* polygon = static_cast< const Item::CommandPolygon*>(c); + const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c); int l = polygon->points.size(); - const Point2*pp=&polygon->points[0]; - r.pos=pp[0]; - for(int i=1;i<l;i++) { + const Point2 *pp = &polygon->points[0]; + r.pos = pp[0]; + for (int i = 1; i < l; i++) { r.expand_to(pp[i]); - } } break; case Item::Command::TYPE_MESH: { - const Item::CommandMesh* mesh = static_cast< const Item::CommandMesh*>(c); - Rect3 aabb = RasterizerStorage::base_signleton->mesh_get_aabb(mesh->mesh,mesh->skeleton); + const Item::CommandMesh *mesh = static_cast<const Item::CommandMesh *>(c); + Rect3 aabb = RasterizerStorage::base_signleton->mesh_get_aabb(mesh->mesh, mesh->skeleton); - r=Rect2(aabb.pos.x,aabb.pos.y,aabb.size.x,aabb.size.y); + r = Rect2(aabb.pos.x, aabb.pos.y, aabb.size.x, aabb.size.y); } break; case Item::Command::TYPE_MULTIMESH: { - const Item::CommandMultiMesh* multimesh = static_cast< const Item::CommandMultiMesh*>(c); + const Item::CommandMultiMesh *multimesh = static_cast<const Item::CommandMultiMesh *>(c); Rect3 aabb = RasterizerStorage::base_signleton->multimesh_get_aabb(multimesh->multimesh); - r=Rect2(aabb.pos.x,aabb.pos.y,aabb.size.x,aabb.size.y); + r = Rect2(aabb.pos.x, aabb.pos.y, aabb.size.x, aabb.size.y); } break; case Item::Command::TYPE_CIRCLE: { - const Item::CommandCircle* circle = static_cast< const Item::CommandCircle*>(c); - r.pos=Point2(-circle->radius,-circle->radius)+circle->pos; - r.size=Point2(circle->radius*2.0,circle->radius*2.0); + const Item::CommandCircle *circle = static_cast<const Item::CommandCircle *>(c); + r.pos = Point2(-circle->radius, -circle->radius) + circle->pos; + r.size = Point2(circle->radius * 2.0, circle->radius * 2.0); } break; case Item::Command::TYPE_TRANSFORM: { - const Item::CommandTransform* transform = static_cast<const Item::CommandTransform*>(c); - xf=transform->xform; - found_xform=true; + const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c); + xf = transform->xform; + found_xform = true; continue; } break; @@ -873,37 +847,59 @@ public: if (found_xform) { r = xf.xform(r); - found_xform=false; + found_xform = false; } - if (first) { - rect=r; - first=false; + rect = r; + first = false; } else - rect=rect.merge(r); + rect = rect.merge(r); } - rect_dirty=false; + rect_dirty = false; return rect; } - void clear() { for (int i=0;i<commands.size();i++) memdelete( commands[i] ); commands.clear(); clip=false; rect_dirty=true; final_clip_owner=NULL; material_owner=NULL; light_masked=false; } - Item() { light_mask=1; vp_render=NULL; next=NULL; final_clip_owner=NULL; clip=false; final_modulate=Color(1,1,1,1); visible=true; rect_dirty=true; custom_rect=false; behind=false; material_owner=NULL; copy_back_buffer=NULL; distance_field=false; light_masked=false; } - virtual ~Item() { clear(); if (copy_back_buffer) memdelete(copy_back_buffer); } + void clear() { + for (int i = 0; i < commands.size(); i++) + memdelete(commands[i]); + commands.clear(); + clip = false; + rect_dirty = true; + final_clip_owner = NULL; + material_owner = NULL; + light_masked = false; + } + Item() { + light_mask = 1; + vp_render = NULL; + next = NULL; + final_clip_owner = NULL; + clip = false; + final_modulate = Color(1, 1, 1, 1); + visible = true; + rect_dirty = true; + custom_rect = false; + behind = false; + material_owner = NULL; + copy_back_buffer = NULL; + distance_field = false; + light_masked = false; + } + virtual ~Item() { + clear(); + if (copy_back_buffer) memdelete(copy_back_buffer); + } }; + virtual void canvas_begin() = 0; - virtual void canvas_begin()=0; - - virtual void canvas_render_items(Item *p_item_list,int p_z,const Color& p_modulate,Light *p_light)=0; - virtual void canvas_debug_viewport_shadows(Light* p_lights_with_shadow)=0; - - + virtual void canvas_render_items(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light) = 0; + virtual void canvas_debug_viewport_shadows(Light *p_lights_with_shadow) = 0; struct LightOccluderInstance : public RID_Data { - bool enabled; RID canvas; RID polygon; @@ -916,52 +912,52 @@ public: LightOccluderInstance *next; - LightOccluderInstance() { enabled=true; next=NULL; light_mask=1; cull_cache=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; } + LightOccluderInstance() { + enabled = true; + next = NULL; + light_mask = 1; + cull_cache = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; + } }; + virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache) = 0; - - virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, LightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache)=0; - - - virtual void reset_canvas()=0; + virtual void reset_canvas() = 0; virtual ~RasterizerCanvas() {} }; - class Rasterizer { protected: - static Rasterizer* (*_create_func)(); + static Rasterizer *(*_create_func)(); + public: static Rasterizer *create(); - virtual RasterizerStorage *get_storage()=0; - virtual RasterizerCanvas *get_canvas()=0; - virtual RasterizerScene *get_scene()=0; - - virtual void initialize()=0; - virtual void begin_frame()=0; - virtual void set_current_render_target(RID p_render_target)=0; - virtual void restore_render_target()=0; - virtual void clear_render_target(const Color& p_color)=0; - virtual void blit_render_target_to_screen(RID p_render_target,const Rect2& p_screen_rect,int p_screen=0)=0; - virtual void end_frame()=0; - virtual void finalize()=0; + virtual RasterizerStorage *get_storage() = 0; + virtual RasterizerCanvas *get_canvas() = 0; + virtual RasterizerScene *get_scene() = 0; + virtual void initialize() = 0; + virtual void begin_frame() = 0; + virtual void set_current_render_target(RID p_render_target) = 0; + virtual void restore_render_target() = 0; + virtual void clear_render_target(const Color &p_color) = 0; + virtual void blit_render_target_to_screen(RID p_render_target, const Rect2 &p_screen_rect, int p_screen = 0) = 0; + virtual void end_frame() = 0; + virtual void finalize() = 0; virtual ~Rasterizer() {} }; - #if 0 /** @author Juan Linietsky <reduzio@gmail.com> */ -#include "servers/visual_server.h" #include "camera_matrix.h" #include "map.h" #include "self_list.h" +#include "servers/visual_server.h" class Rasterizer { protected: @@ -1975,6 +1971,5 @@ public: virtual ~Rasterizer() {} }; - #endif #endif diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp index c680013efa..3bc495f08e 100644 --- a/servers/visual/shader_language.cpp +++ b/servers/visual/shader_language.cpp @@ -27,69 +27,66 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "shader_language.h" -#include "print_string.h" #include "os/os.h" +#include "print_string.h" 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'); } - String ShaderLanguage::get_operator_text(Operator p_op) { - static const char* op_names[OP_MAX]={"==", - "!=", - "<", - "<=", - ">", - ">=", - "&&", - "||", - "!", - "-", - "+", - "-", - "*", - "/", - "%", - "<<", - ">>", - "=", - "+=", - "-=", - "*=", - "/=", - "%=", - "<<=", - ">>=", - "&=", - "|=", - "^=", - "&", - "|", - "^", - "~", - "++" - "--", - "()", - "construct"}; + static const char *op_names[OP_MAX] = { "==", + "!=", + "<", + "<=", + ">", + ">=", + "&&", + "||", + "!", + "-", + "+", + "-", + "*", + "/", + "%", + "<<", + ">>", + "=", + "+=", + "-=", + "*=", + "/=", + "%=", + "<<=", + ">>=", + "&=", + "|=", + "^=", + "&", + "|", + "^", + "~", + "++" + "--", + "()", + "construct" }; return op_names[p_op]; - } - -const char * ShaderLanguage::token_names[TK_MAX]={ +const char *ShaderLanguage::token_names[TK_MAX] = { "EMPTY", "IDENTIFIER", "TRUE", @@ -195,94 +192,92 @@ const char * ShaderLanguage::token_names[TK_MAX]={ String ShaderLanguage::get_token_text(Token p_token) { - String name=token_names[p_token.type]; - if (p_token.type==TK_INT_CONSTANT || p_token.type==TK_REAL_CONSTANT) { - name+="("+rtos(p_token.constant)+")"; - } else if (p_token.type==TK_IDENTIFIER) { - name+="("+String(p_token.text)+")"; - } else if (p_token.type==TK_ERROR) { - name+="("+String(p_token.text)+")"; + String name = token_names[p_token.type]; + if (p_token.type == TK_INT_CONSTANT || p_token.type == TK_REAL_CONSTANT) { + name += "(" + rtos(p_token.constant) + ")"; + } else if (p_token.type == TK_IDENTIFIER) { + name += "(" + String(p_token.text) + ")"; + } else if (p_token.type == TK_ERROR) { + name += "(" + String(p_token.text) + ")"; } return name; } -ShaderLanguage::Token ShaderLanguage::_make_token(TokenType p_type,const StringName& p_text) { +ShaderLanguage::Token ShaderLanguage::_make_token(TokenType p_type, const StringName &p_text) { Token tk; - tk.type=p_type; - tk.text=p_text; - tk.line=tk_line; - if (tk.type==TK_ERROR) { + tk.type = p_type; + tk.text = p_text; + tk.line = tk_line; + if (tk.type == TK_ERROR) { _set_error(p_text); } return tk; } -const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[]={ - {TK_TRUE,"true"}, - {TK_FALSE,"false"}, - {TK_TYPE_VOID,"void"}, - {TK_TYPE_BOOL,"bool"}, - {TK_TYPE_BVEC2,"bvec2"}, - {TK_TYPE_BVEC3,"bvec3"}, - {TK_TYPE_BVEC4,"bvec4"}, - {TK_TYPE_INT,"int"}, - {TK_TYPE_IVEC2,"ivec2"}, - {TK_TYPE_IVEC3,"ivec3"}, - {TK_TYPE_IVEC4,"ivec4"}, - {TK_TYPE_UINT,"uint"}, - {TK_TYPE_UVEC2,"uvec2"}, - {TK_TYPE_UVEC3,"uvec3"}, - {TK_TYPE_UVEC4,"uvec4"}, - {TK_TYPE_FLOAT,"float"}, - {TK_TYPE_VEC2,"vec2"}, - {TK_TYPE_VEC3,"vec3"}, - {TK_TYPE_VEC4,"vec4"}, - {TK_TYPE_MAT2,"mat2"}, - {TK_TYPE_MAT3,"mat3"}, - {TK_TYPE_MAT4,"mat4"}, - {TK_TYPE_SAMPLER2D,"sampler2D"}, - {TK_TYPE_ISAMPLER2D,"isampler2D"}, - {TK_TYPE_USAMPLER2D,"usampler2D"}, - {TK_TYPE_SAMPLERCUBE,"samplerCube"}, - {TK_PRECISION_LOW,"lowp"}, - {TK_PRECISION_MID,"mediump"}, - {TK_PRECISION_HIGH,"highp"}, - {TK_CF_IF,"if"}, - {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_UNIFORM,"uniform"}, - {TK_VARYING,"varying"}, - {TK_RENDER_MODE,"render_mode"}, - {TK_HINT_WHITE_TEXTURE,"hint_white"}, - {TK_HINT_BLACK_TEXTURE,"hint_black"}, - {TK_HINT_NORMAL_TEXTURE,"hint_normal"}, - {TK_HINT_ANISO_TEXTURE,"hint_aniso"}, - {TK_HINT_ALBEDO_TEXTURE,"hint_albedo"}, - {TK_HINT_BLACK_ALBEDO_TEXTURE,"hint_black_albedo"}, - {TK_HINT_COLOR,"hint_color"}, - {TK_HINT_RANGE,"hint_range"}, - - {TK_ERROR,NULL} +const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[] = { + { TK_TRUE, "true" }, + { TK_FALSE, "false" }, + { TK_TYPE_VOID, "void" }, + { TK_TYPE_BOOL, "bool" }, + { TK_TYPE_BVEC2, "bvec2" }, + { TK_TYPE_BVEC3, "bvec3" }, + { TK_TYPE_BVEC4, "bvec4" }, + { TK_TYPE_INT, "int" }, + { TK_TYPE_IVEC2, "ivec2" }, + { TK_TYPE_IVEC3, "ivec3" }, + { TK_TYPE_IVEC4, "ivec4" }, + { TK_TYPE_UINT, "uint" }, + { TK_TYPE_UVEC2, "uvec2" }, + { TK_TYPE_UVEC3, "uvec3" }, + { TK_TYPE_UVEC4, "uvec4" }, + { TK_TYPE_FLOAT, "float" }, + { TK_TYPE_VEC2, "vec2" }, + { TK_TYPE_VEC3, "vec3" }, + { TK_TYPE_VEC4, "vec4" }, + { TK_TYPE_MAT2, "mat2" }, + { TK_TYPE_MAT3, "mat3" }, + { TK_TYPE_MAT4, "mat4" }, + { TK_TYPE_SAMPLER2D, "sampler2D" }, + { TK_TYPE_ISAMPLER2D, "isampler2D" }, + { TK_TYPE_USAMPLER2D, "usampler2D" }, + { TK_TYPE_SAMPLERCUBE, "samplerCube" }, + { TK_PRECISION_LOW, "lowp" }, + { TK_PRECISION_MID, "mediump" }, + { TK_PRECISION_HIGH, "highp" }, + { TK_CF_IF, "if" }, + { 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_UNIFORM, "uniform" }, + { TK_VARYING, "varying" }, + { TK_RENDER_MODE, "render_mode" }, + { TK_HINT_WHITE_TEXTURE, "hint_white" }, + { TK_HINT_BLACK_TEXTURE, "hint_black" }, + { TK_HINT_NORMAL_TEXTURE, "hint_normal" }, + { TK_HINT_ANISO_TEXTURE, "hint_aniso" }, + { TK_HINT_ALBEDO_TEXTURE, "hint_albedo" }, + { TK_HINT_BLACK_ALBEDO_TEXTURE, "hint_black_albedo" }, + { TK_HINT_COLOR, "hint_color" }, + { TK_HINT_RANGE, "hint_range" }, + + { TK_ERROR, NULL } }; - - ShaderLanguage::Token ShaderLanguage::_get_token() { -#define GETCHAR(m_idx) (((char_idx+m_idx)<code.length())?code[char_idx+m_idx]:CharType(0)) +#define GETCHAR(m_idx) (((char_idx + m_idx) < code.length()) ? code[char_idx + m_idx] : CharType(0)) - while(true) { + while (true) { char_idx++; - switch(GETCHAR(-1)) { + switch (GETCHAR(-1)) { case 0: return _make_token(TK_EOF); @@ -297,17 +292,18 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { continue; case '/': { - switch(GETCHAR(0)) { + switch (GETCHAR(0)) { case '*': { // block comment char_idx++; - while(true) { - if (GETCHAR(0)==0) { + while (true) { + if (GETCHAR(0) == 0) { return _make_token(TK_EOF); - } if (GETCHAR(0)=='*' && GETCHAR(1)=='/') { - char_idx+=2; + } + if (GETCHAR(0) == '*' && GETCHAR(1) == '/') { + char_idx += 2; break; - } else if (GETCHAR(0)=='\n') { + } else if (GETCHAR(0) == '\n') { tk_line++; } @@ -317,13 +313,12 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '/': { // line comment skip - - while(true) { - if (GETCHAR(0)=='\n') { + while (true) { + if (GETCHAR(0) == '\n') { char_idx++; break; } - if (GETCHAR(0)==0) { + if (GETCHAR(0) == 0) { return _make_token(TK_EOF); } char_idx++; @@ -344,7 +339,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '=': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_EQUAL); } @@ -353,12 +348,12 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '<': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_LESS_EQUAL); - } else if (GETCHAR(0)=='<') { + } else if (GETCHAR(0) == '<') { char_idx++; - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_SHIFT_LEFT); } @@ -370,12 +365,12 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '>': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_GREATER_EQUAL); - } else if (GETCHAR(0)=='<') { + } else if (GETCHAR(0) == '<') { char_idx++; - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_SHIFT_RIGHT); } @@ -387,7 +382,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '!': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_NOT_EQUAL); } @@ -422,10 +417,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { case '~': return _make_token(TK_OP_BIT_INVERT); case '&': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_BIT_AND); - } else if (GETCHAR(0)=='&') { + } else if (GETCHAR(0) == '&') { char_idx++; return _make_token(TK_OP_AND); } @@ -433,10 +428,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '|': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_BIT_OR); - } else if (GETCHAR(0)=='|') { + } else if (GETCHAR(0) == '|') { char_idx++; return _make_token(TK_OP_OR); } @@ -445,7 +440,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '*': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_MUL); } @@ -453,10 +448,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '+': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_ADD); - } else if (GETCHAR(0)=='+') { + } else if (GETCHAR(0) == '+') { char_idx++; return _make_token(TK_OP_INCREMENT); @@ -466,10 +461,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '-': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_SUB); - }else if (GETCHAR(0)=='-') { + } else if (GETCHAR(0) == '-') { char_idx++; return _make_token(TK_OP_DECREMENT); @@ -479,7 +474,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { } break; case '%': { - if (GETCHAR(0)=='=') { + if (GETCHAR(0) == '=') { char_idx++; return _make_token(TK_OP_ASSIGN_MOD); } @@ -490,69 +485,68 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { char_idx--; //go back one, since we have no idea what this is - 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 minus_exponent_found=false; + bool period_found = false; + bool exponent_found = false; + bool hexa_found = false; + bool sign_found = false; + bool minus_exponent_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) - return _make_token(TK_ERROR,"Invalid numeric constant"); - period_found=true; - } else if (GETCHAR(i)=='x') { - if (hexa_found || str.length()!=1 || str[0]!='0') - return _make_token(TK_ERROR,"Invalid numeric constant"); - hexa_found=true; - } else if (GETCHAR(i)=='e') { + return _make_token(TK_ERROR, "Invalid numeric constant"); + period_found = true; + } else if (GETCHAR(i) == 'x') { + if (hexa_found || str.length() != 1 || str[0] != '0') + return _make_token(TK_ERROR, "Invalid numeric constant"); + hexa_found = true; + } else if (GETCHAR(i) == 'e') { if (hexa_found || exponent_found) - return _make_token(TK_ERROR,"Invalid numeric constant"); - exponent_found=true; + return _make_token(TK_ERROR, "Invalid numeric constant"); + 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) - return _make_token(TK_ERROR,"Invalid numeric constant"); - sign_found=true; - if (GETCHAR(i)=='-') - minus_exponent_found=true; + return _make_token(TK_ERROR, "Invalid numeric constant"); + sign_found = true; + if (GETCHAR(i) == '-') + minus_exponent_found = true; } else break; - str+=CharType(GETCHAR(i)); + str += CharType(GETCHAR(i)); i++; } - if (!_is_number(str[str.length()-1])) - return _make_token(TK_ERROR,"Invalid numeric constant"); + if (!_is_number(str[str.length() - 1])) + return _make_token(TK_ERROR, "Invalid numeric constant"); - char_idx+=str.length(); + char_idx += str.length(); Token tk; if (period_found || minus_exponent_found) - tk.type=TK_REAL_CONSTANT; + tk.type = TK_REAL_CONSTANT; else - tk.type=TK_INT_CONSTANT; + tk.type = TK_INT_CONSTANT; if (!str.is_valid_float()) { - return _make_token(TK_ERROR,"Invalid numeric constant"); + return _make_token(TK_ERROR, "Invalid numeric constant"); } - tk.constant=str.to_double(); - tk.line=tk_line; + tk.constant = str.to_double(); + tk.line = tk_line; return tk; - } - if (GETCHAR(0)=='.') { + if (GETCHAR(0) == '.') { //parse period char_idx++; return _make_token(TK_PERIOD); @@ -562,33 +556,32 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { // parse identifier String str; - while(_is_text_char(GETCHAR(0))) { + while (_is_text_char(GETCHAR(0))) { - str+=CharType(GETCHAR(0)); + str += CharType(GETCHAR(0)); char_idx++; } //see if keyword //should be converted to a static map - int idx=0; + int idx = 0; - while(keyword_list[idx].text) { + while (keyword_list[idx].text) { - if (str==keyword_list[idx].text) { + if (str == keyword_list[idx].text) { return _make_token(keyword_list[idx].token); } idx++; } - - return _make_token(TK_IDENTIFIER,str); + return _make_token(TK_IDENTIFIER, str); } - if (GETCHAR(0)>32) - return _make_token(TK_ERROR,"Tokenizer: Unknown character #"+itos(GETCHAR(0))+": '"+String::chr(GETCHAR(0))+"'"); + if (GETCHAR(0) > 32) + return _make_token(TK_ERROR, "Tokenizer: Unknown character #" + itos(GETCHAR(0)) + ": '" + String::chr(GETCHAR(0)) + "'"); else - return _make_token(TK_ERROR,"Tokenizer: Unknown character #"+itos(GETCHAR(0))); + return _make_token(TK_ERROR, "Tokenizer: Unknown character #" + itos(GETCHAR(0))); } break; } @@ -597,85 +590,79 @@ ShaderLanguage::Token ShaderLanguage::_get_token() { return Token(); } - -String ShaderLanguage::token_debug(const String& p_code) { +String ShaderLanguage::token_debug(const String &p_code) { clear(); - code=p_code; + code = p_code; String output; Token tk = _get_token(); - while(tk.type!=TK_EOF && tk.type!=TK_ERROR) { + while (tk.type != TK_EOF && tk.type != TK_ERROR) { - output+=itos(tk_line)+": "+get_token_text(tk)+"\n"; + output += itos(tk_line) + ": " + get_token_text(tk) + "\n"; tk = _get_token(); } return output; - } bool ShaderLanguage::is_token_datatype(TokenType p_type) { return ( - p_type==TK_TYPE_VOID || - p_type==TK_TYPE_BOOL || - p_type==TK_TYPE_BVEC2 || - p_type==TK_TYPE_BVEC3 || - p_type==TK_TYPE_BVEC4 || - p_type==TK_TYPE_INT || - p_type==TK_TYPE_IVEC2 || - p_type==TK_TYPE_IVEC3 || - p_type==TK_TYPE_IVEC4 || - p_type==TK_TYPE_UINT || - p_type==TK_TYPE_UVEC2 || - p_type==TK_TYPE_UVEC3 || - p_type==TK_TYPE_UVEC4 || - p_type==TK_TYPE_FLOAT || - p_type==TK_TYPE_VEC2 || - p_type==TK_TYPE_VEC3 || - p_type==TK_TYPE_VEC4 || - p_type==TK_TYPE_MAT2 || - p_type==TK_TYPE_MAT3 || - p_type==TK_TYPE_MAT4 || - p_type==TK_TYPE_SAMPLER2D || - p_type==TK_TYPE_ISAMPLER2D || - p_type==TK_TYPE_USAMPLER2D || - p_type==TK_TYPE_SAMPLERCUBE ); - + p_type == TK_TYPE_VOID || + p_type == TK_TYPE_BOOL || + p_type == TK_TYPE_BVEC2 || + p_type == TK_TYPE_BVEC3 || + p_type == TK_TYPE_BVEC4 || + p_type == TK_TYPE_INT || + p_type == TK_TYPE_IVEC2 || + p_type == TK_TYPE_IVEC3 || + p_type == TK_TYPE_IVEC4 || + p_type == TK_TYPE_UINT || + p_type == TK_TYPE_UVEC2 || + p_type == TK_TYPE_UVEC3 || + p_type == TK_TYPE_UVEC4 || + p_type == TK_TYPE_FLOAT || + p_type == TK_TYPE_VEC2 || + p_type == TK_TYPE_VEC3 || + p_type == TK_TYPE_VEC4 || + p_type == TK_TYPE_MAT2 || + p_type == TK_TYPE_MAT3 || + p_type == TK_TYPE_MAT4 || + p_type == TK_TYPE_SAMPLER2D || + p_type == TK_TYPE_ISAMPLER2D || + p_type == TK_TYPE_USAMPLER2D || + p_type == TK_TYPE_SAMPLERCUBE); } ShaderLanguage::DataType ShaderLanguage::get_token_datatype(TokenType p_type) { - return DataType(p_type-TK_TYPE_VOID); + return DataType(p_type - TK_TYPE_VOID); } - bool ShaderLanguage::is_token_precision(TokenType p_type) { return ( - p_type==TK_PRECISION_LOW || - p_type==TK_PRECISION_MID || - p_type==TK_PRECISION_HIGH ); - + p_type == TK_PRECISION_LOW || + p_type == TK_PRECISION_MID || + p_type == TK_PRECISION_HIGH); } ShaderLanguage::DataPrecision ShaderLanguage::get_token_precision(TokenType p_type) { - if (p_type==TK_PRECISION_LOW) + if (p_type == TK_PRECISION_LOW) return PRECISION_LOWP; - else if (p_type==TK_PRECISION_HIGH) + else if (p_type == TK_PRECISION_HIGH) return PRECISION_HIGHP; else return PRECISION_MEDIUMP; } - String ShaderLanguage::get_datatype_name(DataType p_type) { - switch(p_type) { + switch (p_type) { case TYPE_VOID: return "void"; case TYPE_BOOL: return "bool"; @@ -706,83 +693,77 @@ String ShaderLanguage::get_datatype_name(DataType p_type) { return ""; } - bool ShaderLanguage::is_token_nonvoid_datatype(TokenType p_type) { - return is_token_datatype(p_type) && p_type!=TK_TYPE_VOID; - + return is_token_datatype(p_type) && p_type != TK_TYPE_VOID; } - void ShaderLanguage::clear() { - current_function=StringName(); + current_function = StringName(); - completion_type=COMPLETION_NONE; - completion_block=NULL; - completion_function=StringName(); + completion_type = COMPLETION_NONE; + completion_block = NULL; + completion_function = StringName(); - error_line=0; - tk_line=1; - char_idx=0; - error_set=false; - error_str=""; - while(nodes) { + error_line = 0; + tk_line = 1; + char_idx = 0; + error_set = false; + error_str = ""; + while (nodes) { Node *n = nodes; - nodes=nodes->next; + nodes = nodes->next; memdelete(n); } - } - -bool ShaderLanguage::_find_identifier(const BlockNode* p_block,const Map<StringName, DataType> &p_builtin_types,const StringName& p_identifier, DataType *r_data_type, IdentifierType *r_type) { - +bool ShaderLanguage::_find_identifier(const BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, const StringName &p_identifier, DataType *r_data_type, IdentifierType *r_type) { if (p_builtin_types.has(p_identifier)) { if (r_data_type) { - *r_data_type=p_builtin_types[p_identifier]; + *r_data_type = p_builtin_types[p_identifier]; } if (r_type) { - *r_type=IDENTIFIER_BUILTIN_VAR; + *r_type = IDENTIFIER_BUILTIN_VAR; } return true; } - FunctionNode *function=NULL; + FunctionNode *function = NULL; - while(p_block) { + while (p_block) { if (p_block->variables.has(p_identifier)) { if (r_data_type) { - *r_data_type=p_block->variables[p_identifier].type; + *r_data_type = p_block->variables[p_identifier].type; } if (r_type) { - *r_type=IDENTIFIER_LOCAL_VAR; + *r_type = IDENTIFIER_LOCAL_VAR; } return true; } if (p_block->parent_function) { - function=p_block->parent_function; + function = p_block->parent_function; break; } else { - ERR_FAIL_COND_V(!p_block->parent_block,false); - p_block=p_block->parent_block; + ERR_FAIL_COND_V(!p_block->parent_block, false); + p_block = p_block->parent_block; } } if (function) { - for(int i=0;i<function->arguments.size();i++) { - if (function->arguments[i].name==p_identifier) { + for (int i = 0; i < function->arguments.size(); i++) { + if (function->arguments[i].name == p_identifier) { if (r_data_type) { - *r_data_type=function->arguments[i].type; + *r_data_type = function->arguments[i].type; } if (r_type) { - *r_type=IDENTIFIER_FUNCTION_ARGUMENT; + *r_type = IDENTIFIER_FUNCTION_ARGUMENT; } return true; @@ -790,59 +771,56 @@ bool ShaderLanguage::_find_identifier(const BlockNode* p_block,const Map<StringN } } - if (shader->varyings.has(p_identifier)) { if (r_data_type) { - *r_data_type=shader->varyings[p_identifier].type; + *r_data_type = shader->varyings[p_identifier].type; } if (r_type) { - *r_type=IDENTIFIER_VARYING; + *r_type = IDENTIFIER_VARYING; } return true; } if (shader->uniforms.has(p_identifier)) { if (r_data_type) { - *r_data_type=shader->uniforms[p_identifier].type; + *r_data_type = shader->uniforms[p_identifier].type; } if (r_type) { - *r_type=IDENTIFIER_UNIFORM; + *r_type = IDENTIFIER_UNIFORM; } return true; } - for(int i=0;i<shader->functions.size();i++) { + for (int i = 0; i < shader->functions.size(); i++) { if (!shader->functions[i].callable) continue; - if (shader->functions[i].name==p_identifier) { + if (shader->functions[i].name == p_identifier) { if (r_data_type) { - *r_data_type=shader->functions[i].function->return_type; + *r_data_type = shader->functions[i].function->return_type; } if (r_type) { - *r_type=IDENTIFIER_FUNCTION; + *r_type = IDENTIFIER_FUNCTION; } } } return false; - } +bool ShaderLanguage::_validate_operator(OperatorNode *p_op, DataType *r_ret_type) { -bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) { - - bool valid=false; + bool valid = false; DataType ret_type; - switch(p_op->op) { + switch (p_op->op) { case OP_EQUAL: case OP_NOT_EQUAL: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - valid=na==nb; - ret_type=TYPE_BOOL; + valid = na == nb; + ret_type = TYPE_BOOL; } break; case OP_LESS: case OP_LESS_EQUAL: @@ -851,8 +829,8 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - valid = na==nb && (na==TYPE_UINT || na==TYPE_INT || na==TYPE_FLOAT); - ret_type=TYPE_BOOL; + valid = na == nb && (na == TYPE_UINT || na == TYPE_INT || na == TYPE_FLOAT); + ret_type = TYPE_BOOL; } break; case OP_AND: @@ -860,15 +838,15 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - valid = na==nb && na==TYPE_BOOL; - ret_type=TYPE_BOOL; + valid = na == nb && na == TYPE_BOOL; + ret_type = TYPE_BOOL; } break; case OP_NOT: { DataType na = p_op->arguments[0]->get_datatype(); - valid = na==TYPE_BOOL; - ret_type=TYPE_BOOL; + valid = na == TYPE_BOOL; + ret_type = TYPE_BOOL; } break; case OP_INCREMENT: @@ -877,8 +855,8 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) case OP_POST_DECREMENT: case OP_NEGATE: { DataType na = p_op->arguments[0]->get_datatype(); - valid = na>TYPE_BOOL && na<TYPE_MAT2; - ret_type=na; + valid = na > TYPE_BOOL && na < TYPE_MAT2; + ret_type = na; } break; case OP_ADD: case OP_SUB: @@ -887,50 +865,50 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - if (na>nb) { + if (na > nb) { //make things easier; - SWAP(na,nb); - } - - if (na==nb) { - valid = (na>TYPE_BOOL && na<TYPE_MAT2) || (p_op->op==OP_MUL && na>=TYPE_MAT2 && na<=TYPE_MAT4); - ret_type=na; - } else if (na==TYPE_INT && nb==TYPE_IVEC2) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_INT && nb==TYPE_IVEC3) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_INT && nb==TYPE_IVEC4) { - valid=true; - ret_type=TYPE_IVEC4; - } else if (na==TYPE_UINT && nb==TYPE_UVEC2) { - valid=true; - ret_type=TYPE_UVEC2; - } else if (na==TYPE_UINT && nb==TYPE_UVEC3) { - valid=true; - ret_type=TYPE_UVEC3; - } else if (na==TYPE_UINT && nb==TYPE_UVEC4) { - valid=true; - ret_type=TYPE_UVEC4; - } else if (na==TYPE_FLOAT && nb==TYPE_VEC2) { - valid=true; - ret_type=TYPE_VEC2; - } else if (na==TYPE_FLOAT && nb==TYPE_VEC3) { - valid=true; - ret_type=TYPE_VEC3; - } else if (na==TYPE_FLOAT && nb==TYPE_VEC4) { - valid=true; - ret_type=TYPE_VEC4; - } else if (p_op->op==OP_MUL && na==TYPE_VEC2 && nb==TYPE_MAT2) { - valid=true; - ret_type=TYPE_MAT2; - } else if (p_op->op==OP_MUL && na==TYPE_VEC3 && nb==TYPE_MAT3) { - valid=true; - ret_type=TYPE_MAT3; - } else if (p_op->op==OP_MUL && na==TYPE_VEC4 && nb==TYPE_MAT4) { - valid=true; - ret_type=TYPE_MAT4; + SWAP(na, nb); + } + + if (na == nb) { + valid = (na > TYPE_BOOL && na < TYPE_MAT2) || (p_op->op == OP_MUL && na >= TYPE_MAT2 && na <= TYPE_MAT4); + ret_type = na; + } else if (na == TYPE_INT && nb == TYPE_IVEC2) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_INT && nb == TYPE_IVEC3) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_INT && nb == TYPE_IVEC4) { + valid = true; + ret_type = TYPE_IVEC4; + } else if (na == TYPE_UINT && nb == TYPE_UVEC2) { + valid = true; + ret_type = TYPE_UVEC2; + } else if (na == TYPE_UINT && nb == TYPE_UVEC3) { + valid = true; + ret_type = TYPE_UVEC3; + } else if (na == TYPE_UINT && nb == TYPE_UVEC4) { + valid = true; + ret_type = TYPE_UVEC4; + } else if (na == TYPE_FLOAT && nb == TYPE_VEC2) { + valid = true; + ret_type = TYPE_VEC2; + } else if (na == TYPE_FLOAT && nb == TYPE_VEC3) { + valid = true; + ret_type = TYPE_VEC3; + } else if (na == TYPE_FLOAT && nb == TYPE_VEC4) { + valid = true; + ret_type = TYPE_VEC4; + } else if (p_op->op == OP_MUL && na == TYPE_VEC2 && nb == TYPE_MAT2) { + valid = true; + ret_type = TYPE_MAT2; + } else if (p_op->op == OP_MUL && na == TYPE_VEC3 && nb == TYPE_MAT3) { + valid = true; + ret_type = TYPE_MAT3; + } else if (p_op->op == OP_MUL && na == TYPE_VEC4 && nb == TYPE_MAT4) { + valid = true; + ret_type = TYPE_MAT4; } } break; case OP_ASSIGN_MOD: @@ -946,50 +924,49 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - - if (na==TYPE_INT && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_INT; - } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC4; - } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) { - valid=true; - ret_type=TYPE_IVEC4; - ///// - } else if (na==TYPE_UINT && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UINT; - } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC2; - } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC3; - } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC4; - } else if (na==TYPE_UVEC2 && nb==TYPE_UVEC2) { - valid=true; - ret_type=TYPE_UVEC2; - } else if (na==TYPE_UVEC3 && nb==TYPE_UVEC3) { - valid=true; - ret_type=TYPE_UVEC3; - } else if (na==TYPE_UVEC4 && nb==TYPE_UVEC4) { - valid=true; - ret_type=TYPE_UVEC4; + if (na == TYPE_INT && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_INT; + } else if (na == TYPE_IVEC2 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC4; + } else if (na == TYPE_IVEC2 && nb == TYPE_IVEC2) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_IVEC3) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_IVEC4) { + valid = true; + ret_type = TYPE_IVEC4; + ///// + } else if (na == TYPE_UINT && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UINT; + } else if (na == TYPE_UVEC2 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC2; + } else if (na == TYPE_UVEC3 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC3; + } else if (na == TYPE_UVEC4 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC4; + } else if (na == TYPE_UVEC2 && nb == TYPE_UVEC2) { + valid = true; + ret_type = TYPE_UVEC2; + } else if (na == TYPE_UVEC3 && nb == TYPE_UVEC3) { + valid = true; + ret_type = TYPE_UVEC3; + } else if (na == TYPE_UVEC4 && nb == TYPE_UVEC4) { + valid = true; + ret_type = TYPE_UVEC4; } } break; case OP_ASSIGN_SHIFT_LEFT: @@ -1000,42 +977,42 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - if (na>=TYPE_UINT && na<=TYPE_UVEC4) { - na=DataType(na-4); - } - - if (nb>=TYPE_UINT && nb<=TYPE_UVEC4) { - nb=DataType(nb-4); - } - - if (na==TYPE_INT && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_INT; - } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC4; - } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) { - valid=true; - ret_type=TYPE_IVEC4; + if (na >= TYPE_UINT && na <= TYPE_UVEC4) { + na = DataType(na - 4); + } + + if (nb >= TYPE_UINT && nb <= TYPE_UVEC4) { + nb = DataType(nb - 4); + } + + if (na == TYPE_INT && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_INT; + } else if (na == TYPE_IVEC2 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC4; + } else if (na == TYPE_IVEC2 && nb == TYPE_IVEC2) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_IVEC3) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_IVEC4) { + valid = true; + ret_type = TYPE_IVEC4; } } break; case OP_ASSIGN: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - valid=na==nb; - ret_type=na; + valid = na == nb; + ret_type = na; } break; case OP_ASSIGN_ADD: case OP_ASSIGN_SUB: @@ -1045,46 +1022,45 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - - if (na==nb) { - valid = (na>TYPE_BOOL && na<TYPE_MAT2) || (p_op->op==OP_ASSIGN_MUL && na>=TYPE_MAT2 && na<=TYPE_MAT4); - ret_type=na; - } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_INT ) { - valid=true; - ret_type=TYPE_IVEC4; - } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC2; - } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC3; - } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC4; - } else if (na==TYPE_VEC2 && nb==TYPE_FLOAT ) { - valid=true; - ret_type=TYPE_VEC2; - } else if (na==TYPE_VEC3 && nb==TYPE_FLOAT) { - valid=true; - ret_type=TYPE_VEC3; - } else if (na==TYPE_VEC4 && nb==TYPE_FLOAT) { - valid=true; - ret_type=TYPE_VEC4; - } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT2 && nb==TYPE_VEC2) { - valid=true; - ret_type=TYPE_MAT2; - } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT3 && nb==TYPE_VEC3) { - valid=true; - ret_type=TYPE_MAT3; - } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT4 && nb==TYPE_VEC4) { - valid=true; - ret_type=TYPE_MAT4; + if (na == nb) { + valid = (na > TYPE_BOOL && na < TYPE_MAT2) || (p_op->op == OP_ASSIGN_MUL && na >= TYPE_MAT2 && na <= TYPE_MAT4); + ret_type = na; + } else if (na == TYPE_IVEC2 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC4; + } else if (na == TYPE_UVEC2 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC2; + } else if (na == TYPE_UVEC3 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC3; + } else if (na == TYPE_UVEC4 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC4; + } else if (na == TYPE_VEC2 && nb == TYPE_FLOAT) { + valid = true; + ret_type = TYPE_VEC2; + } else if (na == TYPE_VEC3 && nb == TYPE_FLOAT) { + valid = true; + ret_type = TYPE_VEC3; + } else if (na == TYPE_VEC4 && nb == TYPE_FLOAT) { + valid = true; + ret_type = TYPE_VEC4; + } else if (p_op->op == OP_ASSIGN_MUL && na == TYPE_MAT2 && nb == TYPE_VEC2) { + valid = true; + ret_type = TYPE_MAT2; + } else if (p_op->op == OP_ASSIGN_MUL && na == TYPE_MAT3 && nb == TYPE_VEC3) { + valid = true; + ret_type = TYPE_MAT3; + } else if (p_op->op == OP_ASSIGN_MUL && na == TYPE_MAT4 && nb == TYPE_VEC4) { + valid = true; + ret_type = TYPE_MAT4; } } break; case OP_ASSIGN_BIT_AND: @@ -1105,68 +1081,68 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); - if (na>nb && p_op->op>=OP_BIT_AND) { + if (na > nb && p_op->op >= OP_BIT_AND) { //can swap for non assign - SWAP(na,nb); - } - - if (na==TYPE_INT && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_INT; - } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_INT) { - valid=true; - ret_type=TYPE_IVEC4; - } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) { - valid=true; - ret_type=TYPE_IVEC2; - } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) { - valid=true; - ret_type=TYPE_IVEC3; - } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) { - valid=true; - ret_type=TYPE_IVEC4; - ///// - } else if (na==TYPE_UINT && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UINT; - } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC2; - } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC3; - } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) { - valid=true; - ret_type=TYPE_UVEC4; - } else if (na==TYPE_UVEC2 && nb==TYPE_UVEC2) { - valid=true; - ret_type=TYPE_UVEC2; - } else if (na==TYPE_UVEC3 && nb==TYPE_UVEC3) { - valid=true; - ret_type=TYPE_UVEC3; - } else if (na==TYPE_UVEC4 && nb==TYPE_UVEC4) { - valid=true; - ret_type=TYPE_UVEC4; + SWAP(na, nb); + } + + if (na == TYPE_INT && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_INT; + } else if (na == TYPE_IVEC2 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_INT) { + valid = true; + ret_type = TYPE_IVEC4; + } else if (na == TYPE_IVEC2 && nb == TYPE_IVEC2) { + valid = true; + ret_type = TYPE_IVEC2; + } else if (na == TYPE_IVEC3 && nb == TYPE_IVEC3) { + valid = true; + ret_type = TYPE_IVEC3; + } else if (na == TYPE_IVEC4 && nb == TYPE_IVEC4) { + valid = true; + ret_type = TYPE_IVEC4; + ///// + } else if (na == TYPE_UINT && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UINT; + } else if (na == TYPE_UVEC2 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC2; + } else if (na == TYPE_UVEC3 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC3; + } else if (na == TYPE_UVEC4 && nb == TYPE_UINT) { + valid = true; + ret_type = TYPE_UVEC4; + } else if (na == TYPE_UVEC2 && nb == TYPE_UVEC2) { + valid = true; + ret_type = TYPE_UVEC2; + } else if (na == TYPE_UVEC3 && nb == TYPE_UVEC3) { + valid = true; + ret_type = TYPE_UVEC3; + } else if (na == TYPE_UVEC4 && nb == TYPE_UVEC4) { + valid = true; + ret_type = TYPE_UVEC4; } } break; case OP_BIT_INVERT: { //unaries DataType na = p_op->arguments[0]->get_datatype(); - valid = na>=TYPE_INT && na<TYPE_FLOAT; - ret_type=na; + valid = na >= TYPE_INT && na < TYPE_FLOAT; + ret_type = na; } break; case OP_SELECT_IF: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); DataType nc = p_op->arguments[2]->get_datatype(); - valid = na==TYPE_BOOL && (nb==nc); - ret_type=nb; + valid = na == TYPE_BOOL && (nb == nc); + ret_type = nb; } break; default: { ERR_FAIL_V(false); @@ -1174,653 +1150,640 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) } if (r_ret_type) - *r_ret_type=ret_type; + *r_ret_type = ret_type; return valid; - } -const ShaderLanguage::BuiltinFuncDef ShaderLanguage::builtin_func_defs[]={ +const ShaderLanguage::BuiltinFuncDef ShaderLanguage::builtin_func_defs[] = { //constructors - {"bool",TYPE_BOOL,{TYPE_BOOL,TYPE_VOID}}, - {"bvec2",TYPE_BVEC2,{TYPE_BOOL,TYPE_VOID}}, - {"bvec2",TYPE_BVEC2,{TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_BVEC2,TYPE_BOOL,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_BVEC2,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BVEC2,TYPE_BOOL,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BVEC2,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BOOL,TYPE_BVEC2,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BVEC3,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BVEC3,TYPE_BOOL,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}}, - - - {"float",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"vec2",TYPE_VEC2,{TYPE_FLOAT,TYPE_VOID}}, - {"vec2",TYPE_VEC2,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_VEC2,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - - {"int",TYPE_INT,{TYPE_INT,TYPE_VOID}}, - {"ivec2",TYPE_IVEC2,{TYPE_INT,TYPE_VOID}}, - {"ivec2",TYPE_IVEC2,{TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_IVEC2,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_IVEC2,TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_INT,TYPE_IVEC2,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_IVEC3,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_IVEC3,TYPE_INT,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - - {"uint",TYPE_UINT,{TYPE_UINT,TYPE_VOID}}, - {"uvec2",TYPE_UVEC2,{TYPE_UINT,TYPE_VOID}}, - {"uvec2",TYPE_UVEC2,{TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_UVEC2,TYPE_UINT,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_UVEC2,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UVEC2,TYPE_UINT,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UVEC2,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UINT,TYPE_UVEC2,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UVEC3,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UVEC3,TYPE_UINT,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - - {"mat2",TYPE_MAT2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"mat3",TYPE_MAT3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"mat4",TYPE_MAT4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"mat2",TYPE_MAT2,{TYPE_FLOAT,TYPE_VOID}}, - {"mat3",TYPE_MAT3,{TYPE_FLOAT,TYPE_VOID}}, - {"mat4",TYPE_MAT4,{TYPE_FLOAT,TYPE_VOID}}, + { "bool", TYPE_BOOL, { TYPE_BOOL, TYPE_VOID } }, + { "bvec2", TYPE_BVEC2, { TYPE_BOOL, TYPE_VOID } }, + { "bvec2", TYPE_BVEC2, { TYPE_BOOL, TYPE_BOOL, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_BOOL, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_BVEC2, TYPE_BOOL, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_BOOL, TYPE_BVEC2, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BVEC2, TYPE_BOOL, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BVEC2, TYPE_BOOL, TYPE_BOOL, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BOOL, TYPE_BVEC2, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BVEC3, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BVEC3, TYPE_BOOL, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_BVEC2, TYPE_BVEC2, TYPE_VOID } }, + + { "float", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "vec2", TYPE_VEC2, { TYPE_FLOAT, TYPE_VOID } }, + { "vec2", TYPE_VEC2, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_FLOAT, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_VEC2, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_VEC3, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + + { "int", TYPE_INT, { TYPE_INT, TYPE_VOID } }, + { "ivec2", TYPE_IVEC2, { TYPE_INT, TYPE_VOID } }, + { "ivec2", TYPE_IVEC2, { TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_INT, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_INT, TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_IVEC2, TYPE_INT, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_INT, TYPE_IVEC2, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_INT, TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_IVEC2, TYPE_INT, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_IVEC2, TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_INT, TYPE_IVEC2, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_IVEC3, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_IVEC3, TYPE_INT, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + + { "uint", TYPE_UINT, { TYPE_UINT, TYPE_VOID } }, + { "uvec2", TYPE_UVEC2, { TYPE_UINT, TYPE_VOID } }, + { "uvec2", TYPE_UVEC2, { TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_UINT, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_UVEC2, TYPE_UINT, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_UINT, TYPE_UVEC2, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UVEC2, TYPE_UINT, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UVEC2, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UINT, TYPE_UVEC2, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UVEC3, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UVEC3, TYPE_UINT, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + + { "mat2", TYPE_MAT2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "mat3", TYPE_MAT3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "mat4", TYPE_MAT4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "mat2", TYPE_MAT2, { TYPE_FLOAT, TYPE_VOID } }, + { "mat3", TYPE_MAT3, { TYPE_FLOAT, TYPE_VOID } }, + { "mat4", TYPE_MAT4, { TYPE_FLOAT, TYPE_VOID } }, //conversion scalars - {"int",TYPE_INT,{TYPE_BOOL,TYPE_VOID}}, - {"int",TYPE_INT,{TYPE_INT,TYPE_VOID}}, - {"int",TYPE_INT,{TYPE_UINT,TYPE_VOID}}, - {"int",TYPE_INT,{TYPE_FLOAT,TYPE_VOID}}, + { "int", TYPE_INT, { TYPE_BOOL, TYPE_VOID } }, + { "int", TYPE_INT, { TYPE_INT, TYPE_VOID } }, + { "int", TYPE_INT, { TYPE_UINT, TYPE_VOID } }, + { "int", TYPE_INT, { TYPE_FLOAT, TYPE_VOID } }, - {"float",TYPE_FLOAT,{TYPE_BOOL,TYPE_VOID}}, - {"float",TYPE_FLOAT,{TYPE_INT,TYPE_VOID}}, - {"float",TYPE_FLOAT,{TYPE_UINT,TYPE_VOID}}, - {"float",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, + { "float", TYPE_FLOAT, { TYPE_BOOL, TYPE_VOID } }, + { "float", TYPE_FLOAT, { TYPE_INT, TYPE_VOID } }, + { "float", TYPE_FLOAT, { TYPE_UINT, TYPE_VOID } }, + { "float", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, - {"uint",TYPE_UINT,{TYPE_BOOL,TYPE_VOID}}, - {"uint",TYPE_UINT,{TYPE_INT,TYPE_VOID}}, - {"uint",TYPE_UINT,{TYPE_UINT,TYPE_VOID}}, - {"uint",TYPE_UINT,{TYPE_FLOAT,TYPE_VOID}}, + { "uint", TYPE_UINT, { TYPE_BOOL, TYPE_VOID } }, + { "uint", TYPE_UINT, { TYPE_INT, TYPE_VOID } }, + { "uint", TYPE_UINT, { TYPE_UINT, TYPE_VOID } }, + { "uint", TYPE_UINT, { TYPE_FLOAT, TYPE_VOID } }, - {"bool",TYPE_BOOL,{TYPE_BOOL,TYPE_VOID}}, - {"bool",TYPE_BOOL,{TYPE_INT,TYPE_VOID}}, - {"bool",TYPE_BOOL,{TYPE_UINT,TYPE_VOID}}, - {"bool",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}}, + { "bool", TYPE_BOOL, { TYPE_BOOL, TYPE_VOID } }, + { "bool", TYPE_BOOL, { TYPE_INT, TYPE_VOID } }, + { "bool", TYPE_BOOL, { TYPE_UINT, TYPE_VOID } }, + { "bool", TYPE_BOOL, { TYPE_FLOAT, TYPE_VOID } }, //conversion vectors - {"ivec2",TYPE_IVEC2,{TYPE_BVEC2,TYPE_VOID}}, - {"ivec2",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"ivec2",TYPE_IVEC2,{TYPE_UVEC2,TYPE_VOID}}, - {"ivec2",TYPE_IVEC2,{TYPE_VEC2,TYPE_VOID}}, - - {"vec2",TYPE_VEC2,{TYPE_BVEC2,TYPE_VOID}}, - {"vec2",TYPE_VEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"vec2",TYPE_VEC2,{TYPE_UVEC2,TYPE_VOID}}, - {"vec2",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - - {"uvec2",TYPE_UVEC2,{TYPE_BVEC2,TYPE_VOID}}, - {"uvec2",TYPE_UVEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"uvec2",TYPE_UVEC2,{TYPE_UVEC2,TYPE_VOID}}, - {"uvec2",TYPE_UVEC2,{TYPE_VEC2,TYPE_VOID}}, - - {"bvec2",TYPE_BVEC2,{TYPE_BVEC2,TYPE_VOID}}, - {"bvec2",TYPE_BVEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"bvec2",TYPE_BVEC2,{TYPE_UVEC2,TYPE_VOID}}, - {"bvec2",TYPE_BVEC2,{TYPE_VEC2,TYPE_VOID}}, - - {"ivec3",TYPE_IVEC3,{TYPE_BVEC3,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_UVEC3,TYPE_VOID}}, - {"ivec3",TYPE_IVEC3,{TYPE_VEC3,TYPE_VOID}}, - - {"vec3",TYPE_VEC3,{TYPE_BVEC3,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_UVEC3,TYPE_VOID}}, - {"vec3",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - - {"uvec3",TYPE_UVEC3,{TYPE_BVEC3,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_UVEC3,TYPE_VOID}}, - {"uvec3",TYPE_UVEC3,{TYPE_VEC3,TYPE_VOID}}, - - {"bvec3",TYPE_BVEC3,{TYPE_BVEC3,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_UVEC3,TYPE_VOID}}, - {"bvec3",TYPE_BVEC3,{TYPE_VEC3,TYPE_VOID}}, - - {"ivec4",TYPE_IVEC4,{TYPE_BVEC4,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_UVEC4,TYPE_VOID}}, - {"ivec4",TYPE_IVEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"vec4",TYPE_VEC4,{TYPE_BVEC4,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_IVEC4,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_UVEC4,TYPE_VOID}}, - {"vec4",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"uvec4",TYPE_UVEC4,{TYPE_BVEC4,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_IVEC4,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_UVEC4,TYPE_VOID}}, - {"uvec4",TYPE_UVEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"bvec4",TYPE_BVEC4,{TYPE_BVEC4,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_IVEC4,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_UVEC4,TYPE_VOID}}, - {"bvec4",TYPE_BVEC4,{TYPE_VEC4,TYPE_VOID}}, + { "ivec2", TYPE_IVEC2, { TYPE_BVEC2, TYPE_VOID } }, + { "ivec2", TYPE_IVEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "ivec2", TYPE_IVEC2, { TYPE_UVEC2, TYPE_VOID } }, + { "ivec2", TYPE_IVEC2, { TYPE_VEC2, TYPE_VOID } }, + + { "vec2", TYPE_VEC2, { TYPE_BVEC2, TYPE_VOID } }, + { "vec2", TYPE_VEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "vec2", TYPE_VEC2, { TYPE_UVEC2, TYPE_VOID } }, + { "vec2", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + + { "uvec2", TYPE_UVEC2, { TYPE_BVEC2, TYPE_VOID } }, + { "uvec2", TYPE_UVEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "uvec2", TYPE_UVEC2, { TYPE_UVEC2, TYPE_VOID } }, + { "uvec2", TYPE_UVEC2, { TYPE_VEC2, TYPE_VOID } }, + + { "bvec2", TYPE_BVEC2, { TYPE_BVEC2, TYPE_VOID } }, + { "bvec2", TYPE_BVEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "bvec2", TYPE_BVEC2, { TYPE_UVEC2, TYPE_VOID } }, + { "bvec2", TYPE_BVEC2, { TYPE_VEC2, TYPE_VOID } }, + + { "ivec3", TYPE_IVEC3, { TYPE_BVEC3, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_UVEC3, TYPE_VOID } }, + { "ivec3", TYPE_IVEC3, { TYPE_VEC3, TYPE_VOID } }, + + { "vec3", TYPE_VEC3, { TYPE_BVEC3, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_UVEC3, TYPE_VOID } }, + { "vec3", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + + { "uvec3", TYPE_UVEC3, { TYPE_BVEC3, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_UVEC3, TYPE_VOID } }, + { "uvec3", TYPE_UVEC3, { TYPE_VEC3, TYPE_VOID } }, + + { "bvec3", TYPE_BVEC3, { TYPE_BVEC3, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_UVEC3, TYPE_VOID } }, + { "bvec3", TYPE_BVEC3, { TYPE_VEC3, TYPE_VOID } }, + + { "ivec4", TYPE_IVEC4, { TYPE_BVEC4, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_IVEC4, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_UVEC4, TYPE_VOID } }, + { "ivec4", TYPE_IVEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "vec4", TYPE_VEC4, { TYPE_BVEC4, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_IVEC4, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_UVEC4, TYPE_VOID } }, + { "vec4", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "uvec4", TYPE_UVEC4, { TYPE_BVEC4, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_IVEC4, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_UVEC4, TYPE_VOID } }, + { "uvec4", TYPE_UVEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "bvec4", TYPE_BVEC4, { TYPE_BVEC4, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_IVEC4, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_UVEC4, TYPE_VOID } }, + { "bvec4", TYPE_BVEC4, { TYPE_VEC4, TYPE_VOID } }, //builtins - trigonometry - {"sin",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"cos",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"tan",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"asin",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"acos",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"atan",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"atan2",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"sinh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"cosh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"tanh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, + { "sin", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "cos", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "tan", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "asin", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "acos", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "atan", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "atan2", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "sinh", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "cosh", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "tanh", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, //builtins - exponential - {"pow",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"pow",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"pow",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"pow",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"pow",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"pow",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - {"pow",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"exp",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"exp",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"exp",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"exp",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"log",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"log",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"log",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"log",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"sqrt",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"sqrt",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"sqrt",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"sqrt",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, + { "pow", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "pow", TYPE_VEC2, { TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "pow", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "pow", TYPE_VEC3, { TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "pow", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "pow", TYPE_VEC4, { TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + { "pow", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "exp", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "exp", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "exp", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "exp", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "log", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "log", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "log", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "log", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "sqrt", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "sqrt", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "sqrt", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "sqrt", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, //builtins - common - {"abs",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"abs",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"abs",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"abs",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"abs",TYPE_INT,{TYPE_INT,TYPE_VOID}}, - {"abs",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"abs",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"abs",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}}, - - {"abs",TYPE_UINT,{TYPE_UINT,TYPE_VOID}}, - {"abs",TYPE_UVEC2,{TYPE_UVEC2,TYPE_VOID}}, - {"abs",TYPE_UVEC3,{TYPE_UVEC3,TYPE_VOID}}, - {"abs",TYPE_UVEC4,{TYPE_UVEC4,TYPE_VOID}}, - - - {"sign",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"sign",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"sign",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"sign",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"sign",TYPE_INT,{TYPE_INT,TYPE_VOID}}, - {"sign",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"sign",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"sign",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}}, - - - {"floor",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"floor",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"floor",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"floor",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"trunc",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"trunc",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"trunc",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"trunc",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"round",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"round",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"round",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"round",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"ceil",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"ceil",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"ceil",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"ceil",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"fract",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"fract",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"fract",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"fract",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"mod",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"mod",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"mod",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"mod",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"mod",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"mod",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"mod",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"modf",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"modf",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"modf",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"modf",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"min",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"min",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"min",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"min",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"min",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"min",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"min",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"min",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"min",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"min",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"min",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"min",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - {"max",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"max",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"max",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"max",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"max",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"max",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"max",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"max",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"max",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"max",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"max",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"max",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - - {"clamp",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"clamp",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"clamp",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"clamp",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"clamp",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"clamp",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"clamp",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - - - {"clamp",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"clamp",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"clamp",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"clamp",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - {"clamp",TYPE_IVEC2,{TYPE_IVEC2,TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"clamp",TYPE_IVEC3,{TYPE_IVEC3,TYPE_INT,TYPE_INT,TYPE_VOID}}, - {"clamp",TYPE_IVEC4,{TYPE_IVEC4,TYPE_INT,TYPE_INT,TYPE_VOID}}, - - {"clamp",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"clamp",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"clamp",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"clamp",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - {"clamp",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"clamp",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - {"clamp",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, - - {"mix",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"mix",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_BOOL,TYPE_VOID}}, - {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_BOOL,TYPE_VOID}}, - {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_BVEC2,TYPE_VOID}}, - {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_BOOL,TYPE_VOID}}, - {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_BVEC3,TYPE_VOID}}, - {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_BOOL,TYPE_VOID}}, - {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_BVEC3,TYPE_VOID}}, - {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"step",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"step",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"step",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"step",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"step",TYPE_VEC2,{TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, - {"step",TYPE_VEC3,{TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}}, - {"step",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC4,TYPE_VOID}}, - {"smoothstep",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, - {"smoothstep",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"smoothstep",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"smoothstep",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"smoothstep",TYPE_VEC2,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, - {"smoothstep",TYPE_VEC3,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}}, - {"smoothstep",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC4,TYPE_VOID}}, - - {"isnan",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}}, - {"isnan",TYPE_BOOL,{TYPE_VEC2,TYPE_VOID}}, - {"isnan",TYPE_BOOL,{TYPE_VEC3,TYPE_VOID}}, - {"isnan",TYPE_BOOL,{TYPE_VEC4,TYPE_VOID}}, - - {"isinf",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}}, - {"isinf",TYPE_BOOL,{TYPE_VEC2,TYPE_VOID}}, - {"isinf",TYPE_BOOL,{TYPE_VEC3,TYPE_VOID}}, - {"isinf",TYPE_BOOL,{TYPE_VEC4,TYPE_VOID}}, - - {"floatBitsToInt",TYPE_INT,{TYPE_FLOAT,TYPE_VOID}}, - {"floatBitsToInt",TYPE_IVEC2,{TYPE_VEC2,TYPE_VOID}}, - {"floatBitsToInt",TYPE_IVEC3,{TYPE_VEC3,TYPE_VOID}}, - {"floatBitsToInt",TYPE_IVEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"floatBitsToUInt",TYPE_UINT,{TYPE_FLOAT,TYPE_VOID}}, - {"floatBitsToUInt",TYPE_UVEC2,{TYPE_VEC2,TYPE_VOID}}, - {"floatBitsToUInt",TYPE_UVEC3,{TYPE_VEC3,TYPE_VOID}}, - {"floatBitsToUInt",TYPE_UVEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"intBitsToFloat",TYPE_FLOAT,{TYPE_INT,TYPE_VOID}}, - {"intBitsToFloat",TYPE_VEC2,{TYPE_IVEC2,TYPE_VOID}}, - {"intBitsToFloat",TYPE_VEC3,{TYPE_IVEC3,TYPE_VOID}}, - {"intBitsToFloat",TYPE_VEC4,{TYPE_IVEC4,TYPE_VOID}}, - - {"uintBitsToFloat",TYPE_FLOAT,{TYPE_UINT,TYPE_VOID}}, - {"uintBitsToFloat",TYPE_VEC2,{TYPE_UVEC2,TYPE_VOID}}, - {"uintBitsToFloat",TYPE_VEC3,{TYPE_UVEC3,TYPE_VOID}}, - {"uintBitsToFloat",TYPE_VEC4,{TYPE_UVEC4,TYPE_VOID}}, + { "abs", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "abs", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "abs", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "abs", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "abs", TYPE_INT, { TYPE_INT, TYPE_VOID } }, + { "abs", TYPE_IVEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "abs", TYPE_IVEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "abs", TYPE_IVEC4, { TYPE_IVEC4, TYPE_VOID } }, + + { "abs", TYPE_UINT, { TYPE_UINT, TYPE_VOID } }, + { "abs", TYPE_UVEC2, { TYPE_UVEC2, TYPE_VOID } }, + { "abs", TYPE_UVEC3, { TYPE_UVEC3, TYPE_VOID } }, + { "abs", TYPE_UVEC4, { TYPE_UVEC4, TYPE_VOID } }, + + { "sign", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "sign", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "sign", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "sign", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "sign", TYPE_INT, { TYPE_INT, TYPE_VOID } }, + { "sign", TYPE_IVEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "sign", TYPE_IVEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "sign", TYPE_IVEC4, { TYPE_IVEC4, TYPE_VOID } }, + + { "floor", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "floor", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "floor", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "floor", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "trunc", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "trunc", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "trunc", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "trunc", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "round", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "round", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "round", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "round", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "ceil", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "ceil", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "ceil", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "ceil", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "fract", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "fract", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "fract", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "fract", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "mod", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "mod", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "mod", TYPE_VEC2, { TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "mod", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "mod", TYPE_VEC3, { TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "mod", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "mod", TYPE_VEC4, { TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "modf", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "modf", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "modf", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "modf", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "min", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "min", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "min", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "min", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "min", TYPE_INT, { TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "min", TYPE_IVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "min", TYPE_IVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "min", TYPE_IVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "min", TYPE_UINT, { TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "min", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "min", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "min", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "max", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "max", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "max", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "max", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "max", TYPE_INT, { TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "max", TYPE_IVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "max", TYPE_IVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "max", TYPE_IVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "max", TYPE_UINT, { TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "max", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "max", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "max", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "clamp", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "clamp", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "clamp", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "clamp", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "clamp", TYPE_VEC2, { TYPE_VEC2, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "clamp", TYPE_VEC3, { TYPE_VEC3, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "clamp", TYPE_VEC4, { TYPE_VEC4, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + + { "clamp", TYPE_INT, { TYPE_INT, TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "clamp", TYPE_IVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "clamp", TYPE_IVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "clamp", TYPE_IVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + { "clamp", TYPE_IVEC2, { TYPE_IVEC2, TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "clamp", TYPE_IVEC3, { TYPE_IVEC3, TYPE_INT, TYPE_INT, TYPE_VOID } }, + { "clamp", TYPE_IVEC4, { TYPE_IVEC4, TYPE_INT, TYPE_INT, TYPE_VOID } }, + + { "clamp", TYPE_UINT, { TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "clamp", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "clamp", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "clamp", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + { "clamp", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "clamp", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + { "clamp", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UINT, TYPE_UINT, TYPE_VOID } }, + + { "mix", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "mix", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_BOOL, TYPE_VOID } }, + { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_BOOL, TYPE_VOID } }, + { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_BVEC2, TYPE_VOID } }, + { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_BOOL, TYPE_VOID } }, + { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_BVEC3, TYPE_VOID } }, + { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_BOOL, TYPE_VOID } }, + { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_BVEC3, TYPE_VOID } }, + { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "step", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "step", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "step", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "step", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "step", TYPE_VEC2, { TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } }, + { "step", TYPE_VEC3, { TYPE_FLOAT, TYPE_VEC3, TYPE_VOID } }, + { "step", TYPE_VEC4, { TYPE_FLOAT, TYPE_VEC4, TYPE_VOID } }, + { "smoothstep", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } }, + { "smoothstep", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "smoothstep", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "smoothstep", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "smoothstep", TYPE_VEC2, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } }, + { "smoothstep", TYPE_VEC3, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC3, TYPE_VOID } }, + { "smoothstep", TYPE_VEC4, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC4, TYPE_VOID } }, + + { "isnan", TYPE_BOOL, { TYPE_FLOAT, TYPE_VOID } }, + { "isnan", TYPE_BOOL, { TYPE_VEC2, TYPE_VOID } }, + { "isnan", TYPE_BOOL, { TYPE_VEC3, TYPE_VOID } }, + { "isnan", TYPE_BOOL, { TYPE_VEC4, TYPE_VOID } }, + + { "isinf", TYPE_BOOL, { TYPE_FLOAT, TYPE_VOID } }, + { "isinf", TYPE_BOOL, { TYPE_VEC2, TYPE_VOID } }, + { "isinf", TYPE_BOOL, { TYPE_VEC3, TYPE_VOID } }, + { "isinf", TYPE_BOOL, { TYPE_VEC4, TYPE_VOID } }, + + { "floatBitsToInt", TYPE_INT, { TYPE_FLOAT, TYPE_VOID } }, + { "floatBitsToInt", TYPE_IVEC2, { TYPE_VEC2, TYPE_VOID } }, + { "floatBitsToInt", TYPE_IVEC3, { TYPE_VEC3, TYPE_VOID } }, + { "floatBitsToInt", TYPE_IVEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "floatBitsToUInt", TYPE_UINT, { TYPE_FLOAT, TYPE_VOID } }, + { "floatBitsToUInt", TYPE_UVEC2, { TYPE_VEC2, TYPE_VOID } }, + { "floatBitsToUInt", TYPE_UVEC3, { TYPE_VEC3, TYPE_VOID } }, + { "floatBitsToUInt", TYPE_UVEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "intBitsToFloat", TYPE_FLOAT, { TYPE_INT, TYPE_VOID } }, + { "intBitsToFloat", TYPE_VEC2, { TYPE_IVEC2, TYPE_VOID } }, + { "intBitsToFloat", TYPE_VEC3, { TYPE_IVEC3, TYPE_VOID } }, + { "intBitsToFloat", TYPE_VEC4, { TYPE_IVEC4, TYPE_VOID } }, + + { "uintBitsToFloat", TYPE_FLOAT, { TYPE_UINT, TYPE_VOID } }, + { "uintBitsToFloat", TYPE_VEC2, { TYPE_UVEC2, TYPE_VOID } }, + { "uintBitsToFloat", TYPE_VEC3, { TYPE_UVEC3, TYPE_VOID } }, + { "uintBitsToFloat", TYPE_VEC4, { TYPE_UVEC4, TYPE_VOID } }, //builtins - geometric - {"length",TYPE_FLOAT,{TYPE_VEC2,TYPE_VOID}}, - {"length",TYPE_FLOAT,{TYPE_VEC3,TYPE_VOID}}, - {"length",TYPE_FLOAT,{TYPE_VEC4,TYPE_VOID}}, - {"distance",TYPE_FLOAT,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"distance",TYPE_FLOAT,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"distance",TYPE_FLOAT,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"dot",TYPE_FLOAT,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"dot",TYPE_FLOAT,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"dot",TYPE_FLOAT,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - {"cross",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"normalize",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"normalize",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"normalize",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - {"reflect",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"refract",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - - {"facefordward",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"facefordward",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"facefordward",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"matrixCompMult",TYPE_MAT2,{TYPE_MAT2,TYPE_MAT2,TYPE_VOID}}, - {"matrixCompMult",TYPE_MAT3,{TYPE_MAT3,TYPE_MAT3,TYPE_VOID}}, - {"matrixCompMult",TYPE_MAT4,{TYPE_MAT4,TYPE_MAT4,TYPE_VOID}}, - - {"outerProduct",TYPE_MAT2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"outerProduct",TYPE_MAT3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"outerProduct",TYPE_MAT4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"transpose",TYPE_MAT2,{TYPE_MAT2,TYPE_VOID}}, - {"transpose",TYPE_MAT3,{TYPE_MAT3,TYPE_VOID}}, - {"transpose",TYPE_MAT4,{TYPE_MAT4,TYPE_VOID}}, - - {"determinant",TYPE_FLOAT,{TYPE_MAT2,TYPE_VOID}}, - {"determinant",TYPE_FLOAT,{TYPE_MAT3,TYPE_VOID}}, - {"determinant",TYPE_FLOAT,{TYPE_MAT4,TYPE_VOID}}, - - {"inverse",TYPE_MAT2,{TYPE_MAT2,TYPE_VOID}}, - {"inverse",TYPE_MAT3,{TYPE_MAT3,TYPE_VOID}}, - {"inverse",TYPE_MAT4,{TYPE_MAT4,TYPE_VOID}}, - - - {"lessThan",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"lessThan",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"lessThan",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"lessThan",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"lessThan",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"lessThan",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"lessThan",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"lessThan",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"lessThan",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - {"greaterThan",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"greaterThan",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"greaterThan",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"greaterThan",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"greaterThan",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"greaterThan",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"greaterThan",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"greaterThan",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"greaterThan",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - {"lessThanEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"lessThanEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"lessThanEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"lessThanEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"lessThanEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"lessThanEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"lessThanEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"lessThanEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"lessThanEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - {"greaterThanEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"greaterThanEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"greaterThanEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"greaterThanEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"greaterThanEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"greaterThanEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"greaterThanEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"greaterThanEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"greaterThanEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - {"equal",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"equal",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"equal",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"equal",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"equal",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"equal",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, - - {"equal",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"equal",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"equal",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, - - {"equal",TYPE_BVEC2,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}}, - {"equal",TYPE_BVEC3,{TYPE_BVEC3,TYPE_BVEC3,TYPE_VOID}}, - {"equal",TYPE_BVEC4,{TYPE_BVEC4,TYPE_BVEC4,TYPE_VOID}}, - - {"notEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"notEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - {"notEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, - - {"notEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, - {"notEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, - {"notEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, + { "length", TYPE_FLOAT, { TYPE_VEC2, TYPE_VOID } }, + { "length", TYPE_FLOAT, { TYPE_VEC3, TYPE_VOID } }, + { "length", TYPE_FLOAT, { TYPE_VEC4, TYPE_VOID } }, + { "distance", TYPE_FLOAT, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "distance", TYPE_FLOAT, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "distance", TYPE_FLOAT, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "dot", TYPE_FLOAT, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "dot", TYPE_FLOAT, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "dot", TYPE_FLOAT, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + { "cross", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "normalize", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "normalize", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "normalize", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + { "reflect", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "refract", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + + { "facefordward", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "facefordward", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "facefordward", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "matrixCompMult", TYPE_MAT2, { TYPE_MAT2, TYPE_MAT2, TYPE_VOID } }, + { "matrixCompMult", TYPE_MAT3, { TYPE_MAT3, TYPE_MAT3, TYPE_VOID } }, + { "matrixCompMult", TYPE_MAT4, { TYPE_MAT4, TYPE_MAT4, TYPE_VOID } }, + + { "outerProduct", TYPE_MAT2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "outerProduct", TYPE_MAT3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "outerProduct", TYPE_MAT4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "transpose", TYPE_MAT2, { TYPE_MAT2, TYPE_VOID } }, + { "transpose", TYPE_MAT3, { TYPE_MAT3, TYPE_VOID } }, + { "transpose", TYPE_MAT4, { TYPE_MAT4, TYPE_VOID } }, + + { "determinant", TYPE_FLOAT, { TYPE_MAT2, TYPE_VOID } }, + { "determinant", TYPE_FLOAT, { TYPE_MAT3, TYPE_VOID } }, + { "determinant", TYPE_FLOAT, { TYPE_MAT4, TYPE_VOID } }, + + { "inverse", TYPE_MAT2, { TYPE_MAT2, TYPE_VOID } }, + { "inverse", TYPE_MAT3, { TYPE_MAT3, TYPE_VOID } }, + { "inverse", TYPE_MAT4, { TYPE_MAT4, TYPE_VOID } }, + + { "lessThan", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "lessThan", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "lessThan", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "lessThan", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "lessThan", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "lessThan", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "lessThan", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "lessThan", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "lessThan", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "greaterThan", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "greaterThan", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "greaterThan", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "greaterThan", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "greaterThan", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "greaterThan", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "greaterThan", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "greaterThan", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "greaterThan", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "lessThanEqual", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "lessThanEqual", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "lessThanEqual", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "lessThanEqual", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "lessThanEqual", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "lessThanEqual", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "lessThanEqual", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "lessThanEqual", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "lessThanEqual", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "greaterThanEqual", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "greaterThanEqual", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "greaterThanEqual", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "greaterThanEqual", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "greaterThanEqual", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "greaterThanEqual", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "greaterThanEqual", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "greaterThanEqual", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "greaterThanEqual", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "equal", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "equal", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "equal", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "equal", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "equal", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "equal", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, + + { "equal", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "equal", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "equal", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, + + { "equal", TYPE_BVEC2, { TYPE_BVEC2, TYPE_BVEC2, TYPE_VOID } }, + { "equal", TYPE_BVEC3, { TYPE_BVEC3, TYPE_BVEC3, TYPE_VOID } }, + { "equal", TYPE_BVEC4, { TYPE_BVEC4, TYPE_BVEC4, TYPE_VOID } }, + + { "notEqual", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "notEqual", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + { "notEqual", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } }, + + { "notEqual", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } }, + { "notEqual", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } }, + { "notEqual", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } }, - {"notEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, - {"notEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, - {"notEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, + { "notEqual", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } }, + { "notEqual", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } }, + { "notEqual", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } }, - {"notEqual",TYPE_BVEC2,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}}, - {"notEqual",TYPE_BVEC3,{TYPE_BVEC3,TYPE_BVEC3,TYPE_VOID}}, - {"notEqual",TYPE_BVEC4,{TYPE_BVEC4,TYPE_BVEC4,TYPE_VOID}}, + { "notEqual", TYPE_BVEC2, { TYPE_BVEC2, TYPE_BVEC2, TYPE_VOID } }, + { "notEqual", TYPE_BVEC3, { TYPE_BVEC3, TYPE_BVEC3, TYPE_VOID } }, + { "notEqual", TYPE_BVEC4, { TYPE_BVEC4, TYPE_BVEC4, TYPE_VOID } }, - {"any",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}}, - {"any",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}}, - {"any",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}}, + { "any", TYPE_BOOL, { TYPE_BVEC2, TYPE_VOID } }, + { "any", TYPE_BOOL, { TYPE_BVEC3, TYPE_VOID } }, + { "any", TYPE_BOOL, { TYPE_BVEC4, TYPE_VOID } }, - {"all",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}}, - {"all",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}}, - {"all",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}}, + { "all", TYPE_BOOL, { TYPE_BVEC2, TYPE_VOID } }, + { "all", TYPE_BOOL, { TYPE_BVEC3, TYPE_VOID } }, + { "all", TYPE_BOOL, { TYPE_BVEC4, TYPE_VOID } }, - {"not",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}}, - {"not",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}}, - {"not",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}}, + { "not", TYPE_BOOL, { TYPE_BVEC2, TYPE_VOID } }, + { "not", TYPE_BOOL, { TYPE_BVEC3, TYPE_VOID } }, + { "not", TYPE_BOOL, { TYPE_BVEC4, TYPE_VOID } }, //builtins - texture - {"textureSize",TYPE_VEC2,{TYPE_SAMPLER2D,TYPE_INT,TYPE_VOID}}, - {"textureSize",TYPE_VEC2,{TYPE_ISAMPLER2D,TYPE_INT,TYPE_VOID}}, - {"textureSize",TYPE_VEC2,{TYPE_USAMPLER2D,TYPE_INT,TYPE_VOID}}, - {"textureSize",TYPE_VEC2,{TYPE_SAMPLERCUBE,TYPE_INT,TYPE_VOID}}, - - {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_VOID}}, - {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_VOID}}, - {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - - {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_VOID}}, - {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_VOID}}, - {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - - {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_VOID}}, - {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_VOID}}, - {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, - {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - - {"texture",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_VOID}}, - {"texture",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - - {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_VOID}}, - {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_VOID}}, - {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_VOID}}, - {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_VOID}}, - {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_VOID}}, - {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_VOID}}, - {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"textureLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureLod",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - - {"texelFetch",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, - {"texelFetch",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, - {"texelFetch",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, - - {"textureProjLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureProjLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"textureProjLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureProjLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"textureProjLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, - {"textureProjLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, - - {"textureGrad",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"textureGrad",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"textureGrad",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, - {"textureGrad",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, - - {"textureScreen",TYPE_VEC4,{TYPE_VEC2,TYPE_VOID}}, - - {"dFdx",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"dFdx",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"dFdx",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"dFdx",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"dFdy",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"dFdy",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"dFdy",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"dFdy",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - {"fwidth",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, - {"fwidth",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, - {"fwidth",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, - {"fwidth",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, - - - {NULL,TYPE_VOID,{TYPE_VOID}} + { "textureSize", TYPE_VEC2, { TYPE_SAMPLER2D, TYPE_INT, TYPE_VOID } }, + { "textureSize", TYPE_VEC2, { TYPE_ISAMPLER2D, TYPE_INT, TYPE_VOID } }, + { "textureSize", TYPE_VEC2, { TYPE_USAMPLER2D, TYPE_INT, TYPE_VOID } }, + { "textureSize", TYPE_VEC2, { TYPE_SAMPLERCUBE, TYPE_INT, TYPE_VOID } }, + + { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC2, TYPE_VOID } }, + { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_VOID } }, + { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + + { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC2, TYPE_VOID } }, + { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_VOID } }, + { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + + { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC2, TYPE_VOID } }, + { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_VOID } }, + { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } }, + { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + + { "texture", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_VOID } }, + { "texture", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + + { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_VOID } }, + { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC4, TYPE_VOID } }, + { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_VOID } }, + { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC4, TYPE_VOID } }, + { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_VOID } }, + { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC4, TYPE_VOID } }, + { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "textureLod", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureLod", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureLod", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureLod", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + + { "texelFetch", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_IVEC2, TYPE_INT, TYPE_VOID } }, + { "texelFetch", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_IVEC2, TYPE_INT, TYPE_VOID } }, + { "texelFetch", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_IVEC2, TYPE_INT, TYPE_VOID } }, + + { "textureProjLod", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureProjLod", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "textureProjLod", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureProjLod", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "textureProjLod", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } }, + { "textureProjLod", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } }, + + { "textureGrad", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "textureGrad", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "textureGrad", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } }, + { "textureGrad", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } }, + + { "textureScreen", TYPE_VEC4, { TYPE_VEC2, TYPE_VOID } }, + + { "dFdx", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "dFdx", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "dFdx", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "dFdx", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "dFdy", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "dFdy", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "dFdy", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "dFdy", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { "fwidth", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } }, + { "fwidth", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } }, + { "fwidth", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } }, + { "fwidth", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } }, + + { NULL, TYPE_VOID, { TYPE_VOID } } }; +bool ShaderLanguage::_validate_function_call(BlockNode *p_block, OperatorNode *p_func, DataType *r_ret_type) { - -bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p_func,DataType *r_ret_type) { - - ERR_FAIL_COND_V(p_func->op!=OP_CALL && p_func->op!=OP_CONSTRUCT,NULL); - + ERR_FAIL_COND_V(p_func->op != OP_CALL && p_func->op != OP_CONSTRUCT, NULL); Vector<DataType> args; - ERR_FAIL_COND_V( p_func->arguments[0]->type!=Node::TYPE_VARIABLE, NULL ); + ERR_FAIL_COND_V(p_func->arguments[0]->type != Node::TYPE_VARIABLE, NULL); - StringName name = static_cast<VariableNode*>(p_func->arguments[0])->name.operator String(); + StringName name = static_cast<VariableNode *>(p_func->arguments[0])->name.operator String(); - bool all_const=true; - for(int i=1;i<p_func->arguments.size();i++) { - if (p_func->arguments[i]->type!=Node::TYPE_CONSTANT) - all_const=false; + bool all_const = true; + for (int i = 1; i < p_func->arguments.size(); i++) { + if (p_func->arguments[i]->type != Node::TYPE_CONSTANT) + all_const = false; args.push_back(p_func->arguments[i]->get_datatype()); } - int argcount=args.size(); - - bool failed_builtin=false; + int argcount = args.size(); + bool failed_builtin = false; - if (argcount<=4) { + if (argcount <= 4) { // test builtins - int idx=0; + int idx = 0; while (builtin_func_defs[idx].name) { - if (name==builtin_func_defs[idx].name) { + if (name == builtin_func_defs[idx].name) { - failed_builtin=true; - bool fail=false; - for(int i=0;i<argcount;i++) { + failed_builtin = true; + bool fail = false; + for (int i = 0; i < argcount; i++) { - if (get_scalar_type(args[i])==args[i] && p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode*>(p_func->arguments[i+1]),builtin_func_defs[idx].args[i])) { + if (get_scalar_type(args[i]) == args[i] && p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode *>(p_func->arguments[i + 1]), builtin_func_defs[idx].args[i])) { //all good - } else if (args[i]!=builtin_func_defs[idx].args[i]) { - fail=true; + } else if (args[i] != builtin_func_defs[idx].args[i]) { + fail = true; break; } } - if (!fail && argcount<4 && builtin_func_defs[idx].args[argcount]!=TYPE_VOID) - fail=true; //make sure the number of arguments matches + if (!fail && argcount < 4 && builtin_func_defs[idx].args[argcount] != TYPE_VOID) + fail = true; //make sure the number of arguments matches if (!fail) { if (r_ret_type) - *r_ret_type=builtin_func_defs[idx].rettype; + *r_ret_type = builtin_func_defs[idx].rettype; return true; } - } idx++; @@ -1828,17 +1791,17 @@ bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p } if (failed_builtin) { - String err ="Invalid arguments for built-in function: "+String(name)+"("; - for(int i=0;i<argcount;i++) { - if (i>0) - err+=","; + String err = "Invalid arguments for built-in function: " + String(name) + "("; + for (int i = 0; i < argcount; i++) { + if (i > 0) + err += ","; - if (p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && p_func->arguments[i+1]->get_datatype()==TYPE_INT && static_cast<ConstantNode*>(p_func->arguments[i+1])->values[0].sint<0) { - err+="-"; + if (p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && p_func->arguments[i + 1]->get_datatype() == TYPE_INT && static_cast<ConstantNode *>(p_func->arguments[i + 1])->values[0].sint < 0) { + err += "-"; } - err+=get_datatype_name(args[i]); + err += get_datatype_name(args[i]); } - err+=")"; + err += ")"; _set_error(err); return false; } @@ -1904,51 +1867,48 @@ bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p StringName exclude_function; BlockNode *block = p_block; - while(block) { + while (block) { if (block->parent_function) { - exclude_function=block->parent_function->name; + exclude_function = block->parent_function->name; } - block=block->parent_block; + block = block->parent_block; } - if (name==exclude_function) { + if (name == exclude_function) { _set_error("Recursion is not allowed"); return false; } - for(int i=0;i<shader->functions.size();i++) { - + for (int i = 0; i < shader->functions.size(); i++) { if (name != shader->functions[i].name) continue; if (!shader->functions[i].callable) { - _set_error("Function '"+String(name)+" can't be called from source code."); + _set_error("Function '" + String(name) + " can't be called from source code."); return false; } FunctionNode *pfunc = shader->functions[i].function; - - if (pfunc->arguments.size()!=args.size()) + if (pfunc->arguments.size() != args.size()) continue; - bool fail=false; + bool fail = false; + for (int i = 0; i < args.size(); i++) { - for(int i=0;i<args.size();i++) { - - if (get_scalar_type(args[i])==args[i] && p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode*>(p_func->arguments[i+1]),pfunc->arguments[i].type)) { + if (get_scalar_type(args[i]) == args[i] && p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode *>(p_func->arguments[i + 1]), pfunc->arguments[i].type)) { //all good - } else if (args[i]!=pfunc->arguments[i].type) { - fail=true; + } else if (args[i] != pfunc->arguments[i].type) { + fail = true; break; } } if (!fail) { - p_func->return_cache=pfunc->return_type; + p_func->return_cache = pfunc->return_type; return true; } } @@ -1956,58 +1916,51 @@ bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p return false; } - -bool ShaderLanguage::_parse_function_arguments(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types,OperatorNode* p_func,int *r_complete_arg) { +bool ShaderLanguage::_parse_function_arguments(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, OperatorNode *p_func, int *r_complete_arg) { TkPos pos = _get_tkpos(); Token tk = _get_token(); - if (tk.type==TK_PARENTHESIS_CLOSE) { + if (tk.type == TK_PARENTHESIS_CLOSE) { return true; } _set_tkpos(pos); - - while(true) { - + while (true) { if (r_complete_arg) { pos = _get_tkpos(); tk = _get_token(); - if (tk.type==TK_CURSOR) { + if (tk.type == TK_CURSOR) { - *r_complete_arg=p_func->arguments.size()-1; + *r_complete_arg = p_func->arguments.size() - 1; } else { _set_tkpos(pos); } } - Node *arg= _parse_and_reduce_expression(p_block,p_builtin_types); + Node *arg = _parse_and_reduce_expression(p_block, p_builtin_types); if (!arg) { return false; } - p_func->arguments.push_back(arg); tk = _get_token(); - - if (tk.type==TK_PARENTHESIS_CLOSE) { + if (tk.type == TK_PARENTHESIS_CLOSE) { return true; - } else if (tk.type!=TK_COMMA) { + } else if (tk.type != TK_COMMA) { // something is broken _set_error("Expected ',' or ')' after argument"); return false; } - - } return true; @@ -2015,112 +1968,108 @@ bool ShaderLanguage::_parse_function_arguments(BlockNode* p_block,const Map<Stri bool ShaderLanguage::is_token_operator(TokenType p_type) { - - return (p_type==TK_OP_EQUAL || - p_type==TK_OP_NOT_EQUAL || - p_type==TK_OP_LESS || - p_type==TK_OP_LESS_EQUAL || - p_type==TK_OP_GREATER || - p_type==TK_OP_GREATER_EQUAL || - p_type==TK_OP_AND || - p_type==TK_OP_OR || - p_type==TK_OP_NOT || - p_type==TK_OP_ADD || - p_type==TK_OP_SUB || - p_type==TK_OP_MUL || - p_type==TK_OP_DIV || - p_type==TK_OP_MOD || - p_type==TK_OP_SHIFT_LEFT || - p_type==TK_OP_SHIFT_RIGHT || - p_type==TK_OP_ASSIGN || - p_type==TK_OP_ASSIGN_ADD || - p_type==TK_OP_ASSIGN_SUB || - p_type==TK_OP_ASSIGN_MUL || - p_type==TK_OP_ASSIGN_DIV || - p_type==TK_OP_ASSIGN_MOD || - p_type==TK_OP_ASSIGN_SHIFT_LEFT || - p_type==TK_OP_ASSIGN_SHIFT_RIGHT || - p_type==TK_OP_ASSIGN_BIT_AND || - p_type==TK_OP_ASSIGN_BIT_OR || - p_type==TK_OP_ASSIGN_BIT_XOR || - p_type==TK_OP_BIT_AND || - p_type==TK_OP_BIT_OR || - p_type==TK_OP_BIT_XOR || - p_type==TK_OP_BIT_INVERT || - p_type==TK_OP_INCREMENT || - p_type==TK_OP_DECREMENT || - p_type==TK_QUESTION || - p_type==TK_COLON ); - + return (p_type == TK_OP_EQUAL || + p_type == TK_OP_NOT_EQUAL || + p_type == TK_OP_LESS || + p_type == TK_OP_LESS_EQUAL || + p_type == TK_OP_GREATER || + p_type == TK_OP_GREATER_EQUAL || + p_type == TK_OP_AND || + p_type == TK_OP_OR || + p_type == TK_OP_NOT || + p_type == TK_OP_ADD || + p_type == TK_OP_SUB || + p_type == TK_OP_MUL || + p_type == TK_OP_DIV || + p_type == TK_OP_MOD || + p_type == TK_OP_SHIFT_LEFT || + p_type == TK_OP_SHIFT_RIGHT || + p_type == TK_OP_ASSIGN || + p_type == TK_OP_ASSIGN_ADD || + p_type == TK_OP_ASSIGN_SUB || + p_type == TK_OP_ASSIGN_MUL || + p_type == TK_OP_ASSIGN_DIV || + p_type == TK_OP_ASSIGN_MOD || + p_type == TK_OP_ASSIGN_SHIFT_LEFT || + p_type == TK_OP_ASSIGN_SHIFT_RIGHT || + p_type == TK_OP_ASSIGN_BIT_AND || + p_type == TK_OP_ASSIGN_BIT_OR || + p_type == TK_OP_ASSIGN_BIT_XOR || + p_type == TK_OP_BIT_AND || + p_type == TK_OP_BIT_OR || + p_type == TK_OP_BIT_XOR || + p_type == TK_OP_BIT_INVERT || + p_type == TK_OP_INCREMENT || + p_type == TK_OP_DECREMENT || + p_type == TK_QUESTION || + p_type == TK_COLON); } -bool ShaderLanguage::convert_constant(ConstantNode* p_constant, DataType p_to_type,ConstantNode::Value *p_value) { +bool ShaderLanguage::convert_constant(ConstantNode *p_constant, DataType p_to_type, ConstantNode::Value *p_value) { - if (p_constant->datatype==p_to_type) { + if (p_constant->datatype == p_to_type) { if (p_value) { - for(int i=0;i<p_constant->values.size();i++) { - p_value[i]=p_constant->values[i]; + for (int i = 0; i < p_constant->values.size(); i++) { + p_value[i] = p_constant->values[i]; } } return true; - } else if (p_constant->datatype==TYPE_INT && p_to_type==TYPE_FLOAT) { + } else if (p_constant->datatype == TYPE_INT && p_to_type == TYPE_FLOAT) { if (p_value) { - p_value->real=p_constant->values[0].sint; + p_value->real = p_constant->values[0].sint; } return true; - } else if (p_constant->datatype==TYPE_UINT && p_to_type==TYPE_FLOAT) { + } else if (p_constant->datatype == TYPE_UINT && p_to_type == TYPE_FLOAT) { if (p_value) { - p_value->real=p_constant->values[0].uint; + p_value->real = p_constant->values[0].uint; } return true; - } else if (p_constant->datatype==TYPE_INT && p_to_type==TYPE_UINT) { - if (p_constant->values[0].sint<0) { + } else if (p_constant->datatype == TYPE_INT && p_to_type == TYPE_UINT) { + if (p_constant->values[0].sint < 0) { return false; } if (p_value) { - p_value->uint=p_constant->values[0].sint; + p_value->uint = p_constant->values[0].sint; } return true; - } else if (p_constant->datatype==TYPE_UINT && p_to_type==TYPE_INT) { + } else if (p_constant->datatype == TYPE_UINT && p_to_type == TYPE_INT) { - if (p_constant->values[0].uint>0x7FFFFFFF) { + if (p_constant->values[0].uint > 0x7FFFFFFF) { return false; } if (p_value) { - p_value->sint=p_constant->values[0].uint; + p_value->sint = p_constant->values[0].uint; } return true; } else return false; - } bool ShaderLanguage::is_scalar_type(DataType p_type) { - return p_type==TYPE_BOOL || p_type==TYPE_INT || p_type==TYPE_UINT || p_type==TYPE_FLOAT; + return p_type == TYPE_BOOL || p_type == TYPE_INT || p_type == TYPE_UINT || p_type == TYPE_FLOAT; } bool ShaderLanguage::is_sampler_type(DataType p_type) { - return p_type==TYPE_SAMPLER2D || p_type==TYPE_ISAMPLER2D || p_type==TYPE_USAMPLER2D || p_type==TYPE_SAMPLERCUBE; - + return p_type == TYPE_SAMPLER2D || p_type == TYPE_ISAMPLER2D || p_type == TYPE_USAMPLER2D || p_type == TYPE_SAMPLERCUBE; } void ShaderLanguage::get_keyword_list(List<String> *r_keywords) { Set<String> kws; - int idx=0; + int idx = 0; - while(keyword_list[idx].text) { + while (keyword_list[idx].text) { kws.insert(keyword_list[idx].text); idx++; } - idx=0; + idx = 0; while (builtin_func_defs[idx].name) { @@ -2129,17 +2078,16 @@ void ShaderLanguage::get_keyword_list(List<String> *r_keywords) { idx++; } - for(Set<String>::Element *E=kws.front();E;E=E->next()) { + for (Set<String>::Element *E = kws.front(); E; E = E->next()) { r_keywords->push_back(E->get()); } } void ShaderLanguage::get_builtin_funcs(List<String> *r_keywords) { - Set<String> kws; - int idx=0; + int idx = 0; while (builtin_func_defs[idx].name) { @@ -2148,16 +2096,14 @@ void ShaderLanguage::get_builtin_funcs(List<String> *r_keywords) { idx++; } - for(Set<String>::Element *E=kws.front();E;E=E->next()) { + for (Set<String>::Element *E = kws.front(); E; E = E->next()) { r_keywords->push_back(E->get()); } } - - ShaderLanguage::DataType ShaderLanguage::get_scalar_type(DataType p_type) { - static const DataType scalar_types[]={ + static const DataType scalar_types[] = { TYPE_VOID, TYPE_BOOL, TYPE_BOOL, @@ -2187,115 +2133,109 @@ ShaderLanguage::DataType ShaderLanguage::get_scalar_type(DataType p_type) { return scalar_types[p_type]; } +bool ShaderLanguage::_get_completable_identifier(BlockNode *p_block, CompletionType p_type, StringName &identifier) { -bool ShaderLanguage::_get_completable_identifier(BlockNode *p_block,CompletionType p_type,StringName& identifier) { - - identifier=StringName(); + identifier = StringName(); TkPos pos; Token tk = _get_token(); - if (tk.type==TK_IDENTIFIER) { - identifier=tk.text; - pos = _get_tkpos(); + if (tk.type == TK_IDENTIFIER) { + identifier = tk.text; + pos = _get_tkpos(); tk = _get_token(); } - if (tk.type==TK_CURSOR) { + if (tk.type == TK_CURSOR) { - completion_type=p_type; - completion_line=tk_line; - completion_block=p_block; + completion_type = p_type; + completion_line = tk_line; + completion_block = p_block; pos = _get_tkpos(); tk = _get_token(); - if (tk.type==TK_IDENTIFIER) { - identifier=identifier.operator String() + tk.text.operator String(); + if (tk.type == TK_IDENTIFIER) { + identifier = identifier.operator String() + tk.text.operator String(); } else { _set_tkpos(pos); } return true; - } else if (identifier!=StringName()){ + } else if (identifier != StringName()) { _set_tkpos(pos); } return false; } - - -ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types) { +ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types) { Vector<Expression> expression; //Vector<TokenType> operators; - while(true) { + while (true) { - Node *expr=NULL; + Node *expr = NULL; TkPos prepos = _get_tkpos(); Token tk = _get_token(); - TkPos pos = _get_tkpos(); - + TkPos pos = _get_tkpos(); - if (tk.type==TK_PARENTHESIS_OPEN) { + if (tk.type == TK_PARENTHESIS_OPEN) { //handle subexpression - expr = _parse_and_reduce_expression(p_block,p_builtin_types); + expr = _parse_and_reduce_expression(p_block, p_builtin_types); if (!expr) return NULL; tk = _get_token(); - if (tk.type!=TK_PARENTHESIS_CLOSE) { + if (tk.type != TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in expression"); return NULL; } - } else if (tk.type==TK_REAL_CONSTANT) { - + } else if (tk.type == TK_REAL_CONSTANT) { ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; - v.real=tk.constant; + v.real = tk.constant; constant->values.push_back(v); - constant->datatype=TYPE_FLOAT; - expr=constant; - - } else if (tk.type==TK_INT_CONSTANT) { + constant->datatype = TYPE_FLOAT; + expr = constant; + } else if (tk.type == TK_INT_CONSTANT) { ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; - v.sint=tk.constant; + v.sint = tk.constant; constant->values.push_back(v); - constant->datatype=TYPE_INT; - expr=constant; + constant->datatype = TYPE_INT; + expr = constant; - } else if (tk.type==TK_TRUE) { + } else if (tk.type == TK_TRUE) { //print_line("found true"); //handle true constant ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; - v.boolean=true; + v.boolean = true; constant->values.push_back(v); - constant->datatype=TYPE_BOOL; - expr=constant; + constant->datatype = TYPE_BOOL; + expr = constant; - } else if (tk.type==TK_FALSE) { + } else if (tk.type == TK_FALSE) { //handle false constant ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; - v.boolean=false; + v.boolean = false; constant->values.push_back(v); - constant->datatype=TYPE_BOOL; - expr=constant; + constant->datatype = TYPE_BOOL; + expr = constant; - } else if (tk.type==TK_TYPE_VOID) { + } else if (tk.type == TK_TYPE_VOID) { //make sure void is not used in expression _set_error("Void value not allowed in Expression"); @@ -2304,98 +2244,93 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const //basic type constructor OperatorNode *func = alloc_node<OperatorNode>(); - func->op=OP_CONSTRUCT; - + func->op = OP_CONSTRUCT; if (is_token_precision(tk.type)) { - func->return_precision_cache=get_token_precision(tk.type); - tk=_get_token(); + func->return_precision_cache = get_token_precision(tk.type); + tk = _get_token(); } VariableNode *funcname = alloc_node<VariableNode>(); - funcname->name=get_datatype_name(get_token_datatype(tk.type)); + funcname->name = get_datatype_name(get_token_datatype(tk.type)); func->arguments.push_back(funcname); - tk=_get_token(); - if (tk.type!=TK_PARENTHESIS_OPEN) { + tk = _get_token(); + if (tk.type != TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after type name"); return NULL; } - int carg=-1; + int carg = -1; - bool ok = _parse_function_arguments(p_block,p_builtin_types,func,&carg); + bool ok = _parse_function_arguments(p_block, p_builtin_types, func, &carg); - if (carg>=0) { - completion_type=COMPLETION_CALL_ARGUMENTS; - completion_line=tk_line; - completion_block=p_block; - completion_function=funcname->name; - completion_argument=carg; + if (carg >= 0) { + completion_type = COMPLETION_CALL_ARGUMENTS; + completion_line = tk_line; + completion_block = p_block; + completion_function = funcname->name; + completion_argument = carg; } if (!ok) return NULL; - if (!_validate_function_call(p_block,func,&func->return_cache)) { - _set_error("No matching constructor found for: '"+String(funcname->name)+"'"); + if (!_validate_function_call(p_block, func, &func->return_cache)) { + _set_error("No matching constructor found for: '" + String(funcname->name) + "'"); return NULL; } //validate_Function_call() - expr=_reduce_expression(p_block,func); + expr = _reduce_expression(p_block, func); - - } else if (tk.type==TK_IDENTIFIER) { + } else if (tk.type == TK_IDENTIFIER) { _set_tkpos(prepos); StringName identifier; - _get_completable_identifier(p_block,COMPLETION_IDENTIFIER,identifier); - + _get_completable_identifier(p_block, COMPLETION_IDENTIFIER, identifier); - tk=_get_token(); - if (tk.type==TK_PARENTHESIS_OPEN) { + tk = _get_token(); + if (tk.type == TK_PARENTHESIS_OPEN) { //a function StringName name = identifier; OperatorNode *func = alloc_node<OperatorNode>(); - func->op=OP_CALL; + func->op = OP_CALL; VariableNode *funcname = alloc_node<VariableNode>(); - funcname->name=name; + funcname->name = name; func->arguments.push_back(funcname); - int carg=-1; + int carg = -1; - bool ok =_parse_function_arguments(p_block,p_builtin_types,func,&carg); + bool ok = _parse_function_arguments(p_block, p_builtin_types, func, &carg); - for(int i=0;i<shader->functions.size();i++) { - if (shader->functions[i].name==name) { + for (int i = 0; i < shader->functions.size(); i++) { + if (shader->functions[i].name == name) { shader->functions[i].uses_function.insert(name); } } - - - if (carg>=0) { - completion_type=COMPLETION_CALL_ARGUMENTS; - completion_line=tk_line; - completion_block=p_block; - completion_function=funcname->name; - completion_argument=carg; + if (carg >= 0) { + completion_type = COMPLETION_CALL_ARGUMENTS; + completion_line = tk_line; + completion_block = p_block; + completion_function = funcname->name; + completion_argument = carg; } if (!ok) return NULL; - if (!_validate_function_call(p_block,func,&func->return_cache)) { - _set_error("No matching function found for: '"+String(funcname->name)+"'"); + if (!_validate_function_call(p_block, func, &func->return_cache)) { + _set_error("No matching function found for: '" + String(funcname->name) + "'"); return NULL; } - expr=func; + expr = func; } else { //an identifier @@ -2405,71 +2340,65 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const DataType data_type; IdentifierType ident_type; - if (!_find_identifier(p_block,p_builtin_types,identifier,&data_type,&ident_type)) { - _set_error("Unknown identifier in expression: "+String(identifier)); + if (!_find_identifier(p_block, p_builtin_types, identifier, &data_type, &ident_type)) { + _set_error("Unknown identifier in expression: " + String(identifier)); return NULL; } - if (ident_type==IDENTIFIER_FUNCTION) { - _set_error("Can't use function as identifier: "+String(identifier)); + if (ident_type == IDENTIFIER_FUNCTION) { + _set_error("Can't use function as identifier: " + String(identifier)); return NULL; } - VariableNode *varname = alloc_node<VariableNode>(); - varname->name=identifier; - varname->datatype_cache=data_type; - expr=varname; - + varname->name = identifier; + varname->datatype_cache = data_type; + expr = varname; } - - } else if (tk.type==TK_OP_ADD) { + } else if (tk.type == TK_OP_ADD) { continue; //this one does nothing - } else if (tk.type==TK_OP_SUB || tk.type==TK_OP_NOT || tk.type==TK_OP_BIT_INVERT || tk.type==TK_OP_INCREMENT || tk.type==TK_OP_DECREMENT) { - + } else if (tk.type == TK_OP_SUB || tk.type == TK_OP_NOT || tk.type == TK_OP_BIT_INVERT || tk.type == TK_OP_INCREMENT || tk.type == TK_OP_DECREMENT) { Expression e; - e.is_op=true; - - switch(tk.type) { - case TK_OP_SUB: e.op=OP_NEGATE; break; - case TK_OP_NOT: e.op=OP_NOT; break; - case TK_OP_BIT_INVERT: e.op=OP_BIT_INVERT; break; - case TK_OP_INCREMENT: e.op=OP_INCREMENT; break; - case TK_OP_DECREMENT: e.op=OP_DECREMENT; break; + e.is_op = true; + + switch (tk.type) { + case TK_OP_SUB: e.op = OP_NEGATE; break; + case TK_OP_NOT: e.op = OP_NOT; break; + case TK_OP_BIT_INVERT: e.op = OP_BIT_INVERT; break; + case TK_OP_INCREMENT: e.op = OP_INCREMENT; break; + case TK_OP_DECREMENT: e.op = OP_DECREMENT; break; default: ERR_FAIL_V(NULL); } expression.push_back(e); continue; - } else { - _set_error("Expected expression, found: "+get_token_text(tk)); + _set_error("Expected expression, found: " + get_token_text(tk)); return NULL; //nothing } - ERR_FAIL_COND_V(!expr,NULL); - + ERR_FAIL_COND_V(!expr, NULL); /* OK now see what's NEXT to the operator.. */ /* OK now see what's NEXT to the operator.. */ /* OK now see what's NEXT to the operator.. */ - while(true) { + while (true) { TkPos pos = _get_tkpos(); - tk=_get_token(); + tk = _get_token(); - if (tk.type==TK_PERIOD) { + if (tk.type == TK_PERIOD) { StringName identifier; - if (_get_completable_identifier(p_block,COMPLETION_INDEX,identifier)) { - completion_base=expr->get_datatype(); + if (_get_completable_identifier(p_block, COMPLETION_INDEX, identifier)) { + completion_base = expr->get_datatype(); } - if (identifier==StringName()) { + if (identifier == StringName()) { _set_error("Expected identifier as member"); return NULL; } @@ -2477,35 +2406,35 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const DataType dt = expr->get_datatype(); String ident = identifier; - bool ok=true; + bool ok = true; DataType member_type; - switch(dt) { + switch (dt) { case TYPE_BVEC2: case TYPE_IVEC2: case TYPE_UVEC2: case TYPE_VEC2: { int l = ident.length(); - if (l==1) { - member_type=DataType(dt-1); - } else if (l==2) { - member_type=dt; + if (l == 1) { + member_type = DataType(dt - 1); + } else if (l == 2) { + member_type = dt; } else { - ok=false; + ok = false; break; } - const CharType *c=ident.ptr(); - for(int i=0;i<l;i++) { + const CharType *c = ident.ptr(); + for (int i = 0; i < l; i++) { - switch(c[i]) { + switch (c[i]) { case 'r': case 'g': case 'x': case 'y': break; default: - ok=false; + ok = false; break; } } @@ -2517,21 +2446,21 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const case TYPE_VEC3: { int l = ident.length(); - if (l==1) { - member_type=DataType(dt-2); - } else if (l==2) { - member_type=DataType(dt-1); - } else if (l==3) { - member_type=dt; + if (l == 1) { + member_type = DataType(dt - 2); + } else if (l == 2) { + member_type = DataType(dt - 1); + } else if (l == 3) { + member_type = dt; } else { - ok=false; + ok = false; break; } - const CharType *c=ident.ptr(); - for(int i=0;i<l;i++) { + const CharType *c = ident.ptr(); + for (int i = 0; i < l; i++) { - switch(c[i]) { + switch (c[i]) { case 'r': case 'g': case 'b': @@ -2540,7 +2469,7 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const case 'z': break; default: - ok=false; + ok = false; break; } } @@ -2552,23 +2481,23 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const case TYPE_VEC4: { int l = ident.length(); - if (l==1) { - member_type=DataType(dt-3); - } else if (l==2) { - member_type=DataType(dt-2); - } else if (l==3) { - member_type=DataType(dt-1); - } else if (l==4) { - member_type=dt; + if (l == 1) { + member_type = DataType(dt - 3); + } else if (l == 2) { + member_type = DataType(dt - 2); + } else if (l == 3) { + member_type = DataType(dt - 1); + } else if (l == 4) { + member_type = dt; } else { - ok=false; + ok = false; break; } - const CharType *c=ident.ptr(); - for(int i=0;i<l;i++) { + const CharType *c = ident.ptr(); + for (int i = 0; i < l; i++) { - switch(c[i]) { + switch (c[i]) { case 'r': case 'g': case 'b': @@ -2579,55 +2508,62 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const case 'w': break; default: - ok=false; + ok = false; break; } } } break; - case TYPE_MAT2: ok=(ident=="x" || ident=="y"); member_type=TYPE_VEC2; break; - case TYPE_MAT3: ok=(ident=="x" || ident=="y" || ident=="z" ); member_type=TYPE_VEC3; break; - case TYPE_MAT4: ok=(ident=="x" || ident=="y" || ident=="z" || ident=="w"); member_type=TYPE_VEC4; break; + case TYPE_MAT2: + ok = (ident == "x" || ident == "y"); + member_type = TYPE_VEC2; + break; + case TYPE_MAT3: + ok = (ident == "x" || ident == "y" || ident == "z"); + member_type = TYPE_VEC3; + break; + case TYPE_MAT4: + ok = (ident == "x" || ident == "y" || ident == "z" || ident == "w"); + member_type = TYPE_VEC4; + break; default: {} } if (!ok) { - _set_error("Invalid member for expression: ."+ident); + _set_error("Invalid member for expression: ." + ident); return NULL; } MemberNode *mn = alloc_node<MemberNode>(); - mn->basetype=dt; - mn->datatype=member_type; - mn->name=ident; - mn->owner=expr; - expr=mn; - + mn->basetype = dt; + mn->datatype = member_type; + mn->name = ident; + mn->owner = expr; + expr = mn; //todo //member (period) has priority over any operator //creates a subindexing expression in place - - /*} else if (tk.type==TK_BRACKET_OPEN) { + /*} else if (tk.type==TK_BRACKET_OPEN) { //todo //subindexing has priority over any operator //creates a subindexing expression in place */ - } else if (tk.type==TK_OP_INCREMENT || tk.type==TK_OP_DECREMENT) { + } else if (tk.type == TK_OP_INCREMENT || tk.type == TK_OP_DECREMENT) { OperatorNode *op = alloc_node<OperatorNode>(); - op->op=tk.type==TK_OP_DECREMENT ? OP_POST_DECREMENT : OP_POST_INCREMENT; + op->op = tk.type == TK_OP_DECREMENT ? OP_POST_DECREMENT : OP_POST_INCREMENT; op->arguments.push_back(expr); - if (!_validate_operator(op,&op->return_cache)) { + if (!_validate_operator(op, &op->return_cache)) { _set_error("Invalid base type for increment/decrement operator"); return NULL; } - expr=op; - } else { + expr = op; + } else { _set_tkpos(pos); break; @@ -2635,8 +2571,8 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const } Expression e; - e.is_op=false; - e.node=expr; + e.is_op = false; + e.node = expr; expression.push_back(e); pos = _get_tkpos(); @@ -2645,9 +2581,9 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const if (is_token_operator(tk.type)) { Expression o; - o.is_op=true; + o.is_op = true; - switch(tk.type) { + switch (tk.type) { case TK_OP_EQUAL: o.op = OP_EQUAL; break; case TK_OP_NOT_EQUAL: o.op = OP_NOT_EQUAL; break; @@ -2676,12 +2612,12 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const case TK_OP_ASSIGN_BIT_OR: o.op = OP_ASSIGN_BIT_OR; break; case TK_OP_ASSIGN_BIT_XOR: o.op = OP_ASSIGN_BIT_XOR; break; case TK_OP_BIT_AND: o.op = OP_BIT_AND; break; - case TK_OP_BIT_OR: o.op = OP_BIT_OR ; break; + case TK_OP_BIT_OR: o.op = OP_BIT_OR; break; case TK_OP_BIT_XOR: o.op = OP_BIT_XOR; break; case TK_QUESTION: o.op = OP_SELECT_IF; break; case TK_COLON: o.op = OP_SELECT_ELSE; break; default: { - _set_error("Invalid token for operator: "+get_token_text(tk)); + _set_error("Invalid token for operator: " + get_token_text(tk)); return NULL; } } @@ -2694,92 +2630,110 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const } } - - /* 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; + int next_op = -1; + int min_priority = 0xFFFFF; + bool is_unary = false; + bool is_ternary = false; - for(int i=0;i<expression.size();i++) { + for (int i = 0; i < expression.size(); i++) { if (!expression[i].is_op) { continue; } - bool unary=false; - bool ternary=false; + bool unary = false; + bool ternary = false; int priority; - switch(expression[i].op) { - case OP_EQUAL: priority=8; break; - case OP_NOT_EQUAL: priority=8; break; - case OP_LESS: priority=7; break; - case OP_LESS_EQUAL: priority=7; break; - case OP_GREATER: priority=7; break; - case OP_GREATER_EQUAL: priority=7; break; - case OP_AND: priority=12; break; - case OP_OR: priority=14; break; - case OP_NOT: priority=3; unary=true; break; - case OP_NEGATE: priority=3; unary=true; break; - case OP_ADD: priority=5; break; - case OP_SUB: priority=5; break; - case OP_MUL: priority=4; break; - case OP_DIV: priority=4; break; - case OP_MOD: priority=4; break; - case OP_SHIFT_LEFT: priority=6; break; - case OP_SHIFT_RIGHT: priority=6; break; - case OP_ASSIGN: priority=16; break; - case OP_ASSIGN_ADD: priority=16; break; - case OP_ASSIGN_SUB: priority=16; break; - case OP_ASSIGN_MUL: priority=16; break; - case OP_ASSIGN_DIV: priority=16; break; - case OP_ASSIGN_MOD: priority=16; break; - case OP_ASSIGN_SHIFT_LEFT: priority=16; break; - case OP_ASSIGN_SHIFT_RIGHT: priority=16; break; - case OP_ASSIGN_BIT_AND: priority=16; break; - case OP_ASSIGN_BIT_OR: priority=16; break; - case OP_ASSIGN_BIT_XOR: priority=16; break; - case OP_BIT_AND: priority=9; break; - case OP_BIT_OR: priority=11; break; - case OP_BIT_XOR: priority=10; break; - case OP_BIT_INVERT: priority=3; unary=true; break; - case OP_INCREMENT: priority=3; unary=true; break; - case OP_DECREMENT: priority=3; unary=true; break; - case OP_SELECT_IF: priority=15; ternary=true; break; - case OP_SELECT_ELSE: priority=15; ternary=true; break; - - default: ERR_FAIL_V(NULL); //unexpected operator - - } - - if (priority<min_priority) { + switch (expression[i].op) { + case OP_EQUAL: priority = 8; break; + case OP_NOT_EQUAL: priority = 8; break; + case OP_LESS: priority = 7; break; + case OP_LESS_EQUAL: priority = 7; break; + case OP_GREATER: priority = 7; break; + case OP_GREATER_EQUAL: priority = 7; break; + case OP_AND: priority = 12; break; + case OP_OR: priority = 14; break; + case OP_NOT: + priority = 3; + unary = true; + break; + case OP_NEGATE: + priority = 3; + unary = true; + break; + case OP_ADD: priority = 5; break; + case OP_SUB: priority = 5; break; + case OP_MUL: priority = 4; break; + case OP_DIV: priority = 4; break; + case OP_MOD: priority = 4; break; + case OP_SHIFT_LEFT: priority = 6; break; + case OP_SHIFT_RIGHT: priority = 6; break; + case OP_ASSIGN: priority = 16; break; + case OP_ASSIGN_ADD: priority = 16; break; + case OP_ASSIGN_SUB: priority = 16; break; + case OP_ASSIGN_MUL: priority = 16; break; + case OP_ASSIGN_DIV: priority = 16; break; + case OP_ASSIGN_MOD: priority = 16; break; + case OP_ASSIGN_SHIFT_LEFT: priority = 16; break; + case OP_ASSIGN_SHIFT_RIGHT: priority = 16; break; + case OP_ASSIGN_BIT_AND: priority = 16; break; + case OP_ASSIGN_BIT_OR: priority = 16; break; + case OP_ASSIGN_BIT_XOR: priority = 16; break; + case OP_BIT_AND: priority = 9; break; + case OP_BIT_OR: priority = 11; break; + case OP_BIT_XOR: priority = 10; break; + case OP_BIT_INVERT: + priority = 3; + unary = true; + break; + case OP_INCREMENT: + priority = 3; + unary = true; + break; + case OP_DECREMENT: + priority = 3; + unary = true; + break; + case OP_SELECT_IF: + priority = 15; + ternary = true; + break; + case OP_SELECT_ELSE: + priority = 15; + ternary = true; + break; + + default: + ERR_FAIL_V(NULL); //unexpected operator + } + + if (priority < min_priority) { // < 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; } - } - ERR_FAIL_COND_V(next_op==-1,NULL); + ERR_FAIL_COND_V(next_op == -1, NULL); // OK! create operator.. // 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; @@ -2787,162 +2741,149 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const } //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); - - expression[i].is_op=false; - expression[i].node=op; + op->op = expression[i].op; + op->arguments.push_back(expression[i + 1].node); + expression[i].is_op = false; + expression[i].node = op; - if (!_validate_operator(op,&op->return_cache)) { + if (!_validate_operator(op, &op->return_cache)) { String at; - for(int i=0;i<op->arguments.size();i++) { - if (i>0) - at+=" and "; - at+=get_datatype_name(op->arguments[i]->get_datatype()); - + for (int i = 0; i < op->arguments.size(); i++) { + if (i > 0) + at += " and "; + at += get_datatype_name(op->arguments[i]->get_datatype()); } - _set_error("Invalid arguments to unary operator '"+get_operator_text(op->op)+"' :" +at); + _set_error("Invalid arguments to unary operator '" + get_operator_text(op->op) + "' :" + at); return NULL; } - expression.remove(i+1); + expression.remove(i + 1); } } else if (is_ternary) { - 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); } - if (next_op+2 >= expression.size() || !expression[next_op+2].is_op || expression[next_op+2].op!=OP_SELECT_ELSE) { + if (next_op + 2 >= expression.size() || !expression[next_op + 2].is_op || expression[next_op + 2].op != OP_SELECT_ELSE) { _set_error("Mising matching ':' for select operator"); return NULL; } - - OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[next_op].op; - op->arguments.push_back(expression[next_op-1].node); - op->arguments.push_back(expression[next_op+1].node); - op->arguments.push_back(expression[next_op+3].node); + op->op = expression[next_op].op; + op->arguments.push_back(expression[next_op - 1].node); + op->arguments.push_back(expression[next_op + 1].node); + op->arguments.push_back(expression[next_op + 3].node); - expression[next_op-1].is_op=false; - expression[next_op-1].node=op; - if (!_validate_operator(op,&op->return_cache)) { + expression[next_op - 1].is_op = false; + expression[next_op - 1].node = op; + if (!_validate_operator(op, &op->return_cache)) { String at; - for(int i=0;i<op->arguments.size();i++) { - if (i>0) - at+=" and "; - at+=get_datatype_name(op->arguments[i]->get_datatype()); - + for (int i = 0; i < op->arguments.size(); i++) { + if (i > 0) + at += " and "; + at += get_datatype_name(op->arguments[i]->get_datatype()); } - _set_error("Invalid argument to ternary ?: operator: "+at); + _set_error("Invalid argument to ternary ?: operator: " + at); return NULL; } - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { 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->op = expression[next_op].op; - 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, // due to how precedence works, unaries will always dissapear first _set_error("Parser bug.."); - } - - 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 - expression[next_op-1].node=op; + 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 + expression[next_op - 1].node = op; //replace all 3 nodes by this operator and make it an expression - if (!_validate_operator(op,&op->return_cache)) { + if (!_validate_operator(op, &op->return_cache)) { String at; - for(int i=0;i<op->arguments.size();i++) { - if (i>0) - at+=" and "; - at+=get_datatype_name(op->arguments[i]->get_datatype()); - + for (int i = 0; i < op->arguments.size(); i++) { + if (i > 0) + at += " and "; + at += get_datatype_name(op->arguments[i]->get_datatype()); } - _set_error("Invalid arguments to operator '"+get_operator_text(op->op)+"' :" +at); + _set_error("Invalid arguments to operator '" + get_operator_text(op->op) + "' :" + at); return NULL; } expression.remove(next_op); expression.remove(next_op); } - } return expression[0].node; } +ShaderLanguage::Node *ShaderLanguage::_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node) { -ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node) { - - if (p_node->type!=Node::TYPE_OPERATOR) + if (p_node->type != Node::TYPE_OPERATOR) return p_node; //for now only reduce simple constructors - OperatorNode *op=static_cast<OperatorNode*>(p_node); - - if (op->op==OP_CONSTRUCT) { + OperatorNode *op = static_cast<OperatorNode *>(p_node); + if (op->op == OP_CONSTRUCT) { - ERR_FAIL_COND_V(op->arguments[0]->type!=Node::TYPE_VARIABLE,p_node); - VariableNode *vn = static_cast<VariableNode*>(op->arguments[0]); + ERR_FAIL_COND_V(op->arguments[0]->type != Node::TYPE_VARIABLE, p_node); + VariableNode *vn = static_cast<VariableNode *>(op->arguments[0]); //StringName name=vn->name; - DataType base=get_scalar_type(op->get_datatype()); + DataType base = get_scalar_type(op->get_datatype()); Vector<ConstantNode::Value> values; + for (int i = 1; i < op->arguments.size(); i++) { - for(int i=1;i<op->arguments.size();i++) { - - - op->arguments[i]=_reduce_expression(p_block,op->arguments[i]); - if (op->arguments[i]->type==Node::TYPE_CONSTANT) { - ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[i]); + op->arguments[i] = _reduce_expression(p_block, op->arguments[i]); + if (op->arguments[i]->type == Node::TYPE_CONSTANT) { + ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i]); - if (get_scalar_type(cn->datatype)==base) { + if (get_scalar_type(cn->datatype) == base) { - for(int j=0;j<cn->values.size();j++) { + for (int j = 0; j < cn->values.size(); j++) { values.push_back(cn->values[j]); } - } else if (get_scalar_type(cn->datatype)==cn->datatype) { + } else if (get_scalar_type(cn->datatype) == cn->datatype) { ConstantNode::Value v; - if (!convert_constant(cn,base,&v)) { + if (!convert_constant(cn, base, &v)) { return p_node; } values.push_back(v); @@ -2955,37 +2896,36 @@ ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, Sha } } - - ConstantNode *cn=alloc_node<ConstantNode>(); - cn->datatype=op->get_datatype(); - cn->values=values; + ConstantNode *cn = alloc_node<ConstantNode>(); + cn->datatype = op->get_datatype(); + cn->values = values; return cn; - } else if (op->op==OP_NEGATE) { + } else if (op->op == OP_NEGATE) { - op->arguments[0]=_reduce_expression(p_block,op->arguments[0]); - if (op->arguments[0]->type==Node::TYPE_CONSTANT) { + op->arguments[0] = _reduce_expression(p_block, op->arguments[0]); + if (op->arguments[0]->type == Node::TYPE_CONSTANT) { - ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[0]); + ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[0]); - DataType base=get_scalar_type(cn->datatype); + DataType base = get_scalar_type(cn->datatype); Vector<ConstantNode::Value> values; - for(int i=0;i<cn->values.size();i++) { + for (int i = 0; i < cn->values.size(); i++) { ConstantNode::Value nv; - switch(base) { + switch (base) { case TYPE_BOOL: { - nv.boolean=!cn->values[i].boolean; + nv.boolean = !cn->values[i].boolean; } break; case TYPE_INT: { - nv.sint=-cn->values[i].sint; + nv.sint = -cn->values[i].sint; } break; case TYPE_UINT: { - nv.uint=-cn->values[i].uint; + nv.uint = -cn->values[i].uint; } break; case TYPE_FLOAT: { - nv.real=-cn->values[i].real; + nv.real = -cn->values[i].real; } break; default: {} } @@ -2993,41 +2933,33 @@ ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, Sha values.push_back(nv); } - - cn->values=values; + cn->values = values; return cn; } } return p_node; - - } +ShaderLanguage::Node *ShaderLanguage::_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types) { -ShaderLanguage::Node* ShaderLanguage::_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types) { - - - ShaderLanguage::Node* expr = _parse_expression(p_block,p_builtin_types); + ShaderLanguage::Node *expr = _parse_expression(p_block, p_builtin_types); if (!expr) //errored return NULL; - expr = _reduce_expression(p_block,expr); + expr = _reduce_expression(p_block, expr); return expr; } +Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, bool p_just_one, bool p_can_break, bool p_can_continue) { - - -Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types,bool p_just_one,bool p_can_break,bool p_can_continue) { - - while(true) { + while (true) { TkPos pos = _get_tkpos(); Token tk = _get_token(); - if (tk.type==TK_CURLY_BRACKET_CLOSE) { //end of block + if (tk.type == TK_CURLY_BRACKET_CLOSE) { //end of block if (p_just_one) { _set_error("Unexpected '}'"); return ERR_PARSE_ERROR; @@ -3036,9 +2968,9 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT return OK; } else if (is_token_precision(tk.type) || is_token_nonvoid_datatype(tk.type)) { - DataPrecision precision=PRECISION_DEFAULT; + DataPrecision precision = PRECISION_DEFAULT; if (is_token_precision(tk.type)) { - precision=get_token_precision(tk.type); + precision = get_token_precision(tk.type); tk = _get_token(); if (!is_token_nonvoid_datatype(tk.type)) { _set_error("Expected datatype after precission"); @@ -3050,97 +2982,96 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT tk = _get_token(); - while(true) { + while (true) { - if (tk.type!=TK_IDENTIFIER) { + if (tk.type != TK_IDENTIFIER) { _set_error("Expected identifier after type"); return ERR_PARSE_ERROR; } StringName name = tk.text; - if (_find_identifier(p_block,p_builtin_types,name)) { - _set_error("Redefinition of '"+String(name)+"'"); + if (_find_identifier(p_block, p_builtin_types, name)) { + _set_error("Redefinition of '" + String(name) + "'"); return ERR_PARSE_ERROR; } BlockNode::Variable var; - var.type=type; - var.precision=precision; - var.line=tk_line; - p_block->variables[name]=var; + var.type = type; + var.precision = precision; + var.line = tk_line; + p_block->variables[name] = var; tk = _get_token(); - if (tk.type==TK_OP_ASSIGN) { + if (tk.type == TK_OP_ASSIGN) { //variable creted with assignment! must parse an expression - Node* n = _parse_and_reduce_expression(p_block,p_builtin_types); + Node *n = _parse_and_reduce_expression(p_block, p_builtin_types); if (!n) return ERR_PARSE_ERROR; OperatorNode *assign = alloc_node<OperatorNode>(); VariableNode *vnode = alloc_node<VariableNode>(); - vnode->name=name; - vnode->datatype_cache=type; + vnode->name = name; + vnode->datatype_cache = type; assign->arguments.push_back(vnode); assign->arguments.push_back(n); - assign->op=OP_ASSIGN; + assign->op = OP_ASSIGN; p_block->statements.push_back(assign); tk = _get_token(); } - if (tk.type==TK_COMMA) { + if (tk.type == TK_COMMA) { tk = _get_token(); //another variable - } else if (tk.type==TK_SEMICOLON) { + } else if (tk.type == TK_SEMICOLON) { break; } else { _set_error("Expected ',' or ';' after variable"); return ERR_PARSE_ERROR; } } - } else if (tk.type==TK_CURLY_BRACKET_OPEN) { + } else if (tk.type == TK_CURLY_BRACKET_OPEN) { //a sub block, just because.. - BlockNode* block = alloc_node<BlockNode>(); - block->parent_block=p_block; - _parse_block(block,p_builtin_types,false,p_can_break,p_can_continue); + BlockNode *block = alloc_node<BlockNode>(); + block->parent_block = p_block; + _parse_block(block, p_builtin_types, false, p_can_break, p_can_continue); p_block->statements.push_back(block); - } else if (tk.type==TK_CF_IF) { + } else if (tk.type == TK_CF_IF) { //if () {} tk = _get_token(); - if (tk.type!=TK_PARENTHESIS_OPEN) { + if (tk.type != TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after if"); return ERR_PARSE_ERROR; } ControlFlowNode *cf = alloc_node<ControlFlowNode>(); - cf->flow_op=FLOW_OP_IF; - Node* n = _parse_and_reduce_expression(p_block,p_builtin_types); + cf->flow_op = FLOW_OP_IF; + Node *n = _parse_and_reduce_expression(p_block, p_builtin_types); if (!n) return ERR_PARSE_ERROR; tk = _get_token(); - if (tk.type!=TK_PARENTHESIS_CLOSE) { + if (tk.type != TK_PARENTHESIS_CLOSE) { _set_error("Expected '(' after expression"); return ERR_PARSE_ERROR; } - BlockNode* block = alloc_node<BlockNode>(); - block->parent_block=p_block; + BlockNode *block = alloc_node<BlockNode>(); + block->parent_block = p_block; cf->expressions.push_back(n); cf->blocks.push_back(block); p_block->statements.push_back(cf); + Error err = _parse_block(block, p_builtin_types, true, p_can_break, p_can_continue); - Error err=_parse_block(block,p_builtin_types,true,p_can_break,p_can_continue); - - pos=_get_tkpos(); + pos = _get_tkpos(); tk = _get_token(); - if (tk.type==TK_CF_ELSE) { + if (tk.type == TK_CF_ELSE) { block = alloc_node<BlockNode>(); - block->parent_block=p_block; + block->parent_block = p_block; cf->blocks.push_back(block); - err=_parse_block(block,p_builtin_types,true,p_can_break,p_can_continue); + err = _parse_block(block, p_builtin_types, true, p_can_break, p_can_continue); } else { _set_tkpos(pos); //rollback @@ -3150,13 +3081,13 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT //nothng else, so expression _set_tkpos(pos); //rollback - Node*expr = _parse_and_reduce_expression(p_block,p_builtin_types); + Node *expr = _parse_and_reduce_expression(p_block, p_builtin_types); if (!expr) return ERR_PARSE_ERROR; p_block->statements.push_back(expr); tk = _get_token(); - if (tk.type!=TK_SEMICOLON) { + if (tk.type != TK_SEMICOLON) { _set_error("Expected ';' after statement"); return ERR_PARSE_ERROR; } @@ -3169,49 +3100,47 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT return OK; } - -Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes) { - +Error ShaderLanguage::_parse_shader(const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes) { Token tk = _get_token(); int texture_uniforms = 0; - int uniforms =0; + int uniforms = 0; - while(tk.type!=TK_EOF) { + while (tk.type != TK_EOF) { - switch(tk.type) { + switch (tk.type) { case TK_RENDER_MODE: { - while(true) { + while (true) { StringName mode; - _get_completable_identifier(NULL,COMPLETION_RENDER_MODE,mode); + _get_completable_identifier(NULL, COMPLETION_RENDER_MODE, mode); - if (mode==StringName()) { + if (mode == StringName()) { _set_error("Expected identifier for render mode"); return ERR_PARSE_ERROR; } if (!p_render_modes.has(mode)) { - _set_error("Invalid render mode: '"+String(mode)+"'"); + _set_error("Invalid render mode: '" + String(mode) + "'"); return ERR_PARSE_ERROR; } - if (shader->render_modes.find(mode)!=-1) { - _set_error("Duplicate render mode: '"+String(mode)+"'"); + if (shader->render_modes.find(mode) != -1) { + _set_error("Duplicate render mode: '" + String(mode) + "'"); return ERR_PARSE_ERROR; } shader->render_modes.push_back(mode); tk = _get_token(); - if (tk.type==TK_COMMA) { + if (tk.type == TK_COMMA) { //all good, do nothing - } else if (tk.type==TK_SEMICOLON) { + } else if (tk.type == TK_SEMICOLON) { break; //done } else { - _set_error("Unexpected token: "+get_token_text(tk)); + _set_error("Unexpected token: " + get_token_text(tk)); return ERR_PARSE_ERROR; } } @@ -3219,14 +3148,14 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy case TK_UNIFORM: case TK_VARYING: { - bool uniform = tk.type==TK_UNIFORM; + bool uniform = tk.type == TK_UNIFORM; DataPrecision precision = PRECISION_DEFAULT; DataType type; StringName name; tk = _get_token(); if (is_token_precision(tk.type)) { - precision=get_token_precision(tk.type); + precision = get_token_precision(tk.type); tk = _get_token(); } @@ -3237,25 +3166,25 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy type = get_token_datatype(tk.type); - if (type==TYPE_VOID) { + if (type == TYPE_VOID) { _set_error("void datatype not allowed here"); return ERR_PARSE_ERROR; } - if (!uniform && type<TYPE_FLOAT && type>TYPE_VEC4) { // FIXME: always false! should it be || instead? + if (!uniform && type < TYPE_FLOAT && type > TYPE_VEC4) { // FIXME: always false! should it be || instead? _set_error("Invalid type for varying, only float,vec2,vec3,vec4 allowed."); return ERR_PARSE_ERROR; } tk = _get_token(); - if (tk.type!=TK_IDENTIFIER) { + if (tk.type != TK_IDENTIFIER) { _set_error("Expected identifier!"); return ERR_PARSE_ERROR; } - name=tk.text; + name = tk.text; - if (_find_identifier(NULL,Map<StringName,DataType>(),name)) { - _set_error("Redefinition of '"+String(name)+"'"); + if (_find_identifier(NULL, Map<StringName, DataType>(), name)) { + _set_error("Redefinition of '" + String(name) + "'"); return ERR_PARSE_ERROR; } @@ -3264,179 +3193,173 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy ShaderNode::Uniform uniform; if (is_sampler_type(type)) { - uniform.texture_order=texture_uniforms++; - uniform.order=-1; + uniform.texture_order = texture_uniforms++; + uniform.order = -1; } else { - uniform.texture_order=-1; - uniform.order=uniforms++; + uniform.texture_order = -1; + uniform.order = uniforms++; } - uniform.type=type; - uniform.precission=precision; + uniform.type = type; + uniform.precission = precision; //todo parse default value tk = _get_token(); - if (tk.type==TK_OP_ASSIGN) { + if (tk.type == TK_OP_ASSIGN) { - Node* expr = _parse_and_reduce_expression(NULL,Map<StringName,DataType>()); + Node *expr = _parse_and_reduce_expression(NULL, Map<StringName, DataType>()); if (!expr) return ERR_PARSE_ERROR; - if (expr->type!=Node::TYPE_CONSTANT) { + if (expr->type != Node::TYPE_CONSTANT) { _set_error("Expected constant expression after '='"); return ERR_PARSE_ERROR; } - ConstantNode* cn = static_cast<ConstantNode*>(expr); + ConstantNode *cn = static_cast<ConstantNode *>(expr); uniform.default_value.resize(cn->values.size()); - if (!convert_constant(cn,uniform.type,uniform.default_value.ptr())) { - _set_error("Can't convert constant to "+get_datatype_name(uniform.type)); + if (!convert_constant(cn, uniform.type, uniform.default_value.ptr())) { + _set_error("Can't convert constant to " + get_datatype_name(uniform.type)); return ERR_PARSE_ERROR; } tk = _get_token(); } - if (tk.type==TK_COLON) { + if (tk.type == TK_COLON) { //hint tk = _get_token(); - if (tk.type==TK_HINT_WHITE_TEXTURE) { - uniform.hint=ShaderNode::Uniform::HINT_WHITE; - } else if (tk.type==TK_HINT_BLACK_TEXTURE) { - uniform.hint=ShaderNode::Uniform::HINT_BLACK; - } else if (tk.type==TK_HINT_NORMAL_TEXTURE) { - uniform.hint=ShaderNode::Uniform::HINT_NORMAL; - } else if (tk.type==TK_HINT_ANISO_TEXTURE) { - uniform.hint=ShaderNode::Uniform::HINT_ANISO; - } else if (tk.type==TK_HINT_ALBEDO_TEXTURE) { - uniform.hint=ShaderNode::Uniform::HINT_ALBEDO; - } else if (tk.type==TK_HINT_BLACK_ALBEDO_TEXTURE) { - uniform.hint=ShaderNode::Uniform::HINT_BLACK_ALBEDO; - } else if (tk.type==TK_HINT_COLOR) { - if (type!=TYPE_VEC4) { + if (tk.type == TK_HINT_WHITE_TEXTURE) { + uniform.hint = ShaderNode::Uniform::HINT_WHITE; + } else if (tk.type == TK_HINT_BLACK_TEXTURE) { + uniform.hint = ShaderNode::Uniform::HINT_BLACK; + } else if (tk.type == TK_HINT_NORMAL_TEXTURE) { + uniform.hint = ShaderNode::Uniform::HINT_NORMAL; + } else if (tk.type == TK_HINT_ANISO_TEXTURE) { + uniform.hint = ShaderNode::Uniform::HINT_ANISO; + } else if (tk.type == TK_HINT_ALBEDO_TEXTURE) { + uniform.hint = ShaderNode::Uniform::HINT_ALBEDO; + } else if (tk.type == TK_HINT_BLACK_ALBEDO_TEXTURE) { + uniform.hint = ShaderNode::Uniform::HINT_BLACK_ALBEDO; + } else if (tk.type == TK_HINT_COLOR) { + if (type != TYPE_VEC4) { _set_error("Color hint is for vec4 only"); return ERR_PARSE_ERROR; } - uniform.hint=ShaderNode::Uniform::HINT_COLOR; - } else if (tk.type==TK_HINT_RANGE) { + uniform.hint = ShaderNode::Uniform::HINT_COLOR; + } else if (tk.type == TK_HINT_RANGE) { - uniform.hint=ShaderNode::Uniform::HINT_RANGE; - if (type!=TYPE_FLOAT && type!=TYPE_INT) { + uniform.hint = ShaderNode::Uniform::HINT_RANGE; + if (type != TYPE_FLOAT && type != TYPE_INT) { _set_error("Range hint is for float and int only"); return ERR_PARSE_ERROR; } tk = _get_token(); - if (tk.type!=TK_PARENTHESIS_OPEN) { + if (tk.type != TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after hint_range"); return ERR_PARSE_ERROR; } tk = _get_token(); - float sign=1.0; + float sign = 1.0; - if (tk.type==TK_OP_SUB) { - sign=-1.0; + if (tk.type == TK_OP_SUB) { + sign = -1.0; tk = _get_token(); } - if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) { + if (tk.type != TK_REAL_CONSTANT && tk.type != TK_INT_CONSTANT) { _set_error("Expected integer constant"); return ERR_PARSE_ERROR; } - uniform.hint_range[0]=tk.constant; - uniform.hint_range[0]*=sign; + uniform.hint_range[0] = tk.constant; + uniform.hint_range[0] *= sign; tk = _get_token(); - if (tk.type!=TK_COMMA) { + if (tk.type != TK_COMMA) { _set_error("Expected ',' after integer constant"); return ERR_PARSE_ERROR; } tk = _get_token(); - sign=1.0; + sign = 1.0; - if (tk.type==TK_OP_SUB) { - sign=-1.0; + if (tk.type == TK_OP_SUB) { + sign = -1.0; tk = _get_token(); } - - if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) { + if (tk.type != TK_REAL_CONSTANT && tk.type != TK_INT_CONSTANT) { _set_error("Expected integer constant after ','"); return ERR_PARSE_ERROR; } - uniform.hint_range[1]=tk.constant; - uniform.hint_range[1]*=sign; + uniform.hint_range[1] = tk.constant; + uniform.hint_range[1] *= sign; tk = _get_token(); - if (tk.type==TK_COMMA) { + if (tk.type == TK_COMMA) { tk = _get_token(); - if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) { + if (tk.type != TK_REAL_CONSTANT && tk.type != TK_INT_CONSTANT) { _set_error("Expected integer constant after ','"); return ERR_PARSE_ERROR; } - uniform.hint_range[2]=tk.constant; + uniform.hint_range[2] = tk.constant; tk = _get_token(); } else { - if (type==TYPE_INT) { - uniform.hint_range[2]=1; + if (type == TYPE_INT) { + uniform.hint_range[2] = 1; } else { - uniform.hint_range[2]=0.001; + uniform.hint_range[2] = 0.001; } } - if (tk.type!=TK_PARENTHESIS_CLOSE) { + if (tk.type != TK_PARENTHESIS_CLOSE) { _set_error("Expected ','"); return ERR_PARSE_ERROR; } - } else { _set_error("Expected valid type hint after ':'."); } - if (uniform.hint!=ShaderNode::Uniform::HINT_RANGE && uniform.hint!=ShaderNode::Uniform::HINT_NONE && uniform.hint!=ShaderNode::Uniform::HINT_COLOR && type <=TYPE_MAT4) { + if (uniform.hint != ShaderNode::Uniform::HINT_RANGE && uniform.hint != ShaderNode::Uniform::HINT_NONE && uniform.hint != ShaderNode::Uniform::HINT_COLOR && type <= TYPE_MAT4) { _set_error("This hint is only for sampler types"); return ERR_PARSE_ERROR; - } tk = _get_token(); } - shader->uniforms[name]=uniform; + shader->uniforms[name] = uniform; - if (tk.type!=TK_SEMICOLON) { + if (tk.type != TK_SEMICOLON) { _set_error("Expected ';'"); return ERR_PARSE_ERROR; } } else { ShaderNode::Varying varying; - varying.type=type; - varying.precission=precision; - shader->varyings[name]=varying; + varying.type = type; + varying.precission = precision; + shader->varyings[name] = varying; tk = _get_token(); - if (tk.type!=TK_SEMICOLON) { + if (tk.type != TK_SEMICOLON) { _set_error("Expected ';'"); return ERR_PARSE_ERROR; } - } - - } break; default: { //function @@ -3446,7 +3369,7 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy StringName name; if (is_token_precision(tk.type)) { - precision=get_token_precision(tk.type); + precision = get_token_precision(tk.type); tk = _get_token(); } @@ -3457,56 +3380,51 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy type = get_token_datatype(tk.type); - _get_completable_identifier(NULL,COMPLETION_MAIN_FUNCTION,name); + _get_completable_identifier(NULL, COMPLETION_MAIN_FUNCTION, name); - if (name==StringName()) { + if (name == StringName()) { _set_error("Expected function name after datatype"); return ERR_PARSE_ERROR; - } - - if (_find_identifier(NULL,Map<StringName,DataType>(),name)) { - _set_error("Redefinition of '"+String(name)+"'"); + if (_find_identifier(NULL, Map<StringName, DataType>(), name)) { + _set_error("Redefinition of '" + String(name) + "'"); return ERR_PARSE_ERROR; } tk = _get_token(); - if (tk.type!=TK_PARENTHESIS_OPEN) { + if (tk.type != TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after identifier"); return ERR_PARSE_ERROR; - } - - Map<StringName,DataType> builtin_types; + Map<StringName, DataType> builtin_types; if (p_functions.has(name)) { - builtin_types=p_functions[name]; + builtin_types = p_functions[name]; } ShaderNode::Function function; - function.callable=!p_functions.has(name); - function.name=name; + function.callable = !p_functions.has(name); + function.name = name; - FunctionNode* func_node=alloc_node<FunctionNode>(); + FunctionNode *func_node = alloc_node<FunctionNode>(); - function.function=func_node; + function.function = func_node; shader->functions.push_back(function); - func_node->name=name; - func_node->return_type=type; - func_node->return_precision=precision; + func_node->name = name; + func_node->return_type = type; + func_node->return_precision = precision; func_node->body = alloc_node<BlockNode>(); - func_node->body->parent_function=func_node; - + func_node->body->parent_function = func_node; tk = _get_token(); - while(true) { - if (tk.type==TK_PARENTHESIS_CLOSE) { + while (true) { + if (tk.type == TK_PARENTHESIS_CLOSE) { break; } @@ -3515,7 +3433,7 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy DataPrecision pprecision = PRECISION_DEFAULT; if (is_token_precision(tk.type)) { - pprecision=get_token_precision(tk.type); + pprecision = get_token_precision(tk.type); tk = _get_token(); } @@ -3524,73 +3442,70 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy return ERR_PARSE_ERROR; } - ptype=get_token_datatype(tk.type); + ptype = get_token_datatype(tk.type); - if (ptype==TYPE_VOID) { + if (ptype == TYPE_VOID) { _set_error("void not allowed in argument"); return ERR_PARSE_ERROR; } tk = _get_token(); - if (tk.type!=TK_IDENTIFIER) { + if (tk.type != TK_IDENTIFIER) { _set_error("Expected identifier for argument name"); return ERR_PARSE_ERROR; } pname = tk.text; - if (_find_identifier(func_node->body,builtin_types,pname)) { - _set_error("Redefinition of '"+String(pname)+"'"); + if (_find_identifier(func_node->body, builtin_types, pname)) { + _set_error("Redefinition of '" + String(pname) + "'"); return ERR_PARSE_ERROR; } FunctionNode::Argument arg; - arg.type=ptype; - arg.name=pname; - arg.precision=pprecision; + arg.type = ptype; + arg.name = pname; + arg.precision = pprecision; func_node->arguments.push_back(arg); tk = _get_token(); - - if (tk.type==TK_COMMA) { + if (tk.type == TK_COMMA) { tk = _get_token(); //do none and go on - } else if (tk.type!=TK_PARENTHESIS_CLOSE) { + } else if (tk.type != TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')' after identifier"); return ERR_PARSE_ERROR; } - } if (p_functions.has(name)) { //if one of the core functions, make sure they are of the correct form if (func_node->arguments.size() > 0) { - _set_error("Function '"+String(name)+"' expects no arguments."); + _set_error("Function '" + String(name) + "' expects no arguments."); return ERR_PARSE_ERROR; } - if (func_node->return_type!=TYPE_VOID) { - _set_error("Function '"+String(name)+"' must be of void return type."); + if (func_node->return_type != TYPE_VOID) { + _set_error("Function '" + String(name) + "' must be of void return type."); return ERR_PARSE_ERROR; } } - //all good let's parse inside the fucntion! tk = _get_token(); - if (tk.type!=TK_CURLY_BRACKET_OPEN) { + if (tk.type != TK_CURLY_BRACKET_OPEN) { _set_error("Expected '{' to begin function"); return ERR_PARSE_ERROR; } current_function = name; - Error err = _parse_block(func_node->body,builtin_types); + Error err = _parse_block(func_node->body, builtin_types); if (err) return err; - current_function=StringName(); + current_function = StringName(); } } @@ -3600,42 +3515,42 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy return OK; } -Error ShaderLanguage::compile(const String& p_code, const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes) { +Error ShaderLanguage::compile(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes) { clear(); - code=p_code; + code = p_code; - nodes=NULL; + nodes = NULL; shader = alloc_node<ShaderNode>(); - Error err = _parse_shader(p_functions,p_render_modes); + Error err = _parse_shader(p_functions, p_render_modes); - if (err!=OK) { + if (err != OK) { return err; } return OK; } -Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes,List<String>* r_options,String& r_call_hint) { +Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes, List<String> *r_options, String &r_call_hint) { clear(); - code=p_code; + code = p_code; - nodes=NULL; + nodes = NULL; shader = alloc_node<ShaderNode>(); - Error err = _parse_shader(p_functions,p_render_modes); + Error err = _parse_shader(p_functions, p_render_modes); - switch(completion_type) { + switch (completion_type) { case COMPLETION_NONE: { //do none return ERR_PARSE_ERROR; } break; case COMPLETION_RENDER_MODE: { - for(const Set<String>::Element *E=p_render_modes.front();E;E=E->next()) { + for (const Set<String>::Element *E = p_render_modes.front(); E; E = E->next()) { r_options->push_back(E->get()); } @@ -3644,7 +3559,7 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S } break; case COMPLETION_MAIN_FUNCTION: { - for(const Map< StringName, Map<StringName,DataType> >::Element *E=p_functions.front();E;E=E->next()) { + for (const Map<StringName, Map<StringName, DataType> >::Element *E = p_functions.front(); E; E = E->next()) { r_options->push_back(E->key()); } @@ -3654,71 +3569,66 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S case COMPLETION_IDENTIFIER: case COMPLETION_FUNCTION_CALL: { - bool comp_ident=completion_type==COMPLETION_IDENTIFIER; + bool comp_ident = completion_type == COMPLETION_IDENTIFIER; Set<String> matches; StringName skip_function; - BlockNode *block=completion_block; + BlockNode *block = completion_block; - - while(block) { + while (block) { if (comp_ident) { - for (const Map<StringName,BlockNode::Variable>::Element *E=block->variables.front();E;E=E->next()) { + for (const Map<StringName, BlockNode::Variable>::Element *E = block->variables.front(); E; E = E->next()) { - if (E->get().line<completion_line) { + if (E->get().line < completion_line) { matches.insert(E->key()); } } } - if (block->parent_function) { if (comp_ident) { - for(int i=0;i<block->parent_function->arguments.size();i++) { + for (int i = 0; i < block->parent_function->arguments.size(); i++) { matches.insert(block->parent_function->arguments[i].name); } } - skip_function=block->parent_function->name; + skip_function = block->parent_function->name; } - block=block->parent_block; + block = block->parent_block; } - if (comp_ident && skip_function!=StringName() && p_functions.has(skip_function)) { + if (comp_ident && skip_function != StringName() && p_functions.has(skip_function)) { - for (Map<StringName,DataType>::Element *E=p_functions[skip_function].front();E;E=E->next()) { + for (Map<StringName, DataType>::Element *E = p_functions[skip_function].front(); E; E = E->next()) { matches.insert(E->key()); } } if (comp_ident) { - for (const Map<StringName,ShaderNode::Varying>::Element *E=shader->varyings.front();E;E=E->next()) { + for (const Map<StringName, ShaderNode::Varying>::Element *E = shader->varyings.front(); E; E = E->next()) { matches.insert(E->key()); - } - for (const Map<StringName,ShaderNode::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) { + for (const Map<StringName, ShaderNode::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) { matches.insert(E->key()); } - - } - for(int i=0;i<shader->functions.size();i++) { - if (!shader->functions[i].callable || shader->functions[i].name==skip_function) + for (int i = 0; i < shader->functions.size(); i++) { + if (!shader->functions[i].callable || shader->functions[i].name == skip_function) continue; - matches.insert(String(shader->functions[i].name)+"("); + matches.insert(String(shader->functions[i].name) + "("); } - int idx=0; + int idx = 0; while (builtin_func_defs[idx].name) { - matches.insert(String(builtin_func_defs[idx].name)+"("); + matches.insert(String(builtin_func_defs[idx].name) + "("); idx++; } - for(Set<String>::Element *E=matches.front();E;E=E->next()) { + for (Set<String>::Element *E = matches.front(); E; E = E->next()) { r_options->push_back(E->get()); } @@ -3727,118 +3637,112 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S } break; case COMPLETION_CALL_ARGUMENTS: { - for(int i=0;i<shader->functions.size();i++) { + for (int i = 0; i < shader->functions.size(); i++) { if (!shader->functions[i].callable) continue; - if (shader->functions[i].name==completion_function) { + if (shader->functions[i].name == completion_function) { String calltip; - calltip+=get_datatype_name( shader->functions[i].function->return_type ); - calltip+=" "; - calltip+=shader->functions[i].name; - calltip+="("; + calltip += get_datatype_name(shader->functions[i].function->return_type); + calltip += " "; + calltip += shader->functions[i].name; + calltip += "("; - for(int j=0;j<shader->functions[i].function->arguments.size();j++) { + for (int j = 0; j < shader->functions[i].function->arguments.size(); j++) { - if (j>0) - calltip+=", "; + if (j > 0) + calltip += ", "; else - calltip+=" "; + calltip += " "; - if (j==completion_argument) { - calltip+=CharType(0xFFFF); + if (j == completion_argument) { + calltip += CharType(0xFFFF); } - calltip+=get_datatype_name(shader->functions[i].function->arguments[j].type); - calltip+=" "; - calltip+=shader->functions[i].function->arguments[j].name; + calltip += get_datatype_name(shader->functions[i].function->arguments[j].type); + calltip += " "; + calltip += shader->functions[i].function->arguments[j].name; - if (j==completion_argument) { - calltip+=CharType(0xFFFF); + if (j == completion_argument) { + calltip += CharType(0xFFFF); } - } if (shader->functions[i].function->arguments.size()) - calltip+=" "; - calltip+=")"; + calltip += " "; + calltip += ")"; - r_call_hint=calltip; + r_call_hint = calltip; return OK; } - } - int idx=0; + int idx = 0; String calltip; while (builtin_func_defs[idx].name) { - if (completion_function==builtin_func_defs[idx].name) { + if (completion_function == builtin_func_defs[idx].name) { if (calltip.length()) - calltip+="\n"; + calltip += "\n"; - calltip+=get_datatype_name( builtin_func_defs[idx].rettype ); - calltip+=" "; - calltip+=builtin_func_defs[idx].name; - calltip+="("; + calltip += get_datatype_name(builtin_func_defs[idx].rettype); + calltip += " "; + calltip += builtin_func_defs[idx].name; + calltip += "("; - bool found_arg=false; - for(int i=0;i<4;i++) { + bool found_arg = false; + for (int i = 0; i < 4; i++) { - if (builtin_func_defs[idx].args[i]==TYPE_VOID) + if (builtin_func_defs[idx].args[i] == TYPE_VOID) break; - if (i>0) - calltip+=", "; + if (i > 0) + calltip += ", "; else - calltip+=" "; + calltip += " "; - if (i==completion_argument) { - calltip+=CharType(0xFFFF); + if (i == completion_argument) { + calltip += CharType(0xFFFF); } - calltip+=get_datatype_name(builtin_func_defs[idx].args[i]); + calltip += get_datatype_name(builtin_func_defs[idx].args[i]); - if (i==completion_argument) { - calltip+=CharType(0xFFFF); + if (i == completion_argument) { + calltip += CharType(0xFFFF); } - found_arg=true; - + found_arg = true; } if (found_arg) - calltip+=" "; - calltip+=")"; - - + calltip += " "; + calltip += ")"; } idx++; } - r_call_hint=calltip; + r_call_hint = calltip; return OK; } break; case COMPLETION_INDEX: { - const char colv[4]={'r','g','b','a'}; - const char coordv[4]={'x','y','z','w'}; + const char colv[4] = { 'r', 'g', 'b', 'a' }; + const char coordv[4] = { 'x', 'y', 'z', 'w' }; + int limit = 0; - int limit=0; - - switch(completion_base) { + switch (completion_base) { case TYPE_BVEC2: case TYPE_IVEC2: case TYPE_UVEC2: case TYPE_VEC2: { - limit=2; + limit = 2; } break; case TYPE_BVEC3: @@ -3846,7 +3750,7 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S case TYPE_UVEC3: case TYPE_VEC3: { - limit=3; + limit = 3; } break; case TYPE_BVEC4: @@ -3854,23 +3758,21 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S case TYPE_UVEC4: case TYPE_VEC4: { - limit=4; + limit = 4; } break; - case TYPE_MAT2: limit=2; break; - case TYPE_MAT3: limit=3; break; - case TYPE_MAT4: limit=4; break; + case TYPE_MAT2: limit = 2; break; + case TYPE_MAT3: limit = 3; break; + case TYPE_MAT4: limit = 4; break; default: {} } - for(int i=0;i<limit;i++) { + for (int i = 0; i < limit; i++) { r_options->push_back(String::chr(colv[i])); r_options->push_back(String::chr(coordv[i])); } } break; - - } return ERR_PARSE_ERROR; @@ -3893,12 +3795,10 @@ ShaderLanguage::ShaderNode *ShaderLanguage::get_shader() { ShaderLanguage::ShaderLanguage() { - nodes=NULL; + nodes = NULL; } ShaderLanguage::~ShaderLanguage() { clear(); } - - diff --git a/servers/visual/shader_language.h b/servers/visual/shader_language.h index 4f8717088e..a4757e3419 100644 --- a/servers/visual/shader_language.h +++ b/servers/visual/shader_language.h @@ -29,20 +29,16 @@ #ifndef SHADER_LANGUAGE_H #define SHADER_LANGUAGE_H -#include "typedefs.h" -#include "ustring.h" #include "list.h" -#include "string_db.h" #include "map.h" +#include "string_db.h" +#include "typedefs.h" +#include "ustring.h" #include "variant.h" - -class ShaderLanguage { - - +class ShaderLanguage { public: - enum TokenType { TK_EMPTY, @@ -149,12 +145,12 @@ public: TK_MAX }; - /* COMPILER */ +/* COMPILER */ - // lame work around to Apple defining this as a macro in 10.12 SDK - #ifdef TYPE_BOOL - #undef TYPE_BOOL - #endif +// lame work around to Apple defining this as a macro in 10.12 SDK +#ifdef TYPE_BOOL +#undef TYPE_BOOL +#endif enum DataType { TYPE_VOID, @@ -268,26 +264,29 @@ public: virtual ~Node() {} }; - template<class T> - T* alloc_node() { - T* node = memnew(T); - node->next=nodes; - nodes=node; + template <class T> + T *alloc_node() { + T *node = memnew(T); + node->next = nodes; + nodes = node; return node; } Node *nodes; - struct OperatorNode : public Node { DataType return_cache; DataPrecision return_precision_cache; Operator op; - Vector<Node*> arguments; + Vector<Node *> arguments; virtual DataType get_datatype() const { return return_cache; } - OperatorNode() { type=TYPE_OPERATOR; return_cache=TYPE_VOID; return_precision_cache=PRECISION_DEFAULT; } + OperatorNode() { + type = TYPE_OPERATOR; + return_cache = TYPE_VOID; + return_precision_cache = PRECISION_DEFAULT; + } }; struct VariableNode : public Node { @@ -295,7 +294,10 @@ public: StringName name; virtual DataType get_datatype() const { return datatype_cache; } - VariableNode() { type=TYPE_VARIABLE; datatype_cache=TYPE_VOID; } + VariableNode() { + type = TYPE_VARIABLE; + datatype_cache = TYPE_VOID; + } }; struct ConstantNode : public Node { @@ -312,7 +314,7 @@ public: Vector<Value> values; virtual DataType get_datatype() const { return datatype; } - ConstantNode() { type=TYPE_CONSTANT; } + ConstantNode() { type = TYPE_CONSTANT; } }; struct FunctionNode; @@ -327,17 +329,24 @@ public: int line; //for completion }; - Map<StringName,Variable> variables; - List<Node*> statements; - BlockNode() { type=TYPE_BLOCK; parent_block=NULL; parent_function=NULL; } + Map<StringName, Variable> variables; + List<Node *> statements; + BlockNode() { + type = TYPE_BLOCK; + parent_block = NULL; + parent_function = NULL; + } }; struct ControlFlowNode : public Node { FlowOperation flow_op; - Vector<Node*> expressions; - Vector<BlockNode*> blocks; - ControlFlowNode() { type=TYPE_CONTROL_FLOW; flow_op=FLOW_OP_IF;} + Vector<Node *> expressions; + Vector<BlockNode *> blocks; + ControlFlowNode() { + type = TYPE_CONTROL_FLOW; + flow_op = FLOW_OP_IF; + } }; struct MemberNode : public Node { @@ -345,15 +354,13 @@ public: DataType basetype; DataType datatype; StringName name; - Node* owner; + Node *owner; virtual DataType get_datatype() const { return datatype; } - MemberNode() { type=TYPE_MEMBER; } + MemberNode() { type = TYPE_MEMBER; } }; - struct FunctionNode : public Node { - struct Argument { StringName name; @@ -367,16 +374,17 @@ public: Vector<Argument> arguments; BlockNode *body; - FunctionNode() { type=TYPE_FUNCTION; return_precision=PRECISION_DEFAULT; } - + FunctionNode() { + type = TYPE_FUNCTION; + return_precision = PRECISION_DEFAULT; + } }; - struct ShaderNode : public Node { struct Function { StringName name; - FunctionNode*function; + FunctionNode *function; Set<StringName> uses_function; bool callable; }; @@ -408,20 +416,23 @@ public: Hint hint; float hint_range[3]; - Uniform() { hint=HINT_NONE; hint_range[0]=0; hint_range[1]=1; hint_range[2]=0.001;} + Uniform() { + hint = HINT_NONE; + hint_range[0] = 0; + hint_range[1] = 1; + hint_range[2] = 0.001; + } }; - - Map<StringName,Varying> varyings; - Map<StringName,Uniform> uniforms; + Map<StringName, Varying> varyings; + Map<StringName, Uniform> uniforms; Vector<StringName> render_modes; Vector<Function> functions; - ShaderNode() { type=TYPE_SHADER; } + ShaderNode() { type = TYPE_SHADER; } }; - struct Expression { bool is_op; @@ -431,8 +442,6 @@ public: }; }; - - struct VarInfo { StringName name; @@ -457,7 +466,6 @@ public: uint16_t line; }; - static String get_operator_text(Operator p_op); static String get_token_text(Token p_token); @@ -469,16 +477,19 @@ public: static bool is_token_nonvoid_datatype(TokenType p_type); static bool is_token_operator(TokenType p_type); - static bool convert_constant(ConstantNode* p_constant, DataType p_to_type,ConstantNode::Value *p_value=NULL); + static bool convert_constant(ConstantNode *p_constant, DataType p_to_type, ConstantNode::Value *p_value = NULL); static DataType get_scalar_type(DataType p_type); static bool is_scalar_type(DataType p_type); static bool is_sampler_type(DataType p_type); static void get_keyword_list(List<String> *r_keywords); static void get_builtin_funcs(List<String> *r_keywords); -private: - struct KeyWord { TokenType token; const char *text;}; +private: + struct KeyWord { + TokenType token; + const char *text; + }; static const KeyWord keyword_list[]; bool error_set; @@ -498,33 +509,28 @@ private: TkPos _get_tkpos() { TkPos tkp; - tkp.char_idx=char_idx; - tkp.tk_line=tk_line; + tkp.char_idx = char_idx; + tkp.tk_line = tk_line; return tkp; } - void _set_tkpos(TkPos p_pos) { - char_idx=p_pos.char_idx; - tk_line=p_pos.tk_line; + char_idx = p_pos.char_idx; + tk_line = p_pos.tk_line; } - void _set_error(const String& p_str) { + void _set_error(const String &p_str) { if (error_set) return; - error_line=tk_line; - error_set=true; - error_str=p_str; + error_line = tk_line; + error_set = true; + error_str = p_str; } + static const char *token_names[TK_MAX]; - static const char * token_names[TK_MAX]; - - - - - Token _make_token(TokenType p_type, const StringName& p_text=StringName()); + Token _make_token(TokenType p_type, const StringName &p_text = StringName()); Token _get_token(); ShaderNode *shader; @@ -538,18 +544,16 @@ private: IDENTIFIER_BUILTIN_VAR, }; - bool _find_identifier(const BlockNode* p_block,const Map<StringName, DataType> &p_builtin_types,const StringName& p_identifier, DataType *r_data_type=NULL, IdentifierType *r_type=NULL); - - bool _validate_operator(OperatorNode *p_op,DataType *r_ret_type=NULL); + bool _find_identifier(const BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, const StringName &p_identifier, DataType *r_data_type = NULL, IdentifierType *r_type = NULL); + bool _validate_operator(OperatorNode *p_op, DataType *r_ret_type = NULL); struct BuiltinFuncDef { - enum { MAX_ARGS=5 }; - const char* name; + enum { MAX_ARGS = 5 }; + const char *name; DataType rettype; const DataType args[MAX_ARGS]; - }; CompletionType completion_type; @@ -559,44 +563,38 @@ private: StringName completion_function; int completion_argument; - - bool _get_completable_identifier(BlockNode *p_block, CompletionType p_type, StringName& identifier); + bool _get_completable_identifier(BlockNode *p_block, CompletionType p_type, StringName &identifier); static const BuiltinFuncDef builtin_func_defs[]; - bool _validate_function_call(BlockNode* p_block, OperatorNode *p_func,DataType *r_ret_type); - - bool _parse_function_arguments(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types, OperatorNode* p_func, int *r_complete_arg=NULL); + bool _validate_function_call(BlockNode *p_block, OperatorNode *p_func, DataType *r_ret_type); - Node* _parse_expression(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types); + bool _parse_function_arguments(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, OperatorNode *p_func, int *r_complete_arg = NULL); - ShaderLanguage::Node* _reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node); - Node* _parse_and_reduce_expression(BlockNode *p_block,const Map<StringName,DataType> &p_builtin_types); + Node *_parse_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types); - Error _parse_block(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, bool p_just_one=false, bool p_can_break=false, bool p_can_continue=false); + ShaderLanguage::Node *_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node); + Node *_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types); - Error _parse_shader(const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes); + Error _parse_block(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, bool p_just_one = false, bool p_can_break = false, bool p_can_continue = false); + Error _parse_shader(const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes); public: - //static void get_keyword_list(ShaderType p_type,List<String> *p_keywords); void clear(); - Error compile(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes); - Error complete(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes,List<String>* r_options,String& r_call_hint); - - + Error compile(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes); + Error complete(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes, List<String> *r_options, String &r_call_hint); String get_error_text(); int get_error_line(); ShaderNode *get_shader(); - String token_debug(const String& p_code); + String token_debug(const String &p_code); ShaderLanguage(); ~ShaderLanguage(); }; - #endif // SHADER_LANGUAGE_H diff --git a/servers/visual/shader_types.cpp b/servers/visual/shader_types.cpp index d119e81a4b..cd9afa7735 100644 --- a/servers/visual/shader_types.cpp +++ b/servers/visual/shader_types.cpp @@ -28,85 +28,82 @@ /*************************************************************************/ #include "shader_types.h" - -const Map< StringName, Map<StringName,ShaderLanguage::DataType> >& ShaderTypes::get_functions(VS::ShaderMode p_mode) { +const Map<StringName, Map<StringName, ShaderLanguage::DataType> > &ShaderTypes::get_functions(VS::ShaderMode p_mode) { return shader_modes[p_mode].functions; } -const Set<String>& ShaderTypes::get_modes(VS::ShaderMode p_mode) { +const Set<String> &ShaderTypes::get_modes(VS::ShaderMode p_mode) { return shader_modes[p_mode].modes; } +ShaderTypes *ShaderTypes::singleton = NULL; -ShaderTypes *ShaderTypes::singleton=NULL; - -ShaderTypes::ShaderTypes() -{ - singleton=this; +ShaderTypes::ShaderTypes() { + singleton = this; /*************** SPATIAL ***********************/ - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_VERTEX"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_NORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_TANGENT"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_BONES"]=ShaderLanguage::TYPE_IVEC4; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_WEIGHTS"]=ShaderLanguage::TYPE_VEC4; - - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POSITION"]=ShaderLanguage::TYPE_VEC4 ; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VERTEX"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TANGENT"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["BINORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV2"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POINT_SIZE"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INSTANCE_ID"]=ShaderLanguage::TYPE_INT; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_VERTEX"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_NORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_TANGENT"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_BONES"] = ShaderLanguage::TYPE_IVEC4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_WEIGHTS"] = ShaderLanguage::TYPE_VEC4; + + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POSITION"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VERTEX"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["NORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TANGENT"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["BINORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV2"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POINT_SIZE"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INSTANCE_ID"] = ShaderLanguage::TYPE_INT; //builtins - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INV_CAMERA_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2; - - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VERTEX"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRAGCOORD"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRONT_FACING"]=ShaderLanguage::TYPE_BOOL; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TANGENT"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["BINORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP_DEPTH"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV2"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALBEDO"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALPHA"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECULAR"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ROUGHNESS"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM_TINT"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT_GLOSS"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY_FLOW"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SSS_STRENGTH"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["AO"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["EMISSION"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECIAL"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["DISCARD"]=ShaderLanguage::TYPE_BOOL; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2; - - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["INV_CAMERA_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TIME"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["WORLD_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INV_CAMERA_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["PROJECTION_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TIME"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VIEWPORT_SIZE"] = ShaderLanguage::TYPE_VEC2; + + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VERTEX"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRAGCOORD"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRONT_FACING"] = ShaderLanguage::TYPE_BOOL; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TANGENT"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["BINORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP_DEPTH"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV2"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALBEDO"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALPHA"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECULAR"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ROUGHNESS"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM_TINT"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT_GLOSS"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY_FLOW"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SSS_STRENGTH"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["AO"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["EMISSION"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECIAL"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["DISCARD"] = ShaderLanguage::TYPE_BOOL; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SCREEN_UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["POINT_COORD"] = ShaderLanguage::TYPE_VEC2; + + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["WORLD_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["INV_CAMERA_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["PROJECTION_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TIME"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VIEWPORT_SIZE"] = ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_mix"); shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_add"); @@ -129,48 +126,48 @@ ShaderTypes::ShaderTypes() /************ CANVAS ITEM **************************/ - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["SRC_VERTEX"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX_COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["POINT_SIZE"]=ShaderLanguage::TYPE_FLOAT; - - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["EXTRA_MATRIX"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT; - - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SRC_COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POSITION"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP_DEPTH"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE"]=ShaderLanguage::TYPE_SAMPLER2D; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE_PIXEL_SIZE"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TIME"]=ShaderLanguage::TYPE_FLOAT; - - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POSITION"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE"]=ShaderLanguage::TYPE_SAMPLER2D; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE_PIXEL_SIZE"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR1"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR2"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_VEC"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_HEIGHT"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_UV"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_SHADOW"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SHADOW"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2; - shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TIME"]=ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["SRC_VERTEX"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX_COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["POINT_SIZE"] = ShaderLanguage::TYPE_FLOAT; + + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["WORLD_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["PROJECTION_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["EXTRA_MATRIX"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["TIME"] = ShaderLanguage::TYPE_FLOAT; + + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SRC_COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POSITION"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP_DEPTH"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE"] = ShaderLanguage::TYPE_SAMPLER2D; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE_PIXEL_SIZE"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SCREEN_UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POINT_COORD"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TIME"] = ShaderLanguage::TYPE_FLOAT; + + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POSITION"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["NORMAL"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE"] = ShaderLanguage::TYPE_SAMPLER2D; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE_PIXEL_SIZE"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR1"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR2"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SCREEN_UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_VEC"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_HEIGHT"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_UV"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_SHADOW"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SHADOW"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POINT_COORD"] = ShaderLanguage::TYPE_VEC2; + shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TIME"] = ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("skip_transform"); @@ -183,28 +180,23 @@ ShaderTypes::ShaderTypes() shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("unshaded"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("light_only"); - /************ PARTICLES **************************/ - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["COLOR"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["VELOCITY"]=ShaderLanguage::TYPE_VEC3; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["MASS"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ACTIVE"]=ShaderLanguage::TYPE_BOOL; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["RESTART"]=ShaderLanguage::TYPE_BOOL; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["CUSTOM"]=ShaderLanguage::TYPE_VEC4; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TRANSFORM"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["LIFETIME"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["DELTA"]=ShaderLanguage::TYPE_FLOAT; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["SEED"]=ShaderLanguage::TYPE_BOOL; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ORIGIN"]=ShaderLanguage::TYPE_MAT4; - shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["INDEX"]=ShaderLanguage::TYPE_INT; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["COLOR"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["VELOCITY"] = ShaderLanguage::TYPE_VEC3; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["MASS"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ACTIVE"] = ShaderLanguage::TYPE_BOOL; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["RESTART"] = ShaderLanguage::TYPE_BOOL; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["CUSTOM"] = ShaderLanguage::TYPE_VEC4; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TRANSFORM"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TIME"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["LIFETIME"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["DELTA"] = ShaderLanguage::TYPE_FLOAT; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["SEED"] = ShaderLanguage::TYPE_BOOL; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ORIGIN"] = ShaderLanguage::TYPE_MAT4; + shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["INDEX"] = ShaderLanguage::TYPE_INT; shader_modes[VS::SHADER_PARTICLES].modes.insert("billboard"); shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_force"); shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_velocity"); - - - - } diff --git a/servers/visual/shader_types.h b/servers/visual/shader_types.h index b8a96af922..1bddde8c82 100644 --- a/servers/visual/shader_types.h +++ b/servers/visual/shader_types.h @@ -29,25 +29,25 @@ #ifndef SHADERTYPES_H #define SHADERTYPES_H -#include "shader_language.h" #include "servers/visual_server.h" +#include "shader_language.h" class ShaderTypes { - struct Type { - Map< StringName, Map<StringName,ShaderLanguage::DataType> > functions; - Set<String> modes; + Map<StringName, Map<StringName, ShaderLanguage::DataType> > functions; + Set<String> modes; }; - Map<VS::ShaderMode,Type> shader_modes; + Map<VS::ShaderMode, Type> shader_modes; static ShaderTypes *singleton; + public: static ShaderTypes *get_singleton() { return singleton; } - const Map< StringName, Map<StringName,ShaderLanguage::DataType> >& get_functions(VS::ShaderMode p_mode); - const Set<String>& get_modes(VS::ShaderMode p_mode); + const Map<StringName, Map<StringName, ShaderLanguage::DataType> > &get_functions(VS::ShaderMode p_mode); + const Set<String> &get_modes(VS::ShaderMode p_mode); ShaderTypes(); }; diff --git a/servers/visual/visual_server_canvas.cpp b/servers/visual/visual_server_canvas.cpp index 84cc1a968d..40fa779170 100644 --- a/servers/visual/visual_server_canvas.cpp +++ b/servers/visual/visual_server_canvas.cpp @@ -30,30 +30,27 @@ #include "visual_server_global.h" #include "visual_server_viewport.h" -void VisualServerCanvas::_render_canvas_item_tree(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color& p_modulate, RasterizerCanvas::Light *p_lights) { +void VisualServerCanvas::_render_canvas_item_tree(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, RasterizerCanvas::Light *p_lights) { - - static const int z_range = VS::CANVAS_ITEM_Z_MAX-VS::CANVAS_ITEM_Z_MIN+1; + static const int z_range = VS::CANVAS_ITEM_Z_MAX - VS::CANVAS_ITEM_Z_MIN + 1; RasterizerCanvas::Item *z_list[z_range]; RasterizerCanvas::Item *z_last_list[z_range]; - for(int i=0;i<z_range;i++) { - z_list[i]=NULL; - z_last_list[i]=NULL; + for (int i = 0; i < z_range; i++) { + z_list[i] = NULL; + z_last_list[i] = NULL; } + _render_canvas_item(p_canvas_item, p_transform, p_clip_rect, Color(1, 1, 1, 1), 0, z_list, z_last_list, NULL, NULL); - _render_canvas_item(p_canvas_item,p_transform,p_clip_rect,Color(1,1,1,1),0,z_list,z_last_list,NULL,NULL); - - for(int i=0;i<z_range;i++) { + for (int i = 0; i < z_range; i++) { if (!z_list[i]) continue; - VSG::canvas_render->canvas_render_items(z_list[i],VS::CANVAS_ITEM_Z_MIN+i,p_modulate,p_lights); + VSG::canvas_render->canvas_render_items(z_list[i], VS::CANVAS_ITEM_Z_MIN + i, p_modulate, p_lights); } - } -void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform2D& p_transform,const Rect2& p_clip_rect, const Color &p_modulate,int p_z,RasterizerCanvas::Item **z_list,RasterizerCanvas::Item **z_last_list,Item *p_canvas_clip,Item *p_material_owner) { +void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, int p_z, RasterizerCanvas::Item **z_list, RasterizerCanvas::Item **z_last_list, Item *p_canvas_clip, Item *p_material_owner) { Item *ci = p_canvas_item; @@ -63,55 +60,52 @@ void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform Rect2 rect = ci->get_rect(); Transform2D xform = p_transform * ci->xform; Rect2 global_rect = xform.xform(rect); - global_rect.pos+=p_clip_rect.pos; - + global_rect.pos += p_clip_rect.pos; if (ci->use_parent_material && p_material_owner) - ci->material_owner=p_material_owner; + ci->material_owner = p_material_owner; else { - p_material_owner=ci; - ci->material_owner=NULL; + p_material_owner = ci; + ci->material_owner = NULL; } + Color modulate(ci->modulate.r * p_modulate.r, ci->modulate.g * p_modulate.g, ci->modulate.b * p_modulate.b, ci->modulate.a * p_modulate.a); - Color modulate( ci->modulate.r * p_modulate.r, ci->modulate.g * p_modulate.g,ci->modulate.b * p_modulate.b,ci->modulate.a * p_modulate.a); - - if (modulate.a<0.007) + if (modulate.a < 0.007) return; - - int child_item_count=ci->child_items.size(); - Item **child_items=(Item**)alloca(child_item_count*sizeof(Item*)); - copymem(child_items,ci->child_items.ptr(),child_item_count*sizeof(Item*)); + int child_item_count = ci->child_items.size(); + Item **child_items = (Item **)alloca(child_item_count * sizeof(Item *)); + copymem(child_items, ci->child_items.ptr(), child_item_count * sizeof(Item *)); if (ci->clip) { if (p_canvas_clip != NULL) { - ci->final_clip_rect=p_canvas_clip->final_clip_rect.clip(global_rect); + ci->final_clip_rect = p_canvas_clip->final_clip_rect.clip(global_rect); } else { - ci->final_clip_rect=global_rect; + ci->final_clip_rect = global_rect; } - ci->final_clip_owner=ci; + ci->final_clip_owner = ci; } else { - ci->final_clip_owner=p_canvas_clip; + ci->final_clip_owner = p_canvas_clip; } if (ci->sort_y) { - SortArray<Item*,ItemPtrSort> sorter; - sorter.sort(child_items,child_item_count); + SortArray<Item *, ItemPtrSort> sorter; + sorter.sort(child_items, child_item_count); } if (ci->z_relative) - p_z=CLAMP(p_z+ci->z,VS::CANVAS_ITEM_Z_MIN,VS::CANVAS_ITEM_Z_MAX); + p_z = CLAMP(p_z + ci->z, VS::CANVAS_ITEM_Z_MIN, VS::CANVAS_ITEM_Z_MAX); else - p_z=ci->z; + p_z = ci->z; - for(int i=0;i<child_item_count;i++) { + for (int i = 0; i < child_item_count; i++) { if (!child_items[i]->behind) continue; - _render_canvas_item(child_items[i],xform,p_clip_rect,modulate,p_z,z_list,z_last_list,(Item*)ci->final_clip_owner,p_material_owner); + _render_canvas_item(child_items[i], xform, p_clip_rect, modulate, p_z, z_list, z_last_list, (Item *)ci->final_clip_owner, p_material_owner); } if (ci->copy_back_buffer) { @@ -121,61 +115,55 @@ void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform if ((!ci->commands.empty() && p_clip_rect.intersects(global_rect)) || ci->vp_render || ci->copy_back_buffer) { //something to draw? - ci->final_transform=xform; - ci->final_modulate=Color(modulate.r*ci->self_modulate.r, modulate.g*ci->self_modulate.g, modulate.b*ci->self_modulate.b, modulate.a*ci->self_modulate.a ); - ci->global_rect_cache=global_rect; - ci->global_rect_cache.pos-=p_clip_rect.pos; - ci->light_masked=false; + ci->final_transform = xform; + ci->final_modulate = Color(modulate.r * ci->self_modulate.r, modulate.g * ci->self_modulate.g, modulate.b * ci->self_modulate.b, modulate.a * ci->self_modulate.a); + ci->global_rect_cache = global_rect; + ci->global_rect_cache.pos -= p_clip_rect.pos; + ci->light_masked = false; - int zidx = p_z-VS::CANVAS_ITEM_Z_MIN; + int zidx = p_z - VS::CANVAS_ITEM_Z_MIN; if (z_last_list[zidx]) { - z_last_list[zidx]->next=ci; - z_last_list[zidx]=ci; + z_last_list[zidx]->next = ci; + z_last_list[zidx] = ci; } else { - z_list[zidx]=ci; - z_last_list[zidx]=ci; + z_list[zidx] = ci; + z_last_list[zidx] = ci; } - ci->next=NULL; - + ci->next = NULL; } - for(int i=0;i<child_item_count;i++) { + for (int i = 0; i < child_item_count; i++) { if (child_items[i]->behind) continue; - _render_canvas_item(child_items[i],xform,p_clip_rect,modulate,p_z,z_list,z_last_list,(Item*)ci->final_clip_owner,p_material_owner); + _render_canvas_item(child_items[i], xform, p_clip_rect, modulate, p_z, z_list, z_last_list, (Item *)ci->final_clip_owner, p_material_owner); } - } -void VisualServerCanvas::_light_mask_canvas_items(int p_z,RasterizerCanvas::Item *p_canvas_item,RasterizerCanvas::Light *p_masked_lights) { +void VisualServerCanvas::_light_mask_canvas_items(int p_z, RasterizerCanvas::Item *p_canvas_item, RasterizerCanvas::Light *p_masked_lights) { if (!p_masked_lights) return; - RasterizerCanvas::Item *ci=p_canvas_item; + RasterizerCanvas::Item *ci = p_canvas_item; - while(ci) { + while (ci) { - RasterizerCanvas::Light *light=p_masked_lights; - while(light) { + RasterizerCanvas::Light *light = p_masked_lights; + while (light) { - if (ci->light_mask&light->item_mask && p_z>=light->z_min && p_z<=light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache,light->rect_cache)) { - ci->light_masked=true; + if (ci->light_mask & light->item_mask && p_z >= light->z_min && p_z <= light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) { + ci->light_masked = true; } - light=light->mask_next_ptr; + light = light->mask_next_ptr; } - ci=ci->next; + ci = ci->next; } - - - - } void VisualServerCanvas::render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights, const Rect2 &p_clip_rect) { @@ -183,112 +171,105 @@ void VisualServerCanvas::render_canvas(Canvas *p_canvas, const Transform2D &p_tr VSG::canvas_render->canvas_begin(); int l = p_canvas->child_items.size(); - Canvas::ChildItem *ci=p_canvas->child_items.ptr(); + Canvas::ChildItem *ci = p_canvas->child_items.ptr(); - bool has_mirror=false; - for(int i=0;i<l;i++) { + bool has_mirror = false; + for (int i = 0; i < l; i++) { if (ci[i].mirror.x || ci[i].mirror.y) { - has_mirror=true; + has_mirror = true; break; } } - if (!has_mirror) { - static const int z_range = VS::CANVAS_ITEM_Z_MAX-VS::CANVAS_ITEM_Z_MIN+1; + static const int z_range = VS::CANVAS_ITEM_Z_MAX - VS::CANVAS_ITEM_Z_MIN + 1; RasterizerCanvas::Item *z_list[z_range]; RasterizerCanvas::Item *z_last_list[z_range]; - for(int i=0;i<z_range;i++) { - z_list[i]=NULL; - z_last_list[i]=NULL; + for (int i = 0; i < z_range; i++) { + z_list[i] = NULL; + z_last_list[i] = NULL; } - for(int i=0;i<l;i++) { - _render_canvas_item(ci[i].item,p_transform,p_clip_rect,Color(1,1,1,1),0,z_list,z_last_list,NULL,NULL); + for (int i = 0; i < l; i++) { + _render_canvas_item(ci[i].item, p_transform, p_clip_rect, Color(1, 1, 1, 1), 0, z_list, z_last_list, NULL, NULL); } - for(int i=0;i<z_range;i++) { + for (int i = 0; i < z_range; i++) { if (!z_list[i]) continue; if (p_masked_lights) { - _light_mask_canvas_items(VS::CANVAS_ITEM_Z_MIN+i,z_list[i],p_masked_lights); + _light_mask_canvas_items(VS::CANVAS_ITEM_Z_MIN + i, z_list[i], p_masked_lights); } - VSG::canvas_render->canvas_render_items(z_list[i],VS::CANVAS_ITEM_Z_MIN+i,p_canvas->modulate,p_lights); + VSG::canvas_render->canvas_render_items(z_list[i], VS::CANVAS_ITEM_Z_MIN + i, p_canvas->modulate, p_lights); } } else { - for(int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - Canvas::ChildItem& ci=p_canvas->child_items[i]; - _render_canvas_item_tree(ci.item,p_transform,p_clip_rect,p_canvas->modulate,p_lights); + Canvas::ChildItem &ci = p_canvas->child_items[i]; + _render_canvas_item_tree(ci.item, p_transform, p_clip_rect, p_canvas->modulate, p_lights); //mirroring (useful for scrolling backgrounds) - if (ci.mirror.x!=0) { + if (ci.mirror.x != 0) { - Transform2D xform2 = p_transform * Transform2D(0,Vector2(ci.mirror.x,0)); - _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights); + Transform2D xform2 = p_transform * Transform2D(0, Vector2(ci.mirror.x, 0)); + _render_canvas_item_tree(ci.item, xform2, p_clip_rect, p_canvas->modulate, p_lights); } - if (ci.mirror.y!=0) { + if (ci.mirror.y != 0) { - Transform2D xform2 = p_transform * Transform2D(0,Vector2(0,ci.mirror.y)); - _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights); + Transform2D xform2 = p_transform * Transform2D(0, Vector2(0, ci.mirror.y)); + _render_canvas_item_tree(ci.item, xform2, p_clip_rect, p_canvas->modulate, p_lights); } - if (ci.mirror.y!=0 && ci.mirror.x!=0) { + if (ci.mirror.y != 0 && ci.mirror.x != 0) { - Transform2D xform2 = p_transform * Transform2D(0,ci.mirror); - _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights); + Transform2D xform2 = p_transform * Transform2D(0, ci.mirror); + _render_canvas_item_tree(ci.item, xform2, p_clip_rect, p_canvas->modulate, p_lights); } - } } - } - RID VisualServerCanvas::canvas_create() { - Canvas * canvas = memnew( Canvas ); - ERR_FAIL_COND_V(!canvas,RID()); - RID rid = canvas_owner.make_rid( canvas ); + Canvas *canvas = memnew(Canvas); + ERR_FAIL_COND_V(!canvas, RID()); + RID rid = canvas_owner.make_rid(canvas); return rid; } -void VisualServerCanvas::canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring) { +void VisualServerCanvas::canvas_set_item_mirroring(RID p_canvas, RID p_item, const Point2 &p_mirroring) { - Canvas * canvas = canvas_owner.getornull(p_canvas); + Canvas *canvas = canvas_owner.getornull(p_canvas); ERR_FAIL_COND(!canvas); Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); int idx = canvas->find_item(canvas_item); - ERR_FAIL_COND(idx==-1); - canvas->child_items[idx].mirror=p_mirroring; - + ERR_FAIL_COND(idx == -1); + canvas->child_items[idx].mirror = p_mirroring; } -void VisualServerCanvas::canvas_set_modulate(RID p_canvas,const Color& p_color) { +void VisualServerCanvas::canvas_set_modulate(RID p_canvas, const Color &p_color) { - Canvas * canvas = canvas_owner.get(p_canvas); + Canvas *canvas = canvas_owner.get(p_canvas); ERR_FAIL_COND(!canvas); - canvas->modulate=p_color; + canvas->modulate = p_color; } - RID VisualServerCanvas::canvas_item_create() { - Item *canvas_item = memnew( Item ); - ERR_FAIL_COND_V(!canvas_item,RID()); + Item *canvas_item = memnew(Item); + ERR_FAIL_COND_V(!canvas_item, RID()); - return canvas_item_owner.make_rid( canvas_item ); + return canvas_item_owner.make_rid(canvas_item); } -void VisualServerCanvas::canvas_item_set_parent(RID p_item,RID p_parent) { - +void VisualServerCanvas::canvas_item_set_parent(RID p_item, RID p_parent) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); if (canvas_item->parent.is_valid()) { @@ -303,285 +284,262 @@ void VisualServerCanvas::canvas_item_set_parent(RID p_item,RID p_parent) { item_owner->child_items.erase(canvas_item); } - canvas_item->parent=RID(); + canvas_item->parent = RID(); } - if (p_parent.is_valid()) { if (canvas_owner.owns(p_parent)) { Canvas *canvas = canvas_owner.get(p_parent); Canvas::ChildItem ci; - ci.item=canvas_item; + ci.item = canvas_item; canvas->child_items.push_back(ci); - canvas->children_order_dirty=true; + canvas->children_order_dirty = true; } else if (canvas_item_owner.owns(p_parent)) { Item *item_owner = canvas_item_owner.get(p_parent); item_owner->child_items.push_back(canvas_item); - item_owner->children_order_dirty=true; + item_owner->children_order_dirty = true; } else { ERR_EXPLAIN("Invalid parent"); ERR_FAIL(); } - - } - canvas_item->parent=p_parent; - - + canvas_item->parent = p_parent; } -void VisualServerCanvas::canvas_item_set_visible(RID p_item,bool p_visible){ +void VisualServerCanvas::canvas_item_set_visible(RID p_item, bool p_visible) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->visible=p_visible; - + canvas_item->visible = p_visible; } -void VisualServerCanvas::canvas_item_set_light_mask(RID p_item,int p_mask){ +void VisualServerCanvas::canvas_item_set_light_mask(RID p_item, int p_mask) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->light_mask=p_mask; - + canvas_item->light_mask = p_mask; } -void VisualServerCanvas::canvas_item_set_transform(RID p_item, const Transform2D& p_transform){ +void VisualServerCanvas::canvas_item_set_transform(RID p_item, const Transform2D &p_transform) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->xform=p_transform; - + canvas_item->xform = p_transform; } -void VisualServerCanvas::canvas_item_set_clip(RID p_item, bool p_clip){ +void VisualServerCanvas::canvas_item_set_clip(RID p_item, bool p_clip) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->clip=p_clip; - + canvas_item->clip = p_clip; } -void VisualServerCanvas::canvas_item_set_distance_field_mode(RID p_item, bool p_enable){ +void VisualServerCanvas::canvas_item_set_distance_field_mode(RID p_item, bool p_enable) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->distance_field=p_enable; - - + canvas_item->distance_field = p_enable; } -void VisualServerCanvas::canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect){ +void VisualServerCanvas::canvas_item_set_custom_rect(RID p_item, bool p_custom_rect, const Rect2 &p_rect) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->custom_rect=p_custom_rect; - canvas_item->rect=p_rect; - + canvas_item->custom_rect = p_custom_rect; + canvas_item->rect = p_rect; } -void VisualServerCanvas::canvas_item_set_modulate(RID p_item, const Color& p_color) { +void VisualServerCanvas::canvas_item_set_modulate(RID p_item, const Color &p_color) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->modulate=p_color; - + canvas_item->modulate = p_color; } -void VisualServerCanvas::canvas_item_set_self_modulate(RID p_item, const Color& p_color){ +void VisualServerCanvas::canvas_item_set_self_modulate(RID p_item, const Color &p_color) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->self_modulate=p_color; - + canvas_item->self_modulate = p_color; } -void VisualServerCanvas::canvas_item_set_draw_behind_parent(RID p_item, bool p_enable){ +void VisualServerCanvas::canvas_item_set_draw_behind_parent(RID p_item, bool p_enable) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->behind=p_enable; - + canvas_item->behind = p_enable; } +void VisualServerCanvas::canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased) { -void VisualServerCanvas::canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased) { - - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandLine * line = memnew( Item::CommandLine ); + Item::CommandLine *line = memnew(Item::CommandLine); ERR_FAIL_COND(!line); - line->color=p_color; - line->from=p_from; - line->to=p_to; - line->width=p_width; - line->antialiased=p_antialiased; - canvas_item->rect_dirty=true; - + line->color = p_color; + line->from = p_from; + line->to = p_to; + line->width = p_width; + line->antialiased = p_antialiased; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(line); } -void VisualServerCanvas::canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color) { +void VisualServerCanvas::canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandRect * rect = memnew( Item::CommandRect ); + Item::CommandRect *rect = memnew(Item::CommandRect); ERR_FAIL_COND(!rect); - rect->modulate=p_color; - rect->rect=p_rect; - canvas_item->rect_dirty=true; + rect->modulate = p_color; + rect->rect = p_rect; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(rect); } -void VisualServerCanvas::canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color) { - +void VisualServerCanvas::canvas_item_add_circle(RID p_item, const Point2 &p_pos, float p_radius, const Color &p_color) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandCircle * circle = memnew( Item::CommandCircle ); + Item::CommandCircle *circle = memnew(Item::CommandCircle); ERR_FAIL_COND(!circle); - circle->color=p_color; - circle->pos=p_pos; - circle->radius=p_radius; + circle->color = p_color; + circle->pos = p_pos; + circle->radius = p_radius; canvas_item->commands.push_back(circle); - } -void VisualServerCanvas::canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile,const Color& p_modulate,bool p_transpose) { +void VisualServerCanvas::canvas_item_add_texture_rect(RID p_item, const Rect2 &p_rect, RID p_texture, bool p_tile, const Color &p_modulate, bool p_transpose) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandRect * rect = memnew( Item::CommandRect ); + Item::CommandRect *rect = memnew(Item::CommandRect); ERR_FAIL_COND(!rect); - rect->modulate=p_modulate; - rect->rect=p_rect; - rect->flags=0; + rect->modulate = p_modulate; + rect->rect = p_rect; + rect->flags = 0; if (p_tile) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_TILE; - rect->flags|=RasterizerCanvas::CANVAS_RECT_REGION; - rect->source=Rect2(0,0,p_rect.size.width,p_rect.size.height); + rect->flags |= RasterizerCanvas::CANVAS_RECT_TILE; + rect->flags |= RasterizerCanvas::CANVAS_RECT_REGION; + rect->source = Rect2(0, 0, p_rect.size.width, p_rect.size.height); } - if (p_rect.size.x<0) { + if (p_rect.size.x < 0) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_H; + rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_H; rect->rect.size.x = -rect->rect.size.x; } - if (p_rect.size.y<0) { + if (p_rect.size.y < 0) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_V; + rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_V; rect->rect.size.y = -rect->rect.size.y; } if (p_transpose) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_TRANSPOSE; + rect->flags |= RasterizerCanvas::CANVAS_RECT_TRANSPOSE; SWAP(rect->rect.size.x, rect->rect.size.y); } - rect->texture=p_texture; - canvas_item->rect_dirty=true; + rect->texture = p_texture; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(rect); } -void VisualServerCanvas::canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate,bool p_transpose) { +void VisualServerCanvas::canvas_item_add_texture_rect_region(RID p_item, const Rect2 &p_rect, RID p_texture, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandRect * rect = memnew( Item::CommandRect ); + Item::CommandRect *rect = memnew(Item::CommandRect); ERR_FAIL_COND(!rect); - rect->modulate=p_modulate; - rect->rect=p_rect; - rect->texture=p_texture; - rect->source=p_src_rect; - rect->flags=RasterizerCanvas::CANVAS_RECT_REGION; + rect->modulate = p_modulate; + rect->rect = p_rect; + rect->texture = p_texture; + rect->source = p_src_rect; + rect->flags = RasterizerCanvas::CANVAS_RECT_REGION; - if (p_rect.size.x<0) { + if (p_rect.size.x < 0) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_H; + rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_H; rect->rect.size.x = -rect->rect.size.x; } - if (p_rect.size.y<0) { + if (p_rect.size.y < 0) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_V; + rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_V; rect->rect.size.y = -rect->rect.size.y; } if (p_transpose) { - rect->flags|=RasterizerCanvas::CANVAS_RECT_TRANSPOSE; + rect->flags |= RasterizerCanvas::CANVAS_RECT_TRANSPOSE; SWAP(rect->rect.size.x, rect->rect.size.y); } - canvas_item->rect_dirty=true; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(rect); - } -void VisualServerCanvas::canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,VS::NinePatchAxisMode p_x_axis_mode, VS::NinePatchAxisMode p_y_axis_mode,bool p_draw_center,const Color& p_modulate) { - +void VisualServerCanvas::canvas_item_add_nine_patch(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector2 &p_topleft, const Vector2 &p_bottomright, VS::NinePatchAxisMode p_x_axis_mode, VS::NinePatchAxisMode p_y_axis_mode, bool p_draw_center, const Color &p_modulate) { - - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandNinePatch * style = memnew( Item::CommandNinePatch ); + Item::CommandNinePatch *style = memnew(Item::CommandNinePatch); ERR_FAIL_COND(!style); - style->texture=p_texture; - style->rect=p_rect; - style->source=p_source; - style->draw_center=p_draw_center; - style->color=p_modulate; - style->margin[MARGIN_LEFT]=p_topleft.x; - style->margin[MARGIN_TOP]=p_topleft.y; - style->margin[MARGIN_RIGHT]=p_bottomright.x; - style->margin[MARGIN_BOTTOM]=p_bottomright.y; - style->axis_x=p_x_axis_mode; - style->axis_y=p_y_axis_mode; - canvas_item->rect_dirty=true; + style->texture = p_texture; + style->rect = p_rect; + style->source = p_source; + style->draw_center = p_draw_center; + style->color = p_modulate; + style->margin[MARGIN_LEFT] = p_topleft.x; + style->margin[MARGIN_TOP] = p_topleft.y; + style->margin[MARGIN_RIGHT] = p_bottomright.x; + style->margin[MARGIN_BOTTOM] = p_bottomright.y; + style->axis_x = p_x_axis_mode; + style->axis_y = p_y_axis_mode; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(style); } -void VisualServerCanvas::canvas_item_add_primitive(RID p_item,const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width) { +void VisualServerCanvas::canvas_item_add_primitive(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandPrimitive * prim = memnew( Item::CommandPrimitive ); + Item::CommandPrimitive *prim = memnew(Item::CommandPrimitive); ERR_FAIL_COND(!prim); - prim->texture=p_texture; - prim->points=p_points; - prim->uvs=p_uvs; - prim->colors=p_colors; - prim->width=p_width; - canvas_item->rect_dirty=true; + prim->texture = p_texture; + prim->points = p_points; + prim->uvs = p_uvs; + prim->colors = p_colors; + prim->width = p_width; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(prim); } -void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture) { - +void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); #ifdef DEBUG_ENABLED int pointcount = p_points.size(); - ERR_FAIL_COND(pointcount<3); - int color_size=p_colors.size(); - int uv_size=p_uvs.size(); - ERR_FAIL_COND(color_size!=0 && color_size!=1 && color_size!=pointcount); - ERR_FAIL_COND(uv_size!=0 && (uv_size!=pointcount || !p_texture.is_valid())); + ERR_FAIL_COND(pointcount < 3); + int color_size = p_colors.size(); + int uv_size = p_uvs.size(); + ERR_FAIL_COND(color_size != 0 && color_size != 1 && color_size != pointcount); + ERR_FAIL_COND(uv_size != 0 && (uv_size != pointcount || !p_texture.is_valid())); #endif Vector<int> indices = Geometry::triangulate_polygon(p_points); @@ -591,30 +549,27 @@ void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2 ERR_FAIL_V(); } - Item::CommandPolygon * polygon = memnew( Item::CommandPolygon ); + Item::CommandPolygon *polygon = memnew(Item::CommandPolygon); ERR_FAIL_COND(!polygon); - polygon->texture=p_texture; - polygon->points=p_points; - polygon->uvs=p_uvs; - polygon->colors=p_colors; - polygon->indices=indices; - polygon->count=indices.size(); - canvas_item->rect_dirty=true; + polygon->texture = p_texture; + polygon->points = p_points; + polygon->uvs = p_uvs; + polygon->colors = p_colors; + polygon->indices = indices; + polygon->count = indices.size(); + canvas_item->rect_dirty = true; canvas_item->commands.push_back(polygon); - } +void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, int p_count) { -void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture, int p_count) { - - - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); int ps = p_points.size(); - ERR_FAIL_COND(!p_colors.empty() && p_colors.size()!=ps && p_colors.size()!=1); - ERR_FAIL_COND(!p_uvs.empty() && p_uvs.size()!=ps); + ERR_FAIL_COND(!p_colors.empty() && p_colors.size() != ps && p_colors.size() != 1); + ERR_FAIL_COND(!p_uvs.empty() && p_uvs.size() != ps); Vector<int> indices = p_indices; @@ -622,181 +577,169 @@ void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector if (indices.empty()) { - ERR_FAIL_COND( ps % 3 != 0 ); + ERR_FAIL_COND(ps % 3 != 0); if (p_count == -1) count = ps; } else { - ERR_FAIL_COND( indices.size() % 3 != 0 ); + ERR_FAIL_COND(indices.size() % 3 != 0); if (p_count == -1) count = indices.size(); } - Item::CommandPolygon * polygon = memnew( Item::CommandPolygon ); + Item::CommandPolygon *polygon = memnew(Item::CommandPolygon); ERR_FAIL_COND(!polygon); - polygon->texture=p_texture; - polygon->points=p_points; - polygon->uvs=p_uvs; - polygon->colors=p_colors; - polygon->indices=indices; + polygon->texture = p_texture; + polygon->points = p_points; + polygon->uvs = p_uvs; + polygon->colors = p_colors; + polygon->indices = indices; polygon->count = count; - canvas_item->rect_dirty=true; + canvas_item->rect_dirty = true; canvas_item->commands.push_back(polygon); } +void VisualServerCanvas::canvas_item_add_set_transform(RID p_item, const Transform2D &p_transform) { -void VisualServerCanvas::canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform) { - - - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandTransform * tr = memnew( Item::CommandTransform ); + Item::CommandTransform *tr = memnew(Item::CommandTransform); ERR_FAIL_COND(!tr); - tr->xform=p_transform; + tr->xform = p_transform; canvas_item->commands.push_back(tr); - } -void VisualServerCanvas::canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton){ +void VisualServerCanvas::canvas_item_add_mesh(RID p_item, const RID &p_mesh, RID p_skeleton) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandMesh * m = memnew( Item::CommandMesh ); + Item::CommandMesh *m = memnew(Item::CommandMesh); ERR_FAIL_COND(!m); - m->mesh=p_mesh; - m->skeleton=p_skeleton; + m->mesh = p_mesh; + m->skeleton = p_skeleton; canvas_item->commands.push_back(m); } -void VisualServerCanvas::canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton){ +void VisualServerCanvas::canvas_item_add_multimesh(RID p_item, RID p_mesh, RID p_skeleton) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandMultiMesh * mm = memnew( Item::CommandMultiMesh ); + Item::CommandMultiMesh *mm = memnew(Item::CommandMultiMesh); ERR_FAIL_COND(!mm); - mm->multimesh=p_mesh; - mm->skeleton=p_skeleton; + mm->multimesh = p_mesh; + mm->skeleton = p_skeleton; canvas_item->commands.push_back(mm); - } -void VisualServerCanvas::canvas_item_add_clip_ignore(RID p_item, bool p_ignore){ - +void VisualServerCanvas::canvas_item_add_clip_ignore(RID p_item, bool p_ignore) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - Item::CommandClipIgnore * ci = memnew( Item::CommandClipIgnore); + Item::CommandClipIgnore *ci = memnew(Item::CommandClipIgnore); ERR_FAIL_COND(!ci); - ci->ignore=p_ignore; + ci->ignore = p_ignore; canvas_item->commands.push_back(ci); } -void VisualServerCanvas::canvas_item_set_sort_children_by_y(RID p_item, bool p_enable){ - +void VisualServerCanvas::canvas_item_set_sort_children_by_y(RID p_item, bool p_enable) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->sort_y=p_enable; + canvas_item->sort_y = p_enable; } -void VisualServerCanvas::canvas_item_set_z(RID p_item, int p_z){ +void VisualServerCanvas::canvas_item_set_z(RID p_item, int p_z) { - ERR_FAIL_COND(p_z<VS::CANVAS_ITEM_Z_MIN || p_z>VS::CANVAS_ITEM_Z_MAX); + ERR_FAIL_COND(p_z < VS::CANVAS_ITEM_Z_MIN || p_z > VS::CANVAS_ITEM_Z_MAX); - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->z=p_z; + canvas_item->z = p_z; } -void VisualServerCanvas::canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable){ +void VisualServerCanvas::canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->z_relative=p_enable; - + canvas_item->z_relative = p_enable; } -void VisualServerCanvas::canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect){ +void VisualServerCanvas::canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable, const Rect2 &p_rect) { - - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - if (bool(canvas_item->copy_back_buffer!=NULL) !=p_enable) { + if (bool(canvas_item->copy_back_buffer != NULL) != p_enable) { if (p_enable) { - canvas_item->copy_back_buffer = memnew( RasterizerCanvas::Item::CopyBackBuffer ); + canvas_item->copy_back_buffer = memnew(RasterizerCanvas::Item::CopyBackBuffer); } else { memdelete(canvas_item->copy_back_buffer); - canvas_item->copy_back_buffer=NULL; + canvas_item->copy_back_buffer = NULL; } } if (p_enable) { - canvas_item->copy_back_buffer->rect=p_rect; - canvas_item->copy_back_buffer->full=p_rect==Rect2(); + canvas_item->copy_back_buffer->rect = p_rect; + canvas_item->copy_back_buffer->full = p_rect == Rect2(); } - } -void VisualServerCanvas::canvas_item_clear(RID p_item){ +void VisualServerCanvas::canvas_item_clear(RID p_item) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); canvas_item->clear(); } -void VisualServerCanvas::canvas_item_set_draw_index(RID p_item,int p_index){ +void VisualServerCanvas::canvas_item_set_draw_index(RID p_item, int p_index) { - Item *canvas_item = canvas_item_owner.getornull( p_item ); + Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->index=p_index; + canvas_item->index = p_index; - if (canvas_item_owner.owns( canvas_item->parent)) { - Item *canvas_item_parent = canvas_item_owner.getornull( canvas_item->parent ); - canvas_item_parent->children_order_dirty=true; + if (canvas_item_owner.owns(canvas_item->parent)) { + Item *canvas_item_parent = canvas_item_owner.getornull(canvas_item->parent); + canvas_item_parent->children_order_dirty = true; return; } - Canvas* canvas = canvas_owner.getornull( canvas_item->parent ); + Canvas *canvas = canvas_owner.getornull(canvas_item->parent); if (canvas) { - canvas->children_order_dirty=true; + canvas->children_order_dirty = true; return; } - } -void VisualServerCanvas::canvas_item_set_material(RID p_item, RID p_material){ +void VisualServerCanvas::canvas_item_set_material(RID p_item, RID p_material) { - Item *canvas_item = canvas_item_owner.get( p_item ); + Item *canvas_item = canvas_item_owner.get(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->material=p_material; + canvas_item->material = p_material; } -void VisualServerCanvas::canvas_item_set_use_parent_material(RID p_item, bool p_enable){ +void VisualServerCanvas::canvas_item_set_use_parent_material(RID p_item, bool p_enable) { - Item *canvas_item = canvas_item_owner.get( p_item ); + Item *canvas_item = canvas_item_owner.get(p_item); ERR_FAIL_COND(!canvas_item); - canvas_item->use_parent_material=p_enable; - + canvas_item->use_parent_material = p_enable; } -RID VisualServerCanvas::canvas_light_create(){ +RID VisualServerCanvas::canvas_light_create() { - RasterizerCanvas::Light *clight = memnew( RasterizerCanvas::Light ); + RasterizerCanvas::Light *clight = memnew(RasterizerCanvas::Light); clight->light_internal = VSG::canvas_render->light_internal_create(); return canvas_light_owner.make_rid(clight); - } -void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas){ +void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light, RID p_canvas) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); @@ -808,9 +751,9 @@ void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas) } if (!canvas_owner.owns(p_canvas)) - p_canvas=RID(); + p_canvas = RID(); - clight->canvas=p_canvas; + clight->canvas = p_canvas; if (clight->canvas.is_valid()) { @@ -819,196 +762,164 @@ void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas) } } - -void VisualServerCanvas::canvas_light_set_enabled(RID p_light, bool p_enabled){ +void VisualServerCanvas::canvas_light_set_enabled(RID p_light, bool p_enabled) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->enabled=p_enabled; - + clight->enabled = p_enabled; } -void VisualServerCanvas::canvas_light_set_scale(RID p_light, float p_scale){ - +void VisualServerCanvas::canvas_light_set_scale(RID p_light, float p_scale) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->scale=p_scale; - + clight->scale = p_scale; } -void VisualServerCanvas::canvas_light_set_transform(RID p_light, const Transform2D& p_transform){ - +void VisualServerCanvas::canvas_light_set_transform(RID p_light, const Transform2D &p_transform) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->xform=p_transform; - + clight->xform = p_transform; } -void VisualServerCanvas::canvas_light_set_texture(RID p_light, RID p_texture){ - +void VisualServerCanvas::canvas_light_set_texture(RID p_light, RID p_texture) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->texture=p_texture; - + clight->texture = p_texture; } -void VisualServerCanvas::canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset){ - +void VisualServerCanvas::canvas_light_set_texture_offset(RID p_light, const Vector2 &p_offset) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->texture_offset=p_offset; - + clight->texture_offset = p_offset; } -void VisualServerCanvas::canvas_light_set_color(RID p_light, const Color& p_color){ - - +void VisualServerCanvas::canvas_light_set_color(RID p_light, const Color &p_color) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->color=p_color; + clight->color = p_color; } -void VisualServerCanvas::canvas_light_set_height(RID p_light, float p_height){ - +void VisualServerCanvas::canvas_light_set_height(RID p_light, float p_height) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->height=p_height; - + clight->height = p_height; } -void VisualServerCanvas::canvas_light_set_energy(RID p_light, float p_energy){ - +void VisualServerCanvas::canvas_light_set_energy(RID p_light, float p_energy) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->energy=p_energy; - + clight->energy = p_energy; } -void VisualServerCanvas::canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z){ - +void VisualServerCanvas::canvas_light_set_z_range(RID p_light, int p_min_z, int p_max_z) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->z_min=p_min_z; - clight->z_max=p_max_z; - + clight->z_min = p_min_z; + clight->z_max = p_max_z; } -void VisualServerCanvas::canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer){ - +void VisualServerCanvas::canvas_light_set_layer_range(RID p_light, int p_min_layer, int p_max_layer) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - - clight->layer_max=p_max_layer; - clight->layer_min=p_min_layer; - - + clight->layer_max = p_max_layer; + clight->layer_min = p_min_layer; } -void VisualServerCanvas::canvas_light_set_item_cull_mask(RID p_light, int p_mask){ - +void VisualServerCanvas::canvas_light_set_item_cull_mask(RID p_light, int p_mask) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->item_mask=p_mask; - + clight->item_mask = p_mask; } -void VisualServerCanvas::canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask){ +void VisualServerCanvas::canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->item_shadow_mask=p_mask; - + clight->item_shadow_mask = p_mask; } -void VisualServerCanvas::canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode){ +void VisualServerCanvas::canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->mode=p_mode; - + clight->mode = p_mode; } - -void VisualServerCanvas::canvas_light_set_shadow_enabled(RID p_light, bool p_enabled){ +void VisualServerCanvas::canvas_light_set_shadow_enabled(RID p_light, bool p_enabled) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - if (clight->shadow_buffer.is_valid()==p_enabled) + if (clight->shadow_buffer.is_valid() == p_enabled) return; if (p_enabled) { - clight->shadow_buffer=VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size); + clight->shadow_buffer = VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size); } else { VSG::storage->free(clight->shadow_buffer); - clight->shadow_buffer=RID(); + clight->shadow_buffer = RID(); } - } -void VisualServerCanvas::canvas_light_set_shadow_buffer_size(RID p_light, int p_size){ +void VisualServerCanvas::canvas_light_set_shadow_buffer_size(RID p_light, int p_size) { - ERR_FAIL_COND(p_size<32 || p_size>16384); + ERR_FAIL_COND(p_size < 32 || p_size > 16384); RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); int new_size = nearest_power_of_2(p_size); - if (new_size==clight->shadow_buffer_size) + if (new_size == clight->shadow_buffer_size) return; - clight->shadow_buffer_size=nearest_power_of_2(p_size); + clight->shadow_buffer_size = nearest_power_of_2(p_size); if (clight->shadow_buffer.is_valid()) { VSG::storage->free(clight->shadow_buffer); - clight->shadow_buffer=VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size); + clight->shadow_buffer = VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size); } } void VisualServerCanvas::canvas_light_set_shadow_gradient_length(RID p_light, float p_length) { - ERR_FAIL_COND(p_length<0); + ERR_FAIL_COND(p_length < 0); RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->shadow_gradient_length=p_length; - + clight->shadow_gradient_length = p_length; } void VisualServerCanvas::canvas_light_set_shadow_filter(RID p_light, VS::CanvasLightShadowFilter p_filter) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->shadow_filter=p_filter; - + clight->shadow_filter = p_filter; } -void VisualServerCanvas::canvas_light_set_shadow_color(RID p_light, const Color& p_color) { +void VisualServerCanvas::canvas_light_set_shadow_color(RID p_light, const Color &p_color) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); - clight->shadow_color=p_color; + clight->shadow_color = p_color; } - - RID VisualServerCanvas::canvas_light_occluder_create() { - RasterizerCanvas::LightOccluderInstance *occluder = memnew( RasterizerCanvas::LightOccluderInstance ); + RasterizerCanvas::LightOccluderInstance *occluder = memnew(RasterizerCanvas::LightOccluderInstance); return canvas_light_occluder_owner.make_rid(occluder); } -void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas){ +void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder, RID p_canvas) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); @@ -1020,9 +931,9 @@ void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,R } if (!canvas_owner.owns(p_canvas)) - p_canvas=RID(); + p_canvas = RID(); - occluder->canvas=p_canvas; + occluder->canvas = p_canvas; if (occluder->canvas.is_valid()) { @@ -1030,14 +941,14 @@ void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,R canvas->occluders.insert(occluder); } } -void VisualServerCanvas::canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled) { +void VisualServerCanvas::canvas_light_occluder_set_enabled(RID p_occluder, bool p_enabled) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); - occluder->enabled=p_enabled; + occluder->enabled = p_enabled; } -void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon) { +void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder, RID p_polygon) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); @@ -1049,153 +960,147 @@ void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder,RID p_ } } - occluder->polygon=p_polygon; - occluder->polygon_buffer=RID(); + occluder->polygon = p_polygon; + occluder->polygon_buffer = RID(); if (occluder->polygon.is_valid()) { LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_polygon); if (!occluder_poly) - occluder->polygon=RID(); + occluder->polygon = RID(); ERR_FAIL_COND(!occluder_poly); occluder_poly->owners.insert(occluder); - occluder->polygon_buffer=occluder_poly->occluder; - occluder->aabb_cache=occluder_poly->aabb; - occluder->cull_cache=occluder_poly->cull_mode; + occluder->polygon_buffer = occluder_poly->occluder; + occluder->aabb_cache = occluder_poly->aabb; + occluder->cull_cache = occluder_poly->cull_mode; } - } -void VisualServerCanvas::canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform) { +void VisualServerCanvas::canvas_light_occluder_set_transform(RID p_occluder, const Transform2D &p_xform) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); - occluder->xform=p_xform; + occluder->xform = p_xform; } -void VisualServerCanvas::canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask) { +void VisualServerCanvas::canvas_light_occluder_set_light_mask(RID p_occluder, int p_mask) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); - occluder->light_mask=p_mask; + occluder->light_mask = p_mask; } RID VisualServerCanvas::canvas_occluder_polygon_create() { - LightOccluderPolygon * occluder_poly = memnew( LightOccluderPolygon ); - occluder_poly->occluder=VSG::storage->canvas_light_occluder_create(); + LightOccluderPolygon *occluder_poly = memnew(LightOccluderPolygon); + occluder_poly->occluder = VSG::storage->canvas_light_occluder_create(); return canvas_light_occluder_polygon_owner.make_rid(occluder_poly); - } -void VisualServerCanvas::canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed) { +void VisualServerCanvas::canvas_occluder_polygon_set_shape(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape, bool p_closed) { - if (p_shape.size()<3) { - canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon,p_shape); + if (p_shape.size() < 3) { + canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon, p_shape); return; } PoolVector<Vector2> lines; - int lc = p_shape.size()*2; + int lc = p_shape.size() * 2; - lines.resize(lc-(p_closed?0:2)); + lines.resize(lc - (p_closed ? 0 : 2)); { PoolVector<Vector2>::Write w = lines.write(); PoolVector<Vector2>::Read r = p_shape.read(); - int max=lc/2; + int max = lc / 2; if (!p_closed) { max--; } - for(int i=0;i<max;i++) { + for (int i = 0; i < max; i++) { Vector2 a = r[i]; - Vector2 b = r[(i+1)%(lc/2)]; - w[i*2+0]=a; - w[i*2+1]=b; + Vector2 b = r[(i + 1) % (lc / 2)]; + w[i * 2 + 0] = a; + w[i * 2 + 1] = b; } - } - canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon,lines); + canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon, lines); } -void VisualServerCanvas::canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape) { +void VisualServerCanvas::canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape) { - LightOccluderPolygon * occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon); + LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon); ERR_FAIL_COND(!occluder_poly); - ERR_FAIL_COND(p_shape.size()&1); + ERR_FAIL_COND(p_shape.size() & 1); int lc = p_shape.size(); - occluder_poly->aabb=Rect2(); + occluder_poly->aabb = Rect2(); { PoolVector<Vector2>::Read r = p_shape.read(); - for(int i=0;i<lc;i++) { - if (i==0) - occluder_poly->aabb.pos=r[i]; + for (int i = 0; i < lc; i++) { + if (i == 0) + occluder_poly->aabb.pos = r[i]; else occluder_poly->aabb.expand_to(r[i]); } } - VSG::storage->canvas_light_occluder_set_polylines(occluder_poly->occluder,p_shape); - for( Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=occluder_poly->owners.front();E;E=E->next()) { - E->get()->aabb_cache=occluder_poly->aabb; + VSG::storage->canvas_light_occluder_set_polylines(occluder_poly->occluder, p_shape); + for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *E = occluder_poly->owners.front(); E; E = E->next()) { + E->get()->aabb_cache = occluder_poly->aabb; } } +void VisualServerCanvas::canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon, VS::CanvasOccluderPolygonCullMode p_mode) { -void VisualServerCanvas::canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,VS::CanvasOccluderPolygonCullMode p_mode) { - - LightOccluderPolygon * occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon); + LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon); ERR_FAIL_COND(!occluder_poly); - occluder_poly->cull_mode=p_mode; - for( Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=occluder_poly->owners.front();E;E=E->next()) { - E->get()->cull_cache=p_mode; + occluder_poly->cull_mode = p_mode; + for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *E = occluder_poly->owners.front(); E; E = E->next()) { + E->get()->cull_cache = p_mode; } } - - bool VisualServerCanvas::free(RID p_rid) { if (canvas_owner.owns(p_rid)) { Canvas *canvas = canvas_owner.get(p_rid); - ERR_FAIL_COND_V(!canvas,false); + ERR_FAIL_COND_V(!canvas, false); - while(canvas->viewports.size()) { + while (canvas->viewports.size()) { VisualServerViewport::Viewport *vp = VSG::viewport->viewport_owner.get(canvas->viewports.front()->get()); - ERR_FAIL_COND_V(!vp,true); + ERR_FAIL_COND_V(!vp, true); - Map<RID,VisualServerViewport::Viewport::CanvasData>::Element *E=vp->canvas_map.find(p_rid); - ERR_FAIL_COND_V(!E,true); + Map<RID, VisualServerViewport::Viewport::CanvasData>::Element *E = vp->canvas_map.find(p_rid); + ERR_FAIL_COND_V(!E, true); vp->canvas_map.erase(p_rid); - canvas->viewports.erase( canvas->viewports.front() ); + canvas->viewports.erase(canvas->viewports.front()); } - for (int i=0;i<canvas->child_items.size();i++) { + for (int i = 0; i < canvas->child_items.size(); i++) { - canvas->child_items[i].item->parent=RID(); + canvas->child_items[i].item->parent = RID(); } - for (Set<RasterizerCanvas::Light*>::Element *E=canvas->lights.front();E;E=E->next()) { + for (Set<RasterizerCanvas::Light *>::Element *E = canvas->lights.front(); E; E = E->next()) { - E->get()->canvas=RID(); + E->get()->canvas = RID(); } - for (Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=canvas->occluders.front();E;E=E->next()) { + for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *E = canvas->occluders.front(); E; E = E->next()) { - E->get()->canvas=RID(); + E->get()->canvas = RID(); } - canvas_owner.free( p_rid ); + canvas_owner.free(p_rid); - memdelete( canvas ); + memdelete(canvas); } else if (canvas_item_owner.owns(p_rid)) { Item *canvas_item = canvas_item_owner.get(p_rid); - ERR_FAIL_COND_V(!canvas_item,true); + ERR_FAIL_COND_V(!canvas_item, true); if (canvas_item->parent.is_valid()) { @@ -1207,13 +1112,12 @@ bool VisualServerCanvas::free(RID p_rid) { Item *item_owner = canvas_item_owner.get(canvas_item->parent); item_owner->child_items.erase(canvas_item); - } } - for (int i=0;i<canvas_item->child_items.size();i++) { + for (int i = 0; i < canvas_item->child_items.size(); i++) { - canvas_item->child_items[i]->parent=RID(); + canvas_item->child_items[i]->parent = RID(); } /* @@ -1222,17 +1126,17 @@ bool VisualServerCanvas::free(RID p_rid) { } */ - canvas_item_owner.free( p_rid ); + canvas_item_owner.free(p_rid); - memdelete( canvas_item ); + memdelete(canvas_item); } else if (canvas_light_owner.owns(p_rid)) { RasterizerCanvas::Light *canvas_light = canvas_light_owner.get(p_rid); - ERR_FAIL_COND_V(!canvas_light,true); + ERR_FAIL_COND_V(!canvas_light, true); if (canvas_light->canvas.is_valid()) { - Canvas* canvas = canvas_owner.get(canvas_light->canvas); + Canvas *canvas = canvas_owner.get(canvas_light->canvas); if (canvas) canvas->lights.erase(canvas_light); } @@ -1242,13 +1146,13 @@ bool VisualServerCanvas::free(RID p_rid) { VSG::canvas_render->light_internal_free(canvas_light->light_internal); - canvas_light_owner.free( p_rid ); - memdelete( canvas_light ); + canvas_light_owner.free(p_rid); + memdelete(canvas_light); } else if (canvas_light_occluder_owner.owns(p_rid)) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_rid); - ERR_FAIL_COND_V(!occluder,true); + ERR_FAIL_COND_V(!occluder, true); if (occluder->polygon.is_valid()) { @@ -1256,32 +1160,30 @@ bool VisualServerCanvas::free(RID p_rid) { if (occluder_poly) { occluder_poly->owners.erase(occluder); } - } if (occluder->canvas.is_valid() && canvas_owner.owns(occluder->canvas)) { Canvas *canvas = canvas_owner.get(occluder->canvas); canvas->occluders.erase(occluder); - } - canvas_light_occluder_owner.free( p_rid ); + canvas_light_occluder_owner.free(p_rid); memdelete(occluder); } else if (canvas_light_occluder_polygon_owner.owns(p_rid)) { LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_rid); - ERR_FAIL_COND_V(!occluder_poly,true); + ERR_FAIL_COND_V(!occluder_poly, true); VSG::storage->free(occluder_poly->occluder); - while(occluder_poly->owners.size()) { + while (occluder_poly->owners.size()) { - occluder_poly->owners.front()->get()->polygon=RID(); - occluder_poly->owners.erase( occluder_poly->owners.front() ); + occluder_poly->owners.front()->get()->polygon = RID(); + occluder_poly->owners.erase(occluder_poly->owners.front()); } - canvas_light_occluder_polygon_owner.free( p_rid ); + canvas_light_occluder_polygon_owner.free(p_rid); memdelete(occluder_poly); } else { return false; @@ -1290,9 +1192,5 @@ bool VisualServerCanvas::free(RID p_rid) { return true; } - - -VisualServerCanvas::VisualServerCanvas() -{ - +VisualServerCanvas::VisualServerCanvas() { } diff --git a/servers/visual/visual_server_canvas.h b/servers/visual/visual_server_canvas.h index b405bc804d..3c2dde17d5 100644 --- a/servers/visual/visual_server_canvas.h +++ b/servers/visual/visual_server_canvas.h @@ -34,13 +34,10 @@ class VisualServerCanvas { public: - - struct Item : public RasterizerCanvas::Item { - RID parent; // canvas it belongs to - List<Item*>::Element *E; + List<Item *>::Element *E; int z; bool z_relative; bool sort_y; @@ -50,29 +47,26 @@ public: int index; bool children_order_dirty; - - Vector<Item*> child_items; - + Vector<Item *> child_items; Item() { - children_order_dirty=true; - E=NULL; - z=0; - modulate=Color(1,1,1,1); - self_modulate=Color(1,1,1,1); - sort_y=false; - use_parent_material=false; - z_relative=true; - index=0; + children_order_dirty = true; + E = NULL; + z = 0; + modulate = Color(1, 1, 1, 1); + self_modulate = Color(1, 1, 1, 1); + sort_y = false; + use_parent_material = false; + z_relative = true; + index = 0; } }; - struct ItemPtrSort { - _FORCE_INLINE_ bool operator()(const Item* p_left,const Item* p_right) const { + _FORCE_INLINE_ bool operator()(const Item *p_left, const Item *p_right) const { - if(Math::abs(p_left->xform.elements[2].y - p_right->xform.elements[2].y) < CMP_EPSILON ) + if (Math::abs(p_left->xform.elements[2].y - p_right->xform.elements[2].y) < CMP_EPSILON) return p_left->xform.elements[2].x < p_right->xform.elements[2].x; else return p_left->xform.elements[2].y < p_right->xform.elements[2].y; @@ -85,12 +79,14 @@ public: Rect2 aabb; VS::CanvasOccluderPolygonCullMode cull_mode; RID occluder; - Set<RasterizerCanvas::LightOccluderInstance*> owners; + Set<RasterizerCanvas::LightOccluderInstance *> owners; - LightOccluderPolygon() { active=false; cull_mode=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; } + LightOccluderPolygon() { + active = false; + cull_mode = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; + } }; - RID_Owner<LightOccluderPolygon> canvas_light_occluder_polygon_owner; RID_Owner<RasterizerCanvas::LightOccluderInstance> canvas_light_occluder_owner; @@ -102,91 +98,86 @@ public: Point2 mirror; Item *item; - bool operator<(const ChildItem& p_item) const { + bool operator<(const ChildItem &p_item) const { return item->index < p_item.item->index; } }; + Set<RasterizerCanvas::Light *> lights; - - Set<RasterizerCanvas::Light*> lights; - - Set<RasterizerCanvas::LightOccluderInstance*> occluders; + Set<RasterizerCanvas::LightOccluderInstance *> occluders; bool children_order_dirty; Vector<ChildItem> child_items; Color modulate; int find_item(Item *p_item) { - for(int i=0;i<child_items.size();i++) { - if (child_items[i].item==p_item) + for (int i = 0; i < child_items.size(); i++) { + if (child_items[i].item == p_item) return i; } return -1; } void erase_item(Item *p_item) { - int idx=find_item(p_item); - if (idx>=0) + int idx = find_item(p_item); + if (idx >= 0) child_items.remove(idx); } - - Canvas() { modulate=Color(1,1,1,1); children_order_dirty=true; } - + Canvas() { + modulate = Color(1, 1, 1, 1); + children_order_dirty = true; + } }; - RID_Owner<Canvas> canvas_owner; RID_Owner<Item> canvas_item_owner; RID_Owner<RasterizerCanvas::Light> canvas_light_owner; private: + void _render_canvas_item_tree(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, RasterizerCanvas::Light *p_lights); + void _render_canvas_item(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, int p_z, RasterizerCanvas::Item **z_list, RasterizerCanvas::Item **z_last_list, Item *p_canvas_clip, Item *p_material_owner); + void _light_mask_canvas_items(int p_z, RasterizerCanvas::Item *p_canvas_item, RasterizerCanvas::Light *p_masked_lights); - void _render_canvas_item_tree(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color &p_modulate, RasterizerCanvas::Light *p_lights); - void _render_canvas_item(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color &p_modulate, int p_z, RasterizerCanvas::Item **z_list, RasterizerCanvas::Item **z_last_list, Item *p_canvas_clip, Item *p_material_owner); - void _light_mask_canvas_items(int p_z,RasterizerCanvas::Item *p_canvas_item,RasterizerCanvas::Light *p_masked_lights); public: - - void render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights,const Rect2& p_clip_rect); + void render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights, const Rect2 &p_clip_rect); RID canvas_create(); - void canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring); - void canvas_set_modulate(RID p_canvas,const Color& p_color); - + void canvas_set_item_mirroring(RID p_canvas, RID p_item, const Point2 &p_mirroring); + void canvas_set_modulate(RID p_canvas, const Color &p_color); RID canvas_item_create(); - void canvas_item_set_parent(RID p_item,RID p_parent); + void canvas_item_set_parent(RID p_item, RID p_parent); - void canvas_item_set_visible(RID p_item,bool p_visible); - void canvas_item_set_light_mask(RID p_item,int p_mask); + void canvas_item_set_visible(RID p_item, bool p_visible); + void canvas_item_set_light_mask(RID p_item, int p_mask); - void canvas_item_set_transform(RID p_item, const Transform2D& p_transform); + void canvas_item_set_transform(RID p_item, const Transform2D &p_transform); void canvas_item_set_clip(RID p_item, bool p_clip); void canvas_item_set_distance_field_mode(RID p_item, bool p_enable); - void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect=Rect2()); - void canvas_item_set_modulate(RID p_item, const Color& p_color); - void canvas_item_set_self_modulate(RID p_item, const Color& p_color); + void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect, const Rect2 &p_rect = Rect2()); + void canvas_item_set_modulate(RID p_item, const Color &p_color); + void canvas_item_set_self_modulate(RID p_item, const Color &p_color); void canvas_item_set_draw_behind_parent(RID p_item, bool p_enable); - - void canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width=1.0,bool p_antialiased=false); - void canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color); - void canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color); - void canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile=false,const Color& p_modulate=Color(1,1,1),bool p_transpose=false); - void canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1),bool p_transpose=false); - void canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,VS::NinePatchAxisMode p_x_axis_mode=VS::NINE_PATCH_STRETCH, VS::NinePatchAxisMode p_y_axis_mode=VS::NINE_PATCH_STRETCH,bool p_draw_center=true,const Color& p_modulate=Color(1,1,1)); - void canvas_item_add_primitive(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width=1.0); - void canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID()); - void canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID(), int p_count=-1); - void canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton=RID()); - void canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton=RID()); - void canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform); + void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false); + void canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color); + void canvas_item_add_circle(RID p_item, const Point2 &p_pos, float p_radius, const Color &p_color); + void canvas_item_add_texture_rect(RID p_item, const Rect2 &p_rect, RID p_texture, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false); + void canvas_item_add_texture_rect_region(RID p_item, const Rect2 &p_rect, RID p_texture, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false); + void canvas_item_add_nine_patch(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector2 &p_topleft, const Vector2 &p_bottomright, VS::NinePatchAxisMode p_x_axis_mode = VS::NINE_PATCH_STRETCH, VS::NinePatchAxisMode p_y_axis_mode = VS::NINE_PATCH_STRETCH, bool p_draw_center = true, const Color &p_modulate = Color(1, 1, 1)); + void canvas_item_add_primitive(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width = 1.0); + void canvas_item_add_polygon(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID()); + void canvas_item_add_triangle_array(RID p_item, const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID(), int p_count = -1); + void canvas_item_add_mesh(RID p_item, const RID &p_mesh, RID p_skeleton = RID()); + void canvas_item_add_multimesh(RID p_item, RID p_mesh, RID p_skeleton = RID()); + void canvas_item_add_set_transform(RID p_item, const Transform2D &p_transform); void canvas_item_add_clip_ignore(RID p_item, bool p_ignore); void canvas_item_set_sort_children_by_y(RID p_item, bool p_enable); void canvas_item_set_z(RID p_item, int p_z); void canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable); - void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect); + void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable, const Rect2 &p_rect); void canvas_item_clear(RID p_item); void canvas_item_set_draw_index(RID p_item, int p_index); @@ -196,50 +187,43 @@ public: void canvas_item_set_use_parent_material(RID p_item, bool p_enable); RID canvas_light_create(); - void canvas_light_attach_to_canvas(RID p_light,RID p_canvas); + void canvas_light_attach_to_canvas(RID p_light, RID p_canvas); void canvas_light_set_enabled(RID p_light, bool p_enabled); void canvas_light_set_scale(RID p_light, float p_scale); - void canvas_light_set_transform(RID p_light, const Transform2D& p_transform); + void canvas_light_set_transform(RID p_light, const Transform2D &p_transform); void canvas_light_set_texture(RID p_light, RID p_texture); - void canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset); - void canvas_light_set_color(RID p_light, const Color& p_color); + void canvas_light_set_texture_offset(RID p_light, const Vector2 &p_offset); + void canvas_light_set_color(RID p_light, const Color &p_color); void canvas_light_set_height(RID p_light, float p_height); void canvas_light_set_energy(RID p_light, float p_energy); - void canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z); - void canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer); + void canvas_light_set_z_range(RID p_light, int p_min_z, int p_max_z); + void canvas_light_set_layer_range(RID p_light, int p_min_layer, int p_max_layer); void canvas_light_set_item_cull_mask(RID p_light, int p_mask); void canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask); void canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode); - void canvas_light_set_shadow_enabled(RID p_light, bool p_enabled); void canvas_light_set_shadow_buffer_size(RID p_light, int p_size); void canvas_light_set_shadow_gradient_length(RID p_light, float p_length); void canvas_light_set_shadow_filter(RID p_light, VS::CanvasLightShadowFilter p_filter); - void canvas_light_set_shadow_color(RID p_light, const Color& p_color); - - + void canvas_light_set_shadow_color(RID p_light, const Color &p_color); RID canvas_light_occluder_create(); - void canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas); - void canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled); - void canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon); - void canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform); - void canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask); + void canvas_light_occluder_attach_to_canvas(RID p_occluder, RID p_canvas); + void canvas_light_occluder_set_enabled(RID p_occluder, bool p_enabled); + void canvas_light_occluder_set_polygon(RID p_occluder, RID p_polygon); + void canvas_light_occluder_set_transform(RID p_occluder, const Transform2D &p_xform); + void canvas_light_occluder_set_light_mask(RID p_occluder, int p_mask); RID canvas_occluder_polygon_create(); - void canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed); - void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape); - - - void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,VS::CanvasOccluderPolygonCullMode p_mode); + void canvas_occluder_polygon_set_shape(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape, bool p_closed); + void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape); + void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon, VS::CanvasOccluderPolygonCullMode p_mode); bool free(RID p_rid); VisualServerCanvas(); - - }; #endif // VISUALSERVERCANVAS_H diff --git a/servers/visual/visual_server_global.cpp b/servers/visual/visual_server_global.cpp index 3704192c7e..75506f7add 100644 --- a/servers/visual/visual_server_global.cpp +++ b/servers/visual/visual_server_global.cpp @@ -28,11 +28,11 @@ /*************************************************************************/ #include "visual_server_global.h" -RasterizerStorage *VisualServerGlobals::storage=NULL; -RasterizerCanvas *VisualServerGlobals::canvas_render=NULL; -RasterizerScene *VisualServerGlobals::scene_render=NULL; -Rasterizer *VisualServerGlobals::rasterizer=NULL; +RasterizerStorage *VisualServerGlobals::storage = NULL; +RasterizerCanvas *VisualServerGlobals::canvas_render = NULL; +RasterizerScene *VisualServerGlobals::scene_render = NULL; +Rasterizer *VisualServerGlobals::rasterizer = NULL; -VisualServerCanvas *VisualServerGlobals::canvas=NULL; -VisualServerViewport *VisualServerGlobals::viewport=NULL; -VisualServerScene *VisualServerGlobals::scene=NULL; +VisualServerCanvas *VisualServerGlobals::canvas = NULL; +VisualServerViewport *VisualServerGlobals::viewport = NULL; +VisualServerScene *VisualServerGlobals::scene = NULL; diff --git a/servers/visual/visual_server_global.h b/servers/visual/visual_server_global.h index f95aed3ffb..d55059cd55 100644 --- a/servers/visual/visual_server_global.h +++ b/servers/visual/visual_server_global.h @@ -35,10 +35,8 @@ class VisualServerCanvas; class VisualServerViewport; class VisualServerScene; -class VisualServerGlobals -{ +class VisualServerGlobals { public: - static RasterizerStorage *storage; static RasterizerCanvas *canvas_render; static RasterizerScene *scene_render; diff --git a/servers/visual/visual_server_light_baker.cpp b/servers/visual/visual_server_light_baker.cpp index bdf20df618..493eeb49ca 100644 --- a/servers/visual/visual_server_light_baker.cpp +++ b/servers/visual/visual_server_light_baker.cpp @@ -28,7 +28,5 @@ /*************************************************************************/ #include "visual_server_light_baker.h" -VisualServerLightBaker::VisualServerLightBaker() -{ - +VisualServerLightBaker::VisualServerLightBaker() { } diff --git a/servers/visual/visual_server_light_baker.h b/servers/visual/visual_server_light_baker.h index 416c16ed3a..82909bb082 100644 --- a/servers/visual/visual_server_light_baker.h +++ b/servers/visual/visual_server_light_baker.h @@ -33,7 +33,6 @@ class VisualServerLightBaker { public: - struct BakeCell { uint32_t cells[8]; @@ -43,14 +42,8 @@ public: uint32_t light[4]; //accumulated light in 16:16 fixed point (needs to be integer for moving lights fast) float alpha; //used for upsampling uint32_t directional_pass; //used for baking directional - }; - - - - - VisualServerLightBaker(); }; diff --git a/servers/visual/visual_server_raster.cpp b/servers/visual/visual_server_raster.cpp index 3a5ffda8f5..2666a95595 100644 --- a/servers/visual/visual_server_raster.cpp +++ b/servers/visual/visual_server_raster.cpp @@ -27,48 +27,37 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "visual_server_raster.h" -#include "os/os.h" -#include "global_config.h" #include "default_mouse_cursor.xpm" -#include "sort.h" +#include "global_config.h" #include "io/marshalls.h" +#include "os/os.h" +#include "sort.h" #include "visual_server_canvas.h" #include "visual_server_global.h" #include "visual_server_scene.h" // careful, these may run in different threads than the visual server - - - /* CURSOR */ -void VisualServerRaster::cursor_set_rotation(float p_rotation, int p_cursor ){ - +void VisualServerRaster::cursor_set_rotation(float p_rotation, int p_cursor) { } -void VisualServerRaster::cursor_set_texture(RID p_texture, const Point2 &p_center_offset, int p_cursor, const Rect2 &p_region){ - +void VisualServerRaster::cursor_set_texture(RID p_texture, const Point2 &p_center_offset, int p_cursor, const Rect2 &p_region) { } -void VisualServerRaster::cursor_set_visible(bool p_visible, int p_cursor ){ - +void VisualServerRaster::cursor_set_visible(bool p_visible, int p_cursor) { } -void VisualServerRaster::cursor_set_pos(const Point2& p_pos, int p_cursor ){ - +void VisualServerRaster::cursor_set_pos(const Point2 &p_pos, int p_cursor) { } /* BLACK BARS */ - -void VisualServerRaster::black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom){ - +void VisualServerRaster::black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom) { } -void VisualServerRaster::black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom){ - +void VisualServerRaster::black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom) { } - /* FREE */ -void VisualServerRaster::free( RID p_rid ){ +void VisualServerRaster::free(RID p_rid) { if (VSG::storage->free(p_rid)) return; @@ -78,19 +67,18 @@ void VisualServerRaster::free( RID p_rid ){ return; if (VSG::scene->free(p_rid)) return; - } /* EVENT QUEUING */ -void VisualServerRaster::draw(){ +void VisualServerRaster::draw() { /* if (changes) print_line("changes: "+itos(changes)); */ - changes=0; + changes = 0; VSG::rasterizer->begin_frame(); @@ -102,19 +90,17 @@ void VisualServerRaster::draw(){ VSG::rasterizer->end_frame(); //draw_extra_frame=VS:rasterizer->needs_to_draw_next_frame(); } -void VisualServerRaster::sync(){ - +void VisualServerRaster::sync() { } -bool VisualServerRaster::has_changed() const{ +bool VisualServerRaster::has_changed() const { - return changes>0; + return changes > 0; } -void VisualServerRaster::init(){ +void VisualServerRaster::init() { VSG::rasterizer->initialize(); - } -void VisualServerRaster::finish(){ +void VisualServerRaster::finish() { if (test_cube.is_valid()) { free(test_cube); @@ -123,26 +109,18 @@ void VisualServerRaster::finish(){ VSG::rasterizer->finalize(); } - /* STATUS INFORMATION */ - -int VisualServerRaster::get_render_info(RenderInfo p_info){ +int VisualServerRaster::get_render_info(RenderInfo p_info) { return 0; } - - /* TESTING */ - - -void VisualServerRaster::set_boot_image(const Image& p_image, const Color& p_color,bool p_scale){ - +void VisualServerRaster::set_boot_image(const Image &p_image, const Color &p_color, bool p_scale) { } -void VisualServerRaster::set_default_clear_color(const Color& p_color){ - +void VisualServerRaster::set_default_clear_color(const Color &p_color) { } bool VisualServerRaster::has_feature(Features p_feature) const { @@ -152,27 +130,25 @@ bool VisualServerRaster::has_feature(Features p_feature) const { RID VisualServerRaster::get_test_cube() { if (!test_cube.is_valid()) { - test_cube=_make_test_cube(); + test_cube = _make_test_cube(); } return test_cube; } - -bool VisualServerRaster::has_os_feature(const String& p_feature) const { +bool VisualServerRaster::has_os_feature(const String &p_feature) const { return VSG::storage->has_os_feature(p_feature); } VisualServerRaster::VisualServerRaster() { - VSG::canvas = memnew( VisualServerCanvas); - VSG::viewport = memnew( VisualServerViewport); - VSG::scene = memnew( VisualServerScene ); + VSG::canvas = memnew(VisualServerCanvas); + VSG::viewport = memnew(VisualServerViewport); + VSG::scene = memnew(VisualServerScene); VSG::rasterizer = Rasterizer::create(); - VSG::storage=VSG::rasterizer->get_storage(); - VSG::canvas_render=VSG::rasterizer->get_canvas(); - VSG::scene_render=VSG::rasterizer->get_scene(); - + VSG::storage = VSG::rasterizer->get_storage(); + VSG::canvas_render = VSG::rasterizer->get_canvas(); + VSG::scene_render = VSG::rasterizer->get_scene(); } VisualServerRaster::~VisualServerRaster() { @@ -182,12 +158,11 @@ VisualServerRaster::~VisualServerRaster() { memdelete(VSG::rasterizer); } - #if 0 BalloonAllocator<> *VisualServerRaster::OctreeAllocator::allocator=NULL; -#define VS_CHANGED\ +#define VS_CHANGED \ changes++;\ //print_line(__FUNCTION__); @@ -5371,8 +5346,6 @@ CameraMatrix _lispm_look( const Vector3 pos, const Vector3 dir, const Vector3 up return cmout; } - - #if 1 void VisualServerRaster::_light_instance_update_lispsm_shadow(Instance *p_light,Scenario *p_scenario,Camera *p_camera,const CullRange& p_cull_range) { diff --git a/servers/visual/visual_server_raster.h b/servers/visual/visual_server_raster.h index 7d547e1862..58e07057f2 100644 --- a/servers/visual/visual_server_raster.h +++ b/servers/visual/visual_server_raster.h @@ -29,36 +29,30 @@ #ifndef VISUAL_SERVER_RASTER_H #define VISUAL_SERVER_RASTER_H - -#include "servers/visual_server.h" -#include "servers/visual/rasterizer.h" #include "allocators.h" #include "octree.h" -#include "visual_server_global.h" -#include "visual_server_viewport.h" +#include "servers/visual/rasterizer.h" +#include "servers/visual_server.h" #include "visual_server_canvas.h" +#include "visual_server_global.h" #include "visual_server_scene.h" +#include "visual_server_viewport.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - - - class VisualServerRaster : public VisualServer { - enum { - MAX_INSTANCE_CULL=8192, - MAX_INSTANCE_LIGHTS=4, - LIGHT_CACHE_DIRTY=-1, - MAX_LIGHTS_CULLED=256, - MAX_ROOM_CULL=32, - MAX_EXTERIOR_PORTALS=128, - MAX_LIGHT_SAMPLERS=256, - INSTANCE_ROOMLESS_MASK=(1<<20) - + MAX_INSTANCE_CULL = 8192, + MAX_INSTANCE_LIGHTS = 4, + LIGHT_CACHE_DIRTY = -1, + MAX_LIGHTS_CULLED = 256, + MAX_ROOM_CULL = 32, + MAX_EXTERIOR_PORTALS = 128, + MAX_LIGHT_SAMPLERS = 256, + INSTANCE_ROOMLESS_MASK = (1 << 20) }; @@ -66,8 +60,7 @@ class VisualServerRaster : public VisualServer { bool draw_extra_frame; RID test_cube; - - #if 0 +#if 0 struct Room { bool occlude_exterior; @@ -582,293 +575,299 @@ class VisualServerRaster : public VisualServer { #endif public: - #define DISPLAY_CHANGED changes++; -#define BIND0R(m_r,m_name) m_r m_name() { return BINDBASE->m_name(); } -#define BIND1R(m_r,m_name,m_type1) m_r m_name(m_type1 arg1) { return BINDBASE->m_name(arg1); } -#define BIND1RC(m_r,m_name,m_type1) m_r m_name(m_type1 arg1) const { return BINDBASE->m_name(arg1); } -#define BIND2RC(m_r,m_name,m_type1,m_type2) m_r m_name(m_type1 arg1,m_type2 arg2) const { return BINDBASE->m_name(arg1,arg2); } -#define BIND3RC(m_r,m_name,m_type1,m_type2,m_type3) m_r m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3) const { return BINDBASE->m_name(arg1,arg2,arg3); } -#define BIND4RC(m_r,m_name,m_type1,m_type2,m_type3,m_type4) m_r m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4) const { return BINDBASE->m_name(arg1,arg2,arg3,arg4); } - -#define BIND1(m_name,m_type1) void m_name(m_type1 arg1) { DISPLAY_CHANGED BINDBASE->m_name(arg1); } -#define BIND2(m_name,m_type1,m_type2) void m_name(m_type1 arg1,m_type2 arg2) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2); } -#define BIND2C(m_name,m_type1,m_type2) void m_name(m_type1 arg1,m_type2 arg2) const { BINDBASE->m_name(arg1,arg2); } -#define BIND3(m_name,m_type1,m_type2,m_type3) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3); } -#define BIND4(m_name,m_type1,m_type2,m_type3,m_type4) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4); } -#define BIND5(m_name,m_type1,m_type2,m_type3,m_type4,m_type5) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5); } -#define BIND6(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6); } -#define BIND7(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7); } -#define BIND8(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7,m_type8) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7,m_type8 arg8) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); } -#define BIND9(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7,m_type8,m_type9) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7,m_type8 arg8,m_type9 arg9) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); } -#define BIND10(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7,m_type8,m_type9,m_type10) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7,m_type8 arg8,m_type9 arg9,m_type10 arg10) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); } +#define BIND0R(m_r, m_name) \ + m_r m_name() { return BINDBASE->m_name(); } +#define BIND1R(m_r, m_name, m_type1) \ + m_r m_name(m_type1 arg1) { return BINDBASE->m_name(arg1); } +#define BIND1RC(m_r, m_name, m_type1) \ + m_r m_name(m_type1 arg1) const { return BINDBASE->m_name(arg1); } +#define BIND2RC(m_r, m_name, m_type1, m_type2) \ + m_r m_name(m_type1 arg1, m_type2 arg2) const { return BINDBASE->m_name(arg1, arg2); } +#define BIND3RC(m_r, m_name, m_type1, m_type2, m_type3) \ + m_r m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3) const { return BINDBASE->m_name(arg1, arg2, arg3); } +#define BIND4RC(m_r, m_name, m_type1, m_type2, m_type3, m_type4) \ + m_r m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4) const { return BINDBASE->m_name(arg1, arg2, arg3, arg4); } + +#define BIND1(m_name, m_type1) \ + void m_name(m_type1 arg1) { DISPLAY_CHANGED BINDBASE->m_name(arg1); } +#define BIND2(m_name, m_type1, m_type2) \ + void m_name(m_type1 arg1, m_type2 arg2) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2); } +#define BIND2C(m_name, m_type1, m_type2) \ + void m_name(m_type1 arg1, m_type2 arg2) const { BINDBASE->m_name(arg1, arg2); } +#define BIND3(m_name, m_type1, m_type2, m_type3) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3); } +#define BIND4(m_name, m_type1, m_type2, m_type3, m_type4) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4); } +#define BIND5(m_name, m_type1, m_type2, m_type3, m_type4, m_type5) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5); } +#define BIND6(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6); } +#define BIND7(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7); } +#define BIND8(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } +#define BIND9(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } +#define BIND10(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9, m_type10) \ + void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9, m_type10 arg10) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } //from now on, calls forwarded to this singleton #define BINDBASE VSG::storage /* TEXTURE API */ + BIND0R(RID, texture_create) + BIND5(texture_allocate, RID, int, int, Image::Format, uint32_t) + BIND3(texture_set_data, RID, const Image &, CubeMapSide) + BIND2RC(Image, texture_get_data, RID, CubeMapSide) + BIND2(texture_set_flags, RID, uint32_t) + BIND1RC(uint32_t, texture_get_flags, RID) + BIND1RC(Image::Format, texture_get_format, RID) + BIND1RC(uint32_t, texture_get_width, RID) + BIND1RC(uint32_t, texture_get_height, RID) + BIND3(texture_set_size_override, RID, int, int) + BIND2RC(RID, texture_create_radiance_cubemap, RID, int) - BIND0R(RID,texture_create) - BIND5(texture_allocate,RID,int,int,Image::Format,uint32_t) - BIND3(texture_set_data,RID,const Image&,CubeMapSide) - BIND2RC(Image,texture_get_data,RID,CubeMapSide) - BIND2(texture_set_flags,RID,uint32_t) - BIND1RC(uint32_t,texture_get_flags,RID) - BIND1RC(Image::Format,texture_get_format,RID) - BIND1RC(uint32_t,texture_get_width,RID) - BIND1RC(uint32_t,texture_get_height,RID) - BIND3(texture_set_size_override,RID,int,int) - BIND2RC(RID,texture_create_radiance_cubemap,RID,int) - - BIND3(texture_set_detect_3d_callback,RID,TextureDetectCallback,void*) - BIND3(texture_set_detect_srgb_callback,RID,TextureDetectCallback,void*) + BIND3(texture_set_detect_3d_callback, RID, TextureDetectCallback, void *) + BIND3(texture_set_detect_srgb_callback, RID, TextureDetectCallback, void *) - BIND2(texture_set_path,RID,const String&) - BIND1RC(String,texture_get_path,RID) - BIND1(texture_set_shrink_all_x2_on_set_data,bool) - BIND1(texture_debug_usage,List<TextureInfo>*) + BIND2(texture_set_path, RID, const String &) + BIND1RC(String, texture_get_path, RID) + BIND1(texture_set_shrink_all_x2_on_set_data, bool) + BIND1(texture_debug_usage, List<TextureInfo> *) - BIND1(textures_keep_original,bool) + BIND1(textures_keep_original, bool) /* SKYBOX API */ - BIND0R(RID,skybox_create) - BIND3(skybox_set_texture,RID,RID,int) + BIND0R(RID, skybox_create) + BIND3(skybox_set_texture, RID, RID, int) /* SHADER API */ - BIND1R(RID,shader_create,ShaderMode) + BIND1R(RID, shader_create, ShaderMode) + BIND2(shader_set_mode, RID, ShaderMode) + BIND1RC(ShaderMode, shader_get_mode, RID) - BIND2(shader_set_mode,RID,ShaderMode) - BIND1RC(ShaderMode,shader_get_mode,RID) + BIND2(shader_set_code, RID, const String &) + BIND1RC(String, shader_get_code, RID) - BIND2(shader_set_code,RID,const String&) - BIND1RC(String,shader_get_code,RID) - - BIND2C(shader_get_param_list,RID, List<PropertyInfo> *) - - BIND3(shader_set_default_texture_param,RID,const StringName&,RID) - BIND2RC(RID,shader_get_default_texture_param,RID,const StringName&) + BIND2C(shader_get_param_list, RID, List<PropertyInfo> *) + BIND3(shader_set_default_texture_param, RID, const StringName &, RID) + BIND2RC(RID, shader_get_default_texture_param, RID, const StringName &) /* COMMON MATERIAL API */ - BIND0R(RID,material_create) - - BIND2(material_set_shader,RID,RID) - BIND1RC(RID,material_get_shader,RID) - - BIND3(material_set_param,RID, const StringName&, const Variant& ) - BIND2RC(Variant,material_get_param,RID, const StringName& ) + BIND0R(RID, material_create) - BIND2(material_set_line_width,RID, float ) + BIND2(material_set_shader, RID, RID) + BIND1RC(RID, material_get_shader, RID) + BIND3(material_set_param, RID, const StringName &, const Variant &) + BIND2RC(Variant, material_get_param, RID, const StringName &) + BIND2(material_set_line_width, RID, float) /* MESH API */ - BIND0R(RID,mesh_create) + BIND0R(RID, mesh_create) - BIND10(mesh_add_surface,RID,uint32_t,PrimitiveType,const PoolVector<uint8_t>&,int ,const PoolVector<uint8_t>& ,int ,const Rect3&,const Vector<PoolVector<uint8_t> >&,const Vector<Rect3>& ) + BIND10(mesh_add_surface, RID, uint32_t, PrimitiveType, const PoolVector<uint8_t> &, int, const PoolVector<uint8_t> &, int, const Rect3 &, const Vector<PoolVector<uint8_t> > &, const Vector<Rect3> &) - BIND2(mesh_set_blend_shape_count,RID,int) - BIND1RC(int,mesh_get_blend_shape_count,RID) + BIND2(mesh_set_blend_shape_count, RID, int) + BIND1RC(int, mesh_get_blend_shape_count, RID) + BIND2(mesh_set_blend_shape_mode, RID, BlendShapeMode) + BIND1RC(BlendShapeMode, mesh_get_blend_shape_mode, RID) - BIND2(mesh_set_blend_shape_mode,RID,BlendShapeMode) - BIND1RC(BlendShapeMode, mesh_get_blend_shape_mode,RID ) + BIND3(mesh_surface_set_material, RID, int, RID) + BIND2RC(RID, mesh_surface_get_material, RID, int) - BIND3(mesh_surface_set_material,RID, int , RID ) - BIND2RC(RID,mesh_surface_get_material,RID, int ) + BIND2RC(int, mesh_surface_get_array_len, RID, int) + BIND2RC(int, mesh_surface_get_array_index_len, RID, int) - BIND2RC(int,mesh_surface_get_array_len,RID,int) - BIND2RC(int,mesh_surface_get_array_index_len,RID,int) + BIND2RC(PoolVector<uint8_t>, mesh_surface_get_array, RID, int) + BIND2RC(PoolVector<uint8_t>, mesh_surface_get_index_array, RID, int) - BIND2RC(PoolVector<uint8_t>,mesh_surface_get_array,RID,int) - BIND2RC(PoolVector<uint8_t>,mesh_surface_get_index_array,RID, int) + BIND2RC(uint32_t, mesh_surface_get_format, RID, int) + BIND2RC(PrimitiveType, mesh_surface_get_primitive_type, RID, int) - BIND2RC(uint32_t,mesh_surface_get_format,RID,int) - BIND2RC(PrimitiveType,mesh_surface_get_primitive_type,RID,int) + BIND2RC(Rect3, mesh_surface_get_aabb, RID, int) + BIND2RC(Vector<PoolVector<uint8_t> >, mesh_surface_get_blend_shapes, RID, int) + BIND2RC(Vector<Rect3>, mesh_surface_get_skeleton_aabb, RID, int) - BIND2RC(Rect3,mesh_surface_get_aabb,RID,int) - BIND2RC(Vector<PoolVector<uint8_t> >,mesh_surface_get_blend_shapes,RID,int) - BIND2RC(Vector<Rect3>,mesh_surface_get_skeleton_aabb,RID,int) + BIND2(mesh_remove_surface, RID, int) + BIND1RC(int, mesh_get_surface_count, RID) - BIND2(mesh_remove_surface,RID,int) - BIND1RC(int,mesh_get_surface_count,RID) + BIND2(mesh_set_custom_aabb, RID, const Rect3 &) + BIND1RC(Rect3, mesh_get_custom_aabb, RID) - BIND2(mesh_set_custom_aabb,RID,const Rect3&) - BIND1RC(Rect3,mesh_get_custom_aabb,RID) - - BIND1(mesh_clear,RID) + BIND1(mesh_clear, RID) /* MULTIMESH API */ + BIND0R(RID, multimesh_create) - BIND0R(RID,multimesh_create) - - BIND4(multimesh_allocate,RID,int,MultimeshTransformFormat,MultimeshColorFormat) - BIND1RC(int,multimesh_get_instance_count,RID) + BIND4(multimesh_allocate, RID, int, MultimeshTransformFormat, MultimeshColorFormat) + BIND1RC(int, multimesh_get_instance_count, RID) - BIND2(multimesh_set_mesh,RID,RID) - BIND3(multimesh_instance_set_transform,RID,int,const Transform&) - BIND3(multimesh_instance_set_transform_2d,RID,int,const Transform2D& ) - BIND3(multimesh_instance_set_color,RID,int,const Color&) + BIND2(multimesh_set_mesh, RID, RID) + BIND3(multimesh_instance_set_transform, RID, int, const Transform &) + BIND3(multimesh_instance_set_transform_2d, RID, int, const Transform2D &) + BIND3(multimesh_instance_set_color, RID, int, const Color &) - BIND1RC(RID,multimesh_get_mesh,RID) - BIND1RC(Rect3,multimesh_get_aabb,RID) + BIND1RC(RID, multimesh_get_mesh, RID) + BIND1RC(Rect3, multimesh_get_aabb, RID) - BIND2RC(Transform,multimesh_instance_get_transform,RID,int ) - BIND2RC(Transform2D,multimesh_instance_get_transform_2d,RID,int) - BIND2RC(Color,multimesh_instance_get_color,RID,int) - - BIND2(multimesh_set_visible_instances,RID,int) - BIND1RC(int,multimesh_get_visible_instances,RID) + BIND2RC(Transform, multimesh_instance_get_transform, RID, int) + BIND2RC(Transform2D, multimesh_instance_get_transform_2d, RID, int) + BIND2RC(Color, multimesh_instance_get_color, RID, int) + BIND2(multimesh_set_visible_instances, RID, int) + BIND1RC(int, multimesh_get_visible_instances, RID) /* IMMEDIATE API */ - BIND0R(RID,immediate_create) - BIND3(immediate_begin,RID,PrimitiveType,RID) - BIND2(immediate_vertex,RID,const Vector3&) - BIND2(immediate_normal,RID,const Vector3&) - BIND2(immediate_tangent,RID,const Plane&) - BIND2(immediate_color,RID,const Color&) - BIND2(immediate_uv,RID,const Vector2& ) - BIND2(immediate_uv2,RID,const Vector2&) - BIND1(immediate_end,RID) - BIND1(immediate_clear,RID) - BIND2(immediate_set_material,RID ,RID ) - BIND1RC(RID,immediate_get_material,RID) + BIND0R(RID, immediate_create) + BIND3(immediate_begin, RID, PrimitiveType, RID) + BIND2(immediate_vertex, RID, const Vector3 &) + BIND2(immediate_normal, RID, const Vector3 &) + BIND2(immediate_tangent, RID, const Plane &) + BIND2(immediate_color, RID, const Color &) + BIND2(immediate_uv, RID, const Vector2 &) + BIND2(immediate_uv2, RID, const Vector2 &) + BIND1(immediate_end, RID) + BIND1(immediate_clear, RID) + BIND2(immediate_set_material, RID, RID) + BIND1RC(RID, immediate_get_material, RID) /* SKELETON API */ - BIND0R(RID,skeleton_create) - BIND3(skeleton_allocate,RID,int,bool) - BIND1RC(int,skeleton_get_bone_count,RID) - BIND3(skeleton_bone_set_transform,RID,int,const Transform&) - BIND2RC(Transform,skeleton_bone_get_transform,RID,int) - BIND3(skeleton_bone_set_transform_2d,RID,int, const Transform2D& ) - BIND2RC(Transform2D,skeleton_bone_get_transform_2d,RID,int) + BIND0R(RID, skeleton_create) + BIND3(skeleton_allocate, RID, int, bool) + BIND1RC(int, skeleton_get_bone_count, RID) + BIND3(skeleton_bone_set_transform, RID, int, const Transform &) + BIND2RC(Transform, skeleton_bone_get_transform, RID, int) + BIND3(skeleton_bone_set_transform_2d, RID, int, const Transform2D &) + BIND2RC(Transform2D, skeleton_bone_get_transform_2d, RID, int) /* Light API */ - BIND1R(RID,light_create,LightType) + BIND1R(RID, light_create, LightType) - BIND2(light_set_color,RID,const Color&) - BIND3(light_set_param,RID ,LightParam ,float ) - BIND2(light_set_shadow,RID ,bool ) - BIND2(light_set_shadow_color,RID ,const Color& ) - BIND2(light_set_projector,RID,RID ) - BIND2(light_set_negative,RID,bool ) - BIND2(light_set_cull_mask,RID ,uint32_t ) + BIND2(light_set_color, RID, const Color &) + BIND3(light_set_param, RID, LightParam, float) + BIND2(light_set_shadow, RID, bool) + BIND2(light_set_shadow_color, RID, const Color &) + BIND2(light_set_projector, RID, RID) + BIND2(light_set_negative, RID, bool) + BIND2(light_set_cull_mask, RID, uint32_t) - BIND2(light_omni_set_shadow_mode,RID,LightOmniShadowMode) - BIND2(light_omni_set_shadow_detail,RID,LightOmniShadowDetail) + BIND2(light_omni_set_shadow_mode, RID, LightOmniShadowMode) + BIND2(light_omni_set_shadow_detail, RID, LightOmniShadowDetail) - BIND2(light_directional_set_shadow_mode,RID,LightDirectionalShadowMode) - BIND2(light_directional_set_blend_splits,RID,bool) + BIND2(light_directional_set_shadow_mode, RID, LightDirectionalShadowMode) + BIND2(light_directional_set_blend_splits, RID, bool) /* PROBE API */ - BIND0R(RID,reflection_probe_create) - - BIND2(reflection_probe_set_update_mode,RID, ReflectionProbeUpdateMode ) - BIND2(reflection_probe_set_intensity,RID, float ) - BIND2(reflection_probe_set_interior_ambient,RID, const Color& ) - BIND2(reflection_probe_set_interior_ambient_energy,RID, float ) - BIND2(reflection_probe_set_interior_ambient_probe_contribution,RID, float ) - BIND2(reflection_probe_set_max_distance,RID, float ) - BIND2(reflection_probe_set_extents,RID, const Vector3& ) - BIND2(reflection_probe_set_origin_offset,RID, const Vector3& ) - BIND2(reflection_probe_set_as_interior,RID, bool ) - BIND2(reflection_probe_set_enable_box_projection,RID, bool ) - BIND2(reflection_probe_set_enable_shadows,RID, bool ) - BIND2(reflection_probe_set_cull_mask,RID, uint32_t ) + BIND0R(RID, reflection_probe_create) + + BIND2(reflection_probe_set_update_mode, RID, ReflectionProbeUpdateMode) + BIND2(reflection_probe_set_intensity, RID, float) + BIND2(reflection_probe_set_interior_ambient, RID, const Color &) + BIND2(reflection_probe_set_interior_ambient_energy, RID, float) + BIND2(reflection_probe_set_interior_ambient_probe_contribution, RID, float) + BIND2(reflection_probe_set_max_distance, RID, float) + BIND2(reflection_probe_set_extents, RID, const Vector3 &) + BIND2(reflection_probe_set_origin_offset, RID, const Vector3 &) + BIND2(reflection_probe_set_as_interior, RID, bool) + BIND2(reflection_probe_set_enable_box_projection, RID, bool) + BIND2(reflection_probe_set_enable_shadows, RID, bool) + BIND2(reflection_probe_set_cull_mask, RID, uint32_t) /* ROOM API */ - BIND0R(RID,room_create) - BIND4(room_add_bounds,RID, const PoolVector<Vector2>& ,float ,const Transform& ) - BIND1(room_clear_bounds,RID) + BIND0R(RID, room_create) + BIND4(room_add_bounds, RID, const PoolVector<Vector2> &, float, const Transform &) + BIND1(room_clear_bounds, RID) /* PORTAL API */ // portals are only (x/y) points, forming a convex shape, which its clockwise // order points outside. (z is 0); - BIND0R(RID,portal_create) - BIND2(portal_set_shape,RID , const Vector<Point2>& ) - BIND2(portal_set_enabled,RID , bool ) - BIND2(portal_set_disable_distance,RID , float ) - BIND2(portal_set_disabled_color,RID , const Color& ) + BIND0R(RID, portal_create) + BIND2(portal_set_shape, RID, const Vector<Point2> &) + BIND2(portal_set_enabled, RID, bool) + BIND2(portal_set_disable_distance, RID, float) + BIND2(portal_set_disabled_color, RID, const Color &) /* BAKED LIGHT API */ BIND0R(RID, gi_probe_create) - BIND2(gi_probe_set_bounds,RID,const Rect3&) - BIND1RC(Rect3,gi_probe_get_bounds,RID) + BIND2(gi_probe_set_bounds, RID, const Rect3 &) + BIND1RC(Rect3, gi_probe_get_bounds, RID) - BIND2(gi_probe_set_cell_size,RID,float) - BIND1RC(float,gi_probe_get_cell_size,RID) + BIND2(gi_probe_set_cell_size, RID, float) + BIND1RC(float, gi_probe_get_cell_size, RID) - BIND2(gi_probe_set_to_cell_xform,RID,const Transform&) - BIND1RC(Transform,gi_probe_get_to_cell_xform,RID) + BIND2(gi_probe_set_to_cell_xform, RID, const Transform &) + BIND1RC(Transform, gi_probe_get_to_cell_xform, RID) - BIND2(gi_probe_set_dynamic_range,RID,int) - BIND1RC(int,gi_probe_get_dynamic_range,RID) + BIND2(gi_probe_set_dynamic_range, RID, int) + BIND1RC(int, gi_probe_get_dynamic_range, RID) - BIND2(gi_probe_set_energy,RID,float) - BIND1RC(float,gi_probe_get_energy,RID) + BIND2(gi_probe_set_energy, RID, float) + BIND1RC(float, gi_probe_get_energy, RID) - BIND2(gi_probe_set_bias,RID,float) - BIND1RC(float,gi_probe_get_bias,RID) + BIND2(gi_probe_set_bias, RID, float) + BIND1RC(float, gi_probe_get_bias, RID) - BIND2(gi_probe_set_propagation,RID,float) - BIND1RC(float,gi_probe_get_propagation,RID) + BIND2(gi_probe_set_propagation, RID, float) + BIND1RC(float, gi_probe_get_propagation, RID) - BIND2(gi_probe_set_interior,RID,bool) - BIND1RC(bool,gi_probe_is_interior,RID) + BIND2(gi_probe_set_interior, RID, bool) + BIND1RC(bool, gi_probe_is_interior, RID) - BIND2(gi_probe_set_compress,RID,bool) - BIND1RC(bool,gi_probe_is_compressed,RID) + BIND2(gi_probe_set_compress, RID, bool) + BIND1RC(bool, gi_probe_is_compressed, RID) - BIND2(gi_probe_set_dynamic_data,RID,const PoolVector<int>& ) - BIND1RC( PoolVector<int>,gi_probe_get_dynamic_data,RID) + BIND2(gi_probe_set_dynamic_data, RID, const PoolVector<int> &) + BIND1RC(PoolVector<int>, gi_probe_get_dynamic_data, RID) /* PARTICLES */ BIND0R(RID, particles_create) - BIND2(particles_set_emitting,RID,bool) - BIND2(particles_set_amount,RID,int ) - BIND2(particles_set_lifetime,RID,float ) - BIND2(particles_set_pre_process_time,RID,float ) - BIND2(particles_set_explosiveness_ratio,RID,float ) - BIND2(particles_set_randomness_ratio,RID,float ) - BIND2(particles_set_custom_aabb,RID,const Rect3& ) - BIND2(particles_set_gravity,RID,const Vector3& ) - BIND2(particles_set_use_local_coordinates,RID,bool ) - BIND2(particles_set_process_material,RID,RID ) - - BIND2(particles_set_emission_shape,RID,VS::ParticlesEmissionShape ) - BIND2(particles_set_emission_sphere_radius,RID,float ) - BIND2(particles_set_emission_box_extents,RID,const Vector3& ) - BIND2(particles_set_emission_points,RID,const PoolVector<Vector3>& ) + BIND2(particles_set_emitting, RID, bool) + BIND2(particles_set_amount, RID, int) + BIND2(particles_set_lifetime, RID, float) + BIND2(particles_set_pre_process_time, RID, float) + BIND2(particles_set_explosiveness_ratio, RID, float) + BIND2(particles_set_randomness_ratio, RID, float) + BIND2(particles_set_custom_aabb, RID, const Rect3 &) + BIND2(particles_set_gravity, RID, const Vector3 &) + BIND2(particles_set_use_local_coordinates, RID, bool) + BIND2(particles_set_process_material, RID, RID) + BIND2(particles_set_emission_shape, RID, VS::ParticlesEmissionShape) + BIND2(particles_set_emission_sphere_radius, RID, float) + BIND2(particles_set_emission_box_extents, RID, const Vector3 &) + BIND2(particles_set_emission_points, RID, const PoolVector<Vector3> &) - BIND2(particles_set_draw_order,RID,VS::ParticlesDrawOrder ) + BIND2(particles_set_draw_order, RID, VS::ParticlesDrawOrder) - BIND2(particles_set_draw_passes,RID,int ) - BIND3(particles_set_draw_pass_material,RID,int , RID ) - BIND3(particles_set_draw_pass_mesh,RID,int , RID ) - - BIND1R(Rect3,particles_get_current_aabb,RID); + BIND2(particles_set_draw_passes, RID, int) + BIND3(particles_set_draw_pass_material, RID, int, RID) + BIND3(particles_set_draw_pass_mesh, RID, int, RID) + BIND1R(Rect3, particles_get_current_aabb, RID); #undef BINDBASE //from now on, calls forwarded to this singleton @@ -876,14 +875,13 @@ public: /* CAMERA API */ - BIND0R(RID, camera_create) - BIND4(camera_set_perspective,RID,float, float , float ) - BIND4(camera_set_orthogonal,RID,float , float , float ) - BIND2(camera_set_transform,RID,const Transform&) - BIND2(camera_set_cull_mask,RID,uint32_t ) - BIND2(camera_set_environment,RID ,RID ) - BIND2(camera_set_use_vertical_aspect,RID,bool) + BIND4(camera_set_perspective, RID, float, float, float) + BIND4(camera_set_orthogonal, RID, float, float, float) + BIND2(camera_set_transform, RID, const Transform &) + BIND2(camera_set_cull_mask, RID, uint32_t) + BIND2(camera_set_environment, RID, RID) + BIND2(camera_set_use_vertical_aspect, RID, bool) #undef BINDBASE //from now on, calls forwarded to this singleton @@ -891,122 +889,112 @@ public: /* VIEWPORT TARGET API */ - BIND0R(RID,viewport_create) - - BIND3(viewport_set_size,RID,int ,int ) - - BIND2(viewport_set_active,RID ,bool ) - BIND2(viewport_set_parent_viewport,RID,RID) + BIND0R(RID, viewport_create) - BIND2(viewport_set_clear_mode,RID,ViewportClearMode ) + BIND3(viewport_set_size, RID, int, int) - BIND3(viewport_attach_to_screen,RID ,const Rect2& ,int ) - BIND1(viewport_detach,RID) + BIND2(viewport_set_active, RID, bool) + BIND2(viewport_set_parent_viewport, RID, RID) - BIND2(viewport_set_update_mode,RID,ViewportUpdateMode ) - BIND2(viewport_set_vflip,RID,bool) + BIND2(viewport_set_clear_mode, RID, ViewportClearMode) + BIND3(viewport_attach_to_screen, RID, const Rect2 &, int) + BIND1(viewport_detach, RID) - BIND1RC(RID,viewport_get_texture,RID ) + BIND2(viewport_set_update_mode, RID, ViewportUpdateMode) + BIND2(viewport_set_vflip, RID, bool) - BIND2(viewport_set_hide_scenario,RID,bool ) - BIND2(viewport_set_hide_canvas,RID,bool ) - BIND2(viewport_set_disable_environment,RID,bool ) - BIND2(viewport_set_disable_3d,RID,bool ) + BIND1RC(RID, viewport_get_texture, RID) - BIND2(viewport_attach_camera,RID,RID ) - BIND2(viewport_set_scenario,RID,RID ) - BIND2(viewport_attach_canvas,RID,RID ) + BIND2(viewport_set_hide_scenario, RID, bool) + BIND2(viewport_set_hide_canvas, RID, bool) + BIND2(viewport_set_disable_environment, RID, bool) + BIND2(viewport_set_disable_3d, RID, bool) - BIND2(viewport_remove_canvas,RID,RID ) - BIND3(viewport_set_canvas_transform,RID ,RID ,const Transform2D& ) - BIND2(viewport_set_transparent_background,RID ,bool ) + BIND2(viewport_attach_camera, RID, RID) + BIND2(viewport_set_scenario, RID, RID) + BIND2(viewport_attach_canvas, RID, RID) - BIND2(viewport_set_global_canvas_transform,RID,const Transform2D& ) - BIND3(viewport_set_canvas_layer,RID ,RID ,int ) - BIND2(viewport_set_shadow_atlas_size,RID ,int ) - BIND3(viewport_set_shadow_atlas_quadrant_subdivision,RID ,int, int ) - BIND2(viewport_set_msaa,RID ,ViewportMSAA ) - BIND2(viewport_set_hdr,RID ,bool ) + BIND2(viewport_remove_canvas, RID, RID) + BIND3(viewport_set_canvas_transform, RID, RID, const Transform2D &) + BIND2(viewport_set_transparent_background, RID, bool) + BIND2(viewport_set_global_canvas_transform, RID, const Transform2D &) + BIND3(viewport_set_canvas_layer, RID, RID, int) + BIND2(viewport_set_shadow_atlas_size, RID, int) + BIND3(viewport_set_shadow_atlas_quadrant_subdivision, RID, int, int) + BIND2(viewport_set_msaa, RID, ViewportMSAA) + BIND2(viewport_set_hdr, RID, bool) - /* ENVIRONMENT API */ +/* ENVIRONMENT API */ #undef BINDBASE //from now on, calls forwarded to this singleton #define BINDBASE VSG::scene_render - BIND0R(RID,environment_create) - - BIND2(environment_set_background,RID ,EnvironmentBG ) - BIND2(environment_set_skybox,RID,RID ) - BIND2(environment_set_skybox_scale,RID,float) - BIND2(environment_set_bg_color,RID,const Color& ) - BIND2(environment_set_bg_energy,RID,float ) - BIND2(environment_set_canvas_max_layer,RID,int ) - BIND4(environment_set_ambient_light,RID,const Color& ,float,float ) - BIND8(environment_set_ssr,RID,bool,int,float,float,float,bool,bool ) - BIND10(environment_set_ssao,RID ,bool , float , float , float,float,float , float ,const Color &,bool ) - - - - BIND6(environment_set_dof_blur_near,RID,bool ,float,float,float,EnvironmentDOFBlurQuality) - BIND6(environment_set_dof_blur_far,RID,bool ,float,float,float,EnvironmentDOFBlurQuality) - BIND10(environment_set_glow,RID,bool ,int ,float ,float ,float ,EnvironmentGlowBlendMode,float,float,bool ) - BIND5(environment_set_fog,RID,bool ,float ,float ,RID ) + BIND0R(RID, environment_create) - BIND9(environment_set_tonemap,RID,EnvironmentToneMapper, float ,float ,bool, float ,float ,float,float ) + BIND2(environment_set_background, RID, EnvironmentBG) + BIND2(environment_set_skybox, RID, RID) + BIND2(environment_set_skybox_scale, RID, float) + BIND2(environment_set_bg_color, RID, const Color &) + BIND2(environment_set_bg_energy, RID, float) + BIND2(environment_set_canvas_max_layer, RID, int) + BIND4(environment_set_ambient_light, RID, const Color &, float, float) + BIND8(environment_set_ssr, RID, bool, int, float, float, float, bool, bool) + BIND10(environment_set_ssao, RID, bool, float, float, float, float, float, float, const Color &, bool) - BIND6(environment_set_adjustment,RID,bool ,float ,float ,float ,RID ) + BIND6(environment_set_dof_blur_near, RID, bool, float, float, float, EnvironmentDOFBlurQuality) + BIND6(environment_set_dof_blur_far, RID, bool, float, float, float, EnvironmentDOFBlurQuality) + BIND10(environment_set_glow, RID, bool, int, float, float, float, EnvironmentGlowBlendMode, float, float, bool) + BIND5(environment_set_fog, RID, bool, float, float, RID) + BIND9(environment_set_tonemap, RID, EnvironmentToneMapper, float, float, bool, float, float, float, float) - /* SCENARIO API */ + BIND6(environment_set_adjustment, RID, bool, float, float, float, RID) +/* SCENARIO API */ #undef BINDBASE #define BINDBASE VSG::scene - BIND0R(RID,scenario_create) - - BIND2(scenario_set_debug,RID,ScenarioDebugMode ) - BIND2(scenario_set_environment,RID, RID ) - BIND3(scenario_set_reflection_atlas_size,RID, int,int ) - BIND2(scenario_set_fallback_environment,RID, RID ) + BIND0R(RID, scenario_create) + BIND2(scenario_set_debug, RID, ScenarioDebugMode) + BIND2(scenario_set_environment, RID, RID) + BIND3(scenario_set_reflection_atlas_size, RID, int, int) + BIND2(scenario_set_fallback_environment, RID, RID) /* INSTANCING API */ - // from can be mesh, light, area and portal so far. - BIND0R(RID,instance_create) - - BIND2(instance_set_base,RID, RID ) // from can be mesh, light, poly, area and portal so far. - BIND2(instance_set_scenario,RID, RID ) // from can be mesh, light, poly, area and portal so far. - BIND2(instance_set_layer_mask,RID, uint32_t ) - BIND2(instance_set_transform,RID, const Transform& ) - BIND2(instance_attach_object_instance_ID,RID,ObjectID ) - BIND3(instance_set_blend_shape_weight,RID,int , float ) - BIND3(instance_set_surface_material,RID,int , RID ) - BIND2(instance_set_visible,RID ,bool) + // from can be mesh, light, area and portal so far. + BIND0R(RID, instance_create) + BIND2(instance_set_base, RID, RID) // from can be mesh, light, poly, area and portal so far. + BIND2(instance_set_scenario, RID, RID) // from can be mesh, light, poly, area and portal so far. + BIND2(instance_set_layer_mask, RID, uint32_t) + BIND2(instance_set_transform, RID, const Transform &) + BIND2(instance_attach_object_instance_ID, RID, ObjectID) + BIND3(instance_set_blend_shape_weight, RID, int, float) + BIND3(instance_set_surface_material, RID, int, RID) + BIND2(instance_set_visible, RID, bool) - BIND2(instance_attach_skeleton,RID,RID ) - BIND2(instance_set_exterior, RID, bool ) - BIND2(instance_set_room, RID, RID ) + BIND2(instance_attach_skeleton, RID, RID) + BIND2(instance_set_exterior, RID, bool) + BIND2(instance_set_room, RID, RID) - BIND2(instance_set_extra_visibility_margin, RID, real_t ) + BIND2(instance_set_extra_visibility_margin, RID, real_t) // don't use these in a game! - BIND2RC(Vector<ObjectID>,instances_cull_aabb,const Rect3& , RID) - BIND3RC(Vector<ObjectID>,instances_cull_ray,const Vector3& , const Vector3& , RID ) - BIND2RC(Vector<ObjectID>,instances_cull_convex,const Vector<Plane>& , RID) - - - BIND3(instance_geometry_set_flag,RID,InstanceFlags ,bool ) - BIND2(instance_geometry_set_cast_shadows_setting,RID, ShadowCastingSetting ) - BIND2(instance_geometry_set_material_override,RID, RID ) + BIND2RC(Vector<ObjectID>, instances_cull_aabb, const Rect3 &, RID) + BIND3RC(Vector<ObjectID>, instances_cull_ray, const Vector3 &, const Vector3 &, RID) + BIND2RC(Vector<ObjectID>, instances_cull_convex, const Vector<Plane> &, RID) + BIND3(instance_geometry_set_flag, RID, InstanceFlags, bool) + BIND2(instance_geometry_set_cast_shadows_setting, RID, ShadowCastingSetting) + BIND2(instance_geometry_set_material_override, RID, RID) - BIND5(instance_geometry_set_draw_range,RID,float ,float ,float ,float ) - BIND2(instance_geometry_set_as_instance_lod,RID,RID ) + BIND5(instance_geometry_set_draw_range, RID, float, float, float, float) + BIND2(instance_geometry_set_as_instance_lod, RID, RID) #undef BINDBASE //from now on, calls forwarded to this singleton @@ -1014,110 +1002,100 @@ public: /* CANVAS (2D) */ - BIND0R(RID,canvas_create) - BIND3(canvas_set_item_mirroring,RID ,RID ,const Point2& ) - BIND2(canvas_set_modulate,RID,const Color&) - - - BIND0R(RID,canvas_item_create) - BIND2(canvas_item_set_parent,RID ,RID) - - BIND2(canvas_item_set_visible,RID,bool ) - BIND2(canvas_item_set_light_mask,RID,int ) - - BIND2(canvas_item_set_transform,RID, const Transform2D& ) - BIND2(canvas_item_set_clip,RID, bool ) - BIND2(canvas_item_set_distance_field_mode,RID, bool ) - BIND3(canvas_item_set_custom_rect,RID, bool ,const Rect2& ) - BIND2(canvas_item_set_modulate,RID, const Color& ) - BIND2(canvas_item_set_self_modulate,RID, const Color& ) - - BIND2(canvas_item_set_draw_behind_parent,RID, bool ) - - - BIND6(canvas_item_add_line,RID, const Point2& , const Point2& ,const Color& ,float ,bool ) - BIND3(canvas_item_add_rect,RID, const Rect2& , const Color& ) - BIND4(canvas_item_add_circle,RID, const Point2& , float ,const Color& ) - BIND6(canvas_item_add_texture_rect,RID, const Rect2& , RID ,bool ,const Color& ,bool ) - BIND6(canvas_item_add_texture_rect_region,RID, const Rect2& , RID ,const Rect2& ,const Color& ,bool ) - BIND10(canvas_item_add_nine_patch,RID, const Rect2& , const Rect2& , RID ,const Vector2& , const Vector2& ,NinePatchAxisMode , NinePatchAxisMode,bool ,const Color& ) - BIND6(canvas_item_add_primitive,RID, const Vector<Point2>& , const Vector<Color>& ,const Vector<Point2>& , RID ,float ) - BIND5(canvas_item_add_polygon,RID, const Vector<Point2>& , const Vector<Color>& ,const Vector<Point2>& , RID ) - BIND7(canvas_item_add_triangle_array,RID, const Vector<int>& , const Vector<Point2>& , const Vector<Color>& ,const Vector<Point2>& , RID , int) - BIND3(canvas_item_add_mesh,RID, const RID& ,RID ) - BIND3(canvas_item_add_multimesh,RID, RID ,RID ) - BIND2(canvas_item_add_set_transform,RID,const Transform2D& ) - BIND2(canvas_item_add_clip_ignore,RID, bool ) - BIND2(canvas_item_set_sort_children_by_y,RID, bool ) - BIND2(canvas_item_set_z,RID, int ) - BIND2(canvas_item_set_z_as_relative_to_parent,RID, bool ) - BIND3(canvas_item_set_copy_to_backbuffer,RID, bool ,const Rect2& ) - - BIND1(canvas_item_clear,RID ) - BIND2(canvas_item_set_draw_index,RID,int) - - BIND2(canvas_item_set_material,RID, RID ) - - BIND2(canvas_item_set_use_parent_material,RID, bool ) - - - BIND0R(RID,canvas_light_create) - BIND2(canvas_light_attach_to_canvas,RID,RID ) - BIND2(canvas_light_set_enabled,RID, bool ) - BIND2(canvas_light_set_scale,RID, float ) - BIND2(canvas_light_set_transform,RID, const Transform2D& ) - BIND2(canvas_light_set_texture,RID, RID ) - BIND2(canvas_light_set_texture_offset,RID, const Vector2& ) - BIND2(canvas_light_set_color,RID, const Color& ) - BIND2(canvas_light_set_height,RID, float ) - BIND2(canvas_light_set_energy,RID, float ) - BIND3(canvas_light_set_z_range,RID, int ,int ) - BIND3(canvas_light_set_layer_range,RID, int ,int ) - BIND2(canvas_light_set_item_cull_mask,RID, int ) - BIND2(canvas_light_set_item_shadow_cull_mask,RID, int ) - - BIND2(canvas_light_set_mode,RID, CanvasLightMode ) - - BIND2(canvas_light_set_shadow_enabled,RID, bool ) - BIND2(canvas_light_set_shadow_buffer_size,RID, int ) - BIND2(canvas_light_set_shadow_gradient_length,RID, float ) - BIND2(canvas_light_set_shadow_filter,RID, CanvasLightShadowFilter ) - BIND2(canvas_light_set_shadow_color,RID, const Color& ) - - - - BIND0R(RID,canvas_light_occluder_create) - BIND2(canvas_light_occluder_attach_to_canvas,RID,RID ) - BIND2(canvas_light_occluder_set_enabled,RID,bool ) - BIND2(canvas_light_occluder_set_polygon,RID,RID ) - BIND2(canvas_light_occluder_set_transform,RID,const Transform2D& ) - BIND2(canvas_light_occluder_set_light_mask,RID,int ) - - - BIND0R(RID,canvas_occluder_polygon_create) - BIND3(canvas_occluder_polygon_set_shape,RID,const PoolVector<Vector2>& ,bool) - BIND2(canvas_occluder_polygon_set_shape_as_lines,RID ,const PoolVector<Vector2>&) - - - BIND2(canvas_occluder_polygon_set_cull_mode,RID,CanvasOccluderPolygonCullMode) - + BIND0R(RID, canvas_create) + BIND3(canvas_set_item_mirroring, RID, RID, const Point2 &) + BIND2(canvas_set_modulate, RID, const Color &) + + BIND0R(RID, canvas_item_create) + BIND2(canvas_item_set_parent, RID, RID) + + BIND2(canvas_item_set_visible, RID, bool) + BIND2(canvas_item_set_light_mask, RID, int) + + BIND2(canvas_item_set_transform, RID, const Transform2D &) + BIND2(canvas_item_set_clip, RID, bool) + BIND2(canvas_item_set_distance_field_mode, RID, bool) + BIND3(canvas_item_set_custom_rect, RID, bool, const Rect2 &) + BIND2(canvas_item_set_modulate, RID, const Color &) + BIND2(canvas_item_set_self_modulate, RID, const Color &) + + BIND2(canvas_item_set_draw_behind_parent, RID, bool) + + BIND6(canvas_item_add_line, RID, const Point2 &, const Point2 &, const Color &, float, bool) + BIND3(canvas_item_add_rect, RID, const Rect2 &, const Color &) + BIND4(canvas_item_add_circle, RID, const Point2 &, float, const Color &) + BIND6(canvas_item_add_texture_rect, RID, const Rect2 &, RID, bool, const Color &, bool) + BIND6(canvas_item_add_texture_rect_region, RID, const Rect2 &, RID, const Rect2 &, const Color &, bool) + BIND10(canvas_item_add_nine_patch, RID, const Rect2 &, const Rect2 &, RID, const Vector2 &, const Vector2 &, NinePatchAxisMode, NinePatchAxisMode, bool, const Color &) + BIND6(canvas_item_add_primitive, RID, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID, float) + BIND5(canvas_item_add_polygon, RID, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID) + BIND7(canvas_item_add_triangle_array, RID, const Vector<int> &, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID, int) + BIND3(canvas_item_add_mesh, RID, const RID &, RID) + BIND3(canvas_item_add_multimesh, RID, RID, RID) + BIND2(canvas_item_add_set_transform, RID, const Transform2D &) + BIND2(canvas_item_add_clip_ignore, RID, bool) + BIND2(canvas_item_set_sort_children_by_y, RID, bool) + BIND2(canvas_item_set_z, RID, int) + BIND2(canvas_item_set_z_as_relative_to_parent, RID, bool) + BIND3(canvas_item_set_copy_to_backbuffer, RID, bool, const Rect2 &) + + BIND1(canvas_item_clear, RID) + BIND2(canvas_item_set_draw_index, RID, int) + + BIND2(canvas_item_set_material, RID, RID) + + BIND2(canvas_item_set_use_parent_material, RID, bool) + + BIND0R(RID, canvas_light_create) + BIND2(canvas_light_attach_to_canvas, RID, RID) + BIND2(canvas_light_set_enabled, RID, bool) + BIND2(canvas_light_set_scale, RID, float) + BIND2(canvas_light_set_transform, RID, const Transform2D &) + BIND2(canvas_light_set_texture, RID, RID) + BIND2(canvas_light_set_texture_offset, RID, const Vector2 &) + BIND2(canvas_light_set_color, RID, const Color &) + BIND2(canvas_light_set_height, RID, float) + BIND2(canvas_light_set_energy, RID, float) + BIND3(canvas_light_set_z_range, RID, int, int) + BIND3(canvas_light_set_layer_range, RID, int, int) + BIND2(canvas_light_set_item_cull_mask, RID, int) + BIND2(canvas_light_set_item_shadow_cull_mask, RID, int) + + BIND2(canvas_light_set_mode, RID, CanvasLightMode) + + BIND2(canvas_light_set_shadow_enabled, RID, bool) + BIND2(canvas_light_set_shadow_buffer_size, RID, int) + BIND2(canvas_light_set_shadow_gradient_length, RID, float) + BIND2(canvas_light_set_shadow_filter, RID, CanvasLightShadowFilter) + BIND2(canvas_light_set_shadow_color, RID, const Color &) + + BIND0R(RID, canvas_light_occluder_create) + BIND2(canvas_light_occluder_attach_to_canvas, RID, RID) + BIND2(canvas_light_occluder_set_enabled, RID, bool) + BIND2(canvas_light_occluder_set_polygon, RID, RID) + BIND2(canvas_light_occluder_set_transform, RID, const Transform2D &) + BIND2(canvas_light_occluder_set_light_mask, RID, int) + + BIND0R(RID, canvas_occluder_polygon_create) + BIND3(canvas_occluder_polygon_set_shape, RID, const PoolVector<Vector2> &, bool) + BIND2(canvas_occluder_polygon_set_shape_as_lines, RID, const PoolVector<Vector2> &) + + BIND2(canvas_occluder_polygon_set_cull_mode, RID, CanvasOccluderPolygonCullMode) /* CURSOR */ virtual void cursor_set_rotation(float p_rotation, int p_cursor = 0); // radians - virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor=0, const Rect2 &p_region=Rect2()); + virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor = 0, const Rect2 &p_region = Rect2()); virtual void cursor_set_visible(bool p_visible, int p_cursor = 0); - virtual void cursor_set_pos(const Point2& p_pos, int p_cursor = 0); + virtual void cursor_set_pos(const Point2 &p_pos, int p_cursor = 0); /* BLACK BARS */ - virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom); virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom); - /* FREE */ - virtual void free( RID p_rid ); ///< free RIDs associated with the visual server + virtual void free(RID p_rid); ///< free RIDs associated with the visual server /* EVENT QUEUING */ @@ -1129,21 +1107,18 @@ public: /* STATUS INFORMATION */ - virtual int get_render_info(RenderInfo p_info); virtual RID get_test_cube(); - /* TESTING */ - virtual void set_boot_image(const Image& p_image, const Color& p_color,bool p_scale); - virtual void set_default_clear_color(const Color& p_color); + virtual void set_boot_image(const Image &p_image, const Color &p_color, bool p_scale); + virtual void set_default_clear_color(const Color &p_color); virtual bool has_feature(Features p_feature) const; - virtual bool has_os_feature(const String& p_feature) const; - + virtual bool has_os_feature(const String &p_feature) const; VisualServerRaster(); ~VisualServerRaster(); @@ -1166,7 +1141,6 @@ public: #undef BIND8 #undef BIND9 #undef BIND10 - }; #endif diff --git a/servers/visual/visual_server_scene.cpp b/servers/visual/visual_server_scene.cpp index e004103508..46c7fa6791 100644 --- a/servers/visual/visual_server_scene.cpp +++ b/servers/visual/visual_server_scene.cpp @@ -27,84 +27,68 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "visual_server_scene.h" -#include "visual_server_global.h" #include "os/os.h" +#include "visual_server_global.h" /* CAMERA API */ - - - - RID VisualServerScene::camera_create() { - Camera * camera = memnew( Camera ); - return camera_owner.make_rid( camera ); - + Camera *camera = memnew(Camera); + return camera_owner.make_rid(camera); } -void VisualServerScene::camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far) { +void VisualServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) { - Camera *camera = camera_owner.get( p_camera ); + Camera *camera = camera_owner.get(p_camera); ERR_FAIL_COND(!camera); - camera->type=Camera::PERSPECTIVE; - camera->fov=p_fovy_degrees; - camera->znear=p_z_near; - camera->zfar=p_z_far; - + camera->type = Camera::PERSPECTIVE; + camera->fov = p_fovy_degrees; + camera->znear = p_z_near; + camera->zfar = p_z_far; } -void VisualServerScene::camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far) { +void VisualServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) { - Camera *camera = camera_owner.get( p_camera ); + Camera *camera = camera_owner.get(p_camera); ERR_FAIL_COND(!camera); - camera->type=Camera::ORTHOGONAL; - camera->size=p_size; - camera->znear=p_z_near; - camera->zfar=p_z_far; + camera->type = Camera::ORTHOGONAL; + camera->size = p_size; + camera->znear = p_z_near; + camera->zfar = p_z_far; } -void VisualServerScene::camera_set_transform(RID p_camera,const Transform& p_transform) { +void VisualServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) { - Camera *camera = camera_owner.get( p_camera ); + Camera *camera = camera_owner.get(p_camera); ERR_FAIL_COND(!camera); - camera->transform=p_transform.orthonormalized(); - - + camera->transform = p_transform.orthonormalized(); } -void VisualServerScene::camera_set_cull_mask(RID p_camera,uint32_t p_layers) { - +void VisualServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) { - Camera *camera = camera_owner.get( p_camera ); + Camera *camera = camera_owner.get(p_camera); ERR_FAIL_COND(!camera); - camera->visible_layers=p_layers; - + camera->visible_layers = p_layers; } -void VisualServerScene::camera_set_environment(RID p_camera,RID p_env) { +void VisualServerScene::camera_set_environment(RID p_camera, RID p_env) { - Camera *camera = camera_owner.get( p_camera ); + Camera *camera = camera_owner.get(p_camera); ERR_FAIL_COND(!camera); - camera->env=p_env; - + camera->env = p_env; } +void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) { -void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera,bool p_enable) { - - Camera *camera = camera_owner.get( p_camera ); + Camera *camera = camera_owner.get(p_camera); ERR_FAIL_COND(!camera); - camera->vaspect=p_enable; - + camera->vaspect = p_enable; } - /* SCENARIO API */ - - -void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int) { +void *VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) { //VisualServerScene *self = (VisualServerScene*)p_self; Instance *A = p_A; @@ -112,69 +96,64 @@ void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance //instance indices are designed so greater always contains lesser if (A->base_type > B->base_type) { - SWAP(A,B); //lesser always first + SWAP(A, B); //lesser always first } - if (B->base_type==VS::INSTANCE_LIGHT && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { - - InstanceLightData * light = static_cast<InstanceLightData*>(B->base_data); - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); + if (B->base_type == VS::INSTANCE_LIGHT && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) { + InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data); InstanceLightData::PairInfo pinfo; - pinfo.geometry=A; + pinfo.geometry = A; pinfo.L = geom->lighting.push_back(B); List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo); if (geom->can_cast_shadows) { - light->shadow_dirty=true; + light->shadow_dirty = true; } - geom->lighting_dirty=true; + geom->lighting_dirty = true; return E; //this element should make freeing faster - } else if (B->base_type==VS::INSTANCE_REFLECTION_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { - - InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(B->base_data); - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); + } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) { + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data); InstanceReflectionProbeData::PairInfo pinfo; - pinfo.geometry=A; + pinfo.geometry = A; pinfo.L = geom->reflection_probes.push_back(B); List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo); - geom->reflection_dirty=true; + geom->reflection_dirty = true; return E; //this element should make freeing faster - } else if (B->base_type==VS::INSTANCE_GI_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { - - InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); + } else if (B->base_type == VS::INSTANCE_GI_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) { + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data); InstanceGIProbeData::PairInfo pinfo; - pinfo.geometry=A; + pinfo.geometry = A; pinfo.L = geom->gi_probes.push_back(B); List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo); - geom->gi_probes_dirty=true; + geom->gi_probes_dirty = true; return E; //this element should make freeing faster - } else if (B->base_type==VS::INSTANCE_GI_PROBE && A->base_type==VS::INSTANCE_LIGHT) { + } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) { - InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); - InstanceLightData * light = static_cast<InstanceLightData*>(A->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(A->base_data); return gi_probe->lights.insert(A); } - - #if 0 if (A->base_type==INSTANCE_PORTAL) { @@ -228,9 +207,8 @@ void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance #endif return NULL; - } -void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int,void* udata) { +void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) { //VisualServerScene *self = (VisualServerScene*)p_self; Instance *A = p_A; @@ -238,59 +216,54 @@ void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance //instance indices are designed so greater always contains lesser if (A->base_type > B->base_type) { - SWAP(A,B); //lesser always first + SWAP(A, B); //lesser always first } + if (B->base_type == VS::INSTANCE_LIGHT && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) { + InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data); - if (B->base_type==VS::INSTANCE_LIGHT && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { - - InstanceLightData * light = static_cast<InstanceLightData*>(B->base_data); - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); - - List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element*>(udata); + List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata); geom->lighting.erase(E->get().L); light->geometries.erase(E); if (geom->can_cast_shadows) { - light->shadow_dirty=true; + light->shadow_dirty = true; } - geom->lighting_dirty=true; - + geom->lighting_dirty = true; - } else if (B->base_type==VS::INSTANCE_REFLECTION_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { + } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) { - InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(B->base_data); - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data); - List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element*>(udata); + List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata); geom->reflection_probes.erase(E->get().L); reflection_probe->geometries.erase(E); - geom->reflection_dirty=true; + geom->reflection_dirty = true; - } else if (B->base_type==VS::INSTANCE_GI_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { + } else if (B->base_type == VS::INSTANCE_GI_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) { - InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data); - List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element*>(udata); + List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata); geom->gi_probes.erase(E->get().L); gi_probe->geometries.erase(E); - geom->gi_probes_dirty=true; - - - } else if (B->base_type==VS::INSTANCE_GI_PROBE && A->base_type==VS::INSTANCE_LIGHT) { + geom->gi_probes_dirty = true; - InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); - InstanceLightData * light = static_cast<InstanceLightData*>(A->base_data); + } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) { + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(A->base_data); - Set<Instance*>::Element *E = reinterpret_cast<Set<Instance*>::Element*>(udata); + Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata); gi_probe->lights.erase(E); } @@ -349,124 +322,111 @@ void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance RID VisualServerScene::scenario_create() { - Scenario *scenario = memnew( Scenario ); - ERR_FAIL_COND_V(!scenario,RID()); - RID scenario_rid = scenario_owner.make_rid( scenario ); - scenario->self=scenario_rid; - - scenario->octree.set_pair_callback(_instance_pair,this); - scenario->octree.set_unpair_callback(_instance_unpair,this); - scenario->reflection_probe_shadow_atlas=VSG::scene_render->shadow_atlas_create(); - VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas,1024); //make enough shadows for close distance, don't bother with rest - VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,0,4); - VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,1,4); - VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,2,4); - VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,3,8); - scenario->reflection_atlas=VSG::scene_render->reflection_atlas_create(); + Scenario *scenario = memnew(Scenario); + ERR_FAIL_COND_V(!scenario, RID()); + RID scenario_rid = scenario_owner.make_rid(scenario); + scenario->self = scenario_rid; + + scenario->octree.set_pair_callback(_instance_pair, this); + scenario->octree.set_unpair_callback(_instance_unpair, this); + scenario->reflection_probe_shadow_atlas = VSG::scene_render->shadow_atlas_create(); + VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest + VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4); + VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4); + VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4); + VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8); + scenario->reflection_atlas = VSG::scene_render->reflection_atlas_create(); return scenario_rid; } -void VisualServerScene::scenario_set_debug(RID p_scenario,VS::ScenarioDebugMode p_debug_mode) { +void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); - scenario->debug=p_debug_mode; + scenario->debug = p_debug_mode; } void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); - scenario->environment=p_environment; - + scenario->environment = p_environment; } void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) { - Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); - scenario->fallback_environment=p_environment; - - + scenario->fallback_environment = p_environment; } -void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv) { +void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); - VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas,p_size); - VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas,p_subdiv); - - + VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_size); + VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas, p_subdiv); } - - /* INSTANCING API */ -void VisualServerScene::_instance_queue_update(Instance *p_instance,bool p_update_aabb,bool p_update_materials) { +void VisualServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials) { if (p_update_aabb) - p_instance->update_aabb=true; + p_instance->update_aabb = true; if (p_update_materials) - p_instance->update_materials=true; + p_instance->update_materials = true; if (p_instance->update_item.in_list()) return; _instance_update_list.add(&p_instance->update_item); - - } // from can be mesh, light, area and portal so far. -RID VisualServerScene::instance_create(){ +RID VisualServerScene::instance_create() { - Instance *instance = memnew( Instance ); - ERR_FAIL_COND_V(!instance,RID()); + Instance *instance = memnew(Instance); + ERR_FAIL_COND_V(!instance, RID()); RID instance_rid = instance_owner.make_rid(instance); - instance->self=instance_rid; - + instance->self = instance_rid; return instance_rid; - - } -void VisualServerScene::instance_set_base(RID p_instance, RID p_base){ +void VisualServerScene::instance_set_base(RID p_instance, RID p_base) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); Scenario *scenario = instance->scenario; - if (instance->base_type!=VS::INSTANCE_NONE) { + if (instance->base_type != VS::INSTANCE_NONE) { //free anything related to that base - VSG::storage->instance_remove_dependency(instance->base,instance); + VSG::storage->instance_remove_dependency(instance->base, instance); if (scenario && instance->octree_id) { scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away - instance->octree_id=0; + instance->octree_id = 0; } - switch(instance->base_type) { + switch (instance->base_type) { case VS::INSTANCE_LIGHT: { - InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data); if (instance->scenario && light->D) { - instance->scenario->directional_lights.erase( light->D ); - light->D=NULL; + instance->scenario->directional_lights.erase(light->D); + light->D = NULL; } VSG::scene_render->free(light->instance); } break; case VS::INSTANCE_REFLECTION_PROBE: { - InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(instance->base_data); + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data); VSG::scene_render->free(reflection_probe->instance); if (reflection_probe->update_list.in_list()) { reflection_probe_render_list.remove(&reflection_probe->update_list); @@ -474,9 +434,9 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){ } break; case VS::INSTANCE_GI_PROBE: { - InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data); - while(gi_probe->dynamic.updating_stage==GI_UPDATE_STAGE_LIGHTING) { + while (gi_probe->dynamic.updating_stage == GI_UPDATE_STAGE_LIGHTING) { //wait until bake is done if it's baking OS::get_singleton()->delay_usec(1); } @@ -490,19 +450,18 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){ VSG::scene_render->free(gi_probe->probe_instance); } break; - } if (instance->base_data) { - memdelete( instance->base_data ); - instance->base_data=NULL; + memdelete(instance->base_data); + instance->base_data = NULL; } instance->blend_values.clear(); - for(int i=0;i<instance->materials.size();i++) { + for (int i = 0; i < instance->materials.size(); i++) { if (instance->materials[i].is_valid()) { - VSG::storage->material_remove_instance_owner(instance->materials[i],instance); + VSG::storage->material_remove_instance_owner(instance->materials[i], instance); } } instance->materials.clear(); @@ -625,70 +584,65 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){ instance->gi_probe_sampler_info=NULL; } #endif - } - - instance->base_type=VS::INSTANCE_NONE; - instance->base=RID(); - + instance->base_type = VS::INSTANCE_NONE; + instance->base = RID(); if (p_base.is_valid()) { - instance->base_type=VSG::storage->get_base_type(p_base); - ERR_FAIL_COND(instance->base_type==VS::INSTANCE_NONE); + instance->base_type = VSG::storage->get_base_type(p_base); + ERR_FAIL_COND(instance->base_type == VS::INSTANCE_NONE); - switch(instance->base_type) { + switch (instance->base_type) { case VS::INSTANCE_LIGHT: { - InstanceLightData *light = memnew( InstanceLightData ); + InstanceLightData *light = memnew(InstanceLightData); - if (scenario && VSG::storage->light_get_type(p_base)==VS::LIGHT_DIRECTIONAL) { + if (scenario && VSG::storage->light_get_type(p_base) == VS::LIGHT_DIRECTIONAL) { light->D = scenario->directional_lights.push_back(instance); } light->instance = VSG::scene_render->light_instance_create(p_base); - instance->base_data=light; + instance->base_data = light; } break; case VS::INSTANCE_MESH: case VS::INSTANCE_MULTIMESH: case VS::INSTANCE_IMMEDIATE: { - InstanceGeometryData *geom = memnew( InstanceGeometryData ); - instance->base_data=geom; + InstanceGeometryData *geom = memnew(InstanceGeometryData); + instance->base_data = geom; } break; case VS::INSTANCE_REFLECTION_PROBE: { - InstanceReflectionProbeData *reflection_probe = memnew( InstanceReflectionProbeData ); - reflection_probe->owner=instance; - instance->base_data=reflection_probe; + InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData); + reflection_probe->owner = instance; + instance->base_data = reflection_probe; - reflection_probe->instance=VSG::scene_render->reflection_probe_instance_create(p_base); + reflection_probe->instance = VSG::scene_render->reflection_probe_instance_create(p_base); } break; case VS::INSTANCE_GI_PROBE: { - InstanceGIProbeData *gi_probe = memnew( InstanceGIProbeData ); - instance->base_data=gi_probe; - gi_probe->owner=instance; + InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData); + instance->base_data = gi_probe; + gi_probe->owner = instance; if (scenario && !gi_probe->update_element.in_list()) { gi_probe_update_list.add(&gi_probe->update_element); } - gi_probe->probe_instance=VSG::scene_render->gi_probe_instance_create(); + gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create(); } break; - } - VSG::storage->instance_add_dependency(p_base,instance); + VSG::storage->instance_add_dependency(p_base, instance); - instance->base=p_base; + instance->base = p_base; if (scenario) - _instance_queue_update(instance,true,true); - + _instance_queue_update(instance, true, true); #if 0 if (rasterizer->is_mesh(p_base)) { @@ -747,238 +701,219 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){ instance_dependency_map[ p_base ].insert( instance->self ); #endif - - } } -void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario){ +void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); if (instance->scenario) { - instance->scenario->instances.remove( &instance->scenario_item ); + instance->scenario->instances.remove(&instance->scenario_item); if (instance->octree_id) { instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away - instance->octree_id=0; + instance->octree_id = 0; } - - switch(instance->base_type) { + switch (instance->base_type) { case VS::INSTANCE_LIGHT: { - - InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data); if (light->D) { - instance->scenario->directional_lights.erase( light->D ); - light->D=NULL; + instance->scenario->directional_lights.erase(light->D); + light->D = NULL; } } break; case VS::INSTANCE_REFLECTION_PROBE: { - InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(instance->base_data); + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data); VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance); } break; case VS::INSTANCE_GI_PROBE: { - InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data); if (gi_probe->update_element.in_list()) { gi_probe_update_list.remove(&gi_probe->update_element); } } break; - } - instance->scenario=NULL; + instance->scenario = NULL; } - if (p_scenario.is_valid()) { - Scenario *scenario = scenario_owner.get( p_scenario ); + Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); - instance->scenario=scenario; - - scenario->instances.add( &instance->scenario_item ); + instance->scenario = scenario; + scenario->instances.add(&instance->scenario_item); - switch(instance->base_type) { + switch (instance->base_type) { case VS::INSTANCE_LIGHT: { + InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data); - InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data); - - if (VSG::storage->light_get_type(instance->base)==VS::LIGHT_DIRECTIONAL) { + if (VSG::storage->light_get_type(instance->base) == VS::LIGHT_DIRECTIONAL) { light->D = scenario->directional_lights.push_back(instance); } } break; case VS::INSTANCE_GI_PROBE: { - InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data); if (!gi_probe->update_element.in_list()) { gi_probe_update_list.add(&gi_probe->update_element); } } break; } - _instance_queue_update(instance,true,true); + _instance_queue_update(instance, true, true); } } -void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask){ - +void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); - instance->layer_mask=p_mask; + instance->layer_mask = p_mask; } -void VisualServerScene::instance_set_transform(RID p_instance, const Transform& p_transform){ +void VisualServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); - if (instance->transform==p_transform) + if (instance->transform == p_transform) return; //must be checked to avoid worst evil - instance->transform=p_transform; - _instance_queue_update(instance,true); + instance->transform = p_transform; + _instance_queue_update(instance, true); } -void VisualServerScene::instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID){ +void VisualServerScene::instance_attach_object_instance_ID(RID p_instance, ObjectID p_ID) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); - - instance->object_ID=p_ID; + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); + instance->object_ID = p_ID; } -void VisualServerScene::instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight){ +void VisualServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); if (instance->update_item.in_list()) { _update_dirty_instance(instance); } - ERR_FAIL_INDEX(p_shape,instance->blend_values.size()); - instance->blend_values[p_shape]=p_weight; + ERR_FAIL_INDEX(p_shape, instance->blend_values.size()); + instance->blend_values[p_shape] = p_weight; } -void VisualServerScene::instance_set_surface_material(RID p_instance,int p_surface, RID p_material){ +void VisualServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); if (instance->update_item.in_list()) { _update_dirty_instance(instance); } - ERR_FAIL_INDEX(p_surface,instance->materials.size()); + ERR_FAIL_INDEX(p_surface, instance->materials.size()); if (instance->materials[p_surface].is_valid()) { - VSG::storage->material_remove_instance_owner(instance->materials[p_surface],instance); + VSG::storage->material_remove_instance_owner(instance->materials[p_surface], instance); } - instance->materials[p_surface]=p_material; + instance->materials[p_surface] = p_material; instance->base_material_changed(); if (instance->materials[p_surface].is_valid()) { - VSG::storage->material_add_instance_owner(instance->materials[p_surface],instance); + VSG::storage->material_add_instance_owner(instance->materials[p_surface], instance); } - - } -void VisualServerScene::instance_set_visible(RID p_instance,bool p_visible) { +void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); - if (instance->visible==p_visible) + if (instance->visible == p_visible) return; - instance->visible=p_visible; - + instance->visible = p_visible; - switch(instance->base_type) { + switch (instance->base_type) { case VS::INSTANCE_LIGHT: { - if (VSG::storage->light_get_type(instance->base)!=VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) { - instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_LIGHT,p_visible?VS::INSTANCE_GEOMETRY_MASK:0); + if (VSG::storage->light_get_type(instance->base) != VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) { + instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHT, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0); } } break; case VS::INSTANCE_REFLECTION_PROBE: { if (instance->octree_id && instance->scenario) { - instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_REFLECTION_PROBE,p_visible?VS::INSTANCE_GEOMETRY_MASK:0); + instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_REFLECTION_PROBE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0); } } break; case VS::INSTANCE_GI_PROBE: { if (instance->octree_id && instance->scenario) { - instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_GI_PROBE,p_visible?(VS::INSTANCE_GEOMETRY_MASK|(1<<VS::INSTANCE_LIGHT)):0); + instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_GI_PROBE, p_visible ? (VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT)) : 0); } } break; - } - } -void VisualServerScene::instance_attach_skeleton(RID p_instance,RID p_skeleton){ +void VisualServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); - if (instance->skeleton==p_skeleton) + if (instance->skeleton == p_skeleton) return; if (instance->skeleton.is_valid()) { - VSG::storage->instance_remove_skeleton(p_skeleton,instance); + VSG::storage->instance_remove_skeleton(p_skeleton, instance); } - instance->skeleton=p_skeleton; + instance->skeleton = p_skeleton; if (instance->skeleton.is_valid()) { - VSG::storage->instance_add_skeleton(p_skeleton,instance); + VSG::storage->instance_add_skeleton(p_skeleton, instance); } - _instance_queue_update(instance,true); + _instance_queue_update(instance, true); } -void VisualServerScene::instance_set_exterior( RID p_instance, bool p_enabled ){ - +void VisualServerScene::instance_set_exterior(RID p_instance, bool p_enabled) { } -void VisualServerScene::instance_set_room( RID p_instance, RID p_room ){ - +void VisualServerScene::instance_set_room(RID p_instance, RID p_room) { } -void VisualServerScene::instance_set_extra_visibility_margin( RID p_instance, real_t p_margin ){ - +void VisualServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) { } -Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3& p_aabb, RID p_scenario) const { - +Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario) const { Vector<ObjectID> instances; - Scenario *scenario=scenario_owner.get(p_scenario); - ERR_FAIL_COND_V(!scenario,instances); + Scenario *scenario = scenario_owner.get(p_scenario); + ERR_FAIL_COND_V(!scenario, instances); - const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling + const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling - int culled=0; + int culled = 0; Instance *cull[1024]; - culled=scenario->octree.cull_AABB(p_aabb,cull,1024); + culled = scenario->octree.cull_AABB(p_aabb, cull, 1024); - for (int i=0;i<culled;i++) { + for (int i = 0; i < culled; i++) { - Instance *instance=cull[i]; + Instance *instance = cull[i]; ERR_CONTINUE(!instance); - if (instance->object_ID==0) + if (instance->object_ID == 0) continue; instances.push_back(instance->object_ID); @@ -986,79 +921,74 @@ Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3& p_aabb, RID return instances; } -Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario) const{ +Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const { Vector<ObjectID> instances; - Scenario *scenario=scenario_owner.get(p_scenario); - ERR_FAIL_COND_V(!scenario,instances); - const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling + Scenario *scenario = scenario_owner.get(p_scenario); + ERR_FAIL_COND_V(!scenario, instances); + const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling - int culled=0; + int culled = 0; Instance *cull[1024]; - culled=scenario->octree.cull_segment(p_from,p_to*10000,cull,1024); - + culled = scenario->octree.cull_segment(p_from, p_to * 10000, cull, 1024); - for (int i=0;i<culled;i++) { - Instance *instance=cull[i]; + for (int i = 0; i < culled; i++) { + Instance *instance = cull[i]; ERR_CONTINUE(!instance); - if (instance->object_ID==0) + if (instance->object_ID == 0) continue; instances.push_back(instance->object_ID); } return instances; - } -Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario) const{ +Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const { Vector<ObjectID> instances; - Scenario *scenario=scenario_owner.get(p_scenario); - ERR_FAIL_COND_V(!scenario,instances); - const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling + Scenario *scenario = scenario_owner.get(p_scenario); + ERR_FAIL_COND_V(!scenario, instances); + const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling - int culled=0; + int culled = 0; Instance *cull[1024]; + culled = scenario->octree.cull_convex(p_convex, cull, 1024); - culled=scenario->octree.cull_convex(p_convex,cull,1024); + for (int i = 0; i < culled; i++) { - for (int i=0;i<culled;i++) { - - Instance *instance=cull[i]; + Instance *instance = cull[i]; ERR_CONTINUE(!instance); - if (instance->object_ID==0) + if (instance->object_ID == 0) continue; instances.push_back(instance->object_ID); } return instances; - } -void VisualServerScene::instance_geometry_set_flag(RID p_instance,VS::InstanceFlags p_flags,bool p_enabled){ +void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); - switch(p_flags) { + switch (p_flags) { case VS::INSTANCE_FLAG_BILLBOARD: { - instance->billboard=p_enabled; + instance->billboard = p_enabled; } break; case VS::INSTANCE_FLAG_BILLBOARD_FIX_Y: { - instance->billboard_y=p_enabled; + instance->billboard_y = p_enabled; } break; case VS::INSTANCE_FLAG_CAST_SHADOW: { if (p_enabled == true) { instance->cast_shadows = VS::SHADOW_CASTING_SETTING_ON; - } - else { + } else { instance->cast_shadows = VS::SHADOW_CASTING_SETTING_OFF; } @@ -1067,69 +997,59 @@ void VisualServerScene::instance_geometry_set_flag(RID p_instance,VS::InstanceFl } break; case VS::INSTANCE_FLAG_DEPH_SCALE: { - instance->depth_scale=p_enabled; + instance->depth_scale = p_enabled; } break; case VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS: { - instance->visible_in_all_rooms=p_enabled; + instance->visible_in_all_rooms = p_enabled; } break; - } } void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) { - } -void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material){ +void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) { - Instance *instance = instance_owner.get( p_instance ); - ERR_FAIL_COND( !instance ); + Instance *instance = instance_owner.get(p_instance); + ERR_FAIL_COND(!instance); if (instance->material_override.is_valid()) { - VSG::storage->material_remove_instance_owner(instance->material_override,instance); + VSG::storage->material_remove_instance_owner(instance->material_override, instance); } - instance->material_override=p_material; + instance->material_override = p_material; instance->base_material_changed(); if (instance->material_override.is_valid()) { - VSG::storage->material_add_instance_owner(instance->material_override,instance); + VSG::storage->material_add_instance_owner(instance->material_override, instance); } - } - -void VisualServerScene::instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin){ - +void VisualServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) { } -void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance){ - +void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) { } - void VisualServerScene::_update_instance(Instance *p_instance) { p_instance->version++; if (p_instance->base_type == VS::INSTANCE_LIGHT) { - InstanceLightData *light = static_cast<InstanceLightData*>(p_instance->base_data); - - VSG::scene_render->light_instance_set_transform( light->instance, p_instance->transform ); - light->shadow_dirty=true; + InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data); + VSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform); + light->shadow_dirty = true; } if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) { - InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(p_instance->base_data); - - VSG::scene_render->reflection_probe_instance_set_transform( reflection_probe->instance, p_instance->transform ); - reflection_probe->reflection_dirty=true; + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data); + VSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform); + reflection_probe->reflection_dirty = true; } - if (p_instance->aabb.has_no_surface()) return; @@ -1140,18 +1060,17 @@ void VisualServerScene::_update_instance(Instance *p_instance) { } #endif - if ((1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) { + if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) { - InstanceGeometryData *geom = static_cast<InstanceGeometryData*>(p_instance->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data); //make sure lights are updated if it casts shadow if (geom->can_cast_shadows) { - for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) { - InstanceLightData *light = static_cast<InstanceLightData*>(E->get()->base_data); - light->shadow_dirty=true; + for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { + InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); + light->shadow_dirty = true; } } - } #if 0 else if (p_instance->base_type == INSTANCE_ROOM) { @@ -1166,7 +1085,6 @@ void VisualServerScene::_update_instance(Instance *p_instance) { p_instance->gi_probe_info->affine_inverse=(p_instance->data.transform*scale).affine_inverse(); } - #endif p_instance->mirror = p_instance->transform.basis.determinant() < 0.0; @@ -1202,37 +1120,34 @@ void VisualServerScene::_update_instance(Instance *p_instance) { } else { #endif - new_aabb = p_instance->transform.xform(p_instance->aabb); + new_aabb = p_instance->transform.xform(p_instance->aabb); #if 0 } #endif - - p_instance->transformed_aabb=new_aabb; + p_instance->transformed_aabb = new_aabb; if (!p_instance->scenario) { return; } + if (p_instance->octree_id == 0) { + uint32_t base_type = 1 << p_instance->base_type; + uint32_t pairable_mask = 0; + bool pairable = false; - if (p_instance->octree_id==0) { - - uint32_t base_type = 1<<p_instance->base_type; - uint32_t pairable_mask=0; - bool pairable=false; + if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) { - if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type==VS::INSTANCE_REFLECTION_PROBE) { - - pairable_mask=p_instance->visible?VS::INSTANCE_GEOMETRY_MASK:0; - pairable=true; + pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK : 0; + pairable = true; } if (p_instance->base_type == VS::INSTANCE_GI_PROBE) { //lights and geometries - pairable_mask=p_instance->visible?VS::INSTANCE_GEOMETRY_MASK|(1<<VS::INSTANCE_LIGHT):0; - pairable=true; + pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT) : 0; + pairable = true; } #if 0 @@ -1263,7 +1178,7 @@ void VisualServerScene::_update_instance(Instance *p_instance) { #endif // not inside octree - p_instance->octree_id = p_instance->scenario->octree.create(p_instance,new_aabb,0,pairable,base_type,pairable_mask); + p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask); } else { @@ -1272,7 +1187,7 @@ void VisualServerScene::_update_instance(Instance *p_instance) { return; */ - p_instance->scenario->octree.move(p_instance->octree_id,new_aabb); + p_instance->scenario->octree.move(p_instance->octree_id, new_aabb); } #if 0 if (p_instance->base_type==INSTANCE_PORTAL) { @@ -1291,23 +1206,22 @@ void VisualServerScene::_update_instance(Instance *p_instance) { _instance_validate_autorooms(E->get()); } #endif - } void VisualServerScene::_update_instance_aabb(Instance *p_instance) { Rect3 new_aabb; - ERR_FAIL_COND(p_instance->base_type!=VS::INSTANCE_NONE && !p_instance->base.is_valid()); + ERR_FAIL_COND(p_instance->base_type != VS::INSTANCE_NONE && !p_instance->base.is_valid()); - switch(p_instance->base_type) { + switch (p_instance->base_type) { case VisualServer::INSTANCE_NONE: { // do nothing } break; case VisualServer::INSTANCE_MESH: { - new_aabb = VSG::storage->mesh_get_aabb(p_instance->base,p_instance->skeleton); + new_aabb = VSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton); } break; @@ -1320,7 +1234,6 @@ void VisualServerScene::_update_instance_aabb(Instance *p_instance) { new_aabb = VSG::storage->immediate_get_aabb(p_instance->base); - } break; #if 0 @@ -1396,164 +1309,147 @@ void VisualServerScene::_update_instance_aabb(Instance *p_instance) { if (p_instance->extra_margin) new_aabb.grow_by(p_instance->extra_margin); - p_instance->aabb=new_aabb; - + p_instance->aabb = new_aabb; } +void VisualServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario) { + InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data); - - -void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_shadow_atlas,Scenario* p_scenario) { - - - InstanceLightData * light = static_cast<InstanceLightData*>(p_instance->base_data); - - switch(VSG::storage->light_get_type(p_instance->base)) { + switch (VSG::storage->light_get_type(p_instance->base)) { case VS::LIGHT_DIRECTIONAL: { - float max_distance =p_cam_projection.get_z_far(); - float shadow_max = VSG::storage->light_get_param(p_instance->base,VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE); - if (shadow_max>0) { - max_distance=MIN(shadow_max,max_distance); + float max_distance = p_cam_projection.get_z_far(); + float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE); + if (shadow_max > 0) { + max_distance = MIN(shadow_max, max_distance); } - max_distance=MAX(max_distance,p_cam_projection.get_z_near()+0.001); + max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001); - float range = max_distance-p_cam_projection.get_z_near(); + float range = max_distance - p_cam_projection.get_z_near(); - int splits=0; - switch(VSG::storage->light_directional_get_shadow_mode(p_instance->base)) { - case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits=1; break; - case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits=2; break; - case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits=4; break; + int splits = 0; + switch (VSG::storage->light_directional_get_shadow_mode(p_instance->base)) { + case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits = 1; break; + case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits = 2; break; + case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits = 4; break; } float distances[5]; - distances[0]=p_cam_projection.get_z_near(); - for(int i=0;i<splits;i++) { - distances[i+1]=p_cam_projection.get_z_near()+VSG::storage->light_get_param(p_instance->base,VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET+i))*range; + distances[0] = p_cam_projection.get_z_near(); + for (int i = 0; i < splits; i++) { + distances[i + 1] = p_cam_projection.get_z_near() + VSG::storage->light_get_param(p_instance->base, VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range; }; - distances[splits]=max_distance; + distances[splits] = max_distance; - float texture_size=VSG::scene_render->get_directional_light_shadow_size(light->instance); + float texture_size = VSG::scene_render->get_directional_light_shadow_size(light->instance); bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base); - for (int i=0;i<splits;i++) { + for (int i = 0; i < splits; i++) { // setup a camera matrix for that range! CameraMatrix camera_matrix; float aspect = p_cam_projection.get_aspect(); - if (p_cam_orthogonal) { - float w,h; - p_cam_projection.get_viewport_size(w,h); - camera_matrix.set_orthogonal(w,aspect,distances[(i==0 || !overlap )?i:i-1],distances[i+1],false); + float w, h; + p_cam_projection.get_viewport_size(w, h); + camera_matrix.set_orthogonal(w, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false); } else { float fov = p_cam_projection.get_fov(); - camera_matrix.set_perspective(fov,aspect,distances[(i==0 || !overlap )?i:i-1],distances[i+1],false); + camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false); } //obtain the frustum endpoints Vector3 endpoints[8]; // frustum plane endpoints - bool res = camera_matrix.get_endpoints(p_cam_transform,endpoints); + bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints); ERR_CONTINUE(!res); // obtain the light frustm ranges (given endpoints) - Vector3 x_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_X ).normalized(); - Vector3 y_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_Y ).normalized(); - Vector3 z_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_Z ).normalized(); + Vector3 x_vec = p_instance->transform.basis.get_axis(Vector3::AXIS_X).normalized(); + Vector3 y_vec = p_instance->transform.basis.get_axis(Vector3::AXIS_Y).normalized(); + Vector3 z_vec = p_instance->transform.basis.get_axis(Vector3::AXIS_Z).normalized(); //z_vec points agsint the camera, like in default opengl - float x_min,x_max; - float y_min,y_max; - float z_min,z_max; - - float x_min_cam,x_max_cam; - float y_min_cam,y_max_cam; - float z_min_cam,z_max_cam; + float x_min, x_max; + float y_min, y_max; + float z_min, z_max; + float x_min_cam, x_max_cam; + float y_min_cam, y_max_cam; + float z_min_cam, z_max_cam; //used for culling - for(int j=0;j<8;j++) { - - float d_x=x_vec.dot(endpoints[j]); - float d_y=y_vec.dot(endpoints[j]); - float d_z=z_vec.dot(endpoints[j]); - - if (j==0 || d_x<x_min) - x_min=d_x; - if (j==0 || d_x>x_max) - x_max=d_x; - - if (j==0 || d_y<y_min) - y_min=d_y; - if (j==0 || d_y>y_max) - y_max=d_y; - - if (j==0 || d_z<z_min) - z_min=d_z; - if (j==0 || d_z>z_max) - z_max=d_z; - - + for (int j = 0; j < 8; j++) { + + float d_x = x_vec.dot(endpoints[j]); + float d_y = y_vec.dot(endpoints[j]); + float d_z = z_vec.dot(endpoints[j]); + + if (j == 0 || d_x < x_min) + x_min = d_x; + if (j == 0 || d_x > x_max) + x_max = d_x; + + if (j == 0 || d_y < y_min) + y_min = d_y; + if (j == 0 || d_y > y_max) + y_max = d_y; + + if (j == 0 || d_z < z_min) + z_min = d_z; + if (j == 0 || d_z > z_max) + z_max = d_z; } - - - - { //camera viewport stuff //this trick here is what stabilizes the shadow (make potential jaggies to not move) //at the cost of some wasted resolution. Still the quality increase is very well worth it - Vector3 center; - for(int j=0;j<8;j++) { + for (int j = 0; j < 8; j++) { - center+=endpoints[j]; + center += endpoints[j]; } - center/=8.0; + center /= 8.0; //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5; - float radius=0; + float radius = 0; - for(int j=0;j<8;j++) { + for (int j = 0; j < 8; j++) { float d = center.distance_to(endpoints[j]); - if (d>radius) - radius=d; + if (d > radius) + radius = d; } + radius *= texture_size / (texture_size - 2.0); //add a texel by each side, so stepified texture will always fit - radius *= texture_size/(texture_size-2.0); //add a texel by each side, so stepified texture will always fit - - x_max_cam=x_vec.dot(center)+radius; - x_min_cam=x_vec.dot(center)-radius; - y_max_cam=y_vec.dot(center)+radius; - y_min_cam=y_vec.dot(center)-radius; - z_max_cam=z_vec.dot(center)+radius; - z_min_cam=z_vec.dot(center)-radius; - - float unit = radius*2.0/texture_size; + x_max_cam = x_vec.dot(center) + radius; + x_min_cam = x_vec.dot(center) - radius; + y_max_cam = y_vec.dot(center) + radius; + y_min_cam = y_vec.dot(center) - radius; + z_max_cam = z_vec.dot(center) + radius; + z_min_cam = z_vec.dot(center) - radius; - x_max_cam=Math::stepify(x_max_cam,unit); - x_min_cam=Math::stepify(x_min_cam,unit); - y_max_cam=Math::stepify(y_max_cam,unit); - y_min_cam=Math::stepify(y_min_cam,unit); + float unit = radius * 2.0 / texture_size; + x_max_cam = Math::stepify(x_max_cam, unit); + x_min_cam = Math::stepify(x_min_cam, unit); + y_max_cam = Math::stepify(y_max_cam, unit); + y_min_cam = Math::stepify(y_min_cam, unit); } //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree @@ -1562,57 +1458,50 @@ void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const light_frustum_planes.resize(6); //right/left - light_frustum_planes[0]=Plane( x_vec, x_max ); - light_frustum_planes[1]=Plane( -x_vec, -x_min ); + light_frustum_planes[0] = Plane(x_vec, x_max); + light_frustum_planes[1] = Plane(-x_vec, -x_min); //top/bottom - light_frustum_planes[2]=Plane( y_vec, y_max ); - light_frustum_planes[3]=Plane( -y_vec, -y_min ); + light_frustum_planes[2] = Plane(y_vec, y_max); + light_frustum_planes[3] = Plane(-y_vec, -y_min); //near/far - light_frustum_planes[4]=Plane( z_vec, z_max+1e6 ); - light_frustum_planes[5]=Plane( -z_vec, -z_min ); // z_min is ok, since casters further than far-light plane are not needed + light_frustum_planes[4] = Plane(z_vec, z_max + 1e6); + light_frustum_planes[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed - int cull_count = p_scenario->octree.cull_convex(light_frustum_planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); + int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK); // a pre pass will need to be needed to determine the actual z-near to be used + for (int j = 0; j < cull_count; j++) { - for (int j=0;j<cull_count;j++) { - - float min,max; + float min, max; Instance *instance = instance_shadow_cull_result[j]; - if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { + if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) { cull_count--; - SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); + SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]); j--; continue; - } - - instance->transformed_aabb.project_range_in_plane(Plane(z_vec,0),min,max); - if (max>z_max) - z_max=max; + instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max); + if (max > z_max) + z_max = max; } { CameraMatrix ortho_camera; - real_t half_x = (x_max_cam-x_min_cam) * 0.5; - real_t half_y = (y_max_cam-y_min_cam) * 0.5; - + real_t half_x = (x_max_cam - x_min_cam) * 0.5; + real_t half_y = (y_max_cam - y_min_cam) * 0.5; - ortho_camera.set_orthogonal( -half_x, half_x,-half_y,half_y, 0, (z_max-z_min_cam) ); + ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam)); Transform ortho_transform; - ortho_transform.basis=p_instance->transform.basis; - ortho_transform.origin=x_vec*(x_min_cam+half_x)+y_vec*(y_min_cam+half_y)+z_vec*z_max; + ortho_transform.basis = p_instance->transform.basis; + ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max; - VSG::scene_render->light_instance_set_shadow_transform(light->instance,ortho_camera,ortho_transform,0,distances[i+1],i); + VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i); } - - - VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); - + VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count); } } break; @@ -1620,205 +1509,185 @@ void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base); - switch(shadow_mode) { + switch (shadow_mode) { case VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID: { - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { //using this one ensures that raster deferred will have it - float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE); + float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE); - float z =i==0?-1:1; + float z = i == 0 ? -1 : 1; Vector<Plane> planes; planes.resize(5); - planes[0]=p_instance->transform.xform(Plane(Vector3(0,0,z),radius)); - planes[1]=p_instance->transform.xform(Plane(Vector3(1,0,z).normalized(),radius)); - planes[2]=p_instance->transform.xform(Plane(Vector3(-1,0,z).normalized(),radius)); - planes[3]=p_instance->transform.xform(Plane(Vector3(0,1,z).normalized(),radius)); - planes[4]=p_instance->transform.xform(Plane(Vector3(0,-1,z).normalized(),radius)); - + planes[0] = p_instance->transform.xform(Plane(Vector3(0, 0, z), radius)); + planes[1] = p_instance->transform.xform(Plane(Vector3(1, 0, z).normalized(), radius)); + planes[2] = p_instance->transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius)); + planes[3] = p_instance->transform.xform(Plane(Vector3(0, 1, z).normalized(), radius)); + planes[4] = p_instance->transform.xform(Plane(Vector3(0, -1, z).normalized(), radius)); - int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); + int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK); - for (int j=0;j<cull_count;j++) { + for (int j = 0; j < cull_count; j++) { Instance *instance = instance_shadow_cull_result[j]; - if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { + if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) { cull_count--; - SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); + SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]); j--; - } } - VSG::scene_render->light_instance_set_shadow_transform(light->instance,CameraMatrix(),p_instance->transform,radius,0,i); - VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); + VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, i); + VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count); } } break; case VS::LIGHT_OMNI_SHADOW_CUBE: { - float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE); + float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE); CameraMatrix cm; - cm.set_perspective(90,1,0.01,radius); + cm.set_perspective(90, 1, 0.01, radius); - for(int i=0;i<6;i++) { + for (int i = 0; i < 6; i++) { //using this one ensures that raster deferred will have it - - - static const Vector3 view_normals[6]={ + static const Vector3 view_normals[6] = { Vector3(-1, 0, 0), Vector3(+1, 0, 0), - Vector3( 0,-1, 0), - Vector3( 0,+1, 0), - Vector3( 0, 0,-1), - Vector3( 0, 0,+1) + Vector3(0, -1, 0), + Vector3(0, +1, 0), + Vector3(0, 0, -1), + Vector3(0, 0, +1) }; - static const Vector3 view_up[6]={ - Vector3( 0,-1, 0), - Vector3( 0,-1, 0), - Vector3( 0, 0,-1), - Vector3( 0, 0,+1), - Vector3( 0,-1, 0), - Vector3( 0,-1, 0) + static const Vector3 view_up[6] = { + Vector3(0, -1, 0), + Vector3(0, -1, 0), + Vector3(0, 0, -1), + Vector3(0, 0, +1), + Vector3(0, -1, 0), + Vector3(0, -1, 0) }; - Transform xform = p_instance->transform * Transform().looking_at(view_normals[i],view_up[i]); - + Transform xform = p_instance->transform * Transform().looking_at(view_normals[i], view_up[i]); Vector<Plane> planes = cm.get_projection_planes(xform); - int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); + int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK); - for (int j=0;j<cull_count;j++) { + for (int j = 0; j < cull_count; j++) { Instance *instance = instance_shadow_cull_result[j]; - if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { + if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) { cull_count--; - SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); + SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]); j--; - } } - - VSG::scene_render->light_instance_set_shadow_transform(light->instance,cm,xform,radius,0,i); - VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); + VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i); + VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count); } //restore the regular DP matrix - VSG::scene_render->light_instance_set_shadow_transform(light->instance,CameraMatrix(),p_instance->transform,radius,0,0); + VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, 0); } break; } - } break; case VS::LIGHT_SPOT: { - - float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE); - float angle = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE); + float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE); + float angle = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE); CameraMatrix cm; - cm.set_perspective( angle*2.0, 1.0, 0.01, radius ); - + cm.set_perspective(angle * 2.0, 1.0, 0.01, radius); Vector<Plane> planes = cm.get_projection_planes(p_instance->transform); - int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); + int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK); - for (int j=0;j<cull_count;j++) { + for (int j = 0; j < cull_count; j++) { Instance *instance = instance_shadow_cull_result[j]; - if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { + if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) { cull_count--; - SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); + SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]); j--; - } } - - VSG::scene_render->light_instance_set_shadow_transform(light->instance,cm,p_instance->transform,radius,0,0); - VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,0,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); + VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, p_instance->transform, radius, 0, 0); + VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count); } break; } - } - -void VisualServerScene::render_camera(RID p_camera, RID p_scenario,Size2 p_viewport_size,RID p_shadow_atlas) { +void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) { Camera *camera = camera_owner.getornull(p_camera); ERR_FAIL_COND(!camera); /* STEP 1 - SETUP CAMERA */ CameraMatrix camera_matrix; - bool ortho=false; + bool ortho = false; - - switch(camera->type) { + switch (camera->type) { case Camera::ORTHOGONAL: { camera_matrix.set_orthogonal( - camera->size, - p_viewport_size.width / (float)p_viewport_size.height, - camera->znear, - camera->zfar, - camera->vaspect - - ); - ortho=true; + camera->size, + p_viewport_size.width / (float)p_viewport_size.height, + camera->znear, + camera->zfar, + camera->vaspect + + ); + ortho = true; } break; case Camera::PERSPECTIVE: { camera_matrix.set_perspective( - camera->fov, - p_viewport_size.width / (float)p_viewport_size.height, - camera->znear, - camera->zfar, - camera->vaspect + camera->fov, + p_viewport_size.width / (float)p_viewport_size.height, + camera->znear, + camera->zfar, + camera->vaspect - ); - ortho=false; + ); + ortho = false; } break; } - _render_scene(camera->transform,camera_matrix,ortho,camera->env,camera->visible_layers,p_scenario,p_shadow_atlas,RID(),-1); - + _render_scene(camera->transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1); } - -void VisualServerScene::_render_scene(const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_force_environment,uint32_t p_visible_layers, RID p_scenario,RID p_shadow_atlas,RID p_reflection_probe,int p_reflection_probe_pass) { - - +void VisualServerScene::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) { Scenario *scenario = scenario_owner.getornull(p_scenario); render_pass++; - uint32_t camera_layer_mask=p_visible_layers; + uint32_t camera_layer_mask = p_visible_layers; VSG::scene_render->set_scene_pass(render_pass); - //rasterizer->set_camera(camera->transform, camera_matrix,ortho); Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform); - Plane near_plane(p_cam_transform.origin,-p_cam_transform.basis.get_axis(2).normalized()); + Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized()); float z_far = p_cam_projection.get_z_far(); /* STEP 2 - CULL */ - int cull_count = scenario->octree.cull_convex(planes,instance_cull_result,MAX_INSTANCE_CULL); - light_cull_count=0; + int cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL); + light_cull_count = 0; - reflection_probe_cull_count=0; + reflection_probe_cull_count = 0; - //light_samplers_culled=0; +//light_samplers_culled=0; /* print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0)); print_line("OTO: "+itos(p_scenario->octree.get_octant_count())); @@ -1826,10 +1695,9 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came print_line("OTP: "+itos(p_scenario->octree.get_pair_count())); */ - /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */ +/* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */ - - // compute portals +// compute portals #if 0 exterior_visited=false; exterior_portal_cull_count=0; @@ -1913,43 +1781,39 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came #endif /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */ - for(int i=0;i<cull_count;i++) { + for (int i = 0; i < cull_count; i++) { Instance *ins = instance_cull_result[i]; - bool keep=false; + bool keep = false; - if ((camera_layer_mask&ins->layer_mask)==0) { + if ((camera_layer_mask & ins->layer_mask) == 0) { //failure - } else if (ins->base_type==VS::INSTANCE_LIGHT && ins->visible) { - + } else if (ins->base_type == VS::INSTANCE_LIGHT && ins->visible) { - if (ins->visible && light_cull_count<MAX_LIGHTS_CULLED) { + if (ins->visible && light_cull_count < MAX_LIGHTS_CULLED) { - InstanceLightData * light = static_cast<InstanceLightData*>(ins->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data); if (!light->geometries.empty()) { //do not add this light if no geometry is affected by it.. - light_cull_result[light_cull_count]=ins; - light_instance_cull_result[light_cull_count]=light->instance; + light_cull_result[light_cull_count] = ins; + light_instance_cull_result[light_cull_count] = light->instance; if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) { VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later } light_cull_count++; } - - } - } else if (ins->base_type==VS::INSTANCE_REFLECTION_PROBE && ins->visible) { + } else if (ins->base_type == VS::INSTANCE_REFLECTION_PROBE && ins->visible) { + if (ins->visible && reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) { - if (ins->visible && reflection_probe_cull_count<MAX_REFLECTION_PROBES_CULLED) { + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data); - InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(ins->base_data); - - if (p_reflection_probe!=reflection_probe->instance) { + if (p_reflection_probe != reflection_probe->instance) { //avoid entering The Matrix if (!reflection_probe->geometries.empty()) { @@ -1957,32 +1821,31 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) { if (!reflection_probe->update_list.in_list()) { - reflection_probe->render_step=0; + reflection_probe->render_step = 0; reflection_probe_render_list.add(&reflection_probe->update_list); } - reflection_probe->reflection_dirty=false; + reflection_probe->reflection_dirty = false; } if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) { - reflection_probe_instance_cull_result[reflection_probe_cull_count]=reflection_probe->instance; + reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance; reflection_probe_cull_count++; } - } } } - } else if (ins->base_type==VS::INSTANCE_GI_PROBE && ins->visible) { + } else if (ins->base_type == VS::INSTANCE_GI_PROBE && ins->visible) { - InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(ins->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data); if (!gi_probe->update_element.in_list()) { gi_probe_update_list.add(&gi_probe->update_element); } - } else if ((1<<ins->base_type)&VS::INSTANCE_GEOMETRY_MASK && ins->visible && ins->cast_shadows!=VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) { + } else if ((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) { - keep=true; + keep = true; #if 0 bool discarded=false; @@ -2049,230 +1912,207 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came } #endif - - InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(ins->base_data); - + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data); if (geom->lighting_dirty) { - int l=0; + int l = 0; //only called when lights AABB enter/exit this geometry ins->light_instances.resize(geom->lighting.size()); - for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) { + for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { - InstanceLightData * light = static_cast<InstanceLightData*>(E->get()->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); - ins->light_instances[l++]=light->instance; + ins->light_instances[l++] = light->instance; } - geom->lighting_dirty=false; + geom->lighting_dirty = false; } if (geom->reflection_dirty) { - int l=0; + int l = 0; //only called when reflection probe AABB enter/exit this geometry ins->reflection_probe_instances.resize(geom->reflection_probes.size()); - for (List<Instance*>::Element *E=geom->reflection_probes.front();E;E=E->next()) { + for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) { - InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(E->get()->base_data); + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data); - ins->reflection_probe_instances[l++]=reflection_probe->instance; + ins->reflection_probe_instances[l++] = reflection_probe->instance; } - geom->reflection_dirty=false; + geom->reflection_dirty = false; } if (geom->gi_probes_dirty) { - int l=0; + int l = 0; //only called when reflection probe AABB enter/exit this geometry ins->gi_probe_instances.resize(geom->gi_probes.size()); - for (List<Instance*>::Element *E=geom->gi_probes.front();E;E=E->next()) { + for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) { - InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(E->get()->base_data); + InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data); - ins->gi_probe_instances[l++]=gi_probe->probe_instance; + ins->gi_probe_instances[l++] = gi_probe->probe_instance; } - geom->gi_probes_dirty=false; + geom->gi_probes_dirty = false; } ins->depth = near_plane.distance_to(ins->transform.origin); - ins->depth_layer=CLAMP(int(ins->depth*8/z_far),0,7); - + ins->depth_layer = CLAMP(int(ins->depth * 8 / z_far), 0, 7); } if (!keep) { // remove, no reason to keep cull_count--; - SWAP( instance_cull_result[i], instance_cull_result[ cull_count ] ); + SWAP(instance_cull_result[i], instance_cull_result[cull_count]); i--; - ins->last_render_pass=0; // make invalid + ins->last_render_pass = 0; // make invalid } else { - ins->last_render_pass=render_pass; + ins->last_render_pass = render_pass; } } /* STEP 5 - PROCESS LIGHTS */ - RID *directional_light_ptr=&light_instance_cull_result[light_cull_count]; - int directional_light_count=0; + RID *directional_light_ptr = &light_instance_cull_result[light_cull_count]; + int directional_light_count = 0; // directional lights { - Instance** lights_with_shadow = (Instance**)alloca(sizeof(Instance*)*scenario->directional_lights.size()); - int directional_shadow_count=0; + Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size()); + int directional_shadow_count = 0; - for (List<Instance*>::Element *E=scenario->directional_lights.front();E;E=E->next()) { + for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) { - if (light_cull_count+directional_light_count>=MAX_LIGHTS_CULLED) { + if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) { break; } if (!E->get()->visible) continue; - InstanceLightData * light = static_cast<InstanceLightData*>(E->get()->base_data); - + InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); //check shadow.. - if (light && p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) { - lights_with_shadow[directional_shadow_count++]=E->get(); - + lights_with_shadow[directional_shadow_count++] = E->get(); } //add to list - directional_light_ptr[directional_light_count++]=light->instance; + directional_light_ptr[directional_light_count++] = light->instance; } VSG::scene_render->set_directional_shadow_count(directional_shadow_count); - for(int i=0;i<directional_shadow_count;i++) { - - _light_instance_update_shadow(lights_with_shadow[i],p_cam_transform,p_cam_projection,p_cam_orthogonal,p_shadow_atlas,scenario); + for (int i = 0; i < directional_shadow_count; i++) { + _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario); } } - { //setup shadow maps //SortArray<Instance*,_InstanceLightsort> sorter; //sorter.sort(light_cull_result,light_cull_count); - for (int i=0;i<light_cull_count;i++) { + for (int i = 0; i < light_cull_count; i++) { Instance *ins = light_cull_result[i]; if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base)) continue; - InstanceLightData * light = static_cast<InstanceLightData*>(ins->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data); float coverage; - { //compute coverage - + { //compute coverage Transform cam_xf = p_cam_transform; float zn = p_cam_projection.get_z_near(); - Plane p (cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2) ); //camera near plane + Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane - float vp_w,vp_h; //near plane size in screen coordinates - p_cam_projection.get_viewport_size(vp_w,vp_h); + float vp_w, vp_h; //near plane size in screen coordinates + p_cam_projection.get_viewport_size(vp_w, vp_h); - - switch(VSG::storage->light_get_type(ins->base)) { + switch (VSG::storage->light_get_type(ins->base)) { case VS::LIGHT_OMNI: { - float radius = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_RANGE); + float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE); //get two points parallel to near plane - Vector3 points[2]={ + Vector3 points[2] = { ins->transform.origin, - ins->transform.origin+cam_xf.basis.get_axis(0)*radius + ins->transform.origin + cam_xf.basis.get_axis(0) * radius }; if (!p_cam_orthogonal) { //if using perspetive, map them to near plane - for(int j=0;j<2;j++) { - if (p.distance_to(points[j]) < 0 ) { - points[j].z=-zn; //small hack to keep size constant when hitting the screen - + for (int j = 0; j < 2; j++) { + if (p.distance_to(points[j]) < 0) { + points[j].z = -zn; //small hack to keep size constant when hitting the screen } - p.intersects_segment(cam_xf.origin,points[j],&points[j]); //map to plane + p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane } - - } - float screen_diameter = points[0].distance_to(points[1])*2; - coverage = screen_diameter / (vp_w+vp_h); + float screen_diameter = points[0].distance_to(points[1]) * 2; + coverage = screen_diameter / (vp_w + vp_h); } break; case VS::LIGHT_SPOT: { - float radius = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_RANGE); - float angle = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_SPOT_ANGLE); - - - float w = radius*Math::sin(Math::deg2rad(angle)); - float d = radius*Math::cos(Math::deg2rad(angle)); + float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE); + float angle = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_SPOT_ANGLE); + float w = radius * Math::sin(Math::deg2rad(angle)); + float d = radius * Math::cos(Math::deg2rad(angle)); - Vector3 base = ins->transform.origin-ins->transform.basis.get_axis(2).normalized()*d; + Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d; - Vector3 points[2]={ + Vector3 points[2] = { base, - base+cam_xf.basis.get_axis(0)*w + base + cam_xf.basis.get_axis(0) * w }; if (!p_cam_orthogonal) { //if using perspetive, map them to near plane - for(int j=0;j<2;j++) { - if (p.distance_to(points[j]) < 0 ) { - points[j].z=-zn; //small hack to keep size constant when hitting the screen - + for (int j = 0; j < 2; j++) { + if (p.distance_to(points[j]) < 0) { + points[j].z = -zn; //small hack to keep size constant when hitting the screen } - p.intersects_segment(cam_xf.origin,points[j],&points[j]); //map to plane + p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane } - - } - float screen_diameter = points[0].distance_to(points[1])*2; - coverage = screen_diameter / (vp_w+vp_h); - + float screen_diameter = points[0].distance_to(points[1]) * 2; + coverage = screen_diameter / (vp_w + vp_h); } break; default: { ERR_PRINT("Invalid Light Type"); } } - } - if (light->shadow_dirty) { light->last_version++; - light->shadow_dirty=false; + light->shadow_dirty = false; } - - bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas,light->instance,coverage,light->last_version); + bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version); if (redraw) { //must redraw! - _light_instance_update_shadow(ins,p_cam_transform,p_cam_projection,p_cam_orthogonal,p_shadow_atlas,scenario); + _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario); } - } } @@ -2280,11 +2120,11 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came RID environment; if (p_force_environment.is_valid()) //camera has more environment priority - environment=p_force_environment; + environment = p_force_environment; else if (scenario->environment.is_valid()) - environment=scenario->environment; + environment = scenario->environment; else - environment=scenario->fallback_environment; + environment = scenario->fallback_environment; #if 0 /* STEP 6 - SAMPLE BAKED LIGHT */ @@ -2301,62 +2141,57 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came #endif /* STEP 7 - PROCESS GEOMETRY AND DRAW SCENE*/ - VSG::scene_render->render_scene(p_cam_transform, p_cam_projection,p_cam_orthogonal,(RasterizerScene::InstanceBase**)instance_cull_result,cull_count,light_instance_cull_result,light_cull_count+directional_light_count,reflection_probe_instance_cull_result,reflection_probe_cull_count,environment,p_shadow_atlas,scenario->reflection_atlas,p_reflection_probe,p_reflection_probe_pass); - - + VSG::scene_render->render_scene(p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, environment, p_shadow_atlas, scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass); } -bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p_step) { +bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) { - InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(p_instance->base_data); + InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data); Scenario *scenario = p_instance->scenario; - ERR_FAIL_COND_V(!scenario,true); + ERR_FAIL_COND_V(!scenario, true); - if (p_step==0) { + if (p_step == 0) { - if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance,scenario->reflection_atlas)) { + if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) { return true; //sorry, all full :( } } - if (p_step>=0 && p_step<6) { + if (p_step >= 0 && p_step < 6) { - static const Vector3 view_normals[6]={ + static const Vector3 view_normals[6] = { Vector3(-1, 0, 0), Vector3(+1, 0, 0), - Vector3( 0,-1, 0), - Vector3( 0,+1, 0), - Vector3( 0, 0,-1), - Vector3( 0, 0,+1) + Vector3(0, -1, 0), + Vector3(0, +1, 0), + Vector3(0, 0, -1), + Vector3(0, 0, +1) }; Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base); Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base); float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base); + Vector3 edge = view_normals[p_step] * extents; + float distance = ABS(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit - Vector3 edge = view_normals[p_step]*extents; - float distance = ABS(view_normals[p_step].dot(edge)-view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit - - max_distance = MAX(max_distance,distance); - + max_distance = MAX(max_distance, distance); //render cubemap side CameraMatrix cm; - cm.set_perspective(90,1,0.01,max_distance); - - - static const Vector3 view_up[6]={ - Vector3( 0,-1, 0), - Vector3( 0,-1, 0), - Vector3( 0, 0,-1), - Vector3( 0, 0,+1), - Vector3( 0,-1, 0), - Vector3( 0,-1, 0) + cm.set_perspective(90, 1, 0.01, max_distance); + + static const Vector3 view_up[6] = { + Vector3(0, -1, 0), + Vector3(0, -1, 0), + Vector3(0, 0, -1), + Vector3(0, 0, +1), + Vector3(0, -1, 0), + Vector3(0, -1, 0) }; Transform local_view; - local_view.set_look_at(origin_offset,origin_offset+view_normals[p_step],view_up[p_step]); + local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]); Transform xform = p_instance->transform * local_view; @@ -2364,10 +2199,10 @@ bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) { - shadow_atlas=scenario->reflection_probe_shadow_atlas; + shadow_atlas = scenario->reflection_probe_shadow_atlas; } - _render_scene(xform,cm,false,RID(),VSG::storage->reflection_probe_get_cull_mask(p_instance->base),p_instance->scenario->self,shadow_atlas,reflection_probe->instance,p_step); + _render_scene(xform, cm, false, RID(), VSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step); } else { //do roughness postprocess step until it belives it's done @@ -2377,84 +2212,81 @@ bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p return false; } -void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell* p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) { +void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) { - if (p_level==p_header->cell_subdiv-1) { + if (p_level == p_header->cell_subdiv - 1) { Vector3 emission; - emission.x=(p_cell[p_idx].emission>>24)/255.0; - emission.y=((p_cell[p_idx].emission>>16)&0xFF)/255.0; - emission.z=((p_cell[p_idx].emission>>8)&0xFF)/255.0; - float l = (p_cell[p_idx].emission&0xFF)/255.0; - l*=8.0; + emission.x = (p_cell[p_idx].emission >> 24) / 255.0; + emission.y = ((p_cell[p_idx].emission >> 16) & 0xFF) / 255.0; + emission.z = ((p_cell[p_idx].emission >> 8) & 0xFF) / 255.0; + float l = (p_cell[p_idx].emission & 0xFF) / 255.0; + l *= 8.0; - emission*=l; + emission *= l; - p_local_data[p_idx].energy[0]=uint16_t(emission.x*1024); //go from 0 to 1024 for light - p_local_data[p_idx].energy[1]=uint16_t(emission.y*1024); //go from 0 to 1024 for light - p_local_data[p_idx].energy[2]=uint16_t(emission.z*1024); //go from 0 to 1024 for light + p_local_data[p_idx].energy[0] = uint16_t(emission.x * 1024); //go from 0 to 1024 for light + p_local_data[p_idx].energy[1] = uint16_t(emission.y * 1024); //go from 0 to 1024 for light + p_local_data[p_idx].energy[2] = uint16_t(emission.z * 1024); //go from 0 to 1024 for light } else { - p_local_data[p_idx].energy[0]=0; - p_local_data[p_idx].energy[1]=0; - p_local_data[p_idx].energy[2]=0; + p_local_data[p_idx].energy[0] = 0; + p_local_data[p_idx].energy[1] = 0; + p_local_data[p_idx].energy[2] = 0; - int half=(1<<(p_header->cell_subdiv-1))>>(p_level+1); + int half = (1 << (p_header->cell_subdiv - 1)) >> (p_level + 1); - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { uint32_t child = p_cell[p_idx].children[i]; - if (child==0xFFFFFFFF) + if (child == 0xFFFFFFFF) continue; int x = p_x; int y = p_y; int z = p_z; - if (i&1) - x+=half; - if (i&2) - y+=half; - if (i&4) - z+=half; + if (i & 1) + x += half; + if (i & 2) + y += half; + if (i & 4) + z += half; - _gi_probe_fill_local_data(child,p_level+1,x,y,z,p_cell,p_header,p_local_data,prev_cell); + _gi_probe_fill_local_data(child, p_level + 1, x, y, z, p_cell, p_header, p_local_data, prev_cell); } } //position for each part of the mipmaped texture - p_local_data[p_idx].pos[0]=p_x>>(p_header->cell_subdiv-p_level-1); - p_local_data[p_idx].pos[1]=p_y>>(p_header->cell_subdiv-p_level-1); - p_local_data[p_idx].pos[2]=p_z>>(p_header->cell_subdiv-p_level-1); + p_local_data[p_idx].pos[0] = p_x >> (p_header->cell_subdiv - p_level - 1); + p_local_data[p_idx].pos[1] = p_y >> (p_header->cell_subdiv - p_level - 1); + p_local_data[p_idx].pos[2] = p_z >> (p_header->cell_subdiv - p_level - 1); prev_cell[p_level].push_back(p_idx); - } +void VisualServerScene::_gi_probe_bake_threads(void *self) { -void VisualServerScene::_gi_probe_bake_threads(void* self) { - - VisualServerScene* vss = (VisualServerScene*)self; + VisualServerScene *vss = (VisualServerScene *)self; vss->_gi_probe_bake_thread(); } void VisualServerScene::_setup_gi_probe(Instance *p_instance) { - - InstanceGIProbeData *probe = static_cast<InstanceGIProbeData*>(p_instance->base_data); + InstanceGIProbeData *probe = static_cast<InstanceGIProbeData *>(p_instance->base_data); if (probe->dynamic.probe_data.is_valid()) { VSG::storage->free(probe->dynamic.probe_data); - probe->dynamic.probe_data=RID(); + probe->dynamic.probe_data = RID(); } - probe->dynamic.light_data=VSG::storage->gi_probe_get_dynamic_data(p_instance->base); + probe->dynamic.light_data = VSG::storage->gi_probe_get_dynamic_data(p_instance->base); - if (probe->dynamic.light_data.size()==0) + if (probe->dynamic.light_data.size() == 0) return; //using dynamic data - PoolVector<int>::Read r=probe->dynamic.light_data.read(); + PoolVector<int>::Read r = probe->dynamic.light_data.read(); const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr(); @@ -2462,36 +2294,36 @@ void VisualServerScene::_setup_gi_probe(Instance *p_instance) { int cell_count = probe->dynamic.local_data.size(); PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write(); - const GIProbeDataCell *cells = (GIProbeDataCell*)&r[16]; + const GIProbeDataCell *cells = (GIProbeDataCell *)&r[16]; probe->dynamic.level_cell_lists.resize(header->cell_subdiv); - _gi_probe_fill_local_data(0,0,0,0,0,cells,header,ldw.ptr(),probe->dynamic.level_cell_lists.ptr()); + _gi_probe_fill_local_data(0, 0, 0, 0, 0, cells, header, ldw.ptr(), probe->dynamic.level_cell_lists.ptr()); bool compress = VSG::storage->gi_probe_is_compressed(p_instance->base); probe->dynamic.compression = compress ? VSG::storage->gi_probe_get_dynamic_data_get_preferred_compression() : RasterizerStorage::GI_PROBE_UNCOMPRESSED; - probe->dynamic.probe_data=VSG::storage->gi_probe_dynamic_data_create(header->width,header->height,header->depth,probe->dynamic.compression); + probe->dynamic.probe_data = VSG::storage->gi_probe_dynamic_data_create(header->width, header->height, header->depth, probe->dynamic.compression); - probe->dynamic.bake_dynamic_range=VSG::storage->gi_probe_get_dynamic_range(p_instance->base); + probe->dynamic.bake_dynamic_range = VSG::storage->gi_probe_get_dynamic_range(p_instance->base); probe->dynamic.mipmaps_3d.clear(); - probe->dynamic.propagate=VSG::storage->gi_probe_get_propagation(p_instance->base); + probe->dynamic.propagate = VSG::storage->gi_probe_get_propagation(p_instance->base); - probe->dynamic.grid_size[0]=header->width; - probe->dynamic.grid_size[1]=header->height; - probe->dynamic.grid_size[2]=header->depth; + probe->dynamic.grid_size[0] = header->width; + probe->dynamic.grid_size[1] = header->height; + probe->dynamic.grid_size[2] = header->depth; int size_limit = 1; int size_divisor = 1; - if (probe->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) { + if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) { print_line("S3TC"); - size_limit=4; - size_divisor=4; + size_limit = 4; + size_divisor = 4; } - for(int i=0;i<(int)header->cell_subdiv;i++) { + for (int i = 0; i < (int)header->cell_subdiv; i++) { uint32_t x = header->width >> i; uint32_t y = header->height >> i; @@ -2499,56 +2331,55 @@ void VisualServerScene::_setup_gi_probe(Instance *p_instance) { //create and clear mipmap PoolVector<uint8_t> mipmap; - int size = x*y*z*4; - size/=size_divisor; + int size = x * y * z * 4; + size /= size_divisor; mipmap.resize(size); PoolVector<uint8_t>::Write w = mipmap.write(); - zeromem(w.ptr(),size); + zeromem(w.ptr(), size); w = PoolVector<uint8_t>::Write(); probe->dynamic.mipmaps_3d.push_back(mipmap); - if (x<=size_limit || y<=size_limit || z<=size_limit) + if (x <= size_limit || y <= size_limit || z <= size_limit) break; } - probe->dynamic.updating_stage=GI_UPDATE_STAGE_CHECK; - probe->invalid=false; - probe->dynamic.enabled=true; + probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK; + probe->invalid = false; + probe->dynamic.enabled = true; Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base); Rect3 bounds = VSG::storage->gi_probe_get_bounds(p_instance->base); float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base); - probe->dynamic.light_to_cell_xform=cell_to_xform * p_instance->transform.affine_inverse(); + probe->dynamic.light_to_cell_xform = cell_to_xform * p_instance->transform.affine_inverse(); - VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance,p_instance->base,probe->dynamic.probe_data); - VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance,probe->dynamic.light_to_cell_xform); + VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance, p_instance->base, probe->dynamic.probe_data); + VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance, probe->dynamic.light_to_cell_xform); - VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance,bounds.size/cell_size); + VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance, bounds.size / cell_size); - probe->base_version=VSG::storage->gi_probe_get_version(p_instance->base); + probe->base_version = VSG::storage->gi_probe_get_version(p_instance->base); //if compression is S3TC, fill it up - if (probe->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) { + if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) { //create all blocks - Vector<Map<uint32_t,InstanceGIProbeData::CompBlockS3TC> > comp_blocks; + Vector<Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> > comp_blocks; int mipmap_count = probe->dynamic.mipmaps_3d.size(); comp_blocks.resize(mipmap_count); - for(int i=0;i<cell_count;i++) { + for (int i = 0; i < cell_count; i++) { const GIProbeDataCell &c = cells[i]; const InstanceGIProbeData::LocalData &ld = ldw[i]; - int level = c.level_alpha>>16; - int mipmap = header->cell_subdiv - level -1; + int level = c.level_alpha >> 16; + int mipmap = header->cell_subdiv - level - 1; if (mipmap >= mipmap_count) - continue;//uninteresting - + continue; //uninteresting - int blockx = (ld.pos[0]>>2); - int blocky = (ld.pos[1]>>2); + int blockx = (ld.pos[0] >> 2); + int blocky = (ld.pos[1] >> 2); int blockz = (ld.pos[2]); //compression is x/y only int blockw = (header->width >> mipmap) >> 2; @@ -2556,120 +2387,115 @@ void VisualServerScene::_setup_gi_probe(Instance *p_instance) { //print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh)); - uint32_t key = blockz * blockw*blockh + blocky * blockw + blockx; + uint32_t key = blockz * blockw * blockh + blocky * blockw + blockx; - Map<uint32_t,InstanceGIProbeData::CompBlockS3TC> & cmap = comp_blocks[mipmap]; + Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> &cmap = comp_blocks[mipmap]; if (!cmap.has(key)) { InstanceGIProbeData::CompBlockS3TC k; - k.offset=key; //use offset as counter first - k.source_count=0; - cmap[key]=k; + k.offset = key; //use offset as counter first + k.source_count = 0; + cmap[key] = k; } - InstanceGIProbeData::CompBlockS3TC &k=cmap[key]; - ERR_CONTINUE(k.source_count==16); - k.sources[k.source_count++]=i; + InstanceGIProbeData::CompBlockS3TC &k = cmap[key]; + ERR_CONTINUE(k.source_count == 16); + k.sources[k.source_count++] = i; } //fix the blocks, precomputing what is needed probe->dynamic.mipmaps_s3tc.resize(mipmap_count); - for(int i=0;i<mipmap_count;i++) { - print_line("S3TC level: "+itos(i)+" blocks: "+itos(comp_blocks[i].size())); + for (int i = 0; i < mipmap_count; i++) { + print_line("S3TC level: " + itos(i) + " blocks: " + itos(comp_blocks[i].size())); probe->dynamic.mipmaps_s3tc[i].resize(comp_blocks[i].size()); PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc[i].write(); - int block_idx=0; + int block_idx = 0; - for (Map<uint32_t,InstanceGIProbeData::CompBlockS3TC>::Element *E=comp_blocks[i].front();E;E=E->next()) { + for (Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>::Element *E = comp_blocks[i].front(); E; E = E->next()) { InstanceGIProbeData::CompBlockS3TC k = E->get(); //PRECOMPUTE ALPHA - int max_alpha=-100000; - int min_alpha=k.source_count==16 ?100000 :0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero) + int max_alpha = -100000; + int min_alpha = k.source_count == 16 ? 100000 : 0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero) - uint8_t alpha_block[4][4]={ {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0} }; + uint8_t alpha_block[4][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; - for(int j=0;j<k.source_count;j++) { + for (int j = 0; j < k.source_count; j++) { - int alpha = (cells[k.sources[j]].level_alpha>>8)&0xFF; - if (alpha<min_alpha) - min_alpha=alpha; - if (alpha>max_alpha) - max_alpha=alpha; + int alpha = (cells[k.sources[j]].level_alpha >> 8) & 0xFF; + if (alpha < min_alpha) + min_alpha = alpha; + if (alpha > max_alpha) + max_alpha = alpha; //fill up alpha block - alpha_block[ldw[k.sources[j]].pos[0]%4][ldw[k.sources[j]].pos[1]%4]=alpha; - + alpha_block[ldw[k.sources[j]].pos[0] % 4][ldw[k.sources[j]].pos[1] % 4] = alpha; } //use the first mode (8 adjustable levels) - k.alpha[0]=max_alpha; - k.alpha[1]=min_alpha; + k.alpha[0] = max_alpha; + k.alpha[1] = min_alpha; - uint64_t alpha_bits=0; + uint64_t alpha_bits = 0; - if (max_alpha!=min_alpha) { + if (max_alpha != min_alpha) { - int idx=0; + int idx = 0; - for(int y=0;y<4;y++) { - for(int x=0;x<4;x++) { + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 4; x++) { //substract minimum - uint32_t a = uint32_t(alpha_block[x][y])-min_alpha; + uint32_t a = uint32_t(alpha_block[x][y]) - min_alpha; //convert range to 3 bits - a =int((a * 7.0 / (max_alpha-min_alpha))+0.5); - a = CLAMP(a,0,7); //just to be sure - a = 7-a; //because range is inverted in this mode - if (a==0) { + a = int((a * 7.0 / (max_alpha - min_alpha)) + 0.5); + a = CLAMP(a, 0, 7); //just to be sure + a = 7 - a; //because range is inverted in this mode + if (a == 0) { //do none, remain - } else if (a==7) { - a=1; + } else if (a == 7) { + a = 1; } else { - a=a+1; + a = a + 1; } - alpha_bits|=uint64_t(a)<<(idx*3); + alpha_bits |= uint64_t(a) << (idx * 3); idx++; } } } - k.alpha[2]=(alpha_bits >> 0)&0xFF; - k.alpha[3]=(alpha_bits >> 8)&0xFF; - k.alpha[4]=(alpha_bits >> 16)&0xFF; - k.alpha[5]=(alpha_bits >> 24)&0xFF; - k.alpha[6]=(alpha_bits >> 32)&0xFF; - k.alpha[7]=(alpha_bits >> 40)&0xFF; - - w[block_idx++]=k; + k.alpha[2] = (alpha_bits >> 0) & 0xFF; + k.alpha[3] = (alpha_bits >> 8) & 0xFF; + k.alpha[4] = (alpha_bits >> 16) & 0xFF; + k.alpha[5] = (alpha_bits >> 24) & 0xFF; + k.alpha[6] = (alpha_bits >> 32) & 0xFF; + k.alpha[7] = (alpha_bits >> 40) & 0xFF; + w[block_idx++] = k; } - } } - } void VisualServerScene::_gi_probe_bake_thread() { - while(true) { + while (true) { probe_bake_sem->wait(); if (probe_bake_thread_exit) { break; } - Instance* to_bake=NULL; + Instance *to_bake = NULL; probe_bake_mutex->lock(); if (!probe_bake_list.empty()) { - to_bake=probe_bake_list.front()->get(); + to_bake = probe_bake_list.front()->get(); probe_bake_list.pop_front(); - } probe_bake_mutex->unlock(); @@ -2680,111 +2506,103 @@ void VisualServerScene::_gi_probe_bake_thread() { } } +uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv) { + uint32_t cell = 0; -uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells,int x,int y, int z,int p_cell_subdiv) { - + int ofs_x = 0; + int ofs_y = 0; + int ofs_z = 0; + int size = 1 << (p_cell_subdiv - 1); + int half = size / 2; - uint32_t cell=0; - - int ofs_x=0; - int ofs_y=0; - int ofs_z=0; - int size = 1<<(p_cell_subdiv-1); - int half=size/2; - - if (x<0 || x>=size) + if (x < 0 || x >= size) return -1; - if (y<0 || y>=size) + if (y < 0 || y >= size) return -1; - if (z<0 || z>=size) + if (z < 0 || z >= size) return -1; - for(int i=0;i<p_cell_subdiv-1;i++) { + for (int i = 0; i < p_cell_subdiv - 1; i++) { const GIProbeDataCell *bc = &cells[cell]; int child = 0; if (x >= ofs_x + half) { - child|=1; - ofs_x+=half; + child |= 1; + ofs_x += half; } if (y >= ofs_y + half) { - child|=2; - ofs_y+=half; + child |= 2; + ofs_y += half; } if (z >= ofs_z + half) { - child|=4; - ofs_z+=half; + child |= 4; + ofs_z += half; } cell = bc->children[child]; - if (cell==0xFFFFFFFF) + if (cell == 0xFFFFFFFF) return 0xFFFFFFFF; - half>>=1; + half >>= 1; } return cell; - } -static float _get_normal_advance(const Vector3& p_normal ) { +static float _get_normal_advance(const Vector3 &p_normal) { Vector3 normal = p_normal; Vector3 unorm = normal.abs(); - if ( (unorm.x >= unorm.y) && (unorm.x >= unorm.z) ) { - // x code - unorm = normal.x > 0.0 ? Vector3( 1.0, 0.0, 0.0 ) : Vector3( -1.0, 0.0, 0.0 ) ; - } else if ( (unorm.y > unorm.x) && (unorm.y >= unorm.z) ) { - // y code - unorm = normal.y > 0.0 ? Vector3( 0.0, 1.0, 0.0 ) : Vector3( 0.0, -1.0, 0.0 ) ; - } else if ( (unorm.z > unorm.x) && (unorm.z > unorm.y) ) { - // z code - unorm = normal.z > 0.0 ? Vector3( 0.0, 0.0, 1.0 ) : Vector3( 0.0, 0.0, -1.0 ) ; + if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) { + // x code + unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0); + } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) { + // y code + unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0); + } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) { + // z code + unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0); } else { - // oh-no we messed up code - // has to be - unorm = Vector3( 1.0, 0.0, 0.0 ); + // oh-no we messed up code + // has to be + unorm = Vector3(1.0, 0.0, 0.0); } - return 1.0/normal.dot(unorm); - + return 1.0 / normal.dot(unorm); } -void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,const GIProbeDataCell *cells,InstanceGIProbeData::LocalData *local_data,const uint32_t *leaves,int leaf_count, const InstanceGIProbeData::LightCache& light_cache,int sign) { +void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int leaf_count, const InstanceGIProbeData::LightCache &light_cache, int sign) { + int light_r = int(light_cache.color.r * light_cache.energy * 1024.0) * sign; + int light_g = int(light_cache.color.g * light_cache.energy * 1024.0) * sign; + int light_b = int(light_cache.color.b * light_cache.energy * 1024.0) * sign; - int light_r = int(light_cache.color.r * light_cache.energy * 1024.0)*sign; - int light_g = int(light_cache.color.g * light_cache.energy * 1024.0)*sign; - int light_b = int(light_cache.color.b * light_cache.energy * 1024.0)*sign; - - float limits[3]={float(header->width),float(header->height),float(header->depth)}; + float limits[3] = { float(header->width), float(header->height), float(header->depth) }; Plane clip[3]; - int clip_planes=0; - - + int clip_planes = 0; - switch(light_cache.type) { + switch (light_cache.type) { case VS::LIGHT_DIRECTIONAL: { - float max_len = Vector3(limits[0],limits[1],limits[2]).length()*1.1; + float max_len = Vector3(limits[0], limits[1], limits[2]).length() * 1.1; Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized(); - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - if (ABS(light_axis[i])<CMP_EPSILON) + if (ABS(light_axis[i]) < CMP_EPSILON) continue; - clip[clip_planes].normal[i]=1.0; + clip[clip_planes].normal[i] = 1.0; - if (light_axis[i]<0) { + if (light_axis[i] < 0) { - clip[clip_planes].d=limits[i]+1; + clip[clip_planes].d = limits[i] + 1; } else { - clip[clip_planes].d-=1.0; + clip[clip_planes].d -= 1.0; } clip_planes++; @@ -2792,137 +2610,129 @@ void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,con float distance_adv = _get_normal_advance(light_axis); - int success_count=0; + int success_count = 0; uint64_t us = OS::get_singleton()->get_ticks_usec(); - for(int i=0;i<leaf_count;i++) { + for (int i = 0; i < leaf_count; i++) { uint32_t idx = leaves[i]; const GIProbeDataCell *cell = &cells[idx]; InstanceGIProbeData::LocalData *light = &local_data[idx]; - Vector3 to(light->pos[0]+0.5,light->pos[1]+0.5,light->pos[2]+0.5); - Vector3 norm ( - (((cells[idx].normal>>16)&0xFF)/255.0)*2.0-1.0, - (((cells[idx].normal>>8)&0xFF)/255.0)*2.0-1.0, - (((cells[idx].normal>>0)&0xFF)/255.0)*2.0-1.0 - ); - + Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5); + Vector3 norm( + (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0, + (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0, + (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0); float att = norm.dot(-light_axis); - if (att<0.001) { + if (att < 0.001) { //not lighting towards this continue; } Vector3 from = to - max_len * light_axis; - for(int j=0;j<clip_planes;j++) { + for (int j = 0; j < clip_planes; j++) { - clip[j].intersects_segment(from,to,&from); + clip[j].intersects_segment(from, to, &from); } float distance = (to - from).length(); - distance+=distance_adv-Math::fmod(distance,distance_adv); //make it reach the center of the box always + distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always from = to - light_axis * distance; - uint32_t result=0xFFFFFFFF; + uint32_t result = 0xFFFFFFFF; - while(distance>-distance_adv) { //use this to avoid precision errors + while (distance > -distance_adv) { //use this to avoid precision errors - result = _gi_bake_find_cell(cells,int(floor(from.x)),int(floor(from.y)),int(floor(from.z)),header->cell_subdiv); - if (result!=0xFFFFFFFF) { + result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv); + if (result != 0xFFFFFFFF) { break; } - from+=light_axis*distance_adv; - distance-=distance_adv; + from += light_axis * distance_adv; + distance -= distance_adv; } - if (result==idx) { + if (result == idx) { //cell hit itself! hooray! - light->energy[0]+=int32_t(light_r*att*((cell->albedo>>16)&0xFF)/255.0); - light->energy[1]+=int32_t(light_g*att*((cell->albedo>>8)&0xFF)/255.0); - light->energy[2]+=int32_t(light_b*att*((cell->albedo)&0xFF)/255.0); - success_count++; + light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0); + light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0); + light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0); + success_count++; } } - print_line("BAKE TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0)); - print_line("valid cells: "+itos(success_count)); - + print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0)); + print_line("valid cells: " + itos(success_count)); } break; case VS::LIGHT_OMNI: case VS::LIGHT_SPOT: { - uint64_t us = OS::get_singleton()->get_ticks_usec(); Vector3 light_pos = light_cache.transform.origin; Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized(); - float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length(); - for(int i=0;i<leaf_count;i++) { + for (int i = 0; i < leaf_count; i++) { uint32_t idx = leaves[i]; const GIProbeDataCell *cell = &cells[idx]; InstanceGIProbeData::LocalData *light = &local_data[idx]; - Vector3 to(light->pos[0]+0.5,light->pos[1]+0.5,light->pos[2]+0.5); - Vector3 norm ( - (((cells[idx].normal>>16)&0xFF)/255.0)*2.0-1.0, - (((cells[idx].normal>>8)&0xFF)/255.0)*2.0-1.0, - (((cells[idx].normal>>0)&0xFF)/255.0)*2.0-1.0 - ); + Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5); + Vector3 norm( + (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0, + (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0, + (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0); Vector3 light_axis = (to - light_pos).normalized(); float distance_adv = _get_normal_advance(light_axis); float att = norm.dot(-light_axis); - if (att<0.001) { + if (att < 0.001) { //not lighting towards this continue; } { float d = light_pos.distance_to(to); - if (d+distance_adv > local_radius) + if (d + distance_adv > local_radius) continue; // too far away - float dt = CLAMP((d+distance_adv)/local_radius,0,1); - att*= powf(1.0-dt,light_cache.attenuation); + float dt = CLAMP((d + distance_adv) / local_radius, 0, 1); + att *= powf(1.0 - dt, light_cache.attenuation); } - - if (light_cache.type==VS::LIGHT_SPOT) { + if (light_cache.type == VS::LIGHT_SPOT) { float angle = Math::rad2deg(acos(light_axis.dot(spot_axis))); if (angle > light_cache.spot_angle) continue; - float d = CLAMP(angle/light_cache.spot_angle,1,0); - att*= powf(1.0-d,light_cache.spot_attenuation); - + float d = CLAMP(angle / light_cache.spot_angle, 1, 0); + att *= powf(1.0 - d, light_cache.spot_attenuation); } - clip_planes=0; + clip_planes = 0; - for(int c=0;c<3;c++) { + for (int c = 0; c < 3; c++) { - if (ABS(light_axis[c])<CMP_EPSILON) + if (ABS(light_axis[c]) < CMP_EPSILON) continue; - clip[clip_planes].normal[c]=1.0; + clip[clip_planes].normal[c] = 1.0; - if (light_axis[c]<0) { + if (light_axis[c] < 0) { - clip[clip_planes].d=limits[c]+1; + clip[clip_planes].d = limits[c] + 1; } else { - clip[clip_planes].d-=1.0; + clip[clip_planes].d -= 1.0; } clip_planes++; @@ -2930,216 +2740,203 @@ void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,con Vector3 from = light_pos; - for(int j=0;j<clip_planes;j++) { + for (int j = 0; j < clip_planes; j++) { - clip[j].intersects_segment(from,to,&from); + clip[j].intersects_segment(from, to, &from); } float distance = (to - from).length(); - - - distance-=Math::fmod(distance,distance_adv); //make it reach the center of the box always, but this tame make it closer + distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer from = to - light_axis * distance; - uint32_t result=0xFFFFFFFF; + uint32_t result = 0xFFFFFFFF; - while(distance>-distance_adv) { //use this to avoid precision errors + while (distance > -distance_adv) { //use this to avoid precision errors - result = _gi_bake_find_cell(cells,int(floor(from.x)),int(floor(from.y)),int(floor(from.z)),header->cell_subdiv); - if (result!=0xFFFFFFFF) { + result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv); + if (result != 0xFFFFFFFF) { break; } - from+=light_axis*distance_adv; - distance-=distance_adv; + from += light_axis * distance_adv; + distance -= distance_adv; } - if (result==idx) { + if (result == idx) { //cell hit itself! hooray! - light->energy[0]+=int32_t(light_r*att*((cell->albedo>>16)&0xFF)/255.0); - light->energy[1]+=int32_t(light_g*att*((cell->albedo>>8)&0xFF)/255.0); - light->energy[2]+=int32_t(light_b*att*((cell->albedo)&0xFF)/255.0); - + light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0); + light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0); + light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0); } } - print_line("BAKE TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0)); - + print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0)); } break; } } - -void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell* p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data,float p_propagate) { +void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate) { //average light to upper level - float divisor=0; - float sum[3]={0.0,0.0,0.0}; + float divisor = 0; + float sum[3] = { 0.0, 0.0, 0.0 }; - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { uint32_t child = p_cells[p_idx].children[i]; - if (child==0xFFFFFFFF) + if (child == 0xFFFFFFFF) continue; - if (p_level+1 < (int)p_header->cell_subdiv-1) { - _bake_gi_downscale_light(child,p_level+1,p_cells,p_header,p_local_data,p_propagate); + if (p_level + 1 < (int)p_header->cell_subdiv - 1) { + _bake_gi_downscale_light(child, p_level + 1, p_cells, p_header, p_local_data, p_propagate); } - sum[0]+=p_local_data[child].energy[0]; - sum[1]+=p_local_data[child].energy[1]; - sum[2]+=p_local_data[child].energy[2]; - divisor+=1.0; - + sum[0] += p_local_data[child].energy[0]; + sum[1] += p_local_data[child].energy[1]; + sum[2] += p_local_data[child].energy[2]; + divisor += 1.0; } - divisor=Math::lerp((float)8.0,divisor,p_propagate); - sum[0]/=divisor; - sum[1]/=divisor; - sum[2]/=divisor; + divisor = Math::lerp((float)8.0, divisor, p_propagate); + sum[0] /= divisor; + sum[1] /= divisor; + sum[2] /= divisor; //divide by eight for average - p_local_data[p_idx].energy[0]=Math::fast_ftoi(sum[0]); - p_local_data[p_idx].energy[1]=Math::fast_ftoi(sum[1]); - p_local_data[p_idx].energy[2]=Math::fast_ftoi(sum[2]); - + p_local_data[p_idx].energy[0] = Math::fast_ftoi(sum[0]); + p_local_data[p_idx].energy[1] = Math::fast_ftoi(sum[1]); + p_local_data[p_idx].energy[2] = Math::fast_ftoi(sum[2]); } - void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) { - InstanceGIProbeData * probe_data = static_cast<InstanceGIProbeData*>(p_gi_probe->base_data); + InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data); - PoolVector<int>::Read r=probe_data->dynamic.light_data.read(); + PoolVector<int>::Read r = probe_data->dynamic.light_data.read(); const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr(); - const GIProbeDataCell *cells = (const GIProbeDataCell*)&r[16]; + const GIProbeDataCell *cells = (const GIProbeDataCell *)&r[16]; - int leaf_count = probe_data->dynamic.level_cell_lists[ header->cell_subdiv -1 ].size(); - const uint32_t *leaves = probe_data->dynamic.level_cell_lists[ header->cell_subdiv -1 ].ptr(); + int leaf_count = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].size(); + const uint32_t *leaves = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].ptr(); PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write(); InstanceGIProbeData::LocalData *local_data = ldw.ptr(); - //remove what must be removed - for (Map<RID,InstanceGIProbeData::LightCache>::Element *E=probe_data->dynamic.light_cache.front();E;E=E->next()) { + for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache.front(); E; E = E->next()) { RID rid = E->key(); - const InstanceGIProbeData::LightCache& lc = E->get(); + const InstanceGIProbeData::LightCache &lc = E->get(); - if (!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid]==lc)) { + if (!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid] == lc)) { //erase light data - _bake_gi_probe_light(header,cells,local_data,leaves,leaf_count,lc,-1); + _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, -1); } - } //add what must be added - for (Map<RID,InstanceGIProbeData::LightCache>::Element *E=probe_data->dynamic.light_cache_changes.front();E;E=E->next()) { + for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache_changes.front(); E; E = E->next()) { RID rid = E->key(); - const InstanceGIProbeData::LightCache& lc = E->get(); + const InstanceGIProbeData::LightCache &lc = E->get(); - if (!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid]==lc)) { + if (!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid] == lc)) { //add light data - _bake_gi_probe_light(header,cells,local_data,leaves,leaf_count,lc,1); + _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, 1); } } - SWAP(probe_data->dynamic.light_cache_changes,probe_data->dynamic.light_cache); + SWAP(probe_data->dynamic.light_cache_changes, probe_data->dynamic.light_cache); //downscale to lower res levels - _bake_gi_downscale_light(0,0,cells,header,local_data,probe_data->dynamic.propagate); + _bake_gi_downscale_light(0, 0, cells, header, local_data, probe_data->dynamic.propagate); //plot result to 3D texture! - if (probe_data->dynamic.compression==RasterizerStorage::GI_PROBE_UNCOMPRESSED) { + if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_UNCOMPRESSED) { - for(int i=0;i<(int)header->cell_subdiv;i++) { + for (int i = 0; i < (int)header->cell_subdiv; i++) { - int stage = header->cell_subdiv - i -1; + int stage = header->cell_subdiv - i - 1; if (stage >= probe_data->dynamic.mipmaps_3d.size()) continue; //no mipmap for this one - print_line("generating mipmap stage: "+itos(stage)); - int level_cell_count = probe_data->dynamic.level_cell_lists[ i ].size(); - const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[ i ].ptr(); + print_line("generating mipmap stage: " + itos(stage)); + int level_cell_count = probe_data->dynamic.level_cell_lists[i].size(); + const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[i].ptr(); PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d[stage].write(); uint8_t *mipmapw = lw.ptr(); - uint32_t sizes[3]={header->width>>stage,header->height>>stage,header->depth>>stage}; + uint32_t sizes[3] = { header->width >> stage, header->height >> stage, header->depth >> stage }; - for(int j=0;j<level_cell_count;j++) { + for (int j = 0; j < level_cell_count; j++) { uint32_t idx = level_cells[j]; - uint32_t r = (uint32_t(local_data[idx].energy[0])/probe_data->dynamic.bake_dynamic_range)>>2; - uint32_t g = (uint32_t(local_data[idx].energy[1])/probe_data->dynamic.bake_dynamic_range)>>2; - uint32_t b = (uint32_t(local_data[idx].energy[2])/probe_data->dynamic.bake_dynamic_range)>>2; - uint32_t a = (cells[idx].level_alpha>>8)&0xFF; - - uint32_t mm_ofs = sizes[0]*sizes[1]*(local_data[idx].pos[2]) + sizes[0]*(local_data[idx].pos[1]) + (local_data[idx].pos[0]); - mm_ofs*=4; //for RGBA (4 bytes) - - mipmapw[mm_ofs+0]=uint8_t(CLAMP(r,0,255)); - mipmapw[mm_ofs+1]=uint8_t(CLAMP(g,0,255)); - mipmapw[mm_ofs+2]=uint8_t(CLAMP(b,0,255)); - mipmapw[mm_ofs+3]=uint8_t(CLAMP(a,0,255)); + uint32_t r = (uint32_t(local_data[idx].energy[0]) / probe_data->dynamic.bake_dynamic_range) >> 2; + uint32_t g = (uint32_t(local_data[idx].energy[1]) / probe_data->dynamic.bake_dynamic_range) >> 2; + uint32_t b = (uint32_t(local_data[idx].energy[2]) / probe_data->dynamic.bake_dynamic_range) >> 2; + uint32_t a = (cells[idx].level_alpha >> 8) & 0xFF; + uint32_t mm_ofs = sizes[0] * sizes[1] * (local_data[idx].pos[2]) + sizes[0] * (local_data[idx].pos[1]) + (local_data[idx].pos[0]); + mm_ofs *= 4; //for RGBA (4 bytes) + mipmapw[mm_ofs + 0] = uint8_t(CLAMP(r, 0, 255)); + mipmapw[mm_ofs + 1] = uint8_t(CLAMP(g, 0, 255)); + mipmapw[mm_ofs + 2] = uint8_t(CLAMP(b, 0, 255)); + mipmapw[mm_ofs + 3] = uint8_t(CLAMP(a, 0, 255)); } } - } else if (probe_data->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) { - + } else if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) { int mipmap_count = probe_data->dynamic.mipmaps_3d.size(); - for(int mmi=0;mmi<mipmap_count;mmi++) { + for (int mmi = 0; mmi < mipmap_count; mmi++) { PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d[mmi].write(); int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size(); PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read(); - for(int i=0;i<block_count;i++) { + for (int i = 0; i < block_count; i++) { - const InstanceGIProbeData::CompBlockS3TC& b = mmr[i]; + const InstanceGIProbeData::CompBlockS3TC &b = mmr[i]; - uint8_t *blockptr = &mmw[b.offset*16]; - copymem(blockptr,b.alpha,8); //copy alpha part, which is precomputed + uint8_t *blockptr = &mmw[b.offset * 16]; + copymem(blockptr, b.alpha, 8); //copy alpha part, which is precomputed Vector3 colors[16]; - for(int j=0;j<b.source_count;j++) { + for (int j = 0; j < b.source_count; j++) { - colors[j].x=(local_data[b.sources[j]].energy[0]/float(probe_data->dynamic.bake_dynamic_range))/1024.0; - colors[j].y=(local_data[b.sources[j]].energy[1]/float(probe_data->dynamic.bake_dynamic_range))/1024.0; - colors[j].z=(local_data[b.sources[j]].energy[2]/float(probe_data->dynamic.bake_dynamic_range))/1024.0; + colors[j].x = (local_data[b.sources[j]].energy[0] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0; + colors[j].y = (local_data[b.sources[j]].energy[1] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0; + colors[j].z = (local_data[b.sources[j]].energy[2] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0; } //super quick and dirty compression //find 2 most futher apart - float distance=0; - Vector3 from,to; + float distance = 0; + Vector3 from, to; - if (b.source_count==16) { + if (b.source_count == 16) { //all cells are used so, find minmax between them - int further_apart[2]={0,0}; - for(int j=0;j<b.source_count;j++) { - for(int k=j+1;k<b.source_count;k++) { + int further_apart[2] = { 0, 0 }; + for (int j = 0; j < b.source_count; j++) { + for (int k = j + 1; k < b.source_count; k++) { float d = colors[j].distance_squared_to(colors[k]); - if (d>distance) { - distance=d; - further_apart[0]=j; - further_apart[1]=k; + if (d > distance) { + distance = d; + further_apart[0] = j; + further_apart[1] = k; } } } @@ -3154,154 +2951,138 @@ void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) { //average all colors first Vector3 average; - for(int j=0;j<b.source_count;j++) { - average+=colors[j]; + for (int j = 0; j < b.source_count; j++) { + average += colors[j]; } average.normalize(); //find max distance in normal from average - for(int j=0;j<b.source_count;j++) { + for (int j = 0; j < b.source_count; j++) { float d = average.dot(colors[j]); - distance=MAX(d,distance); + distance = MAX(d, distance); } from = Vector3(); //from black to = average * distance; //find max distance - } - int indices[16]; - uint16_t color_0=0; - color_0 = CLAMP(int(from.x*31),0,31)<<11; - color_0 |= CLAMP(int(from.y*63),0,63)<<5; - color_0 |= CLAMP(int(from.z*31),0,31); + uint16_t color_0 = 0; + color_0 = CLAMP(int(from.x * 31), 0, 31) << 11; + color_0 |= CLAMP(int(from.y * 63), 0, 63) << 5; + color_0 |= CLAMP(int(from.z * 31), 0, 31); - uint16_t color_1=0; - color_1 = CLAMP(int(to.x*31),0,31)<<11; - color_1 |= CLAMP(int(to.y*63),0,63)<<5; - color_1 |= CLAMP(int(to.z*31),0,31); + uint16_t color_1 = 0; + color_1 = CLAMP(int(to.x * 31), 0, 31) << 11; + color_1 |= CLAMP(int(to.y * 63), 0, 63) << 5; + color_1 |= CLAMP(int(to.z * 31), 0, 31); if (color_1 > color_0) { - SWAP(color_1,color_0); - SWAP(from,to); + SWAP(color_1, color_0); + SWAP(from, to); } + if (distance > 0) { - if (distance>0) { - - Vector3 dir = (to-from).normalized(); + Vector3 dir = (to - from).normalized(); + for (int j = 0; j < b.source_count; j++) { - for(int j=0;j<b.source_count;j++) { - - float d = (colors[j]-from).dot(dir) / distance; - indices[j]=int(d*3+0.5); - - static const int index_swap[4]={0,3,1,2}; - - indices[j]=index_swap[CLAMP(indices[j],0,3)]; + float d = (colors[j] - from).dot(dir) / distance; + indices[j] = int(d * 3 + 0.5); + static const int index_swap[4] = { 0, 3, 1, 2 }; + indices[j] = index_swap[CLAMP(indices[j], 0, 3)]; } } else { - for(int j=0;j<b.source_count;j++) { - indices[j]=0; + for (int j = 0; j < b.source_count; j++) { + indices[j] = 0; } } //by default, 1 is black, otherwise it will be overriden by source - uint32_t index_block[16]={1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1 }; + uint32_t index_block[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; - for(int j=0;j<b.source_count;j++) { + for (int j = 0; j < b.source_count; j++) { - int x=local_data[b.sources[j]].pos[0]%4; - int y=local_data[b.sources[j]].pos[1]%4; + int x = local_data[b.sources[j]].pos[0] % 4; + int y = local_data[b.sources[j]].pos[1] % 4; - index_block[y*4+x]=indices[j]; + index_block[y * 4 + x] = indices[j]; } - uint32_t encode=0; + uint32_t encode = 0; - for(int j=0;j<16;j++) { - encode|=index_block[j]<<(j*2); + for (int j = 0; j < 16; j++) { + encode |= index_block[j] << (j * 2); } - blockptr[8]=color_0&0xFF; - blockptr[9]=(color_0>>8)&0xFF; - blockptr[10]=color_1&0xFF; - blockptr[11]=(color_1>>8)&0xFF; - blockptr[12]=encode&0xFF; - blockptr[13]=(encode>>8)&0xFF; - blockptr[14]=(encode>>16)&0xFF; - blockptr[15]=(encode>>24)&0xFF; - + blockptr[8] = color_0 & 0xFF; + blockptr[9] = (color_0 >> 8) & 0xFF; + blockptr[10] = color_1 & 0xFF; + blockptr[11] = (color_1 >> 8) & 0xFF; + blockptr[12] = encode & 0xFF; + blockptr[13] = (encode >> 8) & 0xFF; + blockptr[14] = (encode >> 16) & 0xFF; + blockptr[15] = (encode >> 24) & 0xFF; } - - } - } - //send back to main thread to update un little chunks - probe_data->dynamic.updating_stage=GI_UPDATE_STAGE_UPLOADING; - + probe_data->dynamic.updating_stage = GI_UPDATE_STAGE_UPLOADING; } bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) { - InstanceGIProbeData * probe_data = static_cast<InstanceGIProbeData*>(p_gi_probe->base_data); + InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data); probe_data->dynamic.light_cache_changes.clear(); - bool all_equal=true; - + bool all_equal = true; - for (List<Instance*>::Element *E=p_gi_probe->scenario->directional_lights.front();E;E=E->next()) { + for (List<Instance *>::Element *E = p_gi_probe->scenario->directional_lights.front(); E; E = E->next()) { InstanceGIProbeData::LightCache lc; - lc.type=VSG::storage->light_get_type(E->get()->base); - lc.color=VSG::storage->light_get_color(E->get()->base); - lc.energy=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ENERGY); - lc.radius=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_RANGE); - lc.attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ATTENUATION); - lc.spot_angle=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ANGLE); - lc.spot_attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ATTENUATION); + lc.type = VSG::storage->light_get_type(E->get()->base); + lc.color = VSG::storage->light_get_color(E->get()->base); + lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY); + lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE); + lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION); + lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE); + lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION); lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform; - if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self]==lc)) { - all_equal=false; + if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) { + all_equal = false; } - probe_data->dynamic.light_cache_changes[E->get()->self]=lc; - + probe_data->dynamic.light_cache_changes[E->get()->self] = lc; } - - for (Set<Instance*>::Element *E=probe_data->lights.front();E;E=E->next()) { + for (Set<Instance *>::Element *E = probe_data->lights.front(); E; E = E->next()) { InstanceGIProbeData::LightCache lc; - lc.type=VSG::storage->light_get_type(E->get()->base); - lc.color=VSG::storage->light_get_color(E->get()->base); - lc.energy=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ENERGY); - lc.radius=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_RANGE); - lc.attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ATTENUATION); - lc.spot_angle=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ANGLE); - lc.spot_attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ATTENUATION); + lc.type = VSG::storage->light_get_type(E->get()->base); + lc.color = VSG::storage->light_get_color(E->get()->base); + lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY); + lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE); + lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION); + lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE); + lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION); lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform; - if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self]==lc)) { - all_equal=false; + if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) { + all_equal = false; } - probe_data->dynamic.light_cache_changes[E->get()->self]=lc; + probe_data->dynamic.light_cache_changes[E->get()->self] = lc; } //lighting changed from after to before, must do some updating - return !all_equal || probe_data->dynamic.light_cache_changes.size()!=probe_data->dynamic.light_cache.size(); - + return !all_equal || probe_data->dynamic.light_cache_changes.size() != probe_data->dynamic.light_cache.size(); } void VisualServerScene::render_probes() { @@ -3310,82 +3091,80 @@ void VisualServerScene::render_probes() { SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first(); - bool busy=false; + bool busy = false; - while(ref_probe) { + while (ref_probe) { - SelfList<InstanceReflectionProbeData> *next=ref_probe->next(); + SelfList<InstanceReflectionProbeData> *next = ref_probe->next(); RID base = ref_probe->self()->owner->base; - switch(VSG::storage->reflection_probe_get_update_mode(base)) { + switch (VSG::storage->reflection_probe_get_update_mode(base)) { case VS::REFLECTION_PROBE_UPDATE_ONCE: { if (busy) //already rendering something break; - bool done = _render_reflection_probe_step(ref_probe->self()->owner,ref_probe->self()->render_step); + bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step); if (done) { reflection_probe_render_list.remove(ref_probe); } else { ref_probe->self()->render_step++; } - busy=true; //do not render another one of this kind + busy = true; //do not render another one of this kind } break; case VS::REFLECTION_PROBE_UPDATE_ALWAYS: { - int step=0; - bool done=false; - while(!done) { - done = _render_reflection_probe_step(ref_probe->self()->owner,step); + int step = 0; + bool done = false; + while (!done) { + done = _render_reflection_probe_step(ref_probe->self()->owner, step); step++; } reflection_probe_render_list.remove(ref_probe); } break; - } - ref_probe=next; + ref_probe = next; } /* GI PROBES */ SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first(); - while(gi_probe) { + while (gi_probe) { - SelfList<InstanceGIProbeData> *next=gi_probe->next(); + SelfList<InstanceGIProbeData> *next = gi_probe->next(); InstanceGIProbeData *probe = gi_probe->self(); Instance *instance_probe = probe->owner; //check if probe must be setup, but don't do if on the lighting thread - bool force_lighting=false; + bool force_lighting = false; - if (probe->invalid || (probe->dynamic.updating_stage==GI_UPDATE_STAGE_CHECK && probe->base_version!=VSG::storage->gi_probe_get_version(instance_probe->base))) { + if (probe->invalid || (probe->dynamic.updating_stage == GI_UPDATE_STAGE_CHECK && probe->base_version != VSG::storage->gi_probe_get_version(instance_probe->base))) { _setup_gi_probe(instance_probe); - force_lighting=true; + force_lighting = true; } float propagate = VSG::storage->gi_probe_get_propagation(instance_probe->base); - if (probe->dynamic.propagate!=propagate) { - probe->dynamic.propagate=propagate; - force_lighting=true; + if (probe->dynamic.propagate != propagate) { + probe->dynamic.propagate = propagate; + force_lighting = true; } + if (probe->invalid == false && probe->dynamic.enabled) { - if (probe->invalid==false && probe->dynamic.enabled) { - - switch(probe->dynamic.updating_stage) { + switch (probe->dynamic.updating_stage) { case GI_UPDATE_STAGE_CHECK: { if (_check_gi_probe(instance_probe) || force_lighting) { //send to lighting thread - probe->dynamic.updating_stage=GI_UPDATE_STAGE_LIGHTING; + probe->dynamic.updating_stage = GI_UPDATE_STAGE_LIGHTING; #ifndef NO_THREADS probe_bake_mutex->lock(); @@ -3397,7 +3176,6 @@ void VisualServerScene::render_probes() { _bake_gi_probe(instance_probe); #endif - } } break; case GI_UPDATE_STAGE_LIGHTING: { @@ -3408,29 +3186,23 @@ void VisualServerScene::render_probes() { uint64_t us = OS::get_singleton()->get_ticks_usec(); - for(int i=0;i<(int)probe->dynamic.mipmaps_3d.size();i++) { + for (int i = 0; i < (int)probe->dynamic.mipmaps_3d.size(); i++) { int mmsize = probe->dynamic.mipmaps_3d[i].size(); PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read(); - VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data,0,probe->dynamic.grid_size[2]>>i,i,r.ptr()); + VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data, 0, probe->dynamic.grid_size[2] >> i, i, r.ptr()); } - - probe->dynamic.updating_stage=GI_UPDATE_STAGE_CHECK; + probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK; //print_line("UPLOAD TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0)); } break; - } } //_update_gi_probe(gi_probe->self()->owner); - - gi_probe=next; + gi_probe = next; } - - - } void VisualServerScene::_update_dirty_instance(Instance *p_instance) { @@ -3438,143 +3210,131 @@ void VisualServerScene::_update_dirty_instance(Instance *p_instance) { if (p_instance->update_aabb) _update_instance_aabb(p_instance); - if (p_instance->update_materials) { - if (p_instance->base_type==VS::INSTANCE_MESH) { + if (p_instance->base_type == VS::INSTANCE_MESH) { //remove materials no longer used and un-own them int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base); - for(int i=p_instance->materials.size()-1;i>=new_mat_count;i--) { + for (int i = p_instance->materials.size() - 1; i >= new_mat_count; i--) { if (p_instance->materials[i].is_valid()) { - VSG::storage->material_remove_instance_owner(p_instance->materials[i],p_instance); + VSG::storage->material_remove_instance_owner(p_instance->materials[i], p_instance); } } p_instance->materials.resize(new_mat_count); int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base); - if (new_blend_shape_count!=p_instance->blend_values.size()) { + if (new_blend_shape_count != p_instance->blend_values.size()) { p_instance->blend_values.resize(new_blend_shape_count); - for(int i=0;i<new_blend_shape_count;i++) { - p_instance->blend_values[i]=0; + for (int i = 0; i < new_blend_shape_count; i++) { + p_instance->blend_values[i] = 0; } } } - if ((1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) { + if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) { - InstanceGeometryData *geom = static_cast<InstanceGeometryData*>(p_instance->base_data); + InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data); - bool can_cast_shadows=true; + bool can_cast_shadows = true; - if (p_instance->cast_shadows==VS::SHADOW_CASTING_SETTING_OFF) { - can_cast_shadows=false; + if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) { + can_cast_shadows = false; } else if (p_instance->material_override.is_valid()) { - can_cast_shadows=VSG::storage->material_casts_shadows(p_instance->material_override); + can_cast_shadows = VSG::storage->material_casts_shadows(p_instance->material_override); } else { - - - if (p_instance->base_type==VS::INSTANCE_MESH) { - RID mesh=p_instance->base; + if (p_instance->base_type == VS::INSTANCE_MESH) { + RID mesh = p_instance->base; if (mesh.is_valid()) { - bool cast_shadows=false; - - for(int i=0;i<p_instance->materials.size();i++) { + bool cast_shadows = false; + for (int i = 0; i < p_instance->materials.size(); i++) { - RID mat = p_instance->materials[i].is_valid()?p_instance->materials[i]:VSG::storage->mesh_surface_get_material(mesh,i); + RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : VSG::storage->mesh_surface_get_material(mesh, i); if (!mat.is_valid()) { - cast_shadows=true; + cast_shadows = true; break; } if (VSG::storage->material_casts_shadows(mat)) { - cast_shadows=true; + cast_shadows = true; break; } } if (!cast_shadows) { - can_cast_shadows=false; + can_cast_shadows = false; } } - } else if (p_instance->base_type==VS::INSTANCE_MULTIMESH) { + } else if (p_instance->base_type == VS::INSTANCE_MULTIMESH) { RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base); if (mesh.is_valid()) { - bool cast_shadows=false; + bool cast_shadows = false; int sc = VSG::storage->mesh_get_surface_count(mesh); - for(int i=0;i<sc;i++) { + for (int i = 0; i < sc; i++) { - RID mat =VSG::storage->mesh_surface_get_material(mesh,i); + RID mat = VSG::storage->mesh_surface_get_material(mesh, i); if (!mat.is_valid()) { - cast_shadows=true; + cast_shadows = true; break; } if (VSG::storage->material_casts_shadows(mat)) { - cast_shadows=true; + cast_shadows = true; break; } - } if (!cast_shadows) { - can_cast_shadows=false; + can_cast_shadows = false; } } - } else if (p_instance->base_type==VS::INSTANCE_IMMEDIATE) { + } else if (p_instance->base_type == VS::INSTANCE_IMMEDIATE) { RID mat = VSG::storage->immediate_get_material(p_instance->base); if (!mat.is_valid() || VSG::storage->material_casts_shadows(mat)) { - can_cast_shadows=true; + can_cast_shadows = true; } else { - can_cast_shadows=false; + can_cast_shadows = false; } - - } - - - } - if (can_cast_shadows!=geom->can_cast_shadows) { + if (can_cast_shadows != geom->can_cast_shadows) { //ability to cast shadows change, let lights now - for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) { - InstanceLightData *light = static_cast<InstanceLightData*>(E->get()->base_data); - light->shadow_dirty=true; + for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { + InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); + light->shadow_dirty = true; } - geom->can_cast_shadows=can_cast_shadows; + geom->can_cast_shadows = can_cast_shadows; } } - } _update_instance(p_instance); - p_instance->update_aabb=false; - p_instance->update_materials=false; + p_instance->update_aabb = false; + p_instance->update_materials = false; - _instance_update_list.remove( &p_instance->update_item ); + _instance_update_list.remove(&p_instance->update_item); } - void VisualServerScene::update_dirty_instances() { VSG::storage->update_dirty_resources(); - while(_instance_update_list.first()) { + while (_instance_update_list.first()) { - _update_dirty_instance( _instance_update_list.first()->self() ); + _update_dirty_instance(_instance_update_list.first()->self()); } } @@ -3582,17 +3342,17 @@ bool VisualServerScene::free(RID p_rid) { if (camera_owner.owns(p_rid)) { - Camera *camera = camera_owner.get( p_rid ); + Camera *camera = camera_owner.get(p_rid); camera_owner.free(p_rid); memdelete(camera); } else if (scenario_owner.owns(p_rid)) { - Scenario *scenario = scenario_owner.get( p_rid ); + Scenario *scenario = scenario_owner.get(p_rid); - while(scenario->instances.first()) { - instance_set_scenario(scenario->instances.first()->self()->self,RID()); + while (scenario->instances.first()) { + instance_set_scenario(scenario->instances.first()->self()->self, RID()); } VSG::scene_render->free(scenario->reflection_probe_shadow_atlas); VSG::scene_render->free(scenario->reflection_atlas); @@ -3606,11 +3366,11 @@ bool VisualServerScene::free(RID p_rid) { Instance *instance = instance_owner.get(p_rid); - instance_set_room(p_rid,RID()); - instance_set_scenario(p_rid,RID()); - instance_set_base(p_rid,RID()); - instance_geometry_set_material_override(p_rid,RID()); - instance_attach_skeleton(p_rid,RID()); + instance_set_room(p_rid, RID()); + instance_set_scenario(p_rid, RID()); + instance_set_base(p_rid, RID()); + instance_geometry_set_material_override(p_rid, RID()); + instance_attach_skeleton(p_rid, RID()); update_dirty_instances(); //in case something changed this @@ -3620,38 +3380,32 @@ bool VisualServerScene::free(RID p_rid) { return false; } - return true; } -VisualServerScene *VisualServerScene::singleton=NULL; - +VisualServerScene *VisualServerScene::singleton = NULL; VisualServerScene::VisualServerScene() { #ifndef NO_THREADS probe_bake_sem = Semaphore::create(); probe_bake_mutex = Mutex::create(); - probe_bake_thread = Thread::create(_gi_probe_bake_threads,this); - probe_bake_thread_exit=false; + probe_bake_thread = Thread::create(_gi_probe_bake_threads, this); + probe_bake_thread_exit = false; #endif - - render_pass=1; - singleton=this; - + render_pass = 1; + singleton = this; } VisualServerScene::~VisualServerScene() { #ifndef NO_THREADS - probe_bake_thread_exit=true; + probe_bake_thread_exit = true; Thread::wait_to_finish(probe_bake_thread); memdelete(probe_bake_thread); memdelete(probe_bake_sem); memdelete(probe_bake_mutex); #endif - - } diff --git a/servers/visual/visual_server_scene.h b/servers/visual/visual_server_scene.h index 01ad400b80..b02e6c820b 100644 --- a/servers/visual/visual_server_scene.h +++ b/servers/visual/visual_server_scene.h @@ -31,30 +31,27 @@ #include "servers/visual/rasterizer.h" -#include "geometry.h" #include "allocators.h" +#include "geometry.h" #include "octree.h" -#include "self_list.h" -#include "os/thread.h" #include "os/semaphore.h" #include "os/semaphore.h" +#include "os/thread.h" +#include "self_list.h" class VisualServerScene { public: - - enum { - MAX_INSTANCE_CULL=65536, - MAX_LIGHTS_CULLED=4096, - MAX_REFLECTION_PROBES_CULLED=4096, - MAX_ROOM_CULL=32, - MAX_EXTERIOR_PORTALS=128, + MAX_INSTANCE_CULL = 65536, + MAX_LIGHTS_CULLED = 4096, + MAX_REFLECTION_PROBES_CULLED = 4096, + MAX_ROOM_CULL = 32, + MAX_EXTERIOR_PORTALS = 128, }; uint64_t render_pass; - static VisualServerScene *singleton; #if 0 struct Portal { @@ -99,10 +96,9 @@ public: #endif - /* CAMERA API */ - struct Camera : public RID_Data { + struct Camera : public RID_Data { enum Type { PERSPECTIVE, @@ -110,7 +106,7 @@ public: }; Type type; float fov; - float znear,zfar; + float znear, zfar; float size; uint32_t visible_layers; bool vaspect; @@ -120,26 +116,25 @@ public: Camera() { - visible_layers=0xFFFFFFFF; - fov=60; - type=PERSPECTIVE; - znear=0.1; zfar=100; - size=1.0; - vaspect=false; - + visible_layers = 0xFFFFFFFF; + fov = 60; + type = PERSPECTIVE; + znear = 0.1; + zfar = 100; + size = 1.0; + vaspect = false; } }; mutable RID_Owner<Camera> camera_owner; virtual RID camera_create(); - virtual void camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far); - virtual void camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far); - virtual void camera_set_transform(RID p_camera,const Transform& p_transform); - virtual void camera_set_cull_mask(RID p_camera,uint32_t p_layers); - virtual void camera_set_environment(RID p_camera,RID p_env); - virtual void camera_set_use_vertical_aspect(RID p_camera,bool p_enable); - + virtual void camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far); + virtual void camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far); + virtual void camera_set_transform(RID p_camera, const Transform &p_transform); + virtual void camera_set_cull_mask(RID p_camera, uint32_t p_layers); + virtual void camera_set_environment(RID p_camera, RID p_env); + virtual void camera_set_use_vertical_aspect(RID p_camera, bool p_enable); /* @@ -173,56 +168,48 @@ public: }; */ - - /* SCENARIO API */ struct Instance; - struct Scenario : RID_Data { - + struct Scenario : RID_Data { VS::ScenarioDebugMode debug; RID self; // well wtf, balloon allocator is slower? - Octree<Instance,true> octree; + Octree<Instance, true> octree; - List<Instance*> directional_lights; + List<Instance *> directional_lights; RID environment; RID fallback_environment; RID reflection_probe_shadow_atlas; RID reflection_atlas; - SelfList<Instance>::List instances; - Scenario() { debug=VS::SCENARIO_DEBUG_DISABLED; } + Scenario() { debug = VS::SCENARIO_DEBUG_DISABLED; } }; mutable RID_Owner<Scenario> scenario_owner; - static void* _instance_pair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int); - static void _instance_unpair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int,void*); + static void *_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int); + static void _instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *); virtual RID scenario_create(); - virtual void scenario_set_debug(RID p_scenario,VS::ScenarioDebugMode p_debug_mode); + virtual void scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode); virtual void scenario_set_environment(RID p_scenario, RID p_environment); virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment); - virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv); - + virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv); /* INSTANCING API */ struct InstanceBaseData { - virtual ~InstanceBaseData() {} }; - - struct Instance : RasterizerScene::InstanceBase { RID self; @@ -237,7 +224,6 @@ public: SelfList<Instance> update_item; - Rect3 aabb; Rect3 transformed_aabb; float extra_margin; @@ -262,107 +248,99 @@ public: virtual void base_removed() { - singleton->instance_set_base(self,RID()); + singleton->instance_set_base(self, RID()); } virtual void base_changed() { - singleton->_instance_queue_update(this,true,true); + singleton->_instance_queue_update(this, true, true); } virtual void base_material_changed() { - singleton->_instance_queue_update(this,false,true); + singleton->_instance_queue_update(this, false, true); } + Instance() + : scenario_item(this), update_item(this), room_item(this) { - Instance() : scenario_item(this), update_item(this), room_item(this) { - - octree_id=0; - scenario=NULL; - - - update_aabb=false; - update_materials=false; + octree_id = 0; + scenario = NULL; - extra_margin=0; + update_aabb = false; + update_materials = false; + extra_margin = 0; - object_ID=0; - visible=true; + object_ID = 0; + visible = true; - lod_begin=0; - lod_end=0; - lod_begin_hysteresis=0; - lod_end_hysteresis=0; + lod_begin = 0; + lod_end = 0; + lod_begin_hysteresis = 0; + lod_end_hysteresis = 0; - room=NULL; - visible_in_all_rooms=false; - - - - last_render_pass=0; - last_frame_pass=0; - version=1; - base_data=NULL; + room = NULL; + visible_in_all_rooms = false; + last_render_pass = 0; + last_frame_pass = 0; + version = 1; + base_data = NULL; } ~Instance() { if (base_data) memdelete(base_data); - } }; SelfList<Instance>::List _instance_update_list; - void _instance_queue_update(Instance *p_instance,bool p_update_aabb,bool p_update_materials=false); - + void _instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials = false); struct InstanceGeometryData : public InstanceBaseData { - List<Instance*> lighting; + List<Instance *> lighting; bool lighting_dirty; bool can_cast_shadows; - List<Instance*> reflection_probes; + List<Instance *> reflection_probes; bool reflection_dirty; - List<Instance*> gi_probes; + List<Instance *> gi_probes; bool gi_probes_dirty; InstanceGeometryData() { - lighting_dirty=false; - reflection_dirty=true; - can_cast_shadows=true; - gi_probes_dirty=true; + lighting_dirty = false; + reflection_dirty = true; + can_cast_shadows = true; + gi_probes_dirty = true; } }; struct InstanceReflectionProbeData : public InstanceBaseData { - Instance *owner; struct PairInfo { - List<Instance*>::Element *L; //reflection iterator in geometry + List<Instance *>::Element *L; //reflection iterator in geometry Instance *geometry; }; List<PairInfo> geometries; - RID instance; bool reflection_dirty; SelfList<InstanceReflectionProbeData> update_list; int render_step; - InstanceReflectionProbeData() : update_list(this) { + InstanceReflectionProbeData() + : update_list(this) { - reflection_dirty=true; - render_step=-1; + reflection_dirty = true; + render_step = -1; } }; @@ -371,13 +349,13 @@ public: struct InstanceLightData : public InstanceBaseData { struct PairInfo { - List<Instance*>::Element *L; //light iterator in geometry + List<Instance *>::Element *L; //light iterator in geometry Instance *geometry; }; RID instance; uint64_t last_version; - List<Instance*>::Element *D; // directional light in scenario + List<Instance *>::Element *D; // directional light in scenario bool shadow_dirty; @@ -387,26 +365,25 @@ public: InstanceLightData() { - shadow_dirty=true; - D=NULL; - last_version=0; - baked_light=NULL; + shadow_dirty = true; + D = NULL; + last_version = 0; + baked_light = NULL; } }; struct InstanceGIProbeData : public InstanceBaseData { - Instance *owner; struct PairInfo { - List<Instance*>::Element *L; //gi probe iterator in geometry + List<Instance *>::Element *L; //gi probe iterator in geometry Instance *geometry; }; List<PairInfo> geometries; - Set<Instance*> lights; + Set<Instance *> lights; struct LightCache { @@ -419,29 +396,27 @@ public: float spot_angle; float spot_attenuation; - bool operator==(const LightCache& p_cache) { + bool operator==(const LightCache &p_cache) { - return (type==p_cache.type && - transform==p_cache.transform && - color==p_cache.color && - energy==p_cache.energy && - radius==p_cache.radius && - attenuation==p_cache.attenuation && - spot_angle==p_cache.spot_angle && - spot_attenuation==p_cache.spot_attenuation); + return (type == p_cache.type && + transform == p_cache.transform && + color == p_cache.color && + energy == p_cache.energy && + radius == p_cache.radius && + attenuation == p_cache.attenuation && + spot_angle == p_cache.spot_angle && + spot_attenuation == p_cache.spot_attenuation); } LightCache() { - type=VS::LIGHT_DIRECTIONAL; - energy=1.0; - radius=1.0; - attenuation=1.0; - spot_angle=1.0; - spot_attenuation=1.0; - + type = VS::LIGHT_DIRECTIONAL; + energy = 1.0; + radius = 1.0; + attenuation = 1.0; + spot_angle = 1.0; + spot_attenuation = 1.0; } - }; struct LocalData { @@ -456,11 +431,10 @@ public: uint8_t alpha[8]; //alpha block is pre-computed }; - struct Dynamic { - Map<RID,LightCache> light_cache; - Map<RID,LightCache> light_cache_changes; + Map<RID, LightCache> light_cache; + Map<RID, LightCache> light_cache_changes; PoolVector<int> light_data; PoolVector<LocalData> local_data; Vector<Vector<uint32_t> > level_cell_lists; @@ -469,8 +443,8 @@ public: int bake_dynamic_range; RasterizerStorage::GIProbeCompression compression; - Vector< PoolVector<uint8_t> > mipmaps_3d; - Vector< PoolVector<CompBlockS3TC> > mipmaps_s3tc; //for s3tc + Vector<PoolVector<uint8_t> > mipmaps_3d; + Vector<PoolVector<CompBlockS3TC> > mipmaps_s3tc; //for s3tc int updating_stage; float propagate; @@ -481,26 +455,22 @@ public: } dynamic; - RID probe_instance; - bool invalid; uint32_t base_version; SelfList<InstanceGIProbeData> update_element; - InstanceGIProbeData() : update_element(this) { - invalid=true; - base_version=0; + InstanceGIProbeData() + : update_element(this) { + invalid = true; + base_version = 0; } - }; - SelfList<InstanceGIProbeData>::List gi_probe_update_list; - Instance *instance_cull_result[MAX_INSTANCE_CULL]; Instance *instance_shadow_cull_result[MAX_INSTANCE_CULL]; //used for generating shadowmaps Instance *light_cull_result[MAX_LIGHTS_CULLED]; @@ -509,53 +479,47 @@ public: RID reflection_probe_instance_cull_result[MAX_REFLECTION_PROBES_CULLED]; int reflection_probe_cull_count; - RID_Owner<Instance> instance_owner; - // from can be mesh, light, area and portal so far. + // from can be mesh, light, area and portal so far. virtual RID instance_create(); // from can be mesh, light, poly, area and portal so far. virtual void instance_set_base(RID p_instance, RID p_base); // from can be mesh, light, poly, area and portal so far. virtual void instance_set_scenario(RID p_instance, RID p_scenario); // from can be mesh, light, poly, area and portal so far. virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask); - virtual void instance_set_transform(RID p_instance, const Transform& p_transform); - virtual void instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID); - virtual void instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight); - virtual void instance_set_surface_material(RID p_instance,int p_surface, RID p_material); - virtual void instance_set_visible(RID p_instance,bool p_visible); - + virtual void instance_set_transform(RID p_instance, const Transform &p_transform); + virtual void instance_attach_object_instance_ID(RID p_instance, ObjectID p_ID); + virtual void instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight); + virtual void instance_set_surface_material(RID p_instance, int p_surface, RID p_material); + virtual void instance_set_visible(RID p_instance, bool p_visible); - virtual void instance_attach_skeleton(RID p_instance,RID p_skeleton); - virtual void instance_set_exterior( RID p_instance, bool p_enabled ); - virtual void instance_set_room( RID p_instance, RID p_room ); - - virtual void instance_set_extra_visibility_margin( RID p_instance, real_t p_margin ); + virtual void instance_attach_skeleton(RID p_instance, RID p_skeleton); + virtual void instance_set_exterior(RID p_instance, bool p_enabled); + virtual void instance_set_room(RID p_instance, RID p_room); + virtual void instance_set_extra_visibility_margin(RID p_instance, real_t p_margin); // don't use these in a game! - virtual Vector<ObjectID> instances_cull_aabb(const Rect3& p_aabb, RID p_scenario=RID()) const; - virtual Vector<ObjectID> instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario=RID()) const; - virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario=RID()) const; - + virtual Vector<ObjectID> instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario = RID()) const; + virtual Vector<ObjectID> instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const; + virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario = RID()) const; - virtual void instance_geometry_set_flag(RID p_instance,VS::InstanceFlags p_flags,bool p_enabled); + virtual void instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled); virtual void instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting); virtual void instance_geometry_set_material_override(RID p_instance, RID p_material); - - virtual void instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin); - virtual void instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance); - + virtual void instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin); + virtual void instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance); _FORCE_INLINE_ void _update_instance(Instance *p_instance); _FORCE_INLINE_ void _update_instance_aabb(Instance *p_instance); _FORCE_INLINE_ void _update_dirty_instance(Instance *p_instance); - _FORCE_INLINE_ void _light_instance_update_shadow(Instance *p_instance,const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_shadow_atlas,Scenario* p_scenario); + _FORCE_INLINE_ void _light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario); - void _render_scene(const Transform p_cam_transform, const CameraMatrix& p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass); + void _render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass); - void render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas); + void render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas); void update_dirty_instances(); //probes @@ -570,7 +534,6 @@ public: uint32_t leaf_cell_count; }; - struct GIProbeDataCell { uint32_t children[8]; @@ -587,27 +550,26 @@ public: }; void _gi_probe_bake_thread(); - static void _gi_probe_bake_threads(void*); + static void _gi_probe_bake_threads(void *); volatile bool probe_bake_thread_exit; Thread *probe_bake_thread; Semaphore *probe_bake_sem; Mutex *probe_bake_mutex; - List<Instance*> probe_bake_list; + List<Instance *> probe_bake_list; - bool _render_reflection_probe_step(Instance* p_instance,int p_step); - void _gi_probe_fill_local_data(int p_idx,int p_level,int p_x,int p_y,int p_z,const GIProbeDataCell* p_cell,const GIProbeDataHeader *p_header,InstanceGIProbeData::LocalData *p_local_data,Vector<uint32_t> *prev_cell); + bool _render_reflection_probe_step(Instance *p_instance, int p_step); + void _gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell); - _FORCE_INLINE_ uint32_t _gi_bake_find_cell(const GIProbeDataCell *cells,int x,int y, int z,int p_cell_subdiv); - void _bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell* p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate); - void _bake_gi_probe_light(const GIProbeDataHeader *header,const GIProbeDataCell *cells,InstanceGIProbeData::LocalData *local_data,const uint32_t *leaves,int p_leaf_count, const InstanceGIProbeData::LightCache& light_cache,int p_sign); + _FORCE_INLINE_ uint32_t _gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv); + void _bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate); + void _bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int p_leaf_count, const InstanceGIProbeData::LightCache &light_cache, int p_sign); void _bake_gi_probe(Instance *p_probe); bool _check_gi_probe(Instance *p_gi_probe); void _setup_gi_probe(Instance *p_instance); void render_probes(); - bool free(RID p_rid); VisualServerScene(); diff --git a/servers/visual/visual_server_viewport.cpp b/servers/visual/visual_server_viewport.cpp index a88fb69e93..7b8a725c5a 100644 --- a/servers/visual/visual_server_viewport.cpp +++ b/servers/visual/visual_server_viewport.cpp @@ -27,16 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "visual_server_viewport.h" -#include "visual_server_global.h" +#include "global_config.h" #include "visual_server_canvas.h" +#include "visual_server_global.h" #include "visual_server_scene.h" -#include "global_config.h" - - void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { - /* Camera should always be BEFORE any other 3D */ +/* Camera should always be BEFORE any other 3D */ #if 0 bool scenario_draw_canvas_bg=false; int scenario_canvas_max_layer=0; @@ -82,126 +80,117 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { } #endif - if (p_viewport->clear_mode!=VS::VIEWPORT_CLEAR_NEVER) { + if (p_viewport->clear_mode != VS::VIEWPORT_CLEAR_NEVER) { VSG::rasterizer->clear_render_target(clear_color); - if (p_viewport->clear_mode==VS::VIEWPORT_CLEAR_ONLY_NEXT_FRAME) { - p_viewport->clear_mode=VS::VIEWPORT_CLEAR_NEVER; + if (p_viewport->clear_mode == VS::VIEWPORT_CLEAR_ONLY_NEXT_FRAME) { + p_viewport->clear_mode = VS::VIEWPORT_CLEAR_NEVER; } } - if (!p_viewport->disable_3d && p_viewport->camera.is_valid()) { - VSG::scene->render_camera(p_viewport->camera,p_viewport->scenario,p_viewport->size,p_viewport->shadow_atlas); + VSG::scene->render_camera(p_viewport->camera, p_viewport->scenario, p_viewport->size, p_viewport->shadow_atlas); } if (!p_viewport->hide_canvas) { - int i=0; + int i = 0; - Map<Viewport::CanvasKey,Viewport::CanvasData*> canvas_map; + Map<Viewport::CanvasKey, Viewport::CanvasData *> canvas_map; - Rect2 clip_rect(0,0,p_viewport->size.x,p_viewport->size.y); - RasterizerCanvas::Light *lights=NULL; - RasterizerCanvas::Light *lights_with_shadow=NULL; - RasterizerCanvas::Light *lights_with_mask=NULL; + Rect2 clip_rect(0, 0, p_viewport->size.x, p_viewport->size.y); + RasterizerCanvas::Light *lights = NULL; + RasterizerCanvas::Light *lights_with_shadow = NULL; + RasterizerCanvas::Light *lights_with_mask = NULL; Rect2 shadow_rect; - int light_count=0; + int light_count = 0; - for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) { + for (Map<RID, Viewport::CanvasData>::Element *E = p_viewport->canvas_map.front(); E; E = E->next()) { Transform2D xf = p_viewport->global_transform * E->get().transform; - VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get().canvas); + VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas *>(E->get().canvas); //find lights in canvas + for (Set<RasterizerCanvas::Light *>::Element *F = canvas->lights.front(); F; F = F->next()) { - for(Set<RasterizerCanvas::Light*>::Element *F=canvas->lights.front();F;F=F->next()) { - - - RasterizerCanvas::Light* cl=F->get(); + RasterizerCanvas::Light *cl = F->get(); if (cl->enabled && cl->texture.is_valid()) { //not super efficient.. - Size2 tsize(VSG::storage->texture_get_width(cl->texture),VSG::storage->texture_get_height(cl->texture)); - tsize*=cl->scale; + Size2 tsize(VSG::storage->texture_get_width(cl->texture), VSG::storage->texture_get_height(cl->texture)); + tsize *= cl->scale; - Vector2 offset=tsize/2.0; - cl->rect_cache=Rect2(-offset+cl->texture_offset,tsize); - cl->xform_cache=xf * cl->xform; + Vector2 offset = tsize / 2.0; + cl->rect_cache = Rect2(-offset + cl->texture_offset, tsize); + cl->xform_cache = xf * cl->xform; + if (clip_rect.intersects_transformed(cl->xform_cache, cl->rect_cache)) { - if (clip_rect.intersects_transformed(cl->xform_cache,cl->rect_cache)) { - - cl->filter_next_ptr=lights; - lights=cl; - cl->texture_cache=NULL; + cl->filter_next_ptr = lights; + lights = cl; + cl->texture_cache = NULL; Transform2D scale; scale.scale(cl->rect_cache.size); - scale.elements[2]=cl->rect_cache.pos; + scale.elements[2] = cl->rect_cache.pos; cl->light_shader_xform = (cl->xform_cache * scale).affine_inverse(); - cl->light_shader_pos=cl->xform_cache[2]; + cl->light_shader_pos = cl->xform_cache[2]; if (cl->shadow_buffer.is_valid()) { - cl->shadows_next_ptr=lights_with_shadow; - if (lights_with_shadow==NULL) { + cl->shadows_next_ptr = lights_with_shadow; + if (lights_with_shadow == NULL) { shadow_rect = cl->xform_cache.xform(cl->rect_cache); } else { - shadow_rect=shadow_rect.merge( cl->xform_cache.xform(cl->rect_cache) ); + shadow_rect = shadow_rect.merge(cl->xform_cache.xform(cl->rect_cache)); } - lights_with_shadow=cl; - cl->radius_cache=cl->rect_cache.size.length(); - + lights_with_shadow = cl; + cl->radius_cache = cl->rect_cache.size.length(); } - if (cl->mode==VS::CANVAS_LIGHT_MODE_MASK) { - cl->mask_next_ptr=lights_with_mask; - lights_with_mask=cl; + if (cl->mode == VS::CANVAS_LIGHT_MODE_MASK) { + cl->mask_next_ptr = lights_with_mask; + lights_with_mask = cl; } light_count++; } - VSG::canvas_render->light_internal_update(cl->light_internal,cl); - + VSG::canvas_render->light_internal_update(cl->light_internal, cl); } } //print_line("lights: "+itos(light_count)); - canvas_map[ Viewport::CanvasKey( E->key(), E->get().layer) ]=&E->get(); - + canvas_map[Viewport::CanvasKey(E->key(), E->get().layer)] = &E->get(); } if (lights_with_shadow) { //update shadows if any - RasterizerCanvas::LightOccluderInstance * occluders=NULL; + RasterizerCanvas::LightOccluderInstance *occluders = NULL; //make list of occluders - for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) { + for (Map<RID, Viewport::CanvasData>::Element *E = p_viewport->canvas_map.front(); E; E = E->next()) { - VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get().canvas); + VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas *>(E->get().canvas); Transform2D xf = p_viewport->global_transform * E->get().transform; - - for(Set<RasterizerCanvas::LightOccluderInstance*>::Element *F=canvas->occluders.front();F;F=F->next()) { + for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *F = canvas->occluders.front(); F; F = F->next()) { if (!F->get()->enabled) continue; F->get()->xform_cache = xf * F->get()->xform; - if (shadow_rect.intersects_transformed(F->get()->xform_cache,F->get()->aabb_cache)) { - - F->get()->next=occluders; - occluders=F->get(); + if (shadow_rect.intersects_transformed(F->get()->xform_cache, F->get()->aabb_cache)) { + F->get()->next = occluders; + occluders = F->get(); } } } //update the light shadowmaps with them - RasterizerCanvas::Light *light=lights_with_shadow; - while(light) { + RasterizerCanvas::Light *light = lights_with_shadow; + while (light) { - VSG::canvas_render->canvas_light_shadow_buffer_update(light->shadow_buffer,light->xform_cache.affine_inverse(),light->item_mask,light->radius_cache/1000.0,light->radius_cache*1.1,occluders,&light->shadow_matrix_cache); - light=light->shadows_next_ptr; + VSG::canvas_render->canvas_light_shadow_buffer_update(light->shadow_buffer, light->xform_cache.affine_inverse(), light->item_mask, light->radius_cache / 1000.0, light->radius_cache * 1.1, occluders, &light->shadow_matrix_cache); + light = light->shadows_next_ptr; } //VSG::canvas_render->reset_canvas(); @@ -209,7 +198,6 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { VSG::rasterizer->restore_render_target(); - #if 0 if (scenario_draw_canvas_bg && canvas_map.front() && canvas_map.front()->key().layer>scenario_canvas_max_layer) { @@ -219,27 +207,26 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { } #endif + for (Map<Viewport::CanvasKey, Viewport::CanvasData *>::Element *E = canvas_map.front(); E; E = E->next()) { - for (Map<Viewport::CanvasKey,Viewport::CanvasData*>::Element *E=canvas_map.front();E;E=E->next()) { - - VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get()->canvas); + VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas *>(E->get()->canvas); //print_line("canvas "+itos(i)+" size: "+itos(I->get()->canvas->child_items.size())); //print_line("GT "+p_viewport->global_transform+". CT: "+E->get()->transform); Transform2D xform = p_viewport->global_transform * E->get()->transform; - RasterizerCanvas::Light *canvas_lights=NULL; + RasterizerCanvas::Light *canvas_lights = NULL; - RasterizerCanvas::Light *ptr=lights; - while(ptr) { - if (E->get()->layer>=ptr->layer_min && E->get()->layer<=ptr->layer_max) { - ptr->next_ptr=canvas_lights; - canvas_lights=ptr; + RasterizerCanvas::Light *ptr = lights; + while (ptr) { + if (E->get()->layer >= ptr->layer_min && E->get()->layer <= ptr->layer_max) { + ptr->next_ptr = canvas_lights; + canvas_lights = ptr; } - ptr=ptr->filter_next_ptr; + ptr = ptr->filter_next_ptr; } - VSG::canvas->render_canvas( canvas,xform,canvas_lights,lights_with_mask,clip_rect ); + VSG::canvas->render_canvas(canvas, xform, canvas_lights, lights_with_mask, clip_rect); i++; #if 0 if (scenario_draw_canvas_bg && E->key().layer>=scenario_canvas_max_layer) { @@ -247,8 +234,6 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { scenario_draw_canvas_bg=false; } #endif - - } #if 0 if (scenario_draw_canvas_bg) { @@ -259,33 +244,28 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { //VSG::canvas_render->canvas_debug_viewport_shadows(lights_with_shadow); } - - - } void VisualServerViewport::draw_viewports() { //sort viewports - //draw viewports - clear_color=GLOBAL_GET("rendering/viewport/default_clear_color"); - + clear_color = GLOBAL_GET("rendering/viewport/default_clear_color"); active_viewports.sort_custom<ViewportSort>(); - for(int i=0;i<active_viewports.size();i++) { + for (int i = 0; i < active_viewports.size(); i++) { Viewport *vp = active_viewports[i]; - if (vp->update_mode==VS::VIEWPORT_UPDATE_DISABLED) + if (vp->update_mode == VS::VIEWPORT_UPDATE_DISABLED) continue; - ERR_CONTINUE( !vp->render_target.is_valid() ); + ERR_CONTINUE(!vp->render_target.is_valid()); - bool visible = vp->viewport_to_screen_rect!=Rect2() || vp->update_mode==VS::VIEWPORT_UPDATE_ALWAYS || vp->update_mode==VS::VIEWPORT_UPDATE_ONCE; + bool visible = vp->viewport_to_screen_rect != Rect2() || vp->update_mode == VS::VIEWPORT_UPDATE_ALWAYS || vp->update_mode == VS::VIEWPORT_UPDATE_ONCE; if (!visible) continue; @@ -293,177 +273,161 @@ void VisualServerViewport::draw_viewports() { VSG::rasterizer->set_current_render_target(vp->render_target); _draw_viewport(vp); - if (vp->viewport_to_screen_rect!=Rect2()) { + if (vp->viewport_to_screen_rect != Rect2()) { //copy to screen if set as such VSG::rasterizer->set_current_render_target(RID()); - VSG::rasterizer->blit_render_target_to_screen(vp->render_target,vp->viewport_to_screen_rect,vp->viewport_to_screen); + VSG::rasterizer->blit_render_target_to_screen(vp->render_target, vp->viewport_to_screen_rect, vp->viewport_to_screen); } - if (vp->update_mode==VS::VIEWPORT_UPDATE_ONCE) { - vp->update_mode=VS::VIEWPORT_UPDATE_DISABLED; + if (vp->update_mode == VS::VIEWPORT_UPDATE_ONCE) { + vp->update_mode = VS::VIEWPORT_UPDATE_DISABLED; } } } - RID VisualServerViewport::viewport_create() { - Viewport * viewport = memnew( Viewport ); + Viewport *viewport = memnew(Viewport); RID rid = viewport_owner.make_rid(viewport); - viewport->self=rid; - viewport->hide_scenario=false; - viewport->hide_canvas=false; - viewport->render_target=VSG::storage->render_target_create(); - viewport->shadow_atlas=VSG::scene_render->shadow_atlas_create(); + viewport->self = rid; + viewport->hide_scenario = false; + viewport->hide_canvas = false; + viewport->render_target = VSG::storage->render_target_create(); + viewport->shadow_atlas = VSG::scene_render->shadow_atlas_create(); return rid; - } -void VisualServerViewport::viewport_set_size(RID p_viewport,int p_width,int p_height){ +void VisualServerViewport::viewport_set_size(RID p_viewport, int p_width, int p_height) { - ERR_FAIL_COND(p_width<0 && p_height<0); + ERR_FAIL_COND(p_width < 0 && p_height < 0); - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - - - viewport->size=Size2(p_width,p_height); - VSG::storage->render_target_set_size(viewport->render_target,p_width,p_height); - - + viewport->size = Size2(p_width, p_height); + VSG::storage->render_target_set_size(viewport->render_target, p_width, p_height); } -void VisualServerViewport::viewport_set_active(RID p_viewport,bool p_active) { +void VisualServerViewport::viewport_set_active(RID p_viewport, bool p_active) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); if (p_active) { - ERR_FAIL_COND(active_viewports.find(viewport)!=-1);//already active + ERR_FAIL_COND(active_viewports.find(viewport) != -1); //already active active_viewports.push_back(viewport); } else { active_viewports.erase(viewport); } - - } -void VisualServerViewport::viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport) { +void VisualServerViewport::viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->parent=p_parent_viewport; + viewport->parent = p_parent_viewport; } -void VisualServerViewport::viewport_set_clear_mode(RID p_viewport,VS::ViewportClearMode p_clear_mode) { +void VisualServerViewport::viewport_set_clear_mode(RID p_viewport, VS::ViewportClearMode p_clear_mode) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->clear_mode=p_clear_mode; - + viewport->clear_mode = p_clear_mode; } +void VisualServerViewport::viewport_attach_to_screen(RID p_viewport, const Rect2 &p_rect, int p_screen) { -void VisualServerViewport::viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect,int p_screen){ - - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->viewport_to_screen_rect=p_rect; - viewport->viewport_to_screen=p_screen; + viewport->viewport_to_screen_rect = p_rect; + viewport->viewport_to_screen = p_screen; } -void VisualServerViewport::viewport_detach(RID p_viewport){ +void VisualServerViewport::viewport_detach(RID p_viewport) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->viewport_to_screen_rect=Rect2(); - viewport->viewport_to_screen=0; - + viewport->viewport_to_screen_rect = Rect2(); + viewport->viewport_to_screen = 0; } -void VisualServerViewport::viewport_set_update_mode(RID p_viewport,VS::ViewportUpdateMode p_mode){ +void VisualServerViewport::viewport_set_update_mode(RID p_viewport, VS::ViewportUpdateMode p_mode) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->update_mode=p_mode; - + viewport->update_mode = p_mode; } -void VisualServerViewport::viewport_set_vflip(RID p_viewport,bool p_enable){ +void VisualServerViewport::viewport_set_vflip(RID p_viewport, bool p_enable) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_VFLIP,p_enable); - + VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_VFLIP, p_enable); } -RID VisualServerViewport::viewport_get_texture(RID p_viewport) const{ +RID VisualServerViewport::viewport_get_texture(RID p_viewport) const { - const Viewport * viewport = viewport_owner.getornull(p_viewport); - ERR_FAIL_COND_V(!viewport,RID()); + const Viewport *viewport = viewport_owner.getornull(p_viewport); + ERR_FAIL_COND_V(!viewport, RID()); return VSG::storage->render_target_get_texture(viewport->render_target); - } -void VisualServerViewport::viewport_set_hide_scenario(RID p_viewport,bool p_hide){ +void VisualServerViewport::viewport_set_hide_scenario(RID p_viewport, bool p_hide) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->hide_scenario=p_hide; + viewport->hide_scenario = p_hide; } -void VisualServerViewport::viewport_set_hide_canvas(RID p_viewport,bool p_hide){ +void VisualServerViewport::viewport_set_hide_canvas(RID p_viewport, bool p_hide) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->hide_canvas=p_hide; + viewport->hide_canvas = p_hide; } -void VisualServerViewport::viewport_set_disable_environment(RID p_viewport,bool p_disable){ +void VisualServerViewport::viewport_set_disable_environment(RID p_viewport, bool p_disable) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - - viewport->disable_environment=p_disable; + viewport->disable_environment = p_disable; } -void VisualServerViewport::viewport_set_disable_3d(RID p_viewport,bool p_disable){ +void VisualServerViewport::viewport_set_disable_3d(RID p_viewport, bool p_disable) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - - viewport->disable_3d=p_disable; - VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_NO_3D,p_disable); + viewport->disable_3d = p_disable; + VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_NO_3D, p_disable); } -void VisualServerViewport::viewport_attach_camera(RID p_viewport,RID p_camera){ +void VisualServerViewport::viewport_attach_camera(RID p_viewport, RID p_camera) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->camera=p_camera; + viewport->camera = p_camera; } -void VisualServerViewport::viewport_set_scenario(RID p_viewport,RID p_scenario){ +void VisualServerViewport::viewport_set_scenario(RID p_viewport, RID p_scenario) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->scenario=p_scenario; + viewport->scenario = p_scenario; } -void VisualServerViewport::viewport_attach_canvas(RID p_viewport,RID p_canvas){ +void VisualServerViewport::viewport_attach_canvas(RID p_viewport, RID p_canvas) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(viewport->canvas_map.has(p_canvas)); @@ -471,15 +435,14 @@ void VisualServerViewport::viewport_attach_canvas(RID p_viewport,RID p_canvas){ ERR_FAIL_COND(!canvas); canvas->viewports.insert(p_viewport); - viewport->canvas_map[p_canvas]=Viewport::CanvasData(); - viewport->canvas_map[p_canvas].layer=0; - viewport->canvas_map[p_canvas].canvas=canvas; - + viewport->canvas_map[p_canvas] = Viewport::CanvasData(); + viewport->canvas_map[p_canvas].layer = 0; + viewport->canvas_map[p_canvas].canvas = canvas; } -void VisualServerViewport::viewport_remove_canvas(RID p_viewport,RID p_canvas){ +void VisualServerViewport::viewport_remove_canvas(RID p_viewport, RID p_canvas) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VisualServerCanvas::Canvas *canvas = VSG::canvas->canvas_owner.getornull(p_canvas); @@ -487,110 +450,97 @@ void VisualServerViewport::viewport_remove_canvas(RID p_viewport,RID p_canvas){ viewport->canvas_map.erase(p_canvas); canvas->viewports.erase(p_viewport); - } -void VisualServerViewport::viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset){ +void VisualServerViewport::viewport_set_canvas_transform(RID p_viewport, RID p_canvas, const Transform2D &p_offset) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(!viewport->canvas_map.has(p_canvas)); - viewport->canvas_map[p_canvas].transform=p_offset; - + viewport->canvas_map[p_canvas].transform = p_offset; } -void VisualServerViewport::viewport_set_transparent_background(RID p_viewport,bool p_enabled){ +void VisualServerViewport::viewport_set_transparent_background(RID p_viewport, bool p_enabled) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_TRANSPARENT,p_enabled); - + VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_TRANSPARENT, p_enabled); } -void VisualServerViewport::viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform){ +void VisualServerViewport::viewport_set_global_canvas_transform(RID p_viewport, const Transform2D &p_transform) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->global_transform=p_transform; - + viewport->global_transform = p_transform; } -void VisualServerViewport::viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer){ +void VisualServerViewport::viewport_set_canvas_layer(RID p_viewport, RID p_canvas, int p_layer) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(!viewport->canvas_map.has(p_canvas)); - viewport->canvas_map[p_canvas].layer=p_layer; - + viewport->canvas_map[p_canvas].layer = p_layer; } -void VisualServerViewport::viewport_set_shadow_atlas_size(RID p_viewport,int p_size) { +void VisualServerViewport::viewport_set_shadow_atlas_size(RID p_viewport, int p_size) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - viewport->shadow_atlas_size=p_size; - - VSG::scene_render->shadow_atlas_set_size( viewport->shadow_atlas, viewport->shadow_atlas_size); + viewport->shadow_atlas_size = p_size; + VSG::scene_render->shadow_atlas_set_size(viewport->shadow_atlas, viewport->shadow_atlas_size); } -void VisualServerViewport::viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv) { +void VisualServerViewport::viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport, int p_quadrant, int p_subdiv) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - VSG::scene_render->shadow_atlas_set_quadrant_subdivision( viewport->shadow_atlas, p_quadrant, p_subdiv); - + VSG::scene_render->shadow_atlas_set_quadrant_subdivision(viewport->shadow_atlas, p_quadrant, p_subdiv); } -void VisualServerViewport::viewport_set_msaa(RID p_viewport,VS::ViewportMSAA p_msaa) { +void VisualServerViewport::viewport_set_msaa(RID p_viewport, VS::ViewportMSAA p_msaa) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - VSG::storage->render_target_set_msaa(viewport->render_target,p_msaa); + VSG::storage->render_target_set_msaa(viewport->render_target, p_msaa); } -void VisualServerViewport::viewport_set_hdr(RID p_viewport,bool p_enabled) { +void VisualServerViewport::viewport_set_hdr(RID p_viewport, bool p_enabled) { - Viewport * viewport = viewport_owner.getornull(p_viewport); + Viewport *viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); - VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_HDR,p_enabled); - + VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_HDR, p_enabled); } bool VisualServerViewport::free(RID p_rid) { if (viewport_owner.owns(p_rid)) { - Viewport * viewport = viewport_owner.getornull(p_rid); - + Viewport *viewport = viewport_owner.getornull(p_rid); - VSG::storage->free( viewport->render_target ); - VSG::scene_render->free( viewport->shadow_atlas ); + VSG::storage->free(viewport->render_target); + VSG::scene_render->free(viewport->shadow_atlas); - while(viewport->canvas_map.front()) { - viewport_remove_canvas(p_rid,viewport->canvas_map.front()->key()); + while (viewport->canvas_map.front()) { + viewport_remove_canvas(p_rid, viewport->canvas_map.front()->key()); } - viewport_set_scenario(p_rid,RID()); + viewport_set_scenario(p_rid, RID()); active_viewports.erase(viewport); viewport_owner.free(p_rid); memdelete(viewport); - return true; } return false; - } -VisualServerViewport::VisualServerViewport() -{ - +VisualServerViewport::VisualServerViewport() { } diff --git a/servers/visual/visual_server_viewport.h b/servers/visual/visual_server_viewport.h index 1cee90b803..53ad6bde2b 100644 --- a/servers/visual/visual_server_viewport.h +++ b/servers/visual/visual_server_viewport.h @@ -29,20 +29,15 @@ #ifndef VISUALSERVERVIEWPORT_H #define VISUALSERVERVIEWPORT_H -#include "servers/visual_server.h" #include "rasterizer.h" #include "self_list.h" +#include "servers/visual_server.h" -class VisualServerViewport { +class VisualServerViewport { public: - struct CanvasBase : public RID_Data { - - }; - - struct Viewport : public RID_Data { RID self; @@ -67,7 +62,6 @@ public: RID shadow_atlas; int shadow_atlas_size; - VS::ViewportClearMode clear_mode; bool rendered_in_prev_frame; @@ -76,9 +70,15 @@ public: int layer; RID canvas; - bool operator<(const CanvasKey& p_canvas) const { if (layer==p_canvas.layer) return canvas < p_canvas.canvas; return layer<p_canvas.layer; } - CanvasKey() { layer=0; } - CanvasKey(const RID& p_canvas, int p_layer) { canvas=p_canvas; layer=p_layer; } + bool operator<(const CanvasKey &p_canvas) const { + if (layer == p_canvas.layer) return canvas < p_canvas.canvas; + return layer < p_canvas.layer; + } + CanvasKey() { layer = 0; } + CanvasKey(const RID &p_canvas, int p_layer) { + canvas = p_canvas; + layer = p_layer; + } }; struct CanvasData { @@ -90,83 +90,79 @@ public: Transform2D global_transform; - Map<RID,CanvasData> canvas_map; + Map<RID, CanvasData> canvas_map; Viewport() { - update_mode=VS::VIEWPORT_UPDATE_WHEN_VISIBLE; - clear_mode=VS::VIEWPORT_CLEAR_ALWAYS; - rendered_in_prev_frame=false; - disable_environment=false; - viewport_to_screen=0; - shadow_atlas_size=0; - disable_3d=false; - + update_mode = VS::VIEWPORT_UPDATE_WHEN_VISIBLE; + clear_mode = VS::VIEWPORT_CLEAR_ALWAYS; + rendered_in_prev_frame = false; + disable_environment = false; + viewport_to_screen = 0; + shadow_atlas_size = 0; + disable_3d = false; } }; mutable RID_Owner<Viewport> viewport_owner; - struct ViewportSort { - _FORCE_INLINE_ bool operator()(const Viewport*p_left,const Viewport* p_right) const { + _FORCE_INLINE_ bool operator()(const Viewport *p_left, const Viewport *p_right) const { - bool left_to_screen = p_left->viewport_to_screen_rect.size!=Size2(); - bool right_to_screen = p_right->viewport_to_screen_rect.size!=Size2(); + bool left_to_screen = p_left->viewport_to_screen_rect.size != Size2(); + bool right_to_screen = p_right->viewport_to_screen_rect.size != Size2(); - if (left_to_screen==right_to_screen) { + if (left_to_screen == right_to_screen) { - return p_left->parent==p_right->self; + return p_left->parent == p_right->self; } else { return right_to_screen; } } }; + Vector<Viewport *> active_viewports; - Vector<Viewport*> active_viewports; private: Color clear_color; void _draw_viewport(Viewport *p_viewport); -public: - +public: RID viewport_create(); - void viewport_set_size(RID p_viewport,int p_width,int p_height); + void viewport_set_size(RID p_viewport, int p_width, int p_height); - void viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect=Rect2(),int p_screen=0); + void viewport_attach_to_screen(RID p_viewport, const Rect2 &p_rect = Rect2(), int p_screen = 0); void viewport_detach(RID p_viewport); - void viewport_set_active(RID p_viewport,bool p_active); - void viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport); - void viewport_set_update_mode(RID p_viewport,VS::ViewportUpdateMode p_mode); - void viewport_set_vflip(RID p_viewport,bool p_enable); - + void viewport_set_active(RID p_viewport, bool p_active); + void viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport); + void viewport_set_update_mode(RID p_viewport, VS::ViewportUpdateMode p_mode); + void viewport_set_vflip(RID p_viewport, bool p_enable); - void viewport_set_clear_mode(RID p_viewport,VS::ViewportClearMode p_clear_mode); + void viewport_set_clear_mode(RID p_viewport, VS::ViewportClearMode p_clear_mode); RID viewport_get_texture(RID p_viewport) const; - void viewport_set_hide_scenario(RID p_viewport,bool p_hide); - void viewport_set_hide_canvas(RID p_viewport,bool p_hide); - void viewport_set_disable_environment(RID p_viewport,bool p_disable); - void viewport_set_disable_3d(RID p_viewport,bool p_disable); + void viewport_set_hide_scenario(RID p_viewport, bool p_hide); + void viewport_set_hide_canvas(RID p_viewport, bool p_hide); + void viewport_set_disable_environment(RID p_viewport, bool p_disable); + void viewport_set_disable_3d(RID p_viewport, bool p_disable); - void viewport_attach_camera(RID p_viewport,RID p_camera); - void viewport_set_scenario(RID p_viewport,RID p_scenario); - void viewport_attach_canvas(RID p_viewport,RID p_canvas); - void viewport_remove_canvas(RID p_viewport,RID p_canvas); - void viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset); - void viewport_set_transparent_background(RID p_viewport,bool p_enabled); + void viewport_attach_camera(RID p_viewport, RID p_camera); + void viewport_set_scenario(RID p_viewport, RID p_scenario); + void viewport_attach_canvas(RID p_viewport, RID p_canvas); + void viewport_remove_canvas(RID p_viewport, RID p_canvas); + void viewport_set_canvas_transform(RID p_viewport, RID p_canvas, const Transform2D &p_offset); + void viewport_set_transparent_background(RID p_viewport, bool p_enabled); - void viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform); - void viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer); + void viewport_set_global_canvas_transform(RID p_viewport, const Transform2D &p_transform); + void viewport_set_canvas_layer(RID p_viewport, RID p_canvas, int p_layer); - void viewport_set_shadow_atlas_size(RID p_viewport,int p_size); - void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv); + void viewport_set_shadow_atlas_size(RID p_viewport, int p_size); + void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport, int p_quadrant, int p_subdiv); - void viewport_set_msaa(RID p_viewport,VS::ViewportMSAA p_msaa); - void viewport_set_hdr(RID p_viewport,bool p_enabled); + void viewport_set_msaa(RID p_viewport, VS::ViewportMSAA p_msaa); + void viewport_set_hdr(RID p_viewport, bool p_enabled); void draw_viewports(); diff --git a/servers/visual_server.cpp b/servers/visual_server.cpp index 5d231d208e..a28c409b97 100644 --- a/servers/visual_server.cpp +++ b/servers/visual_server.cpp @@ -30,23 +30,20 @@ #include "global_config.h" #include "method_bind_ext.inc" -VisualServer *VisualServer::singleton=NULL; -VisualServer* (*VisualServer::create_func)()=NULL; +VisualServer *VisualServer::singleton = NULL; +VisualServer *(*VisualServer::create_func)() = NULL; VisualServer *VisualServer::get_singleton() { return singleton; } - - PoolVector<String> VisualServer::_shader_get_param_list(RID p_shader) const { -//remove at some point + //remove at some point PoolVector<String> pl; - #if 0 List<StringName> params; shader_get_param_list(p_shader,¶ms); @@ -62,7 +59,7 @@ PoolVector<String> VisualServer::_shader_get_param_list(RID p_shader) const { VisualServer *VisualServer::create() { - ERR_FAIL_COND_V(singleton,NULL); + ERR_FAIL_COND_V(singleton, NULL); if (create_func) return create_func(); @@ -70,13 +67,13 @@ VisualServer *VisualServer::create() { return NULL; } -RID VisualServer::texture_create_from_image(const Image& p_image,uint32_t p_flags) { +RID VisualServer::texture_create_from_image(const Image &p_image, uint32_t p_flags) { RID texture = texture_create(); - texture_allocate(texture,p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags); //if it has mipmaps, use, else generate - ERR_FAIL_COND_V(!texture.is_valid(),texture); + texture_allocate(texture, p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags); //if it has mipmaps, use, else generate + ERR_FAIL_COND_V(!texture.is_valid(), texture); - texture_set_data(texture, p_image ); + texture_set_data(texture, p_image); return texture; } @@ -89,41 +86,40 @@ RID VisualServer::get_test_texture() { #define TEST_TEXTURE_SIZE 256 - PoolVector<uint8_t> test_data; - test_data.resize(TEST_TEXTURE_SIZE*TEST_TEXTURE_SIZE*3); + test_data.resize(TEST_TEXTURE_SIZE * TEST_TEXTURE_SIZE * 3); { - PoolVector<uint8_t>::Write w=test_data.write(); + PoolVector<uint8_t>::Write w = test_data.write(); - for (int x=0;x<TEST_TEXTURE_SIZE;x++) { + for (int x = 0; x < TEST_TEXTURE_SIZE; x++) { - for (int y=0;y<TEST_TEXTURE_SIZE;y++) { + for (int y = 0; y < TEST_TEXTURE_SIZE; y++) { Color c; - int r=255-(x+y)/2; + int r = 255 - (x + y) / 2; - if ((x%(TEST_TEXTURE_SIZE/8))<2 ||(y%(TEST_TEXTURE_SIZE/8))<2) { + if ((x % (TEST_TEXTURE_SIZE / 8)) < 2 || (y % (TEST_TEXTURE_SIZE / 8)) < 2) { - c.r=y; - c.g=r; - c.b=x; + c.r = y; + c.g = r; + c.b = x; } else { - c.r=r; - c.g=x; - c.b=y; + c.r = r; + c.g = x; + c.b = y; } - w[(y*TEST_TEXTURE_SIZE+x)*3+0]=uint8_t(CLAMP(c.r*255,0,255)); - w[(y*TEST_TEXTURE_SIZE+x)*3+1]=uint8_t(CLAMP(c.g*255,0,255)); - w[(y*TEST_TEXTURE_SIZE+x)*3+2]=uint8_t(CLAMP(c.b*255,0,255)); + w[(y * TEST_TEXTURE_SIZE + x) * 3 + 0] = uint8_t(CLAMP(c.r * 255, 0, 255)); + w[(y * TEST_TEXTURE_SIZE + x) * 3 + 1] = uint8_t(CLAMP(c.g * 255, 0, 255)); + w[(y * TEST_TEXTURE_SIZE + x) * 3 + 2] = uint8_t(CLAMP(c.b * 255, 0, 255)); } } } - Image data(TEST_TEXTURE_SIZE,TEST_TEXTURE_SIZE,false,Image::FORMAT_RGB8,test_data); + Image data(TEST_TEXTURE_SIZE, TEST_TEXTURE_SIZE, false, Image::FORMAT_RGB8, test_data); test_texture = texture_create_from_image(data); @@ -139,13 +135,10 @@ void VisualServer::_free_internal_rids() { if (test_material.is_valid()) free(test_material); - for(int i=0;i<16;i++) { + for (int i = 0; i < 16; i++) { if (material_2d[i].is_valid()) free(material_2d[i]); } - - - } RID VisualServer::_make_test_cube() { @@ -155,72 +148,69 @@ RID VisualServer::_make_test_cube() { PoolVector<float> tangents; PoolVector<Vector3> uvs; - int vtx_idx=0; -#define ADD_VTX(m_idx) \ - vertices.push_back( face_points[m_idx] );\ - normals.push_back( normal_points[m_idx] );\ - tangents.push_back( normal_points[m_idx][1] );\ - tangents.push_back( normal_points[m_idx][2] );\ - tangents.push_back( normal_points[m_idx][0] );\ - tangents.push_back( 1.0 );\ - uvs.push_back( Vector3(uv_points[m_idx*2+0],uv_points[m_idx*2+1],0) );\ - vtx_idx++;\ - - for (int i=0;i<6;i++) { + int vtx_idx = 0; +#define ADD_VTX(m_idx) \ + vertices.push_back(face_points[m_idx]); \ + normals.push_back(normal_points[m_idx]); \ + tangents.push_back(normal_points[m_idx][1]); \ + tangents.push_back(normal_points[m_idx][2]); \ + tangents.push_back(normal_points[m_idx][0]); \ + tangents.push_back(1.0); \ + uvs.push_back(Vector3(uv_points[m_idx * 2 + 0], uv_points[m_idx * 2 + 1], 0)); \ + vtx_idx++; + for (int i = 0; i < 6; i++) { Vector3 face_points[4]; Vector3 normal_points[4]; - float uv_points[8]={0,0,0,1,1,1,1,0}; + float uv_points[8] = { 0, 0, 0, 1, 1, 1, 1, 0 }; - 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); } - normal_points[j]=Vector3(); - normal_points[j][i%3]=(i>=3?-1:1); + normal_points[j] = Vector3(); + normal_points[j][i % 3] = (i >= 3 ? -1 : 1); } - //tri 1 + //tri 1 ADD_VTX(0); ADD_VTX(1); ADD_VTX(2); - //tri 2 + //tri 2 ADD_VTX(2); ADD_VTX(3); ADD_VTX(0); - } RID test_cube = mesh_create(); Array d; d.resize(VS::ARRAY_MAX); - d[VisualServer::ARRAY_NORMAL]= normals ; - d[VisualServer::ARRAY_TANGENT]= tangents ; - d[VisualServer::ARRAY_TEX_UV]= uvs ; - d[VisualServer::ARRAY_VERTEX]= vertices ; + d[VisualServer::ARRAY_NORMAL] = normals; + d[VisualServer::ARRAY_TANGENT] = tangents; + d[VisualServer::ARRAY_TEX_UV] = uvs; + d[VisualServer::ARRAY_VERTEX] = vertices; PoolVector<int> indices; indices.resize(vertices.size()); - for(int i=0;i<vertices.size();i++) - indices.set(i,i); - d[VisualServer::ARRAY_INDEX]=indices; - - mesh_add_surface_from_arrays( test_cube, PRIMITIVE_TRIANGLES,d ); + for (int i = 0; i < vertices.size(); i++) + indices.set(i, i); + d[VisualServer::ARRAY_INDEX] = indices; + mesh_add_surface_from_arrays(test_cube, PRIMITIVE_TRIANGLES, d); -/* + /* test_material = fixed_material_create(); //material_set_flag(material, MATERIAL_FLAG_BILLBOARD_TOGGLE,true); fixed_material_set_texture( test_material, FIXED_MATERIAL_PARAM_DIFFUSE, get_test_texture() ); @@ -230,47 +220,45 @@ RID VisualServer::_make_test_cube() { fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_DIFFUSE, Color(1, 1, 1) ); fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_SPECULAR, Color(1,1,1) ); */ - mesh_surface_set_material(test_cube, 0, test_material ); + mesh_surface_set_material(test_cube, 0, test_material); return test_cube; } - -RID VisualServer::make_sphere_mesh(int p_lats,int p_lons,float p_radius) { +RID VisualServer::make_sphere_mesh(int p_lats, int p_lons, float p_radius) { PoolVector<Vector3> vertices; PoolVector<Vector3> normals; - for(int i = 1; i <= p_lats; i++) { - double lat0 = Math_PI * (-0.5 + (double) (i - 1) / p_lats); - double z0 = Math::sin(lat0); - double zr0 = Math::cos(lat0); + for (int i = 1; i <= p_lats; i++) { + double lat0 = Math_PI * (-0.5 + (double)(i - 1) / p_lats); + double z0 = Math::sin(lat0); + double zr0 = Math::cos(lat0); - double lat1 = Math_PI * (-0.5 + (double) i / p_lats); + double lat1 = Math_PI * (-0.5 + (double)i / p_lats); double z1 = Math::sin(lat1); double zr1 = Math::cos(lat1); - for(int j = p_lons; j >= 1; j--) { + for (int j = p_lons; j >= 1; j--) { - double lng0 = 2 * Math_PI * (double) (j - 1) / p_lons; + double lng0 = 2 * Math_PI * (double)(j - 1) / p_lons; double x0 = Math::cos(lng0); double y0 = Math::sin(lng0); - double lng1 = 2 * Math_PI * (double) (j) / p_lons; + double lng1 = 2 * Math_PI * (double)(j) / p_lons; double x1 = Math::cos(lng1); double y1 = Math::sin(lng1); - - Vector3 v[4]={ - Vector3(x1 * zr0, z0, y1 *zr0), - Vector3(x1 * zr1, z1, y1 *zr1), - Vector3(x0 * zr1, z1, y0 *zr1), - Vector3(x0 * zr0, z0, y0 *zr0) + Vector3 v[4] = { + Vector3(x1 * zr0, z0, y1 * zr0), + Vector3(x1 * zr1, z1, y1 * zr1), + Vector3(x0 * zr1, z1, y0 * zr1), + Vector3(x0 * zr0, z0, y0 * zr0) }; -#define ADD_POINT(m_idx)\ - normals.push_back(v[m_idx]); \ - vertices.push_back(v[m_idx]*p_radius);\ +#define ADD_POINT(m_idx) \ + normals.push_back(v[m_idx]); \ + vertices.push_back(v[m_idx] * p_radius); ADD_POINT(0); ADD_POINT(1); @@ -286,32 +274,31 @@ RID VisualServer::make_sphere_mesh(int p_lats,int p_lons,float p_radius) { Array d; d.resize(VS::ARRAY_MAX); - d[ARRAY_VERTEX]=vertices; - d[ARRAY_NORMAL]=normals; + d[ARRAY_VERTEX] = vertices; + d[ARRAY_NORMAL] = normals; - mesh_add_surface_from_arrays(mesh,PRIMITIVE_TRIANGLES,d); + mesh_add_surface_from_arrays(mesh, PRIMITIVE_TRIANGLES, d); return mesh; } - RID VisualServer::material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha, bool p_opaque_prepass) { - int version=0; + int version = 0; if (p_shaded) - version=1; + version = 1; if (p_transparent) - version|=2; + version |= 2; if (p_cut_alpha) - version|=4; + version |= 4; if (p_opaque_prepass) - version|=8; + version |= 8; if (material_2d[version].is_valid()) return material_2d[version]; //not valid, make -/* material_2d[version]=fixed_material_create(); + /* material_2d[version]=fixed_material_create(); fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_USE_ALPHA,p_transparent); fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true); fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_DISCARD_ALPHA,p_cut_alpha); @@ -330,189 +317,167 @@ RID VisualServer::get_white_texture() { return white_texture; PoolVector<uint8_t> wt; - wt.resize(16*3); + wt.resize(16 * 3); { - PoolVector<uint8_t>::Write w =wt.write(); - for(int i=0;i<16*3;i++) - w[i]=255; + PoolVector<uint8_t>::Write w = wt.write(); + for (int i = 0; i < 16 * 3; i++) + w[i] = 255; } - Image white(4,4,0,Image::FORMAT_RGB8,wt); - white_texture=texture_create(); - texture_allocate(white_texture,4,4,Image::FORMAT_RGB8); - texture_set_data(white_texture,white); + Image white(4, 4, 0, Image::FORMAT_RGB8, wt); + white_texture = texture_create(); + texture_allocate(white_texture, 4, 4, Image::FORMAT_RGB8); + texture_set_data(white_texture, white); return white_texture; - } - -Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t *p_offsets,uint32_t p_stride,PoolVector<uint8_t> &r_vertex_array,int p_vertex_array_len,PoolVector<uint8_t> &r_index_array,int p_index_array_len,Rect3 &r_aabb,Vector<Rect3> r_bone_aabb) { +Error VisualServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint32_t *p_offsets, uint32_t p_stride, PoolVector<uint8_t> &r_vertex_array, int p_vertex_array_len, PoolVector<uint8_t> &r_index_array, int p_index_array_len, Rect3 &r_aabb, Vector<Rect3> r_bone_aabb) { PoolVector<uint8_t>::Write vw = r_vertex_array.write(); PoolVector<uint8_t>::Write iw; if (r_index_array.size()) { - print_line("elements: "+itos(r_index_array.size())); - - iw=r_index_array.write(); + print_line("elements: " + itos(r_index_array.size())); + iw = r_index_array.write(); } - int max_bone=0; - + int max_bone = 0; - for(int ai=0;ai<VS::ARRAY_MAX;ai++) { + for (int ai = 0; ai < VS::ARRAY_MAX; ai++) { - if (!(p_format&(1<<ai))) // no array + if (!(p_format & (1 << ai))) // no array continue; - - switch(ai) { + switch (ai) { case VS::ARRAY_VERTEX: { - if (p_format& VS::ARRAY_FLAG_USE_2D_VERTICES) { + if (p_format & VS::ARRAY_FLAG_USE_2D_VERTICES) { PoolVector<Vector2> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER); PoolVector<Vector2>::Read read = array.read(); - const Vector2* src=read.ptr(); + const Vector2 *src = read.ptr(); // setting vertices means regenerating the AABB Rect2 aabb; + if (p_format & ARRAY_COMPRESS_VERTEX) { - if (p_format&ARRAY_COMPRESS_VERTEX) { + for (int i = 0; i < p_vertex_array_len; i++) { - for (int i=0;i<p_vertex_array_len;i++) { + uint16_t vector[2] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) }; + copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(uint16_t) * 2); - uint16_t vector[2]={ Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) }; + if (i == 0) { - copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(uint16_t)*2); - - if (i==0) { - - aabb=Rect2(src[i],Vector2()); + aabb = Rect2(src[i], Vector2()); } else { - aabb.expand_to( src[i] ); + aabb.expand_to(src[i]); } } - } else { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { + float vector[2] = { src[i].x, src[i].y }; - float vector[2]={ src[i].x, src[i].y }; + copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(float) * 2); - copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(float)*2); + if (i == 0) { - if (i==0) { - - aabb=Rect2(src[i],Vector2()); + aabb = Rect2(src[i], Vector2()); } else { - aabb.expand_to( src[i] ); + aabb.expand_to(src[i]); } } } - r_aabb=Rect3(Vector3(aabb.pos.x,aabb.pos.y,0),Vector3(aabb.size.x,aabb.size.y,0)); - + r_aabb = Rect3(Vector3(aabb.pos.x, aabb.pos.y, 0), Vector3(aabb.size.x, aabb.size.y, 0)); } else { PoolVector<Vector3> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER); PoolVector<Vector3>::Read read = array.read(); - const Vector3* src=read.ptr(); + const Vector3 *src = read.ptr(); // setting vertices means regenerating the AABB Rect3 aabb; + if (p_format & ARRAY_COMPRESS_VERTEX) { - if (p_format&ARRAY_COMPRESS_VERTEX) { - - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { + uint16_t vector[4] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y), Math::make_half_float(src[i].z), Math::make_half_float(1.0) }; - uint16_t vector[4]={ Math::make_half_float(src[i].x), Math::make_half_float(src[i].y), Math::make_half_float(src[i].z), Math::make_half_float(1.0) }; + copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(uint16_t) * 4); - copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(uint16_t)*4); + if (i == 0) { - if (i==0) { - - aabb=Rect3(src[i],Vector3()); + aabb = Rect3(src[i], Vector3()); } else { - aabb.expand_to( src[i] ); + aabb.expand_to(src[i]); } } - } else { - for (int i=0;i<p_vertex_array_len;i++) { - + for (int i = 0; i < p_vertex_array_len; i++) { - float vector[3]={ src[i].x, src[i].y, src[i].z }; + float vector[3] = { src[i].x, src[i].y, src[i].z }; - copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(float)*3); + copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(float) * 3); - if (i==0) { + if (i == 0) { - aabb=Rect3(src[i],Vector3()); + aabb = Rect3(src[i], Vector3()); } else { - aabb.expand_to( src[i] ); + aabb.expand_to(src[i]); } } } - r_aabb=aabb; - + r_aabb = aabb; } - } break; case VS::ARRAY_NORMAL: { - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY, ERR_INVALID_PARAMETER); PoolVector<Vector3> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER); PoolVector<Vector3>::Read read = array.read(); - const Vector3* src=read.ptr(); + const Vector3 *src = read.ptr(); // setting vertices means regenerating the AABB - if (p_format&ARRAY_COMPRESS_NORMAL) { + if (p_format & ARRAY_COMPRESS_NORMAL) { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { - uint8_t vector[4]={ - CLAMP(src[i].x*127,-128,127), - CLAMP(src[i].y*127,-128,127), - CLAMP(src[i].z*127,-128,127), + uint8_t vector[4] = { + CLAMP(src[i].x * 127, -128, 127), + CLAMP(src[i].y * 127, -128, 127), + CLAMP(src[i].z * 127, -128, 127), 0, }; - copymem(&vw[p_offsets[ai]+i*p_stride], vector, 4); - + copymem(&vw[p_offsets[ai] + i * p_stride], vector, 4); } } else { - for (int i=0;i<p_vertex_array_len;i++) { - - - float vector[3]={ src[i].x, src[i].y, src[i].z }; - copymem(&vw[p_offsets[ai]+i*p_stride], vector, 3*4); + for (int i = 0; i < p_vertex_array_len; i++) { + float vector[3] = { src[i].x, src[i].y, src[i].z }; + copymem(&vw[p_offsets[ai] + i * p_stride], vector, 3 * 4); } } @@ -520,291 +485,257 @@ Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t case VS::ARRAY_TANGENT: { - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER); PoolVector<real_t> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len*4, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len * 4, ERR_INVALID_PARAMETER); PoolVector<real_t>::Read read = array.read(); - const real_t* src = read.ptr(); + const real_t *src = read.ptr(); - if (p_format&ARRAY_COMPRESS_TANGENT) { + if (p_format & ARRAY_COMPRESS_TANGENT) { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { - uint8_t xyzw[4]={ - CLAMP(src[i*4+0]*127,-128,127), - CLAMP(src[i*4+1]*127,-128,127), - CLAMP(src[i*4+2]*127,-128,127), - CLAMP(src[i*4+3]*127,-128,127) + uint8_t xyzw[4] = { + CLAMP(src[i * 4 + 0] * 127, -128, 127), + CLAMP(src[i * 4 + 1] * 127, -128, 127), + CLAMP(src[i * 4 + 2] * 127, -128, 127), + CLAMP(src[i * 4 + 3] * 127, -128, 127) }; - copymem(&vw[p_offsets[ai]+i*p_stride], xyzw, 4); - + copymem(&vw[p_offsets[ai] + i * p_stride], xyzw, 4); } - } else { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { - float xyzw[4]={ - src[i*4+0], - src[i*4+1], - src[i*4+2], - src[i*4+3] + float xyzw[4] = { + src[i * 4 + 0], + src[i * 4 + 1], + src[i * 4 + 2], + src[i * 4 + 3] }; - copymem(&vw[p_offsets[ai]+i*p_stride], xyzw, 4*4); - + copymem(&vw[p_offsets[ai] + i * p_stride], xyzw, 4 * 4); } } } break; case VS::ARRAY_COLOR: { - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_COLOR_ARRAY, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_COLOR_ARRAY, ERR_INVALID_PARAMETER); PoolVector<Color> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER); PoolVector<Color>::Read read = array.read(); - const Color* src = read.ptr(); + const Color *src = read.ptr(); - if (p_format&ARRAY_COMPRESS_COLOR) { - - for (int i=0;i<p_vertex_array_len;i++) { + if (p_format & ARRAY_COMPRESS_COLOR) { + for (int i = 0; i < p_vertex_array_len; i++) { uint8_t colors[4]; - for(int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { - colors[j]=CLAMP( int((src[i][j])*255.0), 0,255 ); + colors[j] = CLAMP(int((src[i][j]) * 255.0), 0, 255); } - copymem(&vw[p_offsets[ai]+i*p_stride], colors, 4); - + copymem(&vw[p_offsets[ai] + i * p_stride], colors, 4); } } else { - for (int i=0;i<p_vertex_array_len;i++) { - + for (int i = 0; i < p_vertex_array_len; i++) { - copymem(&vw[p_offsets[ai]+i*p_stride], &src[i], 4*4); + copymem(&vw[p_offsets[ai] + i * p_stride], &src[i], 4 * 4); } - } - } break; case VS::ARRAY_TEX_UV: { - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER); PoolVector<Vector2> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len , ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER); PoolVector<Vector2>::Read read = array.read(); - const Vector2 * src=read.ptr(); - - + const Vector2 *src = read.ptr(); - if (p_format&ARRAY_COMPRESS_TEX_UV) { + if (p_format & ARRAY_COMPRESS_TEX_UV) { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { - uint16_t uv[2]={ Math::make_half_float(src[i].x) , Math::make_half_float(src[i].y) }; - copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*2); + uint16_t uv[2] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) }; + copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 2); } } else { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { - float uv[2]={ src[i].x , src[i].y }; - - copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*4); + float uv[2] = { src[i].x, src[i].y }; + copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 4); } } - } break; case VS::ARRAY_TEX_UV2: { - - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER); PoolVector<Vector2> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len , ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER); PoolVector<Vector2>::Read read = array.read(); - const Vector2 * src=read.ptr(); + const Vector2 *src = read.ptr(); + if (p_format & ARRAY_COMPRESS_TEX_UV2) { + for (int i = 0; i < p_vertex_array_len; i++) { - if (p_format&ARRAY_COMPRESS_TEX_UV2) { - - for (int i=0;i<p_vertex_array_len;i++) { - - uint16_t uv[2]={ Math::make_half_float(src[i].x) , Math::make_half_float(src[i].y) }; - copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*2); + uint16_t uv[2] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) }; + copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 2); } } else { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { - float uv[2]={ src[i].x , src[i].y }; - - copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*4); + float uv[2] = { src[i].x, src[i].y }; + copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 4); } } } break; case VS::ARRAY_WEIGHTS: { - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER); PoolVector<real_t> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER); PoolVector<real_t>::Read read = array.read(); - const real_t * src = read.ptr(); + const real_t *src = read.ptr(); - if (p_format&ARRAY_COMPRESS_WEIGHTS) { + if (p_format & ARRAY_COMPRESS_WEIGHTS) { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { uint16_t data[VS::ARRAY_WEIGHTS_SIZE]; - for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { - data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j]*65535,0,65535); + for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) { + data[j] = CLAMP(src[i * VS::ARRAY_WEIGHTS_SIZE + j] * 65535, 0, 65535); } - copymem(&vw[p_offsets[ai]+i*p_stride], data, 2*4); + copymem(&vw[p_offsets[ai] + i * p_stride], data, 2 * 4); } } else { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { float data[VS::ARRAY_WEIGHTS_SIZE]; - for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { - data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j]; + for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) { + data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j]; } - copymem(&vw[p_offsets[ai]+i*p_stride], data, 4*4); - - + copymem(&vw[p_offsets[ai] + i * p_stride], data, 4 * 4); } } } break; case VS::ARRAY_BONES: { - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY && p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY && p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER); PoolVector<int> array = p_arrays[ai]; - ERR_FAIL_COND_V( array.size() != p_vertex_array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER ); - + ERR_FAIL_COND_V(array.size() != p_vertex_array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER); PoolVector<int>::Read read = array.read(); - const int * src = read.ptr(); + const int *src = read.ptr(); + if (!(p_format & ARRAY_FLAG_USE_16_BIT_BONES)) { - if (!(p_format&ARRAY_FLAG_USE_16_BIT_BONES)) { - - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { uint8_t data[VS::ARRAY_WEIGHTS_SIZE]; - for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { - data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j],0,255); - max_bone=MAX(data[j],max_bone); - + for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) { + data[j] = CLAMP(src[i * VS::ARRAY_WEIGHTS_SIZE + j], 0, 255); + max_bone = MAX(data[j], max_bone); } - copymem(&vw[p_offsets[ai]+i*p_stride], data, 4); - - + copymem(&vw[p_offsets[ai] + i * p_stride], data, 4); } } else { - for (int i=0;i<p_vertex_array_len;i++) { + for (int i = 0; i < p_vertex_array_len; i++) { uint16_t data[VS::ARRAY_WEIGHTS_SIZE]; - for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { - data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j]; - max_bone=MAX(data[j],max_bone); - + for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) { + data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j]; + max_bone = MAX(data[j], max_bone); } - copymem(&vw[p_offsets[ai]+i*p_stride], data, 2*4); - - + copymem(&vw[p_offsets[ai] + i * p_stride], data, 2 * 4); } } - } break; case VS::ARRAY_INDEX: { - - ERR_FAIL_COND_V( p_index_array_len<=0, ERR_INVALID_DATA ); - ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_index_array_len <= 0, ERR_INVALID_DATA); + ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY, ERR_INVALID_PARAMETER); PoolVector<int> indices = p_arrays[ai]; - ERR_FAIL_COND_V( indices.size() == 0, ERR_INVALID_PARAMETER ); - ERR_FAIL_COND_V( indices.size() != p_index_array_len, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(indices.size() == 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(indices.size() != p_index_array_len, ERR_INVALID_PARAMETER); /* determine wether using 16 or 32 bits indices */ PoolVector<int>::Read read = indices.read(); - const int *src=read.ptr(); - - for (int i=0;i<p_index_array_len;i++) { + const int *src = read.ptr(); + for (int i = 0; i < p_index_array_len; i++) { - if (p_vertex_array_len<(1<<16)) { - uint16_t v=src[i]; + if (p_vertex_array_len < (1 << 16)) { + uint16_t v = src[i]; - copymem(&iw[i*2], &v, 2); + copymem(&iw[i * 2], &v, 2); } else { - uint32_t v=src[i]; + uint32_t v = src[i]; - copymem(&iw[i*4], &v, 4); + copymem(&iw[i * 4], &v, 4); } } } break; default: { - ERR_FAIL_V( ERR_INVALID_DATA ); + ERR_FAIL_V(ERR_INVALID_DATA); } } } - - if (p_format&VS::ARRAY_FORMAT_BONES) { + if (p_format & VS::ARRAY_FORMAT_BONES) { //create AABBs for each detected bone - int total_bones = max_bone+1; + int total_bones = max_bone + 1; - bool first = r_bone_aabb.size()==0; + bool first = r_bone_aabb.size() == 0; r_bone_aabb.resize(total_bones); if (first) { - for(int i=0;i<total_bones;i++) { - r_bone_aabb[i].size==Vector3(-1,-1,-1); //negative means unused + for (int i = 0; i < total_bones; i++) { + r_bone_aabb[i].size == Vector3(-1, -1, -1); //negative means unused } } @@ -812,33 +743,33 @@ Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t PoolVector<int> bones = p_arrays[VS::ARRAY_BONES]; PoolVector<float> weights = p_arrays[VS::ARRAY_WEIGHTS]; - bool any_valid=false; + bool any_valid = false; - if (vertices.size() && bones.size()==vertices.size()*4 && weights.size()==bones.size()) { + if (vertices.size() && bones.size() == vertices.size() * 4 && weights.size() == bones.size()) { int vs = vertices.size(); - PoolVector<Vector3>::Read rv =vertices.read(); - PoolVector<int>::Read rb=bones.read(); - PoolVector<float>::Read rw=weights.read(); + PoolVector<Vector3>::Read rv = vertices.read(); + PoolVector<int>::Read rb = bones.read(); + PoolVector<float>::Read rw = weights.read(); Rect3 *bptr = r_bone_aabb.ptr(); - for(int i=0;i<vs;i++) { + for (int i = 0; i < vs; i++) { Vector3 v = rv[i]; - for(int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { - int idx = rb[i*4+j]; - float w = rw[i*4+j]; - if (w==0) - continue;//break; - ERR_FAIL_INDEX_V(idx,total_bones,ERR_INVALID_DATA); + int idx = rb[i * 4 + j]; + float w = rw[i * 4 + j]; + if (w == 0) + continue; //break; + ERR_FAIL_INDEX_V(idx, total_bones, ERR_INVALID_DATA); - if (bptr->size.x<0) { + if (bptr->size.x < 0) { //first - bptr[idx]=Rect3(); - bptr[idx].pos=v; - any_valid=true; + bptr[idx] = Rect3(); + bptr[idx].pos = v; + any_valid = true; } else { bptr[idx].expand_to(v); } @@ -854,226 +785,217 @@ Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t return OK; } +void VisualServer::mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, uint32_t p_compress_format) { -void VisualServer::mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,uint32_t p_compress_format) { - - ERR_FAIL_INDEX( p_primitive, VS::PRIMITIVE_MAX ); - ERR_FAIL_COND(p_arrays.size()!=VS::ARRAY_MAX); + ERR_FAIL_INDEX(p_primitive, VS::PRIMITIVE_MAX); + ERR_FAIL_COND(p_arrays.size() != VS::ARRAY_MAX); - uint32_t format=0; + uint32_t format = 0; // validation - int index_array_len=0; - int array_len=0; + int index_array_len = 0; + int array_len = 0; - for(int i=0;i<p_arrays.size();i++) { + for (int i = 0; i < p_arrays.size(); i++) { - if (p_arrays[i].get_type()==Variant::NIL) + if (p_arrays[i].get_type() == Variant::NIL) continue; - format|=(1<<i); + format |= (1 << i); - if (i==VS::ARRAY_VERTEX) { + if (i == VS::ARRAY_VERTEX) { Variant var = p_arrays[i]; - switch(var.get_type()) { + switch (var.get_type()) { case Variant::POOL_VECTOR2_ARRAY: { PoolVector<Vector2> v2 = var; - array_len=v2.size(); + array_len = v2.size(); } break; case Variant::POOL_VECTOR3_ARRAY: { PoolVector<Vector3> v3 = var; - array_len=v3.size(); + array_len = v3.size(); } break; default: { Array v = var; - array_len=v.size(); + array_len = v.size(); } break; } - array_len=PoolVector3Array(p_arrays[i]).size(); - ERR_FAIL_COND(array_len==0); - } else if (i==VS::ARRAY_INDEX) { + array_len = PoolVector3Array(p_arrays[i]).size(); + ERR_FAIL_COND(array_len == 0); + } else if (i == VS::ARRAY_INDEX) { - index_array_len=PoolIntArray(p_arrays[i]).size(); + index_array_len = PoolIntArray(p_arrays[i]).size(); } } - ERR_FAIL_COND((format&VS::ARRAY_FORMAT_VERTEX)==0); // mandatory - + ERR_FAIL_COND((format & VS::ARRAY_FORMAT_VERTEX) == 0); // mandatory if (p_blend_shapes.size()) { //validate format for morphs - for(int i=0;i<p_blend_shapes.size();i++) { + for (int i = 0; i < p_blend_shapes.size(); i++) { - uint32_t bsformat=0; + uint32_t bsformat = 0; Array arr = p_blend_shapes[i]; - for(int j=0;j<arr.size();j++) { - + for (int j = 0; j < arr.size(); j++) { - if (arr[j].get_type()!=Variant::NIL) - bsformat|=(1<<j); + if (arr[j].get_type() != Variant::NIL) + bsformat |= (1 << j); } - ERR_FAIL_COND( (bsformat)!=(format&(VS::ARRAY_FORMAT_INDEX-1))); + ERR_FAIL_COND((bsformat) != (format & (VS::ARRAY_FORMAT_INDEX - 1))); } } uint32_t offsets[VS::ARRAY_MAX]; - int total_elem_size=0; - - for (int i=0;i<VS::ARRAY_MAX;i++) { + int total_elem_size = 0; + for (int i = 0; i < VS::ARRAY_MAX; i++) { - offsets[i]=0; //reset + offsets[i] = 0; //reset - if (!(format&(1<<i))) // no array + if (!(format & (1 << i))) // no array continue; + int elem_size = 0; - int elem_size=0; - - switch(i) { + switch (i) { case VS::ARRAY_VERTEX: { Variant arr = p_arrays[0]; - if (arr.get_type()==Variant::POOL_VECTOR2_ARRAY) { - elem_size=2; - p_compress_format|=ARRAY_FLAG_USE_2D_VERTICES; - } else if (arr.get_type()==Variant::POOL_VECTOR3_ARRAY) { - p_compress_format&=~ARRAY_FLAG_USE_2D_VERTICES; - elem_size=3; + if (arr.get_type() == Variant::POOL_VECTOR2_ARRAY) { + elem_size = 2; + p_compress_format |= ARRAY_FLAG_USE_2D_VERTICES; + } else if (arr.get_type() == Variant::POOL_VECTOR3_ARRAY) { + p_compress_format &= ~ARRAY_FLAG_USE_2D_VERTICES; + elem_size = 3; } else { - elem_size=(p_compress_format&ARRAY_FLAG_USE_2D_VERTICES)?2:3; + elem_size = (p_compress_format & ARRAY_FLAG_USE_2D_VERTICES) ? 2 : 3; } - if (p_compress_format&ARRAY_COMPRESS_VERTEX) { - elem_size*=sizeof(int16_t); + if (p_compress_format & ARRAY_COMPRESS_VERTEX) { + elem_size *= sizeof(int16_t); } else { - elem_size*=sizeof(float); + elem_size *= sizeof(float); } - if (elem_size==6) { + if (elem_size == 6) { //had to pad - elem_size=8; + elem_size = 8; } } break; case VS::ARRAY_NORMAL: { - if (p_compress_format&ARRAY_COMPRESS_NORMAL) { - elem_size=sizeof(uint32_t); + if (p_compress_format & ARRAY_COMPRESS_NORMAL) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*3; + elem_size = sizeof(float) * 3; } } break; case VS::ARRAY_TANGENT: { - if (p_compress_format&ARRAY_COMPRESS_TANGENT) { - elem_size=sizeof(uint32_t); + if (p_compress_format & ARRAY_COMPRESS_TANGENT) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*4; + elem_size = sizeof(float) * 4; } } break; case VS::ARRAY_COLOR: { - if (p_compress_format&ARRAY_COMPRESS_COLOR) { - elem_size=sizeof(uint32_t); + if (p_compress_format & ARRAY_COMPRESS_COLOR) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*4; + elem_size = sizeof(float) * 4; } } break; case VS::ARRAY_TEX_UV: { - if (p_compress_format&ARRAY_COMPRESS_TEX_UV) { - elem_size=sizeof(uint32_t); + if (p_compress_format & ARRAY_COMPRESS_TEX_UV) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*2; + elem_size = sizeof(float) * 2; } } break; case VS::ARRAY_TEX_UV2: { - if (p_compress_format&ARRAY_COMPRESS_TEX_UV2) { - elem_size=sizeof(uint32_t); + if (p_compress_format & ARRAY_COMPRESS_TEX_UV2) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*2; + elem_size = sizeof(float) * 2; } } break; case VS::ARRAY_WEIGHTS: { - if (p_compress_format&ARRAY_COMPRESS_WEIGHTS) { - elem_size=sizeof(uint16_t)*4; + if (p_compress_format & ARRAY_COMPRESS_WEIGHTS) { + elem_size = sizeof(uint16_t) * 4; } else { - elem_size=sizeof(float)*4; + elem_size = sizeof(float) * 4; } } break; case VS::ARRAY_BONES: { PoolVector<int> bones = p_arrays[VS::ARRAY_BONES]; - int max_bone=0; + int max_bone = 0; { int bc = bones.size(); - PoolVector<int>::Read r=bones.read(); - for(int j=0;j<bc;j++) { - max_bone=MAX(r[j],max_bone); + PoolVector<int>::Read r = bones.read(); + for (int j = 0; j < bc; j++) { + max_bone = MAX(r[j], max_bone); } } if (max_bone > 255) { - p_compress_format|=ARRAY_FLAG_USE_16_BIT_BONES; - elem_size=sizeof(uint16_t)*4; + p_compress_format |= ARRAY_FLAG_USE_16_BIT_BONES; + elem_size = sizeof(uint16_t) * 4; } else { - p_compress_format&=~ARRAY_FLAG_USE_16_BIT_BONES; - elem_size=sizeof(uint32_t); + p_compress_format &= ~ARRAY_FLAG_USE_16_BIT_BONES; + elem_size = sizeof(uint32_t); } - } break; case VS::ARRAY_INDEX: { - if (index_array_len<=0) { + if (index_array_len <= 0) { ERR_PRINT("index_array_len==NO_INDEX_ARRAY"); break; } /* determine wether using 16 or 32 bits indices */ - if (array_len>=(1<<16)) { + if (array_len >= (1 << 16)) { - elem_size=4; + elem_size = 4; } else { - elem_size=2; + elem_size = 2; } - offsets[i]=elem_size; + offsets[i] = elem_size; continue; } break; default: { - ERR_FAIL( ); + ERR_FAIL(); } } - offsets[i]=total_elem_size; - total_elem_size+=elem_size; - - + offsets[i] = total_elem_size; + total_elem_size += elem_size; } - uint32_t mask = (1<<ARRAY_MAX)-1; - format|=(~mask)&p_compress_format; //make the full format - + uint32_t mask = (1 << ARRAY_MAX) - 1; + format |= (~mask) & p_compress_format; //make the full format int array_size = total_elem_size * array_len; PoolVector<uint8_t> vertex_array; vertex_array.resize(array_size); - int index_array_size = offsets[VS::ARRAY_INDEX]*index_array_len; + int index_array_size = offsets[VS::ARRAY_INDEX] * index_array_len; PoolVector<uint8_t> index_array; index_array.resize(index_array_size); @@ -1081,163 +1003,156 @@ void VisualServer::mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primi Rect3 aabb; Vector<Rect3> bone_aabb; - Error err = _surface_set_data(p_arrays,format,offsets,total_elem_size,vertex_array,array_len,index_array,index_array_len,aabb,bone_aabb); + Error err = _surface_set_data(p_arrays, format, offsets, total_elem_size, vertex_array, array_len, index_array, index_array_len, aabb, bone_aabb); if (err) { ERR_EXPLAIN("Invalid array format for surface"); - ERR_FAIL_COND(err!=OK); + ERR_FAIL_COND(err != OK); } Vector<PoolVector<uint8_t> > blend_shape_data; - for(int i=0;i<p_blend_shapes.size();i++) { + for (int i = 0; i < p_blend_shapes.size(); i++) { PoolVector<uint8_t> vertex_array_shape; vertex_array_shape.resize(array_size); PoolVector<uint8_t> noindex; Rect3 laabb; - Error err = _surface_set_data(p_blend_shapes[i],format&~ARRAY_FORMAT_INDEX,offsets,total_elem_size,vertex_array_shape,array_len,noindex,0,laabb,bone_aabb); + Error err = _surface_set_data(p_blend_shapes[i], format & ~ARRAY_FORMAT_INDEX, offsets, total_elem_size, vertex_array_shape, array_len, noindex, 0, laabb, bone_aabb); aabb.merge_with(laabb); if (err) { ERR_EXPLAIN("Invalid blend shape array format for surface"); - ERR_FAIL_COND(err!=OK); + ERR_FAIL_COND(err != OK); } blend_shape_data.push_back(vertex_array_shape); } - mesh_add_surface(p_mesh,format,p_primitive,vertex_array,array_len,index_array,index_array_len,aabb,blend_shape_data,bone_aabb); - + mesh_add_surface(p_mesh, format, p_primitive, vertex_array, array_len, index_array, index_array_len, aabb, blend_shape_data, bone_aabb); } -Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t> p_vertex_data,int p_vertex_len,PoolVector<uint8_t> p_index_data,int p_index_len) const { - +Array VisualServer::_get_array_from_surface(uint32_t p_format, PoolVector<uint8_t> p_vertex_data, int p_vertex_len, PoolVector<uint8_t> p_index_data, int p_index_len) const { uint32_t offsets[ARRAY_MAX]; - int total_elem_size=0; + int total_elem_size = 0; - for (int i=0;i<VS::ARRAY_MAX;i++) { + for (int i = 0; i < VS::ARRAY_MAX; i++) { + offsets[i] = 0; //reset - offsets[i]=0; //reset - - if (!(p_format&(1<<i))) // no array + if (!(p_format & (1 << i))) // no array continue; + int elem_size = 0; - int elem_size=0; - - switch(i) { + switch (i) { case VS::ARRAY_VERTEX: { - - if (p_format&ARRAY_FLAG_USE_2D_VERTICES) { - elem_size=2; + if (p_format & ARRAY_FLAG_USE_2D_VERTICES) { + elem_size = 2; } else { - elem_size=3; + elem_size = 3; } - if (p_format&ARRAY_COMPRESS_VERTEX) { - elem_size*=sizeof(int16_t); + if (p_format & ARRAY_COMPRESS_VERTEX) { + elem_size *= sizeof(int16_t); } else { - elem_size*=sizeof(float); + elem_size *= sizeof(float); } - if (elem_size==6) { - elem_size=8; + if (elem_size == 6) { + elem_size = 8; } } break; case VS::ARRAY_NORMAL: { - if (p_format&ARRAY_COMPRESS_NORMAL) { - elem_size=sizeof(uint32_t); + if (p_format & ARRAY_COMPRESS_NORMAL) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*3; + elem_size = sizeof(float) * 3; } } break; case VS::ARRAY_TANGENT: { - if (p_format&ARRAY_COMPRESS_TANGENT) { - elem_size=sizeof(uint32_t); + if (p_format & ARRAY_COMPRESS_TANGENT) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*4; + elem_size = sizeof(float) * 4; } } break; case VS::ARRAY_COLOR: { - if (p_format&ARRAY_COMPRESS_COLOR) { - elem_size=sizeof(uint32_t); + if (p_format & ARRAY_COMPRESS_COLOR) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*4; + elem_size = sizeof(float) * 4; } } break; case VS::ARRAY_TEX_UV: { - if (p_format&ARRAY_COMPRESS_TEX_UV) { - elem_size=sizeof(uint32_t); + if (p_format & ARRAY_COMPRESS_TEX_UV) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*2; + elem_size = sizeof(float) * 2; } } break; case VS::ARRAY_TEX_UV2: { - if (p_format&ARRAY_COMPRESS_TEX_UV2) { - elem_size=sizeof(uint32_t); + if (p_format & ARRAY_COMPRESS_TEX_UV2) { + elem_size = sizeof(uint32_t); } else { - elem_size=sizeof(float)*2; + elem_size = sizeof(float) * 2; } } break; case VS::ARRAY_WEIGHTS: { - if (p_format&ARRAY_COMPRESS_WEIGHTS) { - elem_size=sizeof(uint16_t)*4; + if (p_format & ARRAY_COMPRESS_WEIGHTS) { + elem_size = sizeof(uint16_t) * 4; } else { - elem_size=sizeof(float)*4; + elem_size = sizeof(float) * 4; } } break; case VS::ARRAY_BONES: { - if (p_format&ARRAY_FLAG_USE_16_BIT_BONES) { - elem_size=sizeof(uint16_t)*4; + if (p_format & ARRAY_FLAG_USE_16_BIT_BONES) { + elem_size = sizeof(uint16_t) * 4; } else { - elem_size=sizeof(uint32_t); + elem_size = sizeof(uint32_t); } } break; case VS::ARRAY_INDEX: { - if (p_index_len<=0) { + if (p_index_len <= 0) { ERR_PRINT("index_array_len==NO_INDEX_ARRAY"); break; } /* determine wether using 16 or 32 bits indices */ - if (p_vertex_len>=(1<<16)) { + if (p_vertex_len >= (1 << 16)) { - elem_size=4; + elem_size = 4; } else { - elem_size=2; + elem_size = 2; } - offsets[i]=elem_size; + offsets[i] = elem_size; continue; } break; default: { - ERR_FAIL_V( Array() ); + ERR_FAIL_V(Array()); } } - offsets[i]=total_elem_size; - total_elem_size+=elem_size; - - + offsets[i] = total_elem_size; + total_elem_size += elem_size; } Array ret; @@ -1245,127 +1160,123 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t PoolVector<uint8_t>::Read r = p_vertex_data.read(); - for(int i=0;i<VS::ARRAY_MAX;i++) { + for (int i = 0; i < VS::ARRAY_MAX; i++) { - if (!(p_format&(1<<i))) + if (!(p_format & (1 << i))) continue; - - switch(i) { + switch (i) { case VS::ARRAY_VERTEX: { - - if (p_format&ARRAY_FLAG_USE_2D_VERTICES) { + if (p_format & ARRAY_FLAG_USE_2D_VERTICES) { PoolVector<Vector2> arr_2d; arr_2d.resize(p_vertex_len); - if (p_format&ARRAY_COMPRESS_VERTEX) { + if (p_format & ARRAY_COMPRESS_VERTEX) { PoolVector<Vector2>::Write w = arr_2d.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1])); + const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector2(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1])); } } else { PoolVector<Vector2>::Write w = arr_2d.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector2(v[0],v[1]); + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector2(v[0], v[1]); } } - ret[i]=arr_2d; + ret[i] = arr_2d; } else { PoolVector<Vector3> arr_3d; arr_3d.resize(p_vertex_len); - if (p_format&ARRAY_COMPRESS_VERTEX) { + if (p_format & ARRAY_COMPRESS_VERTEX) { PoolVector<Vector3>::Write w = arr_3d.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector3(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1]),Math::halfptr_to_float(&v[2])); + const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector3(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1]), Math::halfptr_to_float(&v[2])); } } else { PoolVector<Vector3>::Write w = arr_3d.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector3(v[0],v[1],v[2]); + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector3(v[0], v[1], v[2]); } } - ret[i]=arr_3d; + ret[i] = arr_3d; } - } break; case VS::ARRAY_NORMAL: { PoolVector<Vector3> arr; arr.resize(p_vertex_len); - if (p_format&ARRAY_COMPRESS_NORMAL) { + if (p_format & ARRAY_COMPRESS_NORMAL) { PoolVector<Vector3>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector3( float(v[0]/255.0)*2.0-1.0, float(v[1]/255.0)*2.0-1.0, float(v[2]/255.0)*2.0-1.0 ); + const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector3(float(v[0] / 255.0) * 2.0 - 1.0, float(v[1] / 255.0) * 2.0 - 1.0, float(v[2] / 255.0) * 2.0 - 1.0); } } else { PoolVector<Vector3>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector3(v[0],v[1],v[2]); + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector3(v[0], v[1], v[2]); } } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_TANGENT: { PoolVector<float> arr; - arr.resize(p_vertex_len*4); - if (p_format&ARRAY_COMPRESS_TANGENT) { + arr.resize(p_vertex_len * 4); + if (p_format & ARRAY_COMPRESS_TANGENT) { PoolVector<float>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; - for(int k=0;k<4;k++) { - w[j*4+k]=float(v[k]/255.0)*2.0-1.0; + const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]]; + for (int k = 0; k < 4; k++) { + w[j * 4 + k] = float(v[k] / 255.0) * 2.0 - 1.0; } } } else { PoolVector<float>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - for(int k=0;k<4;k++) { - w[j*4+k]=v[k]; + for (int j = 0; j < p_vertex_len; j++) { + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + for (int k = 0; k < 4; k++) { + w[j * 4 + k] = v[k]; } } - } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_COLOR: { @@ -1373,141 +1284,139 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t PoolVector<Color> arr; arr.resize(p_vertex_len); - if (p_format&ARRAY_COMPRESS_COLOR) { + if (p_format & ARRAY_COMPRESS_COLOR) { PoolVector<Color>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; - w[j]=Color( float(v[0]/255.0)*2.0-1.0, float(v[1]/255.0)*2.0-1.0, float(v[2]/255.0)*2.0-1.0, float(v[3]/255.0)*2.0-1.0 ); + const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]]; + w[j] = Color(float(v[0] / 255.0) * 2.0 - 1.0, float(v[1] / 255.0) * 2.0 - 1.0, float(v[2] / 255.0) * 2.0 - 1.0, float(v[3] / 255.0) * 2.0 - 1.0); } } else { PoolVector<Color>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - w[j]=Color(v[0],v[1],v[2],v[3]); + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + w[j] = Color(v[0], v[1], v[2], v[3]); } } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_TEX_UV: { PoolVector<Vector2> arr; arr.resize(p_vertex_len); - if (p_format&ARRAY_COMPRESS_TEX_UV) { + if (p_format & ARRAY_COMPRESS_TEX_UV) { PoolVector<Vector2>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1])); + const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector2(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1])); } } else { PoolVector<Vector2>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector2(v[0],v[1]); + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector2(v[0], v[1]); } } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_TEX_UV2: { PoolVector<Vector2> arr; arr.resize(p_vertex_len); - if (p_format&ARRAY_COMPRESS_TEX_UV2) { + if (p_format & ARRAY_COMPRESS_TEX_UV2) { PoolVector<Vector2>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1])); + const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector2(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1])); } } else { PoolVector<Vector2>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - w[j]=Vector2(v[0],v[1]); + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + w[j] = Vector2(v[0], v[1]); } } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_WEIGHTS: { PoolVector<float> arr; - arr.resize(p_vertex_len*4); - if (p_format&ARRAY_COMPRESS_WEIGHTS) { + arr.resize(p_vertex_len * 4); + if (p_format & ARRAY_COMPRESS_WEIGHTS) { PoolVector<float>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; - for(int k=0;k<4;k++) { - w[j*4+k]=float(v[k]/65535.0)*2.0-1.0; + const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]]; + for (int k = 0; k < 4; k++) { + w[j * 4 + k] = float(v[k] / 65535.0) * 2.0 - 1.0; } } } else { PoolVector<float>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { - const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; - for(int k=0;k<4;k++) { - w[j*4+k]=v[k]; + for (int j = 0; j < p_vertex_len; j++) { + const float *v = (const float *)&r[j * total_elem_size + offsets[i]]; + for (int k = 0; k < 4; k++) { + w[j * 4 + k] = v[k]; } } - } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_BONES: { PoolVector<int> arr; - arr.resize(p_vertex_len*4); - if (p_format&ARRAY_FLAG_USE_16_BIT_BONES) { + arr.resize(p_vertex_len * 4); + if (p_format & ARRAY_FLAG_USE_16_BIT_BONES) { PoolVector<int>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { + for (int j = 0; j < p_vertex_len; j++) { - const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; - for(int k=0;k<4;k++) { - w[j*4+k]=v[k]; + const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]]; + for (int k = 0; k < 4; k++) { + w[j * 4 + k] = v[k]; } } } else { PoolVector<int>::Write w = arr.write(); - for(int j=0;j<p_vertex_len;j++) { - const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; - for(int k=0;k<4;k++) { - w[j*4+k]=v[k]; + for (int j = 0; j < p_vertex_len; j++) { + const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]]; + for (int k = 0; k < 4; k++) { + w[j * 4 + k] = v[k]; } } - } - ret[i]=arr; + ret[i] = arr; } break; case VS::ARRAY_INDEX: { @@ -1517,29 +1426,28 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t PoolVector<int> arr; arr.resize(p_index_len); - if (p_vertex_len<(1<<16)) { + if (p_vertex_len < (1 << 16)) { PoolVector<int>::Write w = arr.write(); - for(int j=0;j<p_index_len;j++) { + for (int j = 0; j < p_index_len; j++) { - const uint16_t *v = (const uint16_t*)&ir[j*2]; - w[j]=*v; + const uint16_t *v = (const uint16_t *)&ir[j * 2]; + w[j] = *v; } } else { PoolVector<int>::Write w = arr.write(); - for(int j=0;j<p_index_len;j++) { - const int *v = (const int*)&ir[j*4]; - w[j]=*v; + for (int j = 0; j < p_index_len; j++) { + const int *v = (const int *)&ir[j * 4]; + w[j] = *v; } - } - ret[i]=arr; + ret[i] = arr; } break; default: { - ERR_FAIL_V( ret ); + ERR_FAIL_V(ret); } } } @@ -1547,141 +1455,118 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t return ret; } -Array VisualServer::mesh_surface_get_arrays(RID p_mesh,int p_surface) const { - - PoolVector<uint8_t> vertex_data = mesh_surface_get_array(p_mesh,p_surface); - ERR_FAIL_COND_V(vertex_data.size()==0,Array()); - int vertex_len = mesh_surface_get_array_len(p_mesh,p_surface); - - PoolVector<uint8_t> index_data = mesh_surface_get_index_array(p_mesh,p_surface); - int index_len = mesh_surface_get_array_index_len(p_mesh,p_surface); +Array VisualServer::mesh_surface_get_arrays(RID p_mesh, int p_surface) const { - uint32_t format = mesh_surface_get_format(p_mesh,p_surface); + PoolVector<uint8_t> vertex_data = mesh_surface_get_array(p_mesh, p_surface); + ERR_FAIL_COND_V(vertex_data.size() == 0, Array()); + int vertex_len = mesh_surface_get_array_len(p_mesh, p_surface); + PoolVector<uint8_t> index_data = mesh_surface_get_index_array(p_mesh, p_surface); + int index_len = mesh_surface_get_array_index_len(p_mesh, p_surface); - return _get_array_from_surface(format,vertex_data,vertex_len,index_data,index_len); + uint32_t format = mesh_surface_get_format(p_mesh, p_surface); + return _get_array_from_surface(format, vertex_data, vertex_len, index_data, index_len); } void VisualServer::_bind_methods() { - - ClassDB::bind_method(D_METHOD("texture_create"),&VisualServer::texture_create); - ClassDB::bind_method(D_METHOD("texture_create_from_image"),&VisualServer::texture_create_from_image,DEFVAL( TEXTURE_FLAGS_DEFAULT ) ); + ClassDB::bind_method(D_METHOD("texture_create"), &VisualServer::texture_create); + ClassDB::bind_method(D_METHOD("texture_create_from_image"), &VisualServer::texture_create_from_image, DEFVAL(TEXTURE_FLAGS_DEFAULT)); //ClassDB::bind_method(D_METHOD("texture_allocate"),&VisualServer::texture_allocate,DEFVAL( TEXTURE_FLAGS_DEFAULT ) ); //ClassDB::bind_method(D_METHOD("texture_set_data"),&VisualServer::texture_blit_rect,DEFVAL( CUBEMAP_LEFT ) ); //ClassDB::bind_method(D_METHOD("texture_get_rect"),&VisualServer::texture_get_rect ); - ClassDB::bind_method(D_METHOD("texture_set_flags"),&VisualServer::texture_set_flags ); - ClassDB::bind_method(D_METHOD("texture_get_flags"),&VisualServer::texture_get_flags ); - ClassDB::bind_method(D_METHOD("texture_get_width"),&VisualServer::texture_get_width ); - ClassDB::bind_method(D_METHOD("texture_get_height"),&VisualServer::texture_get_height ); - - ClassDB::bind_method(D_METHOD("texture_set_shrink_all_x2_on_set_data","shrink"),&VisualServer::texture_set_shrink_all_x2_on_set_data ); - - - + ClassDB::bind_method(D_METHOD("texture_set_flags"), &VisualServer::texture_set_flags); + ClassDB::bind_method(D_METHOD("texture_get_flags"), &VisualServer::texture_get_flags); + ClassDB::bind_method(D_METHOD("texture_get_width"), &VisualServer::texture_get_width); + ClassDB::bind_method(D_METHOD("texture_get_height"), &VisualServer::texture_get_height); + ClassDB::bind_method(D_METHOD("texture_set_shrink_all_x2_on_set_data", "shrink"), &VisualServer::texture_set_shrink_all_x2_on_set_data); } -void VisualServer::_canvas_item_add_style_box(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector<float>& p_margins, const Color& p_modulate) { +void VisualServer::_canvas_item_add_style_box(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector<float> &p_margins, const Color &p_modulate) { - ERR_FAIL_COND(p_margins.size()!=4); + ERR_FAIL_COND(p_margins.size() != 4); //canvas_item_add_style_box(p_item,p_rect,p_source,p_texture,Vector2(p_margins[0],p_margins[1]),Vector2(p_margins[2],p_margins[3]),true,p_modulate); } -void VisualServer::_camera_set_orthogonal(RID p_camera,float p_size,float p_z_near,float p_z_far) { +void VisualServer::_camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) { - camera_set_orthogonal(p_camera,p_size,p_z_near,p_z_far); + camera_set_orthogonal(p_camera, p_size, p_z_near, p_z_far); } - - - - -void VisualServer::mesh_add_surface_from_mesh_data( RID p_mesh, const Geometry::MeshData& p_mesh_data) { +void VisualServer::mesh_add_surface_from_mesh_data(RID p_mesh, const Geometry::MeshData &p_mesh_data) { #if 1 PoolVector<Vector3> vertices; PoolVector<Vector3> normals; - for (int i=0;i<p_mesh_data.faces.size();i++) { + for (int i = 0; i < p_mesh_data.faces.size(); i++) { - const Geometry::MeshData::Face& f = p_mesh_data.faces[i]; + const Geometry::MeshData::Face &f = p_mesh_data.faces[i]; - for (int j=2;j<f.indices.size();j++) { + for (int j = 2; j < f.indices.size(); j++) { -#define _ADD_VERTEX(m_idx)\ - vertices.push_back( p_mesh_data.vertices[ f.indices[m_idx] ] );\ - normals.push_back( f.plane.normal ); +#define _ADD_VERTEX(m_idx) \ + vertices.push_back(p_mesh_data.vertices[f.indices[m_idx]]); \ + normals.push_back(f.plane.normal); - _ADD_VERTEX( 0 ); - _ADD_VERTEX( j-1 ); - _ADD_VERTEX( j ); + _ADD_VERTEX(0); + _ADD_VERTEX(j - 1); + _ADD_VERTEX(j); } } Array d; d.resize(VS::ARRAY_MAX); - d[ARRAY_VERTEX]=vertices; - d[ARRAY_NORMAL]=normals; - mesh_add_surface_from_arrays(p_mesh,PRIMITIVE_TRIANGLES, d); + d[ARRAY_VERTEX] = vertices; + d[ARRAY_NORMAL] = normals; + mesh_add_surface_from_arrays(p_mesh, PRIMITIVE_TRIANGLES, d); #else - PoolVector<Vector3> vertices; + for (int i = 0; i < p_mesh_data.edges.size(); i++) { - - for (int i=0;i<p_mesh_data.edges.size();i++) { - - const Geometry::MeshData::Edge& f = p_mesh_data.edges[i]; - vertices.push_back(p_mesh_data.vertices[ f.a]); - vertices.push_back(p_mesh_data.vertices[ f.b]); + const Geometry::MeshData::Edge &f = p_mesh_data.edges[i]; + vertices.push_back(p_mesh_data.vertices[f.a]); + vertices.push_back(p_mesh_data.vertices[f.b]); } Array d; d.resize(VS::ARRAY_MAX); - d[ARRAY_VERTEX]=vertices; - mesh_add_surface(p_mesh,PRIMITIVE_LINES, d); - - - + d[ARRAY_VERTEX] = vertices; + mesh_add_surface(p_mesh, PRIMITIVE_LINES, d); #endif - } -void VisualServer::mesh_add_surface_from_planes( RID p_mesh, const PoolVector<Plane>& p_planes) { - +void VisualServer::mesh_add_surface_from_planes(RID p_mesh, const PoolVector<Plane> &p_planes) { Geometry::MeshData mdata = Geometry::build_convex_mesh(p_planes); - mesh_add_surface_from_mesh_data(p_mesh,mdata); - + mesh_add_surface_from_mesh_data(p_mesh, mdata); } -void VisualServer::immediate_vertex_2d(RID p_immediate,const Vector2& p_vertex) { - immediate_vertex(p_immediate,Vector3(p_vertex.x,p_vertex.y,0)); +void VisualServer::immediate_vertex_2d(RID p_immediate, const Vector2 &p_vertex) { + immediate_vertex(p_immediate, Vector3(p_vertex.x, p_vertex.y, 0)); } RID VisualServer::instance_create2(RID p_base, RID p_scenario) { RID instance = instance_create(); - instance_set_base(instance,p_base); - instance_set_scenario(instance,p_scenario); + instance_set_base(instance, p_base); + instance_set_scenario(instance, p_scenario); return instance; } - VisualServer::VisualServer() { //ERR_FAIL_COND(singleton); - singleton=this; - + singleton = this; } - VisualServer::~VisualServer() { - singleton=NULL; + singleton = NULL; } diff --git a/servers/visual_server.h b/servers/visual_server.h index 08cf34a653..dfa253ff25 100644 --- a/servers/visual_server.h +++ b/servers/visual_server.h @@ -29,29 +29,28 @@ #ifndef VISUAL_SERVER_H #define VISUAL_SERVER_H - -#include "rid.h" -#include "variant.h" -#include "math_2d.h" #include "bsp_tree.h" #include "geometry.h" +#include "math_2d.h" #include "object.h" +#include "rid.h" +#include "variant.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class VisualServer : public Object { - GDCLASS( VisualServer, Object ); + GDCLASS(VisualServer, Object); static VisualServer *singleton; int mm_policy; PoolVector<String> _shader_get_param_list(RID p_shader) const; - void _camera_set_orthogonal(RID p_camera,float p_size,float p_z_near,float p_z_far); - void _canvas_item_add_style_box(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector<float>& p_margins, const Color& p_modulate=Color(1,1,1)); - Array _get_array_from_surface(uint32_t p_format,PoolVector<uint8_t> p_vertex_data,int p_vertex_len,PoolVector<uint8_t> p_index_data,int p_index_len) const; + void _camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far); + void _canvas_item_add_style_box(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector<float> &p_margins, const Color &p_modulate = Color(1, 1, 1)); + Array _get_array_from_surface(uint32_t p_format, PoolVector<uint8_t> p_vertex_data, int p_vertex_len, PoolVector<uint8_t> p_index_data, int p_index_len) const; protected: RID _make_test_cube(); @@ -61,28 +60,22 @@ protected: RID test_material; RID material_2d[16]; + Error _surface_set_data(Array p_arrays, uint32_t p_format, uint32_t *p_offsets, uint32_t p_stride, PoolVector<uint8_t> &r_vertex_array, int p_vertex_array_len, PoolVector<uint8_t> &r_index_array, int p_index_array_len, Rect3 &r_aabb, Vector<Rect3> r_bone_aabb); - Error _surface_set_data(Array p_arrays,uint32_t p_format,uint32_t *p_offsets,uint32_t p_stride,PoolVector<uint8_t> &r_vertex_array,int p_vertex_array_len,PoolVector<uint8_t> &r_index_array,int p_index_array_len,Rect3 &r_aabb,Vector<Rect3> r_bone_aabb); - - static VisualServer* (*create_func)(); + static VisualServer *(*create_func)(); static void _bind_methods(); -public: +public: static VisualServer *get_singleton(); static VisualServer *create(); - - enum { - NO_INDEX_ARRAY=-1, - ARRAY_WEIGHTS_SIZE=4, - CANVAS_ITEM_Z_MIN=-4096, - CANVAS_ITEM_Z_MAX=4096, - MAX_GLOW_LEVELS=7, - - - + NO_INDEX_ARRAY = -1, + ARRAY_WEIGHTS_SIZE = 4, + CANVAS_ITEM_Z_MIN = -4096, + CANVAS_ITEM_Z_MAX = 4096, + MAX_GLOW_LEVELS = 7, MAX_CURSORS = 8, }; @@ -90,15 +83,15 @@ public: /* TEXTURE API */ enum TextureFlags { - TEXTURE_FLAG_MIPMAPS=1, /// Enable automatic mipmap generation - when available - TEXTURE_FLAG_REPEAT=2, /// Repeat texture (Tiling), otherwise Clamping - TEXTURE_FLAG_FILTER=4, /// Create texure with linear (or available) filter - TEXTURE_FLAG_ANISOTROPIC_FILTER=8, - TEXTURE_FLAG_CONVERT_TO_LINEAR=16, - TEXTURE_FLAG_MIRRORED_REPEAT=32, /// Repeat texture, with alternate sections mirrored - TEXTURE_FLAG_CUBEMAP=2048, - TEXTURE_FLAG_USED_FOR_STREAMING=4096, - TEXTURE_FLAGS_DEFAULT=TEXTURE_FLAG_REPEAT|TEXTURE_FLAG_MIPMAPS|TEXTURE_FLAG_FILTER + TEXTURE_FLAG_MIPMAPS = 1, /// Enable automatic mipmap generation - when available + TEXTURE_FLAG_REPEAT = 2, /// Repeat texture (Tiling), otherwise Clamping + TEXTURE_FLAG_FILTER = 4, /// Create texure with linear (or available) filter + TEXTURE_FLAG_ANISOTROPIC_FILTER = 8, + TEXTURE_FLAG_CONVERT_TO_LINEAR = 16, + TEXTURE_FLAG_MIRRORED_REPEAT = 32, /// Repeat texture, with alternate sections mirrored + TEXTURE_FLAG_CUBEMAP = 2048, + TEXTURE_FLAG_USED_FOR_STREAMING = 4096, + TEXTURE_FLAGS_DEFAULT = TEXTURE_FLAG_REPEAT | TEXTURE_FLAG_MIPMAPS | TEXTURE_FLAG_FILTER }; enum CubeMapSide { @@ -111,28 +104,27 @@ public: CUBEMAP_BACK }; + virtual RID texture_create() = 0; + RID texture_create_from_image(const Image &p_image, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT); // helper + virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT) = 0; + virtual void texture_set_data(RID p_texture, const Image &p_image, CubeMapSide p_cube_side = CUBEMAP_LEFT) = 0; + virtual Image texture_get_data(RID p_texture, CubeMapSide p_cube_side = CUBEMAP_LEFT) const = 0; + virtual void texture_set_flags(RID p_texture, uint32_t p_flags) = 0; + virtual uint32_t texture_get_flags(RID p_texture) const = 0; + virtual Image::Format texture_get_format(RID p_texture) const = 0; + virtual uint32_t texture_get_width(RID p_texture) const = 0; + virtual uint32_t texture_get_height(RID p_texture) const = 0; + virtual void texture_set_size_override(RID p_texture, int p_width, int p_height) = 0; - virtual RID texture_create()=0; - RID texture_create_from_image(const Image& p_image,uint32_t p_flags=TEXTURE_FLAGS_DEFAULT); // helper - virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=TEXTURE_FLAGS_DEFAULT)=0; - virtual void texture_set_data(RID p_texture,const Image& p_image,CubeMapSide p_cube_side=CUBEMAP_LEFT)=0; - virtual Image texture_get_data(RID p_texture,CubeMapSide p_cube_side=CUBEMAP_LEFT) const=0; - virtual void texture_set_flags(RID p_texture,uint32_t p_flags) =0; - virtual uint32_t texture_get_flags(RID p_texture) const=0; - virtual Image::Format texture_get_format(RID p_texture) const=0; - virtual uint32_t texture_get_width(RID p_texture) const=0; - virtual uint32_t texture_get_height(RID p_texture) const=0; - virtual void texture_set_size_override(RID p_texture,int p_width, int p_height)=0; + virtual void texture_set_path(RID p_texture, const String &p_path) = 0; + virtual String texture_get_path(RID p_texture) const = 0; - virtual void texture_set_path(RID p_texture,const String& p_path)=0; - virtual String texture_get_path(RID p_texture) const=0; + virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable) = 0; - virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable)=0; + typedef void (*TextureDetectCallback)(void *); - typedef void (*TextureDetectCallback)(void*); - - virtual void texture_set_detect_3d_callback(RID p_texture,TextureDetectCallback p_callback,void* p_userdata)=0; - virtual void texture_set_detect_srgb_callback(RID p_texture,TextureDetectCallback p_callback,void* p_userdata)=0; + virtual void texture_set_detect_3d_callback(RID p_texture, TextureDetectCallback p_callback, void *p_userdata) = 0; + virtual void texture_set_detect_srgb_callback(RID p_texture, TextureDetectCallback p_callback, void *p_userdata) = 0; struct TextureInfo { RID texture; @@ -142,14 +134,14 @@ public: String path; }; - virtual void texture_debug_usage(List<TextureInfo> *r_info)=0; + virtual void texture_debug_usage(List<TextureInfo> *r_info) = 0; - virtual void textures_keep_original(bool p_enable)=0; + virtual void textures_keep_original(bool p_enable) = 0; /* SKYBOX API */ - virtual RID skybox_create()=0; - virtual void skybox_set_texture(RID p_skybox,RID p_cube_map,int p_radiance_size)=0; + virtual RID skybox_create() = 0; + virtual void skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size) = 0; /* SHADER API */ @@ -161,137 +153,132 @@ public: SHADER_MAX }; + virtual RID shader_create(ShaderMode p_mode = SHADER_SPATIAL) = 0; - virtual RID shader_create(ShaderMode p_mode=SHADER_SPATIAL)=0; - - virtual void shader_set_mode(RID p_shader,ShaderMode p_mode)=0; - virtual ShaderMode shader_get_mode(RID p_shader) const=0; - - virtual void shader_set_code(RID p_shader, const String& p_code)=0; - virtual String shader_get_code(RID p_shader) const=0; - virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const=0; + virtual void shader_set_mode(RID p_shader, ShaderMode p_mode) = 0; + virtual ShaderMode shader_get_mode(RID p_shader) const = 0; - virtual void shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture)=0; - virtual RID shader_get_default_texture_param(RID p_shader, const StringName& p_name) const=0; + virtual void shader_set_code(RID p_shader, const String &p_code) = 0; + virtual String shader_get_code(RID p_shader) const = 0; + virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const = 0; + virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) = 0; + virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const = 0; /* COMMON MATERIAL API */ - virtual RID material_create()=0; + virtual RID material_create() = 0; - virtual void material_set_shader(RID p_shader_material, RID p_shader)=0; - virtual RID material_get_shader(RID p_shader_material) const=0; + virtual void material_set_shader(RID p_shader_material, RID p_shader) = 0; + virtual RID material_get_shader(RID p_shader_material) const = 0; - virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value)=0; - virtual Variant material_get_param(RID p_material, const StringName& p_param) const=0; + virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) = 0; + virtual Variant material_get_param(RID p_material, const StringName &p_param) const = 0; - virtual void material_set_line_width(RID p_material, float p_width)=0; + virtual void material_set_line_width(RID p_material, float p_width) = 0; /* MESH API */ enum ArrayType { - ARRAY_VERTEX=0, - ARRAY_NORMAL=1, - ARRAY_TANGENT=2, - ARRAY_COLOR=3, - ARRAY_TEX_UV=4, - ARRAY_TEX_UV2=5, - ARRAY_BONES=6, - ARRAY_WEIGHTS=7, - ARRAY_INDEX=8, - ARRAY_MAX=9 + ARRAY_VERTEX = 0, + ARRAY_NORMAL = 1, + ARRAY_TANGENT = 2, + ARRAY_COLOR = 3, + ARRAY_TEX_UV = 4, + ARRAY_TEX_UV2 = 5, + ARRAY_BONES = 6, + ARRAY_WEIGHTS = 7, + ARRAY_INDEX = 8, + ARRAY_MAX = 9 }; enum ArrayFormat { /* ARRAY FORMAT FLAGS */ - ARRAY_FORMAT_VERTEX=1<<ARRAY_VERTEX, // mandatory - ARRAY_FORMAT_NORMAL=1<<ARRAY_NORMAL, - ARRAY_FORMAT_TANGENT=1<<ARRAY_TANGENT, - ARRAY_FORMAT_COLOR=1<<ARRAY_COLOR, - ARRAY_FORMAT_TEX_UV=1<<ARRAY_TEX_UV, - ARRAY_FORMAT_TEX_UV2=1<<ARRAY_TEX_UV2, - ARRAY_FORMAT_BONES=1<<ARRAY_BONES, - ARRAY_FORMAT_WEIGHTS=1<<ARRAY_WEIGHTS, - ARRAY_FORMAT_INDEX=1<<ARRAY_INDEX, - - ARRAY_COMPRESS_BASE=(ARRAY_INDEX+1), - ARRAY_COMPRESS_VERTEX=1<<(ARRAY_VERTEX+ARRAY_COMPRESS_BASE), // mandatory - ARRAY_COMPRESS_NORMAL=1<<(ARRAY_NORMAL+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_TANGENT=1<<(ARRAY_TANGENT+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_COLOR=1<<(ARRAY_COLOR+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_TEX_UV=1<<(ARRAY_TEX_UV+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_TEX_UV2=1<<(ARRAY_TEX_UV2+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_BONES=1<<(ARRAY_BONES+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_WEIGHTS=1<<(ARRAY_WEIGHTS+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_INDEX=1<<(ARRAY_INDEX+ARRAY_COMPRESS_BASE), - - ARRAY_FLAG_USE_2D_VERTICES=ARRAY_COMPRESS_INDEX<<1, - ARRAY_FLAG_USE_16_BIT_BONES=ARRAY_COMPRESS_INDEX<<2, - - ARRAY_COMPRESS_DEFAULT=ARRAY_COMPRESS_VERTEX|ARRAY_COMPRESS_NORMAL|ARRAY_COMPRESS_TANGENT|ARRAY_COMPRESS_COLOR|ARRAY_COMPRESS_TEX_UV|ARRAY_COMPRESS_TEX_UV2|ARRAY_COMPRESS_WEIGHTS + ARRAY_FORMAT_VERTEX = 1 << ARRAY_VERTEX, // mandatory + ARRAY_FORMAT_NORMAL = 1 << ARRAY_NORMAL, + ARRAY_FORMAT_TANGENT = 1 << ARRAY_TANGENT, + ARRAY_FORMAT_COLOR = 1 << ARRAY_COLOR, + ARRAY_FORMAT_TEX_UV = 1 << ARRAY_TEX_UV, + ARRAY_FORMAT_TEX_UV2 = 1 << ARRAY_TEX_UV2, + ARRAY_FORMAT_BONES = 1 << ARRAY_BONES, + ARRAY_FORMAT_WEIGHTS = 1 << ARRAY_WEIGHTS, + ARRAY_FORMAT_INDEX = 1 << ARRAY_INDEX, + + ARRAY_COMPRESS_BASE = (ARRAY_INDEX + 1), + ARRAY_COMPRESS_VERTEX = 1 << (ARRAY_VERTEX + ARRAY_COMPRESS_BASE), // mandatory + ARRAY_COMPRESS_NORMAL = 1 << (ARRAY_NORMAL + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_TANGENT = 1 << (ARRAY_TANGENT + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_COLOR = 1 << (ARRAY_COLOR + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_TEX_UV = 1 << (ARRAY_TEX_UV + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_TEX_UV2 = 1 << (ARRAY_TEX_UV2 + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_BONES = 1 << (ARRAY_BONES + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_WEIGHTS = 1 << (ARRAY_WEIGHTS + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_INDEX = 1 << (ARRAY_INDEX + ARRAY_COMPRESS_BASE), + + ARRAY_FLAG_USE_2D_VERTICES = ARRAY_COMPRESS_INDEX << 1, + ARRAY_FLAG_USE_16_BIT_BONES = ARRAY_COMPRESS_INDEX << 2, + + ARRAY_COMPRESS_DEFAULT = ARRAY_COMPRESS_VERTEX | ARRAY_COMPRESS_NORMAL | ARRAY_COMPRESS_TANGENT | ARRAY_COMPRESS_COLOR | ARRAY_COMPRESS_TEX_UV | ARRAY_COMPRESS_TEX_UV2 | ARRAY_COMPRESS_WEIGHTS }; - enum PrimitiveType { - PRIMITIVE_POINTS=0, - PRIMITIVE_LINES=1, - PRIMITIVE_LINE_STRIP=2, - PRIMITIVE_LINE_LOOP=3, - PRIMITIVE_TRIANGLES=4, - PRIMITIVE_TRIANGLE_STRIP=5, - PRIMITIVE_TRIANGLE_FAN=6, - PRIMITIVE_MAX=7, + PRIMITIVE_POINTS = 0, + PRIMITIVE_LINES = 1, + PRIMITIVE_LINE_STRIP = 2, + PRIMITIVE_LINE_LOOP = 3, + PRIMITIVE_TRIANGLES = 4, + PRIMITIVE_TRIANGLE_STRIP = 5, + PRIMITIVE_TRIANGLE_FAN = 6, + PRIMITIVE_MAX = 7, }; - virtual RID mesh_create()=0; - + virtual RID mesh_create() = 0; - virtual void mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes=Array(),uint32_t p_compress_format=ARRAY_COMPRESS_DEFAULT); - virtual void mesh_add_surface(RID p_mesh,uint32_t p_format,PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>())=0; + virtual void mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), uint32_t p_compress_format = ARRAY_COMPRESS_DEFAULT); + virtual void mesh_add_surface(RID p_mesh, uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>()) = 0; - virtual void mesh_set_blend_shape_count(RID p_mesh,int p_amount)=0; - virtual int mesh_get_blend_shape_count(RID p_mesh) const=0; + virtual void mesh_set_blend_shape_count(RID p_mesh, int p_amount) = 0; + virtual int mesh_get_blend_shape_count(RID p_mesh) const = 0; enum BlendShapeMode { BLEND_SHAPE_MODE_NORMALIZED, BLEND_SHAPE_MODE_RELATIVE, }; - virtual void mesh_set_blend_shape_mode(RID p_mesh,BlendShapeMode p_mode)=0; - virtual BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const=0; + virtual void mesh_set_blend_shape_mode(RID p_mesh, BlendShapeMode p_mode) = 0; + virtual BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const = 0; - virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material)=0; - virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const=0; + virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) = 0; + virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const = 0; - virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const=0; - virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const=0; + virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const = 0; + virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const = 0; - virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const=0; - virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const=0; + virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const = 0; + virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const = 0; - virtual Array mesh_surface_get_arrays(RID p_mesh,int p_surface) const; + virtual Array mesh_surface_get_arrays(RID p_mesh, int p_surface) const; - virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const=0; - virtual PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const=0; + virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const = 0; + virtual PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const = 0; - virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const=0; - virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const=0; - virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const=0; + virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const = 0; + virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const = 0; + virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const = 0; - virtual void mesh_remove_surface(RID p_mesh,int p_index)=0; - virtual int mesh_get_surface_count(RID p_mesh) const=0; + virtual void mesh_remove_surface(RID p_mesh, int p_index) = 0; + virtual int mesh_get_surface_count(RID p_mesh) const = 0; - virtual void mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb)=0; - virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const=0; + virtual void mesh_set_custom_aabb(RID p_mesh, const Rect3 &p_aabb) = 0; + virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const = 0; - virtual void mesh_clear(RID p_mesh)=0; + virtual void mesh_clear(RID p_mesh) = 0; /* MULTIMESH API */ - - virtual RID multimesh_create()=0; + virtual RID multimesh_create() = 0; enum MultimeshTransformFormat { MULTIMESH_TRANSFORM_2D, @@ -304,50 +291,49 @@ public: MULTIMESH_COLOR_FLOAT, }; - virtual void multimesh_allocate(RID p_multimesh,int p_instances,MultimeshTransformFormat p_transform_format,MultimeshColorFormat p_color_format)=0; - virtual int multimesh_get_instance_count(RID p_multimesh) const=0; - - virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh)=0; - virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform)=0; - virtual void multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform)=0; - virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color)=0; + virtual void multimesh_allocate(RID p_multimesh, int p_instances, MultimeshTransformFormat p_transform_format, MultimeshColorFormat p_color_format) = 0; + virtual int multimesh_get_instance_count(RID p_multimesh) const = 0; - virtual RID multimesh_get_mesh(RID p_multimesh) const=0; - virtual Rect3 multimesh_get_aabb(RID p_multimesh) const=0; + virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) = 0; + virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) = 0; + virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) = 0; + virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) = 0; - virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const=0; - virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const=0; - virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const=0; + virtual RID multimesh_get_mesh(RID p_multimesh) const = 0; + virtual Rect3 multimesh_get_aabb(RID p_multimesh) const = 0; - virtual void multimesh_set_visible_instances(RID p_multimesh,int p_visible)=0; - virtual int multimesh_get_visible_instances(RID p_multimesh) const=0; + virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const = 0; + virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const = 0; + virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const = 0; + virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) = 0; + virtual int multimesh_get_visible_instances(RID p_multimesh) const = 0; /* IMMEDIATE API */ - virtual RID immediate_create()=0; - virtual void immediate_begin(RID p_immediate,PrimitiveType p_rimitive,RID p_texture=RID())=0; - virtual void immediate_vertex(RID p_immediate,const Vector3& p_vertex)=0; - virtual void immediate_vertex_2d(RID p_immediate,const Vector2& p_vertex); - virtual void immediate_normal(RID p_immediate,const Vector3& p_normal)=0; - virtual void immediate_tangent(RID p_immediate,const Plane& p_tangent)=0; - virtual void immediate_color(RID p_immediate,const Color& p_color)=0; - virtual void immediate_uv(RID p_immediate,const Vector2& tex_uv)=0; - virtual void immediate_uv2(RID p_immediate,const Vector2& tex_uv)=0; - virtual void immediate_end(RID p_immediate)=0; - virtual void immediate_clear(RID p_immediate)=0; - virtual void immediate_set_material(RID p_immediate,RID p_material)=0; - virtual RID immediate_get_material(RID p_immediate) const=0; + virtual RID immediate_create() = 0; + virtual void immediate_begin(RID p_immediate, PrimitiveType p_rimitive, RID p_texture = RID()) = 0; + virtual void immediate_vertex(RID p_immediate, const Vector3 &p_vertex) = 0; + virtual void immediate_vertex_2d(RID p_immediate, const Vector2 &p_vertex); + virtual void immediate_normal(RID p_immediate, const Vector3 &p_normal) = 0; + virtual void immediate_tangent(RID p_immediate, const Plane &p_tangent) = 0; + virtual void immediate_color(RID p_immediate, const Color &p_color) = 0; + virtual void immediate_uv(RID p_immediate, const Vector2 &tex_uv) = 0; + virtual void immediate_uv2(RID p_immediate, const Vector2 &tex_uv) = 0; + virtual void immediate_end(RID p_immediate) = 0; + virtual void immediate_clear(RID p_immediate) = 0; + virtual void immediate_set_material(RID p_immediate, RID p_material) = 0; + virtual RID immediate_get_material(RID p_immediate) const = 0; /* SKELETON API */ - virtual RID skeleton_create()=0; - virtual void skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton=false)=0; - virtual int skeleton_get_bone_count(RID p_skeleton) const=0; - virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform)=0; - virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone) const=0; - virtual void skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform)=0; - virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone)const =0; + virtual RID skeleton_create() = 0; + virtual void skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) = 0; + virtual int skeleton_get_bone_count(RID p_skeleton) const = 0; + virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) = 0; + virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone) const = 0; + virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) = 0; + virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const = 0; /* Light API */ @@ -376,15 +362,15 @@ public: LIGHT_PARAM_MAX }; - virtual RID light_create(LightType p_type)=0; + virtual RID light_create(LightType p_type) = 0; - virtual void light_set_color(RID p_light,const Color& p_color)=0; - virtual void light_set_param(RID p_light,LightParam p_param,float p_value)=0; - virtual void light_set_shadow(RID p_light,bool p_enabled)=0; - virtual void light_set_shadow_color(RID p_light,const Color& p_color)=0; - virtual void light_set_projector(RID p_light,RID p_texture)=0; - virtual void light_set_negative(RID p_light,bool p_enable)=0; - virtual void light_set_cull_mask(RID p_light,uint32_t p_mask)=0; + virtual void light_set_color(RID p_light, const Color &p_color) = 0; + virtual void light_set_param(RID p_light, LightParam p_param, float p_value) = 0; + virtual void light_set_shadow(RID p_light, bool p_enabled) = 0; + virtual void light_set_shadow_color(RID p_light, const Color &p_color) = 0; + virtual void light_set_projector(RID p_light, RID p_texture) = 0; + virtual void light_set_negative(RID p_light, bool p_enable) = 0; + virtual void light_set_cull_mask(RID p_light, uint32_t p_mask) = 0; // omni light enum LightOmniShadowMode { @@ -392,7 +378,7 @@ public: LIGHT_OMNI_SHADOW_CUBE, }; - virtual void light_omni_set_shadow_mode(RID p_light,LightOmniShadowMode p_mode)=0; + virtual void light_omni_set_shadow_mode(RID p_light, LightOmniShadowMode p_mode) = 0; // omni light enum LightOmniShadowDetail { @@ -400,7 +386,7 @@ public: LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL }; - virtual void light_omni_set_shadow_detail(RID p_light,LightOmniShadowDetail p_detail)=0; + virtual void light_omni_set_shadow_detail(RID p_light, LightOmniShadowDetail p_detail) = 0; // directional light enum LightDirectionalShadowMode { @@ -409,98 +395,96 @@ public: LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS }; - virtual void light_directional_set_shadow_mode(RID p_light,LightDirectionalShadowMode p_mode)=0; - virtual void light_directional_set_blend_splits(RID p_light,bool p_enable)=0; + virtual void light_directional_set_shadow_mode(RID p_light, LightDirectionalShadowMode p_mode) = 0; + virtual void light_directional_set_blend_splits(RID p_light, bool p_enable) = 0; /* PROBE API */ - virtual RID reflection_probe_create()=0; + virtual RID reflection_probe_create() = 0; enum ReflectionProbeUpdateMode { REFLECTION_PROBE_UPDATE_ONCE, REFLECTION_PROBE_UPDATE_ALWAYS, }; - - virtual void reflection_probe_set_update_mode(RID p_probe, ReflectionProbeUpdateMode p_mode)=0; - virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity)=0; - virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color& p_color)=0; - virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy)=0; - virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib)=0; - virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance)=0; - virtual void reflection_probe_set_extents(RID p_probe, const Vector3& p_extents)=0; - virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset)=0; - virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable)=0; - virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable)=0; - virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable)=0; - virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers)=0; - + virtual void reflection_probe_set_update_mode(RID p_probe, ReflectionProbeUpdateMode p_mode) = 0; + virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity) = 0; + virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color &p_color) = 0; + virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) = 0; + virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) = 0; + virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance) = 0; + virtual void reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) = 0; + virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) = 0; + virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable) = 0; + virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) = 0; + virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) = 0; + virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) = 0; /* ROOM API */ - virtual RID room_create()=0; - virtual void room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform)=0; - virtual void room_clear_bounds(RID p_room)=0; + virtual RID room_create() = 0; + virtual void room_add_bounds(RID p_room, const PoolVector<Vector2> &p_convex_polygon, float p_height, const Transform &p_transform) = 0; + virtual void room_clear_bounds(RID p_room) = 0; /* PORTAL API */ // portals are only (x/y) points, forming a convex shape, which its clockwise // order points outside. (z is 0); - virtual RID portal_create()=0; - virtual void portal_set_shape(RID p_portal, const Vector<Point2>& p_shape)=0; - virtual void portal_set_enabled(RID p_portal, bool p_enabled)=0; - virtual void portal_set_disable_distance(RID p_portal, float p_distance)=0; - virtual void portal_set_disabled_color(RID p_portal, const Color& p_color)=0; + virtual RID portal_create() = 0; + virtual void portal_set_shape(RID p_portal, const Vector<Point2> &p_shape) = 0; + virtual void portal_set_enabled(RID p_portal, bool p_enabled) = 0; + virtual void portal_set_disable_distance(RID p_portal, float p_distance) = 0; + virtual void portal_set_disabled_color(RID p_portal, const Color &p_color) = 0; /* GI PROBE API */ - virtual RID gi_probe_create()=0; + virtual RID gi_probe_create() = 0; - virtual void gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds)=0; - virtual Rect3 gi_probe_get_bounds(RID p_probe) const=0; + virtual void gi_probe_set_bounds(RID p_probe, const Rect3 &p_bounds) = 0; + virtual Rect3 gi_probe_get_bounds(RID p_probe) const = 0; - virtual void gi_probe_set_cell_size(RID p_probe,float p_range)=0; - virtual float gi_probe_get_cell_size(RID p_probe) const=0; + virtual void gi_probe_set_cell_size(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_cell_size(RID p_probe) const = 0; - virtual void gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform)=0; - virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const=0; + virtual void gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform) = 0; + virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const = 0; - virtual void gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data)=0; - virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const=0; + virtual void gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data) = 0; + virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const = 0; - virtual void gi_probe_set_dynamic_range(RID p_probe,int p_range)=0; - virtual int gi_probe_get_dynamic_range(RID p_probe) const=0; + virtual void gi_probe_set_dynamic_range(RID p_probe, int p_range) = 0; + virtual int gi_probe_get_dynamic_range(RID p_probe) const = 0; - virtual void gi_probe_set_energy(RID p_probe,float p_range)=0; - virtual float gi_probe_get_energy(RID p_probe) const=0; + virtual void gi_probe_set_energy(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_energy(RID p_probe) const = 0; - virtual void gi_probe_set_bias(RID p_probe,float p_range)=0; - virtual float gi_probe_get_bias(RID p_probe) const=0; + virtual void gi_probe_set_bias(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_bias(RID p_probe) const = 0; - virtual void gi_probe_set_propagation(RID p_probe,float p_range)=0; - virtual float gi_probe_get_propagation(RID p_probe) const=0; + virtual void gi_probe_set_propagation(RID p_probe, float p_range) = 0; + virtual float gi_probe_get_propagation(RID p_probe) const = 0; - virtual void gi_probe_set_interior(RID p_probe,bool p_enable)=0; - virtual bool gi_probe_is_interior(RID p_probe) const=0; + virtual void gi_probe_set_interior(RID p_probe, bool p_enable) = 0; + virtual bool gi_probe_is_interior(RID p_probe) const = 0; - virtual void gi_probe_set_compress(RID p_probe,bool p_enable)=0; - virtual bool gi_probe_is_compressed(RID p_probe) const=0; + virtual void gi_probe_set_compress(RID p_probe, bool p_enable) = 0; + virtual bool gi_probe_is_compressed(RID p_probe) const = 0; /* PARTICLES API */ - virtual RID particles_create()=0; + virtual RID particles_create() = 0; - virtual void particles_set_emitting(RID p_particles,bool p_emitting)=0; - virtual void particles_set_amount(RID p_particles,int p_amount)=0; - virtual void particles_set_lifetime(RID p_particles,float p_lifetime)=0; - virtual void particles_set_pre_process_time(RID p_particles,float p_time)=0; - virtual void particles_set_explosiveness_ratio(RID p_particles,float p_ratio)=0; - virtual void particles_set_randomness_ratio(RID p_particles,float p_ratio)=0; - virtual void particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb)=0; - virtual void particles_set_gravity(RID p_particles,const Vector3& p_gravity)=0; - virtual void particles_set_use_local_coordinates(RID p_particles,bool p_enable)=0; - virtual void particles_set_process_material(RID p_particles,RID p_material)=0; + virtual void particles_set_emitting(RID p_particles, bool p_emitting) = 0; + virtual void particles_set_amount(RID p_particles, int p_amount) = 0; + virtual void particles_set_lifetime(RID p_particles, float p_lifetime) = 0; + virtual void particles_set_pre_process_time(RID p_particles, float p_time) = 0; + virtual void particles_set_explosiveness_ratio(RID p_particles, float p_ratio) = 0; + virtual void particles_set_randomness_ratio(RID p_particles, float p_ratio) = 0; + virtual void particles_set_custom_aabb(RID p_particles, const Rect3 &p_aabb) = 0; + virtual void particles_set_gravity(RID p_particles, const Vector3 &p_gravity) = 0; + virtual void particles_set_use_local_coordinates(RID p_particles, bool p_enable) = 0; + virtual void particles_set_process_material(RID p_particles, RID p_material) = 0; enum ParticlesEmissionShape { PARTICLES_EMSSION_POINT, @@ -510,10 +494,10 @@ public: PARTICLES_EMSSION_SEGMENTS, }; - virtual void particles_set_emission_shape(RID p_particles,ParticlesEmissionShape)=0; - virtual void particles_set_emission_sphere_radius(RID p_particles,float p_radius)=0; - virtual void particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents)=0; - virtual void particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points)=0; + virtual void particles_set_emission_shape(RID p_particles, ParticlesEmissionShape) = 0; + virtual void particles_set_emission_sphere_radius(RID p_particles, float p_radius) = 0; + virtual void particles_set_emission_box_extents(RID p_particles, const Vector3 &p_extents) = 0; + virtual void particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points) = 0; enum ParticlesDrawOrder { PARTICLES_DRAW_ORDER_INDEX, @@ -521,31 +505,30 @@ public: PARTICLES_DRAW_ORDER_VIEW_DEPTH, }; - virtual void particles_set_draw_order(RID p_particles,ParticlesDrawOrder p_order)=0; + virtual void particles_set_draw_order(RID p_particles, ParticlesDrawOrder p_order) = 0; enum ParticlesDrawPassMode { PARTICLES_DRAW_PASS_MODE_QUAD, PARTICLES_DRAW_PASS_MODE_MESH }; + virtual void particles_set_draw_passes(RID p_particles, int p_count) = 0; + virtual void particles_set_draw_pass_material(RID p_particles, int p_pass, RID p_material) = 0; + virtual void particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) = 0; - virtual void particles_set_draw_passes(RID p_particles,int p_count)=0; - virtual void particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material)=0; - virtual void particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh)=0; - - virtual Rect3 particles_get_current_aabb(RID p_particles)=0; + virtual Rect3 particles_get_current_aabb(RID p_particles) = 0; /* CAMERA API */ - virtual RID camera_create()=0; - virtual void camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far)=0; - virtual void camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far)=0; - virtual void camera_set_transform(RID p_camera,const Transform& p_transform)=0; - virtual void camera_set_cull_mask(RID p_camera,uint32_t p_layers)=0; - virtual void camera_set_environment(RID p_camera,RID p_env)=0; - virtual void camera_set_use_vertical_aspect(RID p_camera,bool p_enable)=0; + virtual RID camera_create() = 0; + virtual void camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) = 0; + virtual void camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) = 0; + virtual void camera_set_transform(RID p_camera, const Transform &p_transform) = 0; + virtual void camera_set_cull_mask(RID p_camera, uint32_t p_layers) = 0; + virtual void camera_set_environment(RID p_camera, RID p_env) = 0; + virtual void camera_set_use_vertical_aspect(RID p_camera, bool p_enable) = 0; -/* + /* enum ParticlesCollisionMode { PARTICLES_COLLISION_NONE, PARTICLES_COLLISION_TEXTURE, @@ -556,14 +539,14 @@ public: */ /* VIEWPORT TARGET API */ - virtual RID viewport_create()=0; + virtual RID viewport_create() = 0; - virtual void viewport_set_size(RID p_viewport,int p_width,int p_height)=0; - virtual void viewport_set_active(RID p_viewport,bool p_active)=0; - virtual void viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport)=0; + virtual void viewport_set_size(RID p_viewport, int p_width, int p_height) = 0; + virtual void viewport_set_active(RID p_viewport, bool p_active) = 0; + virtual void viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport) = 0; - virtual void viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect=Rect2(),int p_screen=0)=0; - virtual void viewport_detach(RID p_viewport)=0; + virtual void viewport_attach_to_screen(RID p_viewport, const Rect2 &p_rect = Rect2(), int p_screen = 0) = 0; + virtual void viewport_detach(RID p_viewport) = 0; enum ViewportUpdateMode { VIEWPORT_UPDATE_DISABLED, @@ -572,9 +555,8 @@ public: VIEWPORT_UPDATE_ALWAYS }; - - virtual void viewport_set_update_mode(RID p_viewport,ViewportUpdateMode p_mode)=0; - virtual void viewport_set_vflip(RID p_viewport,bool p_enable)=0; + virtual void viewport_set_update_mode(RID p_viewport, ViewportUpdateMode p_mode) = 0; + virtual void viewport_set_vflip(RID p_viewport, bool p_enable) = 0; enum ViewportClearMode { @@ -583,27 +565,27 @@ public: VIEWPORT_CLEAR_ONLY_NEXT_FRAME }; - virtual void viewport_set_clear_mode(RID p_viewport,ViewportClearMode p_clear_mode)=0; + virtual void viewport_set_clear_mode(RID p_viewport, ViewportClearMode p_clear_mode) = 0; - virtual RID viewport_get_texture(RID p_viewport) const=0; + virtual RID viewport_get_texture(RID p_viewport) const = 0; - virtual void viewport_set_hide_scenario(RID p_viewport,bool p_hide)=0; - virtual void viewport_set_hide_canvas(RID p_viewport,bool p_hide)=0; - virtual void viewport_set_disable_environment(RID p_viewport,bool p_disable)=0; - virtual void viewport_set_disable_3d(RID p_viewport,bool p_disable)=0; + virtual void viewport_set_hide_scenario(RID p_viewport, bool p_hide) = 0; + virtual void viewport_set_hide_canvas(RID p_viewport, bool p_hide) = 0; + virtual void viewport_set_disable_environment(RID p_viewport, bool p_disable) = 0; + virtual void viewport_set_disable_3d(RID p_viewport, bool p_disable) = 0; - virtual void viewport_attach_camera(RID p_viewport,RID p_camera)=0; - virtual void viewport_set_scenario(RID p_viewport,RID p_scenario)=0; - virtual void viewport_attach_canvas(RID p_viewport,RID p_canvas)=0; - virtual void viewport_remove_canvas(RID p_viewport,RID p_canvas)=0; - virtual void viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset)=0; - virtual void viewport_set_transparent_background(RID p_viewport,bool p_enabled)=0; + virtual void viewport_attach_camera(RID p_viewport, RID p_camera) = 0; + virtual void viewport_set_scenario(RID p_viewport, RID p_scenario) = 0; + virtual void viewport_attach_canvas(RID p_viewport, RID p_canvas) = 0; + virtual void viewport_remove_canvas(RID p_viewport, RID p_canvas) = 0; + virtual void viewport_set_canvas_transform(RID p_viewport, RID p_canvas, const Transform2D &p_offset) = 0; + virtual void viewport_set_transparent_background(RID p_viewport, bool p_enabled) = 0; - virtual void viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform)=0; - virtual void viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer)=0; + virtual void viewport_set_global_canvas_transform(RID p_viewport, const Transform2D &p_transform) = 0; + virtual void viewport_set_canvas_layer(RID p_viewport, RID p_canvas, int p_layer) = 0; - virtual void viewport_set_shadow_atlas_size(RID p_viewport,int p_size)=0; - virtual void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv)=0; + virtual void viewport_set_shadow_atlas_size(RID p_viewport, int p_size) = 0; + virtual void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport, int p_quadrant, int p_subdiv) = 0; enum ViewportMSAA { VIEWPORT_MSAA_DISABLED, @@ -613,12 +595,12 @@ public: VIEWPORT_MSAA_16X, }; - virtual void viewport_set_msaa(RID p_viewport,ViewportMSAA p_msaa)=0; - virtual void viewport_set_hdr(RID p_viewport,bool p_enabled)=0; + virtual void viewport_set_msaa(RID p_viewport, ViewportMSAA p_msaa) = 0; + virtual void viewport_set_hdr(RID p_viewport, bool p_enabled) = 0; /* ENVIRONMENT API */ - virtual RID environment_create()=0; + virtual RID environment_create() = 0; enum EnvironmentBG { @@ -630,13 +612,13 @@ public: ENV_BG_MAX }; - virtual void environment_set_background(RID p_env,EnvironmentBG p_bg)=0; - virtual void environment_set_skybox(RID p_env,RID p_skybox)=0; - virtual void environment_set_skybox_scale(RID p_env,float p_scale)=0; - virtual void environment_set_bg_color(RID p_env,const Color& p_color)=0; - virtual void environment_set_bg_energy(RID p_env,float p_energy)=0; - virtual void environment_set_canvas_max_layer(RID p_env,int p_max_layer)=0; - virtual void environment_set_ambient_light(RID p_env,const Color& p_color,float p_energy=1.0,float p_skybox_contribution=0.0)=0; + virtual void environment_set_background(RID p_env, EnvironmentBG p_bg) = 0; + virtual void environment_set_skybox(RID p_env, RID p_skybox) = 0; + virtual void environment_set_skybox_scale(RID p_env, float p_scale) = 0; + virtual void environment_set_bg_color(RID p_env, const Color &p_color) = 0; + virtual void environment_set_bg_energy(RID p_env, float p_energy) = 0; + virtual void environment_set_canvas_max_layer(RID p_env, int p_max_layer) = 0; + virtual void environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy = 1.0, float p_skybox_contribution = 0.0) = 0; //set default SSAO options //set default SSR options @@ -648,8 +630,8 @@ public: ENV_DOF_BLUR_QUALITY_HIGH, }; - virtual void environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,EnvironmentDOFBlurQuality p_quality)=0; - virtual void environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,EnvironmentDOFBlurQuality p_quality)=0; + virtual void environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, EnvironmentDOFBlurQuality p_quality) = 0; + virtual void environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, EnvironmentDOFBlurQuality p_quality) = 0; enum EnvironmentGlowBlendMode { GLOW_BLEND_MODE_ADDITIVE, @@ -657,9 +639,8 @@ public: GLOW_BLEND_MODE_SOFTLIGHT, GLOW_BLEND_MODE_REPLACE, }; - virtual void environment_set_glow(RID p_env,bool p_enable,int p_level_flags,float p_intensity,float p_strength,float p_bloom_treshold,EnvironmentGlowBlendMode p_blend_mode,float p_hdr_bleed_treshold,float p_hdr_bleed_scale,bool p_bicubic_upscale)=0; - virtual void environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture)=0; - + virtual void environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale) = 0; + virtual void environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) = 0; enum EnvironmentToneMapper { ENV_TONE_MAPPER_LINEAR, @@ -668,16 +649,15 @@ public: ENV_TONE_MAPPER_ACES }; - virtual void environment_set_tonemap(RID p_env,EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_grey)=0; - virtual void environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp)=0; + virtual void environment_set_tonemap(RID p_env, EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_grey) = 0; + virtual void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) = 0; - virtual void environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness)=0; - virtual void environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect,const Color &p_color,bool p_blur)=0; + virtual void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_accel, float p_fade, float p_depth_tolerance, bool p_smooth, bool p_roughness) = 0; + virtual void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, const Color &p_color, bool p_blur) = 0; /* SCENARIO API */ - - virtual RID scenario_create()=0; + virtual RID scenario_create() = 0; enum ScenarioDebugMode { SCENARIO_DEBUG_DISABLED, @@ -687,12 +667,10 @@ public: }; - - virtual void scenario_set_debug(RID p_scenario,ScenarioDebugMode p_debug_mode)=0; - virtual void scenario_set_environment(RID p_scenario, RID p_environment)=0; - virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv)=0; - virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment)=0; - + virtual void scenario_set_debug(RID p_scenario, ScenarioDebugMode p_debug_mode) = 0; + virtual void scenario_set_environment(RID p_scenario, RID p_environment) = 0; + virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) = 0; + virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment) = 0; /* INSTANCING API */ @@ -711,35 +689,33 @@ public: INSTANCE_MAX, /*INSTANCE_BAKED_LIGHT_SAMPLER,*/ - INSTANCE_GEOMETRY_MASK=(1<<INSTANCE_MESH)|(1<<INSTANCE_MULTIMESH)|(1<<INSTANCE_IMMEDIATE) + INSTANCE_GEOMETRY_MASK = (1 << INSTANCE_MESH) | (1 << INSTANCE_MULTIMESH) | (1 << INSTANCE_IMMEDIATE) }; - - virtual RID instance_create2(RID p_base, RID p_scenario); //virtual RID instance_create(RID p_base,RID p_scenario)=0; // from can be mesh, light, area and portal so far. - virtual RID instance_create()=0; // from can be mesh, light, poly, area and portal so far. + virtual RID instance_create() = 0; // from can be mesh, light, poly, area and portal so far. - virtual void instance_set_base(RID p_instance, RID p_base)=0; // from can be mesh, light, poly, area and portal so far. - virtual void instance_set_scenario(RID p_instance, RID p_scenario)=0; // from can be mesh, light, poly, area and portal so far. - virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask)=0; - virtual void instance_set_transform(RID p_instance, const Transform& p_transform)=0; - virtual void instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID)=0; - virtual void instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight)=0; - virtual void instance_set_surface_material(RID p_instance,int p_surface, RID p_material)=0; - virtual void instance_set_visible(RID p_instance,bool p_visible)=0; + virtual void instance_set_base(RID p_instance, RID p_base) = 0; // from can be mesh, light, poly, area and portal so far. + virtual void instance_set_scenario(RID p_instance, RID p_scenario) = 0; // from can be mesh, light, poly, area and portal so far. + virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask) = 0; + virtual void instance_set_transform(RID p_instance, const Transform &p_transform) = 0; + virtual void instance_attach_object_instance_ID(RID p_instance, ObjectID p_ID) = 0; + virtual void instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) = 0; + virtual void instance_set_surface_material(RID p_instance, int p_surface, RID p_material) = 0; + virtual void instance_set_visible(RID p_instance, bool p_visible) = 0; - virtual void instance_attach_skeleton(RID p_instance,RID p_skeleton)=0; - virtual void instance_set_exterior( RID p_instance, bool p_enabled )=0; - virtual void instance_set_room( RID p_instance, RID p_room )=0; + virtual void instance_attach_skeleton(RID p_instance, RID p_skeleton) = 0; + virtual void instance_set_exterior(RID p_instance, bool p_enabled) = 0; + virtual void instance_set_room(RID p_instance, RID p_room) = 0; - virtual void instance_set_extra_visibility_margin( RID p_instance, real_t p_margin )=0; + virtual void instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) = 0; // don't use these in a game! - virtual Vector<ObjectID> instances_cull_aabb(const Rect3& p_aabb, RID p_scenario=RID()) const=0; - virtual Vector<ObjectID> instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario=RID()) const=0; - virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario=RID()) const=0; + virtual Vector<ObjectID> instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario = RID()) const = 0; + virtual Vector<ObjectID> instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const = 0; + virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario = RID()) const = 0; enum InstanceFlags { INSTANCE_FLAG_BILLBOARD, @@ -758,35 +734,33 @@ public: SHADOW_CASTING_SETTING_SHADOWS_ONLY, }; - virtual void instance_geometry_set_flag(RID p_instance,InstanceFlags p_flags,bool p_enabled)=0; + virtual void instance_geometry_set_flag(RID p_instance, InstanceFlags p_flags, bool p_enabled) = 0; virtual void instance_geometry_set_cast_shadows_setting(RID p_instance, ShadowCastingSetting p_shadow_casting_setting) = 0; - virtual void instance_geometry_set_material_override(RID p_instance, RID p_material)=0; + virtual void instance_geometry_set_material_override(RID p_instance, RID p_material) = 0; - - virtual void instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin)=0; - virtual void instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance)=0; + virtual void instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) = 0; + virtual void instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) = 0; /* CANVAS (2D) */ - virtual RID canvas_create()=0; - virtual void canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring)=0; - virtual void canvas_set_modulate(RID p_canvas,const Color& p_color)=0; - + virtual RID canvas_create() = 0; + virtual void canvas_set_item_mirroring(RID p_canvas, RID p_item, const Point2 &p_mirroring) = 0; + virtual void canvas_set_modulate(RID p_canvas, const Color &p_color) = 0; - virtual RID canvas_item_create()=0; - virtual void canvas_item_set_parent(RID p_item,RID p_parent)=0; + virtual RID canvas_item_create() = 0; + virtual void canvas_item_set_parent(RID p_item, RID p_parent) = 0; - virtual void canvas_item_set_visible(RID p_item,bool p_visible)=0; - virtual void canvas_item_set_light_mask(RID p_item,int p_mask)=0; + virtual void canvas_item_set_visible(RID p_item, bool p_visible) = 0; + virtual void canvas_item_set_light_mask(RID p_item, int p_mask) = 0; - virtual void canvas_item_set_transform(RID p_item, const Transform2D& p_transform)=0; - virtual void canvas_item_set_clip(RID p_item, bool p_clip)=0; - virtual void canvas_item_set_distance_field_mode(RID p_item, bool p_enable)=0; - virtual void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect=Rect2())=0; - virtual void canvas_item_set_modulate(RID p_item, const Color& p_color)=0; - virtual void canvas_item_set_self_modulate(RID p_item, const Color& p_color)=0; + virtual void canvas_item_set_transform(RID p_item, const Transform2D &p_transform) = 0; + virtual void canvas_item_set_clip(RID p_item, bool p_clip) = 0; + virtual void canvas_item_set_distance_field_mode(RID p_item, bool p_enable) = 0; + virtual void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect, const Rect2 &p_rect = Rect2()) = 0; + virtual void canvas_item_set_modulate(RID p_item, const Color &p_color) = 0; + virtual void canvas_item_set_self_modulate(RID p_item, const Color &p_color) = 0; - virtual void canvas_item_set_draw_behind_parent(RID p_item, bool p_enable)=0; + virtual void canvas_item_set_draw_behind_parent(RID p_item, bool p_enable) = 0; enum NinePatchAxisMode { NINE_PATCH_STRETCH, @@ -794,45 +768,45 @@ public: NINE_PATCH_TILE_FIT, }; - virtual void canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width=1.0,bool p_antialiased=false)=0; - virtual void canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color)=0; - virtual void canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color)=0; - virtual void canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile=false,const Color& p_modulate=Color(1,1,1),bool p_transpose=false)=0; - virtual void canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1),bool p_transpose=false)=0; - virtual void canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,NinePatchAxisMode p_x_axis_mode=NINE_PATCH_STRETCH, NinePatchAxisMode p_y_axis_mode=NINE_PATCH_STRETCH,bool p_draw_center=true,const Color& p_modulate=Color(1,1,1))=0; - virtual void canvas_item_add_primitive(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width=1.0)=0; - virtual void canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID())=0; - virtual void canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID(), int p_count=-1)=0; - virtual void canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton=RID())=0; - virtual void canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton=RID())=0; - virtual void canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform)=0; - virtual void canvas_item_add_clip_ignore(RID p_item, bool p_ignore)=0; - virtual void canvas_item_set_sort_children_by_y(RID p_item, bool p_enable)=0; - virtual void canvas_item_set_z(RID p_item, int p_z)=0; - virtual void canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable)=0; - virtual void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect)=0; - - virtual void canvas_item_clear(RID p_item)=0; - virtual void canvas_item_set_draw_index(RID p_item,int p_index)=0; - - virtual void canvas_item_set_material(RID p_item, RID p_material)=0; - - virtual void canvas_item_set_use_parent_material(RID p_item, bool p_enable)=0; - - virtual RID canvas_light_create()=0; - virtual void canvas_light_attach_to_canvas(RID p_light,RID p_canvas)=0; - virtual void canvas_light_set_enabled(RID p_light, bool p_enabled)=0; - virtual void canvas_light_set_scale(RID p_light, float p_scale)=0; - virtual void canvas_light_set_transform(RID p_light, const Transform2D& p_transform)=0; - virtual void canvas_light_set_texture(RID p_light, RID p_texture)=0; - virtual void canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset)=0; - virtual void canvas_light_set_color(RID p_light, const Color& p_color)=0; - virtual void canvas_light_set_height(RID p_light, float p_height)=0; - virtual void canvas_light_set_energy(RID p_light, float p_energy)=0; - virtual void canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z)=0; - virtual void canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer)=0; - virtual void canvas_light_set_item_cull_mask(RID p_light, int p_mask)=0; - virtual void canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask)=0; + virtual void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false) = 0; + virtual void canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color) = 0; + virtual void canvas_item_add_circle(RID p_item, const Point2 &p_pos, float p_radius, const Color &p_color) = 0; + virtual void canvas_item_add_texture_rect(RID p_item, const Rect2 &p_rect, RID p_texture, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) = 0; + virtual void canvas_item_add_texture_rect_region(RID p_item, const Rect2 &p_rect, RID p_texture, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) = 0; + virtual void canvas_item_add_nine_patch(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector2 &p_topleft, const Vector2 &p_bottomright, NinePatchAxisMode p_x_axis_mode = NINE_PATCH_STRETCH, NinePatchAxisMode p_y_axis_mode = NINE_PATCH_STRETCH, bool p_draw_center = true, const Color &p_modulate = Color(1, 1, 1)) = 0; + virtual void canvas_item_add_primitive(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width = 1.0) = 0; + virtual void canvas_item_add_polygon(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID()) = 0; + virtual void canvas_item_add_triangle_array(RID p_item, const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID(), int p_count = -1) = 0; + virtual void canvas_item_add_mesh(RID p_item, const RID &p_mesh, RID p_skeleton = RID()) = 0; + virtual void canvas_item_add_multimesh(RID p_item, RID p_mesh, RID p_skeleton = RID()) = 0; + virtual void canvas_item_add_set_transform(RID p_item, const Transform2D &p_transform) = 0; + virtual void canvas_item_add_clip_ignore(RID p_item, bool p_ignore) = 0; + virtual void canvas_item_set_sort_children_by_y(RID p_item, bool p_enable) = 0; + virtual void canvas_item_set_z(RID p_item, int p_z) = 0; + virtual void canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable) = 0; + virtual void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable, const Rect2 &p_rect) = 0; + + virtual void canvas_item_clear(RID p_item) = 0; + virtual void canvas_item_set_draw_index(RID p_item, int p_index) = 0; + + virtual void canvas_item_set_material(RID p_item, RID p_material) = 0; + + virtual void canvas_item_set_use_parent_material(RID p_item, bool p_enable) = 0; + + virtual RID canvas_light_create() = 0; + virtual void canvas_light_attach_to_canvas(RID p_light, RID p_canvas) = 0; + virtual void canvas_light_set_enabled(RID p_light, bool p_enabled) = 0; + virtual void canvas_light_set_scale(RID p_light, float p_scale) = 0; + virtual void canvas_light_set_transform(RID p_light, const Transform2D &p_transform) = 0; + virtual void canvas_light_set_texture(RID p_light, RID p_texture) = 0; + virtual void canvas_light_set_texture_offset(RID p_light, const Vector2 &p_offset) = 0; + virtual void canvas_light_set_color(RID p_light, const Color &p_color) = 0; + virtual void canvas_light_set_height(RID p_light, float p_height) = 0; + virtual void canvas_light_set_energy(RID p_light, float p_energy) = 0; + virtual void canvas_light_set_z_range(RID p_light, int p_min_z, int p_max_z) = 0; + virtual void canvas_light_set_layer_range(RID p_light, int p_min_layer, int p_max_layer) = 0; + virtual void canvas_light_set_item_cull_mask(RID p_light, int p_mask) = 0; + virtual void canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask) = 0; enum CanvasLightMode { CANVAS_LIGHT_MODE_ADD, @@ -841,8 +815,7 @@ public: CANVAS_LIGHT_MODE_MASK, }; - virtual void canvas_light_set_mode(RID p_light, CanvasLightMode p_mode)=0; - + virtual void canvas_light_set_mode(RID p_light, CanvasLightMode p_mode) = 0; enum CanvasLightShadowFilter { CANVAS_LIGHT_FILTER_NONE, @@ -852,57 +825,52 @@ public: CANVAS_LIGHT_FILTER_PCF13, }; - virtual void canvas_light_set_shadow_enabled(RID p_light, bool p_enabled)=0; - virtual void canvas_light_set_shadow_buffer_size(RID p_light, int p_size)=0; - virtual void canvas_light_set_shadow_gradient_length(RID p_light, float p_length)=0; - virtual void canvas_light_set_shadow_filter(RID p_light, CanvasLightShadowFilter p_filter)=0; - virtual void canvas_light_set_shadow_color(RID p_light, const Color& p_color)=0; + virtual void canvas_light_set_shadow_enabled(RID p_light, bool p_enabled) = 0; + virtual void canvas_light_set_shadow_buffer_size(RID p_light, int p_size) = 0; + virtual void canvas_light_set_shadow_gradient_length(RID p_light, float p_length) = 0; + virtual void canvas_light_set_shadow_filter(RID p_light, CanvasLightShadowFilter p_filter) = 0; + virtual void canvas_light_set_shadow_color(RID p_light, const Color &p_color) = 0; + virtual RID canvas_light_occluder_create() = 0; + virtual void canvas_light_occluder_attach_to_canvas(RID p_occluder, RID p_canvas) = 0; + virtual void canvas_light_occluder_set_enabled(RID p_occluder, bool p_enabled) = 0; + virtual void canvas_light_occluder_set_polygon(RID p_occluder, RID p_polygon) = 0; + virtual void canvas_light_occluder_set_transform(RID p_occluder, const Transform2D &p_xform) = 0; + virtual void canvas_light_occluder_set_light_mask(RID p_occluder, int p_mask) = 0; - - virtual RID canvas_light_occluder_create()=0; - virtual void canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas)=0; - virtual void canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled)=0; - virtual void canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon)=0; - virtual void canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform)=0; - virtual void canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask)=0; - - virtual RID canvas_occluder_polygon_create()=0; - virtual void canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed)=0; - virtual void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape)=0; + virtual RID canvas_occluder_polygon_create() = 0; + virtual void canvas_occluder_polygon_set_shape(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape, bool p_closed) = 0; + virtual void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape) = 0; enum CanvasOccluderPolygonCullMode { CANVAS_OCCLUDER_POLYGON_CULL_DISABLED, CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE, CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE, }; - virtual void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,CanvasOccluderPolygonCullMode p_mode)=0; - + virtual void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon, CanvasOccluderPolygonCullMode p_mode) = 0; /* CURSOR */ - virtual void cursor_set_rotation(float p_rotation, int p_cursor = 0)=0; // radians - virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor=0, const Rect2 &p_region=Rect2())=0; - virtual void cursor_set_visible(bool p_visible, int p_cursor = 0)=0; - virtual void cursor_set_pos(const Point2& p_pos, int p_cursor = 0)=0; + virtual void cursor_set_rotation(float p_rotation, int p_cursor = 0) = 0; // radians + virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor = 0, const Rect2 &p_region = Rect2()) = 0; + virtual void cursor_set_visible(bool p_visible, int p_cursor = 0) = 0; + virtual void cursor_set_pos(const Point2 &p_pos, int p_cursor = 0) = 0; /* BLACK BARS */ - - virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom)=0; - virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom)=0; - + virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom) = 0; + virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom) = 0; /* FREE */ - virtual void free( RID p_rid )=0; ///< free RIDs associated with the visual server + virtual void free(RID p_rid) = 0; ///< free RIDs associated with the visual server /* EVENT QUEUING */ - virtual void draw()=0; - virtual void sync()=0; - virtual bool has_changed() const=0; - virtual void init()=0; - virtual void finish()=0; + virtual void draw() = 0; + virtual void sync() = 0; + virtual bool has_changed() const = 0; + virtual void init() = 0; + virtual void finish() = 0; /* STATUS INFORMATION */ @@ -920,56 +888,53 @@ public: INFO_VERTEX_MEM_USED, }; - virtual int get_render_info(RenderInfo p_info)=0; - + virtual int get_render_info(RenderInfo p_info) = 0; /* Materials for 2D on 3D */ - - RID material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha,bool p_opaque_prepass); + RID material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha, bool p_opaque_prepass); /* TESTING */ - virtual RID get_test_cube()=0; + virtual RID get_test_cube() = 0; virtual RID get_test_texture(); virtual RID get_white_texture(); - virtual RID make_sphere_mesh(int p_lats,int p_lons,float p_radius); + virtual RID make_sphere_mesh(int p_lats, int p_lons, float p_radius); - virtual void mesh_add_surface_from_mesh_data( RID p_mesh, const Geometry::MeshData& p_mesh_data); - virtual void mesh_add_surface_from_planes( RID p_mesh, const PoolVector<Plane>& p_planes); + virtual void mesh_add_surface_from_mesh_data(RID p_mesh, const Geometry::MeshData &p_mesh_data); + virtual void mesh_add_surface_from_planes(RID p_mesh, const PoolVector<Plane> &p_planes); - virtual void set_boot_image(const Image& p_image, const Color& p_color,bool p_scale)=0; - virtual void set_default_clear_color(const Color& p_color)=0; + virtual void set_boot_image(const Image &p_image, const Color &p_color, bool p_scale) = 0; + virtual void set_default_clear_color(const Color &p_color) = 0; enum Features { FEATURE_SHADERS, FEATURE_MULTITHREADED, }; - virtual bool has_feature(Features p_feature) const=0; + virtual bool has_feature(Features p_feature) const = 0; - virtual bool has_os_feature(const String& p_feature) const=0; + virtual bool has_os_feature(const String &p_feature) const = 0; VisualServer(); virtual ~VisualServer(); - }; // make variant understand the enums -VARIANT_ENUM_CAST( VisualServer::CubeMapSide ); -VARIANT_ENUM_CAST( VisualServer::TextureFlags ); -VARIANT_ENUM_CAST( VisualServer::ShaderMode ); -VARIANT_ENUM_CAST( VisualServer::ArrayType ); -VARIANT_ENUM_CAST( VisualServer::ArrayFormat ); -VARIANT_ENUM_CAST( VisualServer::PrimitiveType ); -VARIANT_ENUM_CAST( VisualServer::LightType ); -VARIANT_ENUM_CAST( VisualServer::LightParam ); -VARIANT_ENUM_CAST( VisualServer::ScenarioDebugMode ); -VARIANT_ENUM_CAST( VisualServer::InstanceType ); -VARIANT_ENUM_CAST( VisualServer::RenderInfo ); +VARIANT_ENUM_CAST(VisualServer::CubeMapSide); +VARIANT_ENUM_CAST(VisualServer::TextureFlags); +VARIANT_ENUM_CAST(VisualServer::ShaderMode); +VARIANT_ENUM_CAST(VisualServer::ArrayType); +VARIANT_ENUM_CAST(VisualServer::ArrayFormat); +VARIANT_ENUM_CAST(VisualServer::PrimitiveType); +VARIANT_ENUM_CAST(VisualServer::LightType); +VARIANT_ENUM_CAST(VisualServer::LightParam); +VARIANT_ENUM_CAST(VisualServer::ScenarioDebugMode); +VARIANT_ENUM_CAST(VisualServer::InstanceType); +VARIANT_ENUM_CAST(VisualServer::RenderInfo); //typedef VisualServer VS; // makes it easier to use #define VS VisualServer |