//============================================================================= int Amesos_Klu::SymbolicFactorization() { MyPID_ = Comm().MyPID(); NumProcs_ = Comm().NumProc(); IsSymbolicFactorizationOK_ = false; IsNumericFactorizationOK_ = false; CreateTimer(Comm(), 2); ResetTimer(1); // "overhead" time for the following method is considered here AMESOS_CHK_ERR( CreateLocalMatrixAndExporters() ) ; assert( NumGlobalElements_ == RowMatrixA_->NumGlobalCols() ); // // Perform checks in SymbolicFactorization(), but none in // NumericFactorization() or Solve() // if ( TrustMe_ ) { if ( CrsMatrixA_ == 0 ) AMESOS_CHK_ERR( -15 ); if( UseDataInPlace_ != 1 ) AMESOS_CHK_ERR( -15 ) ; if( Reindex_ ) AMESOS_CHK_ERR( -15 ) ; if( ! Problem_->GetLHS() ) AMESOS_CHK_ERR( -15 ) ; if( ! Problem_->GetRHS() ) AMESOS_CHK_ERR( -15 ) ; if( ! Problem_->GetLHS()->NumVectors() ) AMESOS_CHK_ERR( -15 ) ; if( ! Problem_->GetRHS()->NumVectors() ) AMESOS_CHK_ERR( -15 ) ; SerialB_ = Teuchos::rcp(Problem_->GetRHS(),false) ; SerialX_ = Teuchos::rcp(Problem_->GetLHS(),false) ; NumVectors_ = SerialX_->NumVectors(); if (MyPID_ == 0) { AMESOS_CHK_ERR(SerialX_->ExtractView(&SerialXBvalues_,&SerialXlda_ )); AMESOS_CHK_ERR(SerialB_->ExtractView(&SerialBvalues_,&SerialXlda_ )); } } // "overhead" time for the following two methods is considered here AMESOS_CHK_ERR( ExportToSerial() ); AMESOS_CHK_ERR( ConvertToKluCRS(true) ); OverheadTime_ = AddTime("Total Amesos overhead time", OverheadTime_, 1); // All this time if KLU time AMESOS_CHK_ERR( PerformSymbolicFactorization() ); NumSymbolicFact_++; IsSymbolicFactorizationOK_ = true; return 0; }
// 创建一个定时器. int Timer::CreateTimer(int MSec) { // 首先, 要找到一个空的id. OneTimer timer; timer.id = rand(); if( IsExist( timer.id )) CreateTimer( MSec ); // 如果已经存在了,则递归. timer.time = GetTickCount(); m_timer.push_back( timer ); return timer.id; }
//============================================================================= int Amesos_Dscpack::SymbolicFactorization() { IsSymbolicFactorizationOK_ = false; IsNumericFactorizationOK_ = false; CreateTimer(Comm(), 2); AMESOS_CHK_ERR(PerformSymbolicFactorization()); IsSymbolicFactorizationOK_ = true; NumSymbolicFact_++; return(0); }
void CTcpSessionManager::OnConnectorStatus(ConnectorID connectorID, bool bConnected, CTcpSessionPtr session) { auto config = m_mapConnectorConfig.find(connectorID); if (config == m_mapConnectorConfig.end()) { LOGE("Unkwon Connector. Not Found ConnectorID=" << connectorID); return; } if (bConnected) { m_mapConnectorPtr[connectorID] = session; config->second.second.curReconnectCount = 0; config->second.second.totalConnectCount++; Post(std::bind(&CMessageDispatcher::DispatchOnConnectorEstablished, &CMessageDispatcher::getRef(), connectorID)); return; } auto iter = m_mapConnectorPtr.find(connectorID); if (!bConnected && iter != m_mapConnectorPtr.end()) { m_mapConnectorPtr.erase(connectorID); Post(std::bind(&CMessageDispatcher::DispatchOnConnectorDisconnect, &CMessageDispatcher::getRef(), connectorID)); } if (!bConnected && config->second.second.curReconnectCount > 0 && config->second.second.curReconnectCount < config->second.first.reconnectMaxCount) { config->second.second.curReconnectCount++; CTcpSocketPtr sockPtr(new zsummer::network::CTcpSocket()); sockPtr->Initialize(m_summer); static const bool EnableFastConnect = false;//fast reconnect. Be careful of remote server access denied. if (config->second.second.curReconnectCount == 1 && EnableFastConnect) { Post(std::bind(&CTcpSession::BindTcpConnectorPtr, session, sockPtr, config->second)); } else { CreateTimer(config->second.first.reconnectInterval, std::bind(&CTcpSession::BindTcpConnectorPtr, session, sockPtr, config->second)); } } else if (config->second.first.reconnectMaxCount > 0) { LOGE("Try Reconnect Failed. End Try. Traits=" << config->second.first); } }
int main( int argc, char *argv[] ) { Timer<void()> timer; printf("Creating timer...\n"); timer = CreateTimer(); printf("Starting timer...\n"); timer.start(); while( 1) { sleep(20); } return( 0 ); }
void DelayedAction::Restart() { if(!m_HasStarted) { m_pParent->GetScene()->GetStopwatch()->ResetTimer( m_UniqueID, false ); } else { m_HasStarted = false; CreateTimer(); } }
HRESULT CHookedWindow::BeginMainLoop() { if (!_hWnd) return E_FAIL; if (!_stOldWindowProc && !_stOldRootWindowProc) return E_FAIL; if (!_bNoMloopHook && (_uiUpdateTimer = CreateTimer(0, _pDelMainLoop), _uiUpdateTimer != -1)) { LOG("Can't set update timer.", LT_FATAL); return E_ABORT; } LOG("**Entering main loop**",LT_INFO); return S_OK; }
bool X11Window::resize(int width, int height) { XResizeWindow(mDisplay, mWindow, width, height); XFlush(mDisplay); Timer* timer = CreateTimer(); timer->start(); // Wait until the window as actually been resized so that the code calling resize // can assume the window has been resized. const double kResizeWaitDelay = 0.2; while (mHeight != height && mWidth != width && timer->getElapsedTime() < kResizeWaitDelay) { messageLoop(); angle::Sleep(10); } return true; }
int ModulesLoaded(WPARAM, LPARAM) { if (hPluginUpdaterFolder = FoldersRegisterCustomPathT(MODULEA, LPGEN("Plugin Updater"), MIRANDA_PATHT _T("\\")DEFAULT_UPDATES_FOLDER)) { HookEvent(ME_FOLDERS_PATH_CHANGED, OnFoldersChanged); OnFoldersChanged(0, 0); } else lstrcpyn(tszRoot, VARST( _T("%miranda_path%\\"DEFAULT_UPDATES_FOLDER)), _countof(tszRoot)); int iRestartCount = db_get_b(NULL, MODNAME, DB_SETTING_RESTART_COUNT, 2); if (iRestartCount > 0) db_set_b(NULL, MODNAME, DB_SETTING_RESTART_COUNT, iRestartCount - 1); else EmptyFolder(); // silently CheckUpdateOnStartup(); CreateTimer(); return 0; }
void rr::on_StartSim_clicked() { if(CheckQValueBeforeStart()) { if(!bRRStart) { DisableWidgetsWhenStart(); int i = 0; for(i=0;i<MAXIMUM_PROC;i++) { memcpy(&RrProcessInfo[i],&RrProcStructInUse[i],sizeof(ProcessDef)); } CreateTimer(); gUi->StartSim->setText("Stop"); bRRStart= true; gUi->PauseSim->setText("Pause"); gUi->PauseSim->setEnabled(true); } else { EnableWidgetWhenStop(); DeleteTimer(); ClearLabelColour(); ClearRQLabels(); ClearCPULabels(); ClearBTTimeLabel(); ClearStructureForStop(); bRRStart = false; gUi->StartSim->setText("Start"); ProcessDisplayOnHMi(RrProcStructInUse); gUi->PauseSim->setEnabled(false); } } else { return; } }
//============================================================================= int Amesos_Umfpack::SymbolicFactorization() { // MS // NOTE: If you change this method, also change // MS // NumericFactorization(), because it performs part of the actions // MS // of this method. This is to avoid to ship the matrix twice // MS // (once for the symbolic factorization, and once for the numeric // MS // factorization) when it is not necessary. IsSymbolicFactorizationOK_ = false; IsNumericFactorizationOK_ = false; CreateTimer(Comm(), 2); // MS // Initialize two timers: // MS // timer 1: this will track all time spent in Amesos most // MS // important functions, *including* UMFPACK functions // MS // timer 2: this will track all time spent in this function // MS // that is not due to UMFPACK calls, and therefore it // MS // tracks down how much Amesos costs. The timer starts // MS // and ends in *each* method, unless the method does not // MS // perform any real operation. If a method calls another // MS // method, the timer will be stopped before the called // MS // method, then restared. // MS // All the time of this timer goes into "overhead" MyPID_ = Comm().MyPID(); NumProcs_ = Comm().NumProc(); AMESOS_CHK_ERR(ConvertToSerial(true)); AMESOS_CHK_ERR(ConvertToUmfpackCRS()); AMESOS_CHK_ERR(PerformSymbolicFactorization()); IsSymbolicFactorizationOK_ = true; NumSymbolicFact_++; return 0; }
//============================================================================= int Amesos_Umfpack::NumericFactorization() { IsNumericFactorizationOK_ = false; if (IsSymbolicFactorizationOK_ == false) { // Call here what is needed, to avoid double shipping of the matrix CreateTimer(Comm(), 2); MyPID_ = Comm().MyPID(); NumProcs_ = Comm().NumProc(); AMESOS_CHK_ERR(ConvertToSerial(true)); AMESOS_CHK_ERR(ConvertToUmfpackCRS()); AMESOS_CHK_ERR(PerformSymbolicFactorization()); IsSymbolicFactorizationOK_ = true; NumSymbolicFact_++; AMESOS_CHK_ERR(PerformNumericFactorization()); } else { // need to reshuffle and reconvert because entry values may have changed AMESOS_CHK_ERR(ConvertToSerial(false)); AMESOS_CHK_ERR(ConvertToUmfpackCRS()); AMESOS_CHK_ERR(PerformNumericFactorization()); } NumNumericFact_++; IsNumericFactorizationOK_ = true; return 0; }
Displacements::Displacements(Mesh * source, Skeleton * srcSkeleton, int numberSteps, int numIteration, float smoothStepSize, bool isVolumePreserve) { this->sourceMesh = source; this->skeleton = srcSkeleton; CreateTimer(timer); stats["smoothing"] = Stats("Base extraction (smoothing)"); // Create smooth stairway structure stair = SmoothStairway(source, numberSteps, numIteration, smoothStepSize, isVolumePreserve); stats["smoothing"].end(); printf("\n\n\nSmooth stairway time (%d ms).\n", (int)timer.elapsed()); this->isVisible = true; this->isUserFriendly = false; this->isDrawStair = false; this->isReady = false; }
SampleApplication::SampleApplication(const std::string &name, size_t width, size_t height, EGLint glesMajorVersion, EGLint glesMinorVersion, EGLint requestedRenderer) : mName(name), mWidth(width), mHeight(height), mRunning(false) { mEGLWindow.reset(new EGLWindow(glesMajorVersion, glesMinorVersion, EGLPlatformParameters(requestedRenderer))); mTimer.reset(CreateTimer()); mOSWindow.reset(CreateOSWindow()); mEGLWindow->setConfigRedBits(8); mEGLWindow->setConfigGreenBits(8); mEGLWindow->setConfigBlueBits(8); mEGLWindow->setConfigAlphaBits(8); mEGLWindow->setConfigDepthBits(24); mEGLWindow->setConfigStencilBits(8); // Disable vsync mEGLWindow->setSwapInterval(0); }
int CUstpFtdcMduserApi::QuoteProc() { //pthread_t m_tid; //pthread_attr_t pthread_attr; //read quote from file m_quoteFetcher.SetFilePath(m_acQuoteFile); m_quoteFetcher.Init(&m_QuoteQueue); //init quote fetch thread m_quoteFetcher.Start(); //create a thread to send quote /*pthread_attr_init(&pthread_attr); pthread_attr_setdetachstate(&pthread_attr, PTHREAD_CREATE_DETACHED); if (0 != pthread_create(&m_tid,&pthread_attr,SendQuoteThreadFunc,this)) { g_log.error("Fail to create thread to send quote:%s\n", strerror(errno)); return ATF_FAIL; }*/ CreateTimer(); return ATF_SUCC; }
UINT_PTR FASTCALL IntSetTimer( PWND Window, UINT_PTR IDEvent, UINT Elapse, TIMERPROC TimerFunc, INT Type) { PTIMER pTmr; UINT Ret = IDEvent; LARGE_INTEGER DueTime; DueTime.QuadPart = (LONGLONG)(-5000000); #if 0 /* Windows NT/2k/XP behaviour */ if (Elapse > MAX_ELAPSE_TIME) { TRACE("Adjusting uElapse\n"); Elapse = 1; } #else /* Windows XP SP2 and Windows Server 2003 behaviour */ if (Elapse > MAX_ELAPSE_TIME) { TRACE("Adjusting uElapse\n"); Elapse = MAX_ELAPSE_TIME; } #endif /* Windows 2k/XP and Windows Server 2003 SP1 behaviour */ if (Elapse < 10) { TRACE("Adjusting uElapse\n"); Elapse = 10; } /* Passing an IDEvent of 0 and the SetTimer returns 1. It will create the timer with an ID of 0 */ if ((Window) && (IDEvent == 0)) Ret = 1; pTmr = FindTimer(Window, IDEvent, Type); if ((!pTmr) && (Window == NULL) && (!(Type & TMRF_SYSTEM))) { IntLockWindowlessTimerBitmap(); IDEvent = RtlFindClearBitsAndSet(&WindowLessTimersBitMap, 1, HintIndex); if (IDEvent == (UINT_PTR) -1) { IntUnlockWindowlessTimerBitmap(); ERR("Unable to find a free window-less timer id\n"); EngSetLastError(ERROR_NO_SYSTEM_RESOURCES); ASSERT(FALSE); return 0; } IDEvent = NUM_WINDOW_LESS_TIMERS - IDEvent; Ret = IDEvent; IntUnlockWindowlessTimerBitmap(); } if (!pTmr) { pTmr = CreateTimer(); if (!pTmr) return 0; if (Window && (Type & TMRF_TIFROMWND)) pTmr->pti = Window->head.pti->pEThread->Tcb.Win32Thread; else { if (Type & TMRF_RIT) pTmr->pti = ptiRawInput; else pTmr->pti = PsGetCurrentThreadWin32Thread(); } pTmr->pWnd = Window; pTmr->cmsCountdown = Elapse; pTmr->cmsRate = Elapse; pTmr->pfn = TimerFunc; pTmr->nID = IDEvent; pTmr->flags = Type|TMRF_INIT; } else { pTmr->cmsCountdown = Elapse; pTmr->cmsRate = Elapse; } ASSERT(MasterTimer != NULL); // Start the timer thread! if (TimersListHead.Flink == TimersListHead.Blink) // There is only one timer KeSetTimer(MasterTimer, DueTime, NULL); return Ret; }
PR_IMPLEMENT(PRStatus) PR_AddWaitFileDesc( PRWaitGroup *group, PRRecvWait *desc) { _PR_HashStory hrv; PRStatus rv = PR_FAILURE; #ifdef WINNT _MDOverlapped *overlapped; HANDLE hFile; BOOL bResult; DWORD dwError; PRFileDesc *bottom; #endif if (!_pr_initialized) _PR_ImplicitInitialization(); if ((NULL == group) && (NULL == (group = MW_Init2()))) { return rv; } PR_ASSERT(NULL != desc->fd); desc->outcome = PR_MW_PENDING; /* nice, well known value */ desc->bytesRecv = 0; /* likewise, though this value is ambiguious */ PR_Lock(group->ml); if (_prmw_running != group->state) { /* Not allowed to add after cancelling the group */ desc->outcome = PR_MW_INTERRUPT; PR_SetError(PR_INVALID_STATE_ERROR, 0); PR_Unlock(group->ml); return rv; } #ifdef WINNT _PR_MD_LOCK(&group->mdlock); #endif /* ** If the waiter count is zero at this point, there's no telling ** how long we've been idle. Therefore, initialize the beginning ** of the timing interval. As long as the list doesn't go empty, ** it will maintain itself. */ if (0 == group->waiter->count) group->last_poll = PR_IntervalNow(); do { hrv = MW_AddHashInternal(desc, group->waiter); if (_prmw_rehash != hrv) break; hrv = MW_ExpandHashInternal(group); /* gruesome */ if (_prmw_success != hrv) break; } while (PR_TRUE); #ifdef WINNT _PR_MD_UNLOCK(&group->mdlock); #endif PR_NotifyCondVar(group->new_business); /* tell the world */ rv = (_prmw_success == hrv) ? PR_SUCCESS : PR_FAILURE; PR_Unlock(group->ml); #ifdef WINNT overlapped = PR_NEWZAP(_MDOverlapped); if (NULL == overlapped) { PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); NT_HashRemove(group, desc->fd); return rv; } overlapped->ioModel = _MD_MultiWaitIO; overlapped->data.mw.desc = desc; overlapped->data.mw.group = group; if (desc->timeout != PR_INTERVAL_NO_TIMEOUT) { overlapped->data.mw.timer = CreateTimer( desc->timeout, NT_TimeProc, overlapped); if (0 == overlapped->data.mw.timer) { NT_HashRemove(group, desc->fd); PR_DELETE(overlapped); /* * XXX It appears that a maximum of 16 timer events can * be outstanding. GetLastError() returns 0 when I try it. */ PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, GetLastError()); return PR_FAILURE; } } /* Reach to the bottom layer to get the OS fd */ bottom = PR_GetIdentitiesLayer(desc->fd, PR_NSPR_IO_LAYER); PR_ASSERT(NULL != bottom); if (NULL == bottom) { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return PR_FAILURE; } hFile = (HANDLE)bottom->secret->md.osfd; if (!bottom->secret->md.io_model_committed) { PRInt32 st; st = _md_Associate(hFile); PR_ASSERT(0 != st); bottom->secret->md.io_model_committed = PR_TRUE; } bResult = ReadFile(hFile, desc->buffer.start, (DWORD)desc->buffer.length, NULL, &overlapped->overlapped); if (FALSE == bResult && (dwError = GetLastError()) != ERROR_IO_PENDING) { if (desc->timeout != PR_INTERVAL_NO_TIMEOUT) { if (InterlockedCompareExchange((LONG *)&desc->outcome, (LONG)PR_MW_FAILURE, (LONG)PR_MW_PENDING) == (LONG)PR_MW_PENDING) { CancelTimer(overlapped->data.mw.timer); } NT_HashRemove(group, desc->fd); PR_DELETE(overlapped); } _PR_MD_MAP_READ_ERROR(dwError); rv = PR_FAILURE; } #endif return rv; } /* PR_AddWaitFileDesc */
/** * Event callback (player_death) * The player is about to die. * * @param iVictim The victim index. * @param iAttacker The attacker index. **/ void DeathOnClientDeath(int iVictim, int iAttacker) { // Get real player index from event key CBasePlayer* cBaseVictim = view_as<CBasePlayer>(iVictim); CBasePlayer* cBaseAttacker = view_as<CBasePlayer>(iAttacker); // Remove glowing cBaseVictim->m_bSetGlow(false); // Remove night vision cBaseVictim->m_bNightVisionOn = 0; // Clear any existing overlay from screen if(RoundEndGetRoundValidate()) { ToolsSwitchLevel(cBaseVictim, UNVALID_MESSAGE_ID); } // Emit scream sound cBaseVictim->InputEmitAISound(SNDCHAN_VOICE, SNDLEVEL_SCREAMING, (ZombieIsFemale(cBaseVictim->m_nZombieClass)) ? "ZOMBIE_FEMALE_DEATH_SOUNDS" : "ZOMBIE_DEATH_SOUNDS", true); // Player was killed by other ? if(cBaseVictim != cBaseAttacker) { // If respawn amount more, than limit, stop if(cBaseVictim->m_nRespawnTimes > GetConVarInt(gCvarList[CVAR_RESPAWN_AMOUNT])) { return; } // Verify that the attacker is connected and alive if(IsPlayerExist(view_as<int>(cBaseAttacker))) { // Give ammopacks for kill cBaseAttacker->m_nAmmoPacks += GetConVarInt(gCvarList[CVAR_BONUS_KILL]); // Level system work only for humans and zombies if(!cBaseAttacker->m_bNemesis && !cBaseAttacker->m_bSurvivor) { if(GetConVarBool(gCvarList[CVAR_LVL_SYSTEM]) && cBaseAttacker->m_iLevel < 10) { // Increment level cBaseAttacker->m_iLevel++; // Update overlays and speed ToolsSwitchLevel(cBaseAttacker, cBaseAttacker->m_iLevel); ToolsIncreaseSpeed(cBaseAttacker, cBaseAttacker->m_iLevel); } } } } // If player was killed by world, respawn on suicide? else if (!GetConVarBool(gCvarList[CVAR_RESPAWN_WORLD])) { return; } // Respawn if human/zombie/nemesis/survivor? if ((cBaseVictim->m_bZombie && !cBaseVictim->m_bNemesis && !GetConVarBool(gCvarList[CVAR_RESPAWN_ZOMBIE])) || (!cBaseVictim->m_bZombie && !cBaseVictim->m_bSurvivor && !GetConVarBool(gCvarList[CVAR_RESPAWN_HUMAN])) || (cBaseVictim->m_bNemesis && !GetConVarBool(gCvarList[CVAR_RESPAWN_NEMESIS])) || (cBaseVictim->m_bSurvivor && !GetConVarBool(gCvarList[CVAR_RESPAWN_SURVIVOR]))) { return; } // Increment count cBaseVictim->m_nRespawnTimes++; // Set timer for respawn player EndTimer(Task_ZombieRespawn[view_as<int>(cBaseVictim)]); Task_ZombieRespawn[view_as<int>(cBaseVictim)] = CreateTimer(GetConVarFloat(gCvarList[CVAR_RESPAWN_TIME]), EventRespawnZombie, view_as<int>(cBaseVictim)); }
//============================================================================= int Amesos_Paraklete::SymbolicFactorization() { MyPID_ = Comm().MyPID(); NumProcs_ = Comm().NumProc(); IsSymbolicFactorizationOK_ = false; IsNumericFactorizationOK_ = false; #ifdef HAVE_AMESOS_EPETRAEXT transposer_ = static_cast<Teuchos::ENull>( 0 ); #endif CreateTimer(Comm(), 2); ResetTimer(1); // "overhead" time for the following method is considered here AMESOS_CHK_ERR( CreateLocalMatrixAndExporters() ) ; assert( NumGlobalElements_ == RowMatrixA_->NumGlobalCols() ); SetMaxProcesses(MaxProcesses_, *RowMatrixA_); // // Perform checks in SymbolicFactorization(), but none in // NumericFactorization() or Solve() // assert( ! TrustMe_ ) ; if ( TrustMe_ ) { if ( CrsMatrixA_ == 0 ) AMESOS_CHK_ERR(10 ); if( UseDataInPlace_ != 1 ) AMESOS_CHK_ERR( 10 ) ; if( Reindex_ ) AMESOS_CHK_ERR( 10 ) ; if( ! Problem_->GetLHS() ) AMESOS_CHK_ERR( 10 ) ; if( ! Problem_->GetRHS() ) AMESOS_CHK_ERR( 10 ) ; if( ! Problem_->GetLHS()->NumVectors() ) AMESOS_CHK_ERR( 10 ) ; if( ! Problem_->GetRHS()->NumVectors() ) AMESOS_CHK_ERR( 10 ) ; SerialB_ = Problem_->GetRHS() ; SerialX_ = Problem_->GetLHS() ; NumVectors_ = SerialX_->NumVectors(); if (MyPID_ == 0) { AMESOS_CHK_ERR(SerialX_->ExtractView(&SerialXBvalues_,&SerialXlda_ )); AMESOS_CHK_ERR(SerialB_->ExtractView(&SerialBvalues_,&SerialXlda_ )); } } PrivateParakleteData_->common_ = rcp(new paraklete_common()); const Epetra_MpiComm* MpiComm = dynamic_cast<const Epetra_MpiComm*>(&Comm()); assert (MpiComm != 0); MPI_Comm PK_Comm; // // Create an MPI group with MaxProcesses_ processes // if ( MaxProcesses_ != Comm().NumProc()) { if(ParakleteComm_) { MPI_Comm_free(&ParakleteComm_); ParakleteComm_ = 0 ; } std::vector<int> ProcsInGroup(MaxProcesses_); IamInGroup_ = false; for (int i = 0 ; i < MaxProcesses_ ; ++i) { ProcsInGroup[i] = i; if ( Comm().MyPID() == i ) IamInGroup_ = true; } MPI_Group OrigGroup, ParakleteGroup; MPI_Comm_group(MpiComm->GetMpiComm(), &OrigGroup); MPI_Group_incl(OrigGroup, MaxProcesses_, &ProcsInGroup[0], &ParakleteGroup); MPI_Comm_create(MpiComm->GetMpiComm(), ParakleteGroup, &ParakleteComm_); PK_Comm = ParakleteComm_ ; } else { IamInGroup_ = true; PK_Comm = MpiComm->GetMpiComm() ; } paraklete_common& pk_common = *PrivateParakleteData_->common_ ; cholmod_common *cm = &(pk_common.cm) ; amesos_cholmod_l_start (cm) ; PK_DEBUG_INIT ("pk", cm) ; pk_common.nproc = MaxProcesses_ ; pk_common.myid = Comm().MyPID() ; //pk_common.mpicomm = PK_Comm ; cm->print = 1 ; cm->precise = TRUE ; cm->error_handler = my_handler ; pk_common.tol_diag = 0.001 ; pk_common.tol_offdiag = 0.1 ; pk_common.growth = 2. ; // "overhead" time for the following two methods is considered here AMESOS_CHK_ERR( ExportToSerial() ); AMESOS_CHK_ERR( ConvertToParakleteCRS(true) ); OverheadTime_ = AddTime("Total Amesos overhead time", OverheadTime_, 1); // All this time if PARAKLETE time AMESOS_CHK_ERR( PerformSymbolicFactorization() ); NumSymbolicFact_++; IsSymbolicFactorizationOK_ = true; return 0; }
bool VirtualDimension::Start(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; RECT pos; Settings settings; HWND hwndPrev; DWORD dwStyle; // If a previous instance is running, activate // that instance and terminate this one. hwndPrev = FindWindow(); if (hwndPrev != NULL) { SetForegroundWindow (hwndPrev); return false; } m_hInstance = hInstance; InitHotkeyControl(); InitHyperLinkControl(); // Register the window class RegisterClass(); // Bind the message handlers SetCommandHandler(IDM_ABOUT, this, &VirtualDimension::OnCmdAbout); SetSysCommandHandler(IDM_ABOUT, this, &VirtualDimension::OnCmdAbout); SetCommandHandler(IDM_CONFIGURE, this, &VirtualDimension::OnCmdConfigure); SetSysCommandHandler(IDM_CONFIGURE, this, &VirtualDimension::OnCmdConfigure); SetCommandHandler(IDM_EXIT, this, &VirtualDimension::OnCmdExit); SetSysCommandHandler(SC_CLOSE, this, &VirtualDimension::OnCmdExit); SetCommandHandler(IDM_LOCKPREVIEWWND, this, &VirtualDimension::OnCmdLockPreviewWindow); SetSysCommandHandler(IDM_LOCKPREVIEWWND, this, &VirtualDimension::OnCmdLockPreviewWindow); SetCommandHandler(IDM_SHOWCAPTION, this, &VirtualDimension::OnCmdShowCaption); SetSysCommandHandler(IDM_SHOWCAPTION, this, &VirtualDimension::OnCmdShowCaption); SetMessageHandler(WM_DESTROY, this, &VirtualDimension::OnDestroy); SetMessageHandler(WM_ENDSESSION, this, &VirtualDimension::OnEndSession); SetMessageHandler(WM_MOVE, this, &VirtualDimension::OnMove); SetMessageHandler(WM_WINDOWPOSCHANGING, this, &VirtualDimension::OnWindowPosChanging); SetMessageHandler(WM_DISPLAYCHANGE, this, &VirtualDimension::OnDisplayChange); SetMessageHandler(WM_SHOWWINDOW, this, &VirtualDimension::OnShowWindow); SetMessageHandler(WM_LBUTTONDOWN, this, &VirtualDimension::OnLeftButtonDown); SetMessageHandler(WM_LBUTTONUP, this, &VirtualDimension::OnLeftButtonUp); SetMessageHandler(WM_LBUTTONDBLCLK, this, &VirtualDimension::OnLeftButtonDblClk); SetMessageHandler(WM_RBUTTONDOWN, this, &VirtualDimension::OnRightButtonDown); SetMessageHandler(WM_MEASUREITEM, this, &VirtualDimension::OnMeasureItem); SetMessageHandler(WM_DRAWITEM, this, &VirtualDimension::OnDrawItem); m_autoHideTimerId = CreateTimer(this, &VirtualDimension::OnTimer); SetMessageHandler(WM_ACTIVATEAPP, this, &VirtualDimension::OnActivateApp); SetMessageHandler(WM_MOUSEHOVER, this, &VirtualDimension::OnMouseHover); SetMessageHandler(WM_MOUSELEAVE, this, &VirtualDimension::OnMouseLeave); SetMessageHandler(WM_NCHITTEST, this, &VirtualDimension::OnNCHitTest); SetMessageHandler(WM_VD_HOOK_MENU_COMMAND, this, &VirtualDimension::OnHookMenuCommand); SetMessageHandler(WM_VD_PREPARE_HOOK_MENU, this, &VirtualDimension::OnPrepareHookMenu); SetMessageHandler(WM_VD_CHECK_MIN_TO_TRAY, this, &VirtualDimension::OnCheckMinToTray); // compare the window's style m_hasCaption = settings.LoadSetting(Settings::HasCaption); dwStyle = WS_POPUP | WS_SYSMENU | (m_hasCaption ? WS_CAPTION : WS_DLGFRAME); // Reload the window's position settings.LoadSetting(Settings::WindowPosition, &pos); AdjustWindowRectEx(&pos, dwStyle, FALSE, WS_EX_TOOLWINDOW); // Dock the window to the screen borders m_dockedBorders = settings.LoadSetting(Settings::DockedBorders); DockWindow(pos); // Create the main window Create( WS_EX_TOOLWINDOW, m_szWindowClass, m_szTitle, dwStyle, pos.left, pos.top, pos.right - pos.left, pos.bottom - pos.top, NULL, NULL, hInstance); if (!IsValid()) return false; hWnd = *this; // Load some settings m_snapSize = settings.LoadSetting(Settings::SnapSize); m_autoHideDelay = settings.LoadSetting(Settings::AutoHideDelay); m_shrinked = false; m_tracking = false; //Ensure the window gets docked if it is close enough to the borders SetWindowPos(hWnd, NULL, pos.left, pos.top, pos.right - pos.left, pos.bottom - pos.top, SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOOWNERZORDER); // Setup the system menu m_pSysMenu = GetSystemMenu(hWnd, FALSE); if (m_pSysMenu != NULL) { RemoveMenu(m_pSysMenu, SC_RESTORE, MF_BYCOMMAND); RemoveMenu(m_pSysMenu, SC_MINIMIZE, MF_BYCOMMAND); RemoveMenu(m_pSysMenu, SC_MAXIMIZE, MF_BYCOMMAND); RemoveMenu(m_pSysMenu, SC_MOVE, MF_BYCOMMAND); RemoveMenu(m_pSysMenu, SC_SIZE, MF_BYCOMMAND); RemoveMenu(m_pSysMenu, 0, MF_BYCOMMAND); AppendMenu(m_pSysMenu, MF_SEPARATOR, 0, NULL); AppendMenu(m_pSysMenu, MF_STRING, IDM_CONFIGURE, Locale::GetInstance().GetString(IDS_CONFIGURE)); //"C&onfigure" AppendMenu(m_pSysMenu, MF_STRING, IDM_LOCKPREVIEWWND, Locale::GetInstance().GetString(IDS_LOCKPREVIEWWND)); //"&Lock the window" AppendMenu(m_pSysMenu, MF_STRING, IDM_SHOWCAPTION, Locale::GetInstance().GetString(IDS_SHOWCAPTION)); //"S&how the caption" if (CreateLangMenu()) AppendMenu(m_pSysMenu, MF_STRING|MF_POPUP, (UINT_PTR)m_pLangMenu, Locale::GetInstance().GetString(IDS_LANGUAGEMENU)); //"L&anguage" AppendMenu(m_pSysMenu, MF_STRING, IDM_ABOUT, Locale::GetInstance().GetString(IDS_ABOUT)); //"&About" CheckMenuItem(m_pSysMenu, IDM_SHOWCAPTION, m_hasCaption ? MF_CHECKED : MF_UNCHECKED ); } // Lock the preview window as appropriate LockPreviewWindow(settings.LoadSetting(Settings::LockPreviewWindow)); // Bind to explorer explorerWrapper = new ExplorerWrapper(this); // Initialize the tray icon manager trayManager = new TrayIconsManager(); // Initialize tray icon trayIcon = new TrayIcon(hWnd); // Initialize transparency (set value two times, to make a fade-in) transp = new Transparency(hWnd); transp->SetTransparencyLevel(0); transp->SetTransparencyLevel(settings.LoadSetting(Settings::TransparencyLevel), true); // Initialize always on top state ontop = new AlwaysOnTop(hWnd); ontop->SetAlwaysOnTop(settings.LoadSetting(Settings::AlwaysOnTop)); // Create the tooltip tooltip = new ToolTip(hWnd); // Create mouse warp mousewarp = new MouseWarp(); // Create the windows manager winMan = new WindowsManager; // Create the desk manager settings.LoadSetting(Settings::WindowPosition, &pos); //use client position deskMan = new DesktopManager(pos.right - pos.left, pos.bottom - pos.top); // Retrieve the initial list of windows winMan->PopulateInitialWindowsSet(); //Update tray icon tooltip trayIcon->Update(); //Bind some additional message handlers (which need the desktop manager) SetMessageHandler(WM_SIZE, this, &VirtualDimension::OnSize); SetMessageHandler(WM_PAINT, deskMan, &DesktopManager::OnPaint); // Show window if needed if (m_isWndVisible = (settings.LoadSetting(Settings::ShowWindow) || !trayIcon->HasIcon())) { ShowWindow(hWnd, nCmdShow); Refresh(); } return true; }
void Displacements::computeField(int gridSquareSize, int fitMethod, int lRotate, int rRotate) { CreateTimer(allTimer); printf("\nComputing field for selection..\n"); // Get faces and points of selected part Vector<int> selectedFaces = skeleton->getSelectedFaces(true); StdList<Face*> meshFaces = stair.mostBaseMesh()->getFacesFromIndices(selectedFaces); Vector<int> points = SET_TO_VECTOR(stair.mostBaseMesh()->getVerticesFromFaces(selectedFaces)); // Convert selected skeleton part into points in space Vector<Vec> skeletonPoints = skeleton->getSelectedSkeletonPoints(); // Make sure we have a smooth and nicely sampled spine while((int)skeletonPoints.size() < gridSquareSize) { skeleton->smoothSelectedEdges(4); skeletonPoints = skeleton->getSelectedSkeletonPoints(); } // Compute length by traveling spine float gridLength = 0; for(int i = 0; i < (int)skeletonPoints.size() - 1; i++) gridLength += Vec(skeletonPoints[i] - skeletonPoints[i+1]).norm(); // Figure out maximum point on base surface to use as radius (there might be a faster way) HistogramFloat histogram (1); skeleton->sampleProjectPoints(0.75f, stair.mostBaseMesh(), points, &histogram); float radius = histogram.Average(); if(radius <= 0.0f) radius = stair.mostDetailedMesh()->radius * 0.1; // just in case... CreateTimer(gridTimer); // CREATE GRID grid = Grid(skeletonPoints, radius, gridLength, gridSquareSize, &stair, meshFaces,lRotate, rRotate); printf(".Grid time (%d ms).", (int)gridTimer.elapsed()); CreateTimer(fitTimer); // FIT GRID switch(fitMethod) { case 1: // Fit using cross sections grid.FitCrossSections(); break; case 2: // Fit cylinder grid.FitCylinder( ); break; default: grid.FitNothing( ); break; } printf(".Fit time (%d ms).", (int)fitTimer.elapsed()); CreateTimer(gridifyTimer); // Assign detailed mesh points into cylindrical grid cells grid.Gridify( selectedFaces ); isReady = true; printf(".total Gridify time = %d ms\n", (int)gridifyTimer.elapsed()); printf("\n\nField time = %d ms\n=======\n", (int)allTimer.elapsed()); }
/***************************************************************************** * Makes a test case where the timer tick every 1 Ms can be checked * mostly checks the callback dummy function for accuracy in repeating * and non repeating timers. * @param None. * * @return int16_t. * * @note None. * ****************************************************************************/ int16_t Test_TimerTickEvery1Ms(void) { /*Create the timers randomly*/ int no_of_repeatations = 1000; is_soft_timer_init = rand() % 2; while(no_of_repeatations) { u16 isrepeaton = rand() % 2; int remtimer = rand() % 2; u16 count = rand(); CreateTimer(count, isrepeaton, DummyHandler); if(remtimer) { int Random_ID = RAND_ID; RemoveTimer(Random_ID); } no_of_repeatations--; } /*Start the timers*/ MakeCopy(); /* make a copy of the initial state for checking purposes.*/ for(int a=0; a < NUM_TIMER; a++ ) { call_listened[a] = 0; /*Initializing the number of times the call has been made to the callback function*/ } static double max = 0; for(int a=0; a < NUM_TIMER; a++ ) { if((max <= s_all_timers[a].count) && (s_all_timers[a].enable) ) { max = s_all_timers[a].count; } } max *= 4; /*Start the timer tick function*/ while(max) { TimerTickEvery1Ms(); max--; } /*Starting the testing*/ for(int16_t i=0; i<NUM_TIMER; i++) { /*Check whether it doesn't start the non enabled timers This case is checked for all the non enabled timers Checks whether the default values for the non enabled timers have been set properly or not*/ if(s_all_timers[i].enable == 0) { if( s_all_timers[i].Handler != NULL || s_all_timers[i].auto_repeat != 0 || s_all_timers[i].count != 0 || s_all_timers[i].id != 0xFF || s_all_timers[i].load_count !=0) { xil_printf(" Failure function started the non intended" "/enabled timers \n\r"); return ENDO_FAILURE; } } /***********************************************/ if((s_all_timers[i].auto_repeat) && (s_all_timers[i].Handler != NULL)) { /*Checking whether the repeating timers call their callback only *once or less if true then the test fails checked by the *once Call_Listened variable for *that ID*/ if((call_listened[i] == 0) || (call_listened[i] == 1) || (s_all_timers[i].Handler == NULL)) { xil_printf(" Failure the callback for repeating timers" " is not called or called only once (Repeating" " timer behaving as non repeating)\n\r"); return ENDO_FAILURE; } } /*Non repeating timers */ /*Checking whether the non-repeating timers call their callback only once if false then test fails also checks that the timer has been removed after its completion which makes them go to their default values*/ if(!(s_all_timers[i].auto_repeat)) { if((call_listened[i] == 0) || (call_listened[i] > 1) || (s_all_timers[i].Handler != NULL) || (s_all_timers[i].auto_repeat != 0) || (s_all_timers[i].count != 0) || (s_all_timers[i].enable != 0) || (s_all_timers[i].id != 0xFF) || (s_all_timers[i].load_count !=0) ) { xil_printf(" Failure non repeating timers not working" " callback not even called once or timer " "not deleted after getting over\n\r"); return ENDO_FAILURE; } } } return ENDO_SUCCESS; }
/***************************************************************************** * Makes a test case where the timer is created 1000 times for statistical * accuracy checks if the other timers are also effected by this function * also checks whether the correct timer with the correct ID is created * @param None. * * @return int16_t. * * @note None. * ****************************************************************************/ int16_t Test_CreateTimer() { /*Creating a simulation for random add and delete the timers*/ int no_of_repeatations = 1000; EndoInitTimer(); while(no_of_repeatations) { is_soft_timer_init = rand() % 2; u16 is_repeat_on = rand() % 2; int remtimer = rand() % 2; u16 count = rand(); CreateTimer(count, is_repeat_on, DummyHandler); if(remtimer) { int random_id = RAND_ID; RemoveTimer(random_id); } no_of_repeatations--; } no_of_repeatations = 1000; while(no_of_repeatations) { u16 returned_id; u16 is_repeat_on = rand() % 2; u16 count = rand(); MakeCopy(); returned_id = CreateTimer(count, is_repeat_on, DummyHandler); /*Note that checking for rid = 0xFFFF is done for exception * handling in this case it happens when the given id exceeds the * MAX number of timers*/ if(returned_id == 0XFFFF) { u16 i=0; /*Search for the first unused timer*/ while(i < NUM_TIMER) { if(s_all_timers[i].id == 0xFF) { xil_printf("The timers are not full yet create timer" " function behaving abnormally\n\r"); return ENDO_FAILURE; } i++; } EndoInitTimer(); MakeCopy(); } if(!((0 <= returned_id) && (returned_id < NUM_TIMER))) { if(returned_id != 0XFFFF) { xil_printf("The return ID for the create timer function not" " working properly\n\r"); return ENDO_FAILURE; } } /*Check to see if the values have been properly set or not for that *first starting the case whether the returned ID is a valid ID or not *particular ID*/ if(returned_id != 0XFFFF) { if( (s_all_timers[returned_id].Handler != DummyHandler) || (s_all_timers[returned_id].auto_repeat != is_repeat_on) || (s_all_timers[returned_id].count != count) || (s_all_timers[returned_id].enable != 1) || (s_all_timers[returned_id].id != returned_id) || (s_all_timers[returned_id].load_count != count)) { xil_printf("Values not getting initialized " "properly for create timer function\n\r"); return ENDO_FAILURE; } } /*Checking to see if the other ids were effected by the function use*/ if(returned_id != 0XFFFF) { int i = NUM_TIMER - 1; while(i != returned_id && i >= 0) { if( (s_all_timers[i].Handler != Temp_Copy[i].Handler) || (s_all_timers[i].auto_repeat != Temp_Copy[i].auto_repeat)|| (s_all_timers[i].count != Temp_Copy[i].count) || (s_all_timers[i].enable != Temp_Copy[i].enable) || (s_all_timers[i].id != Temp_Copy[i].id) || (s_all_timers[i].load_count != Temp_Copy[i].load_count)) { xil_printf("Failure other timers getting effected by Create" " timer function\n\r"); return ENDO_FAILURE; } i--; } } if(no_of_repeatations == 1) { return ENDO_SUCCESS; } no_of_repeatations--; } xil_printf("Unknown failure in Create Timer Function\n\r"); return ENDO_FAILURE; }
CMyTimer::CMyTimer() { CreateTimer( ); }
//============================================================================= int Amesos_Mumps::SymbolicFactorization() { // erase data if present. if (IsSymbolicFactorizationOK_ && MDS.job != -777) Destroy(); IsSymbolicFactorizationOK_ = false; IsNumericFactorizationOK_ = false; CreateTimer(Comm()); CheckParameters(); AMESOS_CHK_ERR(ConvertToTriplet(false)); #if defined(HAVE_MPI) && defined(HAVE_AMESOS_MPI_C2F) if (MaxProcs_ != Comm().NumProc()) { if(MUMPSComm_) MPI_Comm_free(&MUMPSComm_); std::vector<int> ProcsInGroup(MaxProcs_); for (int i = 0 ; i < MaxProcs_ ; ++i) ProcsInGroup[i] = i; MPI_Group OrigGroup, MumpsGroup; MPI_Comm_group(MPI_COMM_WORLD, &OrigGroup); MPI_Group_incl(OrigGroup, MaxProcs_, &ProcsInGroup[0], &MumpsGroup); MPI_Comm_create(MPI_COMM_WORLD, MumpsGroup, &MUMPSComm_); #ifdef MUMPS_4_9 MDS.comm_fortran = (MUMPS_INT) MPI_Comm_c2f( MUMPSComm_); #else #ifndef HAVE_AMESOS_OLD_MUMPS MDS.comm_fortran = (DMUMPS_INT) MPI_Comm_c2f( MUMPSComm_); #else MDS.comm_fortran = (F_INT) MPI_Comm_c2f( MUMPSComm_); #endif #endif } else { const Epetra_MpiComm* MpiComm = dynamic_cast<const Epetra_MpiComm*>(&Comm()); assert (MpiComm != 0); #ifdef MUMPS_4_9 MDS.comm_fortran = (MUMPS_INT) MPI_Comm_c2f(MpiComm->GetMpiComm()); #else #ifndef HAVE_AMESOS_OLD_MUMPS MDS.comm_fortran = (DMUMPS_INT) MPI_Comm_c2f(MpiComm->GetMpiComm()); #else MDS.comm_fortran = (F_INT) MPI_Comm_c2f(MpiComm->GetMpiComm()); #endif #endif } #else // This next three lines of code were required to make Amesos_Mumps work // with Ifpack_SubdomainFilter. They is usefull in all cases // when using MUMPS on a subdomain. const Epetra_MpiComm* MpiComm = dynamic_cast<const Epetra_MpiComm*>(&Comm()); assert (MpiComm != 0); MDS.comm_fortran = (MUMPS_INT) MPI_Comm_c2f(MpiComm->GetMpiComm()); // only thing I can do, use MPI_COMM_WORLD. This will work in serial as well // Previously, the next line was uncommented, but we don't want MUMPS to work // on the global MPI comm, but on the comm associated with the matrix // MDS.comm_fortran = -987654; #endif MDS.job = -1 ; // Initialization MDS.par = 1 ; // Host IS involved in computations // MDS.sym = MatrixProperty_; MDS.sym = 0; // MatrixProperty_ is unititalized. Furthermore MUMPS // expects only half of the matrix to be provided for // symmetric matrices. Hence setting MDS.sym to be non-zero // indicating that the matrix is symmetric will only work // if we change ConvertToTriplet to pass only half of the // matrix. Bug #2331 and Bug #2332 - low priority RedistrMatrix(true); if (Comm().MyPID() < MaxProcs_) { dmumps_c(&(MDS)); // Initialize MUMPS static_cast<void>( CheckError( ) ); } MDS.n = Matrix().NumGlobalRows(); // fix pointers for nonzero pattern of A. Numerical values // will be entered in PerformNumericalFactorization() if (Comm().NumProc() != 1) { MDS.nz_loc = RedistrMatrix().NumMyNonzeros(); if (Comm().MyPID() < MaxProcs_) { MDS.irn_loc = &Row[0]; MDS.jcn_loc = &Col[0]; } } else { if (Comm().MyPID() == 0) { MDS.nz = Matrix().NumMyNonzeros(); MDS.irn = &Row[0]; MDS.jcn = &Col[0]; } } // scaling if provided by the user if (RowSca_ != 0) { MDS.rowsca = RowSca_; MDS.colsca = ColSca_; } // given ordering if provided by the user if (PermIn_ != 0) { MDS.perm_in = PermIn_; } MDS.job = 1; // Request symbolic factorization SetICNTLandCNTL(); // Perform symbolic factorization ResetTimer(); if (Comm().MyPID() < MaxProcs_) dmumps_c(&(MDS)); SymFactTime_ = AddTime("Total symbolic factorization time", SymFactTime_); int IntWrong = CheckError()?1:0 ; int AnyWrong; Comm().SumAll( &IntWrong, &AnyWrong, 1 ) ; bool Wrong = AnyWrong > 0 ; if ( Wrong ) { AMESOS_CHK_ERR( StructurallySingularMatrixError ) ; } IsSymbolicFactorizationOK_ = true ; NumSymbolicFact_++; return 0; }
void DelayedAction::Initialize() { CreateTimer(); }
bool CStimResponseCollection::ParseSpawnArg( const idDict &args, idEntity *owner, const char sr_class, int index ) { bool rc = false; idStr str; CStimPtr stim; CResponsePtr resp; CStimResponsePtr sr; StimState state( SS_DISABLED ); StimType typeOfStim; // Check if the entity contains either a stim or a response. if( sr_class != 'S' && sr_class != 'R' ) { DM_LOG( LC_STIM_RESPONSE, LT_ERROR )LOGSTRING( "Invalid sr_class value [%s]\r", str.c_str() ); goto Quit; } // Get the id of the stim/response type so we know what sub-class to create args.GetString( va( "sr_type_%u", index ), "-1", str ); // This is invalid as an entity definition if( str == "-1" ) { sr.reset(); goto Quit; } // If the first character is alphanumeric, we check if it // is a known id and convert it. /* StimType */ typeOfStim = ST_DEFAULT; if( ( str[0] >= 'a' && str[0] <= 'z' ) || ( str[0] >= 'A' && str[0] <= 'Z' ) ) { // Try to recognise the string as known Stim type typeOfStim = CStimResponse::GetStimType( str ); // If the string hasn't been found, we have id == ST_DEFAULT. if( typeOfStim == ST_DEFAULT ) { DM_LOG( LC_STIM_RESPONSE, LT_ERROR )LOGSTRING( "Invalid sr_type id [%s]\r", str.c_str() ); sr.reset(); goto Quit; } } else if( str[0] >= '0' && str[0] <= '9' ) { // Is it numeric? typeOfStim = ( StimType ) atol( str.c_str() ); } else { // neither a character nor a number, thus it is invalid. DM_LOG( LC_STIM_RESPONSE, LT_ERROR )LOGSTRING( "Invalid sr_type id [%s]\r", str.c_str() ); sr.reset(); goto Quit; } if( sr_class == 'S' ) { stim = CreateStim( owner, typeOfStim ); if( stim == NULL ) { // grayman #2862 goto Quit; // nasty goto!! } sr = stim; } else if( sr_class == 'R' ) { resp = CreateResponse( owner, typeOfStim ); sr = resp; } // Set stim response type sr->m_StimTypeId = typeOfStim; // Set stim response name string sr->m_StimTypeName = str; // Read stim response state from the def file state = static_cast<StimState>( args.GetInt( va( "sr_state_%u", index ), "1" ) ); sr->SetEnabled( state == SS_ENABLED ); sr->m_Chance = args.GetFloat( va( "sr_chance_%u", index ), "1.0" ); // A stim also may have a radius if( sr_class == 'S' ) { stim->m_Radius = args.GetFloat( va( "sr_radius_%u", index ), "0" ); stim->m_RadiusFinal = args.GetFloat( va( "sr_radius_final_%u", index ), "-1" ); stim->m_FallOffExponent = args.GetInt( va( "sr_falloffexponent_%u", index ), "0" ); stim->m_bUseEntBounds = args.GetBool( va( "sr_use_bounds_%u", index ), "0" ); stim->m_bCollisionBased = args.GetBool( va( "sr_collision_%u", index ), "0" ); stim->m_Velocity = args.GetVector( va( "sr_velocity_%u", index ), "0 0 0" ); stim->m_Bounds[0] = args.GetVector( va( "sr_bounds_mins_%u", index ), "0 0 0" ); stim->m_Bounds[1] = args.GetVector( va( "sr_bounds_maxs_%u", index ), "0 0 0" ); // set up time interleaving so the stim isn't fired every frame stim->m_TimeInterleave = args.GetInt( va( "sr_time_interval_%u", index ), "0" ); // greebo: Add fuzzyness to the timer (ranging from 0.9 - 1.3); stim->m_TimeInterleave = static_cast<int>( stim->m_TimeInterleave * ( 0.9f + gameLocal.random.RandomFloat() * 0.4f ) ); // userfriendly stim duration time stim->m_Duration = args.GetInt( va( "sr_duration_%u", index ), "0" ); stim->m_Magnitude = args.GetFloat( va( "sr_magnitude_%u", index ), "1.0" ); stim->m_MaxFireCount = args.GetInt( va( "sr_max_fire_count_%u", index ), "-1" ); // Check if we have a timer on this stim. CreateTimer( args, stim, index ); } else { // this is only for responses sr->m_ChanceTimer = args.GetInt( va( "sr_chance_timeout_%u", index ), "-1" ); resp->m_NumRandomEffects = args.GetInt( va( "sr_random_effects_%u", index ), "0" ); // Get the name of the script function for processing the response args.GetString( "sr_script_" + str, "", str ); resp->m_ScriptFunction = str; // Try to identify the ResponseEffect spawnargs int effectIdx = 1; while( effectIdx > 0 ) { // Try to find a string like "sr_effect_2_1" args.GetString( va( "sr_effect_%u_%u", index, effectIdx ), "", str ); if( str.IsEmpty() ) { // Set the index to negative values to end the loop effectIdx = -1; } else { // Assemble the postfix of this effect for later key/value lookup // This is passed to the effect script eventually DM_LOG( LC_STIM_RESPONSE, LT_DEBUG )LOGSTRING( "Adding response effect\r" ); resp->AddResponseEffect( str, va( "%u_%u", index, effectIdx ), args ); effectIdx++; } } } rc = true; Quit: if( sr != NULL ) { if( stim != NULL ) { DM_LOG( LC_STIM_RESPONSE, LT_DEBUG )LOGSTRING( "Stim %s added to collection for %s\r", stim->m_StimTypeName.c_str(), owner->name.c_str() ); AddStim( stim ); stim->m_State = state; } if( resp != NULL ) { DM_LOG( LC_STIM_RESPONSE, LT_DEBUG )LOGSTRING( "Response %s added to collection for %s\r", resp->m_StimTypeName.c_str(), owner->name.c_str() ); AddResponse( resp ); } } return rc; }
void McuMessageHandler::ProcessHandshake(int len, int seq) { if(len < 2) { LogUtility::Log(LOG_LEVEL_ERROR, "McuMessageHandler::ProcessHandshake len invalid."); return; } if(PopQueue(MCU_PACKET_HANDSHAKE, seq, NULL, NULL) < 0) { LogUtility::Log(LOG_LEVEL_ERROR, "McuMessageHandler::ProcessHandshake out of order."); return; } unsigned char flag = MCU_GET_BYTE(m_rxPacket, 7); if(flag != 0x01) { LogUtility::Log(LOG_LEVEL_ERROR, "McuMessageHandler::ProcessHandshake invalid flag %d.", flag); return; } unsigned char number = MCU_GET_BYTE(m_rxPacket, 8); if((len < number + 1) || (number > MCU_MAX_POS)) { LogUtility::Log(LOG_LEVEL_ERROR, "McuMessageHandler::ProcessHandshake number invalid %d.", number); return; } m_pos_num = number; LogUtility::Log(LOG_LEVEL_INFO, "McuMessageHandler::ProcessHandshake pos number %d.", m_pos_num); for(int i = 0; i < number; i ++) { m_pos_addr[i] = MCU_GET_BYTE(m_rxPacket, 9 + i); LogUtility::Log(LOG_LEVEL_INFO, "McuMessageHandler::ProcessHandshake pos %d addr: %d.", i, m_pos_addr[i]); } m_handshake = true; m_passengerRecord = new StruPassengerRecord[m_pos_num]; for(int i = 0; i < m_pos_num; i ++) { m_passengerRecord[i].passengerUpCount = 0; m_passengerRecord[i].accuPassengerUpCount = 0; m_passengerRecord[i].passengerDownCount = 0; m_passengerRecord[i].accuPassengerDownCount = 0; m_passengerRecord[i].dealCount = 0; m_passengerRecord[i].lastDealCount = 0; m_passengerRecord[i].posPassengerRecordTimer = CreateTimer(MCU_PASSENGER_RECORD_TIMER, TIMER_SEC_TO_MSEC(MCU_PASSENGER_INTERVAL + i), this, McuTimerHandler, false); m_passengerRecord[i].state = STATE_TIMER; m_passengerRecord[i].posPassengerRecordTimer->data2 = (void *)i; StartTimer(m_passengerRecord[i].posPassengerRecordTimer); } m_passengerup_count = 0; m_passengerdown_count = 0; StartTimer(m_dealReportTimer); StartTimer(m_CanDataTimer); StartTimer(m_CanUploadTimer); return; }
int CBaseVision::Active() { GetProcInfo(); signal(SIGCHLD, sig_chld); m_mapShmKey.clear(); string strAbsName = ""; // 存在父进程? if (!m_ppname.empty()) { strAbsName = m_strCwd + string("/") + m_pname; key_t shmkey; // 注册通信模块 if ((shmkey = CMt::mt_init(SHM_MODE, strAbsName.c_str(), m_pid, GetShmSize(m_pname), sizeof(FEEDBACK_DATA))) == -1) { LOGE("%s register share memory connection module error. %s : %d\n", m_pname.c_str(), __FILE__, __LINE__); return -1; } m_mapShmKey[m_pname] = shmkey; strAbsName = m_strCwd + string("/") + m_ppname; // 注册消息发送模块 (ppname, ppid) : key if ((m_skey = CMt::mt_init(SEM_MODE, strAbsName.c_str(), m_ppid)) == -1) { LOGE("%s register msg module error. %s : %d\n", m_pname.c_str(), __FILE__, __LINE__); return -1; } // 注册消息发送定时器 #key CreateTimer(SendHeartBeat, &m_sTimerid, this); // 启动定时器 SetTimer(m_sTimerid); } // 存在子进程? if (m_vProcInfo.size() > 0) { // 注册通信模块 vector<PROC_INFO>::iterator itr = m_vProcInfo.begin(); for (; itr != m_vProcInfo.end(); ++itr) { strAbsName = m_strCwd + string("/") + itr->pname; key_t key = CMt::mt_init(SHM_MODE, strAbsName.c_str(), itr->pid, GetShmSize(itr->pname), sizeof(FEEDBACK_DATA)); if (-1 == key) { LOGE("%s register share memory connection module error. %s : %d\n", m_pname.c_str(), __FILE__, __LINE__); return -1; } m_mapShmKey[itr->pname] = key; } strAbsName = m_strCwd + string("/") + m_pname; // 注册消息接收模块 (pname, pid) if ((m_rkey = CMt::mt_init(SEM_MODE, strAbsName.c_str(), m_pid)) == -1) { LOGE("%s register msg module error. %s : %d\n", m_pname.c_str(), __FILE__, __LINE__); return -1; } // 注册消息接收定时器 CreateTimer(RecvHeartBeat, &m_rTimerid, this); // 启动定时器 SetTimer(m_rTimerid); } // 默认注册线程函数Run RegisterPthread(&CBaseVision::Run); return 0; }