void ItemColorChannel::process_action(const MenuAction& action) { switch (action) { case MenuAction::REMOVE: remove_char(); break; case MenuAction::LEFT: *m_number = truncf(*m_number * 10.0f) / 10.0f; *m_number -= 0.1f; *m_number = math::clamp(*m_number, 0.0f, 1.0f); set_text(float_to_string(*m_number)); break; case MenuAction::RIGHT: *m_number = truncf(*m_number * 10.0f) / 10.0f; *m_number += 0.1f; *m_number = math::clamp(*m_number, 0.0f, 1.0f); set_text(float_to_string(*m_number)); break; default: break; } }
void MessageInteger::processMessage(int inletIndex, PdMessage *message) { switch (inletIndex) { case 0: { switch (message->getType(0)) { case FLOAT: { constant = truncf(message->getFloat(0)); // allow fallthrough } case BANG: { PdMessage *outgoingMessage = PD_MESSAGE_ON_STACK(1); outgoingMessage->initWithTimestampAndFloat(message->getTimestamp(), constant); sendMessage(0, outgoingMessage); break; } default: { break; } } break; } case 1: { if (message->isFloat(0)) { constant = truncf(message->getFloat(0)); } break; } default: { break; } } }
void BackgroundImageGeometry::setRepeatY(const FillLayer& fillLayer, LayoutUnit unsnappedTileHeight, LayoutUnit snappedAvailableHeight, LayoutUnit unsnappedAvailableHeight, LayoutUnit extraOffset) { // We would like to identify the phase as a fraction of the image size in the // absence of snapping, then re-apply it to the snapped values. This is to // handle large positions. if (unsnappedTileHeight) { LayoutUnit computedYPosition = roundedMinimumValueForLength( fillLayer.yPosition(), unsnappedAvailableHeight); if (fillLayer.backgroundYOrigin() == BottomEdge) { float numberOfTilesInPosition = (snappedAvailableHeight - computedYPosition + extraOffset).toFloat() / unsnappedTileHeight.toFloat(); float fractionalPositionWithinTile = numberOfTilesInPosition - truncf(numberOfTilesInPosition); setPhaseY(LayoutUnit( roundf(fractionalPositionWithinTile * tileSize().height()))); } else { float numberOfTilesInPosition = (computedYPosition + extraOffset).toFloat() / unsnappedTileHeight.toFloat(); float fractionalPositionWithinTile = 1.0f - (numberOfTilesInPosition - truncf(numberOfTilesInPosition)); setPhaseY(LayoutUnit( roundf(fractionalPositionWithinTile * tileSize().height()))); } } else { setPhaseY(LayoutUnit()); } setSpaceSize(LayoutSize(spaceSize().width(), LayoutUnit())); }
void test_truncf() { float f32__x; f32__x = double_interval(-0.5,1.5); float f32__a = truncf(f32__x); f32__x = double_interval(-0.0,0.5); float f32__b = truncf(f32__x); f32__x = double_interval(-2.5,-0.5); float f32__c = truncf(f32__x); }
int main () { /* See IEEE 754, section 6.3: "the sign of the result of the round floating-point number to integral value operation is the sign of the operand. These rules shall apply even when operands or results are zero or infinite." */ /* Zero. */ ASSERT (!signbit (truncf (0.0f))); ASSERT (!!signbit (truncf (minus_zerof)) == !!signbit (minus_zerof)); /* Positive numbers. */ ASSERT (!signbit (truncf (0.3f))); ASSERT (!signbit (truncf (0.7f))); /* Negative numbers. */ ASSERT (!!signbit (truncf (-0.3f)) == !!signbit (minus_zerof)); ASSERT (!!signbit (truncf (-0.7f)) == !!signbit (minus_zerof)); /* [MX] shaded specification in POSIX. */ /* NaN. */ ASSERT (isnanf (truncf (NaNf ()))); /* Infinity. */ ASSERT (truncf (Infinityf ()) == Infinityf ()); ASSERT (truncf (- Infinityf ()) == - Infinityf ()); return 0; }
color calculate_Id(struct matrix *polygons, screen s, color c, int i){ color Id, Idt; Id.red = 0; Id.green = 0; Id.blue = 0; //Idiffuse = Cp * Kd * (L^ (dot product) N^) int li; color cp; double xdot,ydot,zdot,cos_theta; for(li=0; li<light_index; li++){ cp.red = lights[li][3]; cp.green = lights[li][4]; cp.blue = lights[li][5]; xdot = lights_normalized[li][0]*surface_normal[0]; ydot = lights_normalized[li][1]*surface_normal[1]; zdot = lights_normalized[li][2]*surface_normal[2]; cos_theta = xdot + ydot + zdot; //L_dot_N[li] = cos_theta; Idt.red = truncf(cp.red * kdr * cos_theta); Idt.green = truncf(cp.green * kdg * cos_theta); Idt.blue = truncf(cp.blue * kdb * cos_theta); if(Idt.red<0){ Idt.red = 0; }else if(Idt.red>255){ Idt.red = 255; } if(Idt.green<0){ Idt.green = 0; }else if(Idt.green>255){ Idt.green = 255; } if(Idt.blue<0){ Idt.blue = 0; }else if(Idt.blue>255){ Idt.blue = 255; } Id.red += Idt.red; Id.green += Idt.green; Id.blue += Idt.blue; } if(Id.red>255) Id.red=255; if(Id.green>255) Id.green=255; if(Id.blue>255) Id.blue=255; return Id; }
void SciCalc::cb_but_int_i(Fl_Button*, void*) { if (! inv) { value[top] = truncf(value[top]); set_display(value[top],NORM); ready = 1; } else { value[top] = value[top] - truncf(value[top]); set_display(value[top],NORM); ready = 1; }; }
void IPTVChannelFetcher::SetNumChannelsInserted(uint val) { uint minval = 70, range = 100 - minval; uint pct = minval + (uint) truncf((((float)val) / _chan_cnt) * range); if (_scan_monitor) _scan_monitor->ScanPercentComplete(pct); }
void test_trunc() { static_assert((std::is_same<decltype(trunc((double)0)), double>::value), ""); static_assert((std::is_same<decltype(truncf(0)), float>::value), ""); static_assert((std::is_same<decltype(truncl(0)), long double>::value), ""); assert(trunc(1) == 1); }
void SciCalc::factorial() { double lg, alpha; /* uses gamma functions to get result for non-integer values */ alpha = value[top] + 1.0; if ((floor(alpha) == alpha)&&(alpha <= 0.0)) { init_value(0); leddisplay->label("Error: -ve integer "); leddisplay->redraw(); } else if (alpha > 32) { lg = exp(gammaln(alpha)); value[top] = lg; set_display(value[top],NORM); ready = 1; } else if (alpha > 1.0) { int n = (int)truncf(alpha); lg = 1.0; for (int i = 1; i <n; i++) lg *= i; value[top] = lg; set_display(value[top],NORM); ready = 1; } }
int mfp_block_trunc(mfp_block * in, mfp_block * out) { if (mfp_block_use_sse && mfp_block_compiled_with_sse) { #ifdef MFP_USE_SSE int loc = 0; int end = in->blocksize; __v4sf ftmp; __v4si itmp; for(; loc < end; loc+=4) { ftmp = __builtin_ia32_loadups(in->data+loc); itmp = __builtin_ia32_cvttps2dq(ftmp); ftmp = __builtin_ia32_cvtdq2ps(itmp); __builtin_ia32_storeups(out->data + loc, ftmp); } #endif } else { mfp_sample * inptr = in->data, * optr = out->data; mfp_sample * iend = in->data + in->blocksize; for (; inptr < iend; inptr++) { *optr = truncf(*inptr); optr++; } } return 1; }
void vector_trunc (void) { int i; for (i = 0; i < SIZE; i++) a[i] = truncf (b[i]); }
cons_t* proc_truncate(cons_t* p, environment_t*) { assert_length(p, 1); assert_number(car(p)); if ( integerp(car(p)) ) return integer(car(p)->number.integer); else return real(truncf(car(p)->number.real)); }
void RenderTime(int frameNumber, float beatsPerFrame) { char text[20]; int min = (frameNumber / FRAMERATE) / 60; int sec = (frameNumber / FRAMERATE) % 60; float beat = truncf((float)frameNumber / beatsPerFrame);; PrintToString(text, sizeof(text), "%4ldf %ldm%02lds %ldb", frameNumber, min, sec, (int)beat); RenderText(text, 2, 8); }
void Time::setMilliseconds(float newMilliseconds) { if (fabs(newMilliseconds) > 1) { int secondsInMS = truncf(newMilliseconds); setSeconds((unsigned int) secondsInMS); milliseconds = newMilliseconds - secondsInMS; } else milliseconds = newMilliseconds; }
/*ipWidth = ipGrabber[i]->getWidth(); ipHeight = ipGrabber[i]->getHeight(); if ((ipWidth > 0) && (ipHeight >0) ) { if ((ipWidth != ipImg[i].getWidth()) || (ipHeight != ipImg[i].getHeight())) { if (ipImg[i].bAllocated) ipImg[i].resize(ipWidth, ipHeight); else ipImg[i].allocate(ipWidth, ipHeight); } if ((ipWidth != outW) || (ipHeight != outH)) { ofxCvColorImage tempIpImg; tempIpImg.allocate(ipWidth, ipHeight); tempIpImg.setFromPixels(ipGrabber[i]->getPixels(), ipWidth, ipHeight); ipImg[i].scaleIntoMe(tempIpImg, OF_INTERPOLATE_NEAREST_NEIGHBOR); } else { ipImg[i].setFromPixels(ipGrabber[i]->getPixels(), ipWidth, ipHeight); } }*/ } } ///***************************************************************** /// MONOCHANNEL MONOBLOB ///******************************************************************/ void testApp::monoCmonoB(){ int numBlobs = lastBlobs.size(); if (numBlobs > 0) { if (bZoomTarget) { left = lastBlobs[0].boundingRect.x * in_analysis_scale; top = lastBlobs[0].boundingRect.y * in_analysis_scale; targW = lastBlobs[0].boundingRect.width * in_analysis_scale; targH = lastBlobs[0].boundingRect.height * in_analysis_scale; // adjust to mantain inAspect ratio int targW_inAspect = targH*inAspect; if (targW < targW_inAspect) { left -= (targW_inAspect-targW)/2; targW = targW_inAspect; } else { int targH_inAspect = targW/inAspect; top -= (targH_inAspect-targH)/2; targH = targH_inAspect; } } else { targW = cropW; targH = cropH; top = lastBlobs[0].centroid.y*in_analysis_scale-targH/2; left = lastBlobs[0].centroid.x*in_analysis_scale-targW/2; } // copyRegion needs variables as argumets int out_left = 0; copyRegion( fullFrame, left, top, targW, targH, outputImg, out_left, out_H_gap, outW, out_H_in_aspect); } } ///***************************************************************** /// MONOCHANNEL MULTIBLOB ///******************************************************************/ void testApp::monoCmultiB(){ int numBlobs = lastBlobs.size(); if (numBlobs == 1) monoCmonoB(); else if (numBlobs > 1) { int max_x = 0; int max_y = 0; for (unsigned int i = 0; i < lastBlobs.size(); i++) { left = MIN( left, lastBlobs[i].boundingRect.x) ; top = MIN( top, lastBlobs[i].boundingRect.y) ; max_x = MAX( max_x, lastBlobs[i].boundingRect.x+ lastBlobs[i].boundingRect.width ); max_y = MAX( max_y, lastBlobs[i].boundingRect.y+ lastBlobs[i].boundingRect.height ); } left *= in_analysis_scale; top *= in_analysis_scale; max_x *= in_analysis_scale; max_y *= in_analysis_scale; if (bZoomTarget) { targW = (max_x-left); targH = (max_y-top); // adjust to mantain inAspect ratio int targW_inAspect = targH*inAspect; if (targW < targW_inAspect) { left -= (targW_inAspect-targW)/2; targW = targW_inAspect; } else { int targH_inAspect = targW/inAspect; top -= (targH_inAspect-targH)/2; targH = targH_inAspect; } } else { targW = cropW; targH = cropH; // centroid of all blobs top = (float)(top+max_y)/2; top -= ((float)targH/2); left = (float)(left+max_x)/2; left -= ((float)targW/2); } int out_left = 0; // int out_H = outH; copyRegion( fullFrame, left, top, targW, targH, outputImg, out_left, out_H_gap, outW, out_H_in_aspect); } } ///***************************************************************** /// MULTICHANNEL ///******************************************************************/ void testApp::multiC(){ int numBlobs = lastBlobs.size(); if (numBlobs > 0) { // calculate number of rows & columns needeed float sqroot = sqrtf(numBlobs); float trun = truncf(sqroot); float rnd = roundf(sqroot); if (trun == rnd) rnd +=0.5; else trun += 0.5; int rows = (int)roundf(trun); if (rows <= 0) rows = 1; int cols = (int)roundf(rnd); if (cols <= 0) cols = 1; // calculate channel width and height int channelW = (float)outW/(float)cols; int channelH = channelW/outAspect; int comonGap = (outH-channelH*rows)/2; int channelGap = out_H_gap*((float)channelH/(float)outH); // letterbox black zones height // draw channels to output buffer image for (int i =0; i < numBlobs;i++) { int dx = (i%cols)*channelW; int dy = comonGap+(i/cols)*(channelH+channelGap); targW = cropW; targH = cropH; top = 0; left = 0; if (bZoomTarget) { top = lastBlobs[i].boundingRect.y; left = lastBlobs[i].boundingRect.x; targW = lastBlobs[i].boundingRect.width; targH = lastBlobs[i].boundingRect.height; targW = MAX(targW, targH/inAspect); targH = MAX(targH, targW*inAspect); } else { top = lastBlobs[i].centroid.y; left = lastBlobs[i].centroid.x; } // whithout the (float) casting a segmentation fault occurs top = in_out_scale*(float)top; top -= ((float)targH/2); left = in_out_scale*(float)left; left -= ((float)targW/2); copyRegion( fullFrame, left, top, targW, targH, outputImg, dx, dy, channelW, channelH); } } }
void Attack::GetRealtimeAttackBeats(const Song* pSong, const PlayerState** pPlayerState, float& fStartBeat, float& fEndBeat) const { if (fStartSecond >= 0) { GetAttackBeats(pSong, fStartBeat, fEndBeat); return; } ASSERT(pPlayerState); ASSERT(pSong); fStartBeat = min( GAMESTATE->m_fSongBeat+8, pPlayerState->m_fLastDrawnBeat ); fStartBeat = truncf(fStartBeat) + 1; const float fStartSecond = pSong->GetElapsedTimeFromBeat(fStartBeat); const float fEndSecond = fStartSecond + fSecsRemaining; fEndBeat = pSong->GetBeatFromElapsedTime(fEndSecond); fEndBeat = truncf(fEndBeat) + 1; ASSERT_M(fEndBeat >= fStartBeat, ssprintf("%f >= %f", fEndBeat, fStartBeat)); }
/** ***************************************************************************************************** * \fn void recevoirFichier(int socket,struct addr* p_my_addr,socklen_t * tailleSock,char nomFichier[20]) * \brief reçoit le fichier demandé du serveur et le stocke sur le disque local * * \param socket le descripteur de la socket * \param p_my_addr le pointeur vers la structure d'adresse de la socket * \param tailleSock la taille de la structure d'adresse * \param nomFichier le nom du fichier a récupérer ***************************************************************************************************** */ void recevoirFichier(int socket,struct addr* p_my_addr,socklen_t * tailleSock, char nomFichier[20]){ FILE* fichierDestination=fopen(nomFichier,"a+"); char message[20]; int tailleDonnees=0; int tailleRecue; int testFputs; reinitialiserTab(sizeof(message),message); printf("%s est le nom du fichier \n",nomFichier); if(fichierDestination == NULL){ error(-1,"Erreur ouverture fichier destination \n"); } int testEOF=0;int testWrite=0;int compteurRcv=0,compteurWrt=0;int testSendto=0; float pourcentageRecu=0,pourcentageEcrit=0; printf("Reception en cours... \n"); long tailleFichier=0; tailleRecue=recvfrom(socket,&tailleFichier,sizeof(&tailleFichier),0,(struct sockaddr*)p_my_addr,tailleSock); error(tailleRecue,"erreur recv de la taile fichier \n"); printf("Le fichier pèsera %ld octets \n",tailleFichier); while(pourcentageEcrit<100){ fseek(fichierDestination,1,SEEK_END); tailleRecue=recvfrom(socket,message,sizeof(message),0,(struct sockaddr*)p_my_addr,tailleSock); error(tailleRecue,"erreur recv de l'ASK \n"); testWrite=fwrite(message,sizeof(message),1,fichierDestination); compteurRcv=compteurRcv+tailleRecue; compteurWrt=compteurWrt+sizeof(message)*testWrite; pourcentageRecu=compteurRcv/(float)tailleFichier*100; pourcentageEcrit=compteurWrt/(float)tailleFichier*100; printf("\x0d");//remettre le curseur en début de ligne printf("\033[K");//écrase la ligne printf("Reçu : %d %% Ecrit : %d %% ",(int)truncf(pourcentageRecu),(int)truncf(pourcentageEcrit)); testSendto=sendto(socket,"Ack",sizeof("Ack"),0,(struct sockaddr*)p_my_addr,*tailleSock); error(testSendto,"Erreur émission ack \n"); reinitialiserTab(sizeof(message),message); } printf("\n"); fclose(fichierDestination); printf("Fichier reçu \n"); }
void test_truncf_det() { float f32__a = truncf(1.5); float f32__b = truncf(0.5); float f32__c = truncf(0.0); float f32__d = truncf(-0.0); float f32__e = truncf(-0.5); float f32__f = truncf(-1.5); }
//converting raw measurement from ADC values into a floating data type void conversion(uint8_t *calibrate, float *angle, uint8_t *measurement, uint8_t secondmode) { float components[3]={}; float resultant=0; uint8_t i=0; for (i=0;i<=2;i++) { //Convert measurement and zero's into a component of gravity vector ((measurement-zero)*Vref[5V]/ADC resolution[255])/Sensibility[800mV/g] components[i]=((measurement[i]-calibrate[i])*4/255.0); //Add up the components squared in order to obtain... resultant=resultant + (components[i]*components[i]); } // ...Pythagoras theorem resultant=sqrt(resultant); if (secondmode==1) { //obtain direction cosines of the resultant/truncate the value just to one decimal point. //subtract 90 in order to make it more "readable" //just needing x & y axis to show angle[0]=truncf((acos(components[0]/resultant))*572.9)/10; angle[0]=angle[0]-90; } else { for (i=0;i<=1;i++) { //obtain direction cosines of the resultant/truncate the value just to one decimal point. //subtract 90 in order to make it more "readable" //just needing x & y axis to show angle[i]=truncf((acos(components[i]/resultant))*572.9)/10; angle[i]=angle[i]-90; } } }
TEST(math, truncf) { fesetround(FE_UPWARD); // truncf ignores the rounding mode and always rounds toward zero. ASSERT_FLOAT_EQ(1.0f, truncf(1.5f)); ASSERT_FLOAT_EQ(-1.0f, truncf(-1.5f)); ASSERT_FLOAT_EQ(0.0f, truncf(0.0f)); ASSERT_FLOAT_EQ(-0.0f, truncf(-0.0f)); ASSERT_TRUE(isnan(truncf(nanf("")))); ASSERT_FLOAT_EQ(HUGE_VALF, truncf(HUGE_VALF)); }
float expf(float x) { #else float vexpf(float x) { #endif vector float vexpa, va;//, vx, vn, va, vb, // v0, vlog2, vln2; register float exp, a;//, b, b2, b3, b4;//, b6, b8, b10, R0, R; float __attribute__((aligned(16))) xa[4]; xa[0] = x; /* // set up a few constants vlog2 = vec_ld(0, &C_EXPF[0]); v0 = (vector float) vec_splat_u32(0); vln2 = vec_splat(vlog2, 1); vlog2 = vec_splat(vlog2, 0); // Load x into a vector float vx = vec_ld(0, xa); vx = vec_splat(vx, 0); // Split x = n*log2e + b vn = vec_madd(vx, vlog2e, v0); vn = vec_floor(vn);*/ xa[0] = truncf(x*M_LOG2E); va = vec_ld(0, xa); vexpa = vec_expte(va); a = xa[0] * M_LN2; vec_st(vexpa, 0, xa); /* b = x - a; b2 = b*b; b3 = b2*b; b4 = b2*b2; b6 = b4*b2; b8 = b6*b2; b10 = b8*b2; R0 = 0.1666666666666666019037 *b2 - 0.00277777777770155933842 *b4 + 6.61375632143793436117e-05 *b6 - 1.65339022054652515390e-06 *b8 + 4.13813679705723846039e-08 *b10; R = b - R0; //exp = 1.0 + 2.0*b/(2.0 - R); exp = (1680.0 + 840*b + 180*b2 + 20*b3 + b4)/(1680 - 840*b + 180*b2 - 20*b3 + b4); */ exp = xa[0]; return exp; }
long long llroundf (float x) { /* Add +/- 0.5, then round towards zero. */ float tmp = truncf (x + (x >= 0.0F ? 0.5F : -0.5F)); if (!isfinite (tmp) || tmp > (float)LONG_LONG_MAX || tmp < (float)LONG_LONG_MIN) { errno = ERANGE; /* Undefined behaviour, so we could return anything. */ /* return tmp > 0.0F ? LONG_LONG_MAX : LONG_LONG_MIN; */ } return (long long)tmp; }
/* Get the range for an attack that's being applied in realtime, eg. during battle * mode. We need a PlayerState for this, so we can push the region off-screen to * prevent popping when the attack has note modifers. */ void Attack::GetRealtimeAttackBeats( const Song *pSong, const PlayerState* pPlayerState, float &fStartBeat, float &fEndBeat ) const { if( fStartSecond >= 0 ) { GetAttackBeats( pSong, fStartBeat, fEndBeat ); return; } ASSERT( pPlayerState != NULL ); ASSERT( pSong != NULL ); /* If reasonable, push the attack forward 8 beats so that notes on screen don't change suddenly. */ fStartBeat = min( GAMESTATE->m_Position.m_fSongBeat+8, pPlayerState->m_fLastDrawnBeat ); fStartBeat = truncf(fStartBeat)+1; const TimingData &timing = pSong->m_SongTiming; const float lStartSecond = timing.GetElapsedTimeFromBeat( fStartBeat ); const float fEndSecond = lStartSecond + fSecsRemaining; fEndBeat = timing.GetBeatFromElapsedTime( fEndSecond ); fEndBeat = truncf(fEndBeat)+1; // loading the course should have caught this. ASSERT_M( fEndBeat >= fStartBeat, ssprintf("EndBeat %f >= StartBeat %f", fEndBeat, fStartBeat) ); }
void RelAxisEventHandler::update(int msec_delta) { if (m_repeat == -1 && m_stick_value != 0.0f) { // new and improved REL style event sending float rel_value = m_stick_value * m_value * static_cast<float>(msec_delta) / 1000.0f; // keep track of the rest that we lose when converting to integer rel_value += m_rest_value; m_rest_value = rel_value - truncf(rel_value); m_rel_emitter->send(static_cast<int>(rel_value)); } }
void DVBSignalMonitor::GetRotorStatus(bool &was_moving, bool &is_moving) { DVBChannel *dvbchannel = GetDVBChannel(); if (!dvbchannel) return; const DiSEqCDevRotor *rotor = dvbchannel->GetRotor(); if (!rotor) return; QMutexLocker locker(&statusLock); was_moving = rotorPosition.GetValue() < 100; int pos = (int)truncf(rotor->GetProgress() * 100); rotorPosition.SetValue(pos); is_moving = rotorPosition.GetValue() < 100; }
TEST(math, truncf) { auto guard = make_scope_guard([]() { fesetenv(FE_DFL_ENV); }); fesetround(FE_UPWARD); // truncf ignores the rounding mode and always rounds toward zero. ASSERT_FLOAT_EQ(1.0f, truncf(1.5f)); ASSERT_FLOAT_EQ(-1.0f, truncf(-1.5f)); ASSERT_FLOAT_EQ(0.0f, truncf(0.0f)); ASSERT_FLOAT_EQ(-0.0f, truncf(-0.0f)); ASSERT_TRUE(isnan(truncf(nanf("")))); ASSERT_FLOAT_EQ(HUGE_VALF, truncf(HUGE_VALF)); }
QDateTime PremiereContentTransmissionDescriptor::StartTimeUTC(uint index) const { // set buf to the startdate const uint8_t *buf = _date_ptrs[index]; uint mjd = (buf[0] << 8) | buf[1]; // reset buf two bytes before the startime buf = _time_ptrs[index]-2; if (mjd >= 40587) { QDateTime result; // Modified Julian date as number of days since 17th November 1858. // 1st Jan 1970 was date 40587. uint secsSince1970 = (mjd - 40587) * 86400; secsSince1970 += byteBCD2int(buf[2]) * 3600; secsSince1970 += byteBCD2int(buf[3]) * 60; secsSince1970 += byteBCD2int(buf[4]); result.setTime_t(secsSince1970, Qt::LocalTime); return result; } // Original function taken from dvbdate.c in linuxtv-apps code // Use the routine specified in ETSI EN 300 468 V1.4.1, // "Specification for Service Information in Digital Video Broadcasting" // to convert from Modified Julian Date to Year, Month, Day. const float tmpA = 1.0 / 365.25; const float tmpB = 1.0 / 30.6001; float mjdf = mjd; int year = (int) truncf((mjdf - 15078.2f) * tmpA); int month = (int) truncf( (mjdf - 14956.1f - truncf(year * 365.25f)) * tmpB); int day = (int) truncf( (mjdf - 14956.0f - truncf(year * 365.25f) - truncf(month * 30.6001f))); int i = (month == 14 || month == 15) ? 1 : 0; QDate date(1900 + year + i, month - 1 - i * 12, day); QTime time(byteBCD2int(buf[2]), byteBCD2int(buf[3]), byteBCD2int(buf[4])); return QDateTime(date, time); }
int DisplayDevice::pick(int dim, const float *pos, const VMDDisplayList *cmdList, float &eyedist, int *unitcell, float window_size) { char *cmdptr = NULL; int tok; float newEyeDist, currEyeDist = eyedist; int tag = (-1), inRegion, currTag; float minX=0.0f, minY=0.0f, maxX=0.0f, maxY=0.0f; float fminX=0.0f, fminY=0.0f, fminZ=0.0f, fmaxX=0.0f, fmaxY=0.0f, fmaxZ=0.0f; float wpntpos[3], pntpos[3], cpos[3]; if(!cmdList) return (-1); // initialize picking: find screen region to look for object if (dim == 2) { fminX = pos[0] - window_size; fmaxX = pos[0] + window_size; fminY = pos[1] - window_size; fmaxY = pos[1] + window_size; abs_screen_pos(fminX, fminY); abs_screen_pos(fmaxX, fmaxY); #if defined(_MSC_VER) // Win32 lacks the C99 round() routine // Add +/- 0.5 then then round towards zero. #if 1 minX = (int) ((float) (fminX + (fminX >= 0.0f ? 0.5f : -0.5f))); maxX = (int) ((float) (fmaxX + (fmaxX >= 0.0f ? 0.5f : -0.5f))); minY = (int) ((float) (fminY + (fminY >= 0.0f ? 0.5f : -0.5f))); maxY = (int) ((float) (fmaxY + (fmaxY >= 0.0f ? 0.5f : -0.5f))); #else minX = truncf(fminX + (fminX >= 0.0f ? 0.5f : -0.5f)); maxX = truncf(fmaxX + (fmaxX >= 0.0f ? 0.5f : -0.5f)); minY = truncf(fminY + (fminY >= 0.0f ? 0.5f : -0.5f)); maxY = truncf(fmaxY + (fmaxY >= 0.0f ? 0.5f : -0.5f)); // minX = floor(fminX + 0.5); // maxX = floor(fmaxX + 0.5); // minY = floor(fminY + 0.5); // maxY = floor(fmaxY + 0.5); #endif #else minX = round(fminX); maxX = round(fmaxX); minY = round(fminY); maxY = round(fmaxY); #endif } else { fminX = pos[0] - window_size; fmaxX = pos[0] + window_size; fminY = pos[1] - window_size; fmaxY = pos[1] + window_size; fminZ = pos[2] - window_size; fmaxZ = pos[2] + window_size; } // make sure we do not disturb the regular transformation matrix transMat.dup(); (transMat.top()).multmatrix(cmdList->mat); // Transform the current pick point for each periodic image ResizeArray<Matrix4> pbcImages; ResizeArray<int> pbcCells; find_pbc_images(cmdList, pbcImages); find_pbc_cells(cmdList, pbcCells); int pbcimg; for (pbcimg=0; pbcimg<pbcImages.num(); pbcimg++) { transMat.dup(); (transMat.top()).multmatrix(pbcImages[pbcimg]); // scan through the list, getting each command and executing it, until // the end of commands token is found VMDDisplayList::VMDLinkIter cmditer; cmdList->first(&cmditer); while((tok = cmdList->next(&cmditer, cmdptr)) != DLASTCOMMAND) { switch (tok) { case DPICKPOINT: // calculate the transformed position of the point { DispCmdPickPoint *cmd = (DispCmdPickPoint *)cmdptr; vec_copy(wpntpos, cmd->postag); currTag = cmd->tag; } (transMat.top()).multpoint3d(wpntpos, pntpos); // check if in picking region ... different for 2D and 3D if (dim == 2) { // convert the 3D world coordinate to 2D (XY) absolute screen // coordinate, and a normalized Z coordinate. abs_screen_loc_3D(pntpos, cpos); // check to see if the projected picking position falls within the // view frustum, with the XY coords falling within the displayed // window, and the Z coordinate falling within the view volume // between the front and rear clipping planes. inRegion = (cpos[0] >= minX && cpos[0] <= maxX && cpos[1] >= minY && cpos[1] <= maxY && cpos[2] >= 0.0 && cpos[2] <= 1.0); } else { // just check to see if the position is in a box centered on our // pointer. The pointer position should already be transformed. inRegion = (pntpos[0] >= fminX && pntpos[0] <= fmaxX && pntpos[1] >= fminY && pntpos[1] <= fmaxY && pntpos[2] >= fminZ && pntpos[2] <= fmaxZ); } // Clip still-viable pick points against all active clipping planes if (inRegion) { // We must perform a check against all of the active // user-defined clipping planes to ensure that only pick points // associated with visible geometry can be selected. int cp; for (cp=0; cp < VMD_MAX_CLIP_PLANE; cp++) { // The final result is the intersection of all of the // individual clipping plane tests... if (cmdList->clipplanes[cp].mode) { float cpdist[3]; vec_sub(cpdist, wpntpos, cmdList->clipplanes[cp].center); inRegion &= (dot_prod(cpdist, cmdList->clipplanes[cp].normal) > 0.0f); } } } // has a hit occurred? if (inRegion) { // yes, see if it is closer to the eye position than earlier objects if(dim==2) newEyeDist = DTOEYE(pntpos[0], pntpos[1], pntpos[2]); else newEyeDist = DTOPOINT(pntpos[0],pntpos[1],pntpos[2]); if(currEyeDist < 0.0 || newEyeDist < currEyeDist) { currEyeDist = newEyeDist; tag = currTag; if (unitcell) { unitcell[0] = pbcCells[3*pbcimg ]; unitcell[1] = pbcCells[3*pbcimg+1]; unitcell[2] = pbcCells[3*pbcimg+2]; } } } break; case DPICKPOINT_ARRAY: // loop over all of the pick points in the pick point index array DispCmdPickPointArray *cmd = (DispCmdPickPointArray *)cmdptr; float *pickpos=NULL; float *crds=NULL; int *indices=NULL; cmd->getpointers(crds, indices); int i; for (i=0; i<cmd->numpicks; i++) { pickpos = crds + i*3; if (cmd->allselected) { currTag = i + cmd->firstindex; } else { currTag = indices[i]; } vec_copy(wpntpos, pickpos); (transMat.top()).multpoint3d(pickpos, pntpos); // check if in picking region ... different for 2D and 3D if (dim == 2) { // convert the 3D world coordinate to 2D absolute screen coord abs_screen_loc_3D(pntpos, cpos); // check to see if the position falls in our picking region // including the clipping region (cpos[2]) inRegion = (cpos[0] >= minX && cpos[0] <= maxX && cpos[1] >= minY && cpos[1] <= maxY && cpos[2] >= 0.0 && cpos[2] <= 1.0); } else { // just check to see if the position is in a box centered on our // pointer. The pointer position should already be transformed. inRegion = (pntpos[0] >= fminX && pntpos[0] <= fmaxX && pntpos[1] >= fminY && pntpos[1] <= fmaxY && pntpos[2] >= fminZ && pntpos[2] <= fmaxZ); } // Clip still-viable pick points against all active clipping planes if (inRegion) { // We must perform a check against all of the active // user-defined clipping planes to ensure that only pick points // associated with visible geometry can be selected. int cp; for (cp=0; cp < VMD_MAX_CLIP_PLANE; cp++) { // The final result is the intersection of all of the // individual clipping plane tests... if (cmdList->clipplanes[cp].mode) { float cpdist[3]; vec_sub(cpdist, wpntpos, cmdList->clipplanes[cp].center); inRegion &= (dot_prod(cpdist, cmdList->clipplanes[cp].normal) > 0.0f); } } } // has a hit occurred? if (inRegion) { // yes, see if it is closer to the eye than earlier hits if (dim==2) newEyeDist = DTOEYE(pntpos[0], pntpos[1], pntpos[2]); else newEyeDist = DTOPOINT(pntpos[0],pntpos[1],pntpos[2]); if (currEyeDist < 0.0 || newEyeDist < currEyeDist) { currEyeDist = newEyeDist; tag = currTag; if (unitcell) { unitcell[0] = pbcCells[3*pbcimg ]; unitcell[1] = pbcCells[3*pbcimg+1]; unitcell[2] = pbcCells[3*pbcimg+2]; } } } } break; } } // Pop the PBC image transform transMat.pop(); } // end of loop over PBC images // make sure we do not disturb the regular transformation matrix transMat.pop(); // return result; if tag >= 0, we found something eyedist = currEyeDist; return tag; }
float roundf( float f ) { if( f < 0.0f ) return truncf( f-0.5f ); return truncf( f+0.5f ); }