BOOL LLBreastMotion::onUpdate(F32 time, U8* joint_mask) { // Skip if disabled globally. // <FS:PP> Attempt to speed up things a little // if (!gSavedSettings.getBOOL("AvatarPhysics")) static LLCachedControl<bool> AvatarPhysics(gSavedSettings, "AvatarPhysics"); if (!AvatarPhysics) // </FS:PP> { return TRUE; } // Higher LOD is better. This controls the granularity // and frequency of updates for the motions. const F32 lod_factor = LLVOAvatar::sPhysicsLODFactor; if (lod_factor == 0) { return TRUE; } if (mCharacter->getSex() != SEX_FEMALE) return TRUE; const F32 time_delta = calculateTimeDelta(); if (time_delta < .01 || time_delta > 10.0) return TRUE; //////////////////////////////////////////////////////////////////////////////// // Get all parameters and settings // mBreastMassParam = mCharacter->getVisualParamWeight("Breast_Physics_Mass"); mBreastSmoothingParam = (U32)(mCharacter->getVisualParamWeight("Breast_Physics_Smoothing")); mBreastGravityParam = mCharacter->getVisualParamWeight("Breast_Physics_Gravity"); mBreastSpringParam[0] = mCharacter->getVisualParamWeight("Breast_Physics_Side_Spring"); mBreastGainParam[0] = mCharacter->getVisualParamWeight("Breast_Physics_Side_Gain"); mBreastDampingParam[0] = mCharacter->getVisualParamWeight("Breast_Physics_Side_Damping"); mBreastMaxVelocityParam[0] = mCharacter->getVisualParamWeight("Breast_Physics_Side_Max_Velocity"); mBreastDragParam[0] = mCharacter->getVisualParamWeight("Breast_Physics_Side_Drag"); mBreastSpringParam[1] = mCharacter->getVisualParamWeight("Breast_Physics_UpDown_Spring"); mBreastGainParam[1] = mCharacter->getVisualParamWeight("Breast_Physics_UpDown_Gain"); mBreastDampingParam[1] = mCharacter->getVisualParamWeight("Breast_Physics_UpDown_Damping"); mBreastMaxVelocityParam[1] = mCharacter->getVisualParamWeight("Breast_Physics_UpDown_Max_Velocity"); mBreastDragParam[1] = mCharacter->getVisualParamWeight("Breast_Physics_UpDown_Drag"); // Get the current morph parameters. LLVector3 breast_user_local_pt(0,0,0); for (U32 i=0; i < N_PARAMS; i++) { if (mBreastParamsUser[i] != NULL) { breast_user_local_pt[i] = mBreastParamsUser[i]->getWeight(); } } LLVector3 breast_current_local_pt = mBreastLastPosition_local_pt; // // End parameters and settings //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Calculate velocity and acceleration in parameter space. // const LLVector3 char_velocity_local_vec = calculateVelocity_local(time_delta); const LLVector3 char_acceleration_local_vec = calculateAcceleration_local(char_velocity_local_vec, time_delta); mCharLastVelocity_local_vec = char_velocity_local_vec; LLJoint *chest_joint = mChestState->getJoint(); mCharLastPosition_world_pt = chest_joint->getWorldPosition(); // // End velocity and acceleration //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Calculate the total force // // Spring force is a restoring force towards the original user-set breast position. // F = kx const LLVector3 spring_length_local = breast_current_local_pt-breast_user_local_pt; LLVector3 force_spring_local_vec = -spring_length_local; force_spring_local_vec *= mBreastSpringParam; // Acceleration is the force that comes from the change in velocity of the torso. // F = ma + mg LLVector3 force_accel_local_vec = char_acceleration_local_vec * mBreastMassParam; const LLVector3 force_gravity_local_vec = toLocal(LLVector3(0,0,1))* mBreastGravityParam * mBreastMassParam; force_accel_local_vec += force_gravity_local_vec; force_accel_local_vec *= mBreastGainParam; // Damping is a restoring force that opposes the current velocity. // F = -kv LLVector3 force_damping_local_vec = -mBreastDampingParam; force_damping_local_vec *= mBreastVelocity_local_vec; // Drag is a force imparted by velocity, intuitively it is similar to wind resistance. // F = .5v*v LLVector3 force_drag_local_vec = .5*char_velocity_local_vec; force_drag_local_vec *= char_velocity_local_vec; force_drag_local_vec *= mBreastDragParam[0]; LLVector3 force_net_local_vec = force_accel_local_vec + force_gravity_local_vec + force_spring_local_vec + force_damping_local_vec + force_drag_local_vec; // // End total force //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Calculate new params // // Calculate the new acceleration based on the net force. // a = F/m LLVector3 acceleration_local_vec = force_net_local_vec / mBreastMassParam; mBreastVelocity_local_vec += acceleration_local_vec; mBreastVelocity_local_vec.clamp(-mBreastMaxVelocityParam*100.0, mBreastMaxVelocityParam*100.0); // Temporary debugging setting to cause all avatars to move, for profiling purposes. // <FS:PP> Attempt to speed up things a little // if (gSavedSettings.getBOOL("AvatarPhysicsTest")) static LLCachedControl<bool> AvatarPhysicsTest(gSavedSettings, "AvatarPhysicsTest"); if (AvatarPhysicsTest) // </FS:PP> { mBreastVelocity_local_vec[0] = sin(mTimer.getElapsedTimeF32()*4.0)*5.0; mBreastVelocity_local_vec[1] = sin(mTimer.getElapsedTimeF32()*3.0)*5.0; } // Calculate the new parameters and clamp them to the min/max ranges. LLVector3 new_local_pt = breast_current_local_pt + mBreastVelocity_local_vec*time_delta; new_local_pt.clamp(mBreastParamsMin,mBreastParamsMax); // Set the new parameters. for (U32 i=0; i < 3; i++) { // If the param is disabled, just set the param to the user value. if (mBreastMaxVelocityParam[i] == 0) { new_local_pt[i] = breast_user_local_pt[i]; } if (mBreastParamsDriven[i]) { mCharacter->setVisualParamWeight(mBreastParamsDriven[i], new_local_pt[i], FALSE); } } mBreastLastPosition_local_pt = new_local_pt; // // End calculate new params //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Conditionally update the visual params // // Updating the visual params (i.e. what the user sees) is fairly expensive. // So only update if the params have changed enough, and also take into account // the graphics LOD settings. // For non-self, if the avatar is small enough visually, then don't update. const BOOL is_self = (dynamic_cast<LLVOAvatarSelf *>(this) != NULL); if (!is_self) { const F32 area_for_max_settings = 0.0; const F32 area_for_min_settings = 1400.0; const F32 area_for_this_setting = area_for_max_settings + (area_for_min_settings-area_for_max_settings)*(1.0-lod_factor); const F32 pixel_area = fsqrtf(mCharacter->getPixelArea()); if (pixel_area < area_for_this_setting) { return TRUE; } } // If the parameter hasn't changed enough, then don't update. LLVector3 position_diff = mBreastLastUpdatePosition_local_pt-new_local_pt; for (U32 i=0; i < 3; i++) { const F32 min_delta = (1.0-lod_factor)*(mBreastParamsMax[i]-mBreastParamsMin[i])/2.0; if (llabs(position_diff[i]) > min_delta) { mCharacter->updateVisualParams(); mBreastLastUpdatePosition_local_pt = new_local_pt; return TRUE; } } // // End update visual params //////////////////////////////////////////////////////////////////////////////// return TRUE; }
static void aout_DecSynchronize (audio_output_t *aout, mtime_t dec_pts, int input_rate) { aout_owner_t *owner = aout_owner (aout); mtime_t drift; /** * Depending on the drift between the actual and intended playback times, * the audio core may ignore the drift, trigger upsampling or downsampling, * insert silence or even discard samples. * Future VLC versions may instead adjust the input rate. * * The audio output plugin is responsible for estimating its actual * playback time, or rather the estimated time when the next sample will * be played. (The actual playback time is always the current time, that is * to say mdate(). It is not an useful statistic.) * * Most audio output plugins can estimate the delay until playback of * the next sample to be written to the buffer, or equally the time until * all samples in the buffer will have been played. Then: * pts = mdate() + delay */ if (aout_OutputTimeGet (aout, &drift) != 0) return; /* nothing can be done if timing is unknown */ drift += mdate () - dec_pts; /* Late audio output. * This can happen due to insufficient caching, scheduling jitter * or bug in the decoder. Ideally, the output would seek backward. But that * is not portable, not supported by some hardware and often unsafe/buggy * where supported. The other alternative is to flush the buffers * completely. */ if (drift > (owner->sync.discontinuity ? 0 : +3 * input_rate * AOUT_MAX_PTS_DELAY / INPUT_RATE_DEFAULT)) { if (!owner->sync.discontinuity) msg_Warn (aout, "playback way too late (%"PRId64"): " "flushing buffers", drift); else msg_Dbg (aout, "playback too late (%"PRId64"): " "flushing buffers", drift); aout_OutputFlush (aout, false); aout_StopResampling (aout); owner->sync.end = VLC_TS_INVALID; owner->sync.discontinuity = true; /* Now the output might be too early... Recheck. */ if (aout_OutputTimeGet (aout, &drift) != 0) return; /* nothing can be done if timing is unknown */ drift += mdate () - dec_pts; } /* Early audio output. * This is rare except at startup when the buffers are still empty. */ if (drift < (owner->sync.discontinuity ? 0 : -3 * input_rate * AOUT_MAX_PTS_ADVANCE / INPUT_RATE_DEFAULT)) { if (!owner->sync.discontinuity) msg_Warn (aout, "playback way too early (%"PRId64"): " "playing silence", drift); aout_DecSilence (aout, -drift, dec_pts); aout_StopResampling (aout); owner->sync.discontinuity = true; drift = 0; } /* Resampling */ if (drift > +AOUT_MAX_PTS_DELAY && owner->sync.resamp_type != AOUT_RESAMPLING_UP) { msg_Warn (aout, "playback too late (%"PRId64"): up-sampling", drift); owner->sync.resamp_type = AOUT_RESAMPLING_UP; owner->sync.resamp_start_drift = +drift; } if (drift < -AOUT_MAX_PTS_ADVANCE && owner->sync.resamp_type != AOUT_RESAMPLING_DOWN) { msg_Warn (aout, "playback too early (%"PRId64"): down-sampling", drift); owner->sync.resamp_type = AOUT_RESAMPLING_DOWN; owner->sync.resamp_start_drift = -drift; } if (owner->sync.resamp_type == AOUT_RESAMPLING_NONE) return; /* Everything is fine. Nothing to do. */ if (llabs (drift) > 2 * owner->sync.resamp_start_drift) { /* If the drift is ever increasing, then something is seriously wrong. * Cease resampling and hope for the best. */ msg_Warn (aout, "timing screwed (drift: %"PRId64" us): " "stopping resampling", drift); aout_StopResampling (aout); return; } /* Resampling has been triggered earlier. This checks if it needs to be * increased or decreased. Resampling rate changes must be kept slow for * the comfort of listeners. */ int adj = (owner->sync.resamp_type == AOUT_RESAMPLING_UP) ? +2 : -2; if (2 * llabs (drift) <= owner->sync.resamp_start_drift) /* If the drift has been reduced from more than half its initial * value, then it is time to switch back the resampling direction. */ adj *= -1; if (!aout_FiltersAdjustResampling (owner->filters, adj)) { /* Everything is back to normal: stop resampling. */ owner->sync.resamp_type = AOUT_RESAMPLING_NONE; msg_Dbg (aout, "resampling stopped (drift: %"PRId64" us)", drift); } }
void LLChicletBar::reshape(S32 width, S32 height, BOOL called_from_parent) { static S32 debug_calling_number = 0; LL_DEBUGS() << "**************************************** " << ++debug_calling_number << LL_ENDL; S32 current_width = getRect().getWidth(); S32 delta_width = width - current_width; LL_DEBUGS() << "Reshaping: " << ", width: " << width << ", cur width: " << current_width << ", delta_width: " << delta_width << ", called_from_parent: " << called_from_parent << LL_ENDL; if (mChicletPanel) log(mChicletPanel, "before"); // Difference between chiclet bar width required to fit its children and the actual width. (see EXT-991) // Positive value means that chiclet bar is not wide enough. // Negative value means that there is free space. static S32 extra_shrink_width = 0; bool should_be_reshaped = true; if (mChicletPanel && mToolbarStack) { // Firstly, update layout stack to ensure we deal with correct panel sizes. { // Force the updating of layout to reset panels collapse factor. mToolbarStack->updateLayout(); } // chiclet bar is narrowed if (delta_width < 0) { if (extra_shrink_width > 0) // not enough space { extra_shrink_width += llabs(delta_width); should_be_reshaped = false; } else { extra_shrink_width = processWidthDecreased(delta_width); // increase new width to extra_shrink_width value to not reshape less than chiclet bar minimum width += extra_shrink_width; } } // chiclet bar is widened else { if (extra_shrink_width > delta_width) { // Still not enough space. // Only subtract the delta from the required delta and don't reshape. extra_shrink_width -= delta_width; should_be_reshaped = false; } else if (extra_shrink_width > 0) { // If we have some extra shrink width let's reduce delta_width & width delta_width -= extra_shrink_width; width -= extra_shrink_width; extra_shrink_width = 0; } } } if (should_be_reshaped) { LL_DEBUGS() << "Reshape all children with width: " << width << LL_ENDL; LLPanel::reshape(width, height, called_from_parent); } if (mChicletPanel) log(mChicletPanel, "after"); }
llong CExpression::GetSingle( lpctstr & pszArgs ) { ADDTOCALLSTACK("CExpression::GetSingle"); // Parse just a single expression without any operators or ranges. ASSERT(pszArgs); GETNONWHITESPACE( pszArgs ); lpctstr orig = pszArgs; if (pszArgs[0]=='.') ++pszArgs; if ( pszArgs[0] == '0' ) // leading '0' = hex value. { // A hex value. if ( pszArgs[1] == '.' ) // leading 0. means it really is decimal. { pszArgs += 2; goto try_dec; } lpctstr pStart = pszArgs; ullong val = 0; while (true) { tchar ch = *pszArgs; if ( IsDigit(ch) ) ch -= '0'; else { ch = static_cast<tchar>(tolower(ch)); if ( ch > 'f' || ch < 'a' ) { if ( ch == '.' && pStart[0] != '0' ) // ok i'm confused. it must be decimal. { pszArgs = pStart; goto try_dec; } break; } ch -= 'a' - 10; } val *= 0x10; val += ch; ++pszArgs; } return (llong)val; } else if ( pszArgs[0] == '.' || IsDigit(pszArgs[0]) ) { // A decminal number try_dec: llong iVal = 0; for ( ; ; ++pszArgs ) { if ( *pszArgs == '.' ) continue; // just skip this. if ( ! IsDigit(*pszArgs) ) break; iVal *= 10; iVal += *pszArgs - '0'; } return iVal; } else if ( ! _ISCSYMF(pszArgs[0]) ) { #pragma region maths // some sort of math op ? switch ( pszArgs[0] ) { case '{': ++pszArgs; return GetRangeNumber( pszArgs ); case '[': case '(': // Parse out a sub expression. ++pszArgs; return GetVal( pszArgs ); case '+': ++pszArgs; break; case '-': ++pszArgs; return -GetSingle( pszArgs ); case '~': // Bitwise not. ++pszArgs; return ~GetSingle( pszArgs ); case '!': // boolean not. ++pszArgs; if ( pszArgs[0] == '=' ) // odd condition such as (!=x) which is always true of course. { ++pszArgs; // so just skip it. and compare it to 0 return GetSingle( pszArgs ); } return !GetSingle( pszArgs ); case ';': // seperate field. case ',': // seperate field. case '\0': return 0; } #pragma endregion maths } else #pragma region intrinsics { // Symbol or intrinsinc function ? INTRINSIC_TYPE iIntrinsic = (INTRINSIC_TYPE) FindTableHeadSorted( pszArgs, sm_IntrinsicFunctions, CountOf(sm_IntrinsicFunctions)-1 ); if ( iIntrinsic >= 0 ) { size_t iLen = strlen(sm_IntrinsicFunctions[iIntrinsic]); if ( pszArgs[iLen] == '(' ) { pszArgs += (iLen + 1); tchar * pszArgsNext; Str_Parse( const_cast<tchar*>(pszArgs), &(pszArgsNext), ")" ); tchar * ppCmd[5]; llong iResult; size_t iCount = 0; switch ( iIntrinsic ) { case INTRINSIC_ID: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = RES_GET_INDEX( GetVal(pszArgs) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_MAX: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 0; else { const int64 iVal1 = GetVal(ppCmd[0]), iVal2 = GetVal(ppCmd[1]); iResult = maximum(iVal1, iVal2); } } break; case INTRINSIC_MIN: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 0; else { const int64 iVal1 = GetVal(ppCmd[0]), iVal2 = GetVal(ppCmd[1]); iResult = minimum(iVal1, iVal2); } } break; case INTRINSIC_LOGARITHM: { iCount = 0; iResult = 0; if ( pszArgs && *pszArgs ) { llong iArgument = GetVal(pszArgs); if ( iArgument <= 0 ) { DEBUG_ERR(( "Exp_GetVal: (x)Log(%" PRId64 ") is %s\n", iArgument, (!iArgument) ? "infinite" : "undefined" )); } else { iCount = 1; if ( strchr(pszArgs, ',') ) { ++iCount; SKIP_ARGSEP(pszArgs); if ( !strcmpi(pszArgs, "e") ) { iResult = (llong)log( (double)iArgument ); } else if ( !strcmpi(pszArgs, "pi") ) { iResult = (llong)(log( (double)iArgument ) / log( M_PI ) ); } else { llong iBase = GetVal(pszArgs); if ( iBase <= 0 ) { DEBUG_ERR(( "Exp_GetVal: (%" PRId64 ")Log(%" PRId64 ") is %s\n", iBase, iArgument, (!iBase ? "infinite" : "undefined") )); iCount = 0; } else iResult = (llong)(log( (double)iArgument ) / log( (double)iBase )); } } else iResult = (llong)log10( (double)iArgument ); } } } break; case INTRINSIC_NAPIERPOW: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)exp( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_SQRT: { iCount = 0; iResult = 0; if ( pszArgs && *pszArgs ) { llong iTosquare = GetVal(pszArgs); if (iTosquare >= 0) { ++iCount; iResult = (llong)sqrt( (double)iTosquare ); } else DEBUG_ERR(( "Exp_GetVal: Sqrt of negative number (%" PRId64 ") is impossible\n", iTosquare )); } } break; case INTRINSIC_SIN: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)sin( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_ARCSIN: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)asin( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_COS: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)cos( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_ARCCOS: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)acos( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_TAN: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)tan( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_ARCTAN: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = (llong)atan( (double)GetVal( pszArgs ) ); } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_StrIndexOf: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 3, "," ); if ( iCount < 2 ) iResult = -1; else iResult = Str_IndexOf( ppCmd[0] , ppCmd[1] , (iCount==3)?(int)GetVal(ppCmd[2]):0 ); } break; case INTRINSIC_STRMATCH: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 0; else iResult = (Str_Match( ppCmd[0], ppCmd[1] ) == MATCH_VALID ) ? 1 : 0; } break; case INTRINSIC_STRREGEX: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 0; else { tchar * tLastError = Str_GetTemp(); iResult = Str_RegExMatch( ppCmd[0], ppCmd[1], tLastError ); if ( iResult == -1 ) { DEBUG_ERR(( "STRREGEX bad function usage. Error: %s\n", tLastError )); } } } break; case INTRINSIC_RANDBELL: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 0; else iResult = Calc_GetBellCurve( (int)GetVal( ppCmd[0] ), (int)GetVal( ppCmd[1] ) ); } break; case INTRINSIC_STRASCII: { if ( pszArgs && *pszArgs ) { iCount = 1; iResult = pszArgs[0]; } else { iCount = 0; iResult = 0; } } break; case INTRINSIC_RAND: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount <= 0 ) iResult = 0; else { int64 val1 = GetVal( ppCmd[0] ); if ( iCount == 2 ) { int64 val2 = GetVal( ppCmd[1] ); iResult = Calc_GetRandLLVal2( val1, val2 ); } else iResult = Calc_GetRandLLVal(val1); } } break; case INTRINSIC_STRCMP: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 1; else iResult = strcmp(ppCmd[0], ppCmd[1]); } break; case INTRINSIC_STRCMPI: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 2, "," ); if ( iCount < 2 ) iResult = 1; else iResult = strcmpi(ppCmd[0], ppCmd[1]); } break; case INTRINSIC_STRLEN: { iCount = 1; iResult = strlen(pszArgs); } break; case INTRINSIC_ISOBSCENE: { iCount = 1; iResult = g_Cfg.IsObscene( pszArgs ); } break; case INTRINSIC_ISNUMBER: { iCount = 1; { GETNONWHITESPACE( pszArgs ); if (*pszArgs == '-') ++pszArgs; iResult = IsStrNumeric( pszArgs ); } } break; case INTRINSIC_QVAL: { iCount = Str_ParseCmds( const_cast<tchar*>(pszArgs), ppCmd, 5, "," ); if ( iCount < 3 ) iResult = 0; else { llong a1 = GetSingle(ppCmd[0]); llong a2 = GetSingle(ppCmd[1]); if ( a1 < a2 ) iResult = GetSingle(ppCmd[2]); else if ( a1 == a2 ) iResult = ( iCount < 4 ) ? 0 : GetSingle(ppCmd[3]); else iResult = ( iCount < 5 ) ? 0 : GetSingle(ppCmd[4]); } } break; case INTRINSIC_ABS: { iCount = 1; iResult = llabs(GetVal(pszArgs)); } break; default: iCount = 0; iResult = 0; break; } pszArgs = pszArgsNext; if ( !iCount ) { DEBUG_ERR(( "Bad intrinsic function usage: Missing arguments\n" )); return 0; } else return iResult; } } // Must be a symbol of some sort ? lpctstr ptcArgsOriginal = pszArgs; llong llVal; if ( m_VarGlobals.GetParseVal_Advance( pszArgs, &llVal ) ) // VAR. return llVal; if ( m_VarResDefs.GetParseVal( ptcArgsOriginal, &llVal ) ) // RESDEF. return llVal; if ( m_VarDefs.GetParseVal( ptcArgsOriginal, &llVal ) ) // DEF. return llVal; } #pragma endregion intrinsics // hard end ! Error of some sort. tchar szTag[ EXPRESSION_MAX_KEY_LEN ]; size_t i = GetIdentifierString( szTag, pszArgs ); pszArgs += i; // skip it. if ( strlen(orig) > 1) DEBUG_ERR(("Undefined symbol '%s' ['%s']\n", szTag, orig)); else DEBUG_ERR(("Undefined symbol '%s'\n", szTag)); return 0; }
void LLPanelFace::getState() { LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getFirstObject(); LLCalc* calcp = LLCalc::getInstance(); if( objectp && objectp->getPCode() == LL_PCODE_VOLUME && objectp->permModify()) { BOOL editable = objectp->permModify(); // only turn on auto-adjust button if there is a media renderer and the media is loaded childSetEnabled("textbox autofix",FALSE); //mLabelTexAutoFix->setEnabled ( FALSE ); childSetEnabled("button align",FALSE); //mBtnAutoFix->setEnabled ( FALSE ); //if ( LLMediaEngine::getInstance()->getMediaRenderer () ) // if ( LLMediaEngine::getInstance()->getMediaRenderer ()->isLoaded () ) // { // // //mLabelTexAutoFix->setEnabled ( editable ); // // //mBtnAutoFix->setEnabled ( editable ); // } S32 selected_count = LLSelectMgr::getInstance()->getSelection()->getObjectCount(); BOOL single_volume = (LLSelectMgr::getInstance()->selectionAllPCode( LL_PCODE_VOLUME )) && (selected_count == 1); childSetEnabled("copytextures", single_volume && editable); childSetEnabled("pastetextures", single_volume && editable); childSetEnabled("textbox params", single_volume && editable); childSetEnabled("button apply",editable); bool identical; LLTextureCtrl* texture_ctrl = getChild<LLTextureCtrl>("texture control"); // Texture { LLUUID id; struct f1 : public LLSelectedTEGetFunctor<LLUUID> { LLUUID get(LLViewerObject* object, S32 te) { LLViewerImage* image = object->getTEImage(te); return image ? image->getID() : LLUUID::null; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, id ); if (identical) { // All selected have the same texture if(texture_ctrl) { texture_ctrl->setTentative( FALSE ); texture_ctrl->setEnabled( editable ); texture_ctrl->setImageAssetID( id ); } } else { if(texture_ctrl) { if( id.isNull() ) { // None selected texture_ctrl->setTentative( FALSE ); texture_ctrl->setEnabled( FALSE ); texture_ctrl->setImageAssetID( LLUUID::null ); } else { // Tentative: multiple selected with different textures texture_ctrl->setTentative( TRUE ); texture_ctrl->setEnabled( editable ); texture_ctrl->setImageAssetID( id ); } } } if(LLViewerMedia::textureHasMedia(id)) { childSetEnabled("textbox autofix",editable); childSetEnabled("button align",editable); } } LLAggregatePermissions texture_perms; if(texture_ctrl) { // texture_ctrl->setValid( editable ); if (LLSelectMgr::getInstance()->selectGetAggregateTexturePermissions(texture_perms)) { BOOL can_copy = texture_perms.getValue(PERM_COPY) == LLAggregatePermissions::AP_EMPTY || texture_perms.getValue(PERM_COPY) == LLAggregatePermissions::AP_ALL; BOOL can_transfer = texture_perms.getValue(PERM_TRANSFER) == LLAggregatePermissions::AP_EMPTY || texture_perms.getValue(PERM_TRANSFER) == LLAggregatePermissions::AP_ALL; texture_ctrl->setCanApplyImmediately(can_copy && can_transfer); } else { texture_ctrl->setCanApplyImmediately(FALSE); } } // planar align bool align_planar = false; bool identical_planar_aligned = false; { LLCheckBoxCtrl* cb_planar_align = getChild<LLCheckBoxCtrl>("checkbox planar align"); align_planar = (cb_planar_align && cb_planar_align->get()); struct f1 : public LLSelectedTEGetFunctor<bool> { bool get(LLViewerObject* object, S32 face) { return (object->getTE(face)->getTexGen() == LLTextureEntry::TEX_GEN_PLANAR); } } func; bool is_planar; bool texgens_identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, is_planar ); bool enabled = (editable && texgens_identical && is_planar); childSetValue("checkbox planar align", align_planar && enabled); childSetEnabled("checkbox planar align", enabled); if (align_planar && enabled) { struct f2 : public LLSelectedTEGetFunctor<LLFace *> { LLFace* get(LLViewerObject* object, S32 te) { return (object->mDrawable) ? object->mDrawable->getFace(te): NULL; } } get_te_face_func; LLFace* last_face; LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue(&get_te_face_func, last_face); LLPanelFaceGetIsAlignedTEFunctor get_is_aligend_func(last_face); // this will determine if the texture param controls are tentative: identical_planar_aligned = LLSelectMgr::getInstance()->getSelection()->applyToTEs(&get_is_aligend_func); } } // Texture scale { childSetEnabled("tex scale",editable); //mLabelTexScale->setEnabled( editable ); F32 scale_s = 1.f; struct f2 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return object->getTE(face)->mScaleS; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, scale_s ); identical = align_planar ? identical_planar_aligned : identical; childSetValue("TexScaleU",editable ? llabs(scale_s) : 0); childSetTentative("TexScaleU",LLSD((BOOL)(!identical))); childSetEnabled("TexScaleU",editable); childSetValue("checkbox flip s",LLSD((BOOL)(scale_s < 0 ? TRUE : FALSE ))); childSetTentative("checkbox flip s",LLSD((BOOL)((!identical) ? TRUE : FALSE ))); childSetEnabled("checkbox flip s",editable); } { F32 scale_t = 1.f; struct f3 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return object->getTE(face)->mScaleT; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, scale_t ); identical = align_planar ? identical_planar_aligned : identical; childSetValue("TexScaleV",llabs(editable ? llabs(scale_t) : 0)); childSetTentative("TexScaleV",LLSD((BOOL)(!identical))); childSetEnabled("TexScaleV",editable); childSetValue("checkbox flip t",LLSD((BOOL)(scale_t< 0 ? TRUE : FALSE ))); childSetTentative("checkbox flip t",LLSD((BOOL)((!identical) ? TRUE : FALSE ))); childSetEnabled("checkbox flip t",editable); } // Texture offset { childSetEnabled("tex offset",editable); F32 offset_s = 0.f; struct f4 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return object->getTE(face)->mOffsetS; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, offset_s ); identical = align_planar ? identical_planar_aligned : identical; childSetValue("TexOffsetU", editable ? offset_s : 0); childSetTentative("TexOffsetU",!identical); childSetEnabled("TexOffsetU",editable); } { F32 offset_t = 0.f; struct f5 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return object->getTE(face)->mOffsetT; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, offset_t ); identical = align_planar ? identical_planar_aligned : identical; childSetValue("TexOffsetV", editable ? offset_t : 0); childSetTentative("TexOffsetV",!identical); childSetEnabled("TexOffsetV",editable); } // Texture rotation { childSetEnabled("tex rotate",editable); F32 rotation = 0.f; struct f6 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return object->getTE(face)->mRotation; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, rotation ); identical = align_planar ? identical_planar_aligned : identical; childSetValue("TexRot", editable ? rotation * RAD_TO_DEG : 0); childSetTentative("TexRot",!identical); childSetEnabled("TexRot",editable); } // Color swatch LLColorSwatchCtrl* mColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch"); LLColor4 color = LLColor4::white; if(mColorSwatch) { struct f7 : public LLSelectedTEGetFunctor<LLColor4> { LLColor4 get(LLViewerObject* object, S32 face) { return object->getTE(face)->getColor(); } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, color ); mColorSwatch->setOriginal(color); mColorSwatch->set(color, TRUE); mColorSwatch->setValid(editable); mColorSwatch->setEnabled( editable ); mColorSwatch->setCanApplyImmediately( editable ); } // Color transparency { childSetEnabled("color trans",editable); } F32 transparency = (1.f - color.mV[VALPHA]) * 100.f; { childSetValue("ColorTrans", editable ? transparency : 0); childSetEnabled("ColorTrans",editable); } { F32 glow = 0.f; struct f8 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return object->getTE(face)->getGlow(); } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, glow ); childSetValue("glow",glow); childSetEnabled("glow",editable); childSetTentative("glow",!identical); childSetEnabled("glow label",editable); } // Bump { F32 shinyf = 0.f; struct f9 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return (F32)(object->getTE(face)->getShiny()); } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, shinyf ); LLCtrlSelectionInterface* combobox_shininess = childGetSelectionInterface("combobox shininess"); if (combobox_shininess) { combobox_shininess->selectNthItem((S32)shinyf); } else { llwarns << "failed childGetSelectionInterface for 'combobox shininess'" << llendl; } childSetEnabled("combobox shininess",editable); childSetTentative("combobox shininess",!identical); childSetEnabled("label shininess",editable); } { F32 bumpf = 0.f; struct f10 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return (F32)(object->getTE(face)->getBumpmap()); } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, bumpf ); LLCtrlSelectionInterface* combobox_bumpiness = childGetSelectionInterface("combobox bumpiness"); if (combobox_bumpiness) { combobox_bumpiness->selectNthItem((S32)bumpf); } else { llwarns << "failed childGetSelectionInterface for 'combobox bumpiness'" << llendl; } childSetEnabled("combobox bumpiness",editable); childSetTentative("combobox bumpiness",!identical); childSetEnabled("label bumpiness",editable); } { F32 genf = 0.f; struct f11 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return (F32)(object->getTE(face)->getTexGen()); } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, genf ); S32 selected_texgen = ((S32) genf) >> TEM_TEX_GEN_SHIFT; LLCtrlSelectionInterface* combobox_texgen = childGetSelectionInterface("combobox texgen"); if (combobox_texgen) { combobox_texgen->selectNthItem(selected_texgen); } else { llwarns << "failed childGetSelectionInterface for 'combobox texgen'" << llendl; } childSetEnabled("combobox texgen",editable); childSetTentative("combobox texgen",!identical); childSetEnabled("tex gen",editable); if (selected_texgen == 1) { childSetText("tex scale",getString("string repeats per meter")); childSetValue("TexScaleU", 2.0f * childGetValue("TexScaleU").asReal() ); childSetValue("TexScaleV", 2.0f * childGetValue("TexScaleV").asReal() ); } else { childSetText("tex scale",getString("string repeats per face")); } } { F32 fullbrightf = 0.f; struct f12 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { return (F32)(object->getTE(face)->getFullbright()); } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, fullbrightf ); childSetValue("checkbox fullbright",(S32)fullbrightf); childSetEnabled("checkbox fullbright",editable); childSetTentative("checkbox fullbright",!identical); } // Repeats per meter label { childSetEnabled("rpt",editable); } // Repeats per meter { F32 repeats = 1.f; struct f13 : public LLSelectedTEGetFunctor<F32> { F32 get(LLViewerObject* object, S32 face) { U32 s_axis = VX; U32 t_axis = VY; // BUG: Only repeats along S axis // BUG: Only works for boxes. LLPrimitive::getTESTAxes(face, &s_axis, &t_axis); return object->getTE(face)->mScaleS / object->getScale().mV[s_axis]; } } func; identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, repeats ); childSetValue("rptctrl", editable ? repeats : 0); childSetTentative("rptctrl",!identical); LLComboBox* mComboTexGen = getChild<LLComboBox>("combobox texgen"); if (mComboTexGen) { BOOL enabled = editable && (!mComboTexGen || mComboTexGen->getCurrentIndex() != 1); childSetEnabled("rptctrl",enabled); childSetEnabled("button apply",enabled); } } // Set variable values for numeric expressions calcp->setVar(LLCalc::TEX_U_SCALE, childGetValue("TexScaleU").asReal()); calcp->setVar(LLCalc::TEX_V_SCALE, childGetValue("TexScaleV").asReal()); calcp->setVar(LLCalc::TEX_U_OFFSET, childGetValue("TexOffsetU").asReal()); calcp->setVar(LLCalc::TEX_V_OFFSET, childGetValue("TexOffsetV").asReal()); calcp->setVar(LLCalc::TEX_ROTATION, childGetValue("TexRot").asReal()); calcp->setVar(LLCalc::TEX_TRANSPARENCY, childGetValue("ColorTrans").asReal()); calcp->setVar(LLCalc::TEX_GLOW, childGetValue("glow").asReal()); }
BOOL LLToolCamera::handleHover(S32 x, S32 y, MASK mask) { S32 dx = gViewerWindow->getCurrentMouseDX(); S32 dy = gViewerWindow->getCurrentMouseDY(); BOOL moved_outside_slop = FALSE; if (hasMouseCapture() && mValidClickPoint) { mAccumX += llabs(dx); mAccumY += llabs(dy); if (mAccumX >= SLOP_RANGE) { if (!mOutsideSlopX) { moved_outside_slop = TRUE; } mOutsideSlopX = TRUE; } if (mAccumY >= SLOP_RANGE) { if (!mOutsideSlopY) { moved_outside_slop = TRUE; } mOutsideSlopY = TRUE; } } if (mOutsideSlopX || mOutsideSlopY) { if (!mValidClickPoint) { lldebugst(LLERR_USER_INPUT) << "hover handled by LLToolFocus [invalid point]" << llendl; gViewerWindow->setCursor(UI_CURSOR_NO); gViewerWindow->showCursor(); return TRUE; } if (gCameraBtnOrbit || mask == MASK_ORBIT || mask == (MASK_ALT | MASK_ORBIT)) { // Orbit tool if (hasMouseCapture()) { const F32 RADIANS_PER_PIXEL = 360.f * DEG_TO_RAD / gViewerWindow->getWorldViewWidthScaled(); if (dx != 0) { gAgentCamera.cameraOrbitAround( -dx * RADIANS_PER_PIXEL ); } if (dy != 0) { gAgentCamera.cameraOrbitOver( -dy * RADIANS_PER_PIXEL ); } gViewerWindow->moveCursorToCenter(); } lldebugst(LLERR_USER_INPUT) << "hover handled by LLToolFocus [active]" << llendl; } else if ( gCameraBtnPan || mask == MASK_PAN || mask == (MASK_PAN | MASK_ALT) ) { // Pan tool if (hasMouseCapture()) { LLVector3d camera_to_focus = gAgentCamera.getCameraPositionGlobal(); camera_to_focus -= gAgentCamera.getFocusGlobal(); F32 dist = (F32) camera_to_focus.normVec(); // Fudge factor for pan F32 meters_per_pixel = 3.f * dist / gViewerWindow->getWorldViewWidthScaled(); if (dx != 0) { gAgentCamera.cameraPanLeft( dx * meters_per_pixel ); } if (dy != 0) { gAgentCamera.cameraPanUp( -dy * meters_per_pixel ); } gViewerWindow->moveCursorToCenter(); } lldebugst(LLERR_USER_INPUT) << "hover handled by LLToolPan" << llendl; } else if (gCameraBtnZoom) { // Zoom tool if (hasMouseCapture()) { const F32 RADIANS_PER_PIXEL = 360.f * DEG_TO_RAD / gViewerWindow->getWorldViewWidthScaled(); if (dx != 0) { gAgentCamera.cameraOrbitAround( -dx * RADIANS_PER_PIXEL ); } const F32 IN_FACTOR = 0.99f; if (dy != 0 && mOutsideSlopY ) { if (mMouseSteering) { gAgentCamera.cameraOrbitOver( -dy * RADIANS_PER_PIXEL ); } else { gAgentCamera.cameraZoomIn( pow( IN_FACTOR, dy ) ); } } gViewerWindow->moveCursorToCenter(); } lldebugst(LLERR_USER_INPUT) << "hover handled by LLToolZoom" << llendl; } } if (gCameraBtnOrbit || mask == MASK_ORBIT || mask == (MASK_ALT | MASK_ORBIT)) { gViewerWindow->setCursor(UI_CURSOR_TOOLCAMERA); } else if ( gCameraBtnPan || mask == MASK_PAN || mask == (MASK_PAN | MASK_ALT) ) { gViewerWindow->setCursor(UI_CURSOR_TOOLPAN); } else { gViewerWindow->setCursor(UI_CURSOR_TOOLZOOMIN); } return TRUE; }
void LLManip::renderTickValue(const LLVector3& pos, F32 value, const std::string& suffix, const LLColor4 &color) { LLLocale locale(LLLocale::USER_LOCALE); const LLFontGL* big_fontp = LLFontGL::getFontSansSerif(); const LLFontGL* small_fontp = LLFontGL::getFontSansSerifSmall(); std::string val_string; std::string fraction_string; F32 val_to_print = llround(value, 0.001f); S32 fractional_portion = llround(fmodf(llabs(val_to_print), 1.f) * 100.f); if (val_to_print < 0.f) { if (fractional_portion == 0) { val_string = llformat("-%d%s", lltrunc(llabs(val_to_print)), suffix.c_str()); } else { val_string = llformat("-%d", lltrunc(llabs(val_to_print))); } } else { if (fractional_portion == 0) { val_string = llformat("%d%s", lltrunc(llabs(val_to_print)), suffix.c_str()); } else { val_string = llformat("%d", lltrunc(val_to_print)); } } BOOL hud_selection = mObjectSelection->getSelectType() == SELECT_TYPE_HUD; gGL.matrixMode(LLRender::MM_MODELVIEW); gGL.pushMatrix(); LLVector3 render_pos = pos; if (hud_selection) { F32 zoom_amt = gAgentCamera.mHUDCurZoom; F32 inv_zoom_amt = 1.f / zoom_amt; // scale text back up to counter-act zoom level render_pos = pos * zoom_amt; gGL.scalef(inv_zoom_amt, inv_zoom_amt, inv_zoom_amt); } LLColor4 shadow_color = LLColor4::black; shadow_color.mV[VALPHA] = color.mV[VALPHA] * 0.5f; if (fractional_portion != 0) { fraction_string = llformat("%c%02d%s", LLResMgr::getInstance()->getDecimalPoint(), fractional_portion, suffix.c_str()); gViewerWindow->setup3DViewport(1, -1); hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, LLFontGL::NO_SHADOW, -1.f * big_fontp->getWidthF32(val_string), 3.f, shadow_color, hud_selection); hud_render_utf8text(fraction_string, render_pos, *small_fontp, LLFontGL::NORMAL, LLFontGL::NO_SHADOW, 1.f, 3.f, shadow_color, hud_selection); gViewerWindow->setup3DViewport(); hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, LLFontGL::NO_SHADOW, -1.f * big_fontp->getWidthF32(val_string), 3.f, color, hud_selection); hud_render_utf8text(fraction_string, render_pos, *small_fontp, LLFontGL::NORMAL, LLFontGL::NO_SHADOW, 1.f, 3.f, color, hud_selection); } else { gViewerWindow->setup3DViewport(1, -1); hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, LLFontGL::NO_SHADOW, -0.5f * big_fontp->getWidthF32(val_string), 3.f, shadow_color, hud_selection); gViewerWindow->setup3DViewport(); hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, LLFontGL::NO_SHADOW, -0.5f * big_fontp->getWidthF32(val_string), 3.f, color, hud_selection); } gGL.popMatrix(); }
/* check time difference between the replicas */ time_t csync_timediff(CSYNC *ctx) { time_t timediff = -1; char errbuf[256] = {0}; char *luri = NULL; char *ruri = NULL; csync_vio_handle_t *fp = NULL; csync_vio_file_stat_t *st = NULL; csync_vio_handle_t *dp = NULL; /* try to open remote dir to get auth */ ctx->replica = ctx->remote.type; dp = csync_vio_opendir(ctx, ctx->remote.uri); if (dp == NULL) { /* * To prevent problems especially with pam_csync we shouldn't try to create the * remote directory here. Just fail! */ strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Access dienied to remote uri: %s - %s", ctx->remote.uri, errbuf); return -1; } csync_vio_closedir(ctx, dp); if (asprintf(&luri, "%s/.csync_timediff.ctmp", ctx->local.uri) < 0) { goto out; } if (asprintf(&ruri, "%s/.csync_timediff.ctmp", ctx->remote.uri) < 0) { goto out; } /* create temporary file on local */ ctx->replica = ctx->local.type; fp = csync_vio_creat(ctx, luri, 0644); if (fp == NULL) { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Unable to create temporary file: %s - %s", luri, errbuf); goto out; } csync_vio_close(ctx, fp); /* Get the modification time */ st = csync_vio_file_stat_new(); if (csync_vio_stat(ctx, luri, st) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Synchronisation is not possible! %s - %s", luri, errbuf); goto out; } timediff = st->mtime; csync_vio_file_stat_destroy(st); st = NULL; /* create temporary file on remote replica */ ctx->replica = ctx->remote.type; fp = csync_vio_creat(ctx, ruri, 0644); if (fp == NULL) { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Unable to create temporary file: %s - %s", ruri, errbuf); goto out; } csync_vio_close(ctx, fp); /* Get the modification time */ st = csync_vio_file_stat_new(); if (csync_vio_stat(ctx, ruri, st) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); CSYNC_LOG(CSYNC_LOG_PRIORITY_FATAL, "Synchronisation is not possible! %s - %s", ruri, errbuf); goto out; } /* calc time difference */ timediff = llabs(timediff - st->mtime); CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Time difference: %ld seconds", timediff); out: csync_vio_file_stat_destroy(st); ctx->replica = ctx->local.type; csync_vio_unlink(ctx, luri); SAFE_FREE(luri); ctx->replica = ctx->remote.type; csync_vio_unlink(ctx, ruri); SAFE_FREE(ruri); return timediff; }
void LLTracker::drawMarker(const LLVector3d& pos_global, const LLColor4& color) { // get position LLVector3 pos_local = gAgent.getPosAgentFromGlobal(pos_global); // check in frustum LLCoordGL screen; S32 x = 0; S32 y = 0; const BOOL CLAMP = TRUE; if (LLViewerCamera::getInstance()->projectPosAgentToScreen(pos_local, screen, CLAMP) || LLViewerCamera::getInstance()->projectPosAgentToScreenEdge(pos_local, screen) ) { gHUDView->screenPointToLocal(screen.mX, screen.mY, &x, &y); // the center of the rendered position of the arrow obeys // the following rules: // (1) it lies on an ellipse centered on the target position // (2) it lies on the line between the target and the window center // (3) right now the radii of the ellipse are fixed, but eventually // they will be a function of the target text // // from those rules we can compute the position of the // lower left corner of the image LLRect rect = gHUDView->getRect(); S32 x_center = lltrunc(0.5f * (F32)rect.getWidth()); S32 y_center = lltrunc(0.5f * (F32)rect.getHeight()); x = x - x_center; // x and y relative to center y = y - y_center; F32 dist = sqrt((F32)(x*x + y*y)); S32 half_arrow_size = lltrunc(0.5f * HUD_ARROW_SIZE); if (dist > 0.f) { const F32 ARROW_ELLIPSE_RADIUS_X = 2 * HUD_ARROW_SIZE; const F32 ARROW_ELLIPSE_RADIUS_Y = HUD_ARROW_SIZE; // compute where the arrow should be F32 x_target = (F32)(x + x_center) - (ARROW_ELLIPSE_RADIUS_X * ((F32)x / dist) ); F32 y_target = (F32)(y + y_center) - (ARROW_ELLIPSE_RADIUS_Y * ((F32)y / dist) ); // keep the arrow within the window F32 x_clamped = llclamp( x_target, (F32)half_arrow_size, (F32)(rect.getWidth() - half_arrow_size)); F32 y_clamped = llclamp( y_target, (F32)half_arrow_size, (F32)(rect.getHeight() - half_arrow_size)); F32 slope = (F32)(y) / (F32)(x); F32 window_ratio = (F32)(rect.getHeight() - HUD_ARROW_SIZE) / (F32)(rect.getWidth() - HUD_ARROW_SIZE); // if the arrow has been clamped on one axis // then we need to compute the other axis if (llabs(slope) > window_ratio) { if (y_clamped != (F32)y_target) { // clamp by y x_clamped = (y_clamped - (F32)y_center) / slope + (F32)x_center; } } else if (x_clamped != (F32)x_target) { // clamp by x y_clamped = (x_clamped - (F32)x_center) * slope + (F32)y_center; } mHUDArrowCenterX = lltrunc(x_clamped); mHUDArrowCenterY = lltrunc(y_clamped); } else { // recycle the old values x = mHUDArrowCenterX - x_center; y = mHUDArrowCenterY - y_center; } F32 angle = atan2( (F32)y, (F32)x ); gl_draw_scaled_rotated_image(mHUDArrowCenterX - half_arrow_size, mHUDArrowCenterY - half_arrow_size, HUD_ARROW_SIZE, HUD_ARROW_SIZE, RAD_TO_DEG * angle, LLWorldMapView::sTrackArrowImage->getImage(), color); } }
int main(int argc, char *argv[]) { int i, j; uint64_t sse = 0; double sse_d = 0.0; FILE *f[2]; uint8_t buf[2][SIZE]; int len = 1; int64_t max; int shift = argc < 5 ? 0 : atoi(argv[4]); int skip_bytes = argc < 6 ? 0 : atoi(argv[5]); int size0 = 0; int size1 = 0; uint64_t maxdist = 0; double maxdist_d = 0.0; if (argc < 3) { printf("tiny_psnr <file1> <file2> [<elem size> [<shift> [<skip bytes>]]]\n"); printf("WAV headers are skipped automatically.\n"); return 1; } if (argc > 3) { if (!strcmp(argv[3], "u8")) { len = 1; } else if (!strcmp(argv[3], "s16")) { len = 2; } else if (!strcmp(argv[3], "f32")) { len = 4; } else if (!strcmp(argv[3], "f64")) { len = 8; } else { char *end; len = strtol(argv[3], &end, 0); if (*end || len < 1 || len > 2) { fprintf(stderr, "Unsupported sample format: %s\n", argv[3]); return 1; } } } max = (1LL << (8 * len)) - 1; f[0] = fopen(argv[1], "rb"); f[1] = fopen(argv[2], "rb"); if (!f[0] || !f[1]) { fprintf(stderr, "Could not open input files.\n"); return 1; } for (i = 0; i < 2; i++) { uint8_t *p = buf[i]; if (fread(p, 1, 12, f[i]) != 12) return 1; if (!memcmp(p, "RIFF", 4) && !memcmp(p + 8, "WAVE", 4)) { if (fread(p, 1, 8, f[i]) != 8) return 1; while (memcmp(p, "data", 4)) { int s = p[4] | p[5] << 8 | p[6] << 16 | p[7] << 24; fseek(f[i], s, SEEK_CUR); if (fread(p, 1, 8, f[i]) != 8) return 1; } } else { fseek(f[i], -12, SEEK_CUR); } } fseek(f[shift < 0], abs(shift), SEEK_CUR); fseek(f[0], skip_bytes, SEEK_CUR); fseek(f[1], skip_bytes, SEEK_CUR); for (;;) { int s0 = fread(buf[0], 1, SIZE, f[0]); int s1 = fread(buf[1], 1, SIZE, f[1]); for (j = 0; j < FFMIN(s0, s1); j += len) { switch (len) { case 1: case 2: { int64_t a = buf[0][j]; int64_t b = buf[1][j]; int dist; if (len == 2) { a = get_s16l(buf[0] + j); b = get_s16l(buf[1] + j); } else { a = buf[0][j]; b = buf[1][j]; } sse += (a - b) * (a - b); dist = llabs(a - b); if (dist > maxdist) maxdist = dist; break; } case 4: case 8: { double dist, a, b; if (len == 8) { a = get_f64l(buf[0] + j); b = get_f64l(buf[1] + j); } else { a = get_f32l(buf[0] + j); b = get_f32l(buf[1] + j); } dist = fabs(a - b); sse_d += (a - b) * (a - b); if (dist > maxdist_d) maxdist_d = dist; break; } } } size0 += s0; size1 += s1; if (s0 + s1 <= 0) break; } i = FFMIN(size0, size1) / len; if (!i) i = 1; switch (len) { case 1: case 2: { uint64_t psnr; uint64_t dev = int_sqrt(((sse / i) * F * F) + (((sse % i) * F * F) + i / 2) / i); if (sse) psnr = ((2 * log16(max << 16) + log16(i) - log16(sse)) * 284619LL * F + (1LL << 31)) / (1LL << 32); else psnr = 1000 * F - 1; // floating point free infinity :) printf("stddev:%5d.%02d PSNR:%3d.%02d MAXDIFF:%5"PRIu64" bytes:%9d/%9d\n", (int)(dev / F), (int)(dev % F), (int)(psnr / F), (int)(psnr % F), maxdist, size0, size1); break; } case 4: case 8: { char psnr_str[64]; double dev = sqrt(sse_d / i); uint64_t scale = (len == 4) ? (1ULL << 24) : (1ULL << 32); if (sse_d) { double psnr = 2 * log(DBL_MAX) - log(i / sse_d); snprintf(psnr_str, sizeof(psnr_str), "%5.02f", psnr); } else snprintf(psnr_str, sizeof(psnr_str), "inf"); maxdist = maxdist_d * scale; printf("stddev:%10.2f PSNR:%s MAXDIFF:%10"PRIu64" bytes:%9d/%9d\n", dev * scale, psnr_str, maxdist, size0, size1); break; } } return 0; }
ib_status_t ib_field_convert( ib_mpool_t *mp, const ib_ftype_t desired_type, const ib_field_t *in_field, ib_field_t **out_field ) { assert(mp); assert(in_field); ib_status_t rc; /* Holder values for in_field values before being set in out_field. */ size_t sz; const char *str; const ib_bytestr_t *bstr; ib_num_t num; ib_time_t tme; ib_float_t flt; void *new_field_value; if (in_field->type == desired_type) { *out_field = NULL; return IB_OK; } switch (in_field->type) { case IB_FTYPE_NULSTR: /* Extract string. Note that a zero-length nulstr field can * have a NULL value in the union. */ if ( (in_field->val->u.nulstr == NULL) && (in_field->val->pval == NULL) ) { str = ""; } else { rc = ib_field_value(in_field, ib_ftype_nulstr_out(&str)); if (rc != IB_OK){ return rc; } } switch (desired_type) { case IB_FTYPE_BYTESTR: rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mp, str); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_TIME: rc = ib_string_to_time(str, &tme); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_NUM: rc = ib_string_to_num(str, 0, &num); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_num_in(&num); break; case IB_FTYPE_FLOAT: rc = ib_string_to_float(str, &flt); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_BYTESTR: /* Extract bytestr. */ rc = ib_field_value(in_field, ib_ftype_bytestr_out(&bstr)); if (rc != IB_OK){ return rc; } str = (const char *)ib_bytestr_const_ptr(bstr); sz = ib_bytestr_length(bstr); /* Convert byte str. */ switch(desired_type) { case IB_FTYPE_NULSTR: str = ib_mpool_memdup_to_str(mp, str, sz); if (!str) { return rc; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_TIME: rc = ib_string_to_time_ex(str, sz, &tme); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_NUM: rc = ib_string_to_num_ex(str, sz, 0, &num); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_num_in(&num); break; case IB_FTYPE_FLOAT: rc = ib_string_to_float_ex(str, sz, &flt); if (rc != IB_OK) { return rc; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_TIME: /* Extract time. */ rc = ib_field_value(in_field, ib_ftype_time_out(&tme)); if (rc != IB_OK){ return rc; } switch (desired_type) { case IB_FTYPE_NULSTR: str = ib_time_to_string(mp, tme); if (! str) { return IB_EINVAL; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_BYTESTR: str = ib_time_to_string(mp, tme); if (! str) { return IB_EINVAL; } rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mp, str); if (rc != IB_OK){ return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_FLOAT: flt = (ib_float_t)tme; /* Check that our assignment is within error=1, or fail. */ if (llabs(tme - flt) > 1) { return IB_EINVAL; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_NUM: /* Extract unum. */ rc = ib_field_value(in_field, ib_ftype_num_out(&num)); if (rc != IB_OK){ return rc; } switch (desired_type) { case IB_FTYPE_NULSTR: str = ib_num_to_string(mp, num); if (! str) { return IB_EINVAL; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_BYTESTR: str = ib_num_to_string(mp, num); if (! str) { return IB_EINVAL; } rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mp, str); if (rc != IB_OK){ return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_TIME: if (num < 0) { return IB_EINVAL; } tme = (ib_time_t)num; new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_FLOAT: flt = (ib_float_t)num; if (llabs(flt - num) > 1) { return IB_EINVAL; } new_field_value = ib_ftype_float_in(&flt); break; default: return IB_EINVAL; } break; case IB_FTYPE_FLOAT: /* Extract unum. */ rc = ib_field_value(in_field, ib_ftype_float_out(&flt)); if (rc != IB_OK){ return rc; } switch (desired_type) { case IB_FTYPE_NULSTR: str = ib_float_to_string(mp, flt); if (!str) { return IB_EINVAL; } new_field_value = ib_ftype_nulstr_in(str); break; case IB_FTYPE_BYTESTR: str = ib_float_to_string(mp, flt); if (!str) { return IB_EINVAL; } rc = ib_bytestr_dup_nulstr((ib_bytestr_t **)&bstr, mp, str); if (rc != IB_OK){ return rc; } new_field_value = ib_ftype_bytestr_in(bstr); break; case IB_FTYPE_TIME: if (flt < 0) { return IB_EINVAL; } tme = (ib_float_t)flt; new_field_value = ib_ftype_time_in(&tme); break; case IB_FTYPE_NUM: num = (ib_float_t)flt; new_field_value = ib_ftype_num_in(&num); break; default: return IB_EINVAL; } break; default: return IB_EINVAL; } rc = ib_field_create( out_field, mp, in_field->name, in_field->nlen, desired_type, new_field_value ); return rc; }
//Based on trapez_motion_2.m //Assumes 0 initial speed long long trapez_gen_motion_1(long long pos_i, long long pos_f, long long spd_max, long long a) { long long abs_d_pos = 0, abs_acc_pos = 0, dual_abs_acc_pos = 0; //spd_max & a have to be positive spd_max = llabs(spd_max); a = llabs(a); //Compute parameters (in global variables) trapez_compute_params(pos_i, pos_f, spd_max, a); //Absolute values abs_d_pos = llabs(d_pos); abs_acc_pos = llabs(acc_pos); dual_abs_acc_pos = 2*abs_acc_pos; #ifdef DEBUGGING_OUTPUT printf("d_pos = %lld, abs_d_pos = %lld.\n", d_pos, abs_d_pos); printf("1) acc_pos = %lld, abs_acc_pos = %lld.\n", acc_pos, abs_acc_pos); #endif //It's possible to overshoot position if the acceleration is too low. //In that case we should sacrifice the top speed if(dual_abs_acc_pos > abs_d_pos) { #ifdef DEBUGGING_OUTPUT printf("Position overshoot.\n"); #endif //New top speed: spd_max = sqrt(a*abs_d_pos); #ifdef DEBUGGING_OUTPUT printf("New spd_max: %lld.\n", spd_max); #endif //Redo the initial math: //Compute parameters (in global variables) trapez_compute_params(pos_i, pos_f, spd_max, a); //Absolute values (they probably changed) abs_d_pos = abs(d_pos); abs_acc_pos = abs(acc_pos); dual_abs_acc_pos = 2*abs_acc_pos; } //Plateau - constant speed #ifdef DEBUGGING_OUTPUT printf("d_pos = %lld, abs_d_pos = %lld.\n", d_pos, abs_d_pos); printf("2) acc_pos = %lld, abs_acc_pos = %lld.\n", acc_pos, abs_acc_pos); #endif cte_spd_pos = abs_d_pos - (2*abs_acc_pos); if(spd_max == 0) spd_max = 1; //Prevents div/0 cte_spd_pos_discrete = (SPD_FACTOR*cte_spd_pos/spd_max)*TRAPEZ_ONE_OVER_DT; cte_spd_pos_discrete = cte_spd_pos_discrete / SPD_FACTOR; #ifdef DEBUGGING_OUTPUT printf("cte_spd_pos = %lld, cte_spd_pos_discrete = %lld.\n", cte_spd_pos, cte_spd_pos_discrete); #endif if(cte_spd_pos_discrete < 0) { cte_spd_pos_discrete = 0; #ifdef DEBUGGING_OUTPUT printf("No steady speed!\n"); #endif } //Transitions: trapez_transitions[0] = a_t_discrete; trapez_transitions[1] = a_t_discrete + cte_spd_pos_discrete; trapez_transitions[2] = 2*a_t_discrete + cte_spd_pos_discrete; #ifdef DEBUGGING_OUTPUT printf("tr[0] = %lld, tr[1] = %lld, tr[2] = %lld.\n", trapez_transitions[0], trapez_transitions[1], trapez_transitions[2]); #endif pos_step = 0; //Variable used to output the current position command return (2*a_t_discrete + cte_spd_pos_discrete); //Returns the number of steps }
static bool process_audio_delay(struct audio_monitor *monitor, float **data, uint32_t *frames, uint64_t ts, uint32_t pad) { obs_source_t *s = monitor->source; uint64_t last_frame_ts = s->last_frame_ts; uint64_t cur_time = os_gettime_ns(); uint64_t front_ts; uint64_t cur_ts; int64_t diff; uint32_t blocksize = monitor->channels * sizeof(float); /* cut off audio if long-since leftover audio in delay buffer */ if (cur_time - monitor->last_recv_time > 1000000000) circlebuf_free(&monitor->delay_buffer); monitor->last_recv_time = cur_time; ts += monitor->source->sync_offset; circlebuf_push_back(&monitor->delay_buffer, &ts, sizeof(ts)); circlebuf_push_back(&monitor->delay_buffer, frames, sizeof(*frames)); circlebuf_push_back(&monitor->delay_buffer, *data, *frames * blocksize); if (!monitor->prev_video_ts) { monitor->prev_video_ts = last_frame_ts; } else if (monitor->prev_video_ts == last_frame_ts) { monitor->time_since_prev += (uint64_t)*frames * 1000000000ULL / (uint64_t)monitor->sample_rate; } else { monitor->time_since_prev = 0; } while (monitor->delay_buffer.size != 0) { size_t size; bool bad_diff; circlebuf_peek_front(&monitor->delay_buffer, &cur_ts, sizeof(ts)); front_ts = cur_ts - ((uint64_t)pad * 1000000000ULL / (uint64_t)monitor->sample_rate); diff = (int64_t)front_ts - (int64_t)last_frame_ts; bad_diff = !last_frame_ts || llabs(diff) > 5000000000 || monitor->time_since_prev > 100000000ULL; /* delay audio if rushing */ if (!bad_diff && diff > 75000000) { #ifdef DEBUG_AUDIO blog(LOG_INFO, "audio rushing, cutting audio, " "diff: %lld, delay buffer size: %lu, " "v: %llu: a: %llu", diff, (int)monitor->delay_buffer.size, last_frame_ts, front_ts); #endif return false; } circlebuf_pop_front(&monitor->delay_buffer, NULL, sizeof(ts)); circlebuf_pop_front(&monitor->delay_buffer, frames, sizeof(*frames)); size = *frames * blocksize; da_resize(monitor->buf, size); circlebuf_pop_front(&monitor->delay_buffer, monitor->buf.array, size); /* cut audio if dragging */ if (!bad_diff && diff < -75000000 && monitor->delay_buffer.size > 0) { #ifdef DEBUG_AUDIO blog(LOG_INFO, "audio dragging, cutting audio, " "diff: %lld, delay buffer size: %lu, " "v: %llu: a: %llu", diff, (int)monitor->delay_buffer.size, last_frame_ts, front_ts); #endif continue; } *data = monitor->buf.array; return true; } return false; }
// Return TRUE if character has to update visual params. BOOL LLPhysicsMotion::onUpdate(F32 time) { // static FILE *mFileWrite = fopen("c:\\temp\\avatar_data.txt","w"); if (!mParamDriver) return FALSE; if (!mLastTime) { mLastTime = time; return FALSE; } //////////////////////////////////////////////////////////////////////////////// // Get all parameters and settings // const F32 time_delta = time - mLastTime; // Don't update too frequently, to avoid precision errors from small time slices. if (time_delta <= .01) { return FALSE; } // If less than 1FPS, we don't want to be spending time updating physics at all. if (time_delta > 1.0) { mLastTime = time; return FALSE; } // Higher LOD is better. This controls the granularity // and frequency of updates for the motions. const F32 lod_factor = LLVOAvatar::sPhysicsLODFactor; if (lod_factor == 0) { return TRUE; } LLJoint *joint = mJointState->getJoint(); const F32 behavior_mass = getParamValue("Mass"); const F32 behavior_gravity = getParamValue("Gravity"); const F32 behavior_spring = getParamValue("Spring"); const F32 behavior_gain = getParamValue("Gain"); const F32 behavior_damping = getParamValue("Damping"); const F32 behavior_drag = getParamValue("Drag"); const BOOL physics_test = FALSE; // Enable this to simulate bouncing on all parts. F32 behavior_maxeffect = getParamValue("MaxEffect"); if (physics_test) behavior_maxeffect = 1.0f; // Normalize the param position to be from [0,1]. // We have to use normalized values because there may be more than one driven param, // and each of these driven params may have its own range. // This means we'll do all our calculations in normalized [0,1] local coordinates. const F32 position_user_local = (mParamDriver->getWeight() - mParamDriver->getMinWeight()) / (mParamDriver->getMaxWeight() - mParamDriver->getMinWeight()); // // End parameters and settings //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Calculate velocity and acceleration in parameter space. // //const F32 velocity_joint_local = calculateVelocity_local(time_iteration_step); const F32 velocity_joint_local = calculateVelocity_local(); const F32 acceleration_joint_local = calculateAcceleration_local(velocity_joint_local); // // End velocity and acceleration //////////////////////////////////////////////////////////////////////////////// BOOL update_visuals = FALSE; // Break up the physics into a bunch of iterations so that differing framerates will show // roughly the same behavior. for (F32 time_iteration = 0; time_iteration <= time_delta; time_iteration += TIME_ITERATION_STEP) { F32 time_iteration_step = TIME_ITERATION_STEP; if (time_iteration + TIME_ITERATION_STEP > time_delta) { time_iteration_step = time_delta-time_iteration; } // mPositon_local should be in normalized 0,1 range already. Just making sure... const F32 position_current_local = llclamp(mPosition_local, 0.0f, 1.0f); // If the effect is turned off then don't process unless we need one more update // to set the position to the default (i.e. user) position. if ((behavior_maxeffect == 0) && (position_current_local == position_user_local)) { return update_visuals; } //////////////////////////////////////////////////////////////////////////////// // Calculate the total force // // Spring force is a restoring force towards the original user-set breast position. // F = kx const F32 spring_length = position_current_local - position_user_local; const F32 force_spring = -spring_length * behavior_spring; // Acceleration is the force that comes from the change in velocity of the torso. // F = ma const F32 force_accel = behavior_gain * (acceleration_joint_local * behavior_mass); // Gravity always points downward in world space. // F = mg const LLVector3 gravity_world(0,0,1); const F32 force_gravity = (toLocal(gravity_world) * behavior_gravity * behavior_mass); // Damping is a restoring force that opposes the current velocity. // F = -kv const F32 force_damping = -behavior_damping * mVelocity_local; // Drag is a force imparted by velocity (intuitively it is similar to wind resistance) // F = .5kv^2 const F32 force_drag = .5*behavior_drag*velocity_joint_local*velocity_joint_local*llsgn(velocity_joint_local); const F32 force_net = (force_accel + force_gravity + force_spring + force_damping + force_drag); // // End total force //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Calculate new params // // Calculate the new acceleration based on the net force. // a = F/m const F32 acceleration_new_local = force_net / behavior_mass; static const F32 max_velocity = 100.0f; // magic number, used to be customizable. F32 velocity_new_local = mVelocity_local + acceleration_new_local*time_iteration_step; velocity_new_local = llclamp(velocity_new_local, -max_velocity, max_velocity); // Temporary debugging setting to cause all avatars to move, for profiling purposes. if (physics_test) { velocity_new_local = sin(time*4.0); } // Calculate the new parameters, or remain unchanged if max speed is 0. F32 position_new_local = position_current_local + velocity_new_local*time_iteration_step; if (behavior_maxeffect == 0) position_new_local = position_user_local; // Zero out the velocity if the param is being pushed beyond its limits. if ((position_new_local < 0 && velocity_new_local < 0) || (position_new_local > 1 && velocity_new_local > 0)) { velocity_new_local = 0; } // Check for NaN values. A NaN value is detected if the variables doesn't equal itself. // If NaN, then reset everything. if ((mPosition_local != mPosition_local) || (mVelocity_local != mVelocity_local) || (position_new_local != position_new_local)) { position_new_local = 0; mVelocity_local = 0; mVelocityJoint_local = 0; mAccelerationJoint_local = 0; mPosition_local = 0; mPosition_world = LLVector3(0,0,0); } const F32 position_new_local_clamped = llclamp(position_new_local, 0.0f, 1.0f); LLDriverParam *driver_param = dynamic_cast<LLDriverParam *>(mParamDriver); llassert_always(driver_param); if (driver_param) { // If this is one of our "hidden" driver params, then make sure it's // the default value. if ((driver_param->getGroup() != VISUAL_PARAM_GROUP_TWEAKABLE) && (driver_param->getGroup() != VISUAL_PARAM_GROUP_TWEAKABLE_NO_TRANSMIT)) { mCharacter->setVisualParamWeight(driver_param, 0, FALSE); } for (LLDriverParam::entry_list_t::iterator iter = driver_param->mDriven.begin(); iter != driver_param->mDriven.end(); ++iter) { LLDrivenEntry &entry = (*iter); LLViewerVisualParam *driven_param = entry.mParam; setParamValue(driven_param,position_new_local_clamped, behavior_maxeffect); } } // // End calculate new params //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Conditionally update the visual params // // Updating the visual params (i.e. what the user sees) is fairly expensive. // So only update if the params have changed enough, and also take into account // the graphics LOD settings. // For non-self, if the avatar is small enough visually, then don't update. const F32 area_for_max_settings = 0.0; const F32 area_for_min_settings = 1400.0; const F32 area_for_this_setting = area_for_max_settings + (area_for_min_settings-area_for_max_settings)*(1.0-lod_factor); const F32 pixel_area = (F32) sqrt(mCharacter->getPixelArea()); const BOOL is_self = (dynamic_cast<LLVOAvatar *>(mCharacter) != NULL && ((LLVOAvatar*)mCharacter)->isSelf()); if ((pixel_area > area_for_this_setting) || is_self) { const F32 position_diff_local = llabs(mPositionLastUpdate_local-position_new_local_clamped); const F32 min_delta = (1.0001f-lod_factor)*0.4f; if (llabs(position_diff_local) > min_delta) { update_visuals = TRUE; mPositionLastUpdate_local = position_new_local; } } // // End update visual params //////////////////////////////////////////////////////////////////////////////// mVelocity_local = velocity_new_local; mAccelerationJoint_local = acceleration_joint_local; mPosition_local = position_new_local; } mLastTime = time; mPosition_world = joint->getWorldPosition(); mVelocityJoint_local = velocity_joint_local; /* // Write out debugging info into a spreadsheet. if (mFileWrite != NULL && is_self) { fprintf(mFileWrite,"%f\t%f\t%f \t\t%f \t\t%f\t%f\t%f\t \t\t%f\t%f\t%f\t%f\t%f \t\t%f\t%f\t%f\n", position_new_local, velocity_new_local, acceleration_new_local, time_delta, mPosition_world[0], mPosition_world[1], mPosition_world[2], force_net, force_spring, force_accel, force_damping, force_drag, spring_length, velocity_joint_local, acceleration_joint_local ); } */ return update_visuals; }
/** * Callback for solver to notify about assignment changes * * @param cls NULL * @param address the address with changes */ static void bandwidth_changed_cb (void *cls, struct ATS_Address *address) { long long diff_out; long long diff_in; GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bandwidth assignment changed for peer %s to %u/%u\n", GNUNET_i2s (&address->peer), (unsigned int) address->assigned_bw_in, (unsigned int) address->assigned_bw_out); GAS_reservations_set_bandwidth (&address->peer, GNUNET_BANDWIDTH_value_init (address->assigned_bw_in)); /* Notify performance clients about changes to address */ GAS_performance_notify_all_clients (&address->peer, address->plugin, address->addr, address->addr_len, address->active, &address->properties, address->local_address_info, GNUNET_BANDWIDTH_value_init (address->assigned_bw_out), GNUNET_BANDWIDTH_value_init (address->assigned_bw_in)); if ( (0 == address->assigned_bw_in) && (0 == address->assigned_bw_out) ) { GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Telling transport to disconnect peer `%s'\n", GNUNET_i2s (&address->peer)); /* Notify scheduling clients about suggestion */ GAS_scheduling_transmit_address_suggestion (&address->peer, address->session_id, GNUNET_BANDWIDTH_ZERO, GNUNET_BANDWIDTH_ZERO); return; } /* Do bandwidth stability check */ diff_out = llabs ((long long) address->assigned_bw_out - (long long) address->last_notified_bw_out); diff_in = llabs ((long long) address->assigned_bw_in - (long long) address->last_notified_bw_in); if ( (diff_out < htonl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) && (diff_in < htonl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) ) { GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bandwidth change too small, not notifying client\n"); return; } GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending bandwidth update for peer `%s': %u/%u\n", GNUNET_i2s (&address->peer), address->assigned_bw_out, address->assigned_bw_out); /* *Notify scheduling clients about suggestion */ GAS_scheduling_transmit_address_suggestion (&address->peer, address->session_id, GNUNET_BANDWIDTH_value_init (address->assigned_bw_out), GNUNET_BANDWIDTH_value_init (address->assigned_bw_in)); address->last_notified_bw_out = address->assigned_bw_out; address->last_notified_bw_in = address->assigned_bw_in; }
int main(int argc, char** argv) { printf("%lld,%lld\n", llabs(-576460752303423489), llabs(576460752303423489)); return 0; }
bool ContainerParser::TimestampsFuzzyEqual(int64_t aLhs, int64_t aRhs) { return llabs(aLhs - aRhs) <= GetRoundingError(); }
U8* LLBufferArray::seek( S32 channel, U8* start, S32 delta) const { LLMemType m1(LLMemType::MTYPE_IO_BUFFER); const_segment_iterator_t it; const_segment_iterator_t end = mSegments.end(); U8* rv = start; if(0 == delta) { if((U8*)npos == start) { // someone is looking for end of data. segment_list_t::const_reverse_iterator rit = mSegments.rbegin(); segment_list_t::const_reverse_iterator rend = mSegments.rend(); while(rit != rend) { if(!((*rit).isOnChannel(channel))) { ++rit; continue; } rv = (*rit).data() + (*rit).size(); break; } } else if(start) { // This is sort of a weird case - check if zero bytes away // from current position is on channel and return start if // that is true. Otherwise, return NULL. it = getSegment(start); if((it == end) || !(*it).isOnChannel(channel)) { rv = NULL; } } else { // Start is NULL, so return the very first byte on the // channel, or NULL. it = mSegments.begin(); while((it != end) && !(*it).isOnChannel(channel)) { ++it; } if(it != end) { rv = (*it).data(); } } return rv; } if(start) { it = getSegment(start); if((it != end) && (*it).isOnChannel(channel)) { if(delta > 0) { S32 bytes_in_segment = (*it).size() - (start - (*it).data()); S32 local_delta = llmin(delta, bytes_in_segment); rv += local_delta; delta -= local_delta; ++it; } else { S32 bytes_in_segment = start - (*it).data(); S32 local_delta = llmin(llabs(delta), bytes_in_segment); rv -= local_delta; delta += local_delta; } } } else if(delta < 0) { // start is NULL, and delta indicates seeking backwards - // return NULL. return NULL; } else { // start is NULL and delta > 0 it = mSegments.begin(); } if(delta > 0) { // At this point, we have an iterator into the segments, and // are seeking forward until delta is zero or we run out while(delta && (it != end)) { if(!((*it).isOnChannel(channel))) { ++it; continue; } if(delta <= (*it).size()) { // it's in this segment rv = (*it).data() + delta; } delta -= (*it).size(); ++it; } if(delta && (it == end)) { // Whoops - sought past end. rv = NULL; } } else //if(delta < 0) { // We are at the beginning of a segment, and need to search // backwards. segment_list_t::const_reverse_iterator rit(it); segment_list_t::const_reverse_iterator rend = mSegments.rend(); while(delta && (rit != rend)) { if(!((*rit).isOnChannel(channel))) { ++rit; continue; } if(llabs(delta) <= (*rit).size()) { // it's in this segment. rv = (*rit).data() + (*rit).size() + delta; delta = 0; } else { delta += (*rit).size(); } ++rit; } if(delta && (rit == rend)) { // sought past the beginning. rv = NULL; } } return rv; }
string Func_sec_to_time::getStrVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull, CalpontSystemCatalog::ColType& ct) { int64_t val = 0; CalpontSystemCatalog::ColType curCt = parm[0]->data()->resultType(); switch (parm[0]->data()->resultType().colDataType) { case execplan::CalpontSystemCatalog::BIGINT: case execplan::CalpontSystemCatalog::INT: case execplan::CalpontSystemCatalog::MEDINT: case execplan::CalpontSystemCatalog::TINYINT: case execplan::CalpontSystemCatalog::SMALLINT: case execplan::CalpontSystemCatalog::UBIGINT: case execplan::CalpontSystemCatalog::UINT: case execplan::CalpontSystemCatalog::UMEDINT: case execplan::CalpontSystemCatalog::UTINYINT: case execplan::CalpontSystemCatalog::USMALLINT: { val = parm[0]->data()->getIntVal(row, isNull); } break; case execplan::CalpontSystemCatalog::DOUBLE: { const string& valStr = parm[0]->data()->getStrVal(row, isNull); val = parm[0]->data()->getIntVal(row, isNull); size_t x = valStr.find("."); if ( x < string::npos) { string tmp = valStr.substr(x+1,1); char * ptr = &tmp[0]; int i = atoi(ptr); if (i >= 5) { if (val > 0) val += 1; else val -=1; } } } break; case execplan::CalpontSystemCatalog::FLOAT: { const string& valStr = parm[0]->data()->getStrVal(row, isNull); val = parm[0]->data()->getIntVal(row, isNull); size_t x = valStr.find("."); if ( x < string::npos) { string tmp = valStr.substr(x+1,1); char * ptr = &tmp[0]; int i = atoi(ptr); if (i >= 5) { if (val > 0) val += 1; else val -=1; } } } break; case execplan::CalpontSystemCatalog::DECIMAL: { const string& valStr = parm[0]->data()->getStrVal(row, isNull); val = parm[0]->data()->getIntVal(row, isNull); size_t x = valStr.find("."); if ( x < string::npos) { string tmp = valStr.substr(x+1,1); char * ptr = &tmp[0]; int i = atoi(ptr); if (i >= 5) { if (val > 0) val += 1; else val -=1; } } } break; case execplan::CalpontSystemCatalog::CHAR: case execplan::CalpontSystemCatalog::VARCHAR: { val = parm[0]->data()->getIntVal(row, isNull); break; } default: { std::ostringstream oss; oss << "sec_to_time: datatype of " << execplan::colDataTypeToString(parm[0]->data()->resultType().colDataType); throw logging::IDBExcept(oss.str(), ERR_DATATYPE_NOT_SUPPORT); } } int64_t posVal = llabs(val); if (val >3020399) return ("838:59:59"); if (val < -3020399) return ("-838:59:59"); //Format the time uint32_t hour = 0; uint32_t minute = 0; uint32_t second = 0; hour = posVal / 3600; minute = (posVal - (hour * 3600)) / 60; second = posVal - (hour * 3600) - (minute * 60); const char* minus = "-"; const char* nominus = ""; const char* signstr = ( val < 0 ) ? minus : nominus; char buf[32]; // actual string either 9 or 10 characters snprintf( buf, 32, "%s%02d:%02d:%02d", signstr, hour, minute, second ); return buf; }
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output) { int i; uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL; if (ic->nb_streams && !printed) return; av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n", is_output ? "Output" : "Input", index, is_output ? ic->oformat->name : ic->iformat->name, is_output ? "to" : "from", url); dump_metadata(NULL, ic->metadata, " "); if (!is_output) { av_log(NULL, AV_LOG_INFO, " Duration: "); if (ic->duration != AV_NOPTS_VALUE) { int hours, mins, secs, us; int64_t duration = ic->duration + (ic->duration <= INT64_MAX - 5000 ? 5000 : 0); secs = duration / AV_TIME_BASE; us = duration % AV_TIME_BASE; mins = secs / 60; secs %= 60; hours = mins / 60; mins %= 60; av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs, (100 * us) / AV_TIME_BASE); } else { av_log(NULL, AV_LOG_INFO, "N/A"); } if (ic->start_time != AV_NOPTS_VALUE) { int secs, us; av_log(NULL, AV_LOG_INFO, ", start: "); secs = llabs(ic->start_time / AV_TIME_BASE); us = llabs(ic->start_time % AV_TIME_BASE); av_log(NULL, AV_LOG_INFO, "%s%d.%06d", ic->start_time >= 0 ? "" : "-", secs, (int) av_rescale(us, 1000000, AV_TIME_BASE)); } av_log(NULL, AV_LOG_INFO, ", bitrate: "); if (ic->bit_rate) av_log(NULL, AV_LOG_INFO, "%"PRId64" kb/s", ic->bit_rate / 1000); else av_log(NULL, AV_LOG_INFO, "N/A"); av_log(NULL, AV_LOG_INFO, "\n"); } for (i = 0; i < ic->nb_chapters; i++) { AVChapter *ch = ic->chapters[i]; av_log(NULL, AV_LOG_INFO, " Chapter #%d:%d: ", index, i); av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base)); av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base)); dump_metadata(NULL, ch->metadata, " "); } if (ic->nb_programs) { int j, k, total = 0; for (j = 0; j < ic->nb_programs; j++) { AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata, "name", NULL, 0); av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id, name ? name->value : ""); dump_metadata(NULL, ic->programs[j]->metadata, " "); for (k = 0; k < ic->programs[j]->nb_stream_indexes; k++) { dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output); printed[ic->programs[j]->stream_index[k]] = 1; } total += ic->programs[j]->nb_stream_indexes; } if (total < ic->nb_streams) av_log(NULL, AV_LOG_INFO, " No Program\n"); } for (i = 0; i < ic->nb_streams; i++) if (!printed[i]) dump_stream_format(ic, i, index, is_output); av_free(printed); }
int main () { long long int k , a, b; long long int i; scanf("%lld %lld %lld", &k, &a, &b); long long int count = 0; long long int t1, t2,z1, z2, ans; if (a == 0 || b==0 ) { if (a == 0) { t2 = llabs(b - (b%k)); z2 = t2/k; count = z2 +1; } else { t1 = llabs(a - (a%k)); z1 = t1/k; count = z1+1; } } else if ( (a >= 0 && b >= 0) || (a<0 && b<0)) { if ((a<0 && b <0) && (b%k)==0) count++; else if ((a>0 && b>0) && (a%k)==0) count++; t2 = llabs( b - (b%k)); t1 = llabs(a - (a%k)); z1 = t1/k; z2 = t2/k; if ( a<0 && b <0) count = count + (z1-z2); else count = count + (z2-z1); } else if (( a> 0 && b<0) || (a<0 && b>0)) { t2 = llabs( b - (b%k) ); t1 = llabs (a - (a%k)); z1 = t1/k; z2 = t2/k; count = count + (z2+z1) + 1; } printf("%lld\n", count); return 0; }
/*! \brief Implementation routine to compare SIMD4 vs reference functions. * * \param refFuncExpr Description of reference function expression * \param simd4FuncExpr Description of SIMD function expression * \param refFunc Reference math function pointer * \param simd4Func SIMD math function pointer * * The function will be tested with the range and tolerances specified in * the SimdBaseTest class. You should not never call this function directly, * but use the macro GMX_EXPECT_SIMD4_FUNC_NEAR(refFunc,tstFunc) instead. */ ::testing::AssertionResult Simd4MathTest::compareSimd4MathFunction(const char * refFuncExpr, const char *simd4FuncExpr, real refFunc(real x), gmx_simd4_real_t gmx_simdcall simd4Func(gmx_simd4_real_t x)) { std::vector<real> vx(GMX_SIMD4_WIDTH); std::vector<real> vref(GMX_SIMD4_WIDTH); std::vector<real> vtst(GMX_SIMD4_WIDTH); real dx; gmx_int64_t ulpDiff, maxUlpDiff; real maxUlpDiffPos; real refValMaxUlpDiff, simdValMaxUlpDiff; bool eq, signOk; int i, iter; int niter = s_nPoints/GMX_SIMD4_WIDTH; int npoints = niter*GMX_SIMD4_WIDTH; # ifdef GMX_DOUBLE union { double r; gmx_int64_t i; } conv0, conv1; # else union { float r; gmx_int32_t i; } conv0, conv1; # endif maxUlpDiff = 0; dx = (range_.second-range_.first)/npoints; for (iter = 0; iter < niter; iter++) { for (i = 0; i < GMX_SIMD4_WIDTH; i++) { vx[i] = range_.first+dx*(iter*GMX_SIMD4_WIDTH+i); vref[i] = refFunc(vx[i]); } vtst = simd4Real2Vector(simd4Func(vector2Simd4Real(vx))); for (i = 0, eq = true, signOk = true; i < GMX_SIMD4_WIDTH && eq == true; i++) { eq = eq && ( fabs(vref[i]-vtst[i]) < absTol_ ); signOk = signOk && ( vref[i]*vtst[i] >= 0 ); } if (eq == true) { // Go to next point if everything within absolute tolerance continue; } else if (signOk == false) { return ::testing::AssertionFailure() << "Failing SIMD4 math function comparison due to sign differences." << std::endl << "Reference function: " << refFuncExpr << std::endl << "Simd function: " << simd4FuncExpr << std::endl << "Test range is ( " << range_.first << " , " << range_.second << " ) " << std::endl << "First sign difference around x=" << std::setprecision(20) << ::testing::PrintToString(vx) << std::endl << "Ref values: " << std::setprecision(20) << ::testing::PrintToString(vref) << std::endl << "SIMD4 values: " << std::setprecision(20) << ::testing::PrintToString(vtst) << std::endl; } /* We replicate the trivial ulp differences comparison here rather than * calling the lower-level routine for comparing them, since this enables * us to run through the entire test range and report the largest deviation * without lots of extra glue routines. */ for (i = 0; i < GMX_SIMD4_WIDTH; i++) { conv0.r = vref[i]; conv1.r = vtst[i]; ulpDiff = llabs(conv0.i-conv1.i); if (ulpDiff > maxUlpDiff) { maxUlpDiff = ulpDiff; maxUlpDiffPos = vx[i]; refValMaxUlpDiff = vref[i]; simdValMaxUlpDiff = vtst[i]; } } } if (maxUlpDiff <= ulpTol_) { return ::testing::AssertionSuccess(); } else { return ::testing::AssertionFailure() << "Failing SIMD4 math function ulp comparison between " << refFuncExpr << " and " << simd4FuncExpr << std::endl << "Requested ulp tolerance: " << ulpTol_ << std::endl << "Requested abs tolerance: " << absTol_ << std::endl << "Largest Ulp difference occurs for x=" << std::setprecision(20) << maxUlpDiffPos << std::endl << "Ref values: " << std::setprecision(20) << refValMaxUlpDiff << std::endl << "SIMD4 values: " << std::setprecision(20) << simdValMaxUlpDiff << std::endl << "Ulp diff.: " << std::setprecision(20) << maxUlpDiff << std::endl; } }
GainType Ascent() { Node *t; GainType BestW, W, W0, Alpha, MaxAlpha = INT_MAX; int T, Period, P, InitialPhase, BestNorm; Start: /* Initialize Pi and BestPi */ t = FirstNode; do t->Pi = t->BestPi = 0; while ((t = t->Suc) != FirstNode); if (CandidateSetType == DELAUNAY) CreateDelaunayCandidateSet(); else AddTourCandidates(); /* Compute the cost of a minimum 1-tree */ W = Minimum1TreeCost(CandidateSetType == DELAUNAY || MaxCandidates == 0); /* Return this cost if either (1) subgradient optimization is not wanted, or (2) the norm of the tree (its deviation from a tour) is zero (in that case the true optimum has been found). */ if (!Subgradient || !Norm) return W; if (Optimum != MINUS_INFINITY && (Alpha = Optimum * Precision - W) > 0) MaxAlpha = Alpha; if (MaxCandidates > 0) { /* Generate symmetric candididate sets for all nodes */ if (CandidateSetType != DELAUNAY) GenerateCandidates(AscentCandidates, MaxAlpha, 1); else { OrderCandidateSet(AscentCandidates, MaxAlpha, 1); W = Minimum1TreeCost(1); if (!Norm || W / Precision == Optimum) return W; } } if (ExtraCandidates > 0) AddExtraCandidates(ExtraCandidates, ExtraCandidateSetType, ExtraCandidateSetSymmetric); if (TraceLevel >= 2) { CandidateReport(); printff("Subgradient optimization ...\n"); } /* Set LastV of every node to V (the node's degree in the 1-tree) */ t = FirstNode; do t->LastV = t->V; while ((t = t->Suc) != FirstNode); BestW = W0 = W; BestNorm = Norm; InitialPhase = 1; /* Perform subradient optimization with decreasing period length and decreasing step size */ for (Period = InitialPeriod, T = InitialStepSize * Precision; Period > 0 && T > 0 && Norm != 0; Period /= 2, T /= 2) { /* Period and step size are halved at each iteration */ if (TraceLevel >= 2) printff (" T = %d, Period = %d, BestW = %0.1f, Norm = %d\n", T, Period, (double) BestW / Precision, Norm); for (P = 1; T && P <= Period && Norm != 0; P++) { /* Adjust the Pi-values */ t = FirstNode; do { if (t->V != 0) { t->Pi += T * (7 * t->V + 3 * t->LastV) / 10; if (t->Pi > INT_MAX / 4) t->Pi = INT_MAX / 4; else if (t->Pi < -INT_MAX / 4) t->Pi = -INT_MAX / 4; } t->LastV = t->V; } while ((t = t->Suc) != FirstNode); /* Compute a minimum 1-tree in the sparse graph */ W = Minimum1TreeCost(1); /* Test if an improvement has been found */ if (W > BestW || (W == BestW && Norm < BestNorm)) { /* If the lower bound becomes greater than twice its initial value it is taken as a sign that the graph might be too sparse */ if (W - W0 > llabs(W0) && AscentCandidates > 0 && AscentCandidates < Dimension) { W = Minimum1TreeCost(CandidateSetType == DELAUNAY || MaxCandidates == 0); if (W < W0) { /* Double the number of candidate edges and start all over again */ if (TraceLevel >= 2) printff("Warning: AscentCandidates doubled\n"); if ((AscentCandidates *= 2) > Dimension) AscentCandidates = Dimension; goto Start; } W0 = W; } BestW = W; BestNorm = Norm; /* Update the BestPi-values */ t = FirstNode; do t->BestPi = t->Pi; while ((t = t->Suc) != FirstNode); if (TraceLevel >= 2) printff ("* T = %d, Period = %d, P = %d, BestW = %0.1f, Norm = %d\n", T, Period, P, (double) BestW / Precision, Norm); /* If in the initial phase, the step size is doubled */ if (InitialPhase && T * sqrt((double) Norm) > 0) T *= 2; /* If the improvement was found at the last iteration of the current period, then double the period */ if (CandidateSetType != DELAUNAY && P == Period && (Period *= 2) > InitialPeriod) Period = InitialPeriod; } else { if (TraceLevel >= 3) printff (" T = %d, Period = %d, P = %d, W = %0.1f, Norm = %d\n", T, Period, P, (double) W / Precision, Norm); if (InitialPhase && P > Period / 2) { /* Conclude the initial phase */ InitialPhase = 0; P = 0; T = 3 * T / 4; } } } } t = FirstNode; do { t->Pi = t->BestPi; t->BestPi = 0; } while ((t = t->Suc) != FirstNode); /* Compute a minimum 1-tree */ W = BestW = Minimum1TreeCost(CandidateSetType == DELAUNAY || MaxCandidates == 0); if (MaxCandidates > 0) { FreeCandidateSets(); if (CandidateSetType == DELAUNAY) CreateDelaunayCandidateSet(); } else { Candidate *Nt; t = FirstNode; do { for (Nt = t->CandidateSet; Nt && Nt->To; Nt++) Nt->Cost += t->Pi + Nt->To->Pi; } while ((t = t->Suc) != FirstNode); } if (TraceLevel >= 2) printff("Ascent: BestW = %0.1f, Norm = %d\n", (double) BestW / Precision, Norm); return W; }
// static void LLFloaterPay::processPayPriceReply(LLMessageSystem* msg, void **userdata) { LLFloaterPay* self = (LLFloaterPay*)userdata; if (self) { S32 price; LLUUID target; msg->getUUIDFast(_PREHASH_ObjectData,_PREHASH_ObjectID,target); if (target != self->mTargetUUID) { // This is a message for a different object's pay info return; } msg->getS32Fast(_PREHASH_ObjectData,_PREHASH_DefaultPayPrice,price); if (PAY_PRICE_HIDE == price) { self->getChildView("amount")->setVisible(FALSE); self->getChildView("pay btn")->setVisible(FALSE); self->getChildView("amount text")->setVisible(FALSE); } else if (PAY_PRICE_DEFAULT == price) { self->getChildView("amount")->setVisible(TRUE); self->getChildView("pay btn")->setVisible(TRUE); self->getChildView("amount text")->setVisible(TRUE); } else { // PAY_PRICE_HIDE and PAY_PRICE_DEFAULT are negative values // So we take the absolute value here after we have checked for those cases self->getChildView("amount")->setVisible(TRUE); self->getChildView("pay btn")->setVisible(TRUE); self->getChildView("pay btn")->setEnabled(TRUE); self->getChildView("amount text")->setVisible(TRUE); self->getChild<LLUICtrl>("amount")->setValue(llformat("%d", llabs(price))); } S32 num_blocks = msg->getNumberOfBlocksFast(_PREHASH_ButtonData); S32 i = 0; if (num_blocks > MAX_PAY_BUTTONS) num_blocks = MAX_PAY_BUTTONS; S32 max_pay_amount = 0; S32 padding_required = 0; for (i=0;i<num_blocks;++i) { S32 pay_button; msg->getS32Fast(_PREHASH_ButtonData,_PREHASH_PayButton,pay_button,i); if (pay_button > 0) { std::string button_str = "L$"; button_str += LLResMgr::getInstance()->getMonetaryString( pay_button ); self->mQuickPayButton[i]->setLabelSelected(button_str); self->mQuickPayButton[i]->setLabelUnselected(button_str); self->mQuickPayButton[i]->setVisible(TRUE); self->mQuickPayInfo[i]->mAmount = pay_button; self->getChildView("fastpay text")->setVisible(TRUE); if ( pay_button > max_pay_amount ) { max_pay_amount = pay_button; } } else { self->mQuickPayButton[i]->setVisible(FALSE); } } // build a string containing the maximum value and calc nerw button width from it. std::string balance_str = "L$"; balance_str += LLResMgr::getInstance()->getMonetaryString( max_pay_amount ); const LLFontGL* font = LLFontGL::getFontSansSerif(); S32 new_button_width = font->getWidth( std::string(balance_str)); new_button_width += ( 12 + 12 ); // padding // dialong is sized for 2 digit pay amounts - larger pay values need to be scaled const S32 threshold = 100000; if ( max_pay_amount >= threshold ) { S32 num_digits_threshold = (S32)log10((double)threshold) + 1; S32 num_digits_max = (S32)log10((double)max_pay_amount) + 1; // calculate the extra width required by 2 buttons with max amount and some commas padding_required = ( num_digits_max - num_digits_threshold + ( num_digits_max / 3 ) ) * font->getWidth( std::string("0") ); }; // change in button width S32 button_delta = new_button_width - FASTPAY_BUTTON_WIDTH; if ( button_delta < 0 ) button_delta = 0; // now we know the maximum amount, we can resize all the buttons to be for (i=0;i<num_blocks;++i) { LLRect r; r = self->mQuickPayButton[i]->getRect(); // RHS button colum needs to move further because LHS changed too if ( i % 2 ) { r.setCenterAndSize( r.getCenterX() + ( button_delta * 3 ) / 2 , r.getCenterY(), r.getWidth() + button_delta, r.getHeight() ); } else { r.setCenterAndSize( r.getCenterX() + button_delta / 2, r.getCenterY(), r.getWidth() + button_delta, r.getHeight() ); } self->mQuickPayButton[i]->setRect( r ); } for (i=num_blocks;i<MAX_PAY_BUTTONS;++i) { self->mQuickPayButton[i]->setVisible(FALSE); } self->reshape( self->getRect().getWidth() + padding_required, self->getRect().getHeight(), FALSE ); } msg->setHandlerFunc("PayPriceReply",NULL,NULL); }
void * LLAudioEngine_OpenAL::windDSP(void *newbuffer, int length) { // *NOTE: This function gets called a *lot*. // Keep performance in mind if you mess with this. // newbuffer = the buffer being constructed // length = length in samples of the buffer //clear the buffer memset(newbuffer, 0, length*mBytesPerSample); // This turns off wind synth if it is muted or very very low volume if (mTargetGain < 0.0005f) { llinfos << "Wind off" << llendl; return newbuffer; } static const U8 SUBSAMPLES = 2; static const F32 FILTER_SAMPLE_PERIOD = (F32)SUBSAMPLES / float(mSampleRate); static const F32 BANDWIDTH = 50.0f; static const F32 B2 = expf(-F_TWO_PI * BANDWIDTH * FILTER_SAMPLE_PERIOD); static F32 pinking_buf0 = 0.0f; static F32 pinking_buf1 = 0.0f; static F32 pinking_buf2 = 0.0f; static F32 Y0 = 0.0f; static F32 Y1 = 0.0f; static F32 last_sample = 0.0f; static F32 current_freq = 0.0f; static F32 current_gain = 0.0f; static F32 current_pan_gain_r = 0.0f; F32 a0 = 0.0f, b1 = 0.0f; U8 *cursamplep = (U8*)newbuffer; //we assume 16-bit samples, because the ALUT specification maxes out there U8 wordsize = 2; bool interp_freq = false; //if the frequency isn't changing much, we don't need to interpolate in the inner loop if (llabs(mTargetFreq - current_freq) > 200.0f) { interp_freq = true; } else { // calculate resonant filter coefficients current_freq = mTargetFreq; b1 = (-4.0f * B2) / (1.0f + B2) * cosf(F_TWO_PI * (current_freq * FILTER_SAMPLE_PERIOD)); a0 = (1.0f - B2) * sqrtf(1.0f - (b1 * b1) / (4.0f * B2)); } while (length) { F32 next_sample; // Start with white noise [-16384, 16383] next_sample = (F32)rand() * (1.0f / (F32)(RAND_MAX / (U16_MAX / 4))) + (S16_MIN / 4); // Apply a pinking filter // Magic numbers taken from PKE method at http://www.firstpr.com.au/dsp/pink-noise/ pinking_buf0 = pinking_buf0 * 0.99765f + next_sample * 0.0990460f; pinking_buf1 = pinking_buf1 * 0.96300f + next_sample * 0.2965164f; pinking_buf2 = pinking_buf2 * 0.57000f + next_sample * 1.0526913f; next_sample = pinking_buf0 + pinking_buf1 + pinking_buf2 + next_sample * 0.1848f; if (interp_freq) { // calculate resonant filter coefficients current_freq = (0.999f * current_freq) + (0.001f * mTargetFreq); b1 = (-4.0f * B2) / (1.0f + B2) * cosf(F_TWO_PI * (current_freq * FILTER_SAMPLE_PERIOD)); a0 = (1.0f - B2) * sqrtf(1.0f - (b1 * b1) / (4.0f * B2)); } // Apply a resonant low-pass filter on the pink noise next_sample = ( a0 * next_sample - b1 * Y0 - B2 * Y1 ); Y1 = Y0; Y0 = next_sample; current_gain = (0.999f * current_gain) + (0.001f * mTargetGain); current_pan_gain_r = (0.999f * current_pan_gain_r) + (0.001f * mTargetPanGainR); next_sample *= current_gain; F32 delta = (next_sample - last_sample) / (F32)SUBSAMPLES; S32 sample_left; S32 sample_right; // Mix into the audio buffer, clipping if necessary for 16-bit mix buffers. // *TODO: Should do something more intelligent like reducing wind gain to avoid clipping for (int i=SUBSAMPLES; i && length; --i, --length) { last_sample = last_sample + delta; sample_right = (S32)(last_sample * current_pan_gain_r); sample_left = (S32)(last_sample - sample_right); *(S16*)cursamplep = llclamp(sample_left, S16_MIN, S16_MAX); cursamplep += wordsize; *(S16*)cursamplep = llclamp(sample_right, S16_MIN, S16_MAX); cursamplep += wordsize; } } return newbuffer; }
static int filter_frame(AVFilterLink *inlink, AVFrame *buf) { AVFilterContext *ctx = inlink->dst; ASyncContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout); int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts : av_rescale_q(buf->pts, inlink->time_base, outlink->time_base); int out_size, ret; int64_t delta; int64_t new_pts; /* buffer data until we get the next timestamp */ if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) { if (pts != AV_NOPTS_VALUE) { s->pts = pts - get_delay(s); } return write_to_fifo(s, buf); } if (s->first_pts != AV_NOPTS_VALUE) { handle_trimming(ctx); if (!avresample_available(s->avr)) return write_to_fifo(s, buf); } /* when we have two timestamps, compute how many samples would we have * to add/remove to get proper sync between data and timestamps */ delta = pts - s->pts - get_delay(s); out_size = avresample_available(s->avr); if (llabs(delta) > s->min_delta || (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) { av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta); out_size = av_clipl_int32((int64_t)out_size + delta); } else { if (s->resample) { // adjust the compensation if delta is non-zero int delay = get_delay(s); int comp = s->comp + av_clip(delta * inlink->sample_rate / delay, -s->max_comp, s->max_comp); if (comp != s->comp) { av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp); if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) { s->comp = comp; } } } // adjust PTS to avoid monotonicity errors with input PTS jitter pts -= delta; delta = 0; } if (out_size > 0) { AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size); if (!buf_out) { ret = AVERROR(ENOMEM); goto fail; } if (s->first_frame && delta > 0) { int planar = av_sample_fmt_is_planar(buf_out->format); int planes = planar ? nb_channels : 1; int block_size = av_get_bytes_per_sample(buf_out->format) * (planar ? 1 : nb_channels); int ch; av_samples_set_silence(buf_out->extended_data, 0, delta, nb_channels, buf->format); for (ch = 0; ch < planes; ch++) buf_out->extended_data[ch] += delta * block_size; avresample_read(s->avr, buf_out->extended_data, out_size); for (ch = 0; ch < planes; ch++) buf_out->extended_data[ch] -= delta * block_size; } else { avresample_read(s->avr, buf_out->extended_data, out_size); if (delta > 0) { av_samples_set_silence(buf_out->extended_data, out_size - delta, delta, nb_channels, buf->format); } } buf_out->pts = s->pts; ret = ff_filter_frame(outlink, buf_out); if (ret < 0) goto fail; s->got_output = 1; } else if (avresample_available(s->avr)) { av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping " "whole buffer.\n"); } /* drain any remaining buffered data */ avresample_read(s->avr, NULL, avresample_available(s->avr)); new_pts = pts - avresample_get_delay(s->avr); /* check for s->pts monotonicity */ if (new_pts > s->pts) { s->pts = new_pts; ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data, buf->linesize[0], buf->nb_samples); } else { av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping " "whole buffer.\n"); ret = 0; } s->first_frame = 0; fail: av_frame_free(&buf); return ret; }
F32 LLViewerRegion::getCompositionXY(const S32 x, const S32 y) const { if (x >= 256) { if (y >= 256) { LLVector3d center = getCenterGlobal() + LLVector3d(256.f, 256.f, 0.f); LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromPosGlobal(center); if (regionp) { // OK, we need to do some hackery here - different simulators no longer use // the same composition values, necessarily. // If we're attempting to blend, then we want to make the fractional part of // this region match the fractional of the adjacent. For now, just minimize // the delta. F32 our_comp = getComposition()->getValueScaled(255, 255); F32 adj_comp = regionp->getComposition()->getValueScaled(x - 256.f, y - 256.f); while (llabs(our_comp - adj_comp) >= 1.f) { if (our_comp > adj_comp) { adj_comp += 1.f; } else { adj_comp -= 1.f; } } return adj_comp; } } else { LLVector3d center = getCenterGlobal() + LLVector3d(256.f, 0, 0.f); LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromPosGlobal(center); if (regionp) { // OK, we need to do some hackery here - different simulators no longer use // the same composition values, necessarily. // If we're attempting to blend, then we want to make the fractional part of // this region match the fractional of the adjacent. For now, just minimize // the delta. F32 our_comp = getComposition()->getValueScaled(255.f, (F32)y); F32 adj_comp = regionp->getComposition()->getValueScaled(x - 256.f, (F32)y); while (llabs(our_comp - adj_comp) >= 1.f) { if (our_comp > adj_comp) { adj_comp += 1.f; } else { adj_comp -= 1.f; } } return adj_comp; } } } else if (y >= 256) { LLVector3d center = getCenterGlobal() + LLVector3d(0.f, 256.f, 0.f); LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromPosGlobal(center); if (regionp) { // OK, we need to do some hackery here - different simulators no longer use // the same composition values, necessarily. // If we're attempting to blend, then we want to make the fractional part of // this region match the fractional of the adjacent. For now, just minimize // the delta. F32 our_comp = getComposition()->getValueScaled((F32)x, 255.f); F32 adj_comp = regionp->getComposition()->getValueScaled((F32)x, y - 256.f); while (llabs(our_comp - adj_comp) >= 1.f) { if (our_comp > adj_comp) { adj_comp += 1.f; } else { adj_comp -= 1.f; } } return adj_comp; } } return getComposition()->getValueScaled((F32)x, (F32)y); }
op_generic_t *rs_simple_request(resource_service_fn_t *arg, data_attr_t *da, rs_query_t *rsq, data_cap_set_t **caps, rs_request_t *req, int req_size, rs_hints_t *hints_list, int fixed_size, int n_rid, int ignore_fixed_err, int timeout) { rs_simple_priv_t *rss = (rs_simple_priv_t *)arg->priv; rsq_base_t *query_global = (rsq_base_t *)rsq; rsq_base_t *query_local; kvq_table_t kvq_global, kvq_local, *kvq; apr_hash_t *pick_from; rid_change_entry_t *rid_change; ex_off_t change; op_status_t status; opque_t *que; rss_rid_entry_t *rse; rsq_base_ele_t *q; int slot, rnd_off, i, j, k, i_unique, i_pickone, found, err_cnt, loop, loop_end; int state, *a, *b, *op_state, unique_size; tbx_stack_t *stack; log_printf(15, "rs_simple_request: START rss->n_rids=%d n_rid=%d req_size=%d fixed_size=%d\n", rss->n_rids, n_rid, req_size, fixed_size); for (i=0; i<req_size; i++) req[i].rid_key = NULL; //** Clear the result in case of an error apr_thread_mutex_lock(rss->lock); i = _rs_simple_refresh(arg); //** Check if we need to refresh the data if (i != 0) { apr_thread_mutex_unlock(rss->lock); return(gop_dummy(op_failure_status)); } //** Determine the query sizes and make the processing arrays memset(&kvq, 0, sizeof(kvq)); rs_query_count(arg, rsq, &i, &(kvq_global.n_unique), &(kvq_global.n_pickone)); log_printf(15, "rs_simple_request: n_unique=%d n_pickone=%d\n", kvq_global.n_unique, kvq_global.n_pickone); tbx_log_flush(); //** Make space the for the uniq and pickone fields. //** Make sure we have space for at least 1 more than we need of each to pass to the routines even though they aren't used j = (kvq_global.n_pickone == 0) ? 1 : kvq_global.n_pickone + 1; tbx_type_malloc_clear(kvq_global.pickone, kvq_ele_t, j); unique_size = kvq_global.n_unique + 1; tbx_type_malloc_clear(kvq_global.unique, kvq_ele_t *, unique_size); log_printf(15, "MALLOC j=%d\n", unique_size); for (i=0; i<unique_size; i++) { tbx_type_malloc_clear(kvq_global.unique[i], kvq_ele_t, n_rid); } //** We don't allow these on the local but make a temp space anyway kvq_local.n_pickone = 0; tbx_type_malloc_clear(kvq_local.pickone, kvq_ele_t, 1); kvq_global.n_unique = 0; tbx_type_malloc_clear(kvq_local.unique, kvq_ele_t *, 1); tbx_type_malloc_clear(kvq_local.unique[0], kvq_ele_t, n_rid); status = op_success_status; que = new_opque(); stack = tbx_stack_new(); err_cnt = 0; found = 0; // max_size = (req_size > fixed_size) ? req_size : fixed_size; for (i=0; i < n_rid; i++) { found = 0; loop_end = 1; query_local = NULL; rnd_off = tbx_random_get_int64(0, rss->n_rids-1); //rnd_off = 0; //FIXME if (hints_list != NULL) { query_local = (rsq_base_t *)hints_list[i].local_rsq; if (query_local != NULL) { loop_end = 2; rs_query_count(arg, query_local, &j, &(kvq_local.n_unique), &(kvq_local.n_pickone)); if ((kvq_local.n_unique != 0) && (kvq_local.n_pickone != 0)) { log_printf(0, "Unsupported use of pickone/unique in local RSQ hints_list[%d]=%s!\n", i, hints_list[i].fixed_rid_key); status.op_status = OP_STATE_FAILURE; status.error_code = RS_ERROR_FIXED_NOT_FOUND; hints_list[i].status = RS_ERROR_HINTS_INVALID_LOCAL; err_cnt++; continue; } } if (i<fixed_size) { //** Use the fixed list for assignment rse = tbx_list_search(rss->rid_table, hints_list[i].fixed_rid_key); if (rse == NULL) { log_printf(0, "Missing element in hints list[%d]=%s! Ignoring check.\n", i, hints_list[i].fixed_rid_key); hints_list[i].status = RS_ERROR_FIXED_NOT_FOUND; continue; //** Skip the check } rnd_off = rse->slot; } } //** See if we use a restrictive list. Ususally used when rebalancing space pick_from = (hints_list != NULL) ? hints_list[i].pick_from : NULL; rid_change = NULL; change = 0; for (k=0; k<req_size; k++) { if (req[k].rid_index == i) { change += req[k].size; } } for (j=0; j<rss->n_rids; j++) { slot = (rnd_off+j) % rss->n_rids; rse = rss->random_array[slot]; if (pick_from != NULL) { rid_change = apr_hash_get(pick_from, rse->rid_key, APR_HASH_KEY_STRING); log_printf(15, "PICK_FROM != NULL i=%d j=%d slot=%d rse->rid_key=%s rse->status=%d rid_change=%p\n", i, j, slot, rse->rid_key, rse->status, rid_change); if (rid_change == NULL) continue; //** Not in our list so skip to the next ex_off_t delta = rid_change->delta - change; log_printf(15, "PICK_FROM != NULL i=%d j=%d slot=%d rse->rid_key=%s rse->status=%d rc->state=%d (" XOT ") > " XOT "????\n", i, j, slot, rse->rid_key, rse->status, rid_change->state, delta, rid_change->tolerance); //** Make sure we don't overshoot the target if (rid_change->state == 1) continue; //** Already converged RID if (rid_change->delta <= 0) continue; //** Need to move data OFF this RID if ((change - rid_change->delta) > rid_change->tolerance) continue; //**delta>0 if we made it here } log_printf(15, "i=%d j=%d slot=%d rse->rid_key=%s rse->status=%d\n", i, j, slot, rse->rid_key, rse->status); if ((rse->status != RS_STATUS_UP) && (i>=fixed_size)) continue; //** Skip this if disabled and not in the fixed list tbx_stack_empty(stack, 1); q = query_global->head; kvq = &kvq_global; for (loop=0; loop<loop_end; loop++) { i_unique = 0; i_pickone = 0; while (q != NULL) { state = -1; switch (q->op) { case RSQ_BASE_OP_KV: state = rss_test(q, rse, i, kvq->unique[i_unique], &(kvq->pickone[i_pickone])); log_printf(0, "KV: key=%s val=%s i_unique=%d i_pickone=%d loop=%d rss_test=%d rse->rid_key=%s\n", q->key, q->val, i_unique, i_pickone, loop, state, rse->rid_key); tbx_log_flush(); if ((q->key_op & RSQ_BASE_KV_UNIQUE) || (q->val_op & RSQ_BASE_KV_UNIQUE)) i_unique++; if ((q->key_op & RSQ_BASE_KV_PICKONE) || (q->val_op & RSQ_BASE_KV_PICKONE)) i_pickone++; break; case RSQ_BASE_OP_NOT: a = (int *)tbx_stack_pop(stack); state = (*a == 0) ? 1 : 0; //log_printf(0, "NOT(%d)=%d\n", *a, state); free(a); break; case RSQ_BASE_OP_AND: a = (int *)tbx_stack_pop(stack); b = (int *)tbx_stack_pop(stack); state = (*a) && (*b); //log_printf(0, "%d AND %d = %d\n", *a, *b, state); free(a); free(b); break; case RSQ_BASE_OP_OR: a = (int *)tbx_stack_pop(stack); b = (int *)tbx_stack_pop(stack); state = a || b; //log_printf(0, "%d OR %d = %d\n", *a, *b, state); free(a); free(b); break; } tbx_type_malloc(op_state, int, 1); *op_state = state; tbx_stack_push(stack, (void *)op_state); log_printf(15, " stack_size=%d loop=%d push state=%d\n",tbx_stack_count(stack), loop, state); tbx_log_flush(); q = q->next; } if (query_local != NULL) { q = query_local->head; kvq = &kvq_local; } } op_state = (int *)tbx_stack_pop(stack); state = -1; if (op_state != NULL) { state = *op_state; free(op_state); } if (op_state == NULL) { log_printf(1, "rs_simple_request: ERROR processing i=%d EMPTY STACK\n", i); found = 0; status.op_status = OP_STATE_FAILURE; status.error_code = RS_ERROR_EMPTY_STACK; } else if (state == 1) { //** Got one log_printf(15, "rs_simple_request: processing i=%d ds_key=%s\n", i, rse->ds_key); found = 1; if ((i<fixed_size) && hints_list) hints_list[i].status = RS_ERROR_OK; for (k=0; k<req_size; k++) { if (req[k].rid_index == i) { log_printf(15, "rs_simple_request: i=%d ds_key=%s, rid_key=%s size=" XOT "\n", i, rse->ds_key, rse->rid_key, req[k].size); req[k].rid_key = strdup(rse->rid_key); req[k].gop = ds_allocate(rss->ds, rse->ds_key, da, req[k].size, caps[k], timeout); opque_add(que, req[k].gop); } } if (rid_change != NULL) { //** Flag that I'm tweaking things. The caller does the source pending/delta half rid_change->delta -= change; rid_change->state = ((llabs(rid_change->delta) <= rid_change->tolerance) || (rid_change->tolerance == 0)) ? 1 : 0; } break; //** Got one so exit the RID scan and start the next one } else if (i<fixed_size) { //** This should have worked so flag an error if (hints_list) { log_printf(1, "Match fail in fixed list[%d]=%s!\n", i, hints_list[i].fixed_rid_key); hints_list[i].status = RS_ERROR_FIXED_MATCH_FAIL; } else { log_printf(1, "Match fail in fixed list and no hints are provided!\n"); } status.op_status = OP_STATE_FAILURE; status.error_code = RS_ERROR_FIXED_MATCH_FAIL; if (ignore_fixed_err == 0) err_cnt++; break; //** Skip to the next in the list } else { found = 0; } } if ((found == 0) && (i>=fixed_size)) break; } //** Clean up log_printf(15, "FREE j=%d\n", unique_size); for (i=0; i<unique_size; i++) { free(kvq_global.unique[i]); } free(kvq_global.unique); free(kvq_global.pickone); free(kvq_local.unique[0]); free(kvq_local.unique); free(kvq_local.pickone); tbx_stack_free(stack, 1); log_printf(15, "rs_simple_request: END n_rid=%d\n", n_rid); //callback_t *cb = (callback_t *)que->qd.list->top->data; //op_generic_t *gop = (op_generic_t *)cb->priv; //log_printf(15, "top gid=%d reg=%d\n", gop_id(gop), gop_id(req[0].gop)); apr_thread_mutex_unlock(rss->lock); if ((found == 0) || (err_cnt>0)) { opque_free(que, OP_DESTROY); if (status.error_code == 0) { log_printf(1, "rs_simple_request: Can't find enough RIDs! requested=%d found=%d err_cnt=%d\n", n_rid, found, err_cnt); status.op_status = OP_STATE_FAILURE; status.error_code = RS_ERROR_NOT_ENOUGH_RIDS; } return(gop_dummy(status)); } return(opque_get_gop(que)); }
static void camd35_request_emm(ECM_REQUEST *er) { int32_t i; time_t now; uchar mbuf[1024]; struct s_client *cl = cur_client(); struct s_reader *aureader = NULL, *rdr = NULL; if(er->selected_reader && !er->selected_reader->audisabled && ll_contains(cl->aureader_list, er->selected_reader)) { aureader = er->selected_reader; } if(!aureader && cl->aureader_list) { LL_ITER itr = ll_iter_create(cl->aureader_list); while((rdr = ll_iter_next(&itr))) { if(emm_reader_match(rdr, er->caid, er->prid)) { aureader = rdr; break; } } } if(!aureader) { return; } // TODO uint16_t au_caid = aureader->caid; if(!au_caid && caid_is_bulcrypt(er->caid)) // Bulcrypt has 2 caids and aureader->caid can't be used. Use ECM_REQUEST caid for AU. { au_caid = er->caid; } time(&now); if(!memcmp(cl->lastserial, aureader->hexserial, 8)) if(llabs(now - cl->last) < 180) { return; } memcpy(cl->lastserial, aureader->hexserial, 8); cl->last = now; if(au_caid) { cl->disable_counter = 0; cs_log("%s emm-request sent (reader=%s, caid=%04X, auprovid=%06X)", username(cur_client()), aureader->label, au_caid, aureader->auprovid ? aureader->auprovid : b2i(4, aureader->prid[0])); } else if(cl->disable_counter > 2) { return; } else { cl->disable_counter++; } memset(mbuf, 0, sizeof(mbuf)); mbuf[2] = mbuf[3] = 0xff; // must not be zero i2b_buf(2, er->srvid, mbuf + 8); //override request provid with auprovid if set in CMD05 if(aureader->auprovid) { if(aureader->auprovid != er->prid) { i2b_buf(4, aureader->auprovid, mbuf + 12); } else { i2b_buf(4, er->prid, mbuf + 12); } } else { i2b_buf(4, er->prid, mbuf + 12); } i2b_buf(2, er->pid, mbuf + 16); mbuf[0] = 5; mbuf[1] = 111; if(au_caid) { mbuf[39] = 1; // no. caids mbuf[20] = au_caid >> 8; // caid's (max 8) mbuf[21] = au_caid & 0xff; memcpy(mbuf + 40, aureader->hexserial, 6); // serial now 6 bytes mbuf[47] = aureader->nprov; for(i = 0; i < aureader->nprov; i++) { if((au_caid >= 0x1700 && au_caid <= 0x1799) || // Betacrypt (au_caid >= 0x0600 && au_caid <= 0x0699)) // Irdeto (don't know if this is correct, cause I don't own a IRDETO-Card) { mbuf[48 + (i * 5)] = aureader->prid[i][0]; memcpy(&mbuf[50 + (i * 5)], &aureader->prid[i][1], 3); } else { mbuf[48 + (i * 5)] = aureader->prid[i][2]; mbuf[49 + (i * 5)] = aureader->prid[i][3]; memcpy(&mbuf[50 + (i * 5)], &aureader->sa[i][0], 4); // for conax we need at least 4 Bytes } } //we think client/server protocols should deliver all information, and only readers should discard EMM mbuf[128] = (aureader->blockemm & EMM_GLOBAL && !(aureader->saveemm & EMM_GLOBAL)) ? 0 : 1; mbuf[129] = (aureader->blockemm & EMM_SHARED && !(aureader->saveemm & EMM_SHARED)) ? 0 : 1; mbuf[130] = (aureader->blockemm & EMM_UNIQUE && !(aureader->saveemm & EMM_UNIQUE)) ? 0 : 1; mbuf[127] = (aureader->blockemm & EMM_UNKNOWN && !(aureader->saveemm & EMM_UNKNOWN)) ? 0 : 1; } else // disable emm { mbuf[20] = mbuf[39] = mbuf[40] = mbuf[47] = mbuf[49] = 1; }
int main() { long long g; long long i,j; boolean[0]=1; boolean[1]=1; for(i=2;i*i==10000001;i++) { if(!boolean[i]) { for(j=i*i;j<10000001;j+=i) { boolean[j]=1; } } } long long index=0; for(i=2;i<10000001;i++) { if(!boolean[i]) { primes[index++]=i; } } while(scanf("%lld",&g)==1 && g) { if(g==1) { printf("1 = 1"); }else if(g==-1) { printf("-1 = -1 * 1"); }else{ index=0; int counter; long long pf=primes[index++]; long long n=llabs(g); counter=0; while(n!=1 && pf*pf<=n){ while(n%pf==0) { factors[counter++]=pf; n/=pf; factors[counter]=0; } pf=primes[index++]; } if(n>1) { factors[counter]=n; } if(g<0) { printf("%lld = -1 ",g); for(i=0;i<=counter;i++) { if(factors[i]==0) { break; }else { printf("x %lld",factors[i]); if(i<=counter-1 && factors[i+1]!=0) printf(" "); } } }else { printf("%lld = %lld",g,factors[0]); if(counter>0) printf(" "); for(i=1;i<=counter;i++) { if(factors[i]==0){ break; }else { printf("x %lld",factors[i]); if(i<=counter-1 && factors[i+1]!=0) printf(" "); } } } } printf("\n"); } return 0; }