Пример #1
0
void CSignalTimer::Wait()
{
  CLock lock(m_condition);

  //keep looping until we have a timestamp that's not too old
  int64_t now = GetTimeUs();
  int64_t sleeptime;
  do
  {
    m_time += m_interval;
    sleeptime = m_time - now;
  }
  while(sleeptime <= m_interval * -2LL);
  
  if (sleeptime > m_interval * 2LL) //failsafe, m_time must be bork if we get here
  {
    sleeptime = m_interval * 2LL;
    Reset();
  }

  //wait for the timeout, or for the condition variable to be signaled
  while (!m_signaled && sleeptime > 0LL && !(m_timerstop && *m_timerstop))
  {
    m_condition.Wait(Min(sleeptime, 1000000LL));
    now = GetTimeUs();
    sleeptime = m_time - now;
  }

  //if we get signaled, reset the timestamp, this allows us to be signaled faster than the interval
  if (m_signaled)
  {
    Reset();
    m_signaled = false;
  }
}
Пример #2
0
void CDevice::Process()
{
  if (m_output.empty())
    Log("%s: starting", m_name.c_str());
  else
    Log("%s: starting with output \"%s\"", m_name.c_str(), m_output.c_str());
  
  if (m_setpriority)
  {
    sched_param param = {};
    param.sched_priority = m_threadpriority;
    int returnv = pthread_setschedparam(m_thread, SCHED_FIFO, &param);
    if (returnv == 0)
      Log("%s: successfully set thread priority to %i", m_name.c_str(), m_threadpriority);
    else
      LogError("%s: error setting thread priority to %i: %s", m_name.c_str(), m_threadpriority, GetErrno(returnv).c_str());
  }

  int64_t setuptime;

  while(!m_stop)
  {
    //keep trying to set up the device every 10 seconds
    while(!m_stop)
    {
      Log("%s: setting up", m_name.c_str());

      setuptime = GetTimeUs();
      if (!SetupDevice())
      {
        CloseDevice();
	LogError("%s: setting up failed, retrying in 10 seconds", m_name.c_str());
        USleep(10000000LL, &m_stop);
      }
      else
      {
	Log("%s: setup succeeded", m_name.c_str());
        break;
      }
    }

    //keep calling writeoutput until we're asked to stop or writeoutput fails
    while(!m_stop)
    {
      if (!WriteOutput())
      {
        //make sure to wait at least one second before trying to set up again
        Log("%s: io operation failed, retry to setup", m_name.c_str());
        USleep(Max(1000000LL - (GetTimeUs() - setuptime), 0));
        break;
      }
    }

    CloseDevice();

    Log("%s: closed", m_name.c_str());
  }

  Log("%s: stopped", m_name.c_str());
}
Пример #3
0
bool CLuaArguments::CallGlobal ( CLuaMain* pLuaMain, const char* szFunction, CLuaArguments * returnValues ) const
{
    assert ( pLuaMain );
    assert ( szFunction );
    TIMEUS startTime = GetTimeUs ();

    // Add the function name to the stack and get the event from the table
    lua_State* luaVM = pLuaMain->GetVirtualMachine ();
    assert ( luaVM );
    LUA_CHECKSTACK ( luaVM, 1 );
    int luaStackPointer = lua_gettop ( luaVM );
    lua_pushstring ( luaVM, szFunction );
    lua_gettable ( luaVM, LUA_GLOBALSINDEX );

    // Push our arguments onto the stack
    PushArguments ( luaVM );

    // Call the function with our arguments
    pLuaMain->ResetInstructionCount ();
    int iret = 0;
    try {
        iret = lua_pcall ( luaVM, m_Arguments.size (), LUA_MULTRET, 0 );
    }
    catch ( ... )
    {
        return false;
    }
    if ( iret == LUA_ERRRUN || iret == LUA_ERRMEM )
    {
        std::string strRes = ConformResourcePath ( lua_tostring( luaVM, -1 ) );
        g_pGame->GetScriptDebugging()->LogError ( luaVM, "%s", strRes.c_str () );

        // cleanup the stack
        while ( lua_gettop ( luaVM ) - luaStackPointer > 0 )
            lua_pop ( luaVM, 1 );

        return false; // the function call failed
    }
    else
    {
        int iReturns = lua_gettop ( luaVM ) - luaStackPointer;

        if ( returnValues != NULL )
        {
            for ( int i = - iReturns; i <= -1; i++ )
            {
                returnValues->ReadArgument ( luaVM, i );
            }
        }

        // cleanup the stack
        while ( lua_gettop ( luaVM ) - luaStackPointer > 0 )
            lua_pop ( luaVM, 1 );
    }
        
    CPerfStatLuaTiming::GetSingleton ()->UpdateLuaTiming ( pLuaMain, szFunction, GetTimeUs() - startTime );
    return true;
}
Пример #4
0
bool CRegistry::ExecInternal ( const char* szQuery )
{
    TIMEUS startTime = GetTimeUs();
    char *szErrorMsg = NULL;

    if ( sqlite3_exec ( m_db, szQuery, NULL, NULL, &szErrorMsg ) != SQLITE_OK )
    {
        SetLastErrorMessage ( szErrorMsg, szQuery );
        sqlite3_free ( szErrorMsg );
        return false;
    }

    CPerfStatSqliteTiming::GetSingleton ()->UpdateSqliteTiming ( this, szQuery, GetTimeUs() - startTime );
    return true;
}
Пример #5
0
void CDevice::Process()
{
  if (m_output.empty())
    Log("%s: starting", m_name.c_str());
  else
    Log("%s: starting with output \"%s\"", m_name.c_str(), m_output.c_str());
      
  int64_t setuptime;

  while(!m_stop)
  {
    //keep trying to set up the device every 10 seconds
    while(!m_stop)
    {
      Log("%s: setting up", m_name.c_str());

      setuptime = GetTimeUs();
      if (!SetupDevice())
      {
        CloseDevice();
	LogError("%s: setting up failed, retrying in 10 seconds", m_name.c_str());
        USleep(10000000LL, &m_stop);
      }
      else
      {
	Log("%s: setup succeeded", m_name.c_str());
        break;
      }
    }

    //keep calling writeoutput until we're asked to stop or writeoutput fails
    while(!m_stop)
    {
      if (!WriteOutput())
      {
        //make sure to wait at least one second before trying to set up again
        USleep(Max(1000000LL - (GetTimeUs() - setuptime), 0));
        break;
      }
    }

    CloseDevice();

    Log("%s: closed", m_name.c_str());
  }

  Log("%s: stopped", m_name.c_str());
}
Пример #6
0
    ///////////////////////////////////////////////////////////////
    //
    // CloseOpenEvents
    //
    // If more clocks than unclocks, add missing unclocks, and add clocks for next frame
    // Returns number of missing unclocks inserted
    //
    ///////////////////////////////////////////////////////////////
    int CloseOpenEvents ( std::vector < SFrameEvent >& eventList, const char* szSection, const char* szName )
    {
        int iNumClocks = 0;
        int iNumUnclocks = 0;
        for( uint i = 0 ; i < eventList.size () ; i++ )
        {
            if ( eventList[i].type == STATS_CLOCK )
                iNumClocks++;
            else
            if ( eventList[i].type == STATS_UNCLOCK )
            {
                if ( iNumClocks > 0 )
                    iNumUnclocks++;
            }
        }

        int iExtraClocks = Max ( 0, iNumClocks - iNumUnclocks );

        for( int i = 0 ; i < iExtraClocks ; i++ )
        {
            eventList.push_back ( SFrameEvent ( STATS_UNCLOCK, GetTimeUs () ) );
            g_StatEvents.Add ( szSection, szName, STATS_CLOCK );
        }

        return iExtraClocks;
    }
bool CDeviceSPI::WriteOutput()
{
  //get the channel values from the clientshandler
  int64_t now = GetTimeUs();
  m_clients.FillChannels(m_channels, now, this);
  counter=4;
  
  
  
   for (int i = 0; i < (m_channels.size()-2); i+=3) {
      r=(uint16_t) ((m_channels[i].GetValue(now) * m_max)+0.5);
	  // r=Clamp(r,0,(uint16_t)(m_max));
	  g=(uint16_t) ((m_channels[i+1].GetValue(now) * m_max)+0.5);
	  // g=Clamp(g,0,(uint16_t)(m_max));
	  b=(uint16_t) ((m_channels[i+2].GetValue(now) * m_max)+0.5);
	  // b=Clamp(b,0,(uint16_t)(m_max));
	  d = (r*1024) + (g*32) + b + 32768;
	  m_buff[counter] =d >> 8;
      counter++;
      m_buff[counter] =d & 0x00FF;
      counter++;

  }
  if (!WriteBuffer())
    return false;

  m_timer.Wait();
  
  return true;
}
Пример #8
0
static Group       *
GroupCreate(int gid)
{
   Group              *g;

   g = ECALLOC(Group, 1);
   if (!g)
      return NULL;

   if (!group_list)
      group_list = ecore_list_new();
   ecore_list_append(group_list, g);

   if (gid == -1)
     {
	/* Create new group id */
	/* ... using us time. Should really be checked for uniqueness. */
	g->index = (int)GetTimeUs();
     }
   else
     {
	/* Use given group id */
	g->index = gid;
     }
   g->cfg.iconify = Conf_groups.dflt.iconify;
   g->cfg.kill = Conf_groups.dflt.kill;
   g->cfg.move = Conf_groups.dflt.move;
   g->cfg.raise = Conf_groups.dflt.raise;
   g->cfg.set_border = Conf_groups.dflt.set_border;
   g->cfg.stick = Conf_groups.dflt.stick;
   g->cfg.shade = Conf_groups.dflt.shade;

   Dprintf("grp=%p gid=%d\n", g, g->index);
   return g;
}
Пример #9
0
uint64_t 
Timer::StartTimer()
{
	mStartTime	= GetTimeUs();
	mRunning	= true;
	return mStartTime;
}
Пример #10
0
uint64_t 
Timer::StopTimer()
{
	mStopTime		= GetTimeUs();
	mRunning		= false;
	mElapsedTotal	+= (mStopTime - mStartTime);
	return mStopTime;
}
Пример #11
0
void CStreamingSA::LoadAllRequestedModels(BOOL bOnlyPriorityModels, const char* szTag)
{
    TIMEUS startTime = GetTimeUs();

    DWORD dwFunction = FUNC_LoadAllRequestedModels;
    DWORD dwOnlyPriorityModels = bOnlyPriorityModels;
    _asm
    {
        push    dwOnlyPriorityModels
        call    dwFunction
        add     esp, 4
    }

    if (IS_TIMING_CHECKPOINTS())
    {
        uint deltaTimeMs = (GetTimeUs() - startTime) / 1000;
        if (deltaTimeMs > 2)
            TIMING_DETAIL(SString("LoadAllRequestedModels( %d, %s ) took %d ms", bOnlyPriorityModels, szTag, deltaTimeMs));
    }
}
Пример #12
0
uint64_t 
Timer::GetElapsedTotal()
{
	if (mRunning)
	{
		return (GetTimeUs() - mStartTime) + mElapsedTotal;
	}
	else
	{
		return mElapsedTotal;
	}
}
Пример #13
0
uint64_t 
Timer::GetElapsed()
{
	if (mRunning)
	{
		return GetTimeUs() - mStartTime;
	}
	else
	{
		return mStopTime - mStartTime;
	}
}
Пример #14
0
void Cfft::Allocate(unsigned int size)
{
  if (size != m_bufsize)
  {
    Free();

    m_bufsize = size;
    m_inbuf = new float[m_bufsize];
    m_fftin = (float*)fftw_malloc(m_bufsize * sizeof(float));
    m_outbuf = (fftwf_complex*)fftw_malloc(m_bufsize * sizeof(fftwf_complex));
    m_window = new float[m_bufsize];

    //create a hamming window
    for (unsigned int i = 0; i < m_bufsize; i++)
      m_window[i] = 0.54f - 0.46f * cosf(2.0f * M_PI * i / (m_bufsize - 1.0f));

    Log("Building fft plan");
    int64_t start = GetTimeUs();
    m_plan = fftwf_plan_dft_r2c_1d(m_bufsize, m_fftin, m_outbuf, FFTW_MEASURE);
    Log("Built fft plan in %.0f ms", (double)(GetTimeUs() - start) / 1000.0f);
  }
}
Пример #15
0
//
// Called after a Lua function if post call hook has been installed
//
void CLuaDefs::DidUseFunction ( lua_CFunction f, lua_State* luaVM )
{
    // Quick cull of unknown pointer range - Deals with calls from client dll (when the server has been loaded into the same process)
    if ( CLuaCFunctions::IsNotFunction( f ) )
        return;

    if ( !ms_TimingFunctionStack.empty () )
    {
        // Check if the function used was being timed
        const STimingFunction& info = ms_TimingFunctionStack.back ();
        if ( info.f == f )
        {
            // Finish the timing
            TIMEUS elapsedTime = GetTimeUs() - info.startTime;
            uint uiDeltaBytes = g_uiNetSentByteCounter - info.uiStartByteCount;
            // Record timing over a threshold
            if ( elapsedTime >= CPerfStatFunctionTiming::ms_PeakUsThresh || uiDeltaBytes > 1000 )
            {
                CLuaCFunction* pFunction = CLuaCFunctions::GetFunction ( info.f );
                if ( pFunction )
                {
                    CResource* pResource = g_pGame->GetResourceManager ()->GetResourceFromLuaState ( info.luaVM );
                    SString strResourceName = pResource ? pResource->GetName() : "unknown";
                    CPerfStatFunctionTiming::GetSingleton ()->UpdateTiming ( strResourceName, pFunction->GetName ().c_str (), elapsedTime, uiDeltaBytes );
                }
            }

            ms_TimingFunctionStack.pop_back ();
        }
    }

    // Check if we should remove the hook
    if ( !g_pStats->bFunctionTimingActive && !g_pGame->GetDebugHookManager()->HasPostFunctionHooks() )
    {
        ms_TimingFunctionStack.clear ();
        OutputDebugLine ( "[Lua] Removing PostCallHook" );
        assert ( ms_bRegisterdPostCallHook );
        ms_bRegisterdPostCallHook = false;
        lua_registerPostCallHook ( NULL );
    }

    g_pGame->GetDebugHookManager()->OnPostFunction( f, luaVM );
}
Пример #16
0
bool CMapEventManager::Call ( const char* szName, const CLuaArguments& Arguments, class CClientEntity* pSource, class CClientEntity* pThis )
{
    // Check if no events
    if ( !m_bHasEvents )
        return false;

    // Check if no events with a name match
    EventsIterPair itPair = m_EventsMap.equal_range ( szName );
    if ( itPair.first == itPair.second )
        return false;

    TIMEUS startTimeCall = GetTimeUs ();
    SString strStatus;

    // Check for multi-threading slipups
    assert ( IsMainThread () );

    // Call all the events with matching names
    bool bCalled = false;
    bool bIsAlreadyIterating = m_bIteratingList;
    m_bIteratingList = true;

    // Copy the results into a array in case m_EventsMap is modified during the call
    std::vector< CMapEvent* > matchingEvents;
    for ( EventsIter iter = itPair.first ; iter != itPair.second ; ++iter )
        matchingEvents.push_back(iter->second);

    for ( std::vector< CMapEvent* >::iterator iter = matchingEvents.begin() ; iter != matchingEvents.end() ; ++iter )
    {
        CMapEvent* pMapEvent = *iter;

        // If it's not being destroyed
        if ( !pMapEvent->IsBeingDestroyed () )
        {
            // Compare the names
            dassert ( strcmp ( pMapEvent->GetName (), szName ) == 0 );
            {
                // Call if propagated?
                if ( pSource == pThis || pMapEvent->IsPropagated () )
                {
                    // Grab the current VM
                    lua_State* pState = pMapEvent->GetVM ()->GetVM ();

                    LUA_CHECKSTACK ( pState, 1 );   // Ensure some room

                    #if MTA_DEBUG
                        int luaStackPointer = lua_gettop ( pState );
                    #endif

                    TIMEUS startTime = GetTimeUs();

                    // Aspect ratio adjustment bodges
                    if ( pMapEvent->ShouldAllowAspectRatioAdjustment() )
                    {
                        g_bAllowAspectRatioAdjustment = true;
                        if ( pMapEvent->ShouldForceAspectRatioAdjustment() )
                            g_pCore->GetGraphics()->SetAspectRatioAdjustmentEnabled( true );
                    }

                    // Record event for the crash dump writer
                    static bool bEnabled = ( g_pCore->GetDiagnosticDebug () == EDiagnosticDebug::LUA_TRACE_0000 );
                    if ( bEnabled )
                        g_pCore->LogEvent ( 0, "Lua Event", pMapEvent->GetVM ()->GetScriptName (), szName );

                    // Store the current values of the globals
                    lua_getglobal ( pState, "source" );
                    CLuaArgument OldSource ( pState, -1 );
                    lua_pop( pState, 1 );

                    lua_getglobal ( pState, "this" );
                    CLuaArgument OldThis ( pState, -1 );
                    lua_pop( pState, 1 );

                    lua_getglobal ( pState, "sourceResource" );
                    CLuaArgument OldResource ( pState, -1 );
                    lua_pop( pState, 1 );

                    lua_getglobal ( pState, "sourceResourceRoot" );
                    CLuaArgument OldResourceRoot ( pState, -1 );
                    lua_pop( pState, 1 );

                    lua_getglobal ( pState, "eventName" );
                    CLuaArgument OldEventName ( pState, -1 );
                    lua_pop( pState, 1 );

                    // Set the "source", "this", "sourceResource" and the "sourceResourceRoot" globals on that VM
                    lua_pushelement ( pState, pSource );
                    lua_setglobal ( pState, "source" );

                    lua_pushelement ( pState, pThis );
                    lua_setglobal ( pState, "this" );

                    CLuaMain* pLuaMain = g_pClientGame->GetScriptDebugging()->GetTopLuaMain();
                    CResource* pSourceResource = pLuaMain ? pLuaMain->GetResource() : NULL;
                    if ( pSourceResource )
                    {
                        lua_pushresource ( pState, pSourceResource );
                        lua_setglobal ( pState, "sourceResource" );

                        lua_pushelement ( pState, pSourceResource->GetResourceDynamicEntity() );
                        lua_setglobal ( pState, "sourceResourceRoot" );
                    }
                    else
                    {
                        lua_pushnil ( pState );
                        lua_setglobal ( pState, "sourceResource" );

                        lua_pushnil ( pState );
                        lua_setglobal ( pState, "sourceResourceRoot" );
                    }

                    lua_pushstring ( pState, szName );
                    lua_setglobal ( pState, "eventName" );
                    
                    // Call it
                    pMapEvent->Call ( Arguments );
                    bCalled = true;

                    // Reset the globals on that VM
                    OldSource.Push ( pState );
                    lua_setglobal ( pState, "source" );

                    OldThis.Push ( pState );
                    lua_setglobal ( pState, "this" );                

                    OldResource.Push ( pState );
                    lua_setglobal ( pState, "sourceResource" );

                    OldResourceRoot.Push ( pState );
                    lua_setglobal ( pState, "sourceResourceRoot" );

                    OldEventName.Push ( pState );
                    lua_setglobal ( pState, "eventName" );

                    #if MTA_DEBUG
                        assert ( lua_gettop ( pState ) == luaStackPointer );
                    #endif

                    // Aspect ratio adjustment bodges
                    if ( pMapEvent->ShouldAllowAspectRatioAdjustment() )
                    {
                        g_pCore->GetGraphics()->SetAspectRatioAdjustmentEnabled( false );
                        g_bAllowAspectRatioAdjustment = false;
                    }

                    TIMEUS deltaTimeUs = GetTimeUs() - startTime;

                    if ( deltaTimeUs > 3000 ) 
                        if ( IS_TIMING_CHECKPOINTS() )
                            strStatus += SString ( " (%s %d ms)", pMapEvent->GetVM ()->GetScriptName (), deltaTimeUs / 1000 );

                    CClientPerfStatLuaTiming::GetSingleton ()->UpdateLuaTiming ( pMapEvent->GetVM (), szName, deltaTimeUs );
                }
            }
        }
    }

    // Clean out the trash if we're no longer calling events.
    if ( !bIsAlreadyIterating )
    {
        TakeOutTheTrash ();

        // We're no longer iterating the list
        m_bIteratingList = false;
    }

    if ( IS_TIMING_CHECKPOINTS() )
    {
        TIMEUS deltaTimeUs = GetTimeUs() - startTimeCall;
        if ( deltaTimeUs > 5000 )
            TIMING_DETAIL( SString ( "CMapEventManager::Call ( %s, ... ) took %d ms ( %s )", szName, deltaTimeUs / 1000, *strStatus ) );
    }

    // Return whether we called atleast one func or not
    return bCalled;
}
Пример #17
0
int CLuaDefs::CanUseFunction ( lua_CFunction f, lua_State* luaVM )
{
    // Quick cull of unknown pointer range
    if ( CLuaCFunctions::IsNotFunction( f ) )
        return true;

    // these are for OOP and establish the function to call, at which point the function is called normally so we get this called like so:
    // Call 1: f = CLuaClassDefs::NewIndex
    // Call 2: f = setElementHealth
    // ignore new index as it isn't registered as an LuaCFunction and just throws an assert in debug/causes issues.
    if ( f == (lua_CFunction)&CLuaClassDefs::NewIndex || 
        f == (lua_CFunction)&CLuaClassDefs::StaticNewIndex ||
        f == (lua_CFunction)&CLuaClassDefs::Index ||
        f == (lua_CFunction)&CLuaClassDefs::Call || 
        f == (lua_CFunction)&CLuaClassDefs::ToString || 
        f == (lua_CFunction)&CLuaClassDefs::ReadOnly ||
        f == (lua_CFunction)&CLuaClassDefs::WriteOnly )
    {
        return true;
    }

    // Get associated resource
    CResource* pResource = m_pResourceManager->GetResourceFromLuaState( luaVM );
    if ( !pResource )
        return true;

    // Update execution time check
    pResource->GetVirtualMachine()->CheckExecutionTime();

    // Check function right cache in resource
    bool bAllowed;

    // Check cached ACL rights
    if ( pResource->CheckFunctionRightCache( f, &bAllowed ) )
    {
        // If in cache, and not allowed, do warning here
        if ( !bAllowed )
            m_pScriptDebugging->LogBadAccess ( luaVM );
    }
    // Not cached yet
    else
    {
        // If not in cache, do full check
        bAllowed = true;

        // Grab the function name we're calling. If it's one of our functions, see if we can use it.
        CLuaCFunction* pFunction = CLuaCFunctions::GetFunction ( f );

        // works for anything registered for Lua VM
        // e.g. setElementHealth, setElementFrozen
        if ( pFunction )
        {
            // If it's not one of lua's functions, see if we allow it
            bAllowed = CLuaDefs::CanUseFunction ( pFunction->GetName ().c_str (), luaVM, pFunction->IsRestricted () );
        }
        // works for custom ACL functions e.g.
        // Element.position and other custom oop definitions not registered by string.
        else
        {
            // get the 2nd upvalue (ACL Name)
            const char* szName = lua_tostring ( luaVM, lua_upvalueindex ( 2 ) );

            // if it has no name do nothing
            if ( szName != NULL && strcmp ( szName , "" ) != 0 )
            {
                // get the function by name
                CLuaCFunction* pFunction = CLuaCFunctions::GetFunction ( szName );
                if ( pFunction )
                {
                    // check the resource cache for the Lua name we looked up
                    bAllowed = CLuaDefs::CanUseFunction ( szName, luaVM, pFunction->IsRestricted () );
                }
            }
        }
        // Update cache in resource
        pResource->UpdateFunctionRightCache( f, bAllowed );
    }

    g_pGame->GetDebugHookManager()->OnPreFunction( f, luaVM, bAllowed );

    // If not allowed, do no more
    if ( !bAllowed )
        return false;

    // Check if function timing is active
    if ( g_pStats->bFunctionTimingActive || g_pGame->GetDebugHookManager()->HasPostFunctionHooks() )
    {
        // Check if hook needs applying
        if ( !ms_bRegisterdPostCallHook )
        {
            OutputDebugLine ( "[Lua] Registering PostCallHook" );
            ms_bRegisterdPostCallHook = true;
            lua_registerPostCallHook ( CLuaDefs::DidUseFunction );
        }
        // Start to time the function
        ms_TimingFunctionStack.push_back ( STimingFunction( luaVM, f, GetTimeUs(), g_uiNetSentByteCounter ) );
    }
    return true;
}
Пример #18
0
///////////////////////////////////////////////////////////////
//
// CGraphStats::AddTimingPoint
//
//
//
///////////////////////////////////////////////////////////////
void CGraphStats::AddTimingPoint(const char* szName)
{
    if (!IsEnabled())
        return;

    // Start of next frame?
    if (szName[0] == 0)
    {
        TIMEUS endTime = GetTimeUs();
        TIMEUS frameTime = endTime - m_StartTime;
        m_StartTime = endTime;

        // Duplicate data points to make up for missed time
        int Dups = frameTime / 33000;
        if (Dups > 0)
        {
            Dups = std::min(100, Dups);
            for (std::map<SString, SGraphStatLine>::iterator iter = m_LineList.begin(); iter != m_LineList.end(); ++iter)
            {
                SGraphStatLine* pLine = &iter->second;

                float Data = pLine->dataHistory[pLine->iDataPos];
                for (int i = 0; i < Dups; i++)
                {
                    pLine->iDataPos++;
                    if (pLine->iDataPos > GRAPHSTAT_HISTORY_SIZE - 1)
                        pLine->iDataPos = 0;
                    pLine->dataHistory[pLine->iDataPos] = Data;
                }
            }
        }
        return;
    }

    if (m_StartTime == 0)
        return;

    // Find existing line
    SGraphStatLine* pLine = MapFind(m_LineList, szName);

    if (!pLine)
    {
        // Add new line
        MapSet(m_LineList, szName, SGraphStatLine());
        pLine = MapFind(m_LineList, szName);
        pLine->dataHistory.resize(GRAPHSTAT_HISTORY_SIZE);
        memset(&pLine->dataHistory[0], 0, pLine->dataHistory.size());
        pLine->iDataPos = 0;
        pLine->prevData = 0;
        pLine->strName = szName;

        // Random color based on line name
        MD5 md5;
        CMD5Hasher().Calculate(szName, strlen(szName), md5);
        uchar* p = md5.data;
        while (p[0] + p[1] + p[2] < 128)
        {
            int f = rand() % NUMELMS(md5.data);
            int t = rand() % 3;
            p[t] = std::min(255, p[t] + p[f] + 1);
        }
        pLine->color = SColorRGBA(p[0], p[1], p[2], 255);
    }

    // Calc timing averaged with previous frame
    TIMEUS NewData = GetTimeUs() - m_StartTime;
    TIMEUS AvgData = (NewData + pLine->prevData) / 2;
    pLine->prevData = NewData;

    // Inc position
    pLine->iDataPos++;
    if (pLine->iDataPos > GRAPHSTAT_HISTORY_SIZE - 1)
        pLine->iDataPos = 0;

    // Insert data point
    pLine->dataHistory[pLine->iDataPos] = AvgData;
}
Пример #19
0
bool CLuaArguments::Call ( CLuaMain* pLuaMain, const CLuaFunctionRef& iLuaFunction, CLuaArguments * returnValues ) const
{
    assert ( pLuaMain );
    TIMEUS startTime = GetTimeUs ();

    // Add the function name to the stack and get the event from the table
    lua_State* luaVM = pLuaMain->GetVirtualMachine ();
    assert ( luaVM );
    LUA_CHECKSTACK ( luaVM, 1 );
    int luaStackPointer = lua_gettop ( luaVM );
    lua_getref ( luaVM, iLuaFunction.ToInt () );

    // Push our arguments onto the stack
    PushArguments ( luaVM );

    // Call the function with our arguments
    pLuaMain->ResetInstructionCount ();

    int iret = lua_pcall ( luaVM, m_Arguments.size (), LUA_MULTRET, 0 );
    if ( iret == LUA_ERRRUN || iret == LUA_ERRMEM )
    {
        SString strRes = ConformResourcePath ( lua_tostring( luaVM, -1 ) );
        
        vector <SString> vecSplit;
        strRes.Split ( ":", vecSplit );
        
        if ( vecSplit.size ( ) >= 3 )
        {
            SString strFile = vecSplit[0];
            int     iLine   = atoi ( vecSplit[1].c_str ( ) );
            SString strMsg  = vecSplit[2].substr ( 1 );
            
            g_pGame->GetScriptDebugging()->LogError ( strFile, iLine, strMsg );
        }
        else
            g_pGame->GetScriptDebugging()->LogError ( luaVM, "%s", strRes.c_str () );

        // cleanup the stack
        while ( lua_gettop ( luaVM ) - luaStackPointer > 0 )
            lua_pop ( luaVM, 1 );

       return false; // the function call failed
    }
    else
    {
        int iReturns = lua_gettop ( luaVM ) - luaStackPointer;

        if ( returnValues != NULL )
        {
            for ( int i = - iReturns; i <= -1; i++ )
            {
                returnValues->ReadArgument ( luaVM, i );
            }
        }

        // cleanup the stack
        while ( lua_gettop ( luaVM ) - luaStackPointer > 0 )
            lua_pop ( luaVM, 1 );
    }

    CPerfStatLuaTiming::GetSingleton ()->UpdateLuaTiming ( pLuaMain, pLuaMain->GetFunctionTag ( iLuaFunction.m_iFunction ), GetTimeUs() - startTime );
    return true;
}
Пример #20
0
uint64_t GetTimeMs()
{
	uint64_t t = GetTimeUs( );
	t /= 1000;
	return t;
}
Пример #21
0
bool CRegistry::QueryInternal ( const char* szQuery, CRegistryResult* ppResult )
{
    TIMEUS startTime = GetTimeUs();

    // Prepare the query
    sqlite3_stmt* pStmt;
    if ( sqlite3_prepare ( m_db, szQuery, strlen ( szQuery ) + 1, &pStmt, NULL ) != SQLITE_OK )
    {
        SetLastErrorMessage ( sqlite3_errmsg ( m_db ), szQuery );
        return false;
    }

    CRegistryResult& pResult = *ppResult;
    // Get column names
    pResult->nColumns = sqlite3_column_count ( pStmt );
    pResult->ColNames.clear ();
    for ( int i = 0; i < pResult->nColumns; i++ )
    {
        pResult->ColNames.push_back ( sqlite3_column_name ( pStmt, i ) );
    }

    // Fetch the rows
    pResult->nRows = 0;
    pResult->Data.clear ();
    int status;
    while ( (status = sqlite3_step(pStmt)) == SQLITE_ROW )
    {
        pResult->Data.push_back ( vector < CRegistryResultCell > ( pResult->nColumns ) );
        vector < CRegistryResultCell > & row = pResult->Data.back();
        for ( int i = 0; i < pResult->nColumns; i++ )
        {
            CRegistryResultCell& cell = row[i];
            cell.nType = sqlite3_column_type ( pStmt, i );
            switch ( cell.nType )
            {
                case SQLITE_NULL:
                    break;
                case SQLITE_INTEGER:
                    cell.nVal = sqlite3_column_int ( pStmt, i );
                    break;
                case SQLITE_FLOAT:
                    cell.fVal = (float)sqlite3_column_double ( pStmt, i );
                    break;
                case SQLITE_BLOB:
                    cell.nLength = sqlite3_column_bytes ( pStmt, i );
                    if ( cell.nLength == 0 )
                    {
                        cell.pVal = NULL;
                    }
                    else
                    {
                        cell.pVal = new unsigned char [ cell.nLength ];
                        memcpy ( cell.pVal, sqlite3_column_blob ( pStmt, i ), cell.nLength );
                    }
                    break;
                default:
                    cell.nLength = sqlite3_column_bytes ( pStmt, i ) + 1;
                    cell.pVal = new unsigned char [ cell.nLength ];
                    memcpy ( cell.pVal, sqlite3_column_text ( pStmt, i ), cell.nLength );
                    break;
            }
        }
        pResult->nRows++;
    }

    // Did we leave the fetching loop because of an error?
    if ( status != SQLITE_DONE )
    {
        SetLastErrorMessage ( sqlite3_errmsg ( m_db ), szQuery );
        sqlite3_finalize ( pStmt );
        return false;
    }

    // All done
    sqlite3_finalize ( pStmt );

    CPerfStatSqliteTiming::GetSingleton ()->UpdateSqliteTiming ( this, szQuery, GetTimeUs() - startTime );
    return true;
}
Пример #22
0
int CLuaDefs::CanUseFunction ( lua_CFunction f, lua_State* luaVM )
{
    // Quick cull of unknown pointer range
    if ( CLuaCFunctions::IsNotFunction( f ) )
        return true;

    // Get associated resource
    CResource* pResource = m_pResourceManager->GetResourceFromLuaState( luaVM );
    if ( !pResource )
        return true;

    // Update execution time check
    pResource->GetVirtualMachine()->CheckExecutionTime();

    // Check function right cache in resource
    bool bAllowed;
    if ( pResource->CheckFunctionRightCache( f, &bAllowed ) )
    {
        // If in cache, and not allowed, do warning here
        if ( !bAllowed )
            m_pScriptDebugging->LogBadAccess ( luaVM );
    }
    else
    {
        // If not in cache, do full check
        bAllowed = true;

        // Grab the function name we're calling. If it's one of our functions, see if we can use it.
        CLuaCFunction* pFunction = CLuaCFunctions::GetFunction ( f );
        dassert( pFunction );
        if ( pFunction )
        {
            // If it's not one of lua's functions, see if we allow it
            bAllowed = CLuaDefs::CanUseFunction ( pFunction->GetName ().c_str (), luaVM/*, pResource*/, pFunction->IsRestricted () );
        }

        // Update cache in resource
        pResource->UpdateFunctionRightCache( f, bAllowed );
    }

    g_pGame->GetDebugHookManager()->OnPreFunction( f, luaVM, bAllowed );

    // If not allowed, do no more
    if ( !bAllowed )
        return false;

    // Check if function timing is active
    if ( g_pStats->bFunctionTimingActive || g_pGame->GetDebugHookManager()->HasPostFunctionHooks() )
    {
        // Check if hook needs applying
        if ( !ms_bRegisterdPostCallHook )
        {
            OutputDebugLine ( "[Lua] Registering PostCallHook" );
            ms_bRegisterdPostCallHook = true;
            lua_registerPostCallHook ( CLuaDefs::DidUseFunction );
        }
        // Start to time the function
        ms_TimingFunctionStack.push_back ( STimingFunction( luaVM, f, GetTimeUs(), g_uiNetSentByteCounter ) );
    }
    return true;
}