//! Prepares an array with new particles to emitt into the system //! and returns how much new particles there are. s32 CParticleSphereEmitter::emitt(u32 now, u32 timeSinceLastCall, SParticle*& outArray) { Time += timeSinceLastCall; u32 pps = (MaxParticlesPerSecond - MinParticlesPerSecond); f32 perSecond = pps ? (f32)MinParticlesPerSecond + (os::Randomizer::rand() % pps) : MinParticlesPerSecond; f32 everyWhatMillisecond = 1000.0f / perSecond; if(Time > everyWhatMillisecond) { Particles.set_used(0); u32 amount = (u32)((Time / everyWhatMillisecond) + 0.5f); Time = 0; SParticle p; if(amount > MaxParticlesPerSecond*2) amount = MaxParticlesPerSecond * 2; for(u32 i=0; i<amount; ++i) { // Random distance from center f32 distance = fmodf( (f32)os::Randomizer::rand(), Radius * 1000.0f ) * 0.001f; // Random direction from center p.pos.X = Center.X + distance; p.pos.Y = Center.Y + distance; p.pos.Z = Center.Z + distance; p.pos.rotateXYBy( os::Randomizer::rand() % 360, Center ); p.pos.rotateYZBy( os::Randomizer::rand() % 360, Center ); p.pos.rotateXZBy( os::Randomizer::rand() % 360, Center ); p.startTime = now; p.vector = Direction; if(MaxAngleDegrees) { core::vector3df tgt = Direction; tgt.rotateXYBy((os::Randomizer::rand()%(MaxAngleDegrees*2)) - MaxAngleDegrees, core::vector3df()); tgt.rotateYZBy((os::Randomizer::rand()%(MaxAngleDegrees*2)) - MaxAngleDegrees, core::vector3df()); tgt.rotateXZBy((os::Randomizer::rand()%(MaxAngleDegrees*2)) - MaxAngleDegrees, core::vector3df()); p.vector = tgt; } if(MaxLifeTime - MinLifeTime == 0) p.endTime = now + MinLifeTime; else p.endTime = now + MinLifeTime + (os::Randomizer::rand() % (MaxLifeTime - MinLifeTime)); p.color = MinStartColor.getInterpolated( MaxStartColor, (os::Randomizer::rand() % 100) / 100.0f); p.startColor = p.color; p.startVector = p.vector; Particles.push_back(p); } outArray = Particles.pointer(); return Particles.size(); } return 0; }
void CLineDrawer::UpdateLineStipple() { stippleTimer += (gu->lastFrameTime * cmdColors.StippleSpeed()); stippleTimer = fmodf(stippleTimer, (16.0f / 20.0f)); }
void Song::processNextBuffer() { // if not playing, nothing to do if( m_playing == false ) { return; } TrackList trackList; int tcoNum = -1; // track content object number // determine the list of tracks to play and the track content object // (TCO) number switch( m_playMode ) { case Mode_PlaySong: trackList = tracks(); // at song-start we have to reset the LFOs if( m_playPos[Mode_PlaySong] == 0 ) { EnvelopeAndLfoParameters::instances()->reset(); } break; case Mode_PlayBB: if( Engine::getBBTrackContainer()->numOfBBs() > 0 ) { tcoNum = Engine::getBBTrackContainer()-> currentBB(); trackList.push_back( BBTrack::findBBTrack( tcoNum ) ); } break; case Mode_PlayPattern: if( m_patternToPlay != NULL ) { tcoNum = m_patternToPlay->getTrack()-> getTCONum( m_patternToPlay ); trackList.push_back( m_patternToPlay->getTrack() ); } break; default: return; } // if we have no tracks to play, nothing to do if( trackList.empty() == true ) { return; } // check for looping-mode and act if necessary TimeLineWidget * tl = m_playPos[m_playMode].m_timeLine; bool checkLoop = tl != NULL && m_exporting == false && tl->loopPointsEnabled(); if( checkLoop ) { // if looping-mode is enabled and we are outside of the looping // range, go to the beginning of the range if( m_playPos[m_playMode] < tl->loopBegin() || m_playPos[m_playMode] >= tl->loopEnd() ) { setToTime(tl->loopBegin()); m_playPos[m_playMode].setTicks( tl->loopBegin().getTicks() ); emit updateSampleTracks(); } } f_cnt_t framesPlayed = 0; const float framesPerTick = Engine::framesPerTick(); while( framesPlayed < Engine::mixer()->framesPerPeriod() ) { m_vstSyncController.update(); float currentFrame = m_playPos[m_playMode].currentFrame(); // did we play a tick? if( currentFrame >= framesPerTick ) { int ticks = m_playPos[m_playMode].getTicks() + ( int )( currentFrame / framesPerTick ); m_vstSyncController.setAbsolutePosition( ticks ); // did we play a whole tact? if( ticks >= MidiTime::ticksPerTact() ) { // per default we just continue playing even if // there's no more stuff to play // (song-play-mode) int maxTact = m_playPos[m_playMode].getTact() + 2; // then decide whether to go over to next tact // or to loop back to first tact if( m_playMode == Mode_PlayBB ) { maxTact = Engine::getBBTrackContainer() ->lengthOfCurrentBB(); } else if( m_playMode == Mode_PlayPattern && m_loopPattern == true && tl != NULL && tl->loopPointsEnabled() == false ) { maxTact = m_patternToPlay->length() .getTact(); } // end of played object reached? if( m_playPos[m_playMode].getTact() + 1 >= maxTact ) { // then start from beginning and keep // offset ticks %= ( maxTact * MidiTime::ticksPerTact() ); // wrap milli second counter setToTimeByTicks(ticks); m_vstSyncController.setAbsolutePosition( ticks ); } } m_playPos[m_playMode].setTicks( ticks ); if( checkLoop ) { m_vstSyncController.startCycle( tl->loopBegin().getTicks(), tl->loopEnd().getTicks() ); // if looping-mode is enabled and we have got // past the looping range, return to the // beginning of the range if( m_playPos[m_playMode] >= tl->loopEnd() ) { m_playPos[m_playMode].setTicks( tl->loopBegin().getTicks() ); setToTime(tl->loopBegin()); } else if( m_playPos[m_playMode] == tl->loopEnd() - 1 ) { emit updateSampleTracks(); } } else { m_vstSyncController.stopCycle(); } currentFrame = fmodf( currentFrame, framesPerTick ); m_playPos[m_playMode].setCurrentFrame( currentFrame ); } f_cnt_t framesToPlay = Engine::mixer()->framesPerPeriod() - framesPlayed; f_cnt_t framesLeft = ( f_cnt_t )framesPerTick - ( f_cnt_t )currentFrame; // skip last frame fraction if( framesLeft == 0 ) { ++framesPlayed; m_playPos[m_playMode].setCurrentFrame( currentFrame + 1.0f ); continue; } // do we have samples left in this tick but these are less // than samples we have to play? if( framesLeft < framesToPlay ) { // then set framesToPlay to remaining samples, the // rest will be played in next loop framesToPlay = framesLeft; } if( ( f_cnt_t ) currentFrame == 0 ) { processAutomations(trackList, m_playPos[m_playMode], framesToPlay); // loop through all tracks and play them for( int i = 0; i < trackList.size(); ++i ) { trackList[i]->play( m_playPos[m_playMode], framesToPlay, framesPlayed, tcoNum ); } } // update frame-counters framesPlayed += framesToPlay; m_playPos[m_playMode].setCurrentFrame( framesToPlay + currentFrame ); m_elapsedMilliSeconds += MidiTime::ticksToMilliseconds( framesToPlay / framesPerTick, getTempo()); m_elapsedTacts = m_playPos[Mode_PlaySong].getTact(); m_elapsedTicks = ( m_playPos[Mode_PlaySong].getTicks() % ticksPerTact() ) / 48; } }
int Grid::GetIndex(Vector3 _pos) { Vector3 pos = _pos; float multiple = (m_extents.x / ((float)m_splits / 2)); float modifier = 0; if (m_splits % 2 == 0) { modifier = multiple / 2; /*if (pos.x > 0) { modifier *= -1; }*/ } float x = pos.x + (multiple / 2) + modifier; if (x < 0) { x -= multiple + fmodf(x, multiple); } else { x -= fmodf(x, multiple); } x -= modifier; if (x > m_extents.x) { x -= multiple; } else if(x < -m_extents.x) { x += multiple; } x += m_extents.x; x /= multiple; x = floor(x); multiple = (m_extents.y / ((float)m_splits / 2)); modifier = 0; if (m_splits % 2 == 0) { modifier = multiple / 2; /*if (pos.y > 0) { modifier *= -1; }*/ } float y = pos.y + (multiple / 2) + modifier; if (y < 0) { y -= multiple + fmodf(y, multiple); } else { y -= fmodf(y, multiple); } y -= modifier; if (y > m_extents.y) { y -= multiple; } else if (y < -m_extents.y) { y += multiple; } y += m_extents.y; y /= multiple; y = floor(y); return (int)((y * m_splits) + x); }
void handleInput(GameState* gs, InputState* is) { double te = gs->frameSpan; float moveSpeed = gs->settings.keyScroll * te; // should load from config float rotateSpeed = gs->settings.keyRotate * te; // 20.8 degrees float keyZoom = gs->settings.keyZoom * te; float mouseZoom = gs->settings.mouseZoom * te; if(is->clickButton == 1) { /* flattenArea(gs->map.tb, gs->cursorPos.x - 5, gs->cursorPos.y - 5, gs->cursorPos.x + 5, gs->cursorPos.y + 5 ); setZone(&gs->map, gs->cursorPos.x - 5, gs->cursorPos.y - 5, gs->cursorPos.x + 5, gs->cursorPos.y + 5, gs->activeTool + 1 ); checkMapDirty(&gs->map); */ } if(is->buttonDown == 1) { gs->mouseDownPos.x = gs->cursorPos.x; gs->mouseDownPos.y = gs->cursorPos.y; printf("start dragging at (%d,%d)\n", (int)gs->cursorPos.x, (int)gs->cursorPos.y); } if(is->buttonUp == 1) { //vCopy(&gs->cursorPos, &gs->mouseDownPos); printf("stopped dragging at (%d,%d)\n", (int)gs->cursorPos.x, (int)gs->cursorPos.y); } if(is->clickButton == 2) { gs->activeTool = (gs->activeTool + 1) % 3; } // look direction if(is->keyState[38] & IS_KEYDOWN) { gs->direction += rotateSpeed; } if(is->keyState[39] & IS_KEYDOWN) { gs->direction -= rotateSpeed; } // keep rotation in [0,F_2PI) gs->direction = fmodf(F_2PI + gs->direction, F_2PI); // zoom if(is->keyState[52] & IS_KEYDOWN) { gs->zoom += keyZoom; gs->zoom = fmin(gs->zoom, -10.0); } if(is->keyState[53] & IS_KEYDOWN) { gs->zoom -= keyZoom; } if(is->clickButton == 4) { gs->zoom += mouseZoom; gs->zoom = fmin(gs->zoom, -10.0); } if(is->clickButton == 5) { gs->zoom -= mouseZoom; } // movement Vector move = { .x = moveSpeed * sin(F_PI - gs->direction), .y = moveSpeed * cos(F_PI - gs->direction), .z = 0.0f }; if(is->keyState[111] & IS_KEYDOWN) { vAdd(&gs->lookCenter, &move, &gs->lookCenter); } if(is->keyState[116] & IS_KEYDOWN) { vSub(&gs->lookCenter, &move, &gs->lookCenter); } // flip x and y to get ccw normal, using move.z as the temp move.z = move.x; move.x = -move.y; move.y = move.z; move.z = 0.0f; if(is->keyState[113] & IS_KEYDOWN) { vSub(&gs->lookCenter, &move, &gs->lookCenter); } if(is->keyState[114] & IS_KEYDOWN) { vAdd(&gs->lookCenter, &move, &gs->lookCenter); } if(is->keyState[110] & IS_KEYDOWN) { nearPlane += 50 * te; printf("near: %f, far: %f\n", nearPlane, farPlane); } if(is->keyState[115] & IS_KEYDOWN) { nearPlane -= 50 * te; printf("near: %f, far: %f\n", nearPlane, farPlane); } if(is->keyState[112] & IS_KEYDOWN) { farPlane += 250 * te; printf("near: %f, far: %f\n", nearPlane, farPlane); } if(is->keyState[117] & IS_KEYDOWN) { farPlane -= 250 * te; printf("near: %f, far: %f\n", nearPlane, farPlane); } static lastChange = 0; if(is->keyState[119] & IS_KEYDOWN) { if(gs->frameTime > lastChange + 1) { gs->debugMode = (gs->debugMode + 1) % 5; lastChange = gs->frameTime; } } } void setGameSettings(GameSettings* g, UserConfig* u) { const float rotateFactor = 0.7260f; const float scrollFactor = 300.0f; const float zoomFactor = 600.0f; g->keyRotate = rotateFactor * fclampNorm(u->keyRotateSensitivity); g->keyScroll = scrollFactor * fclampNorm(u->keyScrollSensitivity); g->keyZoom = zoomFactor * fclampNorm(u->keyZoomSensitivity); g->mouseRotate = rotateFactor * fclampNorm(u->mouseRotateSensitivity); g->mouseScroll = scrollFactor * fclampNorm(u->mouseScrollSensitivity); g->mouseZoom = 4 * zoomFactor * fclampNorm(u->mouseZoomSensitivity); printf("keyRotate %.3f\n", g->keyRotate); printf("keyScroll %.3f\n", g->keyScroll); printf("keyZoom %.3f\n", g->keyZoom); printf("mouseRotate %.3f\n", g->mouseRotate); printf("mouseScroll %.3f\n", g->mouseScroll); printf("mouseZoom %.3f\n", g->mouseZoom); } void setUpView(GameState* gs) { } void depthPrepass(XStuff* xs, GameState* gs, InputState* is) { // draw UI renderUIPicking(xs, gs); // draw terrain // TODO: factor all the math into the frame setup function //mScale3f(10, 10, 10, &mModel); //mRot3f(0, 1, 0, gs->direction, &mModel); msPush(&gs->proj); msPerspective(60, gs->screen.aspect, nearPlane, farPlane, &gs->proj); msPush(&gs->view); // order matters! don't mess with this. msTrans3f(0, -1, gs->zoom, &gs->view); msRot3f(1, 0, 0, F_PI / 6, &gs->view); msRot3f(0,1,0, gs->direction, &gs->view); msTrans3f(-gs->lookCenter.x, 0, -gs->lookCenter.y, &gs->view); // y-up to z-up rotation msRot3f(1, 0, 0, F_PI_2, &gs->view); msScale3f(1, 1, -1, &gs->view); // calculate cursor position Vector eyeCoord; Vector worldCoord; Matrix p, invp, invv; // device space (-1:1) Vector devCoord; devCoord.x = 0.50; devCoord.y = 0.50; devCoord.z = -1.0; // eye space mInverse(msGetTop(&gs->proj), &invp); vMatrixMul(&devCoord, &invp, &eyeCoord); vNorm(&eyeCoord, &eyeCoord); // world space mInverse(msGetTop(&gs->view), &invv); vMatrixMul(&eyeCoord, &invv, &worldCoord); vNorm(&worldCoord, &worldCoord); // draw terrain // drawTerrainBlockDepth(&gs->map, msGetTop(&gs->model), msGetTop(&gs->view), msGetTop(&gs->proj)); drawTerrainDepth(&gs->map, msGetTop(&gs->view), msGetTop(&gs->proj), &gs->screen.wh); msPop(&gs->view); msPop(&gs->proj); }
void ospml_hybrid(const float* data, int dy, int dt, int dx, const float* center, const float* theta, float* recon, int ngridx, int ngridy, int num_iter, const float* reg_pars, int num_block, const float* ind_block) { if(dy == 0 || dt == 0 || dx == 0) return; float* gridx = (float*) malloc((ngridx + 1) * sizeof(float)); float* gridy = (float*) malloc((ngridy + 1) * sizeof(float)); float* coordx = (float*) malloc((ngridy + 1) * sizeof(float)); float* coordy = (float*) malloc((ngridx + 1) * sizeof(float)); float* ax = (float*) malloc((ngridx + ngridy) * sizeof(float)); float* ay = (float*) malloc((ngridx + ngridy) * sizeof(float)); float* bx = (float*) malloc((ngridx + ngridy) * sizeof(float)); float* by = (float*) malloc((ngridx + ngridy) * sizeof(float)); float* coorx = (float*) malloc((ngridx + ngridy) * sizeof(float)); float* coory = (float*) malloc((ngridx + ngridy) * sizeof(float)); float* dist = (float*) malloc((ngridx + ngridy) * sizeof(float)); int* indi = (int*) malloc((ngridx + ngridy) * sizeof(int)); assert(coordx != NULL && coordy != NULL && ax != NULL && ay != NULL && by != NULL && bx != NULL && coorx != NULL && coory != NULL && dist != NULL && indi != NULL); int s, q, p, d, i, m, n, os; int quadrant; float theta_p, sin_p, cos_p; float mov, xi, yi; int asize, bsize, csize; float* simdata; float upd; int ind_data, ind_recon; float* sum_dist; float sum_dist2; float *E, *F, *G; int ind0, ind1, indg[8]; float totalwg, wg[8], mg[8], rg[8], gammag[8]; int subset_ind1, subset_ind2; for(i = 0; i < num_iter; i++) { simdata = (float*) calloc((dt * dy * dx), sizeof(float)); // For each slice for(s = 0; s < dy; s++) { preprocessing(ngridx, ngridy, dx, center[s], &mov, gridx, gridy); // Outputs: mov, gridx, gridy subset_ind1 = dt / num_block; subset_ind2 = subset_ind1; // For each ordered-subset num_subset for(os = 0; os < num_block + 1; os++) { if(os == num_block) { subset_ind2 = dt % num_block; } sum_dist = (float*) calloc((ngridx * ngridy), sizeof(float)); E = (float*) calloc((ngridx * ngridy), sizeof(float)); F = (float*) calloc((ngridx * ngridy), sizeof(float)); G = (float*) calloc((ngridx * ngridy), sizeof(float)); // For each projection angle for(q = 0; q < subset_ind2; q++) { p = ind_block[q + os * subset_ind1]; // Calculate the sin and cos values // of the projection angle and find // at which quadrant on the cartesian grid. theta_p = fmodf(theta[p], 2.0f * (float) M_PI); quadrant = calc_quadrant(theta_p); sin_p = sinf(theta_p); cos_p = cosf(theta_p); // For each detector pixel for(d = 0; d < dx; d++) { // Calculate coordinates xi = -ngridx - ngridy; yi = 0.5f * (1 - dx) + d + mov; calc_coords(ngridx, ngridy, xi, yi, sin_p, cos_p, gridx, gridy, coordx, coordy); // Merge the (coordx, gridy) and (gridx, coordy) trim_coords(ngridx, ngridy, coordx, coordy, gridx, gridy, &asize, ax, ay, &bsize, bx, by); // Sort the array of intersection points (ax, ay) and // (bx, by). The new sorted intersection points are // stored in (coorx, coory). Total number of points // are csize. sort_intersections(quadrant, asize, ax, ay, bsize, bx, by, &csize, coorx, coory); // Calculate the distances (dist) between the // intersection points (coorx, coory). Find the // indices of the pixels on the reconstruction grid. calc_dist(ngridx, ngridy, csize, coorx, coory, indi, dist); // Calculate simdata calc_simdata(s, p, d, ngridx, ngridy, dt, dx, csize, indi, dist, recon, simdata); // Output: simdata // Calculate dist*dist sum_dist2 = 0.0f; for(n = 0; n < csize - 1; n++) { sum_dist2 += dist[n] * dist[n]; sum_dist[indi[n]] += dist[n]; } // Update if(sum_dist2 != 0.0f) { ind_data = d + p * dx + s * dt * dx; ind_recon = s * ngridx * ngridy; upd = data[ind_data] / simdata[ind_data]; for(n = 0; n < csize - 1; n++) { E[indi[n]] -= recon[indi[n] + ind_recon] * upd * dist[n]; } } } } // Weights for inner neighborhoods. totalwg = 4 + 4 / sqrt(2); wg[0] = 1 / totalwg; wg[1] = 1 / totalwg; wg[2] = 1 / totalwg; wg[3] = 1 / totalwg; wg[4] = 1 / sqrt(2) / totalwg; wg[5] = 1 / sqrt(2) / totalwg; wg[6] = 1 / sqrt(2) / totalwg; wg[7] = 1 / sqrt(2) / totalwg; // (inner region) for(n = 1; n < ngridx - 1; n++) { for(m = 1; m < ngridy - 1; m++) { ind0 = m + n * ngridy; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 + 1; indg[1] = ind1 - 1; indg[2] = ind1 + ngridy; indg[3] = ind1 - ngridy; indg[4] = ind1 + ngridy + 1; indg[5] = ind1 + ngridy - 1; indg[6] = ind1 - ngridy + 1; indg[7] = ind1 - ngridy - 1; for(q = 0; q < 8; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } } } // Weights for edges. totalwg = 3 + 2 / sqrt(2); wg[0] = 1 / totalwg; wg[1] = 1 / totalwg; wg[2] = 1 / totalwg; wg[3] = 1 / sqrt(2) / totalwg; wg[4] = 1 / sqrt(2) / totalwg; // (top) for(m = 1; m < ngridy - 1; m++) { ind0 = m; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 + 1; indg[1] = ind1 - 1; indg[2] = ind1 + ngridy; indg[3] = ind1 + ngridy + 1; indg[4] = ind1 + ngridy - 1; for(q = 0; q < 5; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } } // (bottom) for(m = 1; m < ngridy - 1; m++) { ind0 = m + (ngridx - 1) * ngridy; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 + 1; indg[1] = ind1 - 1; indg[2] = ind1 - ngridy; indg[3] = ind1 - ngridy + 1; indg[4] = ind1 - ngridy - 1; for(q = 0; q < 5; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } } // (left) for(n = 1; n < ngridx - 1; n++) { ind0 = n * ngridy; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 + 1; indg[1] = ind1 + ngridy; indg[2] = ind1 - ngridy; indg[3] = ind1 + ngridy + 1; indg[4] = ind1 - ngridy + 1; for(q = 0; q < 5; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } } // (right) for(n = 1; n < ngridx - 1; n++) { ind0 = (ngridy - 1) + n * ngridy; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 - 1; indg[1] = ind1 + ngridy; indg[2] = ind1 - ngridy; indg[3] = ind1 + ngridy - 1; indg[4] = ind1 - ngridy - 1; for(q = 0; q < 5; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } } // Weights for corners. totalwg = 2 + 1 / sqrt(2); wg[0] = 1 / totalwg; wg[1] = 1 / totalwg; wg[2] = 1 / sqrt(2) / totalwg; // (top-left) ind0 = 0; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 + 1; indg[1] = ind1 + ngridy; indg[2] = ind1 + ngridy + 1; for(q = 0; q < 3; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } // (top-right) ind0 = (ngridy - 1); ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 - 1; indg[1] = ind1 + ngridy; indg[2] = ind1 + ngridy - 1; for(q = 0; q < 3; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } // (bottom-left) ind0 = (ngridx - 1) * ngridy; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 + 1; indg[1] = ind1 - ngridy; indg[2] = ind1 - ngridy + 1; for(q = 0; q < 3; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } // (bottom-right) ind0 = (ngridy - 1) + (ngridx - 1) * ngridy; ind1 = ind0 + s * ngridx * ngridy; indg[0] = ind1 - 1; indg[1] = ind1 - ngridy; indg[2] = ind1 - ngridy - 1; for(q = 0; q < 3; q++) { mg[q] = recon[ind1] + recon[indg[q]]; rg[q] = recon[ind1] - recon[indg[q]]; gammag[q] = 1 / (1 + fabs(rg[q] / reg_pars[1])); F[ind0] += 2 * reg_pars[0] * wg[q] * gammag[q]; G[ind0] -= 2 * reg_pars[0] * wg[q] * gammag[q] * mg[q]; } q = 0; for(n = 0; n < ngridx * ngridy; n++) { G[q] += sum_dist[n]; q++; } for(n = 0; n < ngridx; n++) { for(m = 0; m < ngridy; m++) { q = m + n * ngridy; if(F[q] != 0.0) { ind0 = q + s * ngridx * ngridy; recon[ind0] = (-G[q] + sqrt(G[q] * G[q] - 8 * E[q] * F[q])) / (4 * F[q]); } } } free(sum_dist); free(E); free(F); free(G); } } free(simdata); } free(gridx); free(gridy); free(coordx); free(coordy); free(ax); free(ay); free(bx); free(by); free(coorx); free(coory); free(dist); free(indi); }
int main(int argc, char const *argv[]) { FILE * input; input = fopen('test.txt', "r"); int n; long int lowerlim, upperlim; long int b, found, r, maxk, nextR, gcda, toir; double logresult, a, npowk; fscanf(input, "%d", &n); while(n > 0){ fscanf(input, "%d %d", lowerlim, upperlim); while(lowerlim <= upperlim) { logresult = log2(lowerlim); for (b = 0; b < logresult; ++b) { a = pow(n, 1.0/b); if(a == (int )a){ printf("%s\n", "composite"); printf("%d\n", (int) a); found = 1; break; } } if (!found) { maxk = abs(pow(log2(lowerlim), 2)); r = 2; nextR = 1; for (r = 2, nextR && r < maxk, r++ ){ nextR = 0; for (k = 1; (!nextR) k <= maxk, ++k) { npowk = (int)pow(lowerlim, k); nextR = (((int)fmodf(npowk, r)) == 1 ||((int)fmodf(npowk, r)) == 0); } } r--; for (a = r; a > 1; a--) { gcda = gcd(a, lowerlim); if (gcda > 1 && gcd < lowerlim){ found = 1; printf("%s\n", "composite"); printf("%d\n", a); break; } } } if (!found) { if (n <= r) { found = 1; printf("%s\n", "prime"); printf("%d\n", lowerlim); } } if (!found) { toir = (int )floor(sqrt(phi(r))log(lowerlim)); for(a = 1; a <= toir; a++) { if (/* condition */) { /* code */ } } } lowerlim ++ }
static void layout_flow(fz_context *ctx, fz_html *box, fz_html *top, float em, float page_h) { fz_html_flow *node, *line_start, *word_start, *word_end, *line_end; float glue_w; float word_w; float line_w; float indent; float avail, line_h; float baseline; int align; em = fz_from_css_number(box->style.font_size, em, em); indent = box->is_first_flow ? fz_from_css_number(top->style.text_indent, em, top->w) : 0; align = top->style.text_align; box->x = top->x; box->y = top->y + top->h; box->w = top->w; box->h = 0; if (!box->flow_head) return; for (node = box->flow_head; node; node = node->next) if (node->type == FLOW_IMAGE) measure_image(ctx, node, top->w, page_h); else measure_word(ctx, node, em); line_start = find_next_word(box->flow_head, &glue_w); line_end = NULL; line_w = indent; word_w = 0; word_start = line_start; while (word_start) { word_end = find_next_glue(word_start, &word_w); if (line_w + word_w <= top->w) { line_w += word_w; glue_w = 0; line_end = word_end; word_start = find_next_word(word_end, &glue_w); word_w = glue_w; } else { avail = page_h - fmodf(box->y + box->h, page_h); line_h = measure_line(line_start, line_end, &baseline); if (line_h > avail) box->h += avail; layout_line(ctx, indent, top->w, line_w, align, line_start, line_end, box, baseline); box->h += line_h; word_start = find_next_word(line_end, &glue_w); line_start = word_start; line_end = NULL; indent = 0; line_w = 0; word_w = 0; } } /* don't justify the last line of a paragraph */ if (align == TA_JUSTIFY) align = TA_LEFT; if (line_start) { avail = page_h - fmodf(box->y + box->h, page_h); line_h = measure_line(line_start, line_end, &baseline); if (line_h > avail) box->h += avail; layout_line(ctx, indent, top->w, line_w, align, line_start, line_end, box, baseline); box->h += line_h; } }
void ifs_render(float t) { if(ifs_loaded!=(int)(ifs_number)) ifs_load((int)ifs_number); // if(ifs_loaded!=(int)(angles[254])) ifs_load((int)angles[254]); g_pd3dDevice->BeginScene(); // g_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 0xff000000, 1.0f, 0L ); ifs_clear(); g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); g_pd3dDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_ALWAYS); // render_bg(g_pd3dDevice, bg); D3DXMATRIX matWorld; D3DXMatrixIdentity( &matWorld ); // D3DXMatrixScaling(&matWorld, ifs_z,ifs_z,ifs_z); g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); // Set up our view matrix. A view matrix can be defined given an eye point, // a point to lookat, and a direction for which way is up. Here, we set the // eye five units back along the z-axis and up three units, look at the // origin, and define "up" to be in the y-direction. D3DXMATRIX matView; D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( 0.0f, 0.0f,-3.0f+ifs_z), &D3DXVECTOR3( 0.0f, 0.0f, 0.0f ), &D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) ); g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView ); // For the projection matrix, we set up a perspective transform (which // transforms geometry from 3D view space to 2D viewport space, with // a perspective divide making objects smaller in the distance). To build // a perpsective transform, we need the field of view (1/4 pi is common), // the aspect ratio, and the near and far clipping planes (which define at // what distances geometry should be no longer be rendered). D3DXMATRIX matProj; //D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f ); D3DXMatrixPerspectiveFovLH( &matProj, 1, 4.f/3.f, 0.1f, 100.0f ); g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); g_pd3dDevice->SetTexture(3, m_pParticleTexture ); int alpha=(int)(255*fade); m_pd3dDevice->SetRenderState( D3DRS_TEXTUREFACTOR, 0x01010101*(alpha)); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_TEXCOORDINDEX, 0); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_COLOROP, D3DTOP_MODULATE ); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_COLORARG2, D3DTA_CURRENT); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_COLORARG1, D3DTA_TEXTURE ); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); m_pd3dDevice->SetTextureStageState( 3, D3DTSS_ALPHAARG1, D3DTA_CURRENT ); // Set the render states for using point sprites g_pd3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, TRUE); g_pd3dDevice->SetRenderState( D3DRS_POINTSCALEENABLE, FALSE ); g_pd3dDevice->SetRenderState( D3DRS_POINTSIZE, FtoDW(8.0f) ); g_pd3dDevice->SetRenderState( D3DRS_POINTSIZE_MIN, FtoDW(0.01f) ); g_pd3dDevice->SetRenderState( D3DRS_POINTSCALE_A, FtoDW(0.00f) ); g_pd3dDevice->SetRenderState( D3DRS_POINTSCALE_B, FtoDW(0.00f) ); g_pd3dDevice->SetRenderState( D3DRS_POINTSCALE_C, FtoDW(1.00f) ); // Set up the vertex buffer to be rendered // pd3dDevice->SetStreamSource( 0, ifs_vb, 0, sizeof(POINTVERTEX) ); g_pd3dDevice->SetVertexShader( D3DFVF_XYZ | D3DFVF_DIFFUSE ); /* g_pd3dDevice->SetRenderState (D3DRS_POINTSCALEENABLE, FALSE); // All textures must be turned off. g_pd3dDevice->SetTexture (0, NULL); g_pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); // The point size render state must be set to any value between 0.0-1.0 g_pd3dDevice->SetRenderState(D3DRS_POINTSIZE, 1.0); */ g_pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE ); // Turn off culling g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); // Turn off D3D lighting g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); // printf("%4.2f\n", t); g_anim.time = fmodf(t, g_anim.getEndTime()); g_anim.renderFlame(); g_pd3dDevice->SetTexture(3, NULL); g_pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE ); g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); g_pd3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, FALSE); g_pd3dDevice->EndScene(); // g_pd3dDevice->Present( NULL, NULL, NULL, NULL ); }
static float fast_mod(float angle, float max) { if (angle >= max || angle <= -max) { angle = fmodf(angle, max); } return angle; }
static void paint(void *widget, OsdPainter *painter, int x, int y) { WgVerticalGauge *self = widget; osdPainterTranslate(painter, x, y); osdPainterSetPen(painter, &gaugePen); osdPainterSetBrush(painter, &gaugeBrush); osdPainterDrawLine(painter, 0, -GAUGE_HEIGHT / 2, 0, GAUGE_HEIGHT / 2); // draw scale osdPainterSetFont(painter, osdFontByName("consolas10")); float rem = fmodf(self->value, self->scale); int offset = (int)((rem / self->scale) * LONG_NOTCH_SPACE); float centerNotchVal =self->scale * ((int)(self->value / self->scale)); float upNotchVal = centerNotchVal; float downNotchVal = upNotchVal; int ygamut = 0; while(1) { bool longNotch = (((ygamut) % LONG_NOTCH_SPACE) == 0); int notchLen = (longNotch) ? LONG_NOTCH_LEN : SHORT_NOTCH_LEN; if (self->leftSide) notchLen = -notchLen; if ((ygamut + offset) <= (GAUGE_HEIGHT / 2)) { if ((!self->noNegative) || (downNotchVal >= 0)) { osdPainterDrawLine(painter, 0, ygamut + offset, notchLen, ygamut + offset); // draw notch caption (lower) if (longNotch) { char strVal[8]; itoa((int)downNotchVal, strVal, 10); int textX; if (self->leftSide) { int width = 0; int height = 0; osdPainterTextBounds(painter, strVal, &width, &height); textX = -LONG_NOTCH_LEN - 2 - width; } else { textX = LONG_NOTCH_LEN + 2; } osdPainterDrawText(painter, textX, ygamut + offset - 5, strVal); } } if (longNotch) downNotchVal -= self->scale; } if ((-ygamut + offset) < (-GAUGE_HEIGHT / 2)) break; osdPainterDrawLine(painter, 0, -ygamut + offset, notchLen, -ygamut + offset); // draw notch caption (upper) if (longNotch) { char strVal[8]; itoa((int)upNotchVal, strVal, 10); upNotchVal += self->scale; int textX; if (self->leftSide) { int width = 0; int height = 0; osdPainterTextBounds(painter, strVal, &width, &height); textX = -LONG_NOTCH_LEN - 2 - width; } else { textX = LONG_NOTCH_LEN + 2; } osdPainterDrawText(painter, textX, -ygamut + offset - 5, strVal); } ygamut += SHORT_NOTCH_SPACE; } // draw arrow with value char strVal[12]; if (fabsf(self->value) < 10) { if (self->value < 0) lsprintf(strVal, "-%d.%d", (int)fabsf(self->value), (int)fabsf(self->value * 10) % 10); else lsprintf(strVal, "%d.%d", (int)fabsf(self->value), (int)fabsf(self->value * 10) % 10); } else { itoa((int)self->value, strVal, 10); } int width = 0; int height = 0; osdPainterSetFont(painter, osdFontByName(needleFont)); osdPainterTextBounds(painter, strVal, &width, &height); int textValueX = 0; int textUnitX = 0; int poly[10]; if (!self->leftSide) { poly[0] = 1; poly[1] = 0; poly[2] = NEEDLE_LENGTH; poly[3] = -height / 2 - 1; poly[4] = NEEDLE_LENGTH + width + 1; poly[5] = -height / 2 -1; poly[6] = NEEDLE_LENGTH + width + 1; poly[7] = height / 2 + 1; poly[8] = NEEDLE_LENGTH; poly[9] = height / 2 +1; textValueX = NEEDLE_LENGTH + 1; textUnitX = LONG_NOTCH_LEN + 28; } else { poly[0] = -1; poly[1] = 0; poly[2] = -NEEDLE_LENGTH; poly[3] = -height / 2 - 1; poly[4] = -NEEDLE_LENGTH - width - 1; poly[5] = -height / 2 -1; poly[6] = -NEEDLE_LENGTH - width - 1; poly[7] = height / 2 + 1; poly[8] = -NEEDLE_LENGTH; poly[9] = height / 2 +1; textValueX = - NEEDLE_LENGTH - width + 1; textUnitX = - LONG_NOTCH_LEN - 45; } osdPainterSetPen(painter, &needlePen); osdPainterSetBrush(painter, &needleBrush); osdPainterDrawPoly(painter, poly, 5); osdPainterSetBrush(painter, &gaugeBrush); osdPainterSetPen(painter, &textPen); osdPainterDrawText(painter, textValueX, -height / 2 + 1, strVal); osdPainterSetFont(painter, osdFontByName(captionFont)); osdPainterDrawText(painter, textUnitX, 12, self->units); }
//----------------------------------------------------------------------------- // updateMotion() //----------------------------------------------------------------------------- void LLMotionController::updateMotions(bool force_update) { BOOL use_quantum = (mTimeStep != 0.f); // Always update mPrevTimerElapsed F32 cur_time = mTimer.getElapsedTimeF32(); F32 delta_time = cur_time - mPrevTimerElapsed; mPrevTimerElapsed = cur_time; mLastTime = mAnimTime; // Always cap the number of loaded motions purgeExcessMotions(); // Update timing info for this time step. if (!mPaused) { F32 update_time = mAnimTime + delta_time * mTimeFactor; if (use_quantum) { F32 time_interval = fmodf(update_time, mTimeStep); //<singu> // This old code is nonsense. //S32 quantum_count = llmax(0, ll_round((update_time - time_interval) / mTimeStep)) + 1; // (update_time - time_interval) / mTimeStep is an integer! We need ll_round to get rid of floating point errors, not llfloor. // Moreover, just rounding off to the nearest integer with ll_round(update_time / mTimeStep) makes a lot more sense: // it is the best we can do to get as close to what we should draw as possible. // However, mAnimTime may only be incremented; therefore make sure of that with the llmax. S32 quantum_count = llmax(ll_round(update_time / mTimeStep), llceil(mAnimTime / mTimeStep)); //</singu> if (quantum_count == mTimeStepCount) { // we're still in same time quantum as before, so just interpolate and exit if (!mPaused) { F32 interp = time_interval / mTimeStep; mPoseBlender.interpolate(interp - mLastInterp); mLastInterp = interp; } updateLoadingMotions(); return; } // is calculating a new keyframe pose, make sure the last one gets applied mPoseBlender.interpolate(1.f); clearBlenders(); mTimeStepCount = quantum_count; // Singu note: mAnimTime may never be set back in time. // Despite the llmax/llceil above, (F32)quantum_count * mTimeStep can still // be a tiny bit smaller than mAnimTime due to floating point round off errors. mAnimTime = llmax(mAnimTime, (F32)quantum_count * mTimeStep); mLastInterp = 0.f; } else { // Singu note: mAnimTime may never be set back in time. mAnimTime = llmax(mAnimTime, update_time); } } updateLoadingMotions(); resetJointSignatures(); if (mPaused && !force_update) { updateIdleActiveMotions(); } else { // update additive motions updateAdditiveMotions(); resetJointSignatures(); // update all regular motions updateRegularMotions(); if (use_quantum) { mPoseBlender.blendAndCache(TRUE); } else { mPoseBlender.blendAndApply(); } } mHasRunOnce = TRUE; // llinfos << "Motion controller time " << motionTimer.getElapsedTimeF32() << llendl; }
int audioCallback (const void *inputBuffer, void *outputBuffer, unsigned long frames, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { AudioData *data = (AudioData *) userData; int16_t *inputLeft = ((int16_t **) inputBuffer)[0]; // int16_t *inputRight = ((int16_t **) inputBuffer)[1]; //printf("Audio callback at %6.0f\n", usecTimestampNow()/1000); if (inputLeft != NULL) { // // Measure the loudness of the signal from the microphone and store in audio object // float loudness = 0; for (int i = 0; i < BUFFER_LENGTH_SAMPLES; i++) { loudness += abs(inputLeft[i]); } loudness /= BUFFER_LENGTH_SAMPLES; data->lastInputLoudness = loudness; data->averagedInputLoudness = 0.66*data->averagedInputLoudness + 0.33*loudness; // // If scope is turned on, copy input buffer to scope // if (scope->getState()) { for (int i = 0; i < BUFFER_LENGTH_SAMPLES; i++) { scope->addData((float)inputLeft[i]/32767.0, 1, i); } } if (data->mixerAddress != 0) { sockaddr_in audioMixerSocket; audioMixerSocket.sin_family = AF_INET; audioMixerSocket.sin_addr.s_addr = data->mixerAddress; audioMixerSocket.sin_port = data->mixerPort; int leadingBytes = 2 + (sizeof(float) * 4); // we need the amount of bytes in the buffer + 1 for type // + 12 for 3 floats for position + float for bearing + 1 attenuation byte unsigned char dataPacket[BUFFER_LENGTH_BYTES + leadingBytes]; dataPacket[0] = PACKET_HEADER_INJECT_AUDIO; unsigned char *currentPacketPtr = dataPacket + 1; // memcpy the three float positions for (int p = 0; p < 3; p++) { memcpy(currentPacketPtr, &data->linkedHead->getPos()[p], sizeof(float)); currentPacketPtr += sizeof(float); } // tell the mixer not to add additional attenuation to our source *(currentPacketPtr++) = 255; // memcpy the corrected render yaw float correctedYaw = fmodf(data->linkedHead->getRenderYaw(), 360); if (correctedYaw > 180) { correctedYaw -= 360; } else if (correctedYaw < -180) { correctedYaw += 360; } if (data->mixerLoopbackFlag) { correctedYaw = correctedYaw > 0 ? correctedYaw + AGENT_LOOPBACK_MODIFIER : correctedYaw - AGENT_LOOPBACK_MODIFIER; } memcpy(currentPacketPtr, &correctedYaw, sizeof(float)); currentPacketPtr += sizeof(float); // if (samplesLeftForWalk == 0) { // sampleWalkPointer = walkingSoundArray; // } // // if (data->playWalkSound) { // // if this boolean is true and we aren't currently playing the walk sound // // set the number of samples left for walk // samplesLeftForWalk = walkingSoundSamples; // data->playWalkSound = false; // } // // if (samplesLeftForWalk > 0) { // // we need to play part of the walking sound // // so add it in // int affectedSamples = std::min(samplesLeftForWalk, BUFFER_LENGTH_SAMPLES); // for (int i = 0; i < affectedSamples; i++) { // inputLeft[i] += *sampleWalkPointer; // inputLeft[i] = std::max(inputLeft[i], std::numeric_limits<int16_t>::min()); // inputLeft[i] = std::min(inputLeft[i], std::numeric_limits<int16_t>::max()); // // sampleWalkPointer++; // samplesLeftForWalk--; // // if (sampleWalkPointer - walkingSoundArray > walkingSoundSamples) { // sampleWalkPointer = walkingSoundArray; // }; // } // } // // copy the audio data to the last BUFFER_LENGTH_BYTES bytes of the data packet memcpy(currentPacketPtr, inputLeft, BUFFER_LENGTH_BYTES); data->audioSocket->send((sockaddr *)&audioMixerSocket, dataPacket, BUFFER_LENGTH_BYTES + leadingBytes); } } int16_t *outputLeft = ((int16_t **) outputBuffer)[0]; int16_t *outputRight = ((int16_t **) outputBuffer)[1]; memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL); AudioRingBuffer *ringBuffer = data->ringBuffer; // if we've been reset, and there isn't any new packets yet // just play some silence if (ringBuffer->getEndOfLastWrite() != NULL) { if (!ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() < PACKET_LENGTH_SAMPLES + JITTER_BUFFER_SAMPLES) { //printf("Held back, buffer has %d of %d samples required.\n", ringBuffer->diffLastWriteNextOutput(), PACKET_LENGTH_SAMPLES + JITTER_BUFFER_SAMPLES); } else if (ringBuffer->diffLastWriteNextOutput() < PACKET_LENGTH_SAMPLES) { ringBuffer->setStarted(false); starve_counter++; packetsReceivedThisPlayback = 0; //printf("Starved #%d\n", starve_counter); data->wasStarved = 10; // Frames to render the indication that the system was starved. } else { if (!ringBuffer->isStarted()) { ringBuffer->setStarted(true); printf("starting playback %3.1f msecs delayed \n", (usecTimestampNow() - usecTimestamp(&firstPlaybackTimer))/1000.0); } else { //printf("pushing buffer\n"); } // play whatever we have in the audio buffer // if we haven't fired off the flange effect, check if we should int lastYawMeasured = fabsf(data->linkedHead->getLastMeasuredYaw()); if (!samplesLeftForFlange && lastYawMeasured > MIN_FLANGE_EFFECT_THRESHOLD) { // we should flange for one second if ((lastYawMeasuredMaximum = std::max(lastYawMeasuredMaximum, lastYawMeasured)) != lastYawMeasured) { lastYawMeasuredMaximum = std::min(lastYawMeasuredMaximum, MIN_FLANGE_EFFECT_THRESHOLD); samplesLeftForFlange = SAMPLE_RATE; flangeIntensity = MIN_FLANGE_INTENSITY + ((lastYawMeasuredMaximum - MIN_FLANGE_EFFECT_THRESHOLD) / (float)(MAX_FLANGE_EFFECT_THRESHOLD - MIN_FLANGE_EFFECT_THRESHOLD)) * (1 - MIN_FLANGE_INTENSITY); flangeRate = FLANGE_BASE_RATE * flangeIntensity; flangeWeight = MAX_FLANGE_SAMPLE_WEIGHT * flangeIntensity; } } // check if we have more than we need to play out // int thresholdFrames = ceilf((PACKET_LENGTH_SAMPLES + JITTER_BUFFER_SAMPLES) / (float)PACKET_LENGTH_SAMPLES); // int thresholdSamples = thresholdFrames * PACKET_LENGTH_SAMPLES; // // if (ringBuffer->diffLastWriteNextOutput() > thresholdSamples) { // // we need to push the next output forwards // int samplesToPush = ringBuffer->diffLastWriteNextOutput() - thresholdSamples; // // if (ringBuffer->getNextOutput() + samplesToPush > ringBuffer->getBuffer()) { // ringBuffer->setNextOutput(ringBuffer->getBuffer() + (samplesToPush - (ringBuffer->getBuffer() + RING_BUFFER_SAMPLES - ringBuffer->getNextOutput()))); // } else { // ringBuffer->setNextOutput(ringBuffer->getNextOutput() + samplesToPush); // } // } for (int s = 0; s < PACKET_LENGTH_SAMPLES_PER_CHANNEL; s++) { int leftSample = ringBuffer->getNextOutput()[s]; int rightSample = ringBuffer->getNextOutput()[s + PACKET_LENGTH_SAMPLES_PER_CHANNEL]; if (samplesLeftForFlange > 0) { float exponent = (SAMPLE_RATE - samplesLeftForFlange - (SAMPLE_RATE / flangeRate)) / (SAMPLE_RATE / flangeRate); int sampleFlangeDelay = (SAMPLE_RATE / (1000 * flangeIntensity)) * powf(2, exponent); if (samplesLeftForFlange != SAMPLE_RATE || s >= (SAMPLE_RATE / 2000)) { // we have a delayed sample to add to this sample int16_t *flangeFrame = ringBuffer->getNextOutput(); int flangeIndex = s - sampleFlangeDelay; if (flangeIndex < 0) { // we need to grab the flange sample from earlier in the buffer flangeFrame = ringBuffer->getNextOutput() != ringBuffer->getBuffer() ? ringBuffer->getNextOutput() - PACKET_LENGTH_SAMPLES : ringBuffer->getNextOutput() + RING_BUFFER_SAMPLES - PACKET_LENGTH_SAMPLES; flangeIndex = PACKET_LENGTH_SAMPLES_PER_CHANNEL + (s - sampleFlangeDelay); } int16_t leftFlangeSample = flangeFrame[flangeIndex]; int16_t rightFlangeSample = flangeFrame[flangeIndex + PACKET_LENGTH_SAMPLES_PER_CHANNEL]; leftSample = (1 - flangeWeight) * leftSample + (flangeWeight * leftFlangeSample); rightSample = (1 - flangeWeight) * rightSample + (flangeWeight * rightFlangeSample); samplesLeftForFlange--; if (samplesLeftForFlange == 0) { lastYawMeasuredMaximum = 0; } } } outputLeft[s] = leftSample; outputRight[s] = rightSample; } ringBuffer->setNextOutput(ringBuffer->getNextOutput() + PACKET_LENGTH_SAMPLES); if (ringBuffer->getNextOutput() == ringBuffer->getBuffer() + RING_BUFFER_SAMPLES) { ringBuffer->setNextOutput(ringBuffer->getBuffer()); } } } gettimeofday(&data->lastCallback, NULL); return paContinue; }
void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& point, float width, DocumentMarkerLineStyle style) { if (paintingDisabled()) return; if (style != DocumentMarkerSpellingLineStyle && style != DocumentMarkerGrammarLineStyle) return; // These are the same for misspelling or bad grammar const int patternHeight = 3; // 3 rows ASSERT(cMisspellingLineThickness == patternHeight); const int patternWidth = 4; // 4 pixels ASSERT(patternWidth == cMisspellingLinePatternWidth); // Make sure to draw only complete dots. // NOTE: Code here used to shift the underline to the left and increase the width // to make sure everything gets underlined, but that results in drawing out of // bounds (e.g. when at the edge of a view) and could make it appear that the // space between adjacent misspelled words was underlined. // allow slightly more considering that the pattern ends with a transparent pixel float widthMod = fmodf(width, patternWidth); if (patternWidth - widthMod > cMisspellingLinePatternGapWidth) width -= widthMod; // Draw the underline CGContextRef context = platformContext(); CGContextSaveGState(context); const Color& patternColor = style == DocumentMarkerGrammarLineStyle ? grammarPatternColor() : spellingPatternColor(); setCGStrokeColor(context, patternColor); wkSetPatternPhaseInUserSpace(context, point); CGContextSetBlendMode(context, kCGBlendModeNormal); // 3 rows, each offset by half a pixel for blending purposes const CGPoint upperPoints [] = {{point.x(), point.y() + patternHeight - 2.5 }, {point.x() + width, point.y() + patternHeight - 2.5}}; const CGPoint middlePoints [] = {{point.x(), point.y() + patternHeight - 1.5 }, {point.x() + width, point.y() + patternHeight - 1.5}}; const CGPoint lowerPoints [] = {{point.x(), point.y() + patternHeight - 0.5 }, {point.x() + width, point.y() + patternHeight - 0.5 }}; // Dash lengths for the top and bottom of the error underline are the same. // These are magic. static const float edge_dash_lengths[] = {2.0f, 2.0f}; static const float middle_dash_lengths[] = {2.76f, 1.24f}; static const float edge_offset = -(edge_dash_lengths[1] - 1.0f) / 2.0f; static const float middle_offset = -(middle_dash_lengths[1] - 1.0f) / 2.0f; // Line opacities. Once again, these are magic. const float upperOpacity = 0.33f; const float middleOpacity = 0.75f; const float lowerOpacity = 0.88f; //Top line CGContextSetLineDash(context, edge_offset, edge_dash_lengths, WTF_ARRAY_LENGTH(edge_dash_lengths)); CGContextSetAlpha(context, upperOpacity); CGContextStrokeLineSegments(context, upperPoints, 2); // Middle line CGContextSetLineDash(context, middle_offset, middle_dash_lengths, WTF_ARRAY_LENGTH(middle_dash_lengths)); CGContextSetAlpha(context, middleOpacity); CGContextStrokeLineSegments(context, middlePoints, 2); // Bottom line CGContextSetLineDash(context, edge_offset, edge_dash_lengths, WTF_ARRAY_LENGTH(edge_dash_lengths)); CGContextSetAlpha(context, lowerOpacity); CGContextStrokeLineSegments(context, lowerPoints, 2); CGContextRestoreGState(context); }
static inline bool glyphOrientationIsMultiplyOf180Degrees(float orientationAngle) { return !fabsf(fmodf(orientationAngle, 180)); }
void Guy::Update(float time, float seconds) { // if (Input::GetKey(KeyCode_T)) //d += seconds; //if (Input::GetKey(KeyCode_G)) // d -= seconds; // d = MathUtils::Clamp(d, 0.0f, 1.0f); if (m_meshRibbon != NULL) { float d = 0; if (m_meshRibbon->m_ribbon != NULL && m_meshRibbon->m_ribbon->m_ribbonWeightCurve != NULL) d = m_meshRibbon->m_ribbon->m_ribbonWeightCurve->Evaluate(time); d = MathUtils::Clamp(d, 0.0f, 1.0f); shader->UseProgram(); shader->SetParameter("u_ribbonWeight", d); m_meshRibbon->Update(time, seconds); } if (time < m_positionCurve->GetStartTime() || time > m_positionCurve->GetEndTime()) { for (uint32_t i = 0; i < m_renderables.size(); i++) m_renderables[i]->SetActive(false); } else { for (uint32_t i = 0; i < m_renderables.size(); i++) m_renderables[i]->SetActive(true); } sm::Vec3 position = m_positionCurve->Evaluate(time); sm::Vec3 nextPosition = m_positionCurve->Evaluate(time + 0.05f); sm::Vec3 direction(0, 0, 1); if (position != nextPosition) direction = (nextPosition - position).GetNormalized(); sm::Matrix baseTransform = sm::Matrix::TranslateMatrix(position) * sm::Matrix::CreateLookAt(direction.GetReversed(), sm::Vec3(0, 1, 0)) * sm::Matrix::ScaleMatrix(0.02f, 0.02f, 0.02f); //sm::Matrix baseTransform = sm::Matrix::Identity; int animationIndex = 0; float animLength = m_animations[animationIndex]->GetAnimLength(); //m_animations[animationIndex]->Update(time, m_mesh->m_meshData->m_worldMatrix, seconds); m_animations[animationIndex]->Update(fmodf(time * 1.0f, animLength), baseTransform, seconds); //m_animations[animationIndex]->Update(animLength * 0.8f, baseTransform, seconds); //DrawSegment2(m_animations[0]); /*for (uint32_t i = 0; i < m_renderables.size(); i++) m_renderables[i]->SetActive(false);*/ }
static gboolean _lib_filmstrip_expose_callback(GtkWidget *widget, GdkEventExpose *event, gpointer user_data) { dt_lib_module_t *self = (dt_lib_module_t *)user_data; dt_lib_filmstrip_t *strip = (dt_lib_filmstrip_t *)self->data; GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); int32_t width = allocation.width; int32_t height = allocation.height; gdouble pointerx = strip->pointerx; gdouble pointery = strip->pointery; if(darktable.gui->center_tooltip == 1) darktable.gui->center_tooltip++; strip->image_over = DT_VIEW_DESERT; DT_CTL_SET_GLOBAL(lib_image_mouse_over_id, -1); /* create cairo surface */ cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); /* fill background */ cairo_set_source_rgb (cr, .2, .2, .2); cairo_paint(cr); int offset = strip->offset; const float wd = height; const float ht = height; int max_cols = (int)(width/(float)wd) + 2; if (max_cols%2 == 0) max_cols += 1; const int col_start = max_cols/2 - strip->offset; const int empty_edge = (width - (max_cols * wd))/2; int step_res = SQLITE_ROW; sqlite3_stmt *stmt = NULL; /* mouse over image position in filmstrip */ pointerx -= empty_edge; const int seli = (pointery > 0 && pointery <= ht) ? pointerx / (float)wd : -1; const int img_pointerx = (int)fmodf(pointerx, wd); const int img_pointery = (int)pointery; /* get the count of current collection */ strip->collection_count = dt_collection_get_count (darktable.collection); /* get the collection query */ const gchar *query=dt_collection_get_query (darktable.collection); if(!query) return FALSE; if(offset < 0) strip->offset = offset = 0; if(offset > strip->collection_count-1) strip->offset = offset = strip->collection_count-1; // dt_view_set_scrollbar(self, offset, count, max_cols, 0, 1, 1); DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), query, -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, offset - max_cols/2); DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, max_cols); cairo_save(cr); cairo_translate(cr, empty_edge, 0.0f); for(int col = 0; col < max_cols; col++) { if(col < col_start) { cairo_translate(cr, wd, 0.0f); continue; } if(step_res != SQLITE_DONE) { step_res = sqlite3_step(stmt); } if(step_res == SQLITE_ROW) { int id = sqlite3_column_int(stmt, 0); // set mouse over id if(seli == col) { strip->mouse_over_id = id; DT_CTL_SET_GLOBAL(lib_image_mouse_over_id, strip->mouse_over_id); } cairo_save(cr); // FIXME find out where the y translation is done, how big the value is and use it directly instead of getting it from the matrix ... cairo_matrix_t m; cairo_get_matrix(cr, &m); dt_view_image_expose(&(strip->image_over), id, cr, wd, ht, max_cols, img_pointerx, img_pointery, FALSE); cairo_restore(cr); } else if (step_res == SQLITE_DONE) { /* do nothing, just add some empty thumb frames */ } else goto failure; cairo_translate(cr, wd, 0.0f); } failure: cairo_restore(cr); sqlite3_finalize(stmt); if(darktable.gui->center_tooltip == 1) // set in this round { char* tooltip = dt_history_get_items_as_string(strip->mouse_over_id); if(tooltip != NULL) { g_object_set(G_OBJECT(strip->filmstrip), "tooltip-text", tooltip, (char *)NULL); g_free(tooltip); } } else if(darktable.gui->center_tooltip == 2) // not set in this round { darktable.gui->center_tooltip = 0; g_object_set(G_OBJECT(strip->filmstrip), "tooltip-text", "", (char *)NULL); } #ifdef _DEBUG if(darktable.unmuted & DT_DEBUG_CACHE) dt_mipmap_cache_print(darktable.mipmap_cache); #endif /* cleanup */ cairo_destroy(cr); return TRUE; }
char CInputManager::HandleKeyboard(float dtime) { DWORD oldTime = 0; DWORD tickDelta; // update counts and time oldTime = m_fTime; DWORD newCount = GetTickCount(); tickDelta = newCount - m_fOldCount; // if none of the keys are pressed if (!m_pInputModule->KBIsAnyKeyPressed()) { // clear the key states and return ClearAllKeyStates(); m_fOldCount = (newCount-1); return 0; } int i; char cLastASCII = 0; // figure out if shift is pressed bool bShift = (m_pInputModule->KBIsKeyPressed(EEK_RSHIFT)!=0)|| (m_pInputModule->KBIsKeyPressed(EEK_LSHIFT)!=0); // load key table const SEEKey *pTable = m_pInputModule->GetKeyTable(); // go through all the keys for (i = 0; i < MAX_NUM_KEYS;i++) { // check if key is pressed bool state = (m_pInputModule->KBIsKeyPressed(i)!=0); // check modifiers and escape if (i==EEK_RSHIFT || i==EEK_LSHIFT || i==EEK_LCTRL || i==EEK_RCTRL || i==EEK_LALT || i==EEK_ALTGR || i==EEK_ESC) { m_bPressed[i]=state; continue; } // if a key is pressed if (state) { // make sure the repeat delay time as passed // if it has see the key pressed to be true m_bPressed[i] = (m_fPressedTime[i] == -KEYREPEAT_DELAYTIME); // add time change to time array m_fPressedTime[i] += tickDelta; if (m_fPressedTime[i] >= KEYREPEAT_FREQUENCY) { m_fPressedTime[i] = fmodf(m_fPressedTime[i], KEYREPEAT_FREQUENCY); m_bPressed[i] = true; // also display in output //OutputDebugString(_T("PASSED TEST!\n")); } } else { // otherwise make sure the key isn't pressed // in the array m_fPressedTime[i] = -KEYREPEAT_DELAYTIME; m_bPressed[i] = false; } // map virtual key to ASCII if (!cLastASCII && m_bPressed[i]) { const SEEKey *pKey = &pTable[i]; cLastASCII = (bShift) ? pKey->m_chUpper:pKey->m_chLower; } } // send message that a key has been pressed static DWORD msgHash_KeyPress = CHashString(_T("KeyPress")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_KeyPress, (DWORD)(sizeof(char)), &cLastASCII); m_fOldCount = (newCount-1); return cLastASCII; }
//-------------------------------------------------------------- void ofApp::drawEffects(int mode) { switch (mode) { case 0: { // Mouse Circle ofPushStyle(); float hue = fmodf(ofGetElapsedTimef()*10,255); ofColor c = ofColor::fromHsb(hue, 255, 255); ofSetColor(c); ofRect(mouseX,mouseY,50,70); ofPopStyle(); } break; case 1: { // Like the processing example draw dot images and rotate int size = 120; ofPushMatrix(); ofTranslate(0, 0); ofPushMatrix(); ofTranslate(ofGetWidth()/2,ofGetHeight()/2); ofRotateZ(ofGetElapsedTimeMillis()/10); ofPushMatrix(); ofTranslate(-size,-size); ofEnableBlendMode(OF_BLENDMODE_ADD); ofSetColor(0, 255,20); dot.draw(size/4, size/4, size,size); ofSetColor(255, 0,20); dot.draw((size/4*3), size/4, size,size); ofSetColor(0, 0,255); dot.draw(size/4, (size/4*3), size,size); ofSetColor(255, 0,255); dot.draw((size/4*3),(size/4*3), size,size); ofDisableBlendMode(); ofPopMatrix(); ofPopMatrix(); ofPopMatrix(); } break; case 2: { // Changes the color of a Circle ofPushStyle(); float hue = fmodf(ofGetElapsedTimef()*10,255); ofColor c = ofColor::fromHsb(hue, 255, 255); ofSetColor(c); ofRect(ofGetWidth()/2-25,ofGetHeight()/2-35,40,60); ofPopStyle(); } break; case 3: { // Fade to full brightness then to zero ofPushStyle(); ofSetColor((int)(128 + 128 * sin(ofGetElapsedTimef()))); ofRect(ofGetWidth()/2-25,ofGetHeight()/2-35,40,60); ofPopStyle(); } break; case 4: { ofEnableBlendMode(OF_BLENDMODE_ADD); float rotationAmount = ofGetElapsedTimeMillis()/10; ofSetColor(255, 0, 0); ofPushMatrix(); ofTranslate(ofGetWidth()/2, ofGetHeight()/2); ofRotateZ(rotationAmount); ofPushMatrix(); ofTranslate(-ofGetWidth()/2, -ofGetHeight()/2); ofCircle(ofGetWidth()/2, ofGetHeight()/2-10, 20); ofPopMatrix(); ofPopMatrix(); ofSetColor(0, 0, 255); ofPushMatrix(); ofTranslate(ofGetWidth()/2, ofGetHeight()/2); ofRotateZ(-rotationAmount); ofPushMatrix(); ofTranslate(-ofGetWidth()/2, -ofGetHeight()/2); ofCircle(ofGetWidth()/2, ofGetHeight()/2+10, 20); ofPopMatrix(); ofPopMatrix(); ofDisableBlendMode(); } break; case 5: { ofSetColor(255, 255,255); movie.draw(ofGetWidth()/2-30, ofGetHeight()/2-30, 60, 60); } break; case 6: { ofPushStyle(); float hue = fmodf(ofGetElapsedTimef()*10,255); ofColor c = ofColor::fromHsb(hue, 255, 255); ofSetColor(c); dot.draw(mouseX-75, mouseY-75, 150,150); ofPopStyle(); } break; default: break; } }
//-------------------------------------------------------------------------------- OSStatus Stereo::ProcessBufferLists(AudioUnitRenderActionFlags & ioActionFlags, const AudioBufferList & inBuffer, AudioBufferList & outBuffer, UInt32 inFramesToProcess) { // update internal parameters... float dphi = (float) (3.141 * GetParameter(kParam_Rate) / GetSampleRate()); float mod = (float) ((double)GetParameter(kParam_Mod) * 0.001 * GetSampleRate()); long widthMode = (long) GetParameter(kParam_Mode); if (widthMode >= kNumModes) widthMode = kNumModes - 1; else if (widthMode < 0) widthMode = 0; float widthValue = GetParameter(kParam_Width) * 0.01f; float fli, fld, fri, frd; if (widthMode == kMode_Haas) { fli = 1.0f - (widthValue * 0.75f); fld = 0.0f; fri = 1.0f - widthValue; frd = 1.0f - fri; } else { fli = ((1.0f - widthValue) * 0.5f) + 0.5f; fld = widthValue * 0.5f; fri = fli; frd = -fld; } float fdel = (float) ((double)GetParameter(kParam_Delay) * 0.001 * GetSampleRate()); float balanceValue = GetParameter(kParam_Balance) * 0.01f; float balanceScalar = 1.0f - fabsf(balanceValue); if (balanceValue > 0.0f) { fli *= balanceScalar; fld *= balanceScalar; } else { fri *= balanceScalar; frd *= balanceScalar; } float widthValue_modified = (widthValue * 0.5f) + 0.5f; fri *= widthValue_modified; frd *= widthValue_modified; fli *= widthValue_modified; fld *= widthValue_modified; const float * in1 = (float*)(inBuffer.mBuffers[0].mData); float * in2 = NULL; if (inBuffer.mNumberBuffers > 1) in2 = (float*)(inBuffer.mBuffers[1].mData); float * out[kNumOutputs]; for (SInt16 i=0; i < kNumOutputs; i++) out[i] = (float*)(outBuffer.mBuffers[i].mData); if (mod > 0.0f) // modulated delay { for (UInt32 samp=0; samp < inFramesToProcess; samp++) { float a = in1[samp]; // mono input if (in2 != NULL) a = (a + in2[samp]) * 0.5f; // summed stereo input buffer[bufpos] = a; // write long tmp = (bufpos + (long)(fdel + fabsf(mod * sinf(phi)) ) ) % bufsize; float b = buffer[tmp]; out[0][samp] = (a * fli) - (b * fld); // output out[1][samp] = (a * fri) - (b * frd); // buffer position bufpos--; if (bufpos < 0) bufpos = bufsize - 1; phi = phi + dphi; } } else { for (UInt32 samp=0; samp < inFramesToProcess; samp++) { float a = in1[samp]; // mono input if (in2 != NULL) a = (a + in2[samp]) * 0.5f; // summed stereo input buffer[bufpos] = a; // write long tmp = (bufpos + (long)(fdel) ) % bufsize; float b = buffer[tmp]; out[0][samp] = (a * fli) - (b * fld); // output out[1][samp] = (a * fri) - (b * frd); // buffer position bufpos--; if (bufpos < 0) bufpos = bufsize - 1; } } phi = fmodf(phi, 6.2831853f); return noErr; }
int main(void) { e_coreid_t coreid; unsigned int i; unsigned int num; unsigned int time_p; unsigned int time_c; unsigned int time_compare; unsigned int list[14] = {4, 3, 3, 144953, 68892, 24971, 52908, 96970, 19531, 17676, 10459, 10458, 357432, 36235}; unsigned int index = 0; unsigned *mailbox; float volatile af; float volatile bf; float volatile cf; float volatile df; float volatile ref; unsigned int temp; float volatile in_sin; float volatile in_cos; float volatile in_sqt; float volatile in_ceil; float volatile in_log; float re_f0, re_f1, re_f2, re_f3, re_f4, re_f5; af = 3.5f; bf = 2.8f; cf = 8.0f; df = 3.0f; in_sin = (float) pi; in_sin = in_sin / 6 ; in_cos = (float) pi; in_cos = in_cos / 3 ; in_sqt = 0.25f; in_ceil = 2.5f; in_log = 100.0f; mailbox = (unsigned *)0x6000; mailbox[0] = 0; // Who am I? Query the CoreID from hardware. coreid = e_get_coreid(); sprintf(outbuf, ""); // Get time waste on functions e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; time_p = e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); time_compare = time_p - time_c ; // Addition // E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); ref = bf + af ; time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if (!((ref > 6.299f)&&(ref < 6.301f)) ) { sprintf(outbuf, "\n Addition is wrong!\n"); } else { if ( (temp >=(list[0] - 2)) && (temp <=(list[0] + 2)) ) { index++;//sprintf(outbuf , "\nPASS for addition!\n"); } else { sprintf(outbuf , "\nThe clock cycle for addition is %d instead of %d.\n", temp, list[0]); } } // Subtraction // E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); ref = af - bf; time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if ( !((ref > 0.699f)&&(ref < 0.701f))) { sprintf(outbuf+strlen(outbuf), "\n Subtraction is wrong!\n"); } else { if ((temp >= (list[1] - 2)) && (temp <= (list[1] + 2)) ) { index++;//sprintf(outbuf +strlen(outbuf) , "\nPASS for substraction!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for subtraction is %d instead of %d.\n", temp, list[1]); } } // Mul //E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); ref = af * bf; time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if (!((ref > 9.799f)&&(ref < 9.801f))) { sprintf(outbuf+strlen(outbuf), "\n Multiplication is wrong!\n"); } else { if ((temp >=(unsigned) (list[2] -2)) && (temp <=(unsigned) (list[2]+2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for multiplication!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for multiplication is %d instead of %d.\n", temp, list[2]); } } // Div //E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); ref = ( af / bf); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if (!((ref > 1.2499f)&&(ref < 1.2501f))) { sprintf(outbuf+strlen(outbuf), "\n Division is wrong!\n"); } else { if ( (temp > (unsigned) (list[3] * 0.8)) && (temp < (unsigned) (list[3] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for division!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for division is %d instead of %d.\n", temp, list[3]); } } // Mod // E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); ref = fmodf(cf,df); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if (!((ref > 1.99f)&&(ref < 2.01f))) { sprintf(outbuf+strlen(outbuf), "\n Mod is wrong!\n"); } else { if ( (temp > (unsigned)(list[4] * 0.8)) && (temp < (unsigned)(list[4] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for mod!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for mod is %d instead of %d.\n", temp, list[4]); } } // Sin // E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); re_f0 = sinf(in_sin); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if ( !((re_f0 > 0.499) && (re_f0 < 0.501)) ) { sprintf(outbuf+strlen(outbuf), "\n Sin is wrong!\n"); } else { if ( (temp > (unsigned)(list[5] * 0.8)) && (temp < (unsigned)(list[5] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for sin!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for sin is %d instead of %d.\n", temp, list[5]); } } // Cos // E_CTIMER0 e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); re_f1 = cosf(in_cos); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if ( !((re_f1 > 0.499) && (re_f1 < 0.501))) { sprintf(outbuf+strlen(outbuf), "\n Cos is wrong!\n"); } else { if ( (temp > (unsigned)(list[6] * 0.8)) && (temp < (unsigned)(list[6] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for cos!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for cos is %d instead of %d.\n", temp, list[6]); } } // Sqrt e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); re_f2 = sqrtf(in_sqt); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if ( !((re_f2 > 0.499) && (re_f2 < 0.501)) ) { sprintf(outbuf+strlen(outbuf), "\n Sqrt is wrong!\n"); } else { if ( (temp > (list[7] * 0.8)) && (temp < (list[7] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for square root!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for sqrt is %d instead of %d.\n", temp, list[7]); } } // Ceil e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); re_f3 = ceilf(in_ceil); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if ( !((re_f3 > 2.99) && (re_f3 < 3.01)) ) { sprintf(outbuf+strlen(outbuf), "\n Ceil is wrong!\n"); } else { if ( (temp > (list[8] * 0.8)) && (temp < (list[8] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for ceil!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for ceil is %d instead of %d.\n", temp, list[8]); } } // Floor e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); re_f5 = floorf(in_ceil); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if ( !((re_f5 > 1.99f) && (re_f5 < 2.01f)) ) { sprintf(outbuf+strlen(outbuf), "\n Floor is wrong!\n"); } else { if ( (temp > (list[9] * 0.8)) && (temp < (list[9] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for floor!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for floor is %d instead of %d.\n", temp, list[9]); } } // Log10 e_ctimer_set(E_CTIMER_1, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_1, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_1); re_f4 = log10f(df); time_c = e_ctimer_get(E_CTIMER_1); e_ctimer_stop(E_CTIMER_1); temp = time_p - time_c - time_compare; if ( !((re_f4 > 0.477f) && (re_f4 < 0.478f)) ) { sprintf(outbuf+strlen(outbuf), "\n Log10 is wrong!\n"); } else { if ( (temp > (list[11] * 0.8)) && (temp < (list[11] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for log10!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for log10 is %d instead of %d.\n", temp, list[10]); } } // Ln e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_0); re_f4 = logf(in_log); time_c = e_ctimer_get(E_CTIMER_0); e_ctimer_stop(E_CTIMER_0); temp = time_p - time_c - time_compare; if (!((re_f4 > 4.6f) && (re_f4 < 4.61f)) ) { sprintf(outbuf+strlen(outbuf), "\n Ln is wrong!\n"); } else { if ( (temp > (list[11] * 0.8)) && (temp < (list[11] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for ln!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for ln is %d instead of %d.\n", temp, list[11]); } } // Power e_ctimer_set(E_CTIMER_1, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_1, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_1); re_f4 = powf(cf,df); time_c = e_ctimer_get(E_CTIMER_1); e_ctimer_stop(E_CTIMER_1); temp = time_p - time_c - time_compare; if (!( (re_f4 > 511.99f) && (re_f4 < 512.01f) )) { sprintf(outbuf+strlen(outbuf), "\n Power is wrong!\n"); } else { if ( (temp > (list[12] * 0.8)) && (temp < (list[12] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for power!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for power is %d instead of %d.\n", temp, list[12]); } } // Ldexp e_ctimer_set(E_CTIMER_1, E_CTIMER_MAX) ; e_ctimer_start(E_CTIMER_1, E_CTIMER_CLK); time_p = e_ctimer_get(E_CTIMER_1); re_f4 = ldexpf(cf,df); time_c = e_ctimer_get(E_CTIMER_1); e_ctimer_stop(E_CTIMER_1); temp = time_p - time_c - time_compare; if ( !((re_f4 > 63.99f) && (re_f4 < 64.01f)) ) { sprintf(outbuf+strlen(outbuf), "\n Ldexp is wrong!\n"); } else { if ( (temp > (list[13] * 0.8)) && (temp < (list[13] * 1.2)) ) { index++;//sprintf(outbuf +strlen(outbuf), "\nPASS for ldexp!\n"); } else { sprintf(outbuf +strlen(outbuf), "\nThe clock cycle for ldexp is %d instead of %d.\n", temp, list[13]); } } mailbox[0] = index; return EXIT_SUCCESS; }
void simpleaudio_tone(simpleaudio *sa_out, float tone_freq, size_t nsamples_dur) { unsigned int framesize = simpleaudio_get_framesize(sa_out); void *buf = malloc(nsamples_dur * framesize); assert(buf); if ( tone_freq != 0 ) { float wave_nsamples = simpleaudio_get_rate(sa_out) / tone_freq; size_t i; #define TURNS_TO_RADIANS(t) ( (float)M_PI*2 * (t) ) #define SINE_PHASE_TURNS ( (float)i/wave_nsamples + sa_tone_cphase ) #define SINE_PHASE_RADIANS TURNS_TO_RADIANS(SINE_PHASE_TURNS) switch ( simpleaudio_get_format(sa_out) ) { case SA_SAMPLE_FORMAT_FLOAT: { float *float_buf = buf; if ( sin_table_float ) { for ( i=0; i<nsamples_dur; i++ ) float_buf[i] = sin_lu_float(SINE_PHASE_TURNS); } else { for ( i=0; i<nsamples_dur; i++ ) float_buf[i] = tone_mag * sinf(SINE_PHASE_RADIANS); } } break; case SA_SAMPLE_FORMAT_S16: { short *short_buf = buf; if ( sin_table_short ) { for ( i=0; i<nsamples_dur; i++ ) short_buf[i] = sin_lu_short(SINE_PHASE_TURNS); } else { unsigned short mag_s = 32767.0f * tone_mag + 0.5f; if ( tone_mag > 1.0f ) // clamp to 1.0 to avoid overflow mag_s = 32767; if ( mag_s < 1 ) // "short epsilon" mag_s = 1; for ( i=0; i<nsamples_dur; i++ ) short_buf[i] = lroundf( mag_s * sinf(SINE_PHASE_RADIANS) ); } break; } default: assert(0); break; } sa_tone_cphase = fmodf(sa_tone_cphase + (float)nsamples_dur/wave_nsamples, 1.0); } else { bzero(buf, nsamples_dur * framesize); sa_tone_cphase = 0.0; } assert ( simpleaudio_write(sa_out, buf, nsamples_dur) > 0 ); free(buf); }
virtual void HandleMessage(const CMessage& msg, bool UNUSED(global)) { switch (msg.GetType()) { case MT_Interpolate: { const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg); float rotY = m_RotY.ToFloat(); if (rotY != m_InterpolatedRotY) { float delta = rotY - m_InterpolatedRotY; // Wrap delta to -M_PI..M_PI delta = fmodf(delta + (float)M_PI, 2*(float)M_PI); // range -2PI..2PI if (delta < 0) delta += 2*(float)M_PI; // range 0..2PI delta -= (float)M_PI; // range -M_PI..M_PI // Clamp to max rate float deltaClamped = clamp(delta, -m_RotYSpeed*msgData.deltaSimTime, +m_RotYSpeed*msgData.deltaSimTime); // Calculate new orientation, in a peculiar way in order to make sure the // result gets close to m_orientation (rather than being n*2*M_PI out) m_InterpolatedRotY = rotY + deltaClamped - delta; // update the visual XZ rotation if (m_InWorld) { m_LastInterpolatedRotX = m_InterpolatedRotX; m_LastInterpolatedRotZ = m_InterpolatedRotZ; UpdateXZRotation(); } } if (m_InWorld && m_NeedInitialXZRotation) { // the terrain probably wasn't loaded last time we tried, so update the XZ rotation without interpolation UpdateXZRotation(); m_LastInterpolatedRotX = m_InterpolatedRotX; m_LastInterpolatedRotZ = m_InterpolatedRotZ; } break; } case MT_TurnStart: { m_LastInterpolatedRotX = m_InterpolatedRotX; m_LastInterpolatedRotZ = m_InterpolatedRotZ; if (m_InWorld && (m_LastX != m_X || m_LastZ != m_Z)) UpdateXZRotation(); // Store the positions from the turn before m_PrevX = m_LastX; m_PrevZ = m_LastZ; m_LastX = m_X; m_LastZ = m_Z; break; } } };
void draw_demostuff(NVGcontext *vg, int x, int y, float w, float h) { nvgSave(vg); nvgTranslate(vg, x, y); bndSplitterWidgets(vg, 0, 0, w, h); x = 10; y = 10; bndToolButton(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_DEFAULT, BND_ICONID(6,3),"Default"); y += 25; bndToolButton(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_HOVER, BND_ICONID(6,3),"Hovered"); y += 25; bndToolButton(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_ACTIVE, BND_ICONID(6,3),"Active"); y += 40; bndRadioButton(vg,x,y,80,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_DEFAULT, -1,"Default"); y += 25; bndRadioButton(vg,x,y,80,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_HOVER, -1,"Hovered"); y += 25; bndRadioButton(vg,x,y,80,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_ACTIVE, -1,"Active"); y += 25; bndLabel(vg,x,y,120,BND_WIDGET_HEIGHT,-1,"Label:"); y += BND_WIDGET_HEIGHT; bndChoiceButton(vg,x,y,80,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_DEFAULT, -1, "Default"); y += 25; bndChoiceButton(vg,x,y,80,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_HOVER, -1, "Hovered"); y += 25; bndChoiceButton(vg,x,y,80,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_ACTIVE, -1, "Active"); y += 25; int ry = y; int rx = x; y = 10; x += 130; bndOptionButton(vg,x,y,120,BND_WIDGET_HEIGHT,BND_DEFAULT,"Default"); y += 25; bndOptionButton(vg,x,y,120,BND_WIDGET_HEIGHT,BND_HOVER,"Hovered"); y += 25; bndOptionButton(vg,x,y,120,BND_WIDGET_HEIGHT,BND_ACTIVE,"Active"); y += 40; bndNumberField(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_DOWN,BND_DEFAULT, "Top","100"); y += BND_WIDGET_HEIGHT-2; bndNumberField(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_ALL,BND_DEFAULT, "Center","100"); y += BND_WIDGET_HEIGHT-2; bndNumberField(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_TOP,BND_DEFAULT, "Bottom","100"); int mx = x-30; int my = y-12; int mw = 120; bndMenuBackground(vg,mx,my,mw,120,BND_CORNER_TOP); bndMenuLabel(vg,mx,my,mw,BND_WIDGET_HEIGHT,-1,"Menu Title"); my += BND_WIDGET_HEIGHT-2; bndMenuItem(vg,mx,my,mw,BND_WIDGET_HEIGHT,BND_DEFAULT, BND_ICONID(17,3),"Default"); my += BND_WIDGET_HEIGHT-2; bndMenuItem(vg,mx,my,mw,BND_WIDGET_HEIGHT,BND_HOVER, BND_ICONID(18,3),"Hovered"); my += BND_WIDGET_HEIGHT-2; bndMenuItem(vg,mx,my,mw,BND_WIDGET_HEIGHT,BND_ACTIVE, BND_ICONID(19,3),"Active"); y = 10; x += 130; int ox = x; bndNumberField(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_DEFAULT, "Default","100"); y += 25; bndNumberField(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_HOVER, "Hovered","100"); y += 25; bndNumberField(vg,x,y,120,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_ACTIVE, "Active","100"); y += 40; bndRadioButton(vg,x,y,60,BND_WIDGET_HEIGHT,BND_CORNER_RIGHT,BND_DEFAULT, -1,"One"); x += 60-1; bndRadioButton(vg,x,y,60,BND_WIDGET_HEIGHT,BND_CORNER_ALL,BND_DEFAULT, -1,"Two"); x += 60-1; bndRadioButton(vg,x,y,60,BND_WIDGET_HEIGHT,BND_CORNER_ALL,BND_DEFAULT, -1,"Three"); x += 60-1; bndRadioButton(vg,x,y,60,BND_WIDGET_HEIGHT,BND_CORNER_LEFT,BND_ACTIVE, -1,"Butts"); x = ox; y += 40; float progress_value = fmodf(glfwGetTime()/10.0,1.0); char progress_label[32]; sprintf(progress_label, "%d%%", int(progress_value*100+0.5f)); bndSlider(vg,x,y,240,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_DEFAULT, progress_value,"Default",progress_label); y += 25; bndSlider(vg,x,y,240,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_HOVER, progress_value,"Hovered",progress_label); y += 25; bndSlider(vg,x,y,240,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_ACTIVE, progress_value,"Active",progress_label); int rw = x+240-rx; float s_offset = sinf(glfwGetTime()/2.0)*0.5+0.5; float s_size = cosf(glfwGetTime()/3.11)*0.5+0.5; bndScrollBar(vg,rx,ry,rw,BND_SCROLLBAR_HEIGHT,BND_DEFAULT,s_offset,s_size); ry += 20; bndScrollBar(vg,rx,ry,rw,BND_SCROLLBAR_HEIGHT,BND_HOVER,s_offset,s_size); ry += 20; bndScrollBar(vg,rx,ry,rw,BND_SCROLLBAR_HEIGHT,BND_ACTIVE,s_offset,s_size); const char edit_text[] = "The quick brown fox"; int textlen = strlen(edit_text)+1; int t = int(glfwGetTime()*2); int idx1 = (t/textlen)%textlen; int idx2 = idx1 + (t%(textlen-idx1)); ry += 25; bndTextField(vg,rx,ry,240,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_DEFAULT, -1, edit_text, idx1, idx2); ry += 25; bndTextField(vg,rx,ry,240,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_HOVER, -1, edit_text, idx1, idx2); ry += 25; bndTextField(vg,rx,ry,240,BND_WIDGET_HEIGHT,BND_CORNER_NONE,BND_ACTIVE, -1, edit_text, idx1, idx2); draw_noodles(vg, 20, ry+50); rx += rw + 20; ry = 10; bndScrollBar(vg,rx,ry,BND_SCROLLBAR_WIDTH,240,BND_DEFAULT,s_offset,s_size); rx += 20; bndScrollBar(vg,rx,ry,BND_SCROLLBAR_WIDTH,240,BND_HOVER,s_offset,s_size); rx += 20; bndScrollBar(vg,rx,ry,BND_SCROLLBAR_WIDTH,240,BND_ACTIVE,s_offset,s_size); x = ox; y += 40; bndToolButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_RIGHT, BND_DEFAULT,BND_ICONID(0,10),NULL); x += BND_TOOL_WIDTH-1; bndToolButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(1,10),NULL); x += BND_TOOL_WIDTH-1; bndToolButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(2,10),NULL); x += BND_TOOL_WIDTH-1; bndToolButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(3,10),NULL); x += BND_TOOL_WIDTH-1; bndToolButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(4,10),NULL); x += BND_TOOL_WIDTH-1; bndToolButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_LEFT, BND_DEFAULT,BND_ICONID(5,10),NULL); x += BND_TOOL_WIDTH-1; x += 5; bndRadioButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_RIGHT, BND_DEFAULT,BND_ICONID(0,11),NULL); x += BND_TOOL_WIDTH-1; bndRadioButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(1,11),NULL); x += BND_TOOL_WIDTH-1; bndRadioButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(2,11),NULL); x += BND_TOOL_WIDTH-1; bndRadioButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_DEFAULT,BND_ICONID(3,11),NULL); x += BND_TOOL_WIDTH-1; bndRadioButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_ALL, BND_ACTIVE,BND_ICONID(4,11),NULL); x += BND_TOOL_WIDTH-1; bndRadioButton(vg,x,y,BND_TOOL_WIDTH,BND_WIDGET_HEIGHT,BND_CORNER_LEFT, BND_DEFAULT,BND_ICONID(5,11),NULL); nvgRestore(vg); }
static void waveModifier_do(WaveModifierData *md, Scene *scene, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts) { WaveModifierData *wmd = (WaveModifierData*) md; MVert *mvert = NULL; MDeformVert *dvert; int defgrp_index; float ctime = BKE_curframe(scene); float minfac = (float)(1.0 / exp(wmd->width * wmd->narrow * wmd->width * wmd->narrow)); float lifefac = wmd->height; float (*tex_co)[3] = NULL; const int wmd_axis= wmd->flag & (MOD_WAVE_X|MOD_WAVE_Y); const float falloff= wmd->falloff; float falloff_fac= 1.0f; /* when falloff == 0.0f this stays at 1.0f */ if(wmd->flag & MOD_WAVE_NORM && ob->type == OB_MESH) mvert = dm->getVertArray(dm); if(wmd->objectcenter){ float mat[4][4]; /* get the control object's location in local coordinates */ invert_m4_m4(ob->imat, ob->obmat); mul_m4_m4m4(mat, wmd->objectcenter->obmat, ob->imat); wmd->startx = mat[3][0]; wmd->starty = mat[3][1]; } /* get the index of the deform group */ modifier_get_vgroup(ob, dm, wmd->defgrp_name, &dvert, &defgrp_index); if(wmd->damp == 0) wmd->damp = 10.0f; if(wmd->lifetime != 0.0f) { float x = ctime - wmd->timeoffs; if(x > wmd->lifetime) { lifefac = x - wmd->lifetime; if(lifefac > wmd->damp) lifefac = 0.0; else lifefac = (float)(wmd->height * (1.0f - sqrtf(lifefac / wmd->damp))); } } if(wmd->texture) { tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts, "waveModifier_do tex_co"); wavemod_get_texture_coords(wmd, ob, dm, vertexCos, tex_co, numVerts); } if(lifefac != 0.0f) { /* avoid divide by zero checks within the loop */ float falloff_inv= falloff ? 1.0f / falloff : 1.0f; int i; for(i = 0; i < numVerts; i++) { float *co = vertexCos[i]; float x = co[0] - wmd->startx; float y = co[1] - wmd->starty; float amplit= 0.0f; float def_weight= 1.0f; /* get weights */ if(dvert) { def_weight= defvert_find_weight(&dvert[i], defgrp_index); /* if this vert isn't in the vgroup, don't deform it */ if(def_weight == 0.0f) { continue; } } switch(wmd_axis) { case MOD_WAVE_X|MOD_WAVE_Y: amplit = sqrtf(x*x + y*y); break; case MOD_WAVE_X: amplit = x; break; case MOD_WAVE_Y: amplit = y; break; } /* this way it makes nice circles */ amplit -= (ctime - wmd->timeoffs) * wmd->speed; if(wmd->flag & MOD_WAVE_CYCL) { amplit = (float)fmodf(amplit - wmd->width, 2.0f * wmd->width) + wmd->width; } if(falloff != 0.0f) { float dist = 0.0f; switch(wmd_axis) { case MOD_WAVE_X|MOD_WAVE_Y: dist = sqrtf(x*x + y*y); break; case MOD_WAVE_X: dist = fabsf(x); break; case MOD_WAVE_Y: dist = fabsf(y); break; } falloff_fac = (1.0f - (dist * falloff_inv)); CLAMP(falloff_fac, 0.0f, 1.0f); } /* GAUSSIAN */ if((falloff_fac != 0.0f) && (amplit > -wmd->width) && (amplit < wmd->width)) { amplit = amplit * wmd->narrow; amplit = (float)(1.0f / expf(amplit * amplit) - minfac); /*apply texture*/ if(wmd->texture) { TexResult texres; texres.nor = NULL; get_texture_value(wmd->texture, tex_co[i], &texres); amplit *= texres.tin; } /*apply weight & falloff */ amplit *= def_weight * falloff_fac; if(mvert) { /* move along normals */ if(wmd->flag & MOD_WAVE_NORM_X) { co[0] += (lifefac * amplit) * mvert[i].no[0] / 32767.0f; } if(wmd->flag & MOD_WAVE_NORM_Y) { co[1] += (lifefac * amplit) * mvert[i].no[1] / 32767.0f; } if(wmd->flag & MOD_WAVE_NORM_Z) { co[2] += (lifefac * amplit) * mvert[i].no[2] / 32767.0f; } } else { /* move along local z axis */ co[2] += lifefac * amplit; } } } } if(wmd->texture) MEM_freeN(tex_co); }
void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame) { // If using animation LOD, accumulate time and see if it is time to update if (animationLodBias_ > 0.0f && lodDistance_ > 0.0f) { animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE; if (animationLodTimer_ >= lodDistance_) animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_); else { // No LOD if immediate update forced if (!forceUpdate_) return; } } unsigned numBillboards = billboards_.Size(); unsigned enabledBillboards = 0; const Matrix3x4& worldTransform = node_->GetWorldTransform(); Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY; Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE; // First check number of enabled billboards for (unsigned i = 0; i < numBillboards; ++i) { if (billboards_[i].enabled_) ++enabledBillboards; } sortedBillboards_.Resize(enabledBillboards); unsigned index = 0; // Then set initial sort order and distances for (unsigned i = 0; i < numBillboards; ++i) { Billboard& billboard = billboards_[i]; if (billboard.enabled_) { sortedBillboards_[index++] = &billboard; if (sorted_) billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboardTransform * billboards_[i].position_); } } batches_[0].geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false); bufferDirty_ = false; forceUpdate_ = false; if (!enabledBillboards) return; if (sorted_) Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards); float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true); if (!dest) return; for (unsigned i = 0; i < enabledBillboards; ++i) { Billboard& billboard = *sortedBillboards_[i]; Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_); unsigned color = billboard.color_.ToUInt(); float rotationMatrix[2][2]; rotationMatrix[0][0] = Cos(billboard.rotation_); rotationMatrix[0][1] = Sin(billboard.rotation_); rotationMatrix[1][0] = -rotationMatrix[0][1]; rotationMatrix[1][1] = rotationMatrix[0][0]; dest[0] = billboard.position_.x_; dest[1] = billboard.position_.y_; dest[2] = billboard.position_.z_; ((unsigned&)dest[3]) = color; dest[4] = billboard.uv_.min_.x_; dest[5] = billboard.uv_.min_.y_; dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1]; dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1]; dest[8] = billboard.position_.x_; dest[9] = billboard.position_.y_; dest[10] = billboard.position_.z_; ((unsigned&)dest[11]) = color; dest[12] = billboard.uv_.max_.x_; dest[13] = billboard.uv_.min_.y_; dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1]; dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1]; dest[16] = billboard.position_.x_; dest[17] = billboard.position_.y_; dest[18] = billboard.position_.z_; ((unsigned&)dest[19]) = color; dest[20] = billboard.uv_.max_.x_; dest[21] = billboard.uv_.max_.y_; dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1]; dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1]; dest[24] = billboard.position_.x_; dest[25] = billboard.position_.y_; dest[26] = billboard.position_.z_; ((unsigned&)dest[27]) = color; dest[28] = billboard.uv_.min_.x_; dest[29] = billboard.uv_.max_.y_; dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1]; dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1]; dest += 32; } vertexBuffer_->Unlock(); vertexBuffer_->ClearDataLost(); }
void ScreenEvaluation::Init() { LOG->Trace( "ScreenEvaluation::Init()" ); // debugging // Only fill StageStats with fake info if we're the InitialScreen // (i.e. StageStats not already filled) if( PREFSMAN->m_sTestInitialScreen.Get() == m_sName ) { PROFILEMAN->LoadFirstAvailableProfile(PLAYER_1); PROFILEMAN->LoadFirstAvailableProfile(PLAYER_2); STATSMAN->m_vPlayedStageStats.clear(); STATSMAN->m_vPlayedStageStats.push_back( StageStats() ); StageStats &ss = STATSMAN->m_vPlayedStageStats.back(); GAMESTATE->m_PlayMode.Set( PLAY_MODE_REGULAR ); GAMESTATE->SetCurrentStyle( GAMEMAN->GameAndStringToStyle(GAMEMAN->GetDefaultGame(),"versus"), PLAYER_INVALID ); ss.m_playMode = GAMESTATE->m_PlayMode; ss.m_Stage = Stage_1st; enum_add( ss.m_Stage, rand()%3 ); ss.m_EarnedExtraStage = (EarnedExtraStage)(rand() % NUM_EarnedExtraStage); GAMESTATE->SetMasterPlayerNumber(PLAYER_1); GAMESTATE->m_pCurSong.Set( SONGMAN->GetRandomSong() ); ss.m_vpPlayedSongs.push_back( GAMESTATE->m_pCurSong ); ss.m_vpPossibleSongs.push_back( GAMESTATE->m_pCurSong ); GAMESTATE->m_pCurCourse.Set( SONGMAN->GetRandomCourse() ); GAMESTATE->m_iCurrentStageIndex = 0; FOREACH_ENUM( PlayerNumber, p ) GAMESTATE->m_iPlayerStageTokens[p] = 1; FOREACH_PlayerNumber( p ) { ss.m_player[p].m_pStyle = GAMESTATE->GetCurrentStyle(p); if( RandomInt(2) ) PO_GROUP_ASSIGN_N( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions, ModsLevel_Stage, m_bTransforms, PlayerOptions::TRANSFORM_ECHO, true ); // show "disqualified" SO_GROUP_ASSIGN( GAMESTATE->m_SongOptions, ModsLevel_Stage, m_fMusicRate, 1.1f ); GAMESTATE->JoinPlayer( p ); GAMESTATE->m_pCurSteps[p].Set( GAMESTATE->m_pCurSong->GetAllSteps()[0] ); if( GAMESTATE->m_pCurCourse ) { vector<Trail*> apTrails; GAMESTATE->m_pCurCourse->GetAllTrails( apTrails ); if( apTrails.size() ) GAMESTATE->m_pCurTrail[p].Set( apTrails[0] ); } ss.m_player[p].m_vpPossibleSteps.push_back( GAMESTATE->m_pCurSteps[PLAYER_1] ); ss.m_player[p].m_iStepsPlayed = 1; PO_GROUP_ASSIGN( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions, ModsLevel_Stage, m_fScrollSpeed, 2.0f ); PO_GROUP_CALL( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions, ModsLevel_Stage, ChooseRandomModifiers ); } for( float f = 0; f < 100.0f; f += 1.0f ) { float fP1 = fmodf(f/100*4+.3f,1); ss.m_player[PLAYER_1].SetLifeRecordAt( fP1, f ); ss.m_player[PLAYER_2].SetLifeRecordAt( 1-fP1, f ); } FOREACH_PlayerNumber( p ) { float fSeconds = GAMESTATE->m_pCurSong->GetStepsSeconds(); ss.m_player[p].m_iActualDancePoints = RandomInt( 3 ); ss.m_player[p].m_iPossibleDancePoints = 2; if( RandomInt(2) ) ss.m_player[p].m_iCurCombo = RandomInt(15000); else ss.m_player[p].m_iCurCombo = 0; ss.m_player[p].UpdateComboList( 0, true ); ss.m_player[p].m_iCurCombo += 50; ss.m_player[p].UpdateComboList( 0.10f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 0; ss.m_player[p].UpdateComboList( 0.15f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 1; ss.m_player[p].UpdateComboList( 0.25f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 50; ss.m_player[p].UpdateComboList( 0.35f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 0; ss.m_player[p].UpdateComboList( 0.45f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 1; ss.m_player[p].UpdateComboList( 0.50f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 100; ss.m_player[p].UpdateComboList( 1.00f * fSeconds, false ); if( RandomInt(5) == 0 ) { ss.m_player[p].m_bFailed = true; } ss.m_player[p].m_iTapNoteScores[TNS_W1] = RandomInt( 3 ); ss.m_player[p].m_iTapNoteScores[TNS_W2] = RandomInt( 3 ); ss.m_player[p].m_iTapNoteScores[TNS_W3] = RandomInt( 3 ); ss.m_player[p].m_iPossibleGradePoints = 4*ScoreKeeperNormal::TapNoteScoreToGradePoints(TNS_W1, false); ss.m_player[p].m_fLifeRemainingSeconds = randomf( 90, 580 ); ss.m_player[p].m_iScore = rand() % (900*1000*1000); ss.m_player[p].m_iPersonalHighScoreIndex = (rand() % 3) - 1; ss.m_player[p].m_iMachineHighScoreIndex = (rand() % 3) - 1; ss.m_player[p].m_PeakComboAward = (PeakComboAward)(rand()%NUM_PeakComboAward); ss.m_player[p].m_StageAward = (StageAward)(rand()%NUM_StageAward); FOREACH_ENUM( RadarCategory, rc ) { switch( rc ) { case RadarCategory_Stream: case RadarCategory_Voltage: case RadarCategory_Air: case RadarCategory_Freeze: case RadarCategory_Chaos: ss.m_player[p].m_radarPossible[rc] = randomf( 0, 1 ); ss.m_player[p].m_radarActual[rc] = randomf( 0, ss.m_player[p].m_radarPossible[rc] ); break; case RadarCategory_TapsAndHolds: case RadarCategory_Jumps: case RadarCategory_Holds: case RadarCategory_Mines: case RadarCategory_Hands: case RadarCategory_Rolls: case RadarCategory_Lifts: case RadarCategory_Fakes: ss.m_player[p].m_radarPossible[rc] = 1 + (rand() % 200); ss.m_player[p].m_radarActual[rc] = rand() % (int)(ss.m_player[p].m_radarPossible[rc]); break; default: break; } ; // filled in by ScreenGameplay on start of notes } } }
//---------------------------------------------------------------------------- void BouncingBall::PhysicsTick () { // Update the ball. mBall->DoSimulationStep(mSimTime); mRenderer->Update(mBall->GetMesh()->GetVertexBuffer()); // Get the ball parameters. float period = mBall->GetPeriod(); float tMin = mBall->GetMinActive(); float tMax = mBall->GetMaxActive(); // Translate the ball. const float yMax = 2.5f, zMax = 0.75f; float yTrn, zTrn, ratio, amp; float time = fmodf(mSimTime, 2.0f*period); if (time < tMin) { ratio = time/tMin; yTrn = yMax*ratio; zTrn = zMax*(1.0f - ratio*ratio); } else if (time < tMax) { yTrn = yMax; amp = mBall->GetAmplitude(time); if (amp <= 0.999f) { zTrn = -(1.0f - Mathf::Sqrt(1.0f - amp + amp*amp))/(1.0f - amp); } else { zTrn = -0.5f; } } else if (time < period + tMin) { yTrn = -yMax*(time - period)/tMin; zTrn = zMax*(time - tMax)*(period + tMin - time) / (tMin*(period - tMax)); } else if (time < period + tMax) { yTrn = -yMax; amp = mBall->GetAmplitude(time - period); if (amp <= 0.999f) { zTrn = -(1.0f - Mathf::Sqrt(1.0f - amp + amp*amp))/(1.0f - amp); } else { zTrn = -0.5f; } } else { yTrn = yMax*(time - 2.0f*period)/(period - tMax); zTrn = zMax*(time - (period + tMax))*(2.0f*period + tMin - time) / (tMin*(period - tMax)); } mBallNode->LocalTransform.SetTranslate(APoint(0.0f, yTrn, zTrn)); // Rotate the ball. float angle = Mathf::HALF_PI + 0.5f*yTrn*Mathf::PI/yMax; mBallNode->LocalTransform.SetRotate(HMatrix(AVector::UNIT_Z, angle)); // Update the scene graph. mBallNode->Update(); // Next simulation time. mSimTime += mSimDelta; }
void WidthIterator::advance(int offset, GlyphBuffer* glyphBuffer) { if (offset > m_end) offset = m_end; int currentCharacter = m_currentCharacter; const UChar* cp = m_run.data(currentCharacter); bool rtl = m_run.rtl(); bool hasExtraSpacing = (m_font->letterSpacing() || m_font->wordSpacing() || m_padding) && !m_run.spacingDisabled(); float widthSinceLastRounding = m_runWidthSoFar; m_runWidthSoFar = floorf(m_runWidthSoFar); widthSinceLastRounding -= m_runWidthSoFar; float lastRoundingWidth = m_finalRoundingWidth; FloatRect bounds; const SimpleFontData* primaryFont = m_font->primaryFont(); const SimpleFontData* lastFontData = primaryFont; while (currentCharacter < offset) { UChar32 c = *cp; unsigned clusterLength = 1; if (c >= 0x3041) { if (c <= 0x30FE) { // Deal with Hiragana and Katakana voiced and semi-voiced syllables. // Normalize into composed form, and then look for glyph with base + combined mark. // Check above for character range to minimize performance impact. UChar32 normalized = normalizeVoicingMarks(currentCharacter); if (normalized) { c = normalized; clusterLength = 2; } } else if (U16_IS_SURROGATE(c)) { if (!U16_IS_SURROGATE_LEAD(c)) break; // Do we have a surrogate pair? If so, determine the full Unicode (32 bit) // code point before glyph lookup. // Make sure we have another character and it's a low surrogate. if (currentCharacter + 1 >= m_run.length()) break; UChar low = cp[1]; if (!U16_IS_TRAIL(low)) break; c = U16_GET_SUPPLEMENTARY(c, low); clusterLength = 2; } } const GlyphData& glyphData = m_font->glyphDataForCharacter(c, rtl); Glyph glyph = glyphData.glyph; const SimpleFontData* fontData = glyphData.fontData; ASSERT(fontData); // Now that we have a glyph and font data, get its width. float width; if (c == '\t' && m_run.allowTabs()) { float tabWidth = m_font->tabWidth(*fontData); width = tabWidth - fmodf(m_run.xPos() + m_runWidthSoFar + widthSinceLastRounding, tabWidth); } else { width = fontData->widthForGlyph(glyph); #if ENABLE(SVG) // SVG uses horizontalGlyphStretch(), when textLength is used to stretch/squeeze text. width *= m_run.horizontalGlyphStretch(); #endif // We special case spaces in two ways when applying word rounding. // First, we round spaces to an adjusted width in all fonts. // Second, in fixed-pitch fonts we ensure that all characters that // match the width of the space character have the same width as the space character. if (width == fontData->spaceWidth() && (fontData->pitch() == FixedPitch || glyph == fontData->spaceGlyph()) && m_run.applyWordRounding()) width = fontData->adjustedSpaceWidth(); } if (fontData != lastFontData && width) { lastFontData = fontData; if (m_fallbackFonts && fontData != primaryFont) { // FIXME: This does a little extra work that could be avoided if // glyphDataForCharacter() returned whether it chose to use a small caps font. if (!m_font->isSmallCaps() || c == toUpper(c)) m_fallbackFonts->add(fontData); else { const GlyphData& uppercaseGlyphData = m_font->glyphDataForCharacter(toUpper(c), rtl); if (uppercaseGlyphData.fontData != primaryFont) m_fallbackFonts->add(uppercaseGlyphData.fontData); } } } if (hasExtraSpacing) { // Account for letter-spacing. if (width && m_font->letterSpacing()) width += m_font->letterSpacing(); if (Font::treatAsSpace(c)) { // Account for padding. WebCore uses space padding to justify text. // We distribute the specified padding over the available spaces in the run. if (m_padding) { // Use left over padding if not evenly divisible by number of spaces. if (m_padding < m_padPerSpace) { width += m_padding; m_padding = 0; } else { float previousPadding = m_padding; m_padding -= m_padPerSpace; width += roundf(previousPadding) - roundf(m_padding); } } // Account for word spacing. // We apply additional space between "words" by adding width to the space character. if (currentCharacter != 0 && !Font::treatAsSpace(cp[-1]) && m_font->wordSpacing()) width += m_font->wordSpacing(); } } if (m_accountForGlyphBounds) { bounds = fontData->boundsForGlyph(glyph); if (!currentCharacter) m_firstGlyphOverflow = max<float>(0, -bounds.x()); } if (m_forTextEmphasis && !Font::canReceiveTextEmphasis(c)) glyph = 0; // Advance past the character we just dealt with. cp += clusterLength; currentCharacter += clusterLength; // Account for float/integer impedance mismatch between CG and KHTML. "Words" (characters // followed by a character defined by isRoundingHackCharacter()) are always an integer width. // We adjust the width of the last character of a "word" to ensure an integer width. // If we move KHTML to floats we can remove this (and related) hacks. float oldWidth = width; // Force characters that are used to determine word boundaries for the rounding hack // to be integer width, so following words will start on an integer boundary. if (m_run.applyWordRounding() && Font::isRoundingHackCharacter(c)) { width = ceilf(width); // Since widthSinceLastRounding can lose precision if we include measurements for // preceding whitespace, we bypass it here. m_runWidthSoFar += width; // Since this is a rounding hack character, we should have reset this sum on the previous // iteration. ASSERT(!widthSinceLastRounding); } else { // Check to see if the next character is a "rounding hack character", if so, adjust // width so that the total run width will be on an integer boundary. if ((m_run.applyWordRounding() && currentCharacter < m_run.length() && Font::isRoundingHackCharacter(*cp)) || (m_run.applyRunRounding() && currentCharacter >= m_end)) { float totalWidth = widthSinceLastRounding + width; widthSinceLastRounding = ceilf(totalWidth); width += widthSinceLastRounding - totalWidth; m_runWidthSoFar += widthSinceLastRounding; widthSinceLastRounding = 0; } else widthSinceLastRounding += width; } if (glyphBuffer) glyphBuffer->add(glyph, fontData, (rtl ? oldWidth + lastRoundingWidth : width)); lastRoundingWidth = width - oldWidth; if (m_accountForGlyphBounds) { m_maxGlyphBoundingBoxY = max(m_maxGlyphBoundingBoxY, bounds.bottom()); m_minGlyphBoundingBoxY = min(m_minGlyphBoundingBoxY, bounds.y()); m_lastGlyphOverflow = max<float>(0, bounds.right() - width); } } m_currentCharacter = currentCharacter; m_runWidthSoFar += widthSinceLastRounding; m_finalRoundingWidth = lastRoundingWidth; }
void PhaserEffect::processChannel(const ChannelHandle& handle, PhaserGroupState* pState, const CSAMPLE* pInput, CSAMPLE* pOutput, const mixxx::EngineParameters& bufferParameters, const EffectEnableState enableState, const GroupFeatureState& groupFeatures, const EffectChainMixMode mixMode) { Q_UNUSED(handle); Q_UNUSED(mixMode); if (enableState == EffectEnableState::Enabling) { pState->clear(); } CSAMPLE depth = 0; if (enableState != EffectEnableState::Disabling) { depth = m_pDepthParameter->value(); } double periodParameter = m_pLFOPeriodParameter->value(); double periodSamples; if (groupFeatures.has_beat_length_sec) { // periodParameter is a number of beats periodParameter = std::max(roundToFraction(periodParameter, 2.0), 1/4.0); if (m_pTripletParameter->toBool()) { periodParameter /= 3.0; } periodSamples = periodParameter * groupFeatures.beat_length_sec * bufferParameters.sampleRate(); } else { // periodParameter is a number of seconds periodSamples = std::max(periodParameter, 1/4.0) * bufferParameters.sampleRate(); } // freqSkip is used to calculate the phase independently for each channel, // so do not multiply periodSamples by the number of channels. CSAMPLE freqSkip = 1.0 / periodSamples * 2.0 * M_PI; CSAMPLE feedback = m_pFeedbackParameter->value(); CSAMPLE range = m_pRangeParameter->value(); int stages = 2 * m_pStagesParameter->value(); CSAMPLE* oldInLeft = pState->oldInLeft; CSAMPLE* oldOutLeft = pState->oldOutLeft; CSAMPLE* oldInRight = pState->oldInRight; CSAMPLE* oldOutRight = pState->oldOutRight; // Using two sets of coefficients for left and right channel CSAMPLE filterCoefLeft = 0; CSAMPLE filterCoefRight = 0; CSAMPLE left = 0, right = 0; CSAMPLE_GAIN oldDepth = pState->oldDepth; const CSAMPLE_GAIN depthDelta = (depth - oldDepth) / bufferParameters.framesPerBuffer(); const CSAMPLE_GAIN depthStart = oldDepth + depthDelta; int stereoCheck = m_pStereoParameter->value(); int counter = 0; for (unsigned int i = 0; i < bufferParameters.samplesPerBuffer(); i += bufferParameters.channelCount()) { left = pInput[i] + tanh(left * feedback); right = pInput[i + 1] + tanh(right * feedback); // For stereo enabled, the channels are out of phase pState->leftPhase = fmodf(pState->leftPhase + freqSkip, 2.0 * M_PI); pState->rightPhase = fmodf(pState->rightPhase + freqSkip + M_PI * stereoCheck, 2.0 * M_PI); // Updating filter coefficients once every 'updateCoef' samples to avoid // extra computing if ((counter++) % updateCoef == 0) { CSAMPLE delayLeft = 0.5 + 0.5 * sin(pState->leftPhase); CSAMPLE delayRight = 0.5 + 0.5 * sin(pState->rightPhase); // Coefficient computing based on the following: // https://ccrma.stanford.edu/~jos/pasp/Classic_Virtual_Analog_Phase.html CSAMPLE wLeft = range * delayLeft; CSAMPLE wRight = range * delayRight; CSAMPLE tanwLeft = tanh(wLeft / 2); CSAMPLE tanwRight = tanh(wRight / 2); filterCoefLeft = (1.0 - tanwLeft) / (1.0 + tanwLeft); filterCoefRight = (1.0 - tanwRight) / (1.0 + tanwRight); } left = processSample(left, oldInLeft, oldOutLeft, filterCoefLeft, stages); right = processSample(right, oldInRight, oldOutRight, filterCoefRight, stages); const CSAMPLE_GAIN depth = depthStart + depthDelta * (i / bufferParameters.channelCount()); // Computing output combining the original and processed sample pOutput[i] = pInput[i] * (1.0 - 0.5 * depth) + left * depth * 0.5; pOutput[i + 1] = pInput[i + 1] * (1.0 - 0.5 * depth) + right * depth * 0.5; } pState->oldDepth = depth; }