int _tmain(int argc, WCHAR* argv[]) { HRESULT hr; CComPtr<IStream> pOutFileStream; CComPtr<IXmlWriter> pWriter; CComPtr<IXmlWriterOutput> pWriterOutput; if (argc != 2) { wprintf(L"Usage: XmlLiteWriteWithEncoding.exe name-of-output-file\n"); return 0; } //Open writeable output stream if (FAILED(hr = FileStream::OpenFile(argv[1], &pOutFileStream, TRUE))) { wprintf(L"Error creating file writer, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlWriter(__uuidof(IXmlWriter), (void**) &pWriter, NULL))) { wprintf(L"Error creating xml writer, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlWriterOutputWithEncodingName(pOutFileStream, NULL, L"utf-16", &pWriterOutput))) { wprintf(L"Error creating xml reader with encoding code page, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->SetOutput(pWriterOutput))) { wprintf(L"Error setting output for writer, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->SetProperty(XmlWriterProperty_Indent, TRUE))) { wprintf(L"Error setting indent property in writer, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteStartDocument(XmlStandalone_Omit))) { wprintf(L"Error, Method: WriteStartDocument, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteStartElement(NULL, L"root", NULL))) { wprintf(L"Error, Method: WriteStartElement, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteStartElement(NULL, L"sub", NULL))) { wprintf(L"Error, Method: WriteStartElement, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteAttributeString(NULL, L"myAttr", NULL, L"1234"))) { wprintf(L"Error, Method: WriteAttributeString, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteString(L"This is a string"))) { wprintf(L"Error, Method: WriteString, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteFullEndElement())) { wprintf(L"Error, Method: WriteFullEndElement, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->WriteEndDocument())) { wprintf(L"Error, Method: WriteEndDocument, error is %08.8lx", hr); return -1; } if (FAILED(hr = pWriter->Flush())) { wprintf(L"Error, Method: Flush, error is %08.8lx", hr); return -1; } return 0; }
bool RefCountDXGIObject::HandleWrap(REFIID riid, void **ppvObject) { if(ppvObject == NULL || *ppvObject == NULL) { RDCWARN("HandleWrap called with NULL ppvObject"); return false; } if(riid == __uuidof(IDXGIDevice)) { // should have been handled elsewhere, so we can properly create this device RDCERR("Unexpected uuid in RefCountDXGIObject::HandleWrap"); return false; } else if(riid == __uuidof(IDXGIAdapter)) { IDXGIAdapter *real = (IDXGIAdapter *)(*ppvObject); *ppvObject = new WrappedIDXGIAdapter(real); return true; } else if(riid == __uuidof(IDXGIFactory)) { // yes I know PRECISELY how f****d up this is. Speak to microsoft - after KB2670838 the internal D3D11 // device creation function will pass in __uuidof(IDXGIFactory) then attempt to call EnumDevices1 (which // is in the IDXGIFactory1 vtable). Doing this *should* be safe as using a IDXGIFactory1 like a IDXGIFactory // should all just work by definition, but there's no way to know now if someone trying to create a IDXGIFactory // really means it or not. IDXGIFactory1 *real = (IDXGIFactory1 *)(*ppvObject); *ppvObject = new WrappedIDXGIFactory1(real); return true; } else if(riid == __uuidof(IDXGIDevice1)) { // should have been handled elsewhere, so we can properly create this device RDCERR("Unexpected uuid in RefCountDXGIObject::HandleWrap"); return false; } else if(riid == __uuidof(IDXGIAdapter1)) { IDXGIAdapter1 *real = (IDXGIAdapter1 *)(*ppvObject); *ppvObject = new WrappedIDXGIAdapter1(real); return true; } else if(riid == __uuidof(IDXGIFactory1)) { IDXGIFactory1 *real = (IDXGIFactory1 *)(*ppvObject); *ppvObject = new WrappedIDXGIFactory1(real); return true; } else if(riid == __uuidof(IDXGIAdapter2)) { IDXGIAdapter2 *real = (IDXGIAdapter2 *)(*ppvObject); *ppvObject = new WrappedIDXGIAdapter2(real); return true; } else if(riid == __uuidof(IDXGIFactory2)) { IDXGIFactory2 *real = (IDXGIFactory2 *)(*ppvObject); *ppvObject = new WrappedIDXGIFactory2(real); return true; } else if(riid == __uuidof(IDXGIFactory3)) { IDXGIFactory3 *real = (IDXGIFactory3 *)(*ppvObject); *ppvObject = new WrappedIDXGIFactory3(real); return true; } else { string guid = ToStr::Get(riid); RDCWARN("Querying IDXGIObject for interface: %s", guid.c_str()); } return false; }
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = { {&MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_NULL}, }; const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = { {&MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_NULL}, {&MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_NULL}, }; const AMOVIESETUP_PIN sudpPins[] = { {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, NULL, _countof(sudPinTypesIn), sudPinTypesIn}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, _countof(sudPinTypesOut), sudPinTypesOut} }; const AMOVIESETUP_FILTER sudFilter[] = { {&__uuidof(CDeCSSFilter), DeCSSFilterName, MERIT_DO_NOT_USE, _countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}, }; CFactoryTemplate g_Templates[] = { {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CDeCSSFilter>, NULL, &sudFilter[0]}, }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { return AMovieDllRegisterServer2(TRUE); } STDAPI DllUnregisterServer() {
int MainWindow::checkWlanHosteed(){ DWORD dwError = 0; DWORD dwServiceVersion = 0; HANDLE hClient = NULL; if (ERROR_SUCCESS != (dwError = WlanOpenHandle( WLAN_API_VERSION, NULL, // reserved &dwServiceVersion, &hClient ))) { return dwError; } // check service version if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0)) { WlanCloseHandle(hClient, NULL); return -1; } std::string strSSID = "test"; std::string strSecondaryKey = "123456780"; // Set the network mode to allow BOOL bIsAllow = TRUE; WLAN_HOSTED_NETWORK_REASON dwFailedReason; DWORD dwReturnValue = WlanHostedNetworkSetProperty(hClient, wlan_hosted_network_opcode_enable, sizeof(BOOL), &bIsAllow, &dwFailedReason, NULL); if(ERROR_SUCCESS != dwReturnValue) { return dwReturnValue; } // Set the network SSID and the maximum number of connections WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS wlanConnectionSetting; memset(&wlanConnectionSetting, 0, sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS)); // The SSID field in WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS must be of type ANSI, so if the program uses the Unicode, you need to do the conversion. #ifdef _UNICODE WideCharToMultiByte(CP_ACP, 0, strSSID.c_str(), // Save SSID CString types strSSID.length(), // SSID the length of a string (LPSTR)wlanConnectionSetting.hostedNetworkSSID.ucSSID, 32, NULL, NULL); #else memcpy(wlanConnectionSetting.hostedNetworkSSID.ucSSID, strSSID.c_str(), strlen(strSSID.c_str())); #endif wlanConnectionSetting.hostedNetworkSSID.uSSIDLength = strlen((const char*)wlanConnectionSetting.hostedNetworkSSID.ucSSID); wlanConnectionSetting.dwMaxNumberOfPeers = 100; dwReturnValue = WlanHostedNetworkSetProperty(hClient, wlan_hosted_network_opcode_connection_settings, sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS), &wlanConnectionSetting, &dwFailedReason, NULL); if(ERROR_SUCCESS != dwReturnValue) { return dwReturnValue; } UCHAR keyBuf[100] = {0}; #ifdef _UNICODE WideCharToMultiByte(CP_ACP, 0, strSecondaryKey.c_str(), strSecondaryKey.length(), (LPSTR)keyBuf, 100, NULL, NULL); #else memcpy(keyBuf, strSecondaryKey.c_str(), strSecondaryKey.length()); #endif dwReturnValue = WlanHostedNetworkSetSecondaryKey(hClient, strlen((const char*)keyBuf) + 1, keyBuf, TRUE, FALSE, &dwFailedReason, NULL); if(ERROR_SUCCESS != dwReturnValue) { return dwReturnValue; } dwReturnValue = WlanHostedNetworkStartUsing(hClient, &dwFailedReason, NULL); if(ERROR_SUCCESS != dwReturnValue) { if (wlan_hosted_network_reason_interface_unavailable == dwFailedReason) { return dwFailedReason; } return dwReturnValue; } /*PIP_ADAPTER_INFO pAdapterInfo; pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO)); ULONG buflen = sizeof(IP_ADAPTER_INFO); if(GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) { free(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO *) malloc(buflen); } if(GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) { PIP_ADAPTER_INFO pAdapter = pAdapterInfo; while (pAdapter) { QString str = QString("\tAdapter Name: \t%1\n\ \tAdapter Desc: \t%2\n\ \tIP Address: \t%3\n\ \tGateway: \t%4\n").arg(pAdapter->AdapterName) .arg(pAdapter->Description) //.arg((byte*)pAdapter->Address) .arg(pAdapter->IpAddressList.IpAddress.String) .arg(pAdapter->GatewayList.IpAddress.String); pAdapter = pAdapter->Next; QMessageBox msg(this); msg.setText(str); msg.exec(); } } else { printf("Call to GetAdaptersInfo failed.\n"); }*/ CoInitialize (NULL); // init security to enum RAS connections CoInitializeSecurity (NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); INetSharingManager * pNSM = NULL; HRESULT hr = ::CoCreateInstance (__uuidof(NetSharingManager), NULL, CLSCTX_ALL, __uuidof(INetSharingManager), (void**)&pNSM); if(hr == S_OK){ // in case it exists already //DeletePortMapping (pNSM, NAT_PROTOCOL_TCP, 555); // add a port mapping to every shared or firewalled connection. hr = DoTheWork (pNSM); pNSM->Release(); if (hr!= S_OK){ return hr; } }else return hr; return 0; }
/** * Callback to draw things in world space. ***/ void OSVR_DirectMode::DrawWorld(void* userData, osvr::renderkit::GraphicsLibrary cLibrary, osvr::renderkit::RenderBuffer cBuffers, osvr::renderkit::OSVR_ViewportDescription sViewport, OSVR_PoseState pose, osvr::renderkit::OSVR_ProjectionMatrix sProjection, OSVR_TimeValue deadline) { static int nEye = 0; static float fAspect = 1.0f; // Make sure our pointers are filled in correctly. The config file selects // the graphics library to use, and may not match our needs. if (cLibrary.D3D11 == nullptr) { std::cerr << "SetupDisplay: No D3D11 GraphicsLibrary" << std::endl; return; } if (cBuffers.D3D11 == nullptr) { std::cerr << "SetupDisplay: No D3D11 RenderBuffer" << std::endl; return; } // auto pcContext = cLibrary.D3D11->context; auto pcDevice = cLibrary.D3D11->device; auto pcContext = cLibrary.D3D11->context; // create all bool bool bAllCreated = true; // create vertex shader if (!m_pcVertexShader11) { if (FAILED(Create2DVertexShader(pcDevice, &m_pcVertexShader11, &m_pcVertexLayout11))) { OutputDebugString(L"FAILED"); bAllCreated = false; } } // create pixel shader... if (!m_pcPixelShader11) { if (FAILED(CreatePixelShaderEffect(pcDevice, &m_pcPixelShader11, PixelShaderTechnique::FullscreenGammaCorrection))) bAllCreated = false; } // Create vertex buffer if (!m_pcVertexBuffer11) { if (FAILED(CreateFullScreenVertexBuffer(pcDevice, &m_pcVertexBuffer11))) bAllCreated = false; } // create constant buffer if (!m_pcConstantBufferDirect11) { if (FAILED(CreateMatrixConstantBuffer(pcDevice, &m_pcConstantBufferDirect11))) bAllCreated = false; } // sampler ? if (!m_pcSamplerState) { bAllCreated = false; } if ((bAllCreated) && (m_sStereoTextureViews.m_ppcTexView11[nEye])) { // Set the input layout pcContext->IASetInputLayout(m_pcVertexLayout11); // Set vertex buffer UINT stride = sizeof(TexturedVertex); UINT offset = 0; pcContext->IASetVertexBuffers(0, 1, &m_pcVertexBuffer11, &stride, &offset); // get orthographic matrix from projection and normalize it by its width (since we use a fullscreen shader here) float afProjectionD3D[16]; osvr::renderkit::OSVR_Projection_to_D3D(afProjectionD3D, sProjection); D3DXMATRIX sProj(afProjectionD3D); // due to the aspect ratio (90° horizontal, 90° vertical) of the HDK we adjust the screen by // the height, not by the width... in this case we need to set a higher FOV by following formular: // V = 2 * arctan( tan(H / 2) * aspectratio ) - so we get V 90° and H 121° sProj.m[0][0] = sProj.m[0][0] * fAspect; // < incorporate game screen aspect ratio; sProj.m[0][1] = 0.0f; sProj.m[0][3] = sProj.m[0][2]; sProj.m[0][2] = 0.0f; sProj.m[1][0] = 0.0f; sProj.m[1][1] = sProj.m[1][1]; sProj.m[1][3] = sProj.m[1][2]; sProj.m[1][2] = 0.0f; sProj.m[2][0] = 0.0f; sProj.m[2][1] = 0.0f; sProj.m[2][2] = 1.0f; // 1.0f here... fullscreen shader ! sProj.m[2][3] = 0.0f; sProj.m[3][0] = 0.0f; sProj.m[3][1] = 0.0f; sProj.m[3][2] = 0.0f; sProj.m[3][3] = 1.0f; // zoom out ? if (m_pbZoomOut) { if (*m_pbZoomOut) { sProj.m[0][0] /= 2.0f; sProj.m[1][1] /= 2.0f; } } // Set constant buffer, first update it... scale and translate the left and right image pcContext->UpdateSubresource((ID3D11Resource*)m_pcConstantBufferDirect11, 0, NULL, &sProj, 0, 0); pcContext->VSSetConstantBuffers(0, 1, &m_pcConstantBufferDirect11); // Set primitive topology pcContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // texture connected ? if ((m_sStereoTextureViews.m_ppcTexView11[nEye]) && (*m_sStereoTextureViews.m_ppcTexView11[nEye])) { if (m_eMethod == OSVR_DirectModeMethods::OSVR_D3D11_use_Game_Device) { // set texture, sampler state pcContext->PSSetShaderResources(0, 1, m_sStereoTextureViews.m_ppcTexView11[nEye]); pcContext->PSSetSamplers(0, 1, &m_pcSamplerState); } else { ID3D11Resource* pcResource = nullptr; (*m_sStereoTextureViews.m_ppcTexView11[nEye])->GetResource(&pcResource); if (!m_sStereoTextureCopies.m_pcTex11Copy[nEye]) { // get the description and create the copy texture D3D11_TEXTURE2D_DESC sDesc; ((ID3D11Texture2D*)pcResource)->GetDesc(&sDesc); sDesc.MiscFlags |= D3D11_RESOURCE_MISC_SHARED; sDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; if (FAILED(((ID3D11Device*)m_pcGameDevice)->CreateTexture2D(&sDesc, NULL, (ID3D11Texture2D**)&m_sStereoTextureCopies.m_pcTex11Copy[nEye]))) { OutputDebugString(L"StereoSplitterDX10 : Failed to create twin texture !"); return; } // aspect ratio fAspect = (float)sDesc.Width / (float)sDesc.Height; // TODO !! DX9 // DX10 !! // get shared handle IDXGIResource* pcDXGIResource(NULL); m_sStereoTextureCopies.m_pcTex11Copy[nEye]->QueryInterface(__uuidof(IDXGIResource), (void**)&pcDXGIResource); HANDLE sharedHandle; if (pcDXGIResource) { pcDXGIResource->GetSharedHandle(&sharedHandle); pcDXGIResource->Release(); } else OutputDebugString(L"Failed to query IDXGIResource."); // open the shared handle with the temporary device ID3D11Resource* pcResourceShared; pcDevice->OpenSharedResource(sharedHandle, __uuidof(ID3D11Resource), (void**)(&pcResourceShared)); if (pcResourceShared) { pcResourceShared->QueryInterface(__uuidof(ID3D11Texture2D), (void**)(&m_sStereoFrameTextures.m_pcFrameTexture[nEye])); pcResourceShared->Release(); } else OutputDebugString(L"Could not open shared resource."); // create shader resource view if (m_sStereoFrameTextures.m_pcFrameTexture[nEye]) { D3D11_SHADER_RESOURCE_VIEW_DESC sDescSRV; ZeroMemory(&sDescSRV, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC)); sDescSRV.Format = sDesc.Format; sDescSRV.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; sDescSRV.Texture2D.MostDetailedMip = 0; sDescSRV.Texture2D.MipLevels = 1; if (FAILED(pcDevice->CreateShaderResourceView(m_sStereoFrameTextures.m_pcFrameTexture[nEye], &sDescSRV, &m_sSteroFrameTextureSRViews.m_pcFrameTextureSRView[nEye]))) OutputDebugString(L"Failed to create shader resource view."); } else OutputDebugString(L"No Texture available."); } else { // copy the frame tex to shared texture m_pcGameDeviceContext->CopyResource(m_sStereoTextureCopies.m_pcTex11Copy[nEye], pcResource); if (pcResource) pcResource->Release(); // set texture, sampler state pcContext->PSSetShaderResources(0, 1, &m_sSteroFrameTextureSRViews.m_pcFrameTextureSRView[nEye]); pcContext->PSSetSamplers(0, 1, &m_pcSamplerState); } } } // set shaders pcContext->VSSetShader(m_pcVertexShader11, 0, 0); pcContext->PSSetShader(m_pcPixelShader11, 0, 0); // Render a triangle pcContext->Draw(6, 0); // switch eye for next call nEye = !nEye; } }
void VolumeControl::init() { //initialize audio mixer interface #if defined (__APPLE__) #warning TODO: Not implemented for MacOS yet!!! #elif defined(__linux__) //try to open mixer device if (mixerHandle == nullptr) { snd_mixer_selem_id_alloca(&mixerSelemId); //sets simple-mixer index and name snd_mixer_selem_id_set_index(mixerSelemId, mixerIndex); snd_mixer_selem_id_set_name(mixerSelemId, mixerName); //open mixer if (snd_mixer_open(&mixerHandle, 0) >= 0) { LOG(LogDebug) << "VolumeControl::init() - Opened ALSA mixer"; //ok. attach to defualt card if (snd_mixer_attach(mixerHandle, mixerCard) >= 0) { LOG(LogDebug) << "VolumeControl::init() - Attached to default card"; //ok. register simple element class if (snd_mixer_selem_register(mixerHandle, NULL, NULL) >= 0) { LOG(LogDebug) << "VolumeControl::init() - Registered simple element class"; //ok. load registered elements if (snd_mixer_load(mixerHandle) >= 0) { LOG(LogDebug) << "VolumeControl::init() - Loaded mixer elements"; //ok. find elements now mixerElem = snd_mixer_find_selem(mixerHandle, mixerSelemId); if (mixerElem != nullptr) { //wohoo. good to go... LOG(LogDebug) << "VolumeControl::init() - Mixer initialized"; } else { LOG(LogError) << "VolumeControl::init() - Failed to find mixer elements!"; snd_mixer_close(mixerHandle); mixerHandle = nullptr; } } else { LOG(LogError) << "VolumeControl::init() - Failed to load mixer elements!"; snd_mixer_close(mixerHandle); mixerHandle = nullptr; } } else { LOG(LogError) << "VolumeControl::init() - Failed to register simple element class!"; snd_mixer_close(mixerHandle); mixerHandle = nullptr; } } else { LOG(LogError) << "VolumeControl::init() - Failed to attach to default card!"; snd_mixer_close(mixerHandle); mixerHandle = nullptr; } } else { LOG(LogError) << "VolumeControl::init() - Failed to open ALSA mixer!"; } } #elif defined(WIN32) || defined(_WIN32) //get windows version information OSVERSIONINFOEXA osVer = {sizeof(OSVERSIONINFO)}; ::GetVersionExA(reinterpret_cast<LPOSVERSIONINFOA>(&osVer)); //check windows version if(osVer.dwMajorVersion < 6) { //Windows older than Vista. use mixer API. open default mixer if (mixerHandle == nullptr) { if (mixerOpen(&mixerHandle, 0, NULL, 0, 0) == MMSYSERR_NOERROR) { //retrieve info on the volume slider control for the "Speaker Out" line MIXERLINECONTROLS mixerLineControls; mixerLineControls.cbStruct = sizeof(MIXERLINECONTROLS); mixerLineControls.dwLineID = 0xFFFF0000; //Id of "Speaker Out" line mixerLineControls.cControls = 1; //mixerLineControls.dwControlID = 0x00000000; //Id of "Speaker Out" line's volume slider mixerLineControls.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; //Get volume control mixerLineControls.pamxctrl = &mixerControl; mixerLineControls.cbmxctrl = sizeof(MIXERCONTROL); if (mixerGetLineControls((HMIXEROBJ)mixerHandle, &mixerLineControls, MIXER_GETLINECONTROLSF_ONEBYTYPE) != MMSYSERR_NOERROR) { LOG(LogError) << "VolumeControl::getVolume() - Failed to get mixer volume control!"; mixerClose(mixerHandle); mixerHandle = nullptr; } } else { LOG(LogError) << "VolumeControl::init() - Failed to open mixer!"; } } } else { //Windows Vista or above. use EndpointVolume API. get device enumerator if (endpointVolume == nullptr) { CoInitialize(nullptr); IMMDeviceEnumerator * deviceEnumerator = nullptr; CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID *)&deviceEnumerator); if (deviceEnumerator != nullptr) { //get default endpoint IMMDevice * defaultDevice = nullptr; deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice); if (defaultDevice != nullptr) { //retrieve endpoint volume defaultDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr, (LPVOID *)&endpointVolume); if (endpointVolume == nullptr) { LOG(LogError) << "VolumeControl::init() - Failed to get default audio endpoint volume!"; } //release default device. we don't need it anymore defaultDevice->Release(); } else { LOG(LogError) << "VolumeControl::init() - Failed to get default audio endpoint!"; } //release device enumerator. we don't need it anymore deviceEnumerator->Release(); } else { LOG(LogError) << "VolumeControl::init() - Failed to get audio endpoint enumerator!"; CoUninitialize(); } } } #endif }
bool Engine::LoadContent() { // Setup our SpriteBatch. m_pSpriteBatch = new DirectX::SpriteBatch(d3dContext_); m_pFont->Initialize(d3dDevice_, std::wstring(L"Calibri18.spritefont")); m_pSprite->Initialize(d3dDevice_, std::wstring(L"Test.dds"), 10.0f, 10.0f); m_textToDisplay = Text(); m_textToDisplay.Initialize(std::wstring(L"Sarah"), DirectX::SimpleMath::Vector2(200.0f, 200.0f)); try { MSXML2::IXMLDOMDocument2Ptr xmlDoc; HRESULT hr = xmlDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60), NULL, CLSCTX_INPROC_SERVER); teamStats.InitializeTeam("Players.xml"); // Make sure the file was loaded correctly before trying to load the players. if (xmlDoc->load("Players.xml") == VARIANT_TRUE) { //xmlDoc->setProperty("SelectionLanguage", "XPath"); //teamStats.LoadPlayers(xmlDoc); } if (xmlDoc->load("input.xml") != VARIANT_TRUE) { DXTRACE_MSG("Unable to load input.xml\n"); xmlDoc->save("input.xml"); //xmlDoc-> } else { DXTRACE_MSG("XML was successfully loaded \n"); xmlDoc->setProperty("SelectionLanguage", "XPath"); MSXML2::IXMLDOMNodeListPtr wheels = xmlDoc->selectNodes("/Car/Wheels/*"); DXTRACE_MSG("Car has %u wheels\n", wheels->Getlength()); DXTRACE_MSG(wheels->Getitem(0)->text); //ptr-> MSXML2::IXMLDOMNodePtr node; node = xmlDoc->createNode(MSXML2::NODE_ELEMENT, ("Engine"), ("")); node->text = ("Engine 1.0"); xmlDoc->documentElement->appendChild(node); hr = xmlDoc->save("output.xml"); if (SUCCEEDED(hr)) { DXTRACE_MSG("output.xml successfully saved\n"); } } } catch (_com_error &e) { DXTRACE_MSG(e.ErrorMessage()); } return true; }
STDMETHODIMP CWinRobotService::GetActiveConsoleSession(IUnknown** ppSession) { TrackDebugOut; if(ppSession == 0) { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,ppSession == null"); return E_POINTER; } *ppSession = 0 ; // if has exist,determine whether the process has been closed. CAutoLockEx<CCrtSection> lock(m_csLock); static Kernel32Dll dll; DWORD sid = dll.WTSGetActiveConsoleSessionId(); { CAutoLock<CCrtSection> lock2(m_csLockSessions); SESSIONS::iterator it = m_sessions.find(sid); if ( it != m_sessions.end() ) { CRefObj< CReference_T<SESSION> > sn = it->second; _ASSERT(sn->pSession); if ( sn->IsOK() ) { HRESULT hr = sn->pSession->QueryInterface(__uuidof(IWinRobotSession),(void**)ppSession); if(SUCCEEDED(hr)) { DebugOutF(filelog::log_info,"GetActiveConsoleSession %d ok",sid); } else { DebugOutF(filelog::log_error,"GetActiveConsoleSession %d failed with 0x%x ",sid,hr); } return hr; } } } // else,create a new child process,and then wait for complete HANDLE hProcess = CreateChildProcess(sid); if(!hProcess) { return E_UNEXPECTED; } ResetEvent(m_hNewReg); HANDLE hd[] = {m_hExit,m_hNewReg,hProcess}; HRESULT hr = S_OK; /*while (SUCCEEDED(hr))*/ { DWORD res = WaitForMultipleObjects(RTL_NUMBER_OF(hd),hd,FALSE,-1); if( (res < WAIT_OBJECT_0) || (res>=res+RTL_NUMBER_OF(hd) ) ) { hr = E_UNEXPECTED; DebugOutF(filelog::log_error,"WaitForMultipleObjects failed with %d ",GetLastError() ); } else if (hd[res-WAIT_OBJECT_0] == m_hExit) { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,CWinRobotService stopped"); hr = E_UNEXPECTED; //break; } else if(hd[res-WAIT_OBJECT_0] == m_hNewReg) { CAutoLock<CCrtSection> lock2(m_csLockSessions); for (SESSIONS::iterator it = m_sessions.begin(); it != m_sessions.end(); it++) { if(GetProcessId(hProcess) == GetProcessId(it->second->m_hProcess)){ CRefObj< CReference_T<SESSION> > sn = it->second; _ASSERT(sn->pSession); //! this will be a bug ! // sometimes CreateChildProcess failed on the specified session with error 233, // then we CreateChildProcess on session 0 to make sure we can capture something, // so the sid will be not the specified session. if(it->first != sid){ m_sessions.erase(it); m_sessions[sid] = sn; } if ( sn->IsOK() ) { hr = sn->pSession->QueryInterface(__uuidof(IWinRobotSession),(void**)ppSession); if(SUCCEEDED(hr)) { DebugOutF(filelog::log_info,"GetActiveConsoleSession %d ok",sid); } else { DebugOutF(filelog::log_error,"GetActiveConsoleSession %d failed with 0x%x ",sid,hr); } break; } else { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed, process has end"); hr = E_UNEXPECTED; break; } } } } else if(hd[res-WAIT_OBJECT_0] == hProcess) { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,process has end"); hr = E_UNEXPECTED; //break; }else{ DebugOutF(filelog::log_error,"GetActiveConsoleSession failed"); hr = E_UNEXPECTED; } } CloseHandle(hProcess); return hr;// should never be here }
//-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { DXUT_SetDebugName( pd3dDevice, "Main Device" ); HRESULT hr; ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_SettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); IDXGIDevice* pDXGIDevice; hr = pd3dDevice->QueryInterface( __uuidof(IDXGIDevice), (VOID**)&pDXGIDevice ); if( SUCCEEDED(hr) ) { IDXGIAdapter* pAdapter; hr = pDXGIDevice->GetAdapter( &pAdapter ); if( SUCCEEDED(hr) ) { DXGI_ADAPTER_DESC AdapterDesc; pAdapter->GetDesc( &AdapterDesc ); SetAdapterInfoForShaderCompilation( AdapterDesc.Description ); SAFE_RELEASE( pAdapter ); } SAFE_RELEASE( pDXGIDevice ); } ID3D10Blob* pVSBlob = NULL; g_pVSTransform = CompileVertexShader( pd3dDevice, L"SceneRender.hlsl", "VSTransform", &pVSBlob ); g_pPSSceneRender = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRender" ); g_pPSSceneRenderArray = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRenderArray" ); g_pPSSceneRenderQuilt = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRenderQuilt" ); // Create a layout for the object data const D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pDefaultInputLayout ) ); // No longer need the shader blobs SAFE_RELEASE( pVSBlob ); // Create state objects D3D11_SAMPLER_DESC samDesc; ZeroMemory( &samDesc, sizeof(samDesc) ); samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samDesc.AddressU = samDesc.AddressV = samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.MaxAnisotropy = 1; samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samDesc.MaxLOD = D3D11_FLOAT32_MAX; V_RETURN( pd3dDevice->CreateSamplerState( &samDesc, &g_pSamLinear ) ); DXUT_SetDebugName( g_pSamLinear, "Linear" ); D3D11_BLEND_DESC BlendDesc; ZeroMemory( &BlendDesc, sizeof( D3D11_BLEND_DESC ) ); BlendDesc.RenderTarget[0].BlendEnable = FALSE; BlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; BlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; BlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; BlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; BlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; BlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; BlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL; hr = pd3dDevice->CreateBlendState( &BlendDesc, &g_pBlendState ); ASSERT( SUCCEEDED(hr) ); D3D11_DEPTH_STENCIL_DESC DSDesc; ZeroMemory( &DSDesc, sizeof(D3D11_DEPTH_STENCIL_DESC) ); DSDesc.DepthEnable = FALSE; DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; DSDesc.DepthFunc = D3D11_COMPARISON_LESS; DSDesc.StencilEnable = FALSE; DSDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; DSDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; hr = pd3dDevice->CreateDepthStencilState( &DSDesc, &g_pDepthStencilState ); ASSERT( SUCCEEDED(hr) ); D3D11_RASTERIZER_DESC RSDesc; ZeroMemory( &RSDesc, sizeof(RSDesc) ); RSDesc.AntialiasedLineEnable = FALSE; RSDesc.CullMode = D3D11_CULL_BACK; RSDesc.DepthBias = 0; RSDesc.DepthBiasClamp = 0.0f; RSDesc.DepthClipEnable = TRUE; RSDesc.FillMode = D3D11_FILL_SOLID; RSDesc.FrontCounterClockwise = FALSE; RSDesc.MultisampleEnable = TRUE; RSDesc.ScissorEnable = FALSE; RSDesc.SlopeScaledDepthBias = 0.0f; hr = pd3dDevice->CreateRasterizerState( &RSDesc, &g_pRasterizerState ); ASSERT( SUCCEEDED(hr) ); g_pcbVSPerObject11 = CreateConstantBuffer( pd3dDevice, sizeof(CB_VS_PER_OBJECT) ); DXUT_SetDebugName( g_pcbVSPerObject11, "CB_VS_PER_OBJECT" ); // Create other render resources here D3D11_TILED_EMULATION_PARAMETERS EmulationParams; EmulationParams.DefaultPhysicalTileFormat = DXGI_FORMAT_R8G8B8A8_UNORM; EmulationParams.MaxPhysicalTileCount = 1000; D3D11CreateTiledResourceDevice( pd3dDevice, pd3dImmediateContext, &EmulationParams, &g_pd3dDeviceEx ); g_pd3dDeviceEx->CreateTilePool( &g_pTilePool ); g_pTitleResidencyManager = new TitleResidencyManager( pd3dDevice, pd3dImmediateContext, 1, EmulationParams.MaxPhysicalTileCount, g_pTilePool ); ResidencySampleRender::Initialize( pd3dDevice ); g_PageDebugRender.Initialize( pd3dDevice ); CreateSceneGeometry( pd3dDevice ); // Setup the camera's view parameters XMMATRIX matProjection = XMMatrixPerspectiveFovLH( XM_PIDIV4, (FLOAT)pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height, 0.001f, 100.0f ); XMStoreFloat4x4A( &g_matProjection, matProjection ); UpdateViewMatrix(); g_pTitleResidencyManager->StartThreads(); return S_OK; }
void W7EInject::AttemptOperation(HWND hWnd, bool bInject, bool bElevate, DWORD dwPid, const wchar_t *szProcName, const wchar_t *szCmd, const wchar_t *szArgs, const wchar_t *szDir, const wchar_t *szPathToOurDll, DWORD (__stdcall *Redirector)(void)) { bool bThreadWaitSuccess = false; bool bThreadWaitFailure = false; HANDLE hTargetProc = NULL; const BYTE * codeStartAdr = reinterpret_cast< const BYTE * >( &RemoteCodeFunc ); const BYTE * codeEndAdr = reinterpret_cast< const BYTE * >( &DummyRemoteCodeFuncEnd ); if (codeStartAdr >= codeEndAdr) { //MessageBox(hWnd, L"Unexpected function layout", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Unexpected function layout"); return; } wchar_t szPathToSelf[MAX_PATH]; DWORD dwGMFNRes = GetModuleFileName(NULL, szPathToSelf, _countof(szPathToSelf)); if (dwGMFNRes == 0 || dwGMFNRes >= _countof(szPathToSelf)) { //MessageBox(hWnd, L"Couldn't get path to self", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Couldn't get path to self"); return; } wchar_t szProgramFiles[MAX_PATH]; HRESULT hr = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, szProgramFiles); if (S_OK != hr) { //MessageBox(hWnd, L"SHGetFolderPath failed", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"SHGetFolderPath failed"); return; } HMODULE hModKernel32 = LoadLibrary(L"kernel32.dll"); if (hModKernel32 == 0) { //MessageBox(hWnd, L"Couldn't load kernel32.dll", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Couldn't load kernel32.dll"); return; } W7EUtils::GetProcAddr< BOOL (WINAPI *)(HMODULE) > tfpFreeLibrary( &GetProcAddress, hModKernel32, "FreeLibrary"); W7EUtils::GetProcAddr< HMODULE (WINAPI *)(LPCWSTR) > tfpLoadLibrary( &GetProcAddress, hModKernel32, "LoadLibraryW"); W7EUtils::GetProcAddr< FARPROC (WINAPI *)(HMODULE, LPCSTR) > tfpGetProcAddress( &GetProcAddress, hModKernel32, "GetProcAddress"); W7EUtils::GetProcAddr< BOOL (WINAPI *)(HANDLE) > tfpCloseHandle( &GetProcAddress, hModKernel32, "CloseHandle"); W7EUtils::GetProcAddr< DWORD (WINAPI *)(HANDLE,DWORD) > tfpWaitForSingleObject( &GetProcAddress, hModKernel32, "WaitForSingleObject"); if (0 == tfpFreeLibrary.f || 0 == tfpLoadLibrary.f || 0 == tfpGetProcAddress.f || 0 == tfpCloseHandle.f || 0 == tfpWaitForSingleObject.f) { //MessageBox(hWnd, L"Couldn't find API", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Couldn't find API"); } else { // Here we define the target process and DLL for "part 2." This is an auto/silent-elevating process which isn't // directly below System32 and which loads a DLL which is directly below System32 but isn't on the OS's "Known DLLs" list. // If we copy our own DLL with the same name to the exe's folder then the exe will load our DLL instead of the real one. const wchar_t *szElevDir = L"C:\\Windows\\System32\\sysprep"; const wchar_t *szElevDll = L"CRYPTBASE.dll"; const wchar_t *szElevDllFull = L"C:\\Windows\\System32\\sysprep\\CRYPTBASE.dll"; const wchar_t *szElevExeFull = L"C:\\Windows\\System32\\sysprep\\sysprep.exe"; std::wstring strElevArgs = L"\""; // strElevArgs += szElevExeFull; // strElevArgs += L"\" \""; strElevArgs += szCmd; strElevArgs += L"\" \""; strElevArgs += szDir; strElevArgs += L"\" \""; for (const wchar_t *pCmdArgChar = szArgs; *szArgs; ++szArgs) { if (*szArgs != L'\"') { strElevArgs += *szArgs; } else { strElevArgs += L"\"\"\""; // Turn each quote into three to preserve them in the arguments. } } strElevArgs += L"\""; if (!bInject) { // Test code without remoting. // This should result in a UAC prompt, if UAC is on at all and we haven't been launched as admin. // Satisfy CreateProcess's non-const args requirement wchar_t *szElevArgsNonConst = new wchar_t[strElevArgs.length() + 1]; wcscpy_s(szElevArgsNonConst, strElevArgs.length() + 1, strElevArgs.c_str()); InjectArgs ia; ia.fpFreeLibrary = tfpFreeLibrary.f; ia.fpLoadLibrary = tfpLoadLibrary.f; ia.fpGetProcAddress = tfpGetProcAddress.f; ia.fpCloseHandle = tfpCloseHandle.f; ia.fpWaitForSingleObject = tfpWaitForSingleObject.f; ia.szSourceDll = szPathToOurDll; ia.szElevDir = szElevDir; ia.szElevDll = szElevDll; ia.szElevDllFull = szElevDllFull; ia.szElevExeFull = szElevExeFull; ia.szElevArgs = szElevArgsNonConst; ia.szShell32 = L"shell32.dll"; ia.szOle32 = L"ole32.dll"; ia.szCoInitialize = "CoInitialize"; ia.szCoUninitialize = "CoUninitialize"; ia.szCoGetObject = "CoGetObject"; ia.szCoCreateInstance = "CoCreateInstance"; ia.szSHCreateItemFPN = "SHCreateItemFromParsingName"; ia.szShellExecuteExW = "ShellExecuteExW"; ia.szEIFOMoniker = bElevate ? L"Elevation:Administrator!new:{3ad05575-8857-4850-9277-11b85bdb8e09}" : NULL; ia.pIID_EIFOClass = bElevate ? NULL : &__uuidof(FileOperation); ia.pIID_EIFO = &__uuidof(IFileOperation); ia.pIID_ShellItem2 = &__uuidof(IShellItem2); ia.pIID_Unknown = &__uuidof(IUnknown); RemoteCodeFunc(&ia); delete[] szElevArgsNonConst; } else if (W7EUtils::OpenProcessToInject(hWnd, &hTargetProc, dwPid, szProcName)) { // Test code with remoting. // At least as of RC1 build 7100, with the default OS settings, this will run the specified command // with elevation but without triggering a UAC prompt. // Scope CRemoteMemory so it's destroyed before the process handle is closed. { W7EUtils::CRemoteMemory reme(hTargetProc); InjectArgs ia; // ASSUMPTION: Remote process has same ASLR setting as us (i.e. ASLR = on) // kernel32.dll is mapped to the same address range in both processes. ia.fpFreeLibrary = tfpFreeLibrary.f; ia.fpLoadLibrary = tfpLoadLibrary.f; ia.fpGetProcAddress = tfpGetProcAddress.f; ia.fpCloseHandle = tfpCloseHandle.f; ia.fpWaitForSingleObject = tfpWaitForSingleObject.f; // It would be more efficient to allocate and copy the data in one // block but since this is just a proof-of-concept I don't bother. ia.szSourceDll = reme.AllocAndCopyMemory(szPathToOurDll); ia.szElevDir = reme.AllocAndCopyMemory(szElevDir); ia.szElevDll = reme.AllocAndCopyMemory(szElevDll); ia.szElevDllFull = reme.AllocAndCopyMemory(szElevDllFull); ia.szElevExeFull = reme.AllocAndCopyMemory(szElevExeFull); ia.szElevArgs = reme.AllocAndCopyMemory(strElevArgs.c_str(), false); // Leave this page writeable for CreateProcess. ia.szShell32 = reme.AllocAndCopyMemory(L"shell32.dll"); ia.szOle32 = reme.AllocAndCopyMemory(L"ole32.dll"); ia.szCoInitialize = reme.AllocAndCopyMemory("CoInitialize"); ia.szCoUninitialize = reme.AllocAndCopyMemory("CoUninitialize"); ia.szCoGetObject = reme.AllocAndCopyMemory("CoGetObject"); ia.szCoCreateInstance = reme.AllocAndCopyMemory("CoCreateInstance"); ia.szSHCreateItemFPN = reme.AllocAndCopyMemory("SHCreateItemFromParsingName"); ia.szShellExecuteExW = reme.AllocAndCopyMemory("ShellExecuteExW"); ia.szEIFOMoniker = bElevate ? reme.AllocAndCopyMemory(L"Elevation:Administrator!new:{3ad05575-8857-4850-9277-11b85bdb8e09}") : NULL; ia.pIID_EIFOClass = bElevate ? NULL : reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(FileOperation), sizeof(__uuidof(FileOperation)), false) ); ia.pIID_EIFO = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IFileOperation), sizeof(__uuidof(IFileOperation)), false) ); ia.pIID_ShellItem2 = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IShellItem2), sizeof(__uuidof(IShellItem2)), false) ); ia.pIID_Unknown = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IUnknown), sizeof(__uuidof(IUnknown)), false) ); void *pRemoteArgs = reme.AllocAndCopyMemory(&ia, sizeof(ia), false); void *pRemoteFunc = reme.AllocAndCopyMemory( RemoteCodeFunc, codeEndAdr - codeStartAdr, true); if (reme.AnyFailures()) { //MessageBox(hWnd, L"Remote allocation failed", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Remote allocation failed"); } else { HANDLE hRemoteThread = CreateRemoteThread(hTargetProc, NULL, 0, reinterpret_cast< LPTHREAD_START_ROUTINE >( pRemoteFunc ), pRemoteArgs, 0, NULL); if (hRemoteThread == 0) { //MessageBox(hWnd, L"Couldn't create remote thread", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine( CError::Format( GetLastError(), L"Couldn't create remote thread", L"CreateRemoteThread")); } else { if ( Redirector ) Redirector(); while(true) { DWORD dwWaitRes = WaitForSingleObject(hRemoteThread, 10000); if (dwWaitRes == WAIT_OBJECT_0) { bThreadWaitSuccess = true; break; } else if (dwWaitRes != WAIT_TIMEOUT) { bThreadWaitFailure = true; break; } //else if (IDCANCEL == MessageBox(hWnd, L"Continue waiting for remote thread to complete?", L"Win7Elevate", MB_OKCANCEL | MB_ICONQUESTION)) else { CLogger::LogLine(L"Continue waiting for remote thread to complete? : NO"); // See if it completed before the user asked to stop waiting. // Code that wasn't just a proof-of-concept would use a worker thread that could cancel the wait UI. if (WAIT_OBJECT_0 == WaitForSingleObject(hRemoteThread, 0)) { bThreadWaitSuccess = true; } break; } } if (!bThreadWaitSuccess) { // The memory in the other process could still be in use. // Freeing it now will almost certainly crash the other process. // Letting it leak is the lesser of two evils... reme.LeakMemory(); } } } } CloseHandle(hTargetProc); } } FreeLibrary(hModKernel32); if (bThreadWaitFailure) { //MessageBox(hWnd, L"Error waiting on the remote thread to complete", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Error waiting on the remote thread to complete"); } else if (bThreadWaitSuccess) { //MessageBox(hWnd, L"Remote thread completed", L"Win7Elevate", MB_OK | MB_ICONINFORMATION); CLogger::LogLine(L"Remote thread completed"); } }
void RenderSystem::init_device() { ////////////////////////Create buffer desc//////////////////////////// DXGI_MODE_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC)); bufferDesc.Width = m_ScreenWidth; bufferDesc.Height = m_ScreenHeight; bufferDesc.RefreshRate.Numerator = 60; bufferDesc.RefreshRate.Denominator = 1; bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //Create swapChain Desc DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapChainDesc.BufferDesc = bufferDesc; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.OutputWindow = GetHwnd(); swapChainDesc.Windowed = TRUE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; /////////////////////////////////////////////////////////////////////////// HRESULT hr; //Create the double buffer chain hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &m_pSwapChain, &m_pD3D11Device, NULL, &m_pD3D11DeviceContext); //DebugHR(hr); //Create back buffer, buffer also is a texture ID3D11Texture2D *pBackBuffer; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer); hr = m_pD3D11Device->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); //DebugHR(hr); ///////////////////// Set up the description of the depth buffer.//////////////////////// D3D11_TEXTURE2D_DESC depthBufferDesc; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); depthBufferDesc.Width = m_ScreenWidth; depthBufferDesc.Height = m_ScreenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; // Create the texture for the depth buffer using the filled out description. hr = m_pD3D11Device->CreateTexture2D(&depthBufferDesc, NULL, &m_pDepthStencilBuffer); //DebugHR(hr); //////////////////////////// initialize the description of the stencil state./////////////////////////////////////////////// D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing. depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the depth stencil state. hr = m_pD3D11Device->CreateDepthStencilState(&depthStencilDesc, &m_pDepthStencilState); //DebugHR(hr); // initialize the depth stencil view. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; hr = m_pD3D11Device->CreateDepthStencilView(m_pDepthStencilBuffer.Get(), &depthStencilViewDesc, &m_pDepthStencilView); //DebugHR(hr); /////////////////////////////////////////////////////////////////////////////////////////// D3D11_RASTERIZER_DESC rasterDesc; rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; // Create the rasterizer state from the description we just filled out. hr = m_pD3D11Device->CreateRasterizerState(&rasterDesc, &m_pRasterState); DebugHR(hr); /////////////////////////////////////////////////////////////////////////////// unsigned int numModes, i, numerator, denominator, stringLength; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGISurface *surface; DXGI_ADAPTER_DESC adapterDesc; // Create a DirectX graphics interface factory. CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); // Use the factory to create an adapter for the primary graphics interface (video card). factory->EnumAdapters(0, &adapter); adapter->GetDesc(&adapterDesc); m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. m_videoCardInfo = std::wstring(L"Video Card :") + adapterDesc.Description; }
HRESULT WINAPI Mine_CoCreateInstance(IN REFCLSID rclsid, IN LPUNKNOWN pUnkOuter, IN DWORD dwClsContext, IN REFIID riid, OUT LPVOID FAR* ppv) { if(CFilterMapper2::m_pFilterMapper2) { CheckPointer(ppv, E_POINTER); if(rclsid == CLSID_FilterMapper) { ASSERT(0); return REGDB_E_CLASSNOTREG; // sorry... } if(rclsid == CLSID_FilterMapper2) { if(pUnkOuter) return CLASS_E_NOAGGREGATION; if(riid == __uuidof(IUnknown)) { CFilterMapper2::m_pFilterMapper2->AddRef(); *ppv = (IUnknown*)CFilterMapper2::m_pFilterMapper2; return S_OK; } else if(riid == __uuidof(IFilterMapper2)) { CFilterMapper2::m_pFilterMapper2->AddRef(); *ppv = (IFilterMapper2*)CFilterMapper2::m_pFilterMapper2; return S_OK; } else { return E_NOINTERFACE; } } } /* else { if(rclsid == CLSID_FilterMapper2) { CFilterMapper2* pFM2 = DNew CFilterMapper2(true, false, pUnkOuter); CComPtr<IUnknown> pUnk = (IUnknown*)pFM2; return pUnk->QueryInterface(riid, ppv); } } */ if(!pUnkOuter) if(rclsid == CLSID_VideoMixingRenderer || rclsid == CLSID_VideoMixingRenderer9 || rclsid == CLSID_VideoRenderer || rclsid == CLSID_VideoRendererDefault || rclsid == CLSID_OverlayMixer)// || rclsid == CLSID_OverlayMixer2 - where is this declared?) { CMacrovisionKicker* pMK = DNew CMacrovisionKicker(NAME("CMacrovisionKicker"), NULL); CComPtr<IUnknown> pUnk = (IUnknown*)(INonDelegatingUnknown*)pMK; CComPtr<IUnknown> pInner; HRESULT hr; if(SUCCEEDED(hr = Real_CoCreateInstance(rclsid, pUnk, dwClsContext, __uuidof(IUnknown), (void**)&pInner))) { pMK->SetInner(pInner); return pUnk->QueryInterface(riid, ppv); } } return Real_CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv); }
#define RAW_SECTOR_SIZE 2352 #define MSF2UINT(hgs) ((hgs[1] * 4500) + (hgs[2] * 75) + (hgs[3])) #ifdef STANDALONE_FILTER const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = { {&MEDIATYPE_Stream, &MEDIASUBTYPE_WAVE}, }; const AMOVIESETUP_PIN sudOpPin[] = { {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut}, }; const AMOVIESETUP_FILTER sudFilter[] = { {&__uuidof(CCDDAReader), CCDDAReaderName, MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory} }; CFactoryTemplate g_Templates[] = { {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CCDDAReader>, nullptr, &sudFilter[0]} }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { SetRegKeyValue( _T("Media Type\\{e436eb83-524f-11ce-9f53-0020af0ba770}"), _T("{54A35221-2C8D-4a31-A5DF-6D809847E393}"), _T("0"), _T("0,4,,52494646,8,4,,43444441")); // "RIFFxxxxCDDA" SetRegKeyValue(
void Renderer::createRenderTarget() { ID3D11Texture2D* backBuffer; m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**) &backBuffer); m_device->CreateRenderTargetView(backBuffer, nullptr, &m_renderTargetView); backBuffer->Release(); }
void InitBackendInfo() { HRESULT hr = DX11::D3D::LoadDXGI(); if (SUCCEEDED(hr)) hr = DX11::D3D::LoadD3D(); if (FAILED(hr)) { DX11::D3D::UnloadDXGI(); return; } g_Config.backend_info.APIType = API_D3D; g_Config.backend_info.bUseMinimalMipCount = true; g_Config.backend_info.bSupportsExclusiveFullscreen = true; g_Config.backend_info.bSupportsDualSourceBlend = true; g_Config.backend_info.bSupportsPrimitiveRestart = true; g_Config.backend_info.bSupportsOversizedViewports = false; g_Config.backend_info.bSupportsBBox = false; // TODO: not implemented g_Config.backend_info.bSupportsStereoscopy = false; // TODO: not implemented IDXGIFactory* factory; IDXGIAdapter* ad; hr = DX11::PCreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(hr)) PanicAlert("Failed to create IDXGIFactory object"); // adapters g_Config.backend_info.Adapters.clear(); g_Config.backend_info.AAModes.clear(); while (factory->EnumAdapters((UINT)g_Config.backend_info.Adapters.size(), &ad) != DXGI_ERROR_NOT_FOUND) { const size_t adapter_index = g_Config.backend_info.Adapters.size(); DXGI_ADAPTER_DESC desc; ad->GetDesc(&desc); // TODO: These don't get updated on adapter change, yet if (adapter_index == g_Config.iAdapter) { std::string samples; std::vector<DXGI_SAMPLE_DESC> modes = DX11::D3D::EnumAAModes(ad); for (unsigned int i = 0; i < modes.size(); ++i) { if (i == 0) samples = _trans("None"); else if (modes[i].Quality) samples = StringFromFormat(_trans("%d samples (quality level %d)"), modes[i].Count, modes[i].Quality); else samples = StringFromFormat(_trans("%d samples"), modes[i].Count); g_Config.backend_info.AAModes.push_back(samples); } // Requires the earlydepthstencil attribute (only available in shader model 5) g_Config.backend_info.bSupportsEarlyZ = (DX11::D3D::GetFeatureLevel(ad) == D3D_FEATURE_LEVEL_11_0); } g_Config.backend_info.Adapters.push_back(UTF16ToUTF8(desc.Description)); ad->Release(); } factory->Release(); // Clear ppshaders string vector g_Config.backend_info.PPShaders.clear(); DX11::D3D::UnloadDXGI(); DX11::D3D::UnloadD3D(); }
#include "AMRSplitter.h" #ifdef REGISTER_FILTER const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = { {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}, {&MEDIATYPE_Stream, &MEDIASUBTYPE_AMR}, }; const AMOVIESETUP_PIN sudpPins[] = { {L"Input", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, _countof(sudPinTypesIn), sudPinTypesIn}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, NULL, 0, NULL} }; const AMOVIESETUP_FILTER sudFilter[] = { {&__uuidof(CAMRSplitter), AMRSplitterName, MERIT_NORMAL+1, _countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory} }; CFactoryTemplate g_Templates[] = { {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CAMRSplitter>, NULL, &sudFilter[0]} }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { return AMovieDllRegisterServer2(TRUE); } STDAPI DllUnregisterServer() {
GraphicsLayer::GraphicsLayer(HWND in_hWnd, UINT in_bbWidth, UINT in_bbHeight) throw(Exception) { // if (s_pMainLayer) { throw Exception("Graphics layer already initialized"); } s_pMainLayer = this; // Fill out swap chain desc DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Double buffering swapChainDesc.BufferCount = 1; // Backbuffer attributes swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.Width = in_bbWidth; swapChainDesc.BufferDesc.Height = in_bbHeight; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; // Buffer usage swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = in_hWnd; // No multi-sampling swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Windowed = TRUE; // Required feature levels D3D_FEATURE_LEVEL featureLevels[] = {D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_11_0}; UINT numLevels = sizeof(featureLevels)/sizeof(D3D_FEATURE_LEVEL); // Attempt to create device and swap chain if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, 0, D3D11_CREATE_DEVICE_DEBUG, featureLevels, numLevels, D3D11_SDK_VERSION, &swapChainDesc, &m_pSwapChain, &m_pDevice, &m_featureLevel, &m_pImmediateContext ))) { throw Exception("Couldn't create device and swap chain"); } // Retrieve default render target ID3D11Texture2D* pBackBuffer = NULL; if (FAILED(m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer))) { throw Exception("Couldn't retrieve back buffer"); } // Create default render target view if (FAILED(m_pDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pDefaultRT))) { throw Exception("Couldn't create default render target view"); } // Release back buffer pBackBuffer->Release(); // Create depth-stencil texture D3D11_TEXTURE2D_DESC depthTextureDesc; ZeroMemory(&depthTextureDesc, sizeof(depthTextureDesc)); depthTextureDesc.ArraySize = 1; depthTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthTextureDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthTextureDesc.Height = in_bbHeight; depthTextureDesc.Width = in_bbWidth; depthTextureDesc.MipLevels = 1; depthTextureDesc.SampleDesc.Count = 1; depthTextureDesc.Usage = D3D11_USAGE_DEFAULT; if (FAILED(m_pDevice->CreateTexture2D(&depthTextureDesc, NULL, &m_pDepthTexture))) { throw Exception("Couldn't create default depth-stencil"); } // Create depth-stencil view D3D11_DEPTH_STENCIL_VIEW_DESC depthViewDesc; ZeroMemory(&depthViewDesc, sizeof(depthViewDesc)); depthViewDesc.Format = depthTextureDesc.Format; depthViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthViewDesc.Texture2D.MipSlice = 0; if (FAILED(m_pDevice->CreateDepthStencilView(m_pDepthTexture, &depthViewDesc, &m_pDefaultDS))) { throw Exception("Couldn't create default depth-stencil view"); } // Set default render targte and depth stencil m_pImmediateContext->OMSetRenderTargets(1, &m_pDefaultRT, m_pDefaultDS); // Set viewport to cover the whole backbuffer D3D11_VIEWPORT viewport; viewport.TopLeftX = viewport.TopLeftY = 0.f; viewport.MinDepth = 0.f; viewport.MaxDepth = 1.f; viewport.Width = in_bbWidth; viewport.Height = in_bbHeight; m_pImmediateContext->RSSetViewports(1, &viewport); }
HRESULT ScaWebSearch7( __in SCA_WEB7* psw, __deref_out_z_opt LPWSTR* pswWeb, __out_opt BOOL* pfFound ) { HRESULT hr = S_OK; BOOL fInitializedCom = FALSE; BSTR bstrSites = NULL; BSTR bstrAppHostRoot = NULL; IAppHostAdminManager *pAdminMgr = NULL; IAppHostElement *pSites = NULL; IAppHostElementCollection *pCollection = NULL; IAppHostElement *pSite = NULL; if (NULL != pswWeb) { ReleaseNullStr(*pswWeb); } if (NULL != pfFound) { *pfFound = FALSE; } hr = ::CoInitialize(NULL); ExitOnFailure(hr, "Failed to initialize COM"); fInitializedCom = TRUE; hr = CoCreateInstance(__uuidof(AppHostAdminManager), NULL, CLSCTX_INPROC_SERVER, __uuidof(IAppHostAdminManager), reinterpret_cast<void**> (&pAdminMgr)); if (REGDB_E_CLASSNOTREG == hr) { WcaLog(LOGMSG_VERBOSE, "AppHostAdminManager was not registered, cannot find site."); hr = S_OK; ExitFunction(); } ExitOnFailure(hr, "Failed to CoCreate IAppHostAdminManager"); bstrSites = ::SysAllocString(IIS_CONFIG_SITES_SECTION); ExitOnNull(bstrSites, hr, E_OUTOFMEMORY, "Failed to allocate sites string."); bstrAppHostRoot = ::SysAllocString(IIS_CONFIG_APPHOST_ROOT); ExitOnNull(bstrAppHostRoot, hr, E_OUTOFMEMORY, "Failed to allocate host root string."); hr = pAdminMgr->GetAdminSection(bstrSites, bstrAppHostRoot, &pSites); ExitOnFailure(hr, "Failed get sites section"); ExitOnNull(pSites, hr, ERROR_FILE_NOT_FOUND, "Failed get sites section object"); hr = pSites->get_Collection(&pCollection); ExitOnFailure(hr, "Failed get sites collection"); // not explicitly doing a Description search if (-1 != psw->iSiteId) { if (MSI_NULL_INTEGER == psw->iSiteId) { // Enumerate sites & determine if the binding matches hr = Iis7EnumAppHostElements(pCollection, EnumSiteCompareBinding, psw, &pSite, NULL); ExitOnFailure(hr, "Failed locate site by ID"); } else { // Find a site with ID matches hr = Iis7FindAppHostElementInteger(pCollection, IIS_CONFIG_SITE, IIS_CONFIG_ID, psw->iSiteId, &pSite, NULL); ExitOnFailure(hr, "Failed locate site by ID"); } } if (NULL == pSite) { // Find a site with Name that matches hr = Iis7FindAppHostElementString(pCollection, IIS_CONFIG_SITE, IIS_CONFIG_NAME, psw->wzDescription, &pSite, NULL); ExitOnFailure(hr, "Failed locate site by ID"); } if (NULL != pSite) { if (NULL != pfFound) { *pfFound = TRUE; } if (NULL != pswWeb) { // We found a site, return its description hr = Iis7GetPropertyString(pSite, IIS_CONFIG_NAME, pswWeb); ExitOnFailure(hr, "Failed get site name"); } } LExit: ReleaseNullObject(pAdminMgr); ReleaseNullObject(pSites); ReleaseNullObject(pCollection); ReleaseNullObject(pSite); ReleaseBSTR(bstrAppHostRoot); ReleaseBSTR(bstrSites); if (fInitializedCom) { ::CoUninitialize(); } return hr; }
#include <Audioclient.h> #include <stdint.h> #include <algorithm> #include "cores/AudioEngine/Utils/AEUtil.h" #include "utils/log.h" #include "utils/TimeUtils.h" #include "cores/AudioEngine/Utils/AEDeviceInfo.h" #include <Mmreg.h> #include "utils/StringUtils.h" #ifdef TARGET_WINDOWS_DESKTOP # pragma comment(lib, "Avrt.lib") #endif // TARGET_WINDOWS_DESKTOP const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient); const IID IID_IAudioClock = __uuidof(IAudioClock); DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14); DEFINE_PROPERTYKEY(PKEY_Device_EnumeratorName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 24); extern const char *WASAPIErrToStr(HRESULT err); #define EXIT_ON_FAILURE(hr, reason, ...) if(FAILED(hr)) {CLog::Log(LOGERROR, reason " - %s", __VA_ARGS__, WASAPIErrToStr(hr)); goto failed;} CAESinkWASAPI::CAESinkWASAPI() : m_needDataEvent(0), m_pDevice(NULL), m_pAudioClient(NULL), m_pRenderClient(NULL), m_pAudioClock(NULL), m_encodedChannels(0), m_encodedSampleRate(0),
/*------------------------------------------- バック バッファの初期化(バック バッファを描画ターゲットに設定) --------------------------------------------*/ HRESULT InitBackBuffer(void) { HRESULT hr; // スワップ・チェインから最初のバック・バッファを取得する ID3D11Texture2D *pBackBuffer; // バッファのアクセスに使うインターフェイス hr = g_pSwapChain->GetBuffer( 0, // バック・バッファの番号 __uuidof(ID3D11Texture2D), // バッファにアクセスするインターフェイス (LPVOID*)&pBackBuffer); // バッファを受け取る変数 if(FAILED(hr)) return DXTRACE_ERR(L"InitBackBuffer g_pSwapChain->GetBuffer", hr); // 失敗 // バック・バッファの情報 D3D11_TEXTURE2D_DESC descBackBuffer; pBackBuffer->GetDesc(&descBackBuffer); // バック・バッファの描画ターゲット・ビューを作る hr = g_pD3DDevice->CreateRenderTargetView( pBackBuffer, // ビューでアクセスするリソース NULL, // 描画ターゲット・ビューの定義 &g_pRenderTargetView); // 描画ターゲット・ビューを受け取る変数 SAFE_RELEASE(pBackBuffer); // 以降、バック・バッファは直接使わないので解放 if(FAILED(hr)) return DXTRACE_ERR(L"InitBackBuffer g_pD3DDevice->CreateRenderTargetView", hr); // 失敗 // 深度/ステンシル・テクスチャの作成 D3D11_TEXTURE2D_DESC descDepth = descBackBuffer; // descDepth.Width = descBackBuffer.Width; // 幅 // descDepth.Height = descBackBuffer.Height; // 高さ descDepth.MipLevels = 1; // ミップマップ・レベル数 descDepth.ArraySize = 1; // 配列サイズ descDepth.Format = DXGI_FORMAT_D32_FLOAT; // フォーマット(深度のみ) // descDepth.SampleDesc.Count = 1; // マルチサンプリングの設定 // descDepth.SampleDesc.Quality = 0; // マルチサンプリングの品質 descDepth.Usage = D3D11_USAGE_DEFAULT; // デフォルト使用法 descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; // 深度/ステンシルとして使用 descDepth.CPUAccessFlags = 0; // CPUからはアクセスしない descDepth.MiscFlags = 0; // その他の設定なし hr = g_pD3DDevice->CreateTexture2D( &descDepth, // 作成する2Dテクスチャの設定 NULL, // &g_pDepthStencil); // 作成したテクスチャを受け取る変数 if (FAILED(hr)) return DXTRACE_ERR(L"InitBackBuffer g_pD3DDevice->CreateTexture2D", hr); // 失敗 // 深度/ステンシル ビューの作成 D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; descDSV.Format = descDepth.Format; // ビューのフォーマット descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Flags = 0; descDSV.Texture2D.MipSlice = 0; hr = g_pD3DDevice->CreateDepthStencilView( g_pDepthStencil, // 深度/ステンシル・ビューを作るテクスチャ &descDSV, // 深度/ステンシル・ビューの設定 &g_pDepthStencilView); // 作成したビューを受け取る変数 if (FAILED(hr)) return DXTRACE_ERR(L"InitBackBuffer g_pD3DDevice->CreateDepthStencilView", hr); // 失敗 // ビューポートの設定 g_ViewPort[0].TopLeftX = 0.0f; // ビューポート領域の左上X座標。 g_ViewPort[0].TopLeftY = 0.0f; // ビューポート領域の左上Y座標。 g_ViewPort[0].Width = (FLOAT)descBackBuffer.Width; // ビューポート領域の幅 g_ViewPort[0].Height = (FLOAT)descBackBuffer.Height; // ビューポート領域の高さ g_ViewPort[0].MinDepth = 0.0f; // ビューポート領域の深度値の最小値 g_ViewPort[0].MaxDepth = 1.0f; // ビューポート領域の深度値の最大値 // 定数バッファを更新 // 射影変換行列(パースペクティブ(透視法)射影) XMMATRIX mat = XMMatrixPerspectiveFovLH( XMConvertToRadians(30.0f), // 視野角30° (float)descBackBuffer.Width / (float)descBackBuffer.Height, // アスペクト比 1.0f, // 前方投影面までの距離 400.0f); // 後方投影面までの距離 mat = XMMatrixTranspose(mat); XMStoreFloat4x4(&g_cbCBuffer.Projection, mat); //サイズを保存 g_sizeWindow.cx = descBackBuffer.Width; g_sizeWindow.cy = descBackBuffer.Height; return S_OK; }
//----------------------------------------------------------------------------- // Resize // Resizes the graphics device (along with the back buffer ) //----------------------------------------------------------------------------- void CD3DDevice::Resize( uint nWidth, uint nHeight ) { /* We handle the resizing and back buffer 100% natively, just like OpenGL, rather than creating D3DRenderTargets, etc */ ////////////////////////////////////////// // First release all the current default objects if( m_pContext != NULL ) m_pContext->OMSetRenderTargets( 0, 0, 0 ); SAFE_RELEASE( m_pDefaultRenderTargetView ); SAFE_RELEASE( m_pDefaultDepthStencilResource ); SAFE_RELEASE( m_pDefaultDepthStencilView ); ASSERT( m_pSwapChain ); ////////////////////////////////////////// // Then recreate them HRESULT hr = S_OK; // TODO: Don't use these hardcoded values int nAACount = 1, nAAQuality = 0; ////////////////////////////////////////// // Resize the swap chain m_pSwapChain->ResizeBuffers( 2, nWidth, nHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0 ); // First, null it out and resize ////////////////////////////////////////////// // Create the new render target ID3D11Texture2D* pBackBuffer = NULL; hr = m_pSwapChain->GetBuffer( 0, __uuidof( pBackBuffer ), (void**)(&pBackBuffer) ); hr = m_pDevice->CreateRenderTargetView( pBackBuffer, NULL, &m_pDefaultRenderTargetView ); ASSERT( hr == S_OK ); ASSERT( m_pDefaultRenderTargetView ); SAFE_RELEASE( pBackBuffer ); ///////////////////////////////////////////// // Create the depth stencil texture and view D3D11_TEXTURE2D_DESC descDepth; descDepth.Width = nWidth; descDepth.Height = nHeight; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = nAACount; descDepth.SampleDesc.Quality = nAAQuality; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = m_pDevice->CreateTexture2D( &descDepth, 0, &m_pDefaultDepthStencilResource ); ASSERT( m_pDefaultDepthStencilResource); if(FAILED(hr)) { // TODO: Handle gracefully MessageBox( 0, L"DepthStencil texture could not be created", L"Error", 0 ); return; } // Create depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; descDSV.Format = descDepth.Format; descDSV.ViewDimension = nAACount > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; descDSV.Flags = 0; hr = m_pDevice->CreateDepthStencilView( m_pDefaultDepthStencilResource, &descDSV, &m_pDefaultDepthStencilView ); ASSERT( m_pDefaultDepthStencilView ); if(FAILED(hr)) { // TODO: Handle gracefully MessageBox( 0, L"DepthStencilView could not be created", L"Error", 0 ); return; } // Set up the view port SetViewport( nWidth, nHeight ); // Finally restore the default render/depth targets m_pContext->OMSetRenderTargets( 1, &m_pDefaultRenderTargetView, m_pDefaultDepthStencilView ); }
HRESULT WindowsFirewallAddApp( IN INetFwProfile* fwProfile, IN const wchar_t* fwProcessImageFileName, IN const wchar_t* fwName ) { HRESULT hr = S_OK; BOOL fwAppEnabled; BSTR fwBstrName = NULL; BSTR fwBstrProcessImageFileName = NULL; INetFwAuthorizedApplication* fwApp = NULL; INetFwAuthorizedApplications* fwApps = NULL; assert(fwProfile != NULL); assert(fwProcessImageFileName != NULL); assert(fwName != NULL); // First check to see if the application is already authorized. hr = WindowsFirewallAppIsEnabled( fwProfile, fwProcessImageFileName, &fwAppEnabled ); if (FAILED(hr)) { MYTRACE(ACE_TEXT("WindowsFirewallAppIsEnabled failed: 0x%08lx\n"), hr); goto error; } // Only add the application if it isn't already authorized. if (!fwAppEnabled) { // Retrieve the authorized application collection. hr = fwProfile->get_AuthorizedApplications(&fwApps); if (FAILED(hr)) { MYTRACE(ACE_TEXT("get_AuthorizedApplications failed: 0x%08lx\n"), hr); goto error; } // Create an instance of an authorized application. hr = CoCreateInstance( __uuidof(NetFwAuthorizedApplication), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwAuthorizedApplication), (void**)&fwApp ); if (FAILED(hr)) { MYTRACE(ACE_TEXT("CoCreateInstance failed: 0x%08lx\n"), hr); goto error; } // Allocate a BSTR for the process image file name. fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName); if (fwBstrProcessImageFileName == NULL) { hr = E_OUTOFMEMORY; MYTRACE(ACE_TEXT("SysAllocString failed: 0x%08lx\n"), hr); goto error; } // Set the process image file name. hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName); if (FAILED(hr)) { MYTRACE(ACE_TEXT("put_ProcessImageFileName failed: 0x%08lx\n"), hr); goto error; } // Allocate a BSTR for the application friendly name. fwBstrName = SysAllocString(fwName); if (SysStringLen(fwBstrName) == 0) { hr = E_OUTOFMEMORY; MYTRACE(ACE_TEXT("SysAllocString failed: 0x%08lx\n"), hr); goto error; } // Set the application friendly name. hr = fwApp->put_Name(fwBstrName); if (FAILED(hr)) { MYTRACE(ACE_TEXT("put_Name failed: 0x%08lx\n"), hr); goto error; } // Set scope (added by bdr -- begin) //hr = fwApp->put_Scope(NET_FW_SCOPE_ALL); //if (FAILED(hr)) //{ // MYTRACE(ACE_TEXT("put_Scope failed: 0x%08lx\n"), hr); // goto error; //} //hr = fwApp->put_RemoteAddresses(L"*"); //if (FAILED(hr)) //{ // MYTRACE(ACE_TEXT("put_Scope failed: 0x%08lx\n"), hr); // goto error; //} // Set scope (added by bdr -- end) // Add the application to the collection. hr = fwApps->Add(fwApp); if (FAILED(hr)) { MYTRACE(ACE_TEXT("Add failed: 0x%08lx\n"), hr); goto error; } MYTRACE(ACE_TEXT( "Authorized application %lS is now enabled in the firewall.\n"), fwProcessImageFileName ); } error: // Free the BSTRs. SysFreeString(fwBstrName); SysFreeString(fwBstrProcessImageFileName); // Release the authorized application instance. if (fwApp != NULL) { fwApp->Release(); } // Release the authorized application collection. if (fwApps != NULL) { fwApps->Release(); } return hr; }
HRESULT DoTheWork (INetSharingManager * pNSM) { // add a port mapping to every firewalled or shared connection INetSharingEveryConnectionCollection * pNSECC = NULL; HRESULT hr = pNSM->get_EnumEveryConnection (&pNSECC); int LastErrorCode = 0; if (!pNSECC) return ICS_Error_FailGetEvery; else { // enumerate connections IEnumVARIANT * pEV = NULL; IUnknown * pUnk = NULL; hr = pNSECC->get__NewEnum (&pUnk); if (pUnk) { hr = pUnk->QueryInterface (__uuidof(IEnumVARIANT), (void**)&pEV); pUnk->Release(); }else{ return ICS_Error_FailGetNewEnum; } if (pEV) { VARIANT v; VariantInit (&v); while (S_OK == pEV->Next (1, &v, NULL)) { if (V_VT (&v) == VT_UNKNOWN) { INetConnection * pNC = NULL; V_UNKNOWN (&v)->QueryInterface (__uuidof(INetConnection), (void**)&pNC); if (pNC) { INetConnectionProps * pNCP = NULL; pNSM->get_NetConnectionProps (pNC, &pNCP); if (!pNCP) wprintf (L"failed to get NetConnectionProps!\r\n"); else { // check properties for firewalled or shared connection NETCON_MEDIATYPE MediaType; pNCP->get_MediaType(&MediaType); NETCON_STATUS Status; pNCP->get_Status(&Status); BSTR DevName; pNCP->get_DeviceName(&DevName); if (MediaType & (NCM_LAN | NCM_SHAREDACCESSHOST_LAN | NCM_PHONE) && Status == NCS_CONNECTED && QString(_com_util::ConvertBSTRToString(DevName)).indexOf("hosted network", 0, Qt::CaseInsensitive)==-1 && QString(_com_util::ConvertBSTRToString(DevName)).indexOf("virtual", 0, Qt::CaseInsensitive)==-1 && QString(_com_util::ConvertBSTRToString(DevName)).indexOf("teamviewer", 0, Qt::CaseInsensitive)==-1) { // got a shared/firewalled connection INetSharingConfiguration * pNSC = NULL; hr = pNSM->get_INetSharingConfigurationForINetConnection (pNC, &pNSC); if (!pNSC) wprintf (L"can't make INetSharingConfiguration object!\r\n"); else { hr = pNSC->EnableSharing(ICSSHARINGTYPE_PRIVATE); if(hr!=S_OK){ LastErrorCode = ICS_Error_EnableSharing; }else{ BSTR Name; pNCP->get_Name(&Name); QMessageBox msg; msg.setText(QString("Network: %1 %2 %3").arg(_com_util::ConvertBSTRToString(Name)).arg(_com_util::ConvertBSTRToString(DevName)).arg(Status)); msg.exec(); return 0; } pNSC->Release(); } } pNCP->Release(); } pNC->Release(); } } VariantClear (&v); } pEV->Release(); }else{ return ICS_Error_FailGetEnumVariant; } pNSECC->Release(); } if(LastErrorCode!=0) return LastErrorCode; return hr; }
HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile, BOOL bInvokeUAE) { HRESULT hr = S_OK; INetFwMgr* fwMgr = NULL; INetFwPolicy* fwPolicy = NULL; assert(fwProfile != NULL); *fwProfile = NULL; if(bInvokeUAE) hr = CoCreateInstanceAsAdmin(NULL, __uuidof(NetFwMgr), __uuidof(INetFwMgr), (void**)&fwMgr); else { // Create an instance of the firewall settings manager. hr = CoCreateInstance( __uuidof(NetFwMgr), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwMgr), (void**)&fwMgr ); } if (FAILED(hr)) { MYTRACE(ACE_TEXT("CoCreateInstance failed: 0x%08lx\n"), hr); goto error; } // Retrieve the local firewall policy. hr = fwMgr->get_LocalPolicy(&fwPolicy); if (FAILED(hr)) { MYTRACE(ACE_TEXT("get_LocalPolicy failed: 0x%08lx\n"), hr); goto error; } // Retrieve the firewall profile currently in effect. hr = fwPolicy->get_CurrentProfile(fwProfile); if (FAILED(hr)) { MYTRACE(ACE_TEXT("get_CurrentProfile failed: 0x%08lx\n"), hr); goto error; } error: // Release the local firewall policy. if (fwPolicy != NULL) { fwPolicy->Release(); } // Release the firewall settings manager. if (fwMgr != NULL) { fwMgr->Release(); } return hr; }
bool Common::isXInputController( const GUID* pGuidProductFromDirectInput ) { IWbemLocator* pIWbemLocator = NULL; IEnumWbemClassObject* pEnumDevices = NULL; IWbemClassObject* pDevices[20] = {0}; IWbemServices* pIWbemServices = NULL; BSTR bstrNamespace = NULL; BSTR bstrDeviceID = NULL; BSTR bstrClassName = NULL; DWORD uReturned = 0; bool bIsXinputDevice= false; UINT iDevice = 0; VARIANT var; HRESULT hr; //unsigned int t0 = Time::getTimeAsMilliseconds(); // CoInit if needed hr = CoInitialize(NULL); bool bCleanupCOM = SUCCEEDED(hr); //unsigned int t1 = Time::getTimeAsMilliseconds(); // Create WMI hr = CoCreateInstance( __uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*) &pIWbemLocator); if( FAILED(hr) || pIWbemLocator == NULL ) goto LCleanup; //unsigned int t2 = Time::getTimeAsMilliseconds(); bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto LCleanup; bstrClassName = SysAllocString( L"Win32_PNPEntity" ); if( bstrClassName == NULL ) goto LCleanup; bstrDeviceID = SysAllocString( L"DeviceID" ); if( bstrDeviceID == NULL ) goto LCleanup; // Connect to WMI hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L, 0L, NULL, NULL, &pIWbemServices ); if( FAILED(hr) || pIWbemServices == NULL ) goto LCleanup; //unsigned int t3 = Time::getTimeAsMilliseconds(); // Switch security level to IMPERSONATE. CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE ); hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices ); if( FAILED(hr) || pEnumDevices == NULL ) goto LCleanup; //unsigned int t4 = Time::getTimeAsMilliseconds(); // Loop over all devices for( ;; ) { // Get 20 at a time hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned ); if( FAILED(hr) ) goto LCleanup; if( uReturned == 0 ) break; for( iDevice=0; iDevice<uReturned; iDevice++ ) { // For each device, get its device ID hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL ); if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL ) { // Check if the device ID contains "IG_". If it does, then it's an XInput device // This information can not be found from DirectInput if( wcsstr( var.bstrVal, L"IG_" ) ) { // If it does, then get the VID/PID from var.bstrVal DWORD dwPid = 0, dwVid = 0; WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" ); #ifdef _MSC_VER #pragma warning( push ) #pragma warning ( disable : 4996 ) #endif if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 ) dwVid = 0; WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" ); if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 ) dwPid = 0; #ifdef _MSC_VER #pragma warning(pop) #endif // Compare the VID/PID to the DInput device DWORD dwVidPid = MAKELONG( dwVid, dwPid ); if( dwVidPid == pGuidProductFromDirectInput->Data1 ) { bIsXinputDevice = true; goto LCleanup; } } } SAFE_RELEASE( pDevices[iDevice] ); } } LCleanup: //unsigned int t5 = Time::getTimeAsMilliseconds(); if(bstrNamespace) SysFreeString(bstrNamespace); if(bstrDeviceID) SysFreeString(bstrDeviceID); if(bstrClassName) SysFreeString(bstrClassName); for( iDevice=0; iDevice<20; iDevice++ ) SAFE_RELEASE( pDevices[iDevice] ); SAFE_RELEASE( pEnumDevices ); SAFE_RELEASE( pIWbemLocator ); SAFE_RELEASE( pIWbemServices ); if( bCleanupCOM ) CoUninitialize(); //unsigned int t6 = Time::getTimeAsMilliseconds(); /*t1 = t1-t0; t2 = t2-t0; t3 = t3-t0; t4 = t4-t0; t5 = t5-t0; t6 = t6-t0; t0 = 0; */ return bIsXinputDevice; }
HRESULT WindowsFirewallRemoveApp( IN INetFwProfile* fwProfile, IN const wchar_t* fwProcessImageFileName ) { HRESULT hr = S_OK; BOOL fwAppEnabled; BSTR fwBstrName = NULL; BSTR fwBstrProcessImageFileName = NULL; INetFwAuthorizedApplication* fwApp = NULL; INetFwAuthorizedApplications* fwApps = NULL; assert(fwProfile != NULL); assert(fwProcessImageFileName != NULL); // First check to see if the application is already authorized. hr = WindowsFirewallAppIsEnabled( fwProfile, fwProcessImageFileName, &fwAppEnabled ); if (FAILED(hr)) { MYTRACE(ACE_TEXT("WindowsFirewallAppIsEnabled failed: 0x%08lx\n"), hr); goto error; } // Only remove the application if it is already authorized. if (fwAppEnabled) { // Retrieve the authorized application collection. hr = fwProfile->get_AuthorizedApplications(&fwApps); if (FAILED(hr)) { MYTRACE(ACE_TEXT("get_AuthorizedApplications failed: 0x%08lx\n"), hr); goto error; } // Create an instance of an authorized application. hr = CoCreateInstance( __uuidof(NetFwAuthorizedApplication), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwAuthorizedApplication), (void**)&fwApp ); if (FAILED(hr)) { MYTRACE(ACE_TEXT("CoCreateInstance failed: 0x%08lx\n"), hr); goto error; } // Allocate a BSTR for the process image file name. fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName); if (fwBstrProcessImageFileName == NULL) { hr = E_OUTOFMEMORY; MYTRACE(ACE_TEXT("SysAllocString failed: 0x%08lx\n"), hr); goto error; } // Add the application to the collection. hr = fwApps->Remove(fwBstrProcessImageFileName); if (FAILED(hr)) { MYTRACE(ACE_TEXT("Add failed: 0x%08lx\n"), hr); goto error; } MYTRACE(ACE_TEXT( "Authorized application %lS is now removed in the firewall.\n"), fwProcessImageFileName ); } error: // Free the BSTRs. SysFreeString(fwBstrName); SysFreeString(fwBstrProcessImageFileName); // Release the authorized application instance. if (fwApp != NULL) { fwApp->Release(); } // Release the authorized application collection. if (fwApps != NULL) { fwApps->Release(); } return hr; }
bool DX11Render::Initialize(int screenWidth, int screenHeight, bool fullscreen, HWND hwnd) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, numerator, denominator, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; ID3D11Texture2D* backBufferPtr; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; float fieldOfView, screenAspect; m_vsync_enabled = VSYNC_ENABLED; //Dx Graphics interface factory result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) return false; //Factory is used to create adapter result = factory->EnumAdapters(0, &adapter); if(FAILED(result)) return false; //Enumerate the adapter output (monitor) result = adapter->EnumOutputs(0, &adapterOutput); if(FAILED(result)) return false; //Get # modes that fit format result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if(FAILED(result)) return false; //create list for display modes displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) return false; //fill mode list result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if(FAILED(result)) return false; //go through list and find one that matches current monitor settings for(unsigned int i = 0; i < numModes; i++) { if(displayModeList[i].Width == (unsigned int)screenWidth) { if(displayModeList[i].Height == (unsigned int)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } //Get adapter desc. result = adapter->GetDesc(&adapterDesc); if(FAILED(result)) return false; //Get MB of video card m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //Convert Video Card desc to char array error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if(error != 0) return false; //release video card data delete [] displayModeList; displayModeList = 0; //Not needed, will go out of scope right after? adapterOutput->Release(); adapterOutput = 0; //Not needed, will go out of scope right after? adapter->Release(); adapter = 0; //Not needed, will go out of scope right after? factory->Release(); factory = 0; //Not needed, will go out of scope right after? //init swap chain ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; if(m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } //set scan line and scaling swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //set buffer usage swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //set handle swapChainDesc.OutputWindow = hwnd; //turn multisample off swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; //set fullscreen if(fullscreen) swapChainDesc.Windowed = false; else swapChainDesc.Windowed = true; //set swap effect swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //dont set flags swapChainDesc.Flags = 0; //set dx level featureLevel = D3D_FEATURE_LEVEL_11_0; //Create the swap chain, d3d device and device context result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if(FAILED(result)) return false; //get pointer to back buffer result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if(FAILED(result)) return false; //create render target result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); if(FAILED(result)) return false; //release pointer to back buffer backBufferPtr->Release(); backBufferPtr = 0; //Setup depth buffer desc. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; //create depth buffer result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if(FAILED(result)) return false; //setup depth stencil desc. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing. depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; //create depth stencil result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if(FAILED(result)) return false; //set the depth stencil state m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); //create stencil view desc ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; //create depth stencil view result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if(FAILED(result)) return false; //bind render target view and depth stencil buffer to output m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); //create raster control desc. rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; //create raster state result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if(FAILED(result)) return false; //now set state m_deviceContext->RSSetState(m_rasterState); //setup viewport viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; //create viewport m_deviceContext->RSSetViewports(1, &viewport); //setup projetion matrix fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; //create projection matrix D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, SCREEN_NEAR, SCREEN_DEPTH); //create world matrix D3DXMatrixIdentity(&m_worldMatrix); //create orthogonal projection matrix D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, SCREEN_NEAR, SCREEN_DEPTH); //Tell someone we did well MessageManager::Instance()->NotifyHandlers(DEFAULT_MSG, "Default:\t DX11Renderer Init Complete."); return true; }
HRESULT WindowsFirewallPortAdd( IN INetFwProfile* fwProfile, IN LONG portNumber, IN NET_FW_IP_PROTOCOL ipProtocol, IN const wchar_t* name ) { HRESULT hr = S_OK; BOOL fwPortEnabled; BSTR fwBstrName = NULL; INetFwOpenPort* fwOpenPort = NULL; INetFwOpenPorts* fwOpenPorts = NULL; assert(fwProfile != NULL); assert(name != NULL); // First check to see if the port is already added. hr = WindowsFirewallPortIsEnabled( fwProfile, portNumber, ipProtocol, &fwPortEnabled ); if (FAILED(hr)) { MYTRACE(ACE_TEXT("WindowsFirewallPortIsEnabled failed: 0x%08lx\n"), hr); goto error; } // Only add the port if it isn't already added. if (!fwPortEnabled) { // Retrieve the collection of globally open ports. hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts); if (FAILED(hr)) { MYTRACE(ACE_TEXT("get_GloballyOpenPorts failed: 0x%08lx\n"), hr); goto error; } // Create an instance of an open port. hr = CoCreateInstance( __uuidof(NetFwOpenPort), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwOpenPort), (void**)&fwOpenPort ); if (FAILED(hr)) { MYTRACE(ACE_TEXT("CoCreateInstance failed: 0x%08lx\n"), hr); goto error; } // Set the port number. hr = fwOpenPort->put_Port(portNumber); if (FAILED(hr)) { MYTRACE(ACE_TEXT("put_Port failed: 0x%08lx\n"), hr); goto error; } // Set the IP protocol. hr = fwOpenPort->put_Protocol(ipProtocol); if (FAILED(hr)) { MYTRACE(ACE_TEXT("put_Protocol failed: 0x%08lx\n"), hr); goto error; } // Allocate a BSTR for the friendly name of the port. fwBstrName = SysAllocString(name); if (SysStringLen(fwBstrName) == 0) { hr = E_OUTOFMEMORY; MYTRACE(ACE_TEXT("SysAllocString failed: 0x%08lx\n"), hr); goto error; } // Set the friendly name of the port. hr = fwOpenPort->put_Name(fwBstrName); if (FAILED(hr)) { MYTRACE(ACE_TEXT("put_Name failed: 0x%08lx\n"), hr); goto error; } // Opens the port and adds it to the collection. hr = fwOpenPorts->Add(fwOpenPort); if (FAILED(hr)) { MYTRACE(ACE_TEXT("Add failed: 0x%08lx\n"), hr); goto error; } MYTRACE(ACE_TEXT("Port %ld is now open in the firewall.\n"), portNumber); } error: // Free the BSTR. SysFreeString(fwBstrName); // Release the open port instance. if (fwOpenPort != NULL) { fwOpenPort->Release(); } // Release the globally open ports collection. if (fwOpenPorts != NULL) { fwOpenPorts->Release(); } return hr; }
UINT num, size; Gdiplus::GetImageEncodersSize(&num, &size); Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size)); Gdiplus::GetImageEncoders(num, size, pImageCodecInfo); bool found = false; for (UINT ix = 0; !found && ix < num; ++ix) { if (0 == _wcsicmp(pImageCodecInfo[ix].MimeType, format) == 0) { *pClsid = pImageCodecInfo[ix].Clsid; found = true; } } free(pImageCodecInfo); return found; } typedef _com_ptr_t<_com_IIID<IStream, &__uuidof(IStream)>> IStreamSmartPtr; void test32Bmp(const void* buffer, int width, int height){ unsigned int linebyte = (((width << 5) + 31) >> 5) << 2; unsigned int lineInval = 4 - ((width << 5) >> 3) & 3; unsigned int sum = linebyte * height; //unsigned int total = width << 5 >> 3 * height;// width * 32 / 8 * height; unsigned int total = width * 4 * height; Gdiplus::Bitmap* pBitmap = NULL; IStream* pStream;
HRESULT CSRKeyColumnUsage::Execute(LONG *pcRowsAffected, ULONG cRestrictions, const VARIANT *rgRestrictions) { ATLTRACE2(atlTraceDBProvider, 2, "CSRKeyColumnUsage::Execute()\n"); //// int cci_connection_handle = -999; char tableName[128] = {'\0', }; HRESULT hr = E_FAIL; //// hr = GetConnectionHandleFromSessionObject(cci_connection_handle); if (FAILED(hr)) return hr; GetRestrictions(cRestrictions, rgRestrictions, tableName); //// int cci_return_code = -999; int cci_request_handle = 0; T_CCI_ERROR cci_error_buffer; //// #if 1 cci_return_code = cci_schema_info ( cci_connection_handle, CCI_SCH_PRIMARY_KEY, (tableName[0]? tableName:NULL), NULL, // no attribute name is specified. CCI_CLASS_NAME_PATTERN_MATCH, &cci_error_buffer ); #endif if (cci_return_code < 0) { ATLTRACE2(atlTraceDBProvider, 2, "CSRPrimaryKeys::cci_schema_info() FAILED! \n"); return RaiseError(E_FAIL, 1, __uuidof(IDBSchemaRowset), cci_error_buffer.err_msg); } cci_request_handle = cci_return_code; cci_return_code = cci_cursor(cci_request_handle, 1, CCI_CURSOR_FIRST, &cci_error_buffer); if (cci_return_code < 0) { if (cci_return_code == CCI_ER_NO_MORE_DATA) { cci_close_req_handle(cci_request_handle); return S_OK; } else { cci_close_req_handle(cci_request_handle); return RaiseError(E_FAIL, 1, __uuidof(IDBSchemaRowset), cci_error_buffer.err_msg); } } while (1) { CKeyColumnUsageRow row; hr = FetchData(cci_request_handle, row); if (FAILED(hr)) return hr; if (hr == S_OK) { _ATLTRY { size_t position = 0; for (position = 0; position < m_rgRowData.GetCount() ; position++) { int result = CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNOREKANATYPE | NORM_IGNOREWIDTH | SORT_STRINGSORT, m_rgRowData[position].GetConstraintName(), -1, row.GetConstraintName(), -1); if ( result == CSTR_GREATER_THAN ) { break; } else if (result == CSTR_EQUAL) { result = CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNOREKANATYPE | NORM_IGNOREWIDTH | SORT_STRINGSORT, m_rgRowData[position].GetTableName(), -1, row.GetTableName(), -1); if (result == CSTR_GREATER_THAN) break; else if (result == CSTR_EQUAL) { if (m_rgRowData[position].GetOrdinalPosition() >= row.GetOrdinalPosition()) break; } } } m_rgRowData.InsertAt(position, row); } _ATLCATCHALL() { cci_close_req_handle(cci_request_handle); return E_OUTOFMEMORY; } } cci_return_code = cci_cursor(cci_request_handle, 1, CCI_CURSOR_CURRENT, &cci_error_buffer); if (cci_return_code < 0) { if (cci_return_code == CCI_ER_NO_MORE_DATA) { cci_close_req_handle(cci_request_handle); return S_OK; } else { cci_close_req_handle(cci_request_handle); return RaiseError(E_FAIL, 1, __uuidof(IDBSchemaRowset), cci_error_buffer.err_msg); } } }