Beispiel #1
0
Vec3<float> Scene::calculate_shadowing_optimal_point(Vec3<float> near_values[4],Vec3<float> far_values[4], float &radius) {
    float max_top=near_values[0].y,max_bot=near_values[0].y,max_right=near_values[0].x,max_left=near_values[0].x;

    float depth=0;

    for(int i=0;i<4;i++) {
        float cur_max_right = maxf(near_values[i].x,far_values[i].x);
        float cur_max_left = minf(near_values[i].x,far_values[i].x);
        float cur_max_top = maxf(near_values[i].y,far_values[i].y);
        float cur_max_bot = minf(near_values[i].y,far_values[i].y);

        max_top=maxf(max_top,cur_max_top);
        max_bot=minf(max_bot,cur_max_bot);
        max_right=maxf(max_right,cur_max_right);
        max_left=minf(max_left,cur_max_left);
        
        depth+=(near_values[0].z+far_values[0].z);
    }

    float max_height=max_top-max_bot;
    float max_width=max_right-max_left;

    radius=maxf(max_height,max_width);
    return Vec3<float>((max_right+max_left)/2,(max_top+max_bot)/2,depth/8);
}
// input : spread weighted energy *werg, spread energy *erg
// output: masking threshold *erg after applying the tonality-offset
static void
ApplyTonalityOffset ( float* erg0, float* erg1, const float* werg0, const float* werg1 )
{
    int    n;
    float  Offset;
    float  quot;


    // calculation of the masked threshold in the partition range
    for ( n = 0; n < PART_LONG; n++ ) {
        quot = *werg0++ / *erg0;
        if      (quot <= 0.05737540597f) Offset = O_MAX;
        else if (quot <  0.5871011603f ) Offset = FAC1 * POW (quot, FAC2);
        else                             Offset = O_MIN;
        *erg0++ *= iw[n] * minf(MinVal[n], Offset);

        quot = *werg1++ / *erg1;
        if      (quot <= 0.05737540597f) Offset = O_MAX;
        else if (quot <  0.5871011603f ) Offset = FAC1 * POW (quot, FAC2);
        else                             Offset = O_MIN;
		*erg1++ *= iw[n] * minf(MinVal[n], Offset);
    }

    return;
}
static void morpho_erode(CompBuf *cbuf)
{
	int x, y;
	float *p, *rectf = cbuf->rect;
	
	for (y = 0; y < cbuf->y; y++) {
		for (x = 0; x < cbuf->x - 1; x++) {
			p = rectf + cbuf->x * y + x;
			*p = minf(*p, *(p + 1));
		}
	}

	for (y = 0; y < cbuf->y; y++) {
		for (x = cbuf->x - 1; x >= 1; x--) {
			p = rectf + cbuf->x * y + x;
			*p = minf(*p, *(p - 1));
		}
	}

	for (x = 0; x < cbuf->x; x++) {
		for (y = 0; y < cbuf->y - 1; y++) {
			p = rectf + cbuf->x * y + x;
			*p = minf(*p, *(p + cbuf->x));
		}
	}

	for (x = 0; x < cbuf->x; x++) {
		for (y = cbuf->y - 1; y >= 1; y--) {
			p = rectf + cbuf->x * y + x;
			*p = minf(*p, *(p - cbuf->x));
		}
	}
	
}
Beispiel #4
0
void sreScissors::UpdateWithProjectedPoint(float x, float y, double z) {
    if (z >= - 1.001d) {
        // Beyond the near plane.
        z = maxd(- 1.0d, z);
        double depth = 0.5d * z + 0.5d;
        near = mind(depth, near);
        far = maxd(depth, far);
        left = minf(x, left);
        right = maxf(x, right);
        bottom = minf(y, bottom);
        top = maxf(y, top);
        return;
    }
    sreMessage(SRE_MESSAGE_WARNING,
        "Unexpected vertex in front of the near plane in UpdateWorldSpaceBoundingHull "
        "z = %lf", z);
    // In front of the near plane.
    near = 0;
    far = 1.0;
    // We know that the light volume intersects the frustum, so it must extend to
    // both sides of the near plane.
    // Assume it fills the whole viewport (not optimal).
    left = - 1.0f;
    right = 1.0f;
    bottom = - 1.0f;
    top = 1.0f;
}
Beispiel #5
0
std::pair<int, int> find_min_max(int a[], int length)
{
    int min(0), max(0), i(0); 
    if (length % 2)
    {
        min = a[0];
        max = a[0];
        i = 1;
    }
    else
    {
        min = minf(a[0], a[1]);
        max = maxf(a[0], a[1]);
        i = 2;
    }
    for (; i < length; i += 2)
    {
        int min2(0), max2(0);
        if (a[i] < a[i+1])
        {
            min2 = a[i];
            max2 = a[i+1];
        }
        else
        {
            max2 = a[i];
            min2 = a[i+1];
        }
        min = minf(min, min2);
        max = maxf(max, max2);
    }

    return std::make_pair(min, max);
}
/**
 * @brief
 * Calculate the Time Interval.
 *
 */
double getTimeInterval(structMesh *mesh, physics *phy, double CFL){
    double dt;
    dt = mesh->dx/phy->u;
    dt = minf(dt, mesh->dy/phy->v);
    dt = minf(dt, pow(mesh->dx, 2)/phy->Dx);
    dt = minf(dt, pow(mesh->dy, 2)/phy->Dy);
    return dt*CFL;
}
Beispiel #7
0
struct aabb* aabb_merge(struct aabb* rb, const struct aabb* b1, const struct aabb* b2)
{
    struct vec4f minpt;
    struct vec4f maxpt;

    vec3_setf(&minpt, minf(b1->minpt.x, b2->minpt.x), minf(b1->minpt.y, b2->minpt.y),
              minf(b1->minpt.z, b2->minpt.z));
    vec3_setf(&maxpt, maxf(b1->maxpt.x, b2->maxpt.x), maxf(b1->maxpt.y, b2->maxpt.y),
              maxf(b1->maxpt.z, b2->maxpt.z));
    return aabb_setv(rb, &minpt, &maxpt);
}
Beispiel #8
0
static ALvoid ALdistortionState_update(ALdistortionState *state, ALCdevice *Device, const ALeffectslot *Slot)
{
    ALfloat frequency = (ALfloat)Device->Frequency;
    ALfloat bandwidth;
    ALfloat cutoff;
    ALfloat edge;

    /* Store distorted signal attenuation settings */
    state->attenuation = Slot->EffectProps.Distortion.Gain;

    /* Store waveshaper edge settings */
    edge = sinf(Slot->EffectProps.Distortion.Edge * (F_PI_2));
    edge = minf(edge, 0.99f);
    state->edge_coeff = 2.0f * edge / (1.0f-edge);

    /* Lowpass filter */
    cutoff = Slot->EffectProps.Distortion.LowpassCutoff;
    /* Bandwidth value is constant in octaves */
    bandwidth = (cutoff / 2.0f) / (cutoff * 0.67f);
    ALfilterState_setParams(&state->lowpass, ALfilterType_LowPass, 1.0f,
        cutoff / (frequency*4.0f), calc_rcpQ_from_bandwidth(cutoff / (frequency*4.0f), bandwidth)
    );

    /* Bandpass filter */
    cutoff = Slot->EffectProps.Distortion.EQCenter;
    /* Convert bandwidth in Hz to octaves */
    bandwidth = Slot->EffectProps.Distortion.EQBandwidth / (cutoff * 0.67f);
    ALfilterState_setParams(&state->bandpass, ALfilterType_BandPass, 1.0f,
        cutoff / (frequency*4.0f), calc_rcpQ_from_bandwidth(cutoff / (frequency*4.0f), bandwidth)
    );

    ComputeAmbientGains(Device, Slot->Gain, state->Gain);
}
Beispiel #9
0
/* Calculates the normalized HRTF transition factor (delta) from the changes
 * in gain and listener to source angle between updates.  The result is a
 * normalized delta factor that can be used to calculate moving HRIR stepping
 * values.
 */
ALfloat CalcHrtfDelta(ALfloat oldGain, ALfloat newGain, const ALfloat olddir[3], const ALfloat newdir[3])
{
    ALfloat gainChange, angleChange, change;

    // Calculate the normalized dB gain change.
    newGain = maxf(newGain, 0.0001f);
    oldGain = maxf(oldGain, 0.0001f);
    gainChange = fabsf(log10f(newGain / oldGain) / log10f(0.0001f));

    // Calculate the normalized listener to source angle change when there is
    // enough gain to notice it.
    angleChange = 0.0f;
    if(gainChange > 0.0001f || newGain > 0.0001f)
    {
        // No angle change when the directions are equal or degenerate (when
        // both have zero length).
        if(newdir[0]-olddir[0] || newdir[1]-olddir[1] || newdir[2]-olddir[2])
            angleChange = acosf(olddir[0]*newdir[0] +
                                olddir[1]*newdir[1] +
                                olddir[2]*newdir[2]) / F_PI;

    }

    // Use the largest of the two changes for the delta factor, and apply a
    // significance shaping function to it.
    change = maxf(angleChange * 25.0f, gainChange) * 2.0f;
    return minf(change, 1.0f);
}
Beispiel #10
0
// NoiseShaper for a subband
void
QuantizeSubbandWithNoiseShaping ( unsigned int* qu_output, const float* input, const int res, float* errors, const float* FIR )
{
    float  signal;
    float  mult    = A [res];
    float  invmult = C [res];
    int    offset  = D [res];
    int    n, quant;

	memset(errors, 0, 6 * sizeof *errors);       // arghh, it produces pops on each frame boundary!

    for ( n = 0; n < 36; n++) {
        signal = input[n] * NoiseInjectionCompensation1D [res] - (FIR[5]*errors[n+0] + FIR[4]*errors[n+1] + FIR[3]*errors[n+2] + FIR[2]*errors[n+3] + FIR[1]*errors[n+4] + FIR[0]*errors[n+5]);
		quant = mpc_lrintf(signal * mult);

        // calculate the current error and save it for error refeeding
        errors [n + 6] = invmult * quant - signal * NoiseInjectionCompensation1D [res];

        // limitation to +/-D
        quant = minf ( quant, +offset );
        quant = maxf ( quant, -offset );

        qu_output[n] = (unsigned int)(quant + offset);
    }
}
Beispiel #11
0
int image_hsi_of_block(void *image_, int x, int y, float *hue, float *saturation, float *intensity)
{
	struct image *image = image_;
	int i, j, n, w, h;
	unsigned char *rgb;

	w = BLOCK_WIDTH; h = BLOCK_HEIGHT;
	if(x+w > image_width(image_)) w -= image_width(image_)-x;
	if(y+h > image_height(image_)) h -= image_height(image_)-y;

	rgb = image->rgb + x + (y * bytes_per_scanline(image));
	for(i = 0, n = 0; i < h; i++, rgb += 3*(image_width(image_)-w)) {
		for(j = 0; j < w; j++, n++, rgb += 3, hue++, saturation++, intensity++) {
			float r, g, b, sum;

			sum = rgb[0] + rgb[1] + rgb[2] + EPSILON_F;
			r = (float)rgb[0] / sum;
			g = (float)rgb[1] / sum;
			b = (float)rgb[2] / sum;
			*hue = acosf((0.5 * ((r-g) + (r-b))) /
				     (EPSILON_F + sqrtf(((r-g)*(r-g)) + ((r-b) * (g-b)))));
			if(b > g) *hue = (2.0*M_PI_F) - *hue;
			*saturation = 1.0 - 3.0 * minf(r, g, b);
			*intensity = (float)(rgb[0]+rgb[1]+rgb[2]) / 765.0;
		}
	}

	return n;
}
Beispiel #12
0
int main(int argc, char** argv) {

    TestBox t;
    MidiInfo minf("midifiles/Cisei.kar"); //open file (open initialize also ticklength of file, resolution.....)

    if(minf.isValid())
        minf.readInfo(&t); //if you have a valid midi, read all info filling t
    else
        return ERR_NOTMIDI;

    minf.readInfo(); //now try to call readInfo without parameters. What happens? Nothing special but..

    Tick* inf = minf.getInfo();//you can use defaul struct Tick

    Info *n = inf[22320].info;

    unsigned char* buf;

    while((n != NULL) && (buf = n->nextInfo()))
        printf("\nInfo :%s", buf);

    printf("\n\nNumber of ticks: %d Resolution: %dtpb Length: %dsec.\n", minf.getTickLength(), minf.getResolution(), minf.getSecondLenght());

    return 0;
}
Beispiel #13
0
/* Calculates the fade time from the changes in gain and listener to source
 * angle between updates. The result is a the time, in seconds, for the
 * transition to complete.
 */
static ALfloat CalcFadeTime(ALfloat oldGain, ALfloat newGain, const aluVector *olddir, const aluVector *newdir)
{
    ALfloat gainChange, angleChange, change;

    /* Calculate the normalized dB gain change. */
    newGain = maxf(newGain, 0.0001f);
    oldGain = maxf(oldGain, 0.0001f);
    gainChange = fabsf(log10f(newGain / oldGain) / log10f(0.0001f));

    /* Calculate the angle change only when there is enough gain to notice it. */
    angleChange = 0.0f;
    if(gainChange > 0.0001f || newGain > 0.0001f)
    {
        /* No angle change when the directions are equal or degenerate (when
         * both have zero length).
         */
        if(newdir->v[0] != olddir->v[0] || newdir->v[1] != olddir->v[1] || newdir->v[2] != olddir->v[2])
        {
            ALfloat dotp = aluDotproduct(olddir, newdir);
            angleChange = acosf(clampf(dotp, -1.0f, 1.0f)) / F_PI;
        }
    }

    /* Use the largest of the two changes, and apply a significance shaping
     * function to it. The result is then scaled to cover a 15ms transition
     * range.
     */
    change = maxf(angleChange * 25.0f, gainChange) * 2.0f;
    return minf(change, 1.0f) * 0.015f;
}
Beispiel #14
0
int main()
    {
int n,min=0;
    scanf("%d",&n);
    printf("%d\n",n);
    int i,a[n],max=0;
    for(i=0;i<n;i++)
        {
        scanf("%d",&a[i]);
        if(max<a[i])
            max=a[i];
    }
    
    while(max>0)
        {
        int c=0;
        for(i=0;i<n;i++)
            {
				min=minf(&a,n);
            a[i]=a[i]-min;
             
        if(a[i]>0)
            c++;
    }
printf("%d\n",c);
}
  
    return 0;
}
// input : previous simultaneous masking threshold *preThr,
//         current simultaneous masking threshold *simThr
// output: update of *preThr for next call,
//         current masking threshold *partThr
static void
PreechoControl ( float*        partThr0,
                 float*        preThr0,
                 const float*  simThr0,
                 float*        partThr1,
                 float*        preThr1,
                 const float*  simThr1 )
{
    int  n;

    for ( n = 0; n < PART_LONG; n++ ) {
        *partThr0++ = minf ( *simThr0, *preThr0 * PREFAC_LONG);
        *partThr1++ = minf ( *simThr1, *preThr1 * PREFAC_LONG);
        *preThr0++  = *simThr0++;
        *preThr1++  = *simThr1++;
    }
    return;
}
Beispiel #16
0
static float
cube(float *pos, float *size)
{
	float d[3];
	float dst;
	abs3f(d, pos);
	sub3f(d, d, size);
	dst = minf(maxf(d[0], maxf(d[1],d[2])),0.0);	
	max3f(d, d,(float[]){0,0,0});
double vertex_to_segment_vertical_dist(double x,double y,  double x1,double y1, double x2,double y2) //xy - vertex x1,y1, x2,y2 - line segment
{
	if ((x1<=x && x<=x2) || (x2<=x && x<=x1)) 
	{
		if (x1==x2) {return fabs(minf(y-y2,y-y1));}
		else {return fabs(y-y1-(y2-y1)*(x-x1)/(x2-x1));}
	}
	return -1;	
}
Beispiel #18
0
void handle_mousemove(SDL_MouseMotionEvent motion) {
	if (motion.state & 1) {	// left-drag
		float mousex = motion.x;
		float mousey = Surf_Display->h - motion.y;
		float w = Surf_Display->w;
		float h = Surf_Display->h;
		float dim = minf(w, h);
		transX = gXmouseDown - (mousex / w) * 200.0 * w / dim / zoomFactor;
		transY = gYmouseDown - (mousey / h) * 200.0 * h / dim / zoomFactor;
	}
}
Beispiel #19
0
void GameState::updateCamera( float dt )
{
    vec3 shipPos = ship->transform.position();
    vec3 shipVel = ship->rigidBody().vel();

    vec3 oldCamPos = ( *_scene->camera() )->transform.position();
    vec3 maxCamPos = shipPos;

    // If the ship is moving enough, we'll start moving the camera ahead so the
    // player can see where they're moving
    float seekAheadFactor = minf( 40.f, vec3::length( shipVel ) * .4f );
    maxCamPos += ship->transform.forward() * seekAheadFactor;

    // The camera should pull back from target that it follows (this ship) when the target moves
    maxCamPos.z = shipPos.z - ( 9.5f + seekAheadFactor );

    vec3 desiredCamPos = vec3::lerp( oldCamPos, maxCamPos, minf( 8.f * dt, 0.65f ) );

    ( *_scene->camera() )->transform.position( desiredCamPos );
}
Beispiel #20
0
Datei: nx.c Projekt: biasmv/nx
void collect_statistics(CallStatP call_stats)
{
  int i=0;
  CallStat min=call_stats[0], max=call_stats[0], mean=call_stats[0];
  CallStat stddev;
  memset(&stddev, 0, sizeof(CallStat));
  for (i=1; i<g_num_repeats; ++i) {
    min.real_time=minf(min.real_time, call_stats[i].real_time);
    min.user_time=minf(min.user_time, call_stats[i].user_time);
    min.sys_time=minf(min.sys_time, call_stats[i].sys_time);
    
    max.real_time=maxf(max.real_time, call_stats[i].real_time);
    max.user_time=maxf(max.user_time, call_stats[i].user_time);
    max.sys_time=maxf(max.sys_time, call_stats[i].sys_time);
    
    mean.real_time+=call_stats[i].real_time;
    mean.user_time+=call_stats[i].user_time;
    mean.sys_time+=call_stats[i].sys_time;
  }
  
  mean.real_time/=g_num_repeats;
  mean.user_time/=g_num_repeats;
  mean.sys_time/=g_num_repeats;
  
  for (i=0; i<g_num_repeats; ++i) {
    float d1=call_stats[i].real_time-mean.real_time;
    stddev.real_time+=d1*d1;
    float d2=call_stats[i].user_time-mean.user_time;
    stddev.real_time+=d2*d2;
    float d3=call_stats[i].sys_time-mean.sys_time;
    stddev.sys_time+=d3*d3;
  }
  stddev.real_time=sqrt(stddev.real_time/g_num_repeats);
  stddev.user_time=sqrt(stddev.user_time/g_num_repeats);
  stddev.sys_time=sqrt(stddev.sys_time/g_num_repeats);
  callstat_print(g_output_stream, &mean, "mean", g_output_format);
  callstat_print(g_output_stream, &min, "min", g_output_format);
  callstat_print(g_output_stream, &max, "max", g_output_format);
  callstat_print(g_output_stream, &stddev, "stddev", g_output_format);
  callstat_print_sep(g_output_stream, g_output_format);
}
Beispiel #21
0
void draw_button(BITMAP *bmp, int x, int y, int w, int h, int col, const char *txt, bool selected, bool disabled)
{
	int col1 = makecol( minf(255,getr(col)*1.3f), minf(255,getg(col)*1.3f), minf(255,getb(col)*1.3f) );
	int col2 = makecol( getr(col)*0.7f, getg(col)*0.7f, getb(col)*0.7f );
	int col3 = makecol( minf(255,getr(col)*1.7f), minf(255,getg(col)*1.7f), minf(255,getb(col)*1.7f) );

	if(disabled)
	{
		col1 = makecol(130,130,130);
		col2 = makecol(50,50,50);
		col3 = makecol(170,170,170);
		col = makecol(100,100,100);
	}
	else if(selected)
	{
		rect(bmp, x-2,y-2, x+w+3,y+h+3, makecol(210,210,0));
		rect(bmp, x-1,y-1, x+w+2,y+h+2, makecol(255,255,0));
		col3 = makecol(255,255,255);
	}
	
	rectfill(bmp, x,y, x+w,y+h, col);
	line(bmp, x,y, x+w,y, col1);
	line(bmp, x+w,y, x+w,y+h, col1);
	line(bmp, x,y+1, x+w,y+1, col1);
	line(bmp, x+w+1,y, x+w+1,y+h, col1);	
	
	line(bmp, x,y+h, x+w,y+h, col2);
	line(bmp, x,y, x,y+h, col2);	
	line(bmp, x,y+h+1, x+w,y+h+1, col2);
	line(bmp, x+1,y, x+1,y+h, col2);

	textout_ex(bmp, font2, txt, x + (w/2) - (text_length(font2,txt)/2), y + (h/2) - (text_height(font2)/2), col3, -1);
}
Beispiel #22
0
// calculation of the spreading function
static void
Spread ( PsyModel* m )
{
    int    i;
    int    j;
    float  tmpx;
    float  tmpy;
    float  tmpz;
    float  x;

    // calculation of the spreading-function for all occuring values
    for ( i = 0; i < PART_LONG; i++ ) {                 // i is masking Partition, Source
        for ( j = 0; j < PART_LONG; j++ ) {             // j is masking Partition, Target
            tmpx = LongPart2Bark (m, j) - LongPart2Bark (m, i);// Difference of the partitions in Bark
            tmpy = tmpz = 0.;                           // tmpz = 0: no dip

            if      ( tmpx < 0 ) {                      // downwards (S1)
                tmpy  = -32.f * tmpx;                   // 32 dB per Bark, e33 (10)
            }
            else if ( tmpx > 0 ) {                      // upwards (S2)
#if 0
                x = (wl[i]+wh[i])/2 * (float)(SampleFreq / 2000)/512;   // center frequency in kHz ???????
                if (i==0) x = 0.5f  * (float)(SampleFreq / 2000)/512;   // if first spectral line
#else
                x  = i  ?  MPC_WL[i]+MPC_WH[i]  :  1;
                x *= m->SampleFreq / 1000. / 2048;         // center frequency in kHz
#endif
                // dB/Bark
                tmpy = (22.f + 0.23f / x) * tmpx;       // e33 (10)

                // dip (up to 6 dB)
                tmpz = 8 * minf ( (tmpx-0.5f) * (tmpx-0.5f) - 2 * (tmpx-0.5f), 0.f );
            }

            // calculate coefficient
			m->tables.SPRD[i][j] = POW10 ( -0.1 * (tmpy+tmpz) );  // [Source] [Target]
        }
    }

    // Normierung e33 (10)
    for ( i = 0; i < PART_LONG; i++ ) {                 // i is masked Partition
        float  norm = 0.f;
        for ( j = 0; j < PART_LONG; j++ )               // j is masking Partition
			norm += m->tables.SPRD [j] [i];
        for ( j = 0; j < PART_LONG; j++ )               // j is masking Partition
			m->tables.SPRD [j] [i] /= norm;
    }
}
// input : energy spectrums erg[4][128] (4 delayed FFTs)
//         Energy of the last short block *preerg in short partitions
//         PreechoFac declares allowed traved of the masking threshold
// output: masking threshold *thr in short partitions
//         Energy of the last short block *preerg in short partitions
static void
CalcShortThreshold ( PsyModel* m,
					 const float  erg [4] [128],
                     const float  ShortThr,
                     float*       thr,
                     float        old_erg [2][PART_SHORT],
                     int*         transient )
{
    const int*    index_lo = wl_short; // lower FFT-index
    const int*    index_hi = wh_short; // upper FFT-index
    const float*  iwidth   = iw_short; // inverse partition-width
    int           k;
    int           n;
    int           l;
    float         new_erg;
	float         th, TransDetect = m->TransDetect;
    const float*  ep;

    for ( k = 0; k < PART_SHORT; k++ ) {
        transient [k] = 0;
        th            = old_erg [0][k];
        for ( n = 0; n < 4; n++ ) {
            ep   = erg[n] + index_lo [k];
            l    = index_hi [k] - index_lo [k];

            new_erg = *ep++;
            while (l--)
                new_erg += *ep++;               // e = Short_Partition-energy in piece n

            if ( new_erg > old_erg [0][k] ) {           // bigger than the old?

                if ( new_erg > old_erg [0][k] * TransDetect  ||
					 new_erg > old_erg [1][k] * TransDetect*2 )  // is signal transient?
                    transient [k] = 1;
            }
            else {
                th = minf ( th, new_erg );          // assume short threshold = engr*PreechoFac
            }

            old_erg [1][k] = old_erg [0][k];
            old_erg [0][k] = new_erg;           // save the current one
        }
        thr [k] = th * ShortThr * *iwidth++;  // pull out and multiply only when transient[k]=1
    }

    return;
}
Beispiel #24
0
/** Add a sample to a tile using the AO algorithm
 * @param state global renderer state
 * @param pixels pixel buffer to add sample to
 * @param isect_buffer intersection buffer from samples generated by kernel_ao_gen_samples
 * @param mask_buffer the mask bitmap
 * @param n_pixels number of pixels in buffer
 * @param n_samples number of samples already in the buffer */
void kernel_ao_add_sample(state_t state, vec3* pixels, hit_t* isect_buffer, int* mask_buffer, sample_t* sample_buffer, int n_samples, int i) {
	//compute the sample
	float l;
	if(mask_buffer[i] == 1) {
		l = 0.f;
	}
	else if(isect_buffer[i].t == -1) {
		l = 1.f;
	}
	else {
		l = minf(1.f,isect_buffer[i].t/state.ao_params.length);
	}
	vec3 p = make_vec3(l,l,l);

	if(isnan(p.x) || isnan(p.y) || isnan(p.z)) {
		p = make_vec3(0.f,1.f,0.f);
	}
	pixels[i] = div_vec3_scalar(add_vec3(mul_vec3_scalar(pixels[i], n_samples+(1-sample_buffer[i].weight)), mul_vec3_scalar(p, sample_buffer[i].weight)),(n_samples+1));
}
template<typename Scalar> void special_numbers()
{
  typedef Matrix<Scalar, Dynamic,Dynamic> MatType;
  int rows = internal::random<int>(1,300);
  int cols = internal::random<int>(1,300);
  
  Scalar nan = std::numeric_limits<Scalar>::quiet_NaN();
  Scalar inf = std::numeric_limits<Scalar>::infinity();
  Scalar s1 = internal::random<Scalar>();
  
  MatType m1    = MatType::Random(rows,cols),
          mnan  = MatType::Random(rows,cols),
          minf  = MatType::Random(rows,cols),
          mboth = MatType::Random(rows,cols);
          
  int n = internal::random<int>(1,10);
  for(int k=0; k<n; ++k)
  {
    mnan(internal::random<int>(0,rows-1), internal::random<int>(0,cols-1)) = nan;
    minf(internal::random<int>(0,rows-1), internal::random<int>(0,cols-1)) = inf;
  }
  mboth = mnan + minf;
  
  VERIFY(!m1.hasNaN());
  VERIFY(m1.allFinite());
  
  VERIFY(mnan.hasNaN());
  VERIFY((s1*mnan).hasNaN());
  VERIFY(!minf.hasNaN());
  VERIFY(!(2*minf).hasNaN());
  VERIFY(mboth.hasNaN());
  VERIFY(mboth.array().hasNaN());
  
  VERIFY(!mnan.allFinite());
  VERIFY(!minf.allFinite());
  VERIFY(!(minf-mboth).allFinite());
  VERIFY(!mboth.allFinite());
  VERIFY(!mboth.array().allFinite());
}
Beispiel #26
0
static double
transform_distance_garmin(struct coord *c1, struct coord *c2)
{
#ifdef USE_HALVESINE
	static const int earth_radius = 6371*1000; //m change accordingly
// static const int earth_radius  = 3960; //miles
 
//Point 1 cords
	navit_float lat1  = GC2RAD(c1->y);
	navit_float long1 = GC2RAD(c1->x);

//Point 2 cords
	navit_float lat2  = GC2RAD(c2->y);
	navit_float long2 = GC2RAD(c2->x);

//Haversine Formula
	navit_float dlong = long2-long1;
	navit_float dlat  = lat2-lat1;

	navit_float sinlat  = navit_sin(dlat/2);
	navit_float sinlong = navit_sin(dlong/2);
 
	navit_float a=(sinlat*sinlat)+navit_cos(lat1)*navit_cos(lat2)*(sinlong*sinlong);
	navit_float c=2*navit_asin(minf(1,navit_sqrt(a)));
#ifdef AVOID_FLOAT
	return round(earth_radius*c);
#else
	return earth_radius*c;
#endif
#else
#define GMETER 2.3887499999999999
	navit_float dx,dy;
	dx=c1->x-c2->x;
	dy=c1->y-c2->y;
	return navit_sqrt(dx*dx+dy*dy)*GMETER;
#undef GMETER
#endif
}
Beispiel #27
0
// Calculate the coefficient for a HF (and eventually LF) decay damping
// filter.
static __inline ALfloat CalcDampingCoeff(ALfloat hfRatio, ALfloat length, ALfloat decayTime, ALfloat decayCoeff, ALfloat cw)
{
    ALfloat coeff, g;

    // Eventually this should boost the high frequencies when the ratio
    // exceeds 1.
    coeff = 0.0f;
    if (hfRatio < 1.0f)
    {
        // Calculate the low-pass coefficient by dividing the HF decay
        // coefficient by the full decay coefficient.
        g = CalcDecayCoeff(length, decayTime * hfRatio) / decayCoeff;

        // Damping is done with a 1-pole filter, so g needs to be squared.
        g *= g;
        coeff = lpCoeffCalc(g, cw);

        // Very low decay times will produce minimal output, so apply an
        // upper bound to the coefficient.
        coeff = minf(coeff, 0.98f);
    }
    return coeff;
}
Beispiel #28
0
void BatchRenderer::DrawDashedLine(
	const Vec3D& start,
	const Vec3D& end,
	const FLOAT dashSize,
	const FColor& startColor,
	const FColor& endColor
)
{
	mxSWIPED("Unreal Engine 3");

	Vec3D lineDir = end - start;
	FLOAT lineLeft = (end - start).LengthFast();
	lineDir /= lineLeft;

	while(lineLeft > 0.f)
	{
		Vec3D DrawStart = end - ( lineLeft * lineDir );
		Vec3D DrawEnd = DrawStart + ( minf(dashSize, lineLeft) * lineDir );

		this->DrawLine3D( DrawStart, DrawEnd, startColor, endColor );

		lineLeft -= 2*dashSize;
	}
}
void Cterrain::showAndMark(int jmin,int jmax,int imin,int imax,int curDepth)
{
    //检查当前节点是否与视截体相交
    //求节点p所表示区域的保守包围盒
    //    上面
    //    p[0]--p[3]
    //     |     |
    //    p[1]--p[2]
    //    下面
    //    p[4]--p[7]
    //     |     |
    //    p[5]--p[6]
    float xmin=m_range.getMinX()+gridSize*jmin;
    float xmax=m_range.getMinX()+gridSize*jmax;
    float zmin=m_range.getMinZ()+gridSize*imin;
    float zmax=m_range.getMinZ()+gridSize*imax;
    float ymin=m_range.getMinY();
    float ymax=m_range.getMaxY();
    float c[3]={(xmax+xmin)/2,(ymin+ymax)/2,(zmin+zmax)/2};
    float r=max(xmax-xmin,ymax-ymin)*0.86602540378443864676372317075294;//由于zmax-zmin与xmax-xmin相等,所以不用考虑
    //看球体(c,r)是否都在planeList中某个面的反面,如果是则可剔除
    bool visible=true;
    for(int i=0;i<5;i++){//不考虑远平面
        const Cplane&plane=this->getModel()->getMeshByIndex(0)->getCamera()->getFrustum().getPlaneByIndex(i);
        //看球体(c,r)是否在plane的背面
        float PND=PND_point_plane(plane, c);
        if(PND<-r){//如果在背面
            //断定为不可见,不用再继续检测
            visible=false;
            break;
        }
    }//得到visible
    if(visible){//如果可见
        bool needDiv=false;//是否需要再分
        //求needDiv
        if(imin+1==imax){//无须再分,因为已经无法再分
            needDiv=false;
        }else{//进一步判断
            //求c到视点的距离
            //指数值越大,LOD效应越明显
            float d=square(this->getModel()->getMeshByIndex(0)->getCamera()->getEyePos().x()-c[0])
            +square(minf(0.6*(this->getModel()->getMeshByIndex(0)->getCamera()->getEyePos().y()-c[1]),700))//Y乘以一个比1小的系数是为了让LOD对高度变化不敏感
            +square(this->getModel()->getMeshByIndex(0)->getCamera()->getEyePos().z()-c[2]);
            float e=xmax-xmin;//边长
            if(d<e*reso)needDiv=true;
        }//得到needDiv
        if(needDiv){//继续分
            int imid=(imin+imax)>>1;//除2
            int jmid=(jmin+jmax)>>1;
            markmat[imid][jmid]=true;
            markedElementIndexList.push_back(Cij(imid,jmid));
            //对四个孩子继续递归
            showAndMark(jmin,jmid,imin,imid,curDepth+1);
            showAndMark(jmin,jmid,imid,imax,curDepth+1);
            showAndMark(jmid,jmax,imid,imax,curDepth+1);
            showAndMark(jmid,jmax,imin,imid,curDepth+1);
        }else{//不分
            const int vIDMat_imin=(int)markmat[0].size()*imin;//vIDMat[imin];
            const int vIDMat_imax=(int)markmat[0].size()*imax;//vIDMat[imax];
            const int ID0=vIDMat_imin+jmin;
            const int ID1=vIDMat_imax+jmin;
            const int ID2=vIDMat_imax+jmax;
            const int ID3=vIDMat_imin+jmax;
            this->getModel()->getMeshByIndex(0)->addIDtri(ID0, ID1, ID2);
            this->getModel()->getMeshByIndex(0)->addIDtri(ID0, ID2, ID3);
        }
    }
Beispiel #30
0
void handle_mousedown(SDL_MouseButtonEvent button) {
	//printf("SDL Mousebutton down event: mouse %d, button %d, state %d, %dx%d\n", Event.button.which, Event.button.button, Event.button.state, Event.button.x, Event.button.y);
	switch (button.button) {
		case 1: // left mouse
			{
				float mousex = button.x;
				float mousey = Surf_Display->h - button.y;
				float w = Surf_Display->w;
				float h = Surf_Display->h;
				float dim = minf(w, h);
				gXmouseDown = transX + (mousex / w) * 200.0 * w / dim / zoomFactor;
				gYmouseDown = transY + (mousey / h) * 200.0 * h / dim / zoomFactor;
				if (timerDragRender)
					SDL_RemoveTimer(timerDragRender);
				timerDragRender = SDL_AddTimer(50, &timerCallback, (void *) TIMER_DRAGRENDER);
			}
			break;
		case 2: // middle mouse
			break;
		case 3: // right mouse
			break;
		case 4: // wheel up
			if ((keymodifiermask & (KMM_LSHIFT | KMM_RSHIFT)) == 0) {
			#ifdef	OPENGL
				float mousex = button.x;
				float mousey = Surf_Display->h - button.y;
				float w = Surf_Display->w;
				float h = Surf_Display->h;
				float dim = minf(w, h);
				float gX = transX + (mousex / w) * 200.0 * w / dim / zoomFactor;
				float gY = transY + (mousey / h) * 200.0 * h / dim / zoomFactor;
				//printf("%d,%d->%d,%d\n", (int) transX, (int) transY, (int) gX, (int) gY);
				zoomFactor *= 1.1;
				transX = gX - (mousex / w) * 200.0 * w / dim / zoomFactor;
				transY = gY - (mousey / h) * 200.0 * h / dim/ zoomFactor;
			#else
				//float viewX = (gX - viewPortL) * zoomFactor,
				float gX = ((float) button.x) / zoomFactor + viewPortL;
				// float viewY = (viewPortB - gY) * zoomFactor,
				float gY = viewPortB - ((float) button.y) / zoomFactor;
				zoomFactor *= 1.1;
				//printf("Zoom %g\n", zoomFactor);
				viewPortL = gX - ((float) button.x) / zoomFactor;
				viewPortB = ((float) button.y) / zoomFactor + gY;
			#endif
				render();
			}
			else if (currentLayer > 0)
				drawLayer(--currentLayer);
			break;
		case 5: // wheel down
			if ((keymodifiermask & (KMM_LSHIFT | KMM_RSHIFT)) == 0) {
			#ifdef	OPENGL
				float mousex = button.x;
				float mousey = Surf_Display->h - button.y;
				float w = Surf_Display->w;
				float h = Surf_Display->h;
				float dim = minf(w, h);
				float gX = transX + (mousex / w) * 200.0 * w / dim / zoomFactor;
				float gY = transY + (mousey / h) * 200.0 * h / dim / zoomFactor;
				//printf("%d,%d->%d,%d\n", (int) transX, (int) transY, (int) gX, (int) gY);
				zoomFactor /= 1.1;
				transX = gX - (mousex / w) * 200.0 * w / dim / zoomFactor;
				transY = gY - (mousey / h) * 200.0 * h / dim / zoomFactor;
			#else
				//float viewX = (gX - viewPortL) * zoomFactor,
				float gX = ((float) button.x) / zoomFactor + viewPortL;
				// float viewY = (viewPortB - gY) * zoomFactor,
				float gY = viewPortB - ((float) button.y) / zoomFactor;
				zoomFactor /= 1.1;
				//printf("Zoom %g\n", zoomFactor);
				viewPortL = gX - ((float) button.x) / zoomFactor;
				viewPortB = ((float) button.y) / zoomFactor + gY;
			#endif
				render();
			}
			else if (currentLayer < layerCount - 1)
				drawLayer(++currentLayer);
			break;
	}
}