void* TDocument::Streamer::Read(ipstream& is, uint32 /*version*/) const { TDocument* o = GetObject(); o->NextDoc = 0; o->StreamList = 0; o->DocManager = 0; o->DirtyFlag = false; is >> o->OpenMode; #if defined(UNICODE) _USES_CONVERSION; char * docPath = is.freadString(); char * title = is.freadString(); o->DocPath = _A2W(docPath); o->Title = _A2W(title); delete[] docPath; delete[] title; #else o->DocPath = is.freadString(); o->Title = is.freadString(); #endif is >> o->Template; // static templates must have been already streamed is >> o->ParentDoc; o->ViewList = 0; // must init, does not get set until after view streamed is >> o->ViewList; is >> TView::NextViewId; // static, but must get set by at least 1 document return o; }
bool CScriptEngine::Initialize() { // register custom memory management //asSetGlobalMemoryFunctions() m_vm = asCreateScriptEngine(ANGELSCRIPT_VERSION); m_vm->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true); // treat 'a' as character literal of type uint8 if( m_vm == 0 ) { CON( MSG_ERR, _W("Failed to create script engine!") ); return false; } // set compiler message callback m_vm->SetMessageCallback(asFUNCTION(ScriptMessageCallback), 0, asCALL_CDECL); // write version info CON( MSG_INFO, _W(" AngelScript version %s successfuly initialized."), _A2W( asGetLibraryVersion() ) ); CON( MSG_INFO, _W(" Build flags: %s"), _A2W( asGetLibraryOptions() ) ); // register basic types RegisterBasicTypesToScript(m_vm); // Script UnitTest LoadScriptString(\ "void UnitTest()\n"\ "{\n"\ "Log(\"--- Script engine unit test ---\");\n"\ "\n"\ "Log( \"String comparison: \" + ( (\"str\"==\"str\") ? \"OK\" : \"ERROR\" ) );\n"\ "\n"\ "String float2str = 0.123f;\n"\ "Log(\"Float-to-String: \" + float2str);\n"\ "String strTrue = true; String strFalse = false;\n"\ "Log(\"Bool-to-String: \" + ( (strTrue == \"True\") && (strFalse == \"False\") ? \"OK\" : \"ERROR\" ) );\n"\ "Log(\"String index operator: \" + ( (\"str\"[2]=='r') ? \"OK\" : \"ERROR\") );\n"\ "Log(\"String length(): \" + ( (\"str\".length()==3) ? \"OK\" : \"ERROR\") );\n"\ "\n"\ "float f = 0.123f;\n"\ "float f2 = sin(f);\n"\ "Log(\"sin(\" + f + \") = \" + f2 );\n"\ "\n"\ "Log(\"rand(0.1f, 0.7f) = \" + rand(0.1f, 0.7f) );\n"\ "}\n"\ ,0,"UnitTestSection"); ExecuteString("UnitTest();"); return true; }
//************************************************************************ // Init // // Called after Miranda has finished loading all modules // This is where the main plugin initialization happens and the // connection to the LCD is established, //************************************************************************ int Init(WPARAM, LPARAM) { g_AppletManager = new CAppletManager(); // Memoryleak Detection #ifdef _DEBUG _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif // set up the LCD context as non-autostart, non-persist, callbacked CConfig::Initialize(); // Initialize the output object if(!g_AppletManager->Initialize(toTstring(APP_SHORTNAME))) { if(CConfig::GetBoolSetting(SKIP_DRIVER_ERROR)) { tstring text = L"Failed to initialize the LCD connection\n Make sure you have the newest Logitech drivers installed (>=1.03).\n"; tstring title = _A2W(APP_SHORTNAME); MessageBox(nullptr, text.c_str(), title.c_str(), MB_OK | MB_ICONEXCLAMATION); } TRACE(L"Initialization failed!.\n"); return 0; } g_bInitialized = true; TRACE(L"Initialization completed successfully.\n-------------------------------------------\n"); return 0; }
void ShowError(wchar_t *msg) { wchar_t buffer[512]; ErrorDisplay disp = options.err_method; // funny logic :) ... try to avoid message boxes // if want popups but no popups, try baloons if(disp == ED_POP && !options.bHavePopups) disp = ED_BAL; mir_snwprintf(buffer, L"%s Error", _A2W(MODULENAME)); wchar_t *message; switch (disp) { case ED_POP: { int size = int(mir_wstrlen(msg) + 515); message = new wchar_t[size]; // newline and null terminator mir_snwprintf(message, size, L"%s\r\n%s", buffer, msg); PUShowMessageT(message, SM_WARNING); delete[] message; } break; case ED_MB: MessageBox(nullptr, msg, buffer, MB_OK | MB_ICONERROR); break; case ED_BAL: Clist_TrayNotifyW(MODULENAME, buffer, msg, NIIF_ERROR, 10000); break; } }
//--------------------------------------------------------------------------- bool CFS_Sqlite::Initialize(void* pEngine) { int ret=0; CON(MSG_INFO, _W("Database filesystem sqlite %s:"), _A2W(sqlite3_version) ); if (!sqlite3_threadsafe()) { CON(MSG_ERR, _W("... not compiled thread-safe - will not be used!")); return false; } CON(MSG_INFO, _W("... setting multithread configuration")); sqlite3_config(SQLITE_CONFIG_MULTITHREAD); ret = sqlite3_initialize(); if (ret == SQLITE_OK) CON(MSG_INFO, _W("... successfuly initialized")); else { CON(MSG_ERR, _W("... error code %d returned - will not be used!"), ret); return false; } return true; }
tstring TXOwl::MakeMessage(uint resId, LPCSTR infoStr, TModule* module) { _USES_CONVERSION; tstring rscMsg = ResourceIdToString(0, resId, module); tchar buf[255]; _stprintf(buf, rscMsg.c_str(), _A2W(infoStr)); return tstring(buf); }
// /// Returns the total number of properties for this document, where index is the /// property index, dest contains the property data, and textlen is the size of the /// array. If textlen is 0, property data is returned as binary data; otherwise, /// property data is returned as text data. // int TDocument::GetProperty(int prop, void * dest, int textlen) { LPCTSTR src; tchar numBuf[15]; switch (prop) { case DocumentClass: { _USES_CONVERSION; src = _A2W(_OBJ_FULLTYPENAME(this)); } break; case TemplateName: src = Template ? Template->GetDescription() : 0; break; case ViewCount: { int cnt; TView* view; for (view=ViewList, cnt=0; view != 0; view=view->NextView, cnt++) ; // Do nothing if (!textlen) { *(int *)dest = cnt; return sizeof(int); } wsprintf(numBuf, _T("%d"), cnt); src = numBuf; break; } case StoragePath: src = DocPath; break; case DocTitle: src = Title; break; default: TRACEX(OwlDocView, 0, _T("GetProperty(): invalid property [") << prop << _T("] specified!") ); return 0; } if (!textlen) { TRACEX(OwlDocView, 0, _T("GetProperty(): 0-Length buffer specified!")); return 0; } int srclen = src ? static_cast<int>(::_tcslen(src)) : 0; if (textlen > srclen) textlen = srclen; if (textlen) memcpy(dest, src, textlen*sizeof(tchar)); *((LPTSTR)dest + textlen) = 0; return srclen; }
// TODO: if clicking on error message is not working within VisualStudio, // make second version using #ifdef _DEBUG && MSVC with OutputDebugString // or remove : from the begining of line void ScriptMessageCallback(const asSMessageInfo *msg, void *param) { const wchar *type = _W("ERR "); if( msg->type == asMSGTYPE_WARNING ) type = _W("WARN"); else if( msg->type == asMSGTYPE_INFORMATION ) type = _W("INFO"); CON(MSG_INFO, _W(": %s (%d, %d) : %s : %s\n"), _A2W(msg->section), msg->row, msg->col, type, _A2W(msg->message) ); }
void ShowMessageInline(const MCONTACT hContact, const wchar_t *msg) { wchar_t buff[1024]; mir_snwprintf(buff, L"%s%s", _A2W(LANG_INLINE_PREFIX), msg); T2Utf utf(buff); PROTORECVEVENT pre = {0}; pre.timestamp = time(0); pre.szMessage = utf; pre.flags = PREF_BYPASS_OTR; ProtoChainRecvMsg(hContact, &pre); }
static VOID NTAPI ShowContactMenu(ULONG_PTR wParam) // wParam = hContact { POINT pt; HWND hMenuWnd = CreateWindowEx(WS_EX_TOOLWINDOW, L"static", _A2W(MODULENAME) L"_MenuWindow", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP, nullptr, g_plugin.getInst(), nullptr); SetWindowLongPtr(hMenuWnd, GWLP_WNDPROC, (LONG_PTR)MenuWndProc); HMENU hMenu = Menu_BuildContactMenu(wParam); GetCursorPos(&pt); SetForegroundWindow(hMenuWnd); Clist_MenuProcessCommand(TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, hMenuWnd, nullptr), MPCF_CONTACTMENU, wParam); PostMessage(hMenuWnd, WM_NULL, 0, 0); DestroyMenu(hMenu); DestroyWindow(hMenuWnd); }
//呼びかけを設定します。 //設定したあと、 CommitRule() てしてね。 xreturn::r<bool> Recognition_SAPI::SetYobikake(const std::list<std::string> & yobikakeList) { _USE_WINDOWS_ENCODING; HRESULT hr; this->RuleGrammar->ClearRule(this->YobikakeRuleHandle); this->DictationGrammar->ClearRule(this->FilterRuleHandleHandle); // this->DictationGrammar->ClearRule(this->FilterRuleHandleHandle2); SPSTATEHANDLE appendState; //あとに続くを表現するためには、 新規にステートを作らないといけない。 hr = this->RuleGrammar->CreateNewState(this->YobikakeRuleHandle, &appendState); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->AddRuleTransition(appendState , NULL, this->CommandRuleHandle , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); this->YobikakeListArray = yobikakeList; for(auto it = this->YobikakeListArray.begin(); this->YobikakeListArray.end() != it ; ++it) { //ふつー使う呼びかけ hr = this->RuleGrammar->AddWordTransition(this->YobikakeRuleHandle , appendState , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); //ディクテーションフィルターの呼びかけ // hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle , NULL , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 1.0f , NULL ); hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle , NULL , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle2 , NULL , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 2.0f , NULL ); // if(FAILED(hr)) return xreturn::windowsError(hr); } //ディクテーションフィルター その1はディクテーションノードを加える // hr = this->DictationGrammar->AddRuleTransition(this->FilterRuleHandleHandle, NULL, SPRULETRANS_DICTATION, 1.0f, NULL); // if(FAILED(hr)) return xreturn::windowsError(hr); //ディクテーションフィルター その2はあ-んを加える. { wchar_t word[2]; word[0] = L'あ'; word[1] = 0; for(; word[0] < L'ん' ; word[0] ++ ) { hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle , NULL , word , L" " , SPWT_LEXICAL , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); } } //ルールに変更が加わったのでコミットしないといけません。 this->IsNeedUpdateRule = true; return true; }
int ModernSkinButtonLoadModule() { WNDCLASSEX wc; memset(&wc, 0, sizeof(wc)); wc.cbSize = sizeof(wc); wc.lpszClassName = _A2W(MODERNSKINBUTTONCLASS); wc.lpfnWndProc = ModernSkinButtonWndProc; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.cbWndExtra = sizeof(ModernSkinButtonCtrl*); wc.hbrBackground = nullptr; wc.style = CS_GLOBALCLASS; RegisterClassEx(&wc); ModernSkinButtonModuleIsLoaded = TRUE; return 0; }
void wiki2engConvert(const std::string& filename) { FILE * fp = NULL; fp = fopen(filename.c_str() , "rb"); if (!fp) { fwprintf(stderr,L"can not open %ls file\n" , _A2W(filename).c_str() ); return ; } AutoClear ac([&](){ fclose(fp); }); ReadAllForEng(fp); }
static HWND ModernSkinButtonCreateWindow(ModernSkinButtonCtrl * bct, HWND parent) { HWND hwnd; if (bct == nullptr) return FALSE; { wchar_t *UnicodeID = mir_a2u(bct->ID); hwnd = CreateWindow(_A2W(MODERNSKINBUTTONCLASS), UnicodeID, WS_VISIBLE | WS_CHILD, bct->Left, bct->Top, bct->Right - bct->Left, bct->Bottom - bct->Top, parent, nullptr, g_plugin.getInst(), nullptr); mir_free(UnicodeID); } bct->hwnd = hwnd; bct->focus = 0; SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)bct); return hwnd; }
bool CSoundEngine::Initialize(void *pEngine) { if (m_bInit) return false; m_bInit = true; s_pEngine = (IEngine*)pEngine; // memory leaks detection #if defined(_DEBUG) && defined(_MSC_VER) && _MSC_VER >= 800 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(76); #endif CON(MSG_INFO, _W("= Sound Device initialization =")); m_device = alcOpenDevice(NULL); if(!m_device) { CON(MSG_ERR_FATAL, _W(" Can't initialize OpenAL! Please try to reinstall OpenAL libraries...")); return false; } m_extensions = new COALExtProvider(); if(m_extensions == NULL) { CON(MSG_INFO, _W(" Can't create OpenAL Extension provider instance!")); m_context = alcCreateContext(m_device, NULL); if(m_context != NULL) alcMakeContextCurrent(m_context); } else m_extensions->Create(m_device, m_context); if(m_context == NULL) { CON(MSG_ERR_FATAL, _W(" Can't create OpenAL context!")); return false; } if (!cSoundManager()->Create(m_extensions)) CON(MSG_ERR_FATAL, _W(" Can't create Sound Manager!")); CON(MSG_INFO, _W(" ...using OpenAL version %s"), _A2W(alGetString(AL_VERSION)) ); return true; }
//構築したルールを音声認識エンジンにコミットします。 xreturn::r<bool> Recognition_SAPI::CommitRule() { if (! this->IsNeedUpdateRule ) {//アップデートする必要なし this->PoolMainWindow->SyncInvokeLog("音声認識ルールコミットが呼ばれましたが変更がないので無視します。",LOG_LEVEL_DEBUG); return true; } _USE_WINDOWS_ENCODING; HRESULT hr; hr = this->RuleGrammar->SetRuleState(NULL, NULL, SPRS_INACTIVE ); if(FAILED(hr)) return xreturn::windowsError(hr); //通常ルールのコミット hr = this->RuleGrammar->Commit(0); if(FAILED(hr)) return xreturn::windowsError(hr); //ディクテーションフィルターのコミット hr = this->DictationGrammar->Commit(0); if(FAILED(hr)) return xreturn::windowsError(hr); ///これを入れるとキューが詰まる時があるような。(経験則) /// hr = this->RuleEngine->SetRecoState(SPRST_ACTIVE); /// if(FAILED(hr)) return xreturn::windowsError(hr); if (this->TemporaryRuleCount >= 1) { hr = this->RuleGrammar->SetRuleState(NULL, NULL, SPRS_ACTIVE ); if(FAILED(hr)) return xreturn::windowsError(hr); this->PoolMainWindow->SyncInvokeLog("音声認識ルールコミット:テンポラリルールも含めて commit します",LOG_LEVEL_DEBUG); } else { // hr = this->RuleGrammar->SetRuleState(_A2W("BasicRule"),NULL,SPRS_ACTIVE); hr = this->RuleGrammar->SetRuleState(_A2W("YobikakeRule"),NULL,SPRS_ACTIVE); if(FAILED(hr)) return xreturn::windowsError(hr); this->PoolMainWindow->SyncInvokeLog("音声認識ルールコミット:YobikakeRule以下を commit します",LOG_LEVEL_DEBUG); } //アップデートが終わったので再びルールに変更が加わるまではアップデートしない。 this->IsNeedUpdateRule = false; return true; }
void ShowPopup(const wchar_t* line1, const wchar_t* line2, int timeout, const MCONTACT hContact) { if(Miranda_IsTerminated()) return; if ( !options.bHavePopups) { wchar_t title[256]; mir_snwprintf(title, L"%s Message", _A2W(MODULENAME)); if(line1 && line2) { int size = int(mir_wstrlen(line1) + mir_wstrlen(line2) + 3); wchar_t *message = new wchar_t[size]; // newline and null terminator mir_snwprintf(message, size, L"%s\r\n%s", line1, line2); MessageBox( nullptr, message, title, MB_OK | MB_ICONINFORMATION ); delete[] message; } else if(line1) { MessageBox( nullptr, line1, title, MB_OK | MB_ICONINFORMATION ); } else if(line2) { MessageBox( nullptr, line2, title, MB_OK | MB_ICONINFORMATION ); } return; } POPUPDATAT ppd = {0}; //memset((void *)&ppd, 0, sizeof(POPUPDATAT)); ppd.lchContact = hContact; ppd.lchIcon = nullptr; if(line1 && line2) { wcsncpy( ppd.lptzContactName, line1, MAX_CONTACTNAME-1 ); wcsncpy( ppd.lptzText, line2, MAX_SECONDLINE-1 ); } else if(line1) wcsncpy( ppd.lptzText, line1, MAX_SECONDLINE-1 ); else if(line2) wcsncpy( ppd.lptzText, line2, MAX_SECONDLINE-1 ); ppd.iSeconds = timeout; ppd.PluginWindowProc = nullptr; ppd.PluginData = nullptr; PUAddPopupT(&ppd); }
STDMETHOD(Open)(THIS_ D3D10_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) { char *pData = NULL; ULONG fsize; wchar realfilename[512]; wsprintf(realfilename, 511, _W("shaders/%s"), _A2W(pFileName)); fp = pFS->Load(realfilename, (BYTE *&)pData, fsize, true); if(!fp) return E_FAIL; char *odata = new char[fsize]; memcpy(odata, pData, fsize); //output *ppData = odata; *pBytes = fsize; //clean up pFS->UnLoad(fp, (BYTE *)pData); fp = NULL; return S_OK; }
// // reads an instance of TEditFile from the passed ipstream // void* TEditFile::Streamer::Read(ipstream& is, uint32 /*version*/) const { TEditFile* o = GetObject(); ReadBaseObject((TEditSearch*)o, is); #if defined(UNICODE) _USES_CONVERSION; char * fileName = is.freadString(); o->FileName = _A2W(fileName); delete[] fileName; #else o->FileName = is.freadString(); #endif if (!*o->FileName) { delete o->FileName; o->FileName = 0; } return o; }
//デバッグ用 認識結果をWaveファイルとして保存する xreturn::r<bool> Recognition_SAPI::DebugSaveWavFile(const std::string& directory,ISpStreamFormat* streamFormat) const { HRESULT hr; _USE_WINDOWS_ENCODING; const SPSTREAMFORMAT spFormat = SPSF_22kHz8BitMono; CSpStreamFormat Fmt( spFormat, &hr); if(FAILED(hr)) return xreturn::windowsError(hr); { CSpStreamFormat OriginalFmt; { OriginalFmt.AssignFormat(streamFormat); // basic SAPI-stream for file-based storage CComPtr<ISpStream> cpStream; { ULONG cbWritten = 0; // create file on hard-disk for storing recognized audio, and specify audio format as the retained audio format std::string fff = directory + "\\" + num2str(time(NULL))+".wav"; hr = SPBindToFile(_A2W(fff.c_str()) , SPFM_CREATE_ALWAYS, &cpStream, &OriginalFmt.FormatId(), OriginalFmt.WaveFormatExPtr(), SPFEI_ALL_EVENTS); if(FAILED(hr)) return xreturn::windowsError(hr); // Continuously transfer data between the two streams until no more data is found (i.e. end of stream) // Note only transfer 1000 bytes at a time to creating large chunks of data at one time while (TRUE) { // for logging purposes, the app can retrieve the recognized audio stream length in bytes STATSTG stats; hr = streamFormat->Stat(&stats, NULL); if(FAILED(hr)) return xreturn::windowsError(hr); // create a 1000-byte buffer for transferring BYTE bBuffer[1000]; ULONG cbRead; // request 1000 bytes of data from the input stream hr = streamFormat->Read(bBuffer, 1000, &cbRead); // if data was returned?? if (SUCCEEDED(hr) && cbRead > 0) { // then transfer/write the audio to the file-based stream hr = cpStream->Write(bBuffer, cbRead, &cbWritten); if(FAILED(hr)) return xreturn::windowsError(hr); } // since there is no more data being added to the input stream, if the read request returned less than expected, the end of stream was reached, so break data transfer loop if (cbRead < 1000) { break; } } } // explicitly close the file-based stream to flush file data and allow app to immediately use the file hr = cpStream->Close(); if(FAILED(hr)) return xreturn::windowsError(hr); } } return true; }
//音声認識ルールを構築します。 正規表現にも対応しています。 xreturn::r<bool> Recognition_SAPI::AddRegexp(unsigned int id,const std::string & str ,SPSTATEHANDLE stateHandle ) { _USE_WINDOWS_ENCODING; //ルールに変更が加わるのでアップデートするフラグを立てる。 this->IsNeedUpdateRule = true; //一番最初だけ正規表現の構文変換をかける. // .+ --> (:?.*) // (まる|さんかく)? --> (まる|さんかく|) 正しい正規表現としてはエラーだが、このエンジンの場合容認する. // なのは? --> なの(は|) std::wstring optstr = L""; for( const wchar_t * p = _A2W( str.c_str() ) ; *p ; ++p ) { if ( *p == L'.' && *(p+1) == L'+') { // .+ --> (:?.*) optstr += L"(?:.+)"; ++p; } else if (*p == L'(' && *(p+1) == L'?' && *(p+2) == L':' ) { optstr += L"(?:"; p+=2; } else if (*(p+1) == L'?') { if (*p == L')') {// (まる|さんかく)? --> (まる|さんかく|) optstr += L"|)"; } else {// なのは? --> なの(は|) optstr += std::wstring(L"") + L"(?:" + *p + L"|)"; } ++p; } else if ( *p == L'[' && *(p+1) == L':' ) { const wchar_t * end = wcsstr(p+2 , L":]"); if (end == NULL) { return xreturn::error("[: があるのに :] がありませんでした"); } optstr += std::wstring(p , (end - p) + 2); p = end + 1; } else if (*p == L'*' || *p == L'+' || *p == L'.' || *p == L'[' || *p == L']') { return xreturn::error(std::string("") + "現在は、メタ文字 " + _W2A(p) + " は利用できません。利用可能なメタ文字 () | .+ ?)"); } else { optstr += *p; } } this->LocalCaptureRuleNodeCount = 1; if (id == UINT_MAX) { return AddRegexpImpl(NULL,optstr, stateHandle); } else { SPPROPERTYINFO prop; prop.pszName = L"Id"; prop.pszValue = L"Property"; prop.vValue.vt = VT_UINT; prop.vValue.ulVal = id; return AddRegexpImpl(&prop,optstr, stateHandle); } }
bool CShaderHLSL::Create(P3D::sShaderDesc &desc) { const char *pData; ULONG fsize; IFileSystem* pFS = CRenderer::mEngine()->mFilesystem(); wchar path[P3DMAX_PATH]; wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get()); FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true); if (!fp) { CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get()); return false; } ID3D10Blob *pShaderBlob = NULL; ID3D10Blob *pErrors = NULL; UINT flags = D3D10_SHADER_DEBUG; //D3D10_SHADER_OPTIMIZATION_LEVEL3 char profile[128]; switch(desc.ShaderType) { case SHADERTYPE_VERTEX_SHADER: strcpy(profile, D3D10GetVertexShaderProfile(g_pD3ddev)); break; case SHADERTYPE_GEOMETRY_SHADER: strcpy(profile, D3D10GetGeometryShaderProfile(g_pD3ddev)); break; case SHADERTYPE_PIXEL_SHADER: strcpy(profile, D3D10GetPixelShaderProfile(g_pD3ddev)); break; default: CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given.")); return false; } CIncludeHandler includeHandler; D3D10_SHADER_MACRO Shader_Macros[] = { { "DX10", NULL }, { "SM4", NULL }, NULL }; if(!CheckHRResult(D3DX10CompileFromMemory( pData, fsize, NULL, Shader_Macros, &includeHandler, _W2A(desc.EntryFunction.Get()), profile, flags, 0, NULL, &pShaderBlob, &pErrors, NULL ))) { if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer())); else CON(MSG_ERR, _W("Error description not given")); CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get()); SAFE_RELEASE(pErrors); return false; } pFS->UnLoad(fp, (BYTE *)pData); //save to cache fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb")); const char* cs = (const char*)pShaderBlob->GetBufferPointer(); pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp); pFS->Close(fp); bool shaderCreated = false; switch(desc.ShaderType) { case SHADERTYPE_VERTEX_SHADER: shaderCreated = CheckHRResult(g_pD3ddev->CreateVertexShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pVS)); break; case SHADERTYPE_GEOMETRY_SHADER: shaderCreated = CheckHRResult(g_pD3ddev->CreateGeometryShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pGS)); break; case SHADERTYPE_PIXEL_SHADER: shaderCreated = CheckHRResult(g_pD3ddev->CreatePixelShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pPS)); break; } if(!shaderCreated) { CON(MSG_ERR, _W("Shader creation error")); return false; } //if(!CheckHRResult(D3DReflect((DWORD*)pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), __uuidof(ID3D10ShaderReflection), &m_pReflection))) if(!CheckHRResult(D3D10ReflectShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pReflection))) { CON(MSG_ERR, _W("Could not create a Shader reflection")); return false; } //HRESULT D3DReflect(LPCVOID pSrcData, SIZE_T SrcDataSize, REFIID pInterface, void **ppReflector); D3D10_SHADER_DESC shDesc; m_pReflection->GetDesc(&shDesc); m_numResources = shDesc.BoundResources; //not sure about this if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER) m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob); SAFE_RELEASE(pShaderBlob); m_desc = desc; CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile); return true; }
//ルールベースで認識した結果の音声部分をもう一度 ディクテーションにかけます。 //これで過剰なマッチを排除します。 xreturn::r<std::string> Recognition_SAPI::convertDictation(ISpRecoResult* result,const std::string& ruleName) { HRESULT hr; _USE_WINDOWS_ENCODING; CComPtr<ISpStreamFormat> resultStream; { hr = result->GetAudio( 0, 1, &resultStream ); if(FAILED(hr)) return xreturn::windowsError(hr); //オーディオから読み込んでね hr = this->DictationEngine->SetInput( resultStream, TRUE); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationGrammar->SetRuleState(ruleName.empty() ? NULL : _A2W(ruleName.c_str()), NULL, SPRS_ACTIVE ); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationRecoCtxt->WaitForNotifyEvent(2000); //2秒タイムアウト if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationGrammar->SetRuleState(NULL, NULL, SPRS_INACTIVE ); if(FAILED(hr)) return xreturn::windowsError(hr); { CSpEvent tempevent; hr = tempevent.GetFrom( this->DictationRecoCtxt ); if(FAILED(hr)) return xreturn::windowsError(hr); if (tempevent.eEventId == SPEI_RECOGNITION) {//認識した結果 ISpRecoResult* tempresult; { tempresult = tempevent.RecoResult(); //認識した文字列の取得 CSpDynamicString tempdstrText; hr = tempresult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &tempdstrText, NULL); if(FAILED(hr)) return xreturn::windowsError(hr); SPPHRASE *pPhrase; hr = tempresult->GetPhrase(&pPhrase); if ( FAILED(hr) ) return xreturn::windowsError(hr); double confidence = pPhrase->pElements->SREngineConfidence; std::string ret = _W2A(tempdstrText); this->PoolMainWindow->SyncInvokeLog(std::string() + "ディクテーションフィルター :" + ret + + " " + num2str(confidence),LOG_LEVEL_DEBUG); if (confidence <= 0.60) { this->PoolMainWindow->SyncInvokeLog(std::string() + "ディクテーションフィルター棄却",LOG_LEVEL_DEBUG); return ""; } return ret; } } } } //不明 return ""; }
bool CShaderHLSL::Create(P3D::sShaderDesc &desc) { const char *pData; ULONG fsize; IFileSystem* pFS = CRenderer::mEngine()->mFilesystem(); wchar path[P3DMAX_PATH]; wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get()); FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true); if (!fp) { CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get()); return false; } ID3DXBuffer *pShaderBlob = NULL; ID3DXBuffer *pErrors = NULL; DWORD flags = D3DXSHADER_DEBUG; //D3DXSHADER_OPTIMIZATION_LEVEL3 char profile[128]; switch(desc.ShaderType) { case SHADERTYPE_VERTEX_SHADER: strcpy(profile, D3DXGetVertexShaderProfile(g_pD3ddev)); break; case SHADERTYPE_PIXEL_SHADER: strcpy(profile, D3DXGetPixelShaderProfile(g_pD3ddev)); break; case SHADERTYPE_GEOMETRY_SHADER: CON(MSG_ERR, _W("DX9 does not support geometry shaders.")); return false; default: CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given.")); return false; } CIncludeHandler includeHandler; D3DXMACRO Shader_Macros[] = { { "DX9", NULL }, { "SM3", NULL }, NULL }; if(FAILED(D3DXCompileShader( pData, fsize, Shader_Macros, &includeHandler, _W2A(desc.EntryFunction.Get()), profile, flags, &pShaderBlob, &pErrors, &m_pConstTable ))) { if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer())); else CON(MSG_ERR, _W("Error description not given")); CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get()); SAFE_RELEASE(pErrors); return false; } pFS->UnLoad(fp, (BYTE *)pData); //save to cache fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb")); const char* cs = (const char*)pShaderBlob->GetBufferPointer(); pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp); pFS->Close(fp); bool shaderCreated = false; switch(desc.ShaderType) { case SHADERTYPE_VERTEX_SHADER: shaderCreated = SUCCEEDED(g_pD3ddev->CreateVertexShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pVS)); break; case SHADERTYPE_PIXEL_SHADER: shaderCreated = SUCCEEDED(g_pD3ddev->CreatePixelShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pPS)); break; } if(!shaderCreated) { CON(MSG_ERR, _W("Shader creation error")); return false; } //set constant to their default values m_pConstTable->SetDefaults(g_pD3ddev); //create vertex declaration if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER) m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob); SAFE_RELEASE(pShaderBlob); m_desc = desc; CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile); return true; }
int main(int argc, const char **argv) { srand((unsigned int)time(NULL)); #if _MSC_VER setlocale(LC_ALL, ""); #else std::setlocale(LC_ALL, ""); fwide(stdout,1); fwide(stderr,1); #endif //デバッグビルドだと毎回テストを実行します. 慈悲はない. SEXYTEST_RUNNER(); //オプションを配列にマップ if (! Option::m()->Create(argc,argv) ) { wprintf(L"\n"); usage(); return 0; } if (argc <= 2) { // wiki2yomiConvert("jawiki-latest-pages.xml"); // wiki2ruigiConvert("jawiki-latest-pages.xml"); // wiki2engConvert("jawiki-latest-pages.xml"); // cmudic2yomiConvert("cmudict.0.7a"); // wiki2charaConvert("jawiki-latest-pages.xml"); // wiki2categoryConvert("jawiki-latest-pages.xml"); usage(); return 0; } //モードによって振り分け if ( strcmp(argv[1],"yomi") == 0) { wiki2yomiConvert(argv[2] ); } else if ( strcmp(argv[1],"ruigi") == 0) { wiki2ruigiConvert(argv[2] ); } else if ( strcmp(argv[1],"eng") == 0) { wiki2engConvert(argv[2] ); } else if ( strcmp(argv[1],"chara") == 0) { wiki2charaConvert(argv[2] ); } else if ( strcmp(argv[1],"category") == 0) { wiki2categoryConvert(argv[2] ); } else if ( strcmp(argv[1],"cmudict") == 0) { cmudic2yomiConvert(argv[2] ); } else { wprintf(L"パラメタ(%ls)は存在しません。死んで詫びよ。\n",_A2W(argv[1]).c_str() ); wprintf(L"\n"); usage(); return 0; } return 0; }
//音声認識のためのオブジェクトの構築. xreturn::r<bool> Recognition_SAPI::Create(MainWindow* poolMainWindow) { _USE_WINDOWS_ENCODING; HRESULT hr; this->GlobalRuleNodeCount = 1; this->TemporaryRuleConfidenceFilter = 0.80; this->YobikakeRuleConfidenceFilter = 0.80; this->BasicRuleConfidenceFilter = 0.80; this->UseDictationFilter = true; this->TemporaryRuleCount = 0; this->IsNeedUpdateRule = true; this->PoolMainWindow = poolMainWindow; //Dictation { hr = this->DictationEngine.CoCreateInstance(CLSID_SpInprocRecognizer); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationEngine->CreateRecoContext(&this->DictationRecoCtxt); if(FAILED(hr)) return xreturn::windowsError(hr); ULONGLONG hookevent = SPFEI(SPEI_RECOGNITION)|SPFEI(SPEI_FALSE_RECOGNITION); hr = this->DictationRecoCtxt->SetInterest(hookevent, hookevent); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationRecoCtxt->SetAudioOptions(SPAO_RETAIN_AUDIO, NULL, NULL); if(FAILED(hr)) return xreturn::windowsError(hr); //認識器始動 hr = this->DictationRecoCtxt->CreateGrammar(0, &this->DictationGrammar); if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->DictationGrammar->LoadDictation(NULL, SPLO_STATIC); // if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationRecoCtxt->SetNotifyWin32Event(); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->DictationGrammar->GetRule(_A2W("FilterRule") ,0,SRATopLevel | SRADynamic | SPRAF_Active, TRUE , &this->FilterRuleHandleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->DictationGrammar->GetRule(_A2W("FilterRule2") ,0,SRATopLevel | SRADynamic | SPRAF_Active, TRUE , &this->FilterRuleHandleHandle2); // if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->DictationGrammar->Commit(0); // if(FAILED(hr)) return xreturn::windowsError(hr); } //ルールベースのエンジンを作る. { CComPtr<ISpAudio> cpAudio; hr = SpCreateDefaultObjectFromCategoryId(SPCAT_AUDIOIN, &cpAudio); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleEngine.CoCreateInstance(CLSID_SpInprocRecognizer); if(FAILED(hr)) return xreturn::windowsError(hr); //オーディオから読み込んでね hr = this->RuleEngine->SetInput( cpAudio, TRUE); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleEngine->CreateRecoContext(&this->RuleRecoCtxt); if(FAILED(hr)) return xreturn::windowsError(hr); // ULONGLONG hookevent = SPFEI(SPEI_RECOGNITION)|SPFEI(SPEI_FALSE_RECOGNITION)|SPFEI(SPEI_HYPOTHESIS)| SPFEI(SPEI_SOUND_START) | SPFEI(SPEI_SOUND_END); ULONGLONG hookevent = SPFEI(SPEI_RECOGNITION); hr = this->RuleRecoCtxt->SetInterest(hookevent, hookevent); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleRecoCtxt->SetAudioOptions(SPAO_RETAIN_AUDIO, NULL, NULL); if(FAILED(hr)) return xreturn::windowsError(hr); //認識器始動 hr = this->RuleRecoCtxt->CreateGrammar(0, &this->RuleGrammar); if(FAILED(hr)) return xreturn::windowsError(hr); } //トップレベルルールたちを作成する。 // hr = this->RuleGrammar->GetRule(_A2W("BasicRule") ,0,SRATopLevel | SRADynamic | SPRAF_Active, TRUE , &this->BasicRuleHandleHandle); // if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->GetRule(_A2W("TemporaryRule") ,0,SRATopLevel | SRADynamic | SPRAF_Active , TRUE , &this->TemporaryRuleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->GetRule(_A2W("YobikakeRule") ,0,SRATopLevel | SRADynamic | SPRAF_Active , TRUE , &this->YobikakeRuleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->GetRule(_A2W("CommandRule") ,0,SRADynamic , TRUE , &this->CommandRuleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); /* hr = this->RuleGrammar->GetRule(_A2W("MusicRule") ,0,SRADynamic , TRUE , &this->MusicRuleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->GetRule(_A2W("VideoRule") ,0,SRADynamic , TRUE , &this->VideoRuleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->GetRule(_A2W("BookRule") ,0,SRADynamic , TRUE , &this->BookRuleHandle); if(FAILED(hr)) return xreturn::windowsError(hr); */ //http://msdn.microsoft.com/en-us/library/ee125671(v=vs.85).aspx //BasicRule = YobikakeRule + CommandRule // SPSTATEHANDLE appendState; //あとに続くを表現するためには、 新規にステートを作らないといけない。 // hr = this->RuleGrammar->Z(this->BasicRuleHandleHandle, &appendState); // if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->RuleGrammar->AddRuleTransition(this->BasicRuleHandleHandle , appendState , this->YobikakeRuleHandle , 1.0f , NULL ); // if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->RuleGrammar->AddRuleTransition(appendState , NULL , this->CommandRuleHandle , 1.0f , NULL ); // if(FAILED(hr)) return xreturn::windowsError(hr); ////// // SPSTATEHANDLE appendState; //あとに続くを表現するためには、 新規にステートを作らないといけない。 // hr = this->RuleGrammar->CreateNewState(this->YobikakeRuleHandle, &appendState); // if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->RuleGrammar->AddRuleTransition(this->YobikakeRuleHandle , appendState , this->CommandRuleHandle , 1.0f , NULL ); // if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->RuleGrammar->AddRuleTransition(appendState , NULL , this->CommandRuleHandle , 1.0f , NULL ); // if(FAILED(hr)) return xreturn::windowsError(hr); //戻りはコールバックで。 //SAPIのコールバックはメインスレッドにコールバックされる。 hr = this->RuleRecoCtxt->SetNotifyCallbackFunction ( methodcallback::registstdcall<struct _sapi_callback1,SPNOTIFYCALLBACK*>(this, &Recognition_SAPI::Callback) ,0,0); if(FAILED(hr)) return xreturn::windowsError(hr); //ルールの適応 // this->CommitRule(); return true; }