static void InitCommandLine() { static const uint32 CMD_LINE_MAX = 16384u; // initialize the command line to an empty string FCommandLine::Set(TEXT("")); // read in the command line text file from the sdcard if it exists FString CommandLineFilePath = GFilePathBase + FString("/UE4Game/") + (!FApp::IsGameNameEmpty() ? FApp::GetGameName() : FPlatformProcess::ExecutableName()) + FString("/UE4CommandLine.txt"); FILE* CommandLineFile = fopen(TCHAR_TO_UTF8(*CommandLineFilePath), "r"); if(CommandLineFile == NULL) { // if that failed, try the lowercase version CommandLineFilePath = CommandLineFilePath.Replace(TEXT("UE4CommandLine.txt"), TEXT("ue4commandline.txt")); CommandLineFile = fopen(TCHAR_TO_UTF8(*CommandLineFilePath), "r"); } if(CommandLineFile) { char CommandLine[CMD_LINE_MAX]; fgets(CommandLine, ARRAY_COUNT(CommandLine) - 1, CommandLineFile); fclose(CommandLineFile); // chop off trailing spaces while (*CommandLine && isspace(CommandLine[strlen(CommandLine) - 1])) { CommandLine[strlen(CommandLine) - 1] = 0; } FCommandLine::Append(UTF8_TO_TCHAR(CommandLine)); } }
bool FDesktopPlatformLinux::OpenDirectoryDialog(const void* ParentWindowHandle, const FString& DialogTitle, const FString& DefaultPath, FString& OutFolderName) { #if WITH_LINUX_NATIVE_DIALOGS bool bSuccess; struct UFileDialogHints hints = DEFAULT_UFILEDIALOGHINTS; LinuxApplication->SetCapture(NULL); hints.Action = UFileDialogActionOpenDirectory; hints.WindowTitle = TCHAR_TO_UTF8(*DialogTitle); hints.InitialDirectory = TCHAR_TO_UTF8(*DefaultPath); UFileDialog* dialog = UFileDialog_Create(&hints); while(UFileDialog_ProcessEvents(dialog)) { FPlatformMisc::PumpMessages(true); // pretend that we're the main loop } const UFileDialogResult* result = UFileDialog_Result(dialog); if (result) { if (result->count == 1) { OutFolderName = UTF8_TO_TCHAR(result->selection[0]); //OutFolderName = IFileManager::Get().ConvertToRelativePath(*OutFolderName); // @todo (amigo): converting to relative path ends up without ../... FPaths::NormalizeFilename(OutFolderName); bSuccess = true; } else { bSuccess = false; } // Todo like in Windows, normalize files here instead of above } else { bSuccess = false; } UFileDialog_Destroy(dialog); return bSuccess; #else if (!FModuleManager::Get().IsModuleLoaded("SlateFileDialogs")) { FModuleManager::Get().LoadModule("SlateFileDialogs"); } ISlateFileDialogsModule *FileDialog = FModuleManager::GetModulePtr<ISlateFileDialogsModule>("SlateFileDialogs"); if (FileDialog) { return FileDialog->OpenDirectoryDialog(ParentWindowHandle, DialogTitle, DefaultPath, OutFolderName); } return false; #endif // WITH_LINUX_NATIVE_DIALOGS }
/** * Create a message definition for a given function * @param Function function to extract parameters from to create a message buffer */ const google::protobuf::Message* CreateRPCPrototype(UFunction* Function) { google::protobuf::FileDescriptorProto FunctionProtoDesc; FString FunctionName = Function->GetName(); FString FunctionFileName = FString::Printf(TEXT("%s.proto"), *FunctionName); FunctionProtoDesc.set_package(TCHAR_TO_UTF8(*FunctionName)); FunctionProtoDesc.set_name(TCHAR_TO_UTF8(*FunctionFileName)); google::protobuf::DescriptorProto* MsgProtDesc = FunctionProtoDesc.add_message_type(); MsgProtDesc->set_name(TCHAR_TO_UTF8(*FunctionName)); if (CreateProtoDeclaration(MsgProtDesc, Function, CPF_Parm)) { google::protobuf::string proto = FunctionProtoDesc.DebugString(); const google::protobuf::FileDescriptor* FD = DscrPool.BuildFile(FunctionProtoDesc); const google::protobuf::Descriptor* MsgDescriptor = FD->message_type(0); return ProtoFactory.GetPrototype(MsgDescriptor); } else { FunctionProtoDesc.Clear(); } return NULL; }
void UTangoDevice::ExportCurrentArea(FString UUID, FString Filepath, bool& IsSuccessful) { UE_LOG(ProjectTangoPlugin, Log, TEXT("TangoDeviceAreaLearning::ExportCurrentArea: Starting export")); //Make the call to Java #if PLATFORM_ANDROID jobject AppContext = NULL; if (JNIEnv* Env = FAndroidApplication::GetJavaEnv()) { //Prepare the arguments jstring TangoExportUUIDArg = Env->NewStringUTF(TCHAR_TO_UTF8(*UUID)); jstring TangoExportFilenameArg = Env->NewStringUTF(TCHAR_TO_UTF8(*Filepath)); static jmethodID ADFExportIntentMethod = FJavaWrapper::FindMethod(Env, FJavaWrapper::GameActivityClassID, "AndroidThunkJava_RequestExportPermission", "(Ljava/lang/String;Ljava/lang/String;)V", false); FJavaWrapper::CallVoidMethod(Env, FJavaWrapper::GameActivityThis, ADFExportIntentMethod, TangoExportUUIDArg, TangoExportFilenameArg); } else { UE_LOG(ProjectTangoPlugin, Log, TEXT("TangoDeviceAreaLearning::ExportCurrentArea: Error: Could not get Java environment!")); } #endif UE_LOG(ProjectTangoPlugin, Log, TEXT("TangoDeviceAreaLearning::ExportCurrentArea: Finished export")); }
// Writes all metrics to file under the given section header. void MetricTracker::WriteMetricsToFile() { if (!File.is_open()) { File.open(*(FullPath), std::fstream::app); } File << '[' << TCHAR_TO_UTF8(*(SectionName)) << ']' << '\n'; if (!DiscreteValues.empty() && File.is_open()) { for (auto& e : DiscreteValues) { File << TCHAR_TO_UTF8(*(e.first)) << '=' << e.second << '\n'; } } if (!ContinuousValues.empty()) { for (auto& e : ContinuousValues) { File << TCHAR_TO_UTF8(*(e.first)) << ",\n" << TCHAR_TO_UTF8(*(e.second)) << '\n'; } } File.close(); }
bool USQLiteDatabase::ExecSql(const FString DatabaseName, const FString Query) { //LOGSQLITE(Warning, *query); bool execStatus = false; char *zErrMsg = 0; sqlite3 *db; ANSICHAR* dbNameAsUtf8 = TCHAR_TO_UTF8(*Databases[DatabaseName]); int32 i = sqlite3_open(dbNameAsUtf8, &db); if (i == SQLITE_OK){ int32 k = sqlite3_exec(db, TCHAR_TO_UTF8(*Query), NULL, 0, &zErrMsg); if (i == SQLITE_OK){ execStatus = true; } else { LOGSQLITE(Warning, TEXT("CreateTable - Query Exec Failed..")); } } else { LOGSQLITE(Warning, TEXT("CreateTable - DB Open failed..")); } sqlite3_close(db); return execStatus; }
void FXmppPresenceJingle::ConvertFromPresence(buzz::PresenceStatus& OutStatus, const FXmppUserPresence& InPresence) { OutStatus.set_available(InPresence.bIsAvailable); OutStatus.set_sent_time(TCHAR_TO_UTF8(*InPresence.SentTime.ToIso8601())); OutStatus.set_show(buzz::PresenceStatus::SHOW_OFFLINE); if (InPresence.bIsAvailable) { switch (InPresence.Status) { case EXmppPresenceStatus::Online: OutStatus.set_show(buzz::PresenceStatus::SHOW_ONLINE); break; case EXmppPresenceStatus::Offline: OutStatus.set_show(buzz::PresenceStatus::SHOW_OFFLINE); break; case EXmppPresenceStatus::Away: OutStatus.set_show(buzz::PresenceStatus::SHOW_AWAY); break; case EXmppPresenceStatus::ExtendedAway: OutStatus.set_show(buzz::PresenceStatus::SHOW_XA); break; case EXmppPresenceStatus::DoNotDisturb: OutStatus.set_show(buzz::PresenceStatus::SHOW_DND); break; case EXmppPresenceStatus::Chat: OutStatus.set_show(buzz::PresenceStatus::SHOW_CHAT); break; } } OutStatus.set_status(TCHAR_TO_UTF8(*InPresence.StatusStr)); }
/** * Downloads the save file from CloudyWeb. * * @param Filename Filename of the save game file. * @param PlayerControllerId Player controller ID of the player who requested the file. * * @return Returns true if the file download was successful. Else, returns false. * */ bool CloudyWebConnectorImpl::DownloadFile(FString Filename, int32 PlayerControllerId) { CURL *curl; FILE *fp; CURLcode res; errno_t err; std::string SaveFileURLCString; if (GetGameId() == -1 || GetUsername(PlayerControllerId).Equals("") || PlayerControllerId < 0 || SaveFileUrls.Num() <= PlayerControllerId) { UE_LOG(CloudyWebConnectorLog, Error, TEXT("The game ID, username, or player controller ID is invalid")); return false; } // Use the game id and username of the player to GET the save file URL from CloudyWeb // Then populate SaveFileUrls (TArray) GetSaveFileUrl(GetGameId(), GetUsername(PlayerControllerId), PlayerControllerId); // Read the URL from the SaveFileUrls TArray to download the file and write to disk FString* SaveFileUrlsData = SaveFileUrls.GetData(); if (!SaveFileUrlsData[PlayerControllerId].Equals("")) { UE_LOG(CloudyWebConnectorLog, Log, TEXT("File URL obtained! Writing to disk.")); SaveFileURLCString = TCHAR_TO_UTF8(*SaveFileUrlsData[PlayerControllerId]); // Filepath of .sav file FString Filepath = FPaths::GameDir(); Filepath += "Saved/SaveGames/" + Filename + "-" + FString::FromInt(PlayerControllerId) + ".sav"; std::string filePath(TCHAR_TO_UTF8(*Filepath)); curl = curl_easy_init(); if (curl) { if ((err = fopen_s(&fp, filePath.c_str(), "wb")) == 0) { curl_easy_setopt(curl, CURLOPT_URL, SaveFileURLCString.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } else { UE_LOG(CloudyWebConnectorLog, Error, TEXT("Could not create save file!")); } } return true; } else { UE_LOG(CloudyWebConnectorLog, Warning, TEXT("There was no save file URL!")); return false; } }
static PyObject *py_ue_edgraphpin_get_name(ue_PyEdGraphPin *self, void *closure) { #if ENGINE_MINOR_VERSION > 18 return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinName.ToString()))); #else return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinName))); #endif }
static PyObject *py_ue_edgraphpin_get_sub_category(ue_PyEdGraphPin *self, void *closure) { #if ENGINE_MINOR_VERSION > 18 return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinSubCategory.ToString()))); #else return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->pin->PinType.PinSubCategory))); #endif }
static PyObject *ue_PyEdGraphPin_str(ue_PyEdGraphPin *self) { return PyUnicode_FromFormat("<unreal_engine.EdGraphPin {'name': '%s', 'type': '%s'}>", #if ENGINE_MINOR_VERSION > 18 TCHAR_TO_UTF8(*self->pin->PinName.ToString()), TCHAR_TO_UTF8(*self->pin->PinType.PinCategory.ToString())); #else TCHAR_TO_UTF8(*self->pin->PinName), TCHAR_TO_UTF8(*self->pin->PinType.PinCategory)); #endif }
static PyObject *ue_PySWidget_str(ue_PySWidget *self) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("<unreal_engine.%s '%p' (slate ref count: %d, py ref count: %d)>", TCHAR_TO_UTF8(*self->Widget->GetTypeAsString()), &self->Widget.Get(), self->Widget.GetSharedReferenceCount(), self->ob_base.ob_refcnt); #else return PyUnicode_FromFormat("<unreal_engine.%s '%p' (slate ref count: %d)>", TCHAR_TO_UTF8(*self->Widget->GetTypeAsString()), &self->Widget.Get(), self->Widget.GetSharedReferenceCount()); #endif }
SpatialOSLocator FWorkerConnection::CreateLocator(const FString& ProjectName, const FString& LocatorHost, const FString& LoginToken) { worker::LocatorParameters LocatorParams; LocatorParams.ProjectName = TCHAR_TO_UTF8(*ProjectName); LocatorParams.CredentialsType = worker::LocatorCredentialsType::kLoginToken; LocatorParams.LoginToken = worker::LoginTokenCredentials{TCHAR_TO_UTF8(*LoginToken)}; return SpatialOSLocator{TCHAR_TO_UTF8(*LocatorHost), LocatorParams}; }
bool ULevelDBPluginBPLibrary::WriteStringToLevelDB(ULevelDBObject* DatabaseObject, FString Key, FString Value) { leveldb::WriteOptions writeOptions; if (DatabaseObject->db != NULL) DatabaseObject->db->Put(writeOptions, TCHAR_TO_UTF8(*Key), TCHAR_TO_UTF8(*Value)); else return false; return true; }
UTrackEntry* USpineSkeletonAnimationComponent::AddAnimation (int trackIndex, FString animationName, bool loop, float delay) { CheckState(); if (state && spSkeletonData_findAnimation(skeleton->data, TCHAR_TO_UTF8(*animationName))) { _spAnimationState_disableQueue(state); spTrackEntry* entry = spAnimationState_addAnimationByName(state, trackIndex, TCHAR_TO_UTF8(*animationName), loop ? 1 : 0, delay); _spAnimationState_enableQueue(state); UTrackEntry* uEntry = NewObject<UTrackEntry>(); uEntry->SetTrackEntry(entry); trackEntries.Add(uEntry); return uEntry; } else return NewObject<UTrackEntry>(); }
void ASmrActor::LoadAnimation(FString path) { if (path == "") { FString sourceDir = FPaths::GameSourceDir(); std::string stdSourceDir(TCHAR_TO_UTF8(*sourceDir)); std::string motionFilePath = stdSourceDir + "../SMR/data/bvh/benTest.bvh"; m_motion = loadMotionFromBVH(motionFilePath); return; } m_motion = loadMotionFromBVH(getFileName(std::string(TCHAR_TO_UTF8(*path)))); }
void USQLiteDatabase::PrepareStatement(const FString* DatabaseName, const FString* Query, sqlite3** Db, int32** SqlReturnCode, sqlite3_stmt** PreparedStatement) { ANSICHAR* dbNameAsUtf8 = TCHAR_TO_UTF8(*Databases[**DatabaseName]); int32 i = sqlite3_open(dbNameAsUtf8, Db); **SqlReturnCode = i; ANSICHAR* queryAsUtf8 = TCHAR_TO_UTF8(**Query); **SqlReturnCode = sqlite3_prepare_v2(*Db, queryAsUtf8, -1, PreparedStatement, NULL); }
spAnimationStateData* USpineSkeletonDataAsset::GetAnimationStateData(spAtlas* atlas) { if (!animationStateData) { spSkeletonData* skeletonData = GetSkeletonData(atlas, false); animationStateData = spAnimationStateData_create(skeletonData); } for (auto& data : MixData) { if (!data.From.IsEmpty() && !data.To.IsEmpty()) { const char* fromChar = TCHAR_TO_UTF8(*data.From); const char* toChar = TCHAR_TO_UTF8(*data.To); spAnimationStateData_setMixByName(animationStateData, fromChar, toChar, data.Mix); } } animationStateData->defaultMix = DefaultMix; return this->animationStateData; }
void FWorkerConnection::SendLogMessage(ELogVerbosity::Type Level, const FString& Message) { auto WorkerLogLevel = worker::LogLevel::kInfo; switch (Level) { case ELogVerbosity::Fatal: WorkerLogLevel = worker::LogLevel::kFatal; break; case ELogVerbosity::Error: WorkerLogLevel = worker::LogLevel::kError; break; case ELogVerbosity::Warning: WorkerLogLevel = worker::LogLevel::kWarn; break; case ELogVerbosity::Display: WorkerLogLevel = worker::LogLevel::kInfo; break; case ELogVerbosity::Log: WorkerLogLevel = worker::LogLevel::kInfo; break; case ELogVerbosity::Verbose: WorkerLogLevel = worker::LogLevel::kDebug; break; case ELogVerbosity::VeryVerbose: WorkerLogLevel = worker::LogLevel::kDebug; break; default: break; } Connection->SendLogMessage(WorkerLogLevel, kLoggerName, TCHAR_TO_UTF8(*Message)); }
void UWebsocketClient_impl::Connect(const FString& RemoteLocation, const int32 Port) { if (bIsConnected || bIsConnecting) return; bIsConnecting = true; if (Port > 0 && !RemoteLocation.IsEmpty()) { auto ip = RemoteLocation.Replace(UTF8_TO_TCHAR("ws://"), UTF8_TO_TCHAR("")); auto url = std::string(TCHAR_TO_UTF8( *FString("ws://" + ip + ":" + FString::FromInt(Port)) )); try { m_WebsocketClient.init_asio(); websocketpp::lib::error_code errorCode; m_WebsocketClient.clear_access_channels(websocketpp::log::alevel::all); m_WebsocketClient.clear_error_channels(websocketpp::log::elevel::all); m_WebsocketClient.set_open_handler(bind(&UWebsocketClient_impl::OnWebsocketConnected, this, ::_1)); m_WebsocketClient.set_close_handler(bind(&UWebsocketClient_impl::OnWebsocketConnectionClosed, this, ::_1)); m_WebsocketClient.set_message_handler(bind(&UWebsocketClient_impl::OnMessageReceived, this, ::_1, ::_2)); auto connection = m_WebsocketClient.get_connection(url, errorCode); m_Connection = m_WebsocketClient.get_con_from_hdl(connection); m_WebsocketClient.connect(connection); } catch (std::exception&) {} // just swallow the errors for now } }
bool CreatureCore::LoadDataPacket(const std::string& filename_in, FString* pSourceData) { ////////////////////////////////////////////////////////////////////////// //直接从Data中载入 if (pSourceData == nullptr) { return false; } if (global_load_data_packets.count(filename_in) > 0) { // file already loaded, just return return true; } else { if (pSourceData->Len() == 0) { return false; } std::shared_ptr<CreatureModule::CreatureLoadDataPacket> new_packet = std::make_shared<CreatureModule::CreatureLoadDataPacket>(); CreatureModule::LoadCreatureJSONDataFromString(std::string(TCHAR_TO_UTF8(*(*pSourceData))), *new_packet); global_load_data_packets[filename_in] = new_packet; } return true; }
void FDirectoryWatchRequestLinux::WatchDirectoryTree(const FString & RootAbsolutePath) { UE_LOG(LogDirectoryWatcher, VeryVerbose, TEXT("Watching tree '%s'"), *RootAbsolutePath); TArray<FString> AllFiles; if (bWatchSubtree) { IFileManager::Get().FindFilesRecursive(AllFiles, *RootAbsolutePath, TEXT("*"), false, true); } // add the path as well AllFiles.Add(RootAbsolutePath); for (int32 FileIdx = 0, NumTotal = AllFiles.Num(); FileIdx < NumTotal; ++FileIdx) { const FString& FolderName = AllFiles[FileIdx]; checkf(PathsToWatchDescriptors.Find(FolderName) == nullptr, TEXT("Adding a duplicate watch for directory '%s'"), *FolderName); int32 WatchDescriptor = inotify_add_watch(FileDescriptor, TCHAR_TO_UTF8(*FolderName), NotifyFilter); if (WatchDescriptor == -1) { int ErrNo = errno; UE_LOG(LogDirectoryWatcher, Error, TEXT("inotify_add_watch cannot watch folder %s (errno = %d, %s)"), *FolderName, ErrNo, ANSI_TO_TCHAR(strerror(ErrNo)) ); // proceed further } UE_LOG(LogDirectoryWatcher, VeryVerbose, TEXT("+ Added a watch %d for '%s'"), WatchDescriptor, *FolderName); // update the mapping WatchDescriptorsToPaths.Add(WatchDescriptor, FolderName); PathsToWatchDescriptors.Add(FolderName, WatchDescriptor); } }
void ATotemCharacter::ShotUpMetrics_Implementation() { #if WRITE_METRICS if (Cast<AFireShaman>(this)) { ATotemPlayerController* control = Cast<ATotemPlayerController>(Controller); if (control) { ATotemPlayerState* state = Cast<ATotemPlayerState>(control->PlayerState); if (state) { std::string team; switch (state->Team) { case ETeam::RED_TEAM: team = "Red"; break; case ETeam::BLUE_TEAM: team = "Blue"; break; default: team = "None"; break; } Metrics::WriteToFile(std::string(TCHAR_TO_UTF8(*(state->MyName))), team, std::string("Flamethrower end")); } } } #endif }
float UFMODAudioComponent::GetParameter(FName Name) { float Value = 0.0f; float* StoredParam = StoredParameters.Find(Name); if (StoredParam) { Value = *StoredParam; } if (StudioInstance) { FMOD::Studio::ParameterInstance* ParamInst = nullptr; FMOD_RESULT Result = StudioInstance->getParameter(TCHAR_TO_UTF8(*Name.ToString()), &ParamInst); if (Result == FMOD_OK) { float QueryValue; Result = ParamInst->getValue(&QueryValue); if (Result == FMOD_OK) { Value = QueryValue; } } if (Result != FMOD_OK) { UE_LOG(LogFMOD, Warning, TEXT("Failed to get parameter %s"), *Name.ToString()); } } return Value; }
void UHeliosGetterProxy_Float::OnHeliosRequestComplete(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded) { if (!bSucceeded) { UE_LOG(LogTemp, Error, TEXT("Helios > request failed: %s"), *HttpRequest->GetURL()); OnFail.Broadcast(0); return; } if (!HttpResponse.IsValid()) { UE_LOG(LogTemp, Warning, TEXT("Helios > invalid response for request: %s"), *HttpRequest->GetURL()); OnFail.Broadcast(0); return; } FString ContentAsString = HttpResponse->GetContentAsString(); json Content = json::parse(TCHAR_TO_UTF8(*ContentAsString)); if (Content.size() != 1) { UE_LOG(LogTemp, Warning, TEXT("Helios > invalid json returned")); OnFail.Broadcast(0); return; } if (!Content["value"].is_number_float()) { UE_LOG(LogTemp, Warning, TEXT("Helios > invalid type returned")); OnFail.Broadcast(0); return; } float Result = Content["value"]; OnSuccess.Broadcast(Result); }
PyObject *py_ue_get_actor_label(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (self->ue_object->IsA<AActor>()) { AActor *actor = (AActor *)self->ue_object; return PyUnicode_FromString(TCHAR_TO_UTF8(*(actor->GetActorLabel()))); } if (self->ue_object->IsA<UActorComponent>()) { UActorComponent *component = (UActorComponent *)self->ue_object; return PyUnicode_FromString(TCHAR_TO_UTF8(*(component->GetOwner()->GetActorLabel()))); } return PyErr_Format(PyExc_Exception, "uobject is not an actor or a component"); }
bool ULevelDBPluginBPLibrary::WriteObjectToLevelDB(ULevelDBObject* DatabaseObject, FString Key, UObject* Value) { if (IsValid(Value)) { //Vars TArray<uint8> ObjectBytes; FMemoryWriter MemoryWriter(ObjectBytes, true); //Write Object Class name so we can deserialize it one day FString ObjectClassName = Value->GetClass()->GetName(); MemoryWriter << ObjectClassName; //Serialize Object and put into the byte array as well FObjectAndNameAsStringProxyArchive Ar(MemoryWriter, false); Value->Serialize(Ar); //marshall pointer to first array entry auto ptr = reinterpret_cast<const char*>(ObjectBytes.GetData()); //level db options leveldb::WriteOptions writeOptions; //create a slice to store leveldb::Slice data = leveldb::Slice(ptr, ObjectBytes.Num()); //Smash it into the db if (DatabaseObject->db != NULL) DatabaseObject->db->Put(writeOptions, TCHAR_TO_UTF8(*Key), data); else return false; return true; } return false; }
void APing::StartServer(const int listeningPort = 8888, const FString& responseString = "") { server = RakNet::RakPeerInterface::GetInstance(); int i = server->GetNumberOfAddresses(); char* charString = TCHAR_TO_UTF8(*responseString); //char* charString = TCHAR_TO_UTF8((L"")); UE_LOG(RakNet_Ping, Log, TEXT("Server response string length: %d"), strlen(charString)); UE_LOG(RakNet_Ping, Log, TEXT("Server response string: %s"), *FString(UTF8_TO_TCHAR(charString))); //char* charString = TCHAR_TO_ANSI(L"abc123"); //char enumData[512] = TCHAR_TO_ANSI(L"abc123中文字串あいうえお"); //char enumData[512] = "abc123"; server->SetOfflinePingResponse(charString, (const unsigned int)strlen(charString) + 1); // The server has to be started to respond to pings. RakNet::SocketDescriptor socketDescriptor(listeningPort, 0); bool b = server->Startup(2, &socketDescriptor, 1) == RakNet::RAKNET_STARTED; server->SetMaximumIncomingConnections(2); if (b) { UE_LOG(RakNet_Ping, Log, TEXT("Server started, waiting for connections.")); } else { UE_LOG(RakNet_Ping, Error, TEXT("Server start failed!")); } }
bool FSpeechRecognitionWorker::Init() { std::string modelPath = contentPath_str + "model/" + langStr + "/" + langStr; std::string languageModel = contentPath_str + "model/" + langStr + "/" + langStr + ".lm.bin"; std::string dictionaryPath = contentPath_str + "model/" + langStr + "/" + langStr + ".dict"; // load dictionary dictionaryMap.clear(); std::ifstream file(dictionaryPath); std::vector<std::string> words; std::string currentLine; while (file.good()) { std::getline(file, currentLine); std::string word = currentLine.substr(0, currentLine.find(" ")); std::string phrase = currentLine.substr(currentLine.find(" ") + 1, currentLine.size()); dictionaryMap.insert(make_pair(word, phrase)); } // Start Sphinx config = cmd_ln_init(NULL, ps_args(), 1, "-hmm", modelPath.c_str(), "-lm", languageModel.c_str(), NULL); ps = ps_init(config); if (!Manager | !ps) { ClientMessage(FString(TEXT("Speech Recognition Thread failed to start"))); initSuccess = false; return false; } // only include the words/phrases that have been added for (auto It = dictionaryList.CreateConstIterator(); It; ++It) { FString word = *It; std::string wordStr = std::string(TCHAR_TO_UTF8(*word)); if (dictionaryMap.find(wordStr) != dictionaryMap.end()) { std::string phraseStr = dictionaryMap.at(wordStr); ps_add_word(ps, wordStr.c_str(), phraseStr.c_str(), TRUE); } } // attempt to open the default recording device if ((ad = ad_open_dev(cmd_ln_str_r(config, "-adcdev"), (int)cmd_ln_float32_r(config, "-samprate"))) == NULL) { ClientMessage(FString(TEXT("Failed to open audio device"))); initSuccess = false; return initSuccess; } utt_started = 0; return true; }
PyObject *py_unreal_engine_get_engine_defined_action_mappings(PyObject * self, PyObject * args) { PyObject *py_list = PyList_New(0); TArray<FInputActionKeyMapping> mappings = UPlayerInput::GetEngineDefinedActionMappings(); for (FInputActionKeyMapping mapping : mappings) { PyObject *py_mapping = PyDict_New(); PyDict_SetItemString(py_mapping, (char *)"action_name", PyUnicode_FromString(TCHAR_TO_UTF8(*mapping.ActionName.ToString()))); PyDict_SetItemString(py_mapping, (char *)"key", PyUnicode_FromString(TCHAR_TO_UTF8(*mapping.Key.ToString()))); PyDict_SetItemString(py_mapping, (char *)"alt", mapping.bAlt ? Py_True : Py_False); PyDict_SetItemString(py_mapping, (char *)"cmd", mapping.bCmd ? Py_True : Py_False); PyDict_SetItemString(py_mapping, (char *)"ctrl", mapping.bCtrl ? Py_True : Py_False); PyDict_SetItemString(py_mapping, (char *)"shift", mapping.bShift ? Py_True : Py_False); PyList_Append(py_list, py_mapping); } return py_list; }