Example #1
0
void ModeChoice::Read_Constants (void)
{
    int i, mode, segment, tab, mode_field, segment_field, const_field;
    String text;
    double constant;
    bool table_flag;
    Str_ID_Itr id_itr;

    Show_Message (String ("Reading %s -- Record") % constant_file.File_Type ());
    Set_Progress ();

    //---- identify the data fields ----

    mode_field = constant_file.Optional_Field ("MODE", "M", "MOD", "MODES");
    segment_field = constant_file.Optional_Field ("SEGMENT", "SEG", "MARKET", "S");
    const_field = constant_file.Optional_Field ("CONSTANT", "CONST");

    if (mode_field < 0 || const_field < 0) {
        Error ("Mode Constannt Field Names are Not Defined");
    }
    text = trip_file->Field (table_map [0])->Name ();

    table_flag = (constant_file.Optional_Field (text.c_str ()) >= 0);

    //---- initialize the model constants ----

    while (constant_file.Read ()) {
        Show_Progress ();

        text = constant_file.Get_String (mode_field);
        if (text.empty ()) continue;

        id_itr = mode_id.find (text);
        if (id_itr == mode_id.end ()) {
            Warning ("Constant Mode ") << text << " was Not Defined";
        }
        mode = id_itr->second;

        segment = constant_file.Get_Integer (segment_field);

        if (!segment_flag && segment != 0) {
            Error ("A Segment Map File is needed for Segment Constants");
        } else if (segment < 0 || segment > num_market) {
            Error (String ("Segment %d is Out of Range (1..%d)") % segment % num_market);
        }
        constant = constant_file.Get_Double (const_field);

        if (segment_flag && segment == 0) {
            for (i=0; i <= num_market; i++) {
                seg_constant [i] [mode] [num_tables] = constant;
            }
        } else {
            seg_constant [segment] [mode] [num_tables] = constant;
        }

        if (table_flag) {
            for (tab=0; tab < num_tables; tab++) {
                text = trip_file->Field (table_map [tab])->Name ();

                constant = constant_file.Get_Double (text.c_str ());

                if (segment_flag && segment == 0) {
                    for (i=0; i <= num_market; i++) {
                        seg_constant [i] [mode] [tab] = constant;
                    }
                } else {
                    seg_constant [segment] [mode] [tab] = constant;
                }
            }
        }
    }
    End_Progress ();
    constant_file.Close ();
}
Example #2
0
//-----------------------------------------------------------------------------
bool FileStream::open(const String &inFileName, Torque::FS::File::AccessMode inMode)
{
   AssertWarn(0 == mStreamCaps, "FileStream::setPosition: the stream is already open");
   AssertFatal(inFileName.isNotEmpty(), "FileStream::open: empty filename");

   // make sure the file stream's state is clean
   clearBuffer();

   Torque::Path   filePath(inFileName);

   // IF we are writing, make sure the path exists
   if( inMode == Torque::FS::File::Write || inMode == Torque::FS::File::WriteAppend || inMode == Torque::FS::File::ReadWrite )
      Torque::FS::CreatePath(filePath);

   mFile = Torque::FS::OpenFile(filePath, inMode);

   if (mFile != NULL)
   {
      setStatus();
      switch (inMode)
      {
         case Torque::FS::File::Read:
            mStreamCaps = U32(StreamRead) |
                          U32(StreamPosition);
            break;
         case Torque::FS::File::Write:
         case Torque::FS::File::WriteAppend:
            mStreamCaps = U32(StreamWrite) |
                          U32(StreamPosition);
            break;
         case Torque::FS::File::ReadWrite:
            mStreamCaps = U32(StreamRead)  |
                          U32(StreamWrite) |
                          U32(StreamPosition);
            break;
         default:
            AssertFatal(false, String::ToString( "FileStream::open: bad access mode on %s", inFileName.c_str() ));
      }
   }
   else
   {
      Stream::setStatus(IOError);
      return(false);
   }

   return getStatus() == Ok;
}
Example #3
0
bool UrlFile::open(const String& input_url, const String& mode) {
  String url = input_url;
  const char* modestr = mode.c_str();
  if (strchr(modestr, '+') || strchr(modestr, 'a') || strchr(modestr, 'w')) {
    std::string msg = "cannot open a url stream for write/append operation: ";
    msg += url.c_str();
    m_error = msg;
    return false;
  }
  HttpClient http(m_timeout, m_maxRedirect);
  m_response.clear();

  HeaderMap *pHeaders = nullptr;
  HeaderMap requestHeaders;
  if (!m_headers.empty()) {
    pHeaders = &requestHeaders;
    for (ArrayIter iter(m_headers); iter; ++iter) {
      requestHeaders[std::string(iter.first().toString().data())].
        push_back(iter.second().toString().data());
    }
  }

  Variant user = f_parse_url(url, k_PHP_URL_USER);
  if (user.isString()) {
    Variant pass = f_parse_url(url, k_PHP_URL_PASS);
    http.auth(user.toString().c_str(), pass.toString().c_str());
    url = f_preg_replace(
      s_remove_user_pass_pattern,
      s_remove_user_pass_replace,
      url,
      1
    );
  }

  int code;
  std::vector<String> responseHeaders;
  if (m_get) {
    code = http.get(url.c_str(), m_response, pHeaders, &responseHeaders);
  } else {
    code = http.post(url.c_str(), m_postData.data(), m_postData.size(),
                     m_response, pHeaders, &responseHeaders);
  }

  GlobalVariables *g = get_global_variables();
  Variant &r = g->getRef(s_http_response_header);
  r = Array::Create();
  for (unsigned int i = 0; i < responseHeaders.size(); i++) {
    r.append(responseHeaders[i]);
  }
  m_responseHeaders = r;

  if (code == 200) {
    m_name = (std::string) url;
    m_data = const_cast<char*>(m_response.data());
    m_len = m_response.size();
    return true;
  } else {
    m_error = http.getLastError().c_str();
    return false;
  }
}
Example #4
0
// This method is called immediately before entering the message loop.
// It contains initialization code for the application.
// Returns:
// S_OK => Success. Continue with RunMessageLoop() and PostMessageLoop().
// S_FALSE => Skip RunMessageLoop(), call PostMessageLoop().
// error code => Failure. Skip both RunMessageLoop() and PostMessageLoop().
HRESULT CRhodesModule::PreMessageLoop(int nShowCmd) throw()
{
    HRESULT hr = __super::PreMessageLoop(nShowCmd);
    if (FAILED(hr))
    {
        return hr;
    }
    // Note: In this sample, we don't respond differently to different hr success codes.

#if !defined(OS_WINDOWS_DESKTOP)
    SetLastError(0);
    HANDLE hEvent = CreateEvent( NULL, false, false, CMainWindow::GetWndClassInfo().m_wc.lpszClassName );

    if ( hEvent != NULL && GetLastError() == ERROR_ALREADY_EXISTS)
    {
        // Rho Running so could bring to foreground
        HWND hWnd = FindWindow(CMainWindow::GetWndClassInfo().m_wc.lpszClassName, NULL);

        if (hWnd)
        {
            ShowWindow(hWnd, SW_SHOW);
            SendMessage( hWnd, PB_WINDOW_RESTORE, NULL, TRUE);
            SetForegroundWindow( hWnd );
        }

        return S_FALSE;
    }
#endif

    if ( !rho_sys_check_rollback_bundle(rho_native_rhopath()) )
    {
        rho_sys_impl_exit_with_errormessage( "Bundle update", "Application is corrupted. Reinstall it, please.");
        return S_FALSE;
    }

#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
    rho_logconf_Init((rho_wmimpl_get_logpath()[0]==0 ? m_strRootPath.c_str() : rho_wmimpl_get_logpath()), m_strRootPath.c_str(), m_logPort.c_str());
    if (rho_wmimpl_get_logurl()[0]!=0)
        LOGCONF().setLogURL(rho_wmimpl_get_logurl());
    if (rho_wmimpl_get_logmaxsize())
        LOGCONF().setMaxLogFileSize(*rho_wmimpl_get_logmaxsize());
    if (rho_wmimpl_get_loglevel())
        LOGCONF().setMinSeverity(*rho_wmimpl_get_loglevel());
    if (rho_wmimpl_get_fullscreen())
        RHOCONF().setBool("full_screen", true, false);
    if (rho_wmimpl_get_logmemperiod())
        LOGCONF().setCollectMemoryInfoInterval(*rho_wmimpl_get_logmemperiod());
#else
    rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
#endif // APP_BUILD_CAPABILITY_SHARED_RUNTIME

    LOGCONF().setMemoryInfoCollector(CLogMemory::getInstance());

#ifdef RHODES_EMULATOR
    RHOSIMCONF().setAppConfFilePath(CFilePath::join( m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str());
    RHOSIMCONF().loadFromFile();
    if ( m_strRhodesPath.length() > 0 )
        RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false );
    RHOCONF().setString("rhosim_platform", RHOSIMCONF().getString("platform"), false);
    RHOCONF().setString("app_version", RHOSIMCONF().getString("app_version"), false);
	String start_path = RHOSIMCONF().getString("start_path");
    if ( start_path.length() > 0 )
	    RHOCONF().setString("start_path", start_path, false);
    RHOSIMCONF().setString("ext_path", RHOSIMCONF().getString("ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false);
    RHOSIMCONF().setString("ext_path", RHOSIMCONF().getString("ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false);
    RHOSIMCONF().setString("ext_path", RHOSIMCONF().getString("ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false);
    RHOSIMCONF().setString("ext_path", RHOSIMCONF().getString("ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false);
    RHOSIMCONF().setString("ext_path", RHOSIMCONF().getString("ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false);
#endif

    if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") )
    {
#ifdef OS_WINDOWS_DESKTOP
	    ::MessageBoxW(0, L"This is hidden app and can be started only with security key.", L"Security Token Verification Failed", MB_ICONERROR | MB_OK);
#endif
		LOG(INFO) + "This is hidden app and can be started only with security key.";
		if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0)
			return S_FALSE;
    }

	LOG(INFO) + "Rhodes started";
#ifdef OS_WINDOWS_DESKTOP
	if (m_strHttpProxy.length() > 0) {
		parseHttpProxyURI(m_strHttpProxy);
	} else
#endif
	{
		if (RHOCONF().isExist("http_proxy_url")) {
			parseHttpProxyURI(RHOCONF().getString("http_proxy_url"));
#if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR)
		} else {
			// it's important to call this method from here to perform
			// a proper initialization of proxy implementation for Win32
			GetAppWindow().setProxy();
#endif
		}
	}

#ifdef RHODES_EMULATOR
    if (RHOSIMCONF().getString("debug_host").length() > 0)
        SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() );
    if (RHOSIMCONF().getString("debug_port").length() > 0)
        SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() );
#endif

	//Check for bundle directory is exists.
	HANDLE hFind;
	WIN32_FIND_DATA wfd;
	
	// rootpath + "rho/"
	if (m_strRootPath.at(m_strRootPath.length()-1) == '/') 
    {
		hFind = FindFirstFile(convertToStringW(m_strRootPath.substr(0, m_strRootPath.find_last_of('/'))).c_str(), &wfd);
	} 
    else if (m_strRootPath.at(m_strRootPath.length()-1) == '\\') 
    {
		//delete all '\' from the end of the pathname
		int i = m_strRootPath.length();
		for ( ; i != 1; i--) {
			if (m_strRootPath.at(i-1) != '\\')
				break;
		}

		hFind = FindFirstFile(convertToStringW(m_strRootPath.substr(0, i)).c_str(), &wfd);
	}

	if (INVALID_HANDLE_VALUE == hFind || !(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
    {
		int last = 0, pre_last = 0;
		last = getRhoRootPath().find_last_of('\\');
		pre_last = getRhoRootPath().substr(0, last).find_last_of('\\');
		String appName = getRhoRootPath().substr(pre_last + 1, last - pre_last - 1);

		String messageText = "Bundle directory \"" + 
								m_strRootPath.substr(0, m_strRootPath.find_last_of('/')) + 
								"\" is  missing\n";

		LOG(INFO) + messageText;
		int msgboxID = MessageBox(NULL,
									convertToStringW(messageText).c_str(),
									convertToStringW(appName).c_str(),
									MB_ICONERROR | MB_OK);


		return S_FALSE;
    }

    if (RHOCONF().getBool("Application.autoStart"))
        createAutoStartShortcut();

    rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRuntimePath);

#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
    if ((!rho_wmimpl_get_is_version2()) && (rho_wmimpl_get_startpage()[0] != 0)) {
        String spath = convertToStringA(rho_wmimpl_get_startpage());
        RHOCONF().setString("start_path", spath, false);
    }
#endif // APP_BUILD_CAPABILITY_SHARED_RUNTIME

    DWORD dwStyle = m_bMinimized ? 0 : WS_VISIBLE;

#if !defined(_WIN32_WCE)
    dwStyle |= WS_OVERLAPPEDWINDOW;
#endif
    // Create the main application window
#if defined(OS_WINDOWS_DESKTOP)
#ifdef RHODES_EMULATOR
    StringW windowTitle = convertToStringW(RHOSIMCONF().getString("app_name"));
#else
    StringW windowTitle = convertToStringW(RHODESAPP().getAppTitle());
#endif
    m_appWindow.Initialize(windowTitle.c_str());
    if (NULL == m_appWindow.m_hWnd)
    {
        return S_FALSE;
    }
    if (m_bMinimized)
        nShowCmd = SW_MINIMIZE;

    m_appWindow.ShowWindow(nShowCmd);

#ifndef RHODES_EMULATOR
    rho_wm_impl_CheckLicense();
#endif

#else
    String strTitle = RHODESAPP().getAppTitle();
    m_appWindow.Create(NULL, CWindow::rcDefault, convertToStringW(strTitle).c_str(), dwStyle);

    if (NULL == m_appWindow.m_hWnd)
    {
        return S_FALSE;
    }

    m_appWindow.InvalidateRect(NULL, TRUE);
    m_appWindow.UpdateWindow();

    m_appWindow.initBrowserWindow();

    if (m_bMinimized)
        m_appWindow.ShowWindow(SW_MINIMIZE);
#endif

    bool bRE1App = false;

#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
    if (!rho_wmimpl_get_is_version2())
        bRE1App = true;
#endif

    if (bRE1App)
    {
#if defined(APP_BUILD_CAPABILITY_MOTOROLA)
        registerRhoExtension();
#endif

#if !defined( APP_BUILD_CAPABILITY_WEBKIT_BROWSER ) && defined(OS_WINCE)
	    m_appWindow.Navigate2(_T("about:blank")
#if defined(OS_WINDOWS_DESKTOP)
            , -1
#endif
        );
#endif //!APP_BUILD_CAPABILITY_WEBKIT_BROWSER

        rho_webview_navigate(RHOCONF().getString("start_path").c_str(), 0 );
    }
    else
    {
        const char* a = RHOCONF().getString("start_path").c_str();

        RHODESAPP().startApp();
        
       // rho_webview_navigate(RHOCONF().getString("start_path").c_str(), 0 );

#if !defined( APP_BUILD_CAPABILITY_WEBKIT_BROWSER ) && defined(OS_WINCE)
        // Navigate to the "loading..." page
	    m_appWindow.Navigate2(_T("about:blank")
#if defined(OS_WINDOWS_DESKTOP)
            , -1
#endif
        );
#endif //APP_BUILD_CAPABILITY_WEBKIT_BROWSER
    }

#if defined(_WIN32_WCE)&& !defined( OS_PLATFORM_MOTCE )

    DWORD dwConnCount = 0;
    hr = RegistryGetDWORD( SN_CONNECTIONSNETWORKCOUNT_ROOT,
		SN_CONNECTIONSNETWORKCOUNT_PATH, 
		SN_CONNECTIONSNETWORKCOUNT_VALUE, 
        &dwConnCount
    );
    rho_sysimpl_sethas_network(dwConnCount);

    DWORD dwCellConnected = 0;
    hr = RegistryGetDWORD( SN_CONNECTIONSNETWORKCOUNT_ROOT,
		SN_CELLSYSTEMCONNECTED_PATH, 
		SN_CELLSYSTEMCONNECTED_VALUE, 
        &dwCellConnected
    );
    rho_sysimpl_sethas_cellnetwork(dwCellConnected);

	// Register for changes in the number of network connections
	hr = RegistryNotifyWindow(SN_CONNECTIONSNETWORKCOUNT_ROOT,
		SN_CONNECTIONSNETWORKCOUNT_PATH, 
		SN_CONNECTIONSNETWORKCOUNT_VALUE, 
		m_appWindow.m_hWnd, 
		WM_CONNECTIONSNETWORKCOUNT, 
		0, 
		NULL, 
		&g_hNotify);

	hr = RegistryNotifyWindow(SN_CONNECTIONSNETWORKCOUNT_ROOT,
		SN_CELLSYSTEMCONNECTED_PATH, 
		SN_CELLSYSTEMCONNECTED_VALUE, 
		m_appWindow.m_hWnd, 
		WM_CONNECTIONSNETWORKCELL, 
		0, 
		NULL, 
		&g_hNotifyCell);

#endif

    return S_OK;
}
Example #5
0
extern "C" DLL_EXPORT const char* _dbg_dbginit()
{
    if(!EngineCheckStructAlignment(UE_STRUCT_TITAN_ENGINE_CONTEXT, sizeof(TITAN_ENGINE_CONTEXT_t)))
        return "Invalid TITAN_ENGINE_CONTEXT_t alignment!";
    if(sizeof(TITAN_ENGINE_CONTEXT_t) != sizeof(REGISTERCONTEXT))
        return "Invalid REGISTERCONTEXT alignment!";
    dputs("Initializing locks...");
    SectionLockerGlobal::Initialize();
    dputs("Initializing wait objects...");
    waitinitialize();
    dputs("Initializing debugger...");
    dbginit();
    dputs("Initializing debugger functions...");
    dbgfunctionsinit();
    dputs("Setting JSON memory management functions...");
    json_set_alloc_funcs(json_malloc, json_free);
    dputs("Initializing capstone...");
    Capstone::GlobalInitialize();
    dputs("Initializing Yara...");
    if(yr_initialize() != ERROR_SUCCESS)
        return "Failed to initialize Yara!";
    dputs("Getting directory information...");
    wchar_t wszDir[deflen] = L"";
    if(!GetModuleFileNameW(hInst, wszDir, deflen))
        return "GetModuleFileNameW failed!";
    char dir[deflen] = "";
    strcpy_s(dir, StringUtils::Utf16ToUtf8(wszDir).c_str());
    int len = (int)strlen(dir);
    while(dir[len] != '\\')
        len--;
    dir[len] = 0;
    strcpy_s(alloctrace, dir);
    strcat_s(alloctrace, "\\alloctrace.txt");
    DeleteFileW(StringUtils::Utf8ToUtf16(alloctrace).c_str());
    setalloctrace(alloctrace);
    strcpy_s(dbbasepath, dir); //debug directory
    strcat_s(dbbasepath, "\\db");
    CreateDirectoryW(StringUtils::Utf8ToUtf16(dbbasepath).c_str(), 0); //create database directory
    strcpy_s(szSymbolCachePath, dir);
    strcat_s(szSymbolCachePath, "\\symbols");
    SetCurrentDirectoryW(StringUtils::Utf8ToUtf16(dir).c_str());
    dputs("Allocating message stack...");
    gMsgStack = MsgAllocStack();
    if(!gMsgStack)
        return "Could not allocate message stack!";
    dputs("Initializing global script variables...");
    varinit();
    dputs("Registering debugger commands...");
    registercommands();
    dputs("Starting command loop...");
    hCommandLoopThread = CreateThread(0, 0, DbgCommandLoopThread, 0, 0, 0);
    char plugindir[deflen] = "";
    strcpy_s(plugindir, dir);
    strcat_s(plugindir, "\\plugins");
    CreateDirectoryW(StringUtils::Utf8ToUtf16(plugindir).c_str(), 0);
    dputs("Loading plugins...");
    pluginload(plugindir);
    dputs("Handling command line...");
    //handle command line
    int argc = 0;
    wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if(argc == 2) //we have an argument
    {
        String str = "init \"";
        str += StringUtils::Utf16ToUtf8(argv[1]);
        str += "\"";
        DbgCmdExec(str.c_str());
    }
    else if(argc == 5) //4 arguments (JIT)
    {
        if(_wcsicmp(argv[1], L"-a") == 0 && !_wcsicmp(argv[3], L"-e"))
        {
            String str = "attach .";
            str += StringUtils::Utf16ToUtf8(argv[2]);
            str += ", .";
            str += StringUtils::Utf16ToUtf8(argv[4]);
            DbgCmdExec(str.c_str());
        }
    }
    LocalFree(argv);
    dputs("Initialization successful!");
    return 0;
}
Example #6
0
void WebSocket::sendString(const String& message)
{
    send(message.c_str(), message.length());
}
Example #7
0
extern "C" const char* rho_sys_get_http_proxy_url()
{
    return g_strHttpProxy.c_str();
}
void LightFlareData::prepRender( SceneState *state, LightFlareState *flareState )
{    
   PROFILE_SCOPE( LightFlareData_prepRender );

   // No elements then nothing to render.
   if ( mElementCount == 0 )
      return;

   // We need these all over the place later.
   const Point3F &camPos = state->getCameraPosition();
   const RectI &viewport = GFX->getViewport();
   const Point3F &lightPos = flareState->lightMat.getPosition();
   LightInfo *lightInfo = flareState->lightInfo;

   bool isVectorLight = lightInfo->getType() == LightInfo::Vector;

   // Perform visibility testing on the light...
   // Project the light position from world to screen space, we need this
   // position later, and it tells us if it is actually onscreen.   
   
   Point3F lightPosSS;
   bool onscreen = MathUtils::mProjectWorldToScreen( lightPos, &lightPosSS, viewport, GFX->getWorldMatrix(), gClientSceneGraph->getNonClipProjection() );  

   U32 visDelta = U32_MAX;
   U32 fadeOutTime = 20;
   U32 fadeInTime = 125;    

   // Fade factor based on amount of occlusion.
   F32 occlusionFade = 1.0f;

   bool lightVisible = true;
   
   if ( !state->isReflectPass() )
   {
      // It is onscreen, so raycast as a simple occlusion test.

      U32 losMask =	STATIC_COLLISION_MASK |
                     ShapeBaseObjectType |
                     StaticTSObjectType |
                     ItemObjectType |
                     PlayerObjectType;

      GameConnection *conn = GameConnection::getConnectionToServer();
      if ( !conn )
         return;

      bool needsRaycast = true;

      // NOTE: if hardware does not support HOQ it will return NULL
      // and we will retry every time but there is not currently a good place
      // for one-shot initialization of LightFlareState
      if ( flareState->occlusionQuery == NULL )
         flareState->occlusionQuery = GFX->createOcclusionQuery();
      if ( flareState->fullPixelQuery == NULL )
         flareState->fullPixelQuery = GFX->createOcclusionQuery();

      if ( flareState->occlusionQuery && 
           ( ( isVectorLight && flareState->worldRadius > 0.0f ) || 
             ( !isVectorLight && mOcclusionRadius > 0.0f ) ) )
      {
         // Always treat light as onscreen if using HOQ
         // it will be faded out if offscreen anyway.
         onscreen = true;

         U32 pixels = -1;
         GFXOcclusionQuery::OcclusionQueryStatus status = flareState->occlusionQuery->getStatus( true, &pixels );

         String str = flareState->occlusionQuery->statusToString( status );
         Con::setVariable( "$Flare::OcclusionStatus", str.c_str() );
         Con::setIntVariable( "$Flare::OcclusionVal", pixels );
         
         if ( status == GFXOcclusionQuery::Occluded )
            occlusionFade = 0.0f;

         if ( status != GFXOcclusionQuery::Unset )         
            needsRaycast = false;

         RenderPassManager *pass = state->getRenderPass();

         OccluderRenderInst *ri = pass->allocInst<OccluderRenderInst>();   

         Point3F scale( Point3F::One );

         if ( isVectorLight && flareState->worldRadius > 0.0f )         
            scale *= flareState->worldRadius;
         else
            scale *= mOcclusionRadius;
         
         ri->type = RenderPassManager::RIT_Occluder;
         ri->query = flareState->occlusionQuery;   
         ri->query2 = flareState->fullPixelQuery;
         ri->position = lightPos;
         ri->scale = scale;
         ri->orientation = pass->allocUniqueXform( lightInfo->getTransform() );         
         ri->isSphere = true;
         state->getRenderPass()->addInst( ri );

         if ( status == GFXOcclusionQuery::NotOccluded )
         {
            U32 fullPixels;
            flareState->fullPixelQuery->getStatus( true, &fullPixels );

            occlusionFade = (F32)pixels / (F32)fullPixels;

            // Approximation of the full pixel count rather than doing
            // two queries, but it is not very accurate.
            /*
            F32 dist = ( camPos - lightPos ).len();
            F32 radius = scale.x;
            radius = ( radius / dist ) * state->getWorldToScreenScale().y;

            occlusionFade = (F32)pixels / (4.0f * radius * radius);
            occlusionFade = mClampF( occlusionFade, 0.0f, 1.0f );            
            */
         }
      }

      Con::setFloatVariable( "$Flare::OcclusionFade", occlusionFade );

      if ( needsRaycast )
      {
         // Use a raycast to determine occlusion.

         bool fps = conn->isFirstPerson();

         GameBase *control = conn->getControlObject();
         if ( control && fps )
            control->disableCollision();

         RayInfo rayInfo;

         if ( gClientContainer.castRayRendered( camPos, lightPos, losMask, &rayInfo ) )
            occlusionFade = 0.0f;

         if ( control && fps )
            control->enableCollision();
      }

      lightVisible = onscreen && occlusionFade > 0.0f;

      // To perform a fade in/out when we gain or lose visibility
      // we must update/store the visibility state and time.

      U32 currentTime = Sim::getCurrentTime();

      if ( lightVisible != flareState->visible )
      {
         flareState->visible = lightVisible;
         flareState->visChangedTime = currentTime;
      }      

      // Save this in the state so that we have it during the reflect pass.
      flareState->occlusion = occlusionFade;

      visDelta = currentTime - flareState->visChangedTime;      
   }
   else // state->isReflectPass()
   {
      occlusionFade = flareState->occlusion;
      lightVisible = flareState->visible;
      visDelta = Sim::getCurrentTime() - flareState->visChangedTime;
   }

   // We can only skip rendering if the light is not visible, and it
   // has elapsed the fadeOutTime.
   if ( !lightVisible && visDelta > fadeOutTime )
      return;

   // In a reflection we only render the elements with zero distance.   
   U32 elementCount = mElementCount;
   if ( state->isReflectPass()  )
   {
      elementCount = 0;
      for ( ; elementCount < mElementCount; elementCount++ )
      {
         if ( mElementDist[elementCount] > 0.0f )
            break;
      }
   }

   if ( elementCount == 0 )
      return;

   // A bunch of preparatory math before generating verts...

   const Point2I &vpExtent = viewport.extent;
   Point3F viewportExtent( vpExtent.x, vpExtent.y, 1.0f );
   Point2I halfViewportExtentI( viewport.extent / 2 );
   Point3F halfViewportExtentF( (F32)halfViewportExtentI.x * 0.5f, (F32)halfViewportExtentI.y, 0.0f );
   Point3F screenCenter( 0,0,0 );
   Point3F oneOverViewportExtent( 1.0f / viewportExtent.x, 1.0f / viewportExtent.y, 1.0f );

   lightPosSS.y -= viewport.point.y;
   lightPosSS *= oneOverViewportExtent;
   lightPosSS = ( lightPosSS * 2.0f ) - Point3F::One;
   lightPosSS.y = -lightPosSS.y;
   lightPosSS.z = 0.0f;

   Point3F flareVec( screenCenter - lightPosSS );
   F32 flareLength = flareVec.len();   
   flareVec.normalizeSafe();

   Point3F basePoints[4];
   basePoints[0] = Point3F( -0.5, 0.5, 0.0 );  
   basePoints[1] = Point3F( -0.5, -0.5, 0.0 );   
   basePoints[2] = Point3F( 0.5, -0.5, 0.0 );   
   basePoints[3] = Point3F( 0.5, 0.5, 0.0 );

   Point3F rotatedBasePoints[4];
   rotatedBasePoints[0] = basePoints[0];
   rotatedBasePoints[1] = basePoints[1];
   rotatedBasePoints[2] = basePoints[2];
   rotatedBasePoints[3] = basePoints[3];

   Point3F fvec( -1, 0, 0 );   
   F32 rot = mAcos( mDot( fvec, flareVec ) );
   Point3F rvec( 0, -1, 0 );
   rot *= mDot( rvec, flareVec ) > 0.0f ? 1.0f : -1.0f;

   vectorRotateZAxis( rotatedBasePoints[0], rot );
   vectorRotateZAxis( rotatedBasePoints[1], rot );
   vectorRotateZAxis( rotatedBasePoints[2], rot );
   vectorRotateZAxis( rotatedBasePoints[3], rot );

   // Here we calculate a the light source's influence on the effect's size
   // and brightness...

   // Scale based on the current light brightness compared to its normal output.
   F32 lightSourceBrightnessScale = lightInfo->getBrightness() / flareState->fullBrightness;
   // Scale based on world space distance from camera to light source.
   F32 lightSourceWSDistanceScale = ( isVectorLight ) ? 1.0f : getMin( 10.0f / ( lightPos - camPos ).len(), 1.5f );   
   // Scale based on screen space distance from screen position of light source to the screen center.
   F32 lightSourceSSDistanceScale = ( 1.5f - ( lightPosSS - screenCenter ).len() ) / 1.5f;

   // Scale based on recent visibility changes, fading in or out.
   F32 fadeInOutScale = 1.0f;
   if ( lightVisible && visDelta < fadeInTime && flareState->occlusion )
      fadeInOutScale = (F32)visDelta / (F32)fadeInTime;
   else if ( !lightVisible && visDelta < fadeOutTime )
      fadeInOutScale = 1.0f - (F32)visDelta / (F32)fadeOutTime;

   // This combined scale influences the size of all elements this effect renders.
   // Note we also add in a scale that is user specified in the Light.
   F32 lightSourceIntensityScale = lightSourceBrightnessScale * 
                                   lightSourceWSDistanceScale * 
                                   lightSourceSSDistanceScale * 
                                   fadeInOutScale * 
                                   flareState->scale *
                                   occlusionFade;

   // The baseColor which modulates the color of all elements.
   ColorF baseColor;
   if ( flareState->fullBrightness == 0.0f )
      baseColor = ColorF::BLACK;
   else
      // These are the factors which affect the "alpha" of the flare effect.
      // Modulate more in as appropriate.
      baseColor = ColorF::WHITE * lightSourceBrightnessScale * occlusionFade;

   // Fill in the vertex buffer...
   const U32 vertCount = 4 * elementCount;
   if (  flareState->vertBuffer.isNull() || 
         flareState->vertBuffer->mNumVerts != vertCount )
         flareState->vertBuffer.set( GFX, vertCount, GFXBufferTypeDynamic );

   GFXVertexPCT *pVert = flareState->vertBuffer.lock();

   const Point2I &widthHeightI = mFlareTexture.getWidthHeight();
   Point2F oneOverTexSize( 1.0f / (F32)widthHeightI.x, 1.0f / (F32)widthHeightI.y );

   for ( U32 i = 0; i < elementCount; i++ )
   {      
      Point3F *basePos = mElementRotate[i] ? rotatedBasePoints : basePoints;

      ColorF elementColor( baseColor * mElementTint[i] );
      if ( mElementUseLightColor[i] )
         elementColor *= lightInfo->getColor();

      Point3F elementPos;
      elementPos = lightPosSS + flareVec * mElementDist[i] * flareLength;      
      elementPos.z = 0.0f;

      F32 maxDist = 1.5f;
      F32 elementDist = mSqrt( ( elementPos.x * elementPos.x ) + ( elementPos.y * elementPos.y ) );
      F32 distanceScale = ( maxDist - elementDist ) / maxDist;
      distanceScale = 1.0f;

      const RectF &elementRect = mElementRect[i];
      Point3F elementSize( elementRect.extent.x, elementRect.extent.y, 1.0f );
      elementSize *= mElementScale[i] * distanceScale * mScale * lightSourceIntensityScale;

      if ( elementSize.x < 100.0f )
      {
         F32 alphaScale = mPow( elementSize.x / 100.0f, 2 );
         elementColor *= alphaScale;
      }

      elementColor.clamp();

      Point2F texCoordMin, texCoordMax;
      texCoordMin = elementRect.point * oneOverTexSize;
      texCoordMax = ( elementRect.point + elementRect.extent ) * oneOverTexSize;          

      pVert->color = elementColor;
      pVert->point = ( basePos[0] * elementSize * oneOverViewportExtent ) + elementPos;      
      pVert->texCoord.set( texCoordMin.x, texCoordMax.y );
      pVert++;

      pVert->color = elementColor;
      pVert->point = ( basePos[1] * elementSize * oneOverViewportExtent ) + elementPos;
      pVert->texCoord.set( texCoordMax.x, texCoordMax.y );
      pVert++;

      pVert->color = elementColor;
      pVert->point = ( basePos[2] * elementSize * oneOverViewportExtent ) + elementPos;
      pVert->texCoord.set( texCoordMax.x, texCoordMin.y );
      pVert++;

      pVert->color = elementColor;
      pVert->point = ( basePos[3] * elementSize * oneOverViewportExtent ) + elementPos;
      pVert->texCoord.set( texCoordMin.x, texCoordMin.y );
      pVert++;
   }   

   flareState->vertBuffer.unlock();   

   // Create and submit the render instance...
   
   RenderPassManager *renderManager = state->getRenderPass();
   ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>();

   ri->vertBuff = &flareState->vertBuffer;
   ri->primBuff = &mFlarePrimBuffer;
   ri->translucentSort = true;
   ri->type = RenderPassManager::RIT_Particle;
   ri->sortDistSq = ( lightPos - camPos ).lenSquared();

   ri->modelViewProj = &MatrixF::Identity;
   ri->bbModelViewProj = ri->modelViewProj;

   ri->count = elementCount;

   // Only draw the light flare in high-res mode, never off-screen mode
   ri->systemState = ParticleRenderInst::AwaitingHighResDraw;

   ri->blendStyle = ParticleRenderInst::BlendGreyscale;

   ri->diffuseTex = &*(mFlareTexture);

   ri->softnessDistance = 1.0f; 

   // Sort by texture too.
   ri->defaultKey = ri->diffuseTex ? (U32)ri->diffuseTex : (U32)ri->vertBuff;

   renderManager->addInst( ri );
}
Example #9
0
/**
 * @brief Update diff-number pane text
 */
void CHexMergeDoc::OnUpdateStatusNum(CCmdUI* pCmdUI) 
{
	String s;
	pCmdUI->SetText(s.c_str());
}
Example #10
0
void TembooMessaging::setAppKey(const String& appKey) {
	m_appKey = appKey.c_str();
}
Example #11
0
void TembooMessaging::setDeviceID(const String& deviceID) {
	m_deviceID = deviceID.c_str();
}
Example #12
0
void TembooMessaging::setAppKeyName(const String& appKeyName) {
	m_appKeyName = appKeyName.c_str();
}
Example #13
0
void TembooMessaging::setAccountName(const String& accountName) {
	m_accountName = accountName.c_str();
}
void TerrainObjectManager::loadObject(const Ogre::String &name, const Ogre::Vector3 &pos, const Ogre::Vector3 &rot, Ogre::SceneNode *bakeNode, const Ogre::String &instancename, const Ogre::String &type, bool enable_collisions /* = true */, int scripthandler /* = -1 */, bool uniquifyMaterial /* = false */)
{
	ScopeLog log("object_"+name);

	if (type == "grid")
	{
		// some fast grid object hacks :)
		for (int x=0; x < 500; x += 50)
		{
			for (int z=0; z < 500; z += 50)
			{
				const String notype = "";
				loadObject(name, pos + Vector3(x, 0.0f, z), rot, bakeNode, name, notype, enable_collisions, scripthandler, uniquifyMaterial);
			}
		}
		return;
	}

	// nice idea, but too many random hits
	//if (abs(rot.x+1) < 0.001) rot.x = Math::RangeRandom(0, 360);
	//if (abs(rot.y+1) < 0.001) rot.y = Math::RangeRandom(0, 360);
	//if (abs(rot.z+1) < 0.001) rot.z = Math::RangeRandom(0, 360);

	if (name.empty()) return;

	//FILE *fd;
	//char oname[1024] = {};
	char mesh[1024] = {};
	char line[1024] = {};
	char collmesh[1024] = {};
	Vector3 l(Vector3::ZERO);
	Vector3 h(Vector3::ZERO);
	Vector3 dr(Vector3::ZERO);
	Vector3 fc(Vector3::ZERO);
	Vector3 sc(Vector3::ZERO);
	Vector3 sr(Vector3::ZERO);
	bool forcecam=false;
	bool ismovable=false;

	int event_filter = EVENT_ALL;

	Quaternion rotation = Quaternion(Degree(rot.x), Vector3::UNIT_X) * Quaternion(Degree(rot.y), Vector3::UNIT_Y) * Quaternion(Degree(rot.z), Vector3::UNIT_Z);

	// try to load with UID first!
	String odefgroup = "";
	String odefname = name + ".odef";

	bool odefFound = false;

	bool exists = ResourceGroupManager::getSingleton().resourceExistsInAnyGroup(odefname);
	if (exists)
	{
		odefgroup = ResourceGroupManager::getSingleton().findGroupContainingResource(odefname);
		odefFound = true;
	}
	
	if (!RoR::Application::GetCacheSystem()->checkResourceLoaded(odefname, odefgroup))
		if (!odefFound)
		{
			LOG("Error while loading Terrain: could not find required .odef file: " + odefname + ". Ignoring entry.");
			return;
		}

		DataStreamPtr ds=ResourceGroupManager::getSingleton().openResource(odefname, odefgroup);

		ds->readLine(mesh, 1023);
		if (String(mesh) == "LOD")
		{
			// LOD line is obsolete
			ds->readLine(mesh, 1023);
		}

		//scale
		ds->readLine(line, 1023);
		sscanf(line, "%f, %f, %f",&sc.x, &sc.y, &sc.z);
		String entityName = "object" + TOSTRING(objcounter) + "(" + name + ")";
		objcounter++;

		SceneNode *tenode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode();
		bool background_loading = BSETTING("Background Loading", false);

		MeshObject *mo = NULL;
		if (String(mesh) != "none")
		{
			mo = new MeshObject(mesh, entityName, tenode, NULL, background_loading);
		}

		//mo->setQueryFlags(OBJECTS_MASK);
		//tenode->attachObject(te);
		tenode->setScale(sc);
		tenode->setPosition(pos);
		tenode->rotate(rotation);
		tenode->pitch(Degree(-90));
		tenode->setVisible(true);

		// register in map
		loadedObject_t *obj = &loadedObjects[instancename];
		obj->instanceName = instancename;
		obj->loadType     = 0;
		obj->enabled      = true;
		obj->sceneNode    = tenode;
		obj->collTris.clear();

		if (mo && uniquifyMaterial && !instancename.empty())
		{
			for (unsigned int i = 0; i < mo->getEntity()->getNumSubEntities(); i++)
			{
				SubEntity *se = mo->getEntity()->getSubEntity(i);
				String matname = se->getMaterialName();
				String newmatname = matname + "/" + instancename;
				//LOG("subentity " + TOSTRING(i) + ": "+ matname + " -> " + newmatname);
				se->getMaterial()->clone(newmatname);
				se->setMaterialName(newmatname);
			}
		}

		//String meshGroup = ResourceGroupManager::getSingleton().findGroupContainingResource(mesh);
		//MeshPtr mainMesh = mo->getMesh();

		//collision box(es)
		bool virt=false;
		bool rotating=false;
		bool classic_ref=true;
		// everything is of concrete by default
		ground_model_t *gm = gEnv->collisions->getGroundModelByString("concrete");
		char eventname[256] = {};
		while (!ds->eof())
		{
			size_t ll=ds->readLine(line, 1023);

			// little workaround to trim it
			String lineStr = String(line);
			Ogre::StringUtil::trim(lineStr);

			const char* ptline = lineStr.c_str();
			if (ll==0 || line[0]=='/' || line[0]==';') continue;

			if (!strcmp("end",ptline)) break;
			if (!strcmp("movable", ptline)) {ismovable=true;continue;};
			if (!strcmp("localizer-h", ptline))
			{
				localizers[free_localizer].position=Vector3(pos.x,pos.y,pos.z);
				localizers[free_localizer].rotation=rotation;
				localizers[free_localizer].type=Autopilot::LOCALIZER_HORIZONTAL;
				free_localizer++;
				continue;
			}
			if (!strcmp("localizer-v", ptline))
			{
				localizers[free_localizer].position=Vector3(pos.x,pos.y,pos.z);
				localizers[free_localizer].rotation=rotation;
				localizers[free_localizer].type=Autopilot::LOCALIZER_VERTICAL;
				free_localizer++;
				continue;
			}
			if (!strcmp("localizer-ndb", ptline))
			{
				localizers[free_localizer].position=Vector3(pos.x,pos.y,pos.z);
				localizers[free_localizer].rotation=rotation;
				localizers[free_localizer].type=Autopilot::LOCALIZER_NDB;
				free_localizer++;
				continue;
			}
			if (!strcmp("localizer-vor", ptline))
			{
				localizers[free_localizer].position=Vector3(pos.x,pos.y,pos.z);
				localizers[free_localizer].rotation=rotation;
				localizers[free_localizer].type=Autopilot::LOCALIZER_VOR;
				free_localizer++;
				continue;
			}
			if (!strcmp("standard", ptline)) {classic_ref=false;tenode->pitch(Degree(90));continue;};
			if (!strncmp("sound", ptline, 5))
			{
#ifdef USE_OPENAL
				if (!SoundScriptManager::getSingleton().isDisabled())
				{
					char tmp[255]="";
					sscanf(ptline, "sound %s", tmp);
					SoundScriptInstance *sound = SoundScriptManager::getSingleton().createInstance(tmp, MAX_TRUCKS+1, tenode);
					sound->setPosition(tenode->getPosition(), Vector3::ZERO);
					sound->start();
				}
#endif //USE_OPENAL
				continue;
			}
			if (!strcmp("beginbox", ptline) || !strcmp("beginmesh", ptline))
			{
				dr = Vector3::ZERO;
				rotating=false;
				virt=false;
				forcecam=false;
				event_filter=EVENT_NONE;
				eventname[0]=0;
				collmesh[0]=0;
				gm = gEnv->collisions->getGroundModelByString("concrete");
				continue;
			};
			if (!strncmp("boxcoords", ptline, 9))
			{
				sscanf(ptline, "boxcoords %f, %f, %f, %f, %f, %f",&l.x,&h.x,&l.y,&h.y,&l.z, &h.z);
				continue;
			}
			if (!strncmp("mesh", ptline, 4))
			{
				sscanf(ptline, "mesh %s",collmesh);
				continue;
			}
			if (!strncmp("rotate", ptline, 6))
			{
				sscanf(ptline, "rotate %f, %f, %f",&sr.x, &sr.y, &sr.z);
				rotating=true;
				continue;
			}
			if (!strncmp("forcecamera", ptline, 11))
			{
				sscanf(ptline, "forcecamera %f, %f, %f",&fc.x, &fc.y, &fc.z);
				forcecam=true;
				continue;
			}
			if (!strncmp("direction", ptline, 9))
			{
				sscanf(ptline, "direction %f, %f, %f",&dr.x, &dr.y, &dr.z);
				continue;
			}
			if (!strncmp("frictionconfig", ptline, 14) && strlen(ptline) > 15)
			{
				// load a custom friction config
				gEnv->collisions->loadGroundModelsConfigFile(String(ptline + 15));
				continue;
			}
			if ((!strncmp("stdfriction", ptline, 11) || !strncmp("usefriction", ptline, 11)) && strlen(ptline) > 12)
			{
				String modelName = String(ptline + 12);
				gm = gEnv->collisions->getGroundModelByString(modelName);
				continue;
			}
			if (!strcmp("virtual", ptline)) {virt=true;continue;};
			if (!strncmp("event", ptline, 5))
			{
				char ts[256];
				ts[0]=0;
				sscanf(ptline, "event %s %s",eventname, ts);
				if (!strncmp(ts, "avatar", 6))
					event_filter=EVENT_AVATAR;
				else if (!strncmp(ts, "truck", 5))
					event_filter=EVENT_TRUCK;
				else if (!strncmp(ts, "airplane", 8))
					event_filter=EVENT_AIRPLANE;
				else if (!strncmp(ts, "boat", 8))
					event_filter=EVENT_BOAT;
				else if (!strncmp(ts, "delete", 8))
					event_filter=EVENT_DELETE;

				//if (!strncmp(ts, "shoptruck", 9))
				//	terrainManager->terrainHasTruckShop=true;

				// fallback
				if (strlen(ts) == 0)
					event_filter=EVENT_ALL;

				continue;
			}
			if (!strcmp("endbox", ptline))
			{
				if (enable_collisions)
				{
					const String eventnameStr = eventname;					
					int boxnum = gEnv->collisions->addCollisionBox(tenode, rotating, virt, pos, rot, l, h, sr, eventnameStr, instancename, forcecam, fc, sc, dr, event_filter, scripthandler);
					obj->collBoxes.push_back((boxnum));
				}
				continue;
			}
			if (!strcmp("endmesh", ptline))
			{
				gEnv->collisions->addCollisionMesh(collmesh, Vector3(pos.x,pos.y,pos.z), tenode->getOrientation(), sc, gm, &(obj->collTris));
				continue;
			}

			if (!strncmp("particleSystem", ptline, 14) && tenode)
			{
				float x=0, y=0, z=0, scale=0;
				char pname[255]="", sname[255]="";
				int res = sscanf(ptline, "particleSystem %f, %f, %f, %f, %s %s", &scale, &x, &y, &z, pname, sname);
				if (res != 6) continue;

				// hacky: prevent duplicates
				String paname = String(pname);
				while(gEnv->sceneManager->hasParticleSystem(paname))
					paname += "_";

				// create particle system
				ParticleSystem* pParticleSys = gEnv->sceneManager->createParticleSystem(paname, String(sname));
				pParticleSys->setCastShadows(false);
				pParticleSys->setVisibilityFlags(DEPTHMAP_DISABLED); // disable particles in depthmap

				// Some affectors may need its instance name (e.g. for script feedback purposes)
#ifdef USE_ANGELSCRIPT
				unsigned short affCount = pParticleSys->getNumAffectors();
				ParticleAffector* pAff;
				for (unsigned short i = 0; i<affCount; ++i)
				{
					pAff = pParticleSys->getAffector(i);
					if (pAff->getType()=="ExtinguishableFire")
					{
						((ExtinguishableFireAffector*)pAff)->setInstanceName(obj->instanceName);
					}
				}
#endif // USE_ANGELSCRIPT

				SceneNode *sn = tenode->createChildSceneNode();
				sn->attachObject(pParticleSys);
				sn->pitch(Degree(90));
				continue;
			}

			if (!strncmp("setMeshMaterial", ptline, 15))
			{
				char mat[256]="";
				sscanf(ptline, "setMeshMaterial %s", mat);
				if (mo->getEntity() && strnlen(mat,250)>0)
				{
					mo->getEntity()->setMaterialName(String(mat));
					// load it
					//MaterialManager::getSingleton().load(String(mat), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
				}
				continue;
			}
			if (!strncmp("generateMaterialShaders", ptline, 23))
			{
				char mat[256]="";
				sscanf(ptline, "generateMaterialShaders %s", mat);
				if (BSETTING("Use RTShader System", false))
				{
					Ogre::RTShader::ShaderGenerator::getSingleton().createShaderBasedTechnique(String(mat), Ogre::MaterialManager::DEFAULT_SCHEME_NAME, Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
					Ogre::RTShader::ShaderGenerator::getSingleton().invalidateMaterial(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, String(mat));
				}

				continue;
			}
			if (!strncmp("playanimation", ptline, 13) && mo)
			{
				char animname[256]="";
				float speedfactorMin = 0, speedfactorMax = 0;
				sscanf(ptline, "playanimation %f, %f, %s", &speedfactorMin, &speedfactorMax, animname);
				if (tenode && mo->getEntity() && strnlen(animname,250)>0)
				{
					AnimationStateSet *s = mo->getEntity()->getAllAnimationStates();
					if (!s->hasAnimationState(String(animname)))
					{
						LOG("ODEF: animation '" + String(animname) + "' for mesh: '" + String(mesh) + "' in odef file '" + name + ".odef' not found!");
						continue;
					}
					animated_object_t ao;
					ao.node = tenode;
					ao.ent = mo->getEntity();
					ao.speedfactor = speedfactorMin;
					if (speedfactorMin != speedfactorMax)
						ao.speedfactor = Math::RangeRandom(speedfactorMin, speedfactorMax);
					ao.anim = 0;
					try
					{
						ao.anim = mo->getEntity()->getAnimationState(String(animname));
					} catch (...)
					{
						ao.anim = 0;
					}
					if (!ao.anim)
					{
						LOG("ODEF: animation '" + String(animname) + "' for mesh: '" + String(mesh) + "' in odef file '" + name + ".odef' not found!");
						continue;
					}
					ao.anim->setEnabled(true);
					animatedObjects.push_back(ao);
				}
				continue;
			}
			if (!strncmp("drawTextOnMeshTexture", ptline, 21) && mo)
			{
				if (!mo->getEntity())
					continue;
				String matName = mo->getEntity()->getSubEntity(0)->getMaterialName();
				MaterialPtr m = MaterialManager::getSingleton().getByName(matName);
				if (m.getPointer() == 0)
				{
					LOG("ODEF: problem with drawTextOnMeshTexture command: mesh material not found: "+odefname+" : "+String(ptline));
					continue;
				}
				String texName = m->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureName();
				Texture* background = (Texture *)TextureManager::getSingleton().getByName(texName).getPointer();
				if (!background)
				{
					LOG("ODEF: problem with drawTextOnMeshTexture command: mesh texture not found: "+odefname+" : "+String(ptline));
					continue;
				}

				static int textureNumber = 0;
				textureNumber++;
				char tmpTextName[256]="", tmpMatName[256]="";
				sprintf(tmpTextName, "TextOnTexture_%d_Texture", textureNumber);
				sprintf(tmpMatName, "TextOnTexture_%d_Material", textureNumber);			// Make sure the texture is not WRITE_ONLY, we need to read the buffer to do the blending with the font (get the alpha for example)
				TexturePtr texture = TextureManager::getSingleton().createManual(tmpTextName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, (Ogre::uint)background->getWidth(), (Ogre::uint)background->getHeight(), MIP_UNLIMITED , PF_X8R8G8B8, Ogre::TU_STATIC|Ogre::TU_AUTOMIPMAP, new ResourceBuffer());
				if (texture.getPointer() == 0)
				{
					LOG("ODEF: problem with drawTextOnMeshTexture command: could not create texture: "+odefname+" : "+String(ptline));
					continue;
				}

				float x=0, y=0, w=0, h=0;
				float a=0, r=0, g=0, b=0;
				char fontname[256]="";
				char text[256]="";
				char option='l';
				int res = sscanf(ptline, "drawTextOnMeshTexture %f, %f, %f, %f, %f, %f, %f, %f, %c, %s %s", &x, &y, &w, &h, &r, &g, &b, &a, &option, fontname, text);
				if (res < 11)
				{
					LOG("ODEF: problem with drawTextOnMeshTexture command: "+odefname+" : "+String(ptline));
					continue;
				}

				// check if we got a template argument
				if (!strncmp(text, "{{argument1}}", 13))
					strncpy(text, instancename.c_str(), 250);

				// replace '_' with ' '
				char *text_pointer = text;
				while (*text_pointer!=0) {if (*text_pointer=='_') *text_pointer=' ';text_pointer++;};

				Font* font = (Font *)FontManager::getSingleton().getByName(String(fontname)).getPointer();
				if (!font)
				{
					LOG("ODEF: problem with drawTextOnMeshTexture command: font not found: "+odefname+" : "+String(ptline));
					continue;
				}


				//Draw the background to the new texture
				texture->getBuffer()->blit(background->getBuffer());

				x = background->getWidth() * x;
				y = background->getHeight() * y;
				w = background->getWidth() * w;
				h = background->getHeight() * h;

				Image::Box box = Image::Box((size_t)x, (size_t)y, (size_t)(x+w), (size_t)(y+h));
				WriteToTexture(String(text), texture, box, font, ColourValue(r, g, b, a), option);

				// we can save it to disc for debug purposes:
				//SaveImage(texture, "test.png");

				m->clone(tmpMatName);
				MaterialPtr mNew = MaterialManager::getSingleton().getByName(tmpMatName);
				mNew->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(tmpTextName);

				mo->getEntity()->setMaterialName(String(tmpMatName));
				continue;
			}

			LOG("ODEF: unknown command in "+odefname+" : "+String(ptline));
		}

		//add icons if type is set
#ifdef USE_MYGUI
		String typestr = "";
		if (!type.empty() && gEnv->surveyMap)
		{
			typestr = type;
			// hack for raceways
			if (name == "chp-checkpoint")
				typestr = "checkpoint";
			if (name == "chp-start")
				typestr = "racestart";
			if (name == "road", 4)
				typestr = "road";

			if (typestr != "" && typestr != "road" && typestr != "sign")
			{
				SurveyMapEntity *e = gEnv->surveyMap->createMapEntity(typestr);
				if (e)
				{
					e->setVisibility(true);
					e->setPosition(pos);
					e->setRotation(Radian(rot.y));

					if (!name.empty()) e->setDescription(instancename);
				}
			}
		}
#endif //USE_MYGUI
}
Example #15
0
void bar(const String& x)
{
    std::cout << x.c_str() << std::endl;
}
void ChangeFontPropertyCommand::Execute()
{
    //TODO: save data to be able to revert changes
    Logger::FrameworkDebug("ChangeFontPropertyCommand::Execute SetLocalizedFont %s %p %s default", data.fontPresetOriginalName.c_str(), data.font, data.fontPresetName.c_str());
    String newFontPresetName = EditorFontManager::Instance()->SetLocalizedFont(data.fontPresetOriginalName, data.font, data.fontPresetName, data.isApplyToAll, "default");
    
    Map<String, Font*>::iterator it = data.localizedFonts.begin();
    Map<String, Font*>::const_iterator endIt = data.localizedFonts.end();
    for(; it != endIt; ++it)
    {
        Logger::FrameworkDebug("ChangeFontPropertyCommand::Execute SetLocalizedFont %s %p %s %s", data.fontPresetOriginalName.c_str(), it->second, data.fontPresetName.c_str(), it->first.c_str());
        String localizedNewFontPresetName = EditorFontManager::Instance()->SetLocalizedFont(data.fontPresetOriginalName, it->second, newFontPresetName, data.isApplyToAll, it->first);
        if(localizedNewFontPresetName != newFontPresetName)
        {
            Logger::Error("ChangeFontPropertyCommand::Execute newFontPresetName=%s is different for locale %s: localizedNewFontPresetName=%s", newFontPresetName.c_str(), it->first.c_str(), localizedNewFontPresetName.c_str());
        }
    }
    
    if(data.isApplyToAll)
    {
        Logger::FrameworkDebug("ChangeFontPropertyCommand::Execute TODO: apply to all fonts");
        //TODO: set new font in all controls that use this font
    }
    
    // apply current font change
    return ChangePropertyCommand<Font *>::Execute();
}
Example #17
0
	Log::Log(const String& name, LoggingLevel ll) :
		mLogLevel(ll), mTimeStamp(true), mLogName(name)
	{
		mLog.open(name.c_str(), std::ios_base::app);
	}
void WebSocketsClient::sendTXT(String payload) {
    sendTXT((uint8_t *) payload.c_str(), payload.length());
}
Example #19
0
  /** Methods **/
  objectMeasure()
  {
    cout << "Program has started!"<< endl;
    printf("Digite a distancia do objeto a ser medido:\n");
    scanf("%f",&dist);
    // Initializing width and height
    initialW = new Pair();
    finalW = new Pair();
    initialH = new Pair();
    finalH = new Pair();
    dW = -1;
    dH = -1;


    // Capturing from camera
    CvCapture* capture;
    capture = cvCreateCameraCapture( -1 );

    if(!capture)
    {
      printf("\nCouldn't open the camera\n");
      exit(-1);
    }

    // Camera captured image
    image = cvQueryFrame( capture );



    String intrinsicFile  = calibFilesPath + "Intrinsics.xml";
    String distortionFile = calibFilesPath + "Distortion.xml";

    // Reading .xml files for calibration
    CvMat *intrinsic  = (CvMat*)cvLoad(intrinsicFile.c_str());
    CvMat *distortion = (CvMat*)cvLoad(distortionFile.c_str());

    //Getting the values of constants fx,fy,cx and cy
    CvScalar aux_intensity;
    float aux_valor;
    printf("Intrinsic: \n");
          aux_intensity = cvGet2D(intrinsic,0,0);
          fx = aux_intensity.val[0];
          printf(" fx : %f \n",fx);
          aux_intensity = cvGet2D(intrinsic,1,1);
          fy = aux_intensity.val[0];
          printf(" fy : %f \n",fy);
          aux_intensity = cvGet2D(intrinsic,0,2);
          cx = aux_intensity.val[0];
          printf(" cx : %f \n",cx);
          aux_intensity = cvGet2D(intrinsic,1,2);
          cy = aux_intensity.val[0];
          printf(" cy : %f \n",cy);
      printf("\n");
      //Getting the values of constans k1,k2,p1,p2
    printf("Distortion: \n");
          aux_intensity = cvGet2D(distortion,0,0);
          k1 = aux_intensity.val[0];
          printf(" k1 : %f \n",k1);
          aux_intensity = cvGet2D(distortion,1,0);
          k2 = aux_intensity.val[0];
          printf(" k2 : %f \n",k2);
          aux_intensity = cvGet2D(distortion,2,0);
          p1 = aux_intensity.val[0];
          printf(" p1 : %f \n",p1);
          aux_intensity = cvGet2D(distortion,3,0);
          p2 = aux_intensity.val[0];
          printf(" p2 : %f \n",p2);
      printf("\n");

    // Matrices for map calibration
    IplImage* mapx = cvCreateImage( cvGetSize(image), IPL_DEPTH_32F, 1 );
    IplImage* mapy = cvCreateImage( cvGetSize(image), IPL_DEPTH_32F, 1 );
    cvInitUndistortMap(intrinsic,distortion,mapx,mapy);

    // Naming windows
    cvNamedWindow( "Raw Video");
//  cvNamedWindow( "Undistorted Video" );

    // The following loop is interrupted only when user presses Esc. After that, we move to contours find functions
    while(image)
    {
//    IplImage *t = cvCloneImage(image);
      cvShowImage( "Raw Video", image );      // Show raw image
//    cvRemap( t, image, mapx, mapy );      // Undistort image
//    cvReleaseImage(&t);
//    cvShowImage("Undistorted Video", image);      // Show corrected image
          
      int c = cvWaitKey(15);

      if(c == 'p')
      {
        c = 0;
        while(c != 'p' && c != 27)
        {
          c = cvWaitKey(250);
        }
      }

      if(c == 27)
        break;

      image = cvQueryFrame( capture );
    }

    // Close video window
    destroyWindow( "Raw Video");

    // Intermediary Mat matrix
    Mat img(image);

    // Output instructions for user
    cout << "\nNow, you must click, on the 'Contours Gray' window, in the following order:\n"
         << "1) two points to calculate width, and\n"
         << "2) two point to calculate height" << endl;

    // Set window
    namedWindow( "Image", WINDOW_AUTOSIZE );

    // Show image
    imshow( "Image", img );

    // Transform img into img_gray
    cvtColor(img, img_gray, CV_BGR2GRAY);

    // Bluring img_gray
    blur( img_gray, img_gray, Size(3,3) );

    namedWindow( "Contours Gray", WINDOW_AUTOSIZE );

    // Create a bar to change contours thresh
    createTrackbar( "Canny thresh:", "Contours Gray", &thresh, max_thresh, thresh_callback, this );

    // Finding contours
    thresh_callback( thresh, this );
  }
/**
 * handle the WebSocket header reading
 * @param client WSclient_t *  ptr to the client struct
 */
void WebSocketsClient::handleHeader(WSclient_t * client) {

    String headerLine = client->tcp->readStringUntil('\n');
    headerLine.trim(); // remove \r

    if(headerLine.length() > 0) {
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] RX: %s\n", headerLine.c_str());

        if(headerLine.startsWith("HTTP/1.")) {
            // "HTTP/1.1 101 Switching Protocols"
            client->cCode = headerLine.substring(9, headerLine.indexOf(' ', 9)).toInt();
        } else if(headerLine.indexOf(':')) {
            String headerName = headerLine.substring(0, headerLine.indexOf(':'));
            String headerValue = headerLine.substring(headerLine.indexOf(':') + 2);

            if(headerName.equalsIgnoreCase("Connection")) {
                if(headerValue.indexOf("Upgrade") >= 0) {
                    client->cIsUpgrade = true;
                }
            } else if(headerName.equalsIgnoreCase("Upgrade")) {
                if(headerValue.equalsIgnoreCase("websocket")) {
                    client->cIsWebsocket = true;
                }
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Accept")) {
                client->cAccept = headerValue;
                client->cAccept.trim(); // see rfc6455
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Protocol")) {
                client->cProtocol = headerValue;
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Extensions")) {
                client->cExtensions = headerValue;
            } else if(headerName.equalsIgnoreCase("Sec-WebSocket-Version")) {
                client->cVersion = headerValue.toInt();
            }
        } else {
            DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header error (%s)\n", headerLine.c_str());
        }

    } else {
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header read fin.\n");
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Client settings:\n");

        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cURL: %s\n", client->cUrl.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cKey: %s\n", client->cKey.c_str());

        DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Server header:\n");
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cCode: %d\n", client->cCode);
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cIsUpgrade: %d\n", client->cIsUpgrade);
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cIsWebsocket: %d\n", client->cIsWebsocket);
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cAccept: %s\n", client->cAccept.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cProtocol: %s\n", client->cProtocol.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cExtensions: %s\n", client->cExtensions.c_str());
        DEBUG_WEBSOCKETS("[WS-Client][handleHeader]  - cVersion: %d\n", client->cVersion);

        bool ok = (client->cIsUpgrade && client->cIsWebsocket);

        if(ok) {
            switch(client->cCode) {
                case 101:  ///< Switching Protocols

                    break;
                case 403: ///< Forbidden
                    // todo handle login
                default:   ///< Server dont unterstand requrst
                    ok = false;
                    DEBUG_WEBSOCKETS("[WS-Client][handleHeader] serverCode is not 101 (%d)\n", client->cCode);
                    clientDisconnect(client);
                    break;
            }
        }

        if(ok) {
            if(client->cAccept.length() == 0) {
                ok = false;
            } else {
                // generate Sec-WebSocket-Accept key for check
                String sKey = acceptKey(client->cKey);
                if(sKey != client->cAccept) {
                    DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Sec-WebSocket-Accept is wrong\n");
                    ok = false;
                }
            }
        }

        if(ok) {

            DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Websocket connection init done.\n");

            client->status = WSC_CONNECTED;

            runCbEvent(WStype_CONNECTED, (uint8_t *) client->cUrl.c_str(), client->cUrl.length());

        } else {
            DEBUG_WEBSOCKETS("[WS-Client][handleHeader] no Websocket connection close.\n");
            client->tcp->write("This is a webSocket client!");
            clientDisconnect(client);
        }
    }
}
Example #21
0
bool CRhodesModule::ParseCommandLine(LPCTSTR lpCmdLine, HRESULT* pnRetCode ) throw( )
{
	m_nRestarting      = 1;
    m_bMinimized       = false;
    m_startAtBoot      = false;
    m_logPort          = "";
    m_isRhoConnectPush = false;
    LPCTSTR lpszToken  = lpCmdLine;
	LPCTSTR nextToken;

    getRhoRootPath();

	while (lpszToken != NULL)
	{
		// skip leading spaces and double-quote (if present)
	    bool doubleQuote = false;
		while ((*lpszToken != 0) && ((*lpszToken==' ') || ((!doubleQuote) && (*lpszToken=='"')))) {
			if (*lpszToken=='"')
				doubleQuote = true;
			lpszToken++;
		}
		// skip leading spaces and check for leading '/' or '-' of command line option
		bool isCmdLineOpt = false;
		while ((*lpszToken != 0) && ((*lpszToken==' ') || ((!isCmdLineOpt) && ((*lpszToken=='/') || (*lpszToken=='-'))))) {
			if ((*lpszToken=='/') || (*lpszToken=='-'))
				isCmdLineOpt = true;
			lpszToken++;
		}
		// finish command line processing on EOL
		if (*lpszToken == 0) break;

		// if option starts with double-quote, find its end by next double-quote;
		// otherwise the end will be found automatically
		nextToken = doubleQuote ? FindOneOf(lpszToken, _T("\"")) : NULL;

		//parseToken will allocate extra byte at the end of the returned token value
		LPTSTR value = parseToken( lpszToken, &nextToken );

		if (isCmdLineOpt) {
			if (WordCmpI(lpszToken, _T("Restarting"))==0) {
				m_nRestarting = 10;
			}

            if (wcsncmp(lpszToken, _T("minimized"), 9)==0) {
				m_bMinimized = true;
			}

			if (WordCmpI(lpszToken, _T("rhoconnectpush"))==0) {
				m_isRhoConnectPush = true;
			}

			else if (wcsncmp(lpszToken, _T("log"), 3)==0) 
			{
				if (value) {
					m_logPort = convertToStringA(value);
				}
				else {
					m_logPort = rho::String("11000");
				}
			}

#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
			else if (wcsnicmp(lpszToken, _T("s"),1)==0)
			{
				if (value) {
					// RhoElements v1.0 compatibility mode
					String strPath = convertToStringA(value);
					rho_wmimpl_set_startpage(strPath.c_str());
				}
			}
			else if (wcsnicmp(lpszToken, _T("c"),1)==0)
			{
				if (value) {
					String strPath = convertToStringA(value);
					if (strPath.substr(0,7).compare("file://")==0)
						strPath.erase(0,7);
					rho_wmimpl_set_configfilepath(strPath.c_str());
				}
			}
#endif // APP_BUILD_CAPABILITY_SHARED_RUNTIME

#if defined(OS_WINDOWS_DESKTOP)
			else if (wcsncmp(lpszToken, _T("http_proxy_url"),14)==0) 
			{
				if (value) {
					m_strHttpProxy = convertToStringA(value);
				}
				else 
					LOG(WARNING) + "invalid value for \"http_proxy_url\" cmd parameter";

			} else if (wcsncmp(lpszToken, _T("approot"),7)==0) 
			{
				if (value) {
					m_strRootPath = convertToStringA(value);
					String_replace(m_strRootPath, '\\', '/');
					if (m_strRootPath.at(m_strRootPath.length()-1)!='/')
						m_strRootPath.append("/");
				}
			} else if (wcsncmp(lpszToken, _T("rhodespath"),10)==0) 
			{
				if (value) {
					m_strRhodesPath = convertToStringA(value);
					String_replace(m_strRhodesPath, '\\', '/');
				}
			} /* else if (wcsncmp(lpszToken, _T("appname"),7)==0) 
			{
				if (value) {
					m_strAppNameW = convertToStringW(value);
				}
			} else if (wcsncmp(lpszToken, _T("debughost"),9)==0) 
			{
				if (value) {
					m_strDebugHost = convertToStringA(value);
				}
			} else if (wcsncmp(lpszToken, _T("debugport"),9)==0) 
			{
				if (value) {
					m_strDebugPort = convertToStringA(value);
				}
			} */
#else
			else if (wcsnicmp(lpszToken, _T("approot"),7)==0)
			{
				if (value) {
					// RhoElements v2.0 Shared Runtime command line parameter
					m_strRootPath = convertToStringA(value);
					if (m_strRootPath.substr(0,7).compare("file://")==0)
						m_strRootPath.erase(0,7);
					String_replace(m_strRootPath, '\\', '/');
					if (m_strRootPath.at(m_strRootPath.length()-1)!='/')
						m_strRootPath.append("/");
					m_strRootPath.append("rho/");
#ifdef APP_BUILD_CAPABILITY_SHARED_RUNTIME
					rho_wmimpl_set_is_version2(m_strRootPath.c_str());
#endif
        		}
			}
#endif
		}
		if (value) free(value);
		lpszToken = nextToken;
	}

	return __super::ParseCommandLine(lpCmdLine, pnRetCode);
}
void WebSocketsClient::begin(String host, uint16_t port, String url) {
    begin(host.c_str(), port, url.c_str());
}
size_t AsyncAbstractResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time){
  if(!_sourceValid()){
    _state = RESPONSE_FAILED;
    request->client()->close();
    return 0;
  }
  _ackedLength += len;
  size_t space = request->client()->space();
  if(_state == RESPONSE_CONTENT){
    size_t outLen;
    size_t readLen = 0;

    if(_chunked || !_sendContentLength){
      outLen = space;
    } else {
      size_t remaining = _contentLength - _sentLength;
      outLen = (remaining > space)?space:remaining;
    }
    uint8_t *buf = (uint8_t *)malloc(outLen);

    if(_chunked){
      readLen = _fillBuffer(buf, outLen - 8);
      char pre[6];
      sprintf(pre, "%x\r\n", readLen);
      size_t preLen = strlen(pre);
      memmove(buf+preLen, buf, preLen);
      for(size_t i=0; i<preLen; i++)
        buf[i] = pre[i];
      outLen = preLen + readLen;
      buf[outLen++] = '\r';
      buf[outLen++] = '\n';
    } else {
      outLen = _fillBuffer(buf, outLen);
    }

    if(outLen)
      outLen = request->client()->write((const char*)buf, outLen);
    _sentLength += outLen;
    free(buf);

    if((_chunked && readLen == 0) || (!_sendContentLength && outLen == 0) || _sentLength == _contentLength){
      _state = RESPONSE_WAIT_ACK;
    }
    return outLen;

  } else if(_state == RESPONSE_HEADERS){
    size_t outLen = _head.length();
    if(space >= outLen){
      request->client()->write(_head.c_str(), outLen);
      _head = String();
      _state = RESPONSE_CONTENT;
      return outLen;
    } else {
      String out = _head.substring(0, space);
      _head = _head.substring(space);
      request->client()->write(out.c_str(), out.length());
      return out.length();
    }
  } else if(_state == RESPONSE_WAIT_ACK){
    if(!_sendContentLength || _ackedLength >= (_headLength+_contentLength)){
      _state = RESPONSE_END;
      if(!_chunked && !_sendContentLength)
        request->client()->close();
    }
  }
  return 0;
}
void WebSocketsClient::beginSSL(String host, uint16_t port, String url, String fingerprint) {
    beginSSL(host.c_str(), port, url.c_str(), fingerprint.c_str());
}
Example #25
0
bool ALDevice::queryExtension(const String &name) const
{
    return alcIsExtensionPresent(mDevice, name.c_str());
}
// load all textures 
bool CCal3DSceneNode::init()
{
    bool ok = true; 

    if ( coreModels.isFileLoaded( configFile.c_str() ) )
    {
      String ls = configFile.c_str();
      ls.make_lower();
      CCal3DModelCache* cache = 0;
      cache = coreModels.findFile( ls.c_str() );
      if ( cache )
      {
        ///load from cache
        m_calCoreModel = cache->m_calCoreModel;
        m_scale = cache->m_scale;
        for ( int i = 0; i < 255; i++ )
        {
          m_animationId[i] = cache->m_animationId[i];
        }
        //CONSOLE.add( "Model loaded already", COLOR_WARNING );
      }
      else
      {
        bInitialized = false; 
        return false;
      }
    }
    else
    {
      //CONSOLE.add( "Model loading", COLOR_WARNING );
      CCal3DModelCache* cache = PrecacheModel( configFile.c_str() );
      ///load from cache
      if ( cache )
      {
        m_calCoreModel = cache->m_calCoreModel;
        m_scale = cache->m_scale;
        for ( int i = 0; i < 255; i++ )
        {
          m_animationId[i] = cache->m_animationId[i];
        }
      }
      else
      {
        bInitialized = false; 
        return false;
      }
    }


    // create the model instance from the loaded core model 
    m_calModel = new CalModel( m_calCoreModel ); 
    //if(!m_calModel->create(&m_calCoreModel)) 
    //{ 
    //"CalError : %s",CalError::getLastErrorDescription().c_str() 
    //   return false; 
    //} 

    // attach all meshes to the model 
    int meshId; 
    for ( meshId = 0; meshId < m_calCoreModel->getCoreMeshCount(); meshId++ )
    {
      m_calModel->attachMesh( meshId );
    } 
    // set the material set of the whole model 
    m_calModel->setMaterialSet( 0 ); 

    // set initial animation state 
    if ( m_calCoreModel->getCoreAnimationCount() > 0 )
    {
      m_currentAnimationId = 0; 
      m_leftAnimationTime = m_calCoreModel->getCoreAnimation( m_currentAnimationId )->getDuration() - m_blendTime; 
      if ( m_calCoreModel->getCoreAnimationCount() > 1 )
      {
        m_calModel->getMixer()->executeAction( m_currentAnimationId, 0.0f, m_blendTime );
      }
      else
      {
        m_calModel->getMixer()->blendCycle( m_currentAnimationId, 1.0f, 0.0f );
      }
    }
    else
    {
      m_currentAnimationId = -1; 
      m_leftAnimationTime = -1.0f;
    } 

    m_calModel->setLodLevel( m_lodLevel ); 

    m_calModel->update( 0 ); 

    // calculate the irrlicht bounding box 
    CalVector p[8]; 
    m_calModel->getBoundingBox( true ).computePoints( p ); 
    Box.reset( p[0].x, p[0].y, p[0].z ); 
    for ( int i = 0; i < 8; ++i )
    {
      Box.addInternalPoint( p[i].x, p[i].y, p[i].z );
    } 

    //"Init done." 
    bInitialized = ok; 

    return ok;
}
 void InstrumentEditor::Launch(EngineChannel* pEngineChannel, void* pInstrument, String sTypeName, String sTypeVersion, void* pUserData) {
     dmsg(1,("InstrumentEditor::Launch(instr=%x,type=%s,version=%s)\n", pInstrument, sTypeName.c_str(), sTypeVersion.c_str()));
     // prepare the editor's mandatory parameters
     this->pInstrument  = pInstrument;
     this->sTypeName    = sTypeName;
     this->sTypeVersion = sTypeVersion;
     this->pUserData    = pUserData;
     this->pEngineChannel = pEngineChannel;
     // start the editor in its own thread
     StartThread();
 }
Example #28
0
void foo(String x)
{
    std::cout << x.c_str() << std::endl;
}
Example #29
0
Xerces::XMLDocument::XMLDocument( const String& _sRootName )
{
    m_pNode = new Xerces::XMLNode();
    SetNodeType( DOCUMENT_NODE );
    m_spRootElement = XMLElementPtr( new XMLElement() );

    XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::Initialize();

    XMLCh tempStr[100];
    XERCES_CPP_NAMESPACE_QUALIFIER XMLString::transcode("Core", tempStr, 99);
    XERCES_CPP_NAMESPACE_QUALIFIER DOMImplementation* impl = XERCES_CPP_NAMESPACE_QUALIFIER DOMImplementationRegistry::getDOMImplementation( tempStr );

    XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDocNode = impl->createDocument( 0, XERCES_CPP_NAMESPACE_QUALIFIER XMLString::transcode( _sRootName.c_str() ), 0 );
    CO_ASSERT( pDocNode->getNodeType() == XERCES_CPP_NAMESPACE_QUALIFIER DOMNode::DOCUMENT_NODE, "Document with no document node?!" );
	
    SetXMLNode( pDocNode );
    m_spRootElement->SetXMLNode( pDocNode->getDocumentElement() );
}
Example #30
0
File: link.cpp Project: PyroOS/Pyro
/****************************************
* Description: Hopefully noone else uses this class because it is a horrible way to do 
* Author: Rick Caudill
* Date: Fri Mar 19 15:45:18 2004
****************************************/
Link::Link(const String& cLink, const String& cLinkName,Message* pcMessage,Color32_s sBgColor, Color32_s sFgColor) : Control(Rect(0,0,0,0),String(String(cLink.c_str()) + (String)"_" + String(cLinkName.c_str())),cLink,pcMessage,CF_FOLLOW_LEFT|CF_FOLLOW_TOP,WID_WILL_DRAW | WID_CLEAR_BACKGROUND)
{
	m = new Private;
	m->cLink = cLink;
	m->cLinkName = cLinkName;
	m->sBgColor = sBgColor;
	m->sFgColor = sFgColor;
}