{"text":"\/* The Halfling Project - A Graphics Engine and Projects\n *\n * The Halfling Project is the legal property of Adrian Astley\n * Copyright Adrian Astley 2013\n *\/\n\n#include \"deferred_shading_demo\/deferred_shading_demo.h\"\n\n#include \"deferred_shading_demo\/shader_constants.h\"\n\n#include \n#include \n\n\nnamespace DeferredShadingDemo {\n\nvoid DeferredShadingDemo::DrawFrame(double deltaTime) {\n\tRenderMainPass();\n\tRenderHUD();\n\n\tuint syncInterval = m_vsync ? 1 : 0;\n\tm_swapChain->Present(syncInterval, 0);\n}\n\nvoid DeferredShadingDemo::RenderMainPass() {\n\t\/\/ Clear the material list\n\tm_frameMaterialList.clear();\n\n\t\/\/ Bind the gbufferRTVs and depth\/stencil view to the pipeline.\n\tm_immediateContext->OMSetRenderTargets(2, &m_gBufferRTVs[0], m_depthStencilBuffer->GetDepthStencil());\n\n\t\/\/ Clear the Render Targets and DepthStencil\n\tm_immediateContext->ClearRenderTargetView(m_renderTargetView, DirectX::Colors::LightGray);\n\tfor (auto gbufferRTV : m_gBufferRTVs) {\n\t\tm_immediateContext->ClearRenderTargetView(gbufferRTV, DirectX::Colors::Black);\n\t}\n\tm_immediateContext->ClearDepthStencilView(m_depthStencilBuffer->GetDepthStencil(), D3D11_CLEAR_DEPTH, 0.0f, 0);\n\n\t\/\/ Set States\n\tm_immediateContext->PSSetSamplers(0, 1, &m_diffuseSampleState);\n\tfloat blendFactor[4] = {1.0f, 1.0f, 1.0f, 1.0f};\n\tm_immediateContext->OMSetBlendState(m_blendStates.BlendDisabled(), blendFactor, 0xFFFFFFFF);\n\tm_immediateContext->OMSetDepthStencilState(m_depthStencilStates.ReverseDepthWriteEnabled(), 0);\n\tID3D11RasterizerState *rasterState = m_wireframe ? m_rasterizerStates.Wireframe() : m_rasterizerStates.BackFaceCull();\n\tm_immediateContext->RSSetState(rasterState);\n\n\t\/\/ Set the vertex and pixel shaders that will be used to render this triangle.\n\tm_immediateContext->VSSetShader(m_gbufferVertexShader, nullptr, 0);\n\tm_immediateContext->PSSetShader(m_gbufferPixelShader, nullptr, 0);\n\n\tm_immediateContext->IASetInputLayout(m_gBufferInputLayout);\n\tm_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\t\/\/ Fetch the transpose matricies\n\tDirectX::XMMATRIX worldMatrix = m_worldViewProj.world;\n\tDirectX::XMMATRIX viewMatrix = m_worldViewProj.view;\n\tDirectX::XMMATRIX projectionMatrix = m_worldViewProj.projection;\n\n\tuint materialIndex = 0;\n\n\t\/\/ Cache the matrix multiplication\n\tDirectX::XMMATRIX viewProj = viewMatrix * projectionMatrix;\n\n\tfor (uint i = 0; i < m_models.size(); ++i) {\n\t\tm_frameMaterialList.push_back(m_models[i].GetSubsetMaterial(0));\n\n\t\tDirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewProj);\n\n\t\tSetGBufferShaderObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_frameMaterialList.size() - 1);\n\t\n\t\t\/\/ Draw the models\n\t\tm_models[i].DrawSubset(m_immediateContext);\n\t}\n\n\t\/\/ Cleanup (aka make the runtime happy)\n\tm_immediateContext->OMSetRenderTargets(0, 0, 0);\n\n\t\n\t\/\/ Final gather pass\n\tm_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);\n\n\t\/\/ Full screen triangle setup\n\tm_immediateContext->IASetInputLayout(m_fullscreenTriangleInputLayout);\n\tm_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\tm_immediateContext->VSSetShader(m_fullscreenTriangleVertexShader, nullptr, 0);\n\tm_immediateContext->GSSetShader(0, 0, 0);\n\tm_immediateContext->PSSetShader(m_noCullFinalGatherPixelShader, nullptr, 0);\n\n\tm_immediateContext->RSSetState(m_rasterizerStates.NoCull());\n\n\tDirectX::XMMATRIX invViewProj = DirectX::XMMatrixInverse(nullptr, viewProj);\n\tSetNoCullFinalGatherShaderConstants(DirectX::XMMatrixTranspose(projectionMatrix), DirectX::XMMatrixTranspose(invViewProj));\n\n\tm_immediateContext->PSSetShaderResources(0, 3, &m_gBufferSRVs.front());\n\n\t\/\/ Set light buffers\n\tSetLightBuffers();\n\n\tID3D11ShaderResourceView *srvArray[2];\n\tsrvArray[0] = m_pointLightBuffer->GetShaderResource();\n\t\/\/srvArray[1] = m_spotLightBuffer->GetShaderResource();\n\tm_immediateContext->PSSetShaderResources(3, 1, srvArray);\n\n\t\/\/ Set material list\n\tSetMaterialList();\n\n\tm_fullScreenQuad.DrawSubset(m_immediateContext);\n\n\t\/\/ Cleanup (aka make the runtime happy)\n\tm_immediateContext->VSSetShader(0, 0, 0);\n\tm_immediateContext->GSSetShader(0, 0, 0);\n\tm_immediateContext->PSSetShader(0, 0, 0);\n\tm_immediateContext->OMSetRenderTargets(0, 0, 0);\n\tID3D11ShaderResourceView* nullSRV[6] = {0, 0, 0, 0, 0, 0};\n\tm_immediateContext->VSSetShaderResources(0, 6, nullSRV);\n\tm_immediateContext->PSSetShaderResources(0, 6, nullSRV);\n\t\/\/m_immediateContext->CSSetShaderResources(0, 8, nullSRV);\n\t\/\/ID3D11UnorderedAccessView *nullUAV[1] = {0};\n\t\/\/m_immediateContext->CSSetUnorderedAccessViews(0, 1, nullUAV, 0);\n}\n\nvoid DeferredShadingDemo::SetGBufferShaderObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, uint materialIndex) {\n\t\/\/ Fill in object constants\n\tD3D11_MAPPED_SUBRESOURCE mappedResource;\n\n\t\/\/ Lock the constant buffer so it can be written to.\n\tHR(m_immediateContext->Map(m_gBufferVertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));\n\n\tGBufferVertexShaderObjectConstants *vertexShaderObjectConstants = static_cast(mappedResource.pData);\n\tvertexShaderObjectConstants->World = worldMatrix;\n\tvertexShaderObjectConstants->WorldViewProj = worldViewProjMatrix;\n\n\tm_immediateContext->Unmap(m_gBufferVertexShaderObjectConstantsBuffer, 0);\n\tm_immediateContext->VSSetConstantBuffers(1, 1, &m_gBufferVertexShaderObjectConstantsBuffer);\n\n\t\/\/ Lock the constant buffer so it can be written to.\n\tHR(m_immediateContext->Map(m_gBufferPixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));\n\n\tGBufferPixelShaderObjectConstants *pixelShaderObjectConstants = static_cast(mappedResource.pData);\n\tpixelShaderObjectConstants->MaterialIndex = materialIndex;\n\n\tm_immediateContext->Unmap(m_gBufferPixelShaderObjectConstantsBuffer, 0);\n\tm_immediateContext->PSSetConstantBuffers(1, 1, &m_gBufferPixelShaderObjectConstantsBuffer);\n}\n\nvoid DeferredShadingDemo::SetNoCullFinalGatherShaderConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &invViewProjMatrix) {\n\t\/\/ Fill in object constants\n\tD3D11_MAPPED_SUBRESOURCE mappedResource;\n\n\t\/\/ Lock the constant buffer so it can be written to.\n\tHR(m_immediateContext->Map(m_noCullFinalGatherPixelShaderConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));\n\n\tNoCullFinalGatherPixelShaderFrameConstants *pixelShaderFrameConstants = static_cast(mappedResource.pData);\n\tpixelShaderFrameConstants->gProjection = projMatrix;\n\tpixelShaderFrameConstants->gInvViewProjection = invViewProjMatrix;\n\tpixelShaderFrameConstants->gDirectionalLight = m_directionalLight;\n\tpixelShaderFrameConstants->gEyePosition = m_camera.GetCameraPosition();\n\n\tm_immediateContext->Unmap(m_noCullFinalGatherPixelShaderConstantsBuffer, 0);\n\tm_immediateContext->PSSetConstantBuffers(0, 1, &m_noCullFinalGatherPixelShaderConstantsBuffer);\n}\n\nvoid DeferredShadingDemo::SetLightBuffers() {\n\tuint numPointLights = m_pointLights.size();\n\t\/\/uint numSpotLights = m_gameStateManager->SpotLights.size();\n\n\tassert(m_pointLightBuffer->NumElements() == numPointLights);\n\t\/\/assert(m_spotLightBuffer->NumElements() == numSpotLights);\n\n\tCommon::PointLight *pointLightArray = m_pointLightBuffer->MapDiscard(m_immediateContext);\n\tfor (unsigned int i = 0; i < m_pointLights.size(); ++i) {\n\t\tpointLightArray[i] = m_pointLights[i];\n\t}\n\tm_pointLightBuffer->Unmap(m_immediateContext);\n\n\t\/\/Common::SpotLight *spotLightArray = m_spotLightBuffer->MapDiscard(m_immediateContext);\n\t\/\/for (unsigned int i = 0; i < m_gameStateManager->SpotLights.size(); ++i) {\n\t\/\/\tspotLightArray[i] = m_gameStateManager->SpotLights[i];\n\t\/\/}\n\t\/\/m_pointLightBuffer->Unmap(m_immediateContext);\n}\n\nvoid DeferredShadingDemo::SetMaterialList() {\n\tuint numMaterials = m_frameMaterialList.size();\n\tassert(numMaterials <= kMaxMaterialsPerFrame);\n\t\n\tCommon::BlinnPhongMaterial *materialArray = m_frameMaterialListBuffer->MapDiscard(m_immediateContext);\n\tfor (uint i = 0; i < numMaterials; ++i) {\n\t\tmaterialArray[i] = m_frameMaterialList[i];\n\t}\n\tm_frameMaterialListBuffer->Unmap(m_immediateContext);\n\n\tID3D11ShaderResourceView *view = m_frameMaterialListBuffer->GetShaderResource();\n\tm_immediateContext->PSSetShaderResources(5, 1, &view);\n}\n\nvoid DeferredShadingDemo::RenderHUD() {\n\tm_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);\n\n\tm_spriteRenderer.Begin(m_immediateContext, Common::SpriteRenderer::Point);\n\tstd::wostringstream stream;\n\tstream << L\"FPS: \" << m_fps << L\"\\nFrame Time: \" << m_frameTime << L\" (ms)\";\n\n\tDirectX::XMFLOAT4X4 transform{1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t25, 25, 0, 1};\n\tm_spriteRenderer.RenderText(m_timesNewRoman12Font, stream.str().c_str(), transform, DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f) \/* Yellow *\/);\n\tm_spriteRenderer.End();\n\n\tTwDraw();\n\n\t\/\/ Cleanup (aka make the runtime happy)\n\tm_immediateContext->OMSetRenderTargets(0, 0, 0);\n}\n\n} \/\/ End of namespace DeferredShadingDemo\nDEFERRED_SHADING_DEMO: Move the backbuffer RenderTarget clear down to after it's bound to the pipeline\/* The Halfling Project - A Graphics Engine and Projects\n *\n * The Halfling Project is the legal property of Adrian Astley\n * Copyright Adrian Astley 2013\n *\/\n\n#include \"deferred_shading_demo\/deferred_shading_demo.h\"\n\n#include \"deferred_shading_demo\/shader_constants.h\"\n\n#include \n#include \n\n\nnamespace DeferredShadingDemo {\n\nvoid DeferredShadingDemo::DrawFrame(double deltaTime) {\n\tRenderMainPass();\n\tRenderHUD();\n\n\tuint syncInterval = m_vsync ? 1 : 0;\n\tm_swapChain->Present(syncInterval, 0);\n}\n\nvoid DeferredShadingDemo::RenderMainPass() {\n\t\/\/ Clear the material list\n\tm_frameMaterialList.clear();\n\n\t\/\/ Bind the gbufferRTVs and depth\/stencil view to the pipeline.\n\tm_immediateContext->OMSetRenderTargets(2, &m_gBufferRTVs[0], m_depthStencilBuffer->GetDepthStencil());\n\n\t\/\/ Clear the Render Targets and DepthStencil\n\tfor (auto gbufferRTV : m_gBufferRTVs) {\n\t\tm_immediateContext->ClearRenderTargetView(gbufferRTV, DirectX::Colors::Black);\n\t}\n\tm_immediateContext->ClearDepthStencilView(m_depthStencilBuffer->GetDepthStencil(), D3D11_CLEAR_DEPTH, 0.0f, 0);\n\n\t\/\/ Set States\n\tm_immediateContext->PSSetSamplers(0, 1, &m_diffuseSampleState);\n\tfloat blendFactor[4] = {1.0f, 1.0f, 1.0f, 1.0f};\n\tm_immediateContext->OMSetBlendState(m_blendStates.BlendDisabled(), blendFactor, 0xFFFFFFFF);\n\tm_immediateContext->OMSetDepthStencilState(m_depthStencilStates.ReverseDepthWriteEnabled(), 0);\n\tID3D11RasterizerState *rasterState = m_wireframe ? m_rasterizerStates.Wireframe() : m_rasterizerStates.BackFaceCull();\n\tm_immediateContext->RSSetState(rasterState);\n\n\t\/\/ Set the vertex and pixel shaders that will be used to render this triangle.\n\tm_immediateContext->VSSetShader(m_gbufferVertexShader, nullptr, 0);\n\tm_immediateContext->PSSetShader(m_gbufferPixelShader, nullptr, 0);\n\n\tm_immediateContext->IASetInputLayout(m_gBufferInputLayout);\n\tm_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\t\/\/ Fetch the transpose matricies\n\tDirectX::XMMATRIX worldMatrix = m_worldViewProj.world;\n\tDirectX::XMMATRIX viewMatrix = m_worldViewProj.view;\n\tDirectX::XMMATRIX projectionMatrix = m_worldViewProj.projection;\n\n\tuint materialIndex = 0;\n\n\t\/\/ Cache the matrix multiplication\n\tDirectX::XMMATRIX viewProj = viewMatrix * projectionMatrix;\n\n\tfor (uint i = 0; i < m_models.size(); ++i) {\n\t\tm_frameMaterialList.push_back(m_models[i].GetSubsetMaterial(0));\n\n\t\tDirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewProj);\n\n\t\tSetGBufferShaderObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_frameMaterialList.size() - 1);\n\t\n\t\t\/\/ Draw the models\n\t\tm_models[i].DrawSubset(m_immediateContext);\n\t}\n\n\t\/\/ Cleanup (aka make the runtime happy)\n\tm_immediateContext->OMSetRenderTargets(0, 0, 0);\n\n\t\n\t\/\/ Final gather pass\n\tm_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);\n\tm_immediateContext->ClearRenderTargetView(m_renderTargetView, DirectX::Colors::LightGray);\n\n\t\/\/ Full screen triangle setup\n\tm_immediateContext->IASetInputLayout(m_fullscreenTriangleInputLayout);\n\tm_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\tm_immediateContext->VSSetShader(m_fullscreenTriangleVertexShader, nullptr, 0);\n\tm_immediateContext->GSSetShader(0, 0, 0);\n\tm_immediateContext->PSSetShader(m_noCullFinalGatherPixelShader, nullptr, 0);\n\n\tm_immediateContext->RSSetState(m_rasterizerStates.NoCull());\n\n\tDirectX::XMMATRIX invViewProj = DirectX::XMMatrixInverse(nullptr, viewProj);\n\tSetNoCullFinalGatherShaderConstants(DirectX::XMMatrixTranspose(projectionMatrix), DirectX::XMMatrixTranspose(invViewProj));\n\n\tm_immediateContext->PSSetShaderResources(0, 3, &m_gBufferSRVs.front());\n\n\t\/\/ Set light buffers\n\tSetLightBuffers();\n\n\tID3D11ShaderResourceView *srvArray[2];\n\tsrvArray[0] = m_pointLightBuffer->GetShaderResource();\n\t\/\/srvArray[1] = m_spotLightBuffer->GetShaderResource();\n\tm_immediateContext->PSSetShaderResources(3, 1, srvArray);\n\n\t\/\/ Set material list\n\tSetMaterialList();\n\n\tm_fullScreenQuad.DrawSubset(m_immediateContext);\n\n\t\/\/ Cleanup (aka make the runtime happy)\n\tm_immediateContext->VSSetShader(0, 0, 0);\n\tm_immediateContext->GSSetShader(0, 0, 0);\n\tm_immediateContext->PSSetShader(0, 0, 0);\n\tm_immediateContext->OMSetRenderTargets(0, 0, 0);\n\tID3D11ShaderResourceView* nullSRV[6] = {0, 0, 0, 0, 0, 0};\n\tm_immediateContext->VSSetShaderResources(0, 6, nullSRV);\n\tm_immediateContext->PSSetShaderResources(0, 6, nullSRV);\n\t\/\/m_immediateContext->CSSetShaderResources(0, 8, nullSRV);\n\t\/\/ID3D11UnorderedAccessView *nullUAV[1] = {0};\n\t\/\/m_immediateContext->CSSetUnorderedAccessViews(0, 1, nullUAV, 0);\n}\n\nvoid DeferredShadingDemo::SetGBufferShaderObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, uint materialIndex) {\n\t\/\/ Fill in object constants\n\tD3D11_MAPPED_SUBRESOURCE mappedResource;\n\n\t\/\/ Lock the constant buffer so it can be written to.\n\tHR(m_immediateContext->Map(m_gBufferVertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));\n\n\tGBufferVertexShaderObjectConstants *vertexShaderObjectConstants = static_cast(mappedResource.pData);\n\tvertexShaderObjectConstants->World = worldMatrix;\n\tvertexShaderObjectConstants->WorldViewProj = worldViewProjMatrix;\n\n\tm_immediateContext->Unmap(m_gBufferVertexShaderObjectConstantsBuffer, 0);\n\tm_immediateContext->VSSetConstantBuffers(1, 1, &m_gBufferVertexShaderObjectConstantsBuffer);\n\n\t\/\/ Lock the constant buffer so it can be written to.\n\tHR(m_immediateContext->Map(m_gBufferPixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));\n\n\tGBufferPixelShaderObjectConstants *pixelShaderObjectConstants = static_cast(mappedResource.pData);\n\tpixelShaderObjectConstants->MaterialIndex = materialIndex;\n\n\tm_immediateContext->Unmap(m_gBufferPixelShaderObjectConstantsBuffer, 0);\n\tm_immediateContext->PSSetConstantBuffers(1, 1, &m_gBufferPixelShaderObjectConstantsBuffer);\n}\n\nvoid DeferredShadingDemo::SetNoCullFinalGatherShaderConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &invViewProjMatrix) {\n\t\/\/ Fill in object constants\n\tD3D11_MAPPED_SUBRESOURCE mappedResource;\n\n\t\/\/ Lock the constant buffer so it can be written to.\n\tHR(m_immediateContext->Map(m_noCullFinalGatherPixelShaderConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));\n\n\tNoCullFinalGatherPixelShaderFrameConstants *pixelShaderFrameConstants = static_cast(mappedResource.pData);\n\tpixelShaderFrameConstants->gProjection = projMatrix;\n\tpixelShaderFrameConstants->gInvViewProjection = invViewProjMatrix;\n\tpixelShaderFrameConstants->gDirectionalLight = m_directionalLight;\n\tpixelShaderFrameConstants->gEyePosition = m_camera.GetCameraPosition();\n\n\tm_immediateContext->Unmap(m_noCullFinalGatherPixelShaderConstantsBuffer, 0);\n\tm_immediateContext->PSSetConstantBuffers(0, 1, &m_noCullFinalGatherPixelShaderConstantsBuffer);\n}\n\nvoid DeferredShadingDemo::SetLightBuffers() {\n\tuint numPointLights = m_pointLights.size();\n\t\/\/uint numSpotLights = m_gameStateManager->SpotLights.size();\n\n\tassert(m_pointLightBuffer->NumElements() == numPointLights);\n\t\/\/assert(m_spotLightBuffer->NumElements() == numSpotLights);\n\n\tCommon::PointLight *pointLightArray = m_pointLightBuffer->MapDiscard(m_immediateContext);\n\tfor (unsigned int i = 0; i < m_pointLights.size(); ++i) {\n\t\tpointLightArray[i] = m_pointLights[i];\n\t}\n\tm_pointLightBuffer->Unmap(m_immediateContext);\n\n\t\/\/Common::SpotLight *spotLightArray = m_spotLightBuffer->MapDiscard(m_immediateContext);\n\t\/\/for (unsigned int i = 0; i < m_gameStateManager->SpotLights.size(); ++i) {\n\t\/\/\tspotLightArray[i] = m_gameStateManager->SpotLights[i];\n\t\/\/}\n\t\/\/m_pointLightBuffer->Unmap(m_immediateContext);\n}\n\nvoid DeferredShadingDemo::SetMaterialList() {\n\tuint numMaterials = m_frameMaterialList.size();\n\tassert(numMaterials <= kMaxMaterialsPerFrame);\n\t\n\tCommon::BlinnPhongMaterial *materialArray = m_frameMaterialListBuffer->MapDiscard(m_immediateContext);\n\tfor (uint i = 0; i < numMaterials; ++i) {\n\t\tmaterialArray[i] = m_frameMaterialList[i];\n\t}\n\tm_frameMaterialListBuffer->Unmap(m_immediateContext);\n\n\tID3D11ShaderResourceView *view = m_frameMaterialListBuffer->GetShaderResource();\n\tm_immediateContext->PSSetShaderResources(5, 1, &view);\n}\n\nvoid DeferredShadingDemo::RenderHUD() {\n\tm_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, nullptr);\n\n\tm_spriteRenderer.Begin(m_immediateContext, Common::SpriteRenderer::Point);\n\tstd::wostringstream stream;\n\tstream << L\"FPS: \" << m_fps << L\"\\nFrame Time: \" << m_frameTime << L\" (ms)\";\n\n\tDirectX::XMFLOAT4X4 transform{1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t25, 25, 0, 1};\n\tm_spriteRenderer.RenderText(m_timesNewRoman12Font, stream.str().c_str(), transform, DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f) \/* Yellow *\/);\n\tm_spriteRenderer.End();\n\n\tTwDraw();\n\n\t\/\/ Cleanup (aka make the runtime happy)\n\tm_immediateContext->OMSetRenderTargets(0, 0, 0);\n}\n\n} \/\/ End of namespace DeferredShadingDemo\n<|endoftext|>"} {"text":"\/\/ coding: utf-8\n\/* Copyright (c) 2014, Electronic Kiwi\n* All Rights Reserved.\n*\n* The file is part of the xpcc-playground and is released under the 3-clause BSD\n* license. See the file `LICENSE` for the full license governing this code.\n*\/\n\n#include \n#include \n#include \"..\/..\/xpcc\/examples\/stm32f3_discovery\/stm32f3_discovery.hpp\"\n\n\/\/ Create an IODeviceWrapper around the Uart Peripheral we want to use\nxpcc::IODeviceWrapper< Usart2 > loggerDevice;\n\n\/\/ Set all four logger streams to use the UART\nxpcc::log::Logger xpcc::log::debug(loggerDevice);\nxpcc::log::Logger xpcc::log::info(loggerDevice);\nxpcc::log::Logger xpcc::log::warning(loggerDevice);\nxpcc::log::Logger xpcc::log::error(loggerDevice);\n\n\/\/ Set the log level\n#undef\tXPCC_LOG_LEVEL\n#define\tXPCC_LOG_LEVEL xpcc::log::DEBUG\n\n#include \n#include \n\n\n#include \n#include \n#include \n#include \"..\/cc1101\/cc1101.hpp\"\n\n\nclass MainThread : public xpcc::pt::Protothread\n{\npublic:\n\tMainThread() : blinkTimer(500)\n\t{\n\t}\n\n\t\/\/\/ Needs to be called as often as possible.\n\tbool\n\trun()\n\t{\n\t\tif(blinkTimer.isExpired()) {\n\t\t\tLedSouth::toggle();\n\t\t}\n\n\t\tPT_BEGIN();\n\n\t\t\/\/ try to initialize the device\n\t\tstatic Radio::InitializeError e;\n\t\te = PT_CALL(radio.initialize(this));\n\t\tif(e != Radio::InitializeError::None) {\n\t\t\tXPCC_LOG_ERROR << XPCC_FILE_INFO;\n\t\t\tXPCC_LOG_ERROR << \"Error trying to initialize the cc1101: \";\n\t\t\tXPCC_LOG_ERROR << Radio::enumToString(e) << xpcc::endl;\n\t\t} else {\n\t\t\tXPCC_LOG_DEBUG << XPCC_FILE_INFO << \"Initialized cc1101.\" << xpcc::endl;\n\t\t}\n\n\t\t\/\/ main loop\n\t\twhile(true){\n\t\t\tPT_YIELD();\n\t\t}\n\n\t\tPT_END();\n\t}\n\npublic:\n\tstruct CC1101Config {\n\t\ttypedef SpiSimpleMaster3 SpiMaster;\n\t\ttypedef GpioOutputA15 Cs;\n\t\ttypedef GpioInputB4 Miso;\n\t\ttypedef GpioD6 Gdo0;\n\t\ttypedef GpioD4 Gdo2;\n\t};\n\nprivate:\n\ttypedef xpcc::radio::CC1101 Radio;\n\txpcc::Timeout<> timer;\n\txpcc::PeriodicTimer<> blinkTimer;\n\tRadio radio;\n};\n\nMainThread mainThread;\n\n\n\/\/ ----------------------------------------------------------------------------\nMAIN_FUNCTION\n{\n\tdefaultSystemClock::enable();\n\txpcc::cortex::SysTickTimer::enable();\n\n\tLedNorth::setOutput(xpcc::Gpio::Low);\n\tLedSouth::setOutput(xpcc::Gpio::Low);\n\n\t\/\/ Initialize Usart\n\tGpioOutputA2::connect(Usart2::Tx);\n\tGpioInputA3::connect(Usart2::Rx);\n\tUsart2::initialize(10);\n\n\t\/\/ Print project information\n\tXPCC_LOG_INFO << \"[log-start] \" XPCC_PROJECT_NAME \": \" __DATE__ \"@\" __TIME__ << xpcc::endl;\n\tXPCC_LOG_INFO << \"[git] \" XPCC_GIT_SHA_ABBR \" \" XPCC_GIT_SUBJECT << xpcc::endl;\n\tXPCC_LOG_INFO << \"[git] \" XPCC_GIT_AUTHOR \"<\" XPCC_GIT_AUTHOR_EMAIL \">\" << xpcc::endl;\n\n\t\/\/ Initialize Spi\n\tMainThread::CC1101Config::Cs::setOutput(xpcc::Gpio::High);\n\tMainThread::CC1101Config::Miso::connect(SpiSimpleMaster3::Miso);\n\tGpioOutputB5::connect(SpiSimpleMaster3::Mosi);\n\tGpioOutputB3::connect(SpiSimpleMaster3::Sck);\n\tSpiSimpleMaster3::initialize();\n\t\/\/SpiSimpleMaster3::initialize();\n\n\twhile (1)\n\t{\n\t\tmainThread.run();\n\t}\n\n\treturn 0;\n}\nCC1101 Test: can configure Gdo0 as high impedance.\/\/ coding: utf-8\n\/* Copyright (c) 2014, Electronic Kiwi\n* All Rights Reserved.\n*\n* The file is part of the xpcc-playground and is released under the 3-clause BSD\n* license. See the file `LICENSE` for the full license governing this code.\n*\/\n\n#include \n#include \n#include \"..\/..\/xpcc\/examples\/stm32f3_discovery\/stm32f3_discovery.hpp\"\n\n\/\/ Create an IODeviceWrapper around the Uart Peripheral we want to use\nxpcc::IODeviceWrapper< Usart2 > loggerDevice;\n\n\/\/ Set all four logger streams to use the UART\nxpcc::log::Logger xpcc::log::debug(loggerDevice);\nxpcc::log::Logger xpcc::log::info(loggerDevice);\nxpcc::log::Logger xpcc::log::warning(loggerDevice);\nxpcc::log::Logger xpcc::log::error(loggerDevice);\n\n\/\/ Set the log level\n#undef\tXPCC_LOG_LEVEL\n#define\tXPCC_LOG_LEVEL xpcc::log::DEBUG\n\n#include \n#include \n\n\n#include \n#include \n#include \n#include \"..\/cc1101\/cc1101.hpp\"\n\n\nclass MainThread : public xpcc::pt::Protothread\n{\npublic:\n\tMainThread() : blinkTimer(500)\n\t{\n\t}\n\n\t\/\/\/ Needs to be called as often as possible.\n\tbool\n\trun()\n\t{\n\t\tif(blinkTimer.isExpired()) {\n\t\t\tLedSouth::toggle();\n\t\t}\n\n\t\tPT_BEGIN();\n\n\t\t\/\/ try to initialize the device\n\t\tstatic Radio::InitializeError e;\n\t\te = PT_CALL(radio.initialize(this));\n\t\tif(e != Radio::InitializeError::None) {\n\t\t\tXPCC_LOG_ERROR << XPCC_FILE_INFO;\n\t\t\tXPCC_LOG_ERROR << \"Error trying to initialize the cc1101: \";\n\t\t\tXPCC_LOG_ERROR << Radio::enumToString(e) << xpcc::endl;\n\t\t} else {\n\t\t\tXPCC_LOG_DEBUG << XPCC_FILE_INFO << \"Initialized cc1101.\" << xpcc::endl;\n\t\t}\n\t\t\/\/ Configure Gdo0 as high impedance\n\t\tPT_CALL(radio.configureGdo(this,\n\t\t\tRadio::Gdo::Gdo0,\n\t\t\tRadio::GdoInverted::No,\n\t\t\tRadio::GdoSignalSelection::HighImpedance));\n\n\t\t\/\/ main loop\n\t\twhile(true){\n\t\t\tPT_YIELD();\n\t\t}\n\n\t\tPT_END();\n\t}\n\npublic:\n\tstruct CC1101Config {\n\t\ttypedef SpiSimpleMaster3 SpiMaster;\n\t\ttypedef GpioOutputA15 Cs;\n\t\ttypedef GpioInputB4 Miso;\n\t\ttypedef GpioInputD6 Gdo0;\n\t\ttypedef GpioInputD4 Gdo2;\n\t};\n\nprivate:\n\ttypedef xpcc::radio::CC1101 Radio;\n\txpcc::Timeout<> timer;\n\txpcc::PeriodicTimer<> blinkTimer;\n\tRadio radio;\n};\n\nMainThread mainThread;\n\n\n\/\/ ----------------------------------------------------------------------------\nMAIN_FUNCTION\n{\n\tdefaultSystemClock::enable();\n\txpcc::cortex::SysTickTimer::enable();\n\n\tLedNorth::setOutput(xpcc::Gpio::Low);\n\tLedSouth::setOutput(xpcc::Gpio::Low);\n\n\t\/\/ Initialize Usart\n\tGpioOutputA2::connect(Usart2::Tx);\n\tGpioInputA3::connect(Usart2::Rx);\n\tUsart2::initialize(10);\n\n\t\/\/ Print project information\n\tXPCC_LOG_INFO << \"[log-start] \" XPCC_PROJECT_NAME \": \" __DATE__ \"@\" __TIME__ << xpcc::endl;\n\tXPCC_LOG_INFO << \"[git] \" XPCC_GIT_SHA_ABBR \" \" XPCC_GIT_SUBJECT << xpcc::endl;\n\tXPCC_LOG_INFO << \"[git] \" XPCC_GIT_AUTHOR \"<\" XPCC_GIT_AUTHOR_EMAIL \">\" << xpcc::endl;\n\n\t\/\/ Initialize Spi\n\tMainThread::CC1101Config::Cs::setOutput(xpcc::Gpio::High);\n\tMainThread::CC1101Config::Miso::connect(SpiSimpleMaster3::Miso);\n\tGpioOutputB5::connect(SpiSimpleMaster3::Mosi);\n\tGpioOutputB3::connect(SpiSimpleMaster3::Sck);\n\tSpiSimpleMaster3::initialize();\n\t\/\/SpiSimpleMaster3::initialize();\n\n\t\/\/ Initialize Gdos\n\tMainThread::CC1101Config::Gdo0::setInput();\n\tMainThread::CC1101Config::Gdo2::setInput();\n\n\twhile (1)\n\t{\n\t\tmainThread.run();\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define STRINGIZE(x) #x\n#define QUOTE(x) STRINGIZE(x)\n\nint main(int argc, char *argv[])\n{\n QGuiApplication app(argc, argv);\n\n#ifdef Q_OS_WIN\n \/\/ Force usage of OpenGL ES through ANGLE on Windows\n QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);\n#endif\n\n \/\/ Intialize application view\n QQuickView view;\n view.setResizeMode(QQuickView::SizeRootObjectToView);\n\n \/\/ Add the import Path\n view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath(\"qml\"));\n \/\/ Add the Runtime and Extras path\n view.engine()->addImportPath(QUOTE(ARCGIS_RUNTIME_IMPORT_PATH));\n \/\/ Add the Toolkit path\n view.engine()->addImportPath(QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH));\n\n \/\/ Set the source\n view.setSource(QUrl(\"qrc:\/Samples\/Layers\/RasterLayerFile\/RasterLayerFile.qml\"));\n\n view.show();\n\n return app.exec();\n}\nadding linux replace logic\/\/ Copyright 2015 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define STRINGIZE(x) #x\n#define QUOTE(x) STRINGIZE(x)\n\nint main(int argc, char *argv[])\n{\n QGuiApplication app(argc, argv);\n\n#ifdef Q_OS_WIN\n \/\/ Force usage of OpenGL ES through ANGLE on Windows\n QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);\n#endif\n\n \/\/ Intialize application view\n QQuickView view;\n view.setResizeMode(QQuickView::SizeRootObjectToView);\n\n QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);\n QString arcGISToolkitImportPath = QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH);\n\n#if defined(LINUX_PLATFORM_REPLACEMENT)\n \/\/ on some linux platforms the string 'linux' is replaced with 1\n \/\/ fix the replacement paths which were created\n QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT);\n arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, \"linux\", Qt::CaseSensitive);\n arcGISToolkitImportPath = arcGISToolkitImportPath.replace(replaceString, \"linux\", Qt::CaseSensitive);\n#endif\n\n \/\/ Add the Runtime and Extras path\n view.engine()->addImportPath(arcGISRuntimeImportPath);\n \/\/ Add the Toolkit path\n view.engine()->addImportPath(arcGISToolkitImportPath);\n\n \/\/ Set the source\n view.setSource(QUrl(\"qrc:\/Samples\/Layers\/RasterLayerFile\/RasterLayerFile.qml\"));\n\n view.show();\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ This macro add an analysis task for computing efficiency.\n\/\/ It will have as output an AliCFContainer with several steps:\n\/\/\n\/\/ 0) all resonances in MC which decay in the pair specified\n\/\/ 1) subset of (0) whose daughters are in acceptance\n\/\/ 2) subset of (1) whose daughters satisfy quality track cuts (covariance, chi square && nTPCclusters)\n\/\/ 3) subset of (2) whose daughters satisfy primary track cuts (nsigma to vertex, no kink daughters)\n\/\/ 4) subset of (3) whose daughters satisty the BB TPC compatibility cut at 3 sigma\n\/\/\nBool_t AddAnalysisTaskRsnEff\n(\n Bool_t useBB = kFALSE,\n Double_t sigmaTPC = 0.065,\n const char *outFile = \"eff\"\n)\n{\n \/\/ retrieve analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n \/\/ common suffixes\n TString suf[2];\n suf[0] = \"nopid\";\n suf[1] = \"pid\";\n\n \/\/ create task\n AliRsnAnalysisEffSE *task[2];\n task[0] = new AliRsnAnalysisEffSE(\"EffNoPID\");\n task[1] = new AliRsnAnalysisEffSE(\"EffPID\");\n\n \/\/ set prior probabilities for PID\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->SetPriorProbability(AliPID::kElectron, 0.02);\n task[i]->SetPriorProbability(AliPID::kMuon, 0.02);\n task[i]->SetPriorProbability(AliPID::kPion, 0.83);\n task[i]->SetPriorProbability(AliPID::kKaon, 0.07);\n task[i]->SetPriorProbability(AliPID::kProton, 0.06);\n task[i]->DumpPriors();\n }\n\n \/\/ pair definitions:\n \/\/ phi --> K+ K-\n \/\/ kstar --> K+ pi- & K- pi+\n AliRsnPairDef *pairPhi = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kKaon, 333);\n AliRsnPairDef *pairKStar1 = new AliRsnPairDef('-', AliPID::kKaon, '+', AliPID::kPion, 313);\n AliRsnPairDef *pairKStar2 = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kPion, 313);\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->AddPairDef(pairPhi);\n task[i]->AddPairDef(pairKStar1);\n task[i]->AddPairDef(pairKStar2);\n }\n\n \/\/ axis definition\n \/\/ 0) transverse momentum\n \/\/ 1) pseudo-rapidity\n \/\/ 2) multiplicity (estimated with SPD tracklets - uncorrected)\n AliRsnFunctionAxis *axisPt = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairPt, 40, 0.0, 10.0);\n AliRsnFunctionAxis *axisEta = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairEta, 20, -1.5, 1.5);\n AliRsnFunctionAxis *axisMult = new AliRsnFunctionAxis(AliRsnFunctionAxis::kEventMult, 8, 0.0, 200.0);\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->AddAxis(axisMult);\n task[i]->AddAxis(axisPt);\n task[i]->AddAxis(axisEta);\n }\n\n \/\/ define cuts for event selection:\n \/\/ this will determine the filling of bins in the \"info\" histograms\n \/\/ and should be computed as additional correction factor in efficiency\n AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex(\"cutVertex\", 3);\n AliRsnCutSet *cutSetEvent = new AliRsnCutSet(\"eventCuts\");\n cutSetEvent->AddCut(cutVertex);\n cutSetEvent->SetCutScheme(\"cutVertex\");\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->SetEventCuts(cutSetEvent);\n }\n\n \/\/\n \/\/ *** STEP 0 - All resonances which decay in the specified pairs\n \/\/\n \/\/ This step does not need any kind of definition, since\n \/\/ its requirement is automatically checked during execution,\n \/\/ but to avoid segfaults, it is better to initialize a cut manager.\n \/\/\n AliRsnCutMgr *cutMgrMC_step0 = new AliRsnCutMgr(\"mc_step0\", \"\");\n\n \/\/\n \/\/ *** STEP 1 - Acceptance\n \/\/\n \/\/ Here we add a cut on the pseudorapidity for both tracks\n \/\/\n AliRsnCutStd *cutEta = new AliRsnCutStd(\"cutEta\", AliRsnCutStd::kEta, -0.9, 0.9);\n\n AliRsnCutMgr *cutMgrMC_step1 = new AliRsnCutMgr(\"mc_step1\", \"\");\n AliRsnCutSet *cutSetTrack_step1 = new AliRsnCutSet(\"mc_step1_tracks\");\n \n cutSetTrack_step1->AddCut(cutEta);\n cutSetTrack_step1->SetCutScheme(\"cutEta\");\n cutMgrMC_step1 ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step1);\n\n \/\/\n \/\/ *** STEP 2 - Reconstruction & track quality\n \/\/\n \/\/ Use the interface to AliESDtrackCuts\n \/\/ and set only the cuts we are interested in\n AliRsnCutESDPrimary *cutQuality = new AliRsnCutESDPrimary(\"cutCov\");\n cutQuality->GetCuts()->SetMaxCovDiagonalElements(2.0, 2.0, 0.5, 0.5, 2.0);\n cutQuality->GetCuts()->SetRequireSigmaToVertex(kTRUE);\n cutQuality->GetCuts()->SetMaxNsigmaToVertex(10000.0);\n cutQuality->GetCuts()->SetRequireTPCRefit(kTRUE);\n cutQuality->GetCuts()->SetAcceptKinkDaughters(kTRUE);\n cutQuality->GetCuts()->SetMinNClustersTPC(50);\n cutQuality->GetCuts()->SetMaxChi2PerClusterTPC(3.5);\n\n AliRsnCutMgr *cutMgrESD_step2 = new AliRsnCutMgr(\"esd_step2\", \"\");\n AliRsnCutSet *cutSetTrack_step2 = new AliRsnCutSet(\"esd_step2_tracks\");\n\n cutSetTrack_step2->AddCut(cutQuality);\n cutSetTrack_step2->SetCutScheme(\"cutQuality\");\n cutMgrESD_step2 ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step2);\n\n \/\/\n \/\/ *** STEP 3 - Primary tracks\n \/\/\n \/\/ Use the interface to AliESDtrackCuts\n \/\/ and set only the cuts we are interested in\n \/\/ we also disable the cuts we applied before, for clarity\n AliRsnCutESDPrimary *cutESDPrimary = new AliRsnCutESDPrimary(\"cutESDPrimary\");\n cutESDPrimary->GetCuts()->SetMaxCovDiagonalElements(100.0, 100.0, 100.0, 100.0, 100.0);\n cutESDPrimary->GetCuts()->SetRequireSigmaToVertex(kTRUE);\n cutESDPrimary->GetCuts()->SetMaxNsigmaToVertex(3.0);\n cutESDPrimary->GetCuts()->SetRequireTPCRefit(kFALSE);\n cutESDPrimary->GetCuts()->SetAcceptKinkDaughters(kFALSE);\n cutESDPrimary->GetCuts()->SetMinNClustersTPC(0);\n cutESDPrimary->GetCuts()->SetMaxChi2PerClusterTPC(100000000.0);\n\n AliRsnCutMgr *cutMgrESD_step3 = new AliRsnCutMgr(\"esd_step3\", \"\");\n AliRsnCutSet *cutSetTrack_step3 = new AliRsnCutSet(\"esd_step3_tracks\");\n\n cutSetTrack_step3->AddCut(cutESDPrimary);\n cutSetTrack_step3->SetCutScheme(\"cutESDPrimary\");\n cutMgrESD_step3 ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step3);\n\n \/\/\n \/\/ *** STEP 4 - Two possibilities (depend on the first macro argument)\n \/\/\n \/\/ option 1 = Bethe-Bloch cut in 3 sigma (the sigma is one argument)\n \/\/ option 2 = realistic Bayesian PID with all detectors\n \/\/\n AliRsnCutMgr *cutMgrESD_step4[2];\n AliRsnCutSet *cutSetTrack_step4[2];\n \n cutMgrESD_step4[0] = new AliRsnCutMgr(\"esd_step4_nopid\", \"\");\n cutMgrESD_step4[1] = new AliRsnCutMgr(\"esd_step4_pid\", \"\");\n cutSetTrack_step4[0] = new AliRsnCutSet(\"esd_step4_tracks_nopid\");\n cutSetTrack_step4[1] = new AliRsnCutSet(\"esd_step4_tracks_pid\");\n \n \/\/ Bethe-Bloch with kaon mass hypothesis\n AliRsnCutBetheBloch *cutKaonBB = new AliRsnCutBetheBloch(\"cutKaonBB\", 3.0 * sigmaTPC, AliPID::kKaon);\n cutKaonBB->SetCalibConstant(0, 0.76176e-1);\n cutKaonBB->SetCalibConstant(1, 10.632);\n cutKaonBB->SetCalibConstant(2, 0.13279e-4);\n cutKaonBB->SetCalibConstant(3, 1.8631);\n cutKaonBB->SetCalibConstant(4, 1.9479);\n\n \/\/ cuts for realistic PID match\n AliRsnCutStd *cutRealisticPID = new AliRsnCutStd(\"cutKaonPID\", AliRsnCutStd::kRealisticPIDMatch, 0);\n\n cutSetTrack_step4[0]->AddCut(cutKaonBB);\n cutSetTrack_step4[0]->SetCutScheme(\"cutKaonBB\");\n\n cutSetTrack_step4[1]->AddCut(cutRealisticPID);\n cutSetTrack_step4[1]->SetCutScheme(\"cutRealisticPID\");\n\n cutMgrESD_step4[0]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[0]);\n cutMgrESD_step4[1]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[1]);\n\n \/\/ add all steps to the task\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->AddStepMC (cutMgrMC_step0);\n task[i]->AddStepMC (cutMgrMC_step1);\n task[i]->AddStepESD(cutMgrESD_step2);\n task[i]->AddStepESD(cutMgrESD_step3);\n task[i]->AddStepESD(cutMgrESD_step4[i]);\n }\n\n \/\/ connect containers and finalize\n for (Int_t i = 0; i < 2; i++)\n {\n mgr->AddTask(task[i]);\n mgr->ConnectInput(task[i], 0, mgr->GetCommonInputContainer());\n\n \/\/ create paths for the output in the common file\n Char_t infoPath[500], effPath[500];\n sprintf(infoPath , \"%s:PWG2RSNINFO\" , AliAnalysisManager::GetCommonFileName());\n sprintf(effPath , \"%s:PWG2RSNEFF%s\", AliAnalysisManager::GetCommonFileName(), suf[i].Data());\n\n \/\/ initialize and connect container for the output\n AliAnalysisDataContainer *info = 0x0, *out = 0x0;\n info = mgr->CreateContainer(Form(\"EffInfo_%s\", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, infoPath);\n out = mgr->CreateContainer(Form(\"EFF_%s\", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, effPath);\n\n mgr->ConnectOutput(task[i], 1, info);\n mgr->ConnectOutput(task[i], 2, out);\n }\n\n return kTRUE;\n}\nfix number of bins mismatch\/\/\n\/\/ This macro add an analysis task for computing efficiency.\n\/\/ It will have as output an AliCFContainer with several steps:\n\/\/\n\/\/ 0) all resonances in MC which decay in the pair specified\n\/\/ 1) subset of (0) whose daughters are in acceptance\n\/\/ 2) subset of (1) whose daughters satisfy quality track cuts (covariance, chi square && nTPCclusters)\n\/\/ 3) subset of (2) whose daughters satisfy primary track cuts (nsigma to vertex, no kink daughters)\n\/\/ 4) subset of (3) whose daughters satisty the BB TPC compatibility cut at 3 sigma\n\/\/\nBool_t AddAnalysisTaskRsnEff\n(\n Bool_t useBB = kFALSE,\n Double_t sigmaTPC = 0.065,\n const char *outFile = \"eff\"\n)\n{\n \/\/ retrieve analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n \/\/ common suffixes\n TString suf[2];\n suf[0] = \"nopid\";\n suf[1] = \"pid\";\n\n \/\/ create task\n AliRsnAnalysisEffSE *task[2];\n task[0] = new AliRsnAnalysisEffSE(\"EffNoPID\");\n task[1] = new AliRsnAnalysisEffSE(\"EffPID\");\n\n \/\/ set prior probabilities for PID\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->SetPriorProbability(AliPID::kElectron, 0.02);\n task[i]->SetPriorProbability(AliPID::kMuon, 0.02);\n task[i]->SetPriorProbability(AliPID::kPion, 0.83);\n task[i]->SetPriorProbability(AliPID::kKaon, 0.07);\n task[i]->SetPriorProbability(AliPID::kProton, 0.06);\n task[i]->DumpPriors();\n }\n\n \/\/ pair definitions:\n \/\/ phi --> K+ K-\n \/\/ kstar --> K+ pi- & K- pi+\n AliRsnPairDef *pairPhi = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kKaon, 333);\n AliRsnPairDef *pairKStar1 = new AliRsnPairDef('-', AliPID::kKaon, '+', AliPID::kPion, 313);\n AliRsnPairDef *pairKStar2 = new AliRsnPairDef('+', AliPID::kKaon, '-', AliPID::kPion, 313);\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->AddPairDef(pairPhi);\n task[i]->AddPairDef(pairKStar1);\n task[i]->AddPairDef(pairKStar2);\n }\n\n \/\/ axis definition\n \/\/ 0) transverse momentum\n \/\/ 1) pseudo-rapidity\n \/\/ 2) multiplicity (estimated with SPD tracklets - uncorrected)\n AliRsnFunctionAxis *axisPt = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairPt, 50, 0.0, 10.0);\n AliRsnFunctionAxis *axisEta = new AliRsnFunctionAxis(AliRsnFunctionAxis::kPairEta, 20, -1.5, 1.5);\n AliRsnFunctionAxis *axisMult = new AliRsnFunctionAxis(AliRsnFunctionAxis::kEventMult, 8, 0.0, 200.0);\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->AddAxis(axisMult);\n task[i]->AddAxis(axisPt);\n task[i]->AddAxis(axisEta);\n }\n\n \/\/ define cuts for event selection:\n \/\/ this will determine the filling of bins in the \"info\" histograms\n \/\/ and should be computed as additional correction factor in efficiency\n AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex(\"cutVertex\", 3);\n AliRsnCutSet *cutSetEvent = new AliRsnCutSet(\"eventCuts\");\n cutSetEvent->AddCut(cutVertex);\n cutSetEvent->SetCutScheme(\"cutVertex\");\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->SetEventCuts(cutSetEvent);\n }\n\n \/\/\n \/\/ *** STEP 0 - All resonances which decay in the specified pairs\n \/\/\n \/\/ This step does not need any kind of definition, since\n \/\/ its requirement is automatically checked during execution,\n \/\/ but to avoid segfaults, it is better to initialize a cut manager.\n \/\/\n AliRsnCutMgr *cutMgrMC_step0 = new AliRsnCutMgr(\"mc_step0\", \"\");\n\n \/\/\n \/\/ *** STEP 1 - Acceptance\n \/\/\n \/\/ Here we add a cut on the pseudorapidity for both tracks\n \/\/\n AliRsnCutStd *cutEta = new AliRsnCutStd(\"cutEta\", AliRsnCutStd::kEta, -0.9, 0.9);\n\n AliRsnCutMgr *cutMgrMC_step1 = new AliRsnCutMgr(\"mc_step1\", \"\");\n AliRsnCutSet *cutSetTrack_step1 = new AliRsnCutSet(\"mc_step1_tracks\");\n \n cutSetTrack_step1->AddCut(cutEta);\n cutSetTrack_step1->SetCutScheme(\"cutEta\");\n cutMgrMC_step1 ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step1);\n\n \/\/\n \/\/ *** STEP 2 - Reconstruction & track quality\n \/\/\n \/\/ Use the interface to AliESDtrackCuts\n \/\/ and set only the cuts we are interested in\n AliRsnCutESDPrimary *cutQuality = new AliRsnCutESDPrimary(\"cutCov\");\n cutQuality->GetCuts()->SetMaxCovDiagonalElements(2.0, 2.0, 0.5, 0.5, 2.0);\n cutQuality->GetCuts()->SetRequireSigmaToVertex(kTRUE);\n cutQuality->GetCuts()->SetMaxNsigmaToVertex(10000.0);\n cutQuality->GetCuts()->SetRequireTPCRefit(kTRUE);\n cutQuality->GetCuts()->SetAcceptKinkDaughters(kTRUE);\n cutQuality->GetCuts()->SetMinNClustersTPC(50);\n cutQuality->GetCuts()->SetMaxChi2PerClusterTPC(3.5);\n\n AliRsnCutMgr *cutMgrESD_step2 = new AliRsnCutMgr(\"esd_step2\", \"\");\n AliRsnCutSet *cutSetTrack_step2 = new AliRsnCutSet(\"esd_step2_tracks\");\n\n cutSetTrack_step2->AddCut(cutQuality);\n cutSetTrack_step2->SetCutScheme(\"cutQuality\");\n cutMgrESD_step2 ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step2);\n\n \/\/\n \/\/ *** STEP 3 - Primary tracks\n \/\/\n \/\/ Use the interface to AliESDtrackCuts\n \/\/ and set only the cuts we are interested in\n \/\/ we also disable the cuts we applied before, for clarity\n AliRsnCutESDPrimary *cutESDPrimary = new AliRsnCutESDPrimary(\"cutESDPrimary\");\n cutESDPrimary->GetCuts()->SetMaxCovDiagonalElements(100.0, 100.0, 100.0, 100.0, 100.0);\n cutESDPrimary->GetCuts()->SetRequireSigmaToVertex(kTRUE);\n cutESDPrimary->GetCuts()->SetMaxNsigmaToVertex(3.0);\n cutESDPrimary->GetCuts()->SetRequireTPCRefit(kFALSE);\n cutESDPrimary->GetCuts()->SetAcceptKinkDaughters(kFALSE);\n cutESDPrimary->GetCuts()->SetMinNClustersTPC(0);\n cutESDPrimary->GetCuts()->SetMaxChi2PerClusterTPC(100000000.0);\n\n AliRsnCutMgr *cutMgrESD_step3 = new AliRsnCutMgr(\"esd_step3\", \"\");\n AliRsnCutSet *cutSetTrack_step3 = new AliRsnCutSet(\"esd_step3_tracks\");\n\n cutSetTrack_step3->AddCut(cutESDPrimary);\n cutSetTrack_step3->SetCutScheme(\"cutESDPrimary\");\n cutMgrESD_step3 ->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step3);\n\n \/\/\n \/\/ *** STEP 4 - Two possibilities (depend on the first macro argument)\n \/\/\n \/\/ option 1 = Bethe-Bloch cut in 3 sigma (the sigma is one argument)\n \/\/ option 2 = realistic Bayesian PID with all detectors\n \/\/\n AliRsnCutMgr *cutMgrESD_step4[2];\n AliRsnCutSet *cutSetTrack_step4[2];\n \n cutMgrESD_step4[0] = new AliRsnCutMgr(\"esd_step4_nopid\", \"\");\n cutMgrESD_step4[1] = new AliRsnCutMgr(\"esd_step4_pid\", \"\");\n cutSetTrack_step4[0] = new AliRsnCutSet(\"esd_step4_tracks_nopid\");\n cutSetTrack_step4[1] = new AliRsnCutSet(\"esd_step4_tracks_pid\");\n \n \/\/ Bethe-Bloch with kaon mass hypothesis\n AliRsnCutBetheBloch *cutKaonBB = new AliRsnCutBetheBloch(\"cutKaonBB\", 3.0 * sigmaTPC, AliPID::kKaon);\n cutKaonBB->SetCalibConstant(0, 0.76176e-1);\n cutKaonBB->SetCalibConstant(1, 10.632);\n cutKaonBB->SetCalibConstant(2, 0.13279e-4);\n cutKaonBB->SetCalibConstant(3, 1.8631);\n cutKaonBB->SetCalibConstant(4, 1.9479);\n\n \/\/ cuts for realistic PID match\n AliRsnCutStd *cutRealisticPID = new AliRsnCutStd(\"cutKaonPID\", AliRsnCutStd::kRealisticPIDMatch, 0);\n\n cutSetTrack_step4[0]->AddCut(cutKaonBB);\n cutSetTrack_step4[0]->SetCutScheme(\"cutKaonBB\");\n\n cutSetTrack_step4[1]->AddCut(cutRealisticPID);\n cutSetTrack_step4[1]->SetCutScheme(\"cutRealisticPID\");\n\n cutMgrESD_step4[0]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[0]);\n cutMgrESD_step4[1]->SetCutSet(AliRsnCut::kParticle, cutSetTrack_step4[1]);\n\n \/\/ add all steps to the task\n for (Int_t i = 0; i < 2; i++)\n {\n task[i]->AddStepMC (cutMgrMC_step0);\n task[i]->AddStepMC (cutMgrMC_step1);\n task[i]->AddStepESD(cutMgrESD_step2);\n task[i]->AddStepESD(cutMgrESD_step3);\n task[i]->AddStepESD(cutMgrESD_step4[i]);\n }\n\n \/\/ connect containers and finalize\n for (Int_t i = 0; i < 2; i++)\n {\n mgr->AddTask(task[i]);\n mgr->ConnectInput(task[i], 0, mgr->GetCommonInputContainer());\n\n \/\/ create paths for the output in the common file\n Char_t infoPath[500], effPath[500];\n sprintf(infoPath , \"%s:PWG2RSNINFO\" , AliAnalysisManager::GetCommonFileName());\n sprintf(effPath , \"%s:PWG2RSNEFF%s\", AliAnalysisManager::GetCommonFileName(), suf[i].Data());\n\n \/\/ initialize and connect container for the output\n AliAnalysisDataContainer *info = 0x0, *out = 0x0;\n info = mgr->CreateContainer(Form(\"EffInfo_%s\", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, infoPath);\n out = mgr->CreateContainer(Form(\"EFF_%s\", suf[i].Data()), TList::Class(), AliAnalysisManager::kOutputContainer, effPath);\n\n mgr->ConnectOutput(task[i], 1, info);\n mgr->ConnectOutput(task[i], 2, out);\n }\n\n return kTRUE;\n}\n<|endoftext|>"} {"text":"\n\/\/ Copyright (c) 2012, 2013 Lionel MOISAN.\n\/\/ Copyright (c) 2012, 2013 Pascal MONASSE.\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_\n#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_\n\n\/\/-------------------\n\/\/ Generic implementation of ACRANSAC\n\/\/-------------------\n\/\/ The A contrario parametrization have been first explained in [1] and\n\/\/ later extended to generic model estimation in [2] (with a demonstration for\n\/\/ the homography) and extended and use at large scale for Structure from\n\/\/ Motion in [3].\n\/\/\n\/\/--\n\/\/ [1] Lionel Moisan, Berenger Stival,\n\/\/ A probalistic criterion to detect rigid point matches between\n\/\/ two images and estimate the fundamental matrix.\n\/\/ IJCV 04.\n\/\/--\n\/\/ [2] Lionel Moisan, Pierre Moulon, Pascal Monasse.\n\/\/ Automatic Homographic Registration of a Pair of Images,\n\/\/ with A Contrario Elimination of Outliers\n\/\/ Image Processing On Line (IPOL), 2012.\n\/\/ http:\/\/dx.doi.org\/10.5201\/ipol.2012.mmm-oh\n\/\/--\n\/\/ [3] Pierre Moulon, Pascal Monasse and Renaud Marlet.\n\/\/ Adaptive Structure from Motion with a contrario mode estimation.\n\/\/ In 11th Asian Conference on Computer Vision (ACCV 2012)\n\/\/--\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"openMVG\/robust_estimation\/rand_sampling.hpp\"\n\nnamespace openMVG {\nnamespace robust{\n\n\/\/\/ logarithm (base 10) of binomial coefficient\nstatic double logcombi(size_t k, size_t n)\n{\n if (k>=n || k<=0) return(0.0);\n if (n-k\nstatic void makelogcombi_n(size_t n, std::vector & l)\n{\n l.resize(n+1);\n for (size_t k = 0; k <= n; k++)\n l[k] = static_cast( logcombi(k,n) );\n}\n\n\/\/\/ tabulate logcombi(k,.)\ntemplate\nstatic void makelogcombi_k(size_t k, size_t nmax, std::vector & l)\n{\n l.resize(nmax+1);\n for (size_t n = 0; n <= nmax; n++)\n l[n] = static_cast(logcombi(k,n));\n}\n\n\/\/\/ Distance and associated index\ntypedef std::pair ErrorIndex;\n\n\/\/\/ Find best NFA and its index wrt square error threshold in e.\nstatic ErrorIndex bestNFA(\n int startIndex, \/\/number of point required for estimation\n double logalpha0,\n const std::vector& e,\n double loge0,\n double maxThreshold,\n const std::vector &logc_n,\n const std::vector &logc_k,\n double multError = 1.0)\n{\n ErrorIndex bestIndex(std::numeric_limits::infinity(), startIndex);\n const size_t n = e.size();\n for(size_t k = startIndex + 1; k <= n && e[k - 1].first <= maxThreshold; ++k)\n {\n double logalpha = logalpha0 + multError * log10(e[k - 1].first + std::numeric_limits::min());\n ErrorIndex index(loge0 +\n logalpha * (double) (k - startIndex) +\n logc_n[k] +\n logc_k[k], k);\n\n if(index.first < bestIndex.first)\n bestIndex = index;\n }\n return bestIndex;\n}\n\n\/\/\/ Pick a random sample\n\/\/\/ \\param sizeSample The size of the sample.\n\/\/\/ \\param vec_index The possible data indices.\n\/\/\/ \\param sample The random sample of sizeSample indices (output).\nstatic void UniformSample(int sizeSample,\n const std::vector &vec_index,\n std::vector *sample)\n{\n sample->resize(sizeSample);\n random_sample(sizeSample, vec_index.size(), sample);\n for(int i = 0; i < sizeSample; ++i)\n (*sample)[i] = vec_index[ (*sample)[i] ];\n}\n\n\/**\n * @brief ACRANSAC routine (ErrorThreshold, NFA)\n *\n * @param[in] kernel model and metric object\n * @param[out] vec_inliers points that fit the estimated model\n * @param[in] nIter maximum number of consecutive iterations\n * @param[out] model returned model if found\n * @param[in] precision upper bound of the precision (squared error)\n * @param[in] bVerbose display console log\n *\n * @return (errorMax, minNFA)\n *\/\ntemplate\nstd::pair ACRANSAC(const Kernel &kernel,\n std::vector & vec_inliers,\n size_t nIter = 1024,\n typename Kernel::Model * model = NULL,\n double precision = std::numeric_limits::infinity(),\n bool bVerbose = false)\n{\n vec_inliers.clear();\n\n const size_t sizeSample = Kernel::MINIMUM_SAMPLES;\n const size_t nData = kernel.NumSamples();\n if(nData <= (size_t)sizeSample)\n return std::make_pair(0.0,0.0);\n\n const double maxThreshold = (precision==std::numeric_limits::infinity()) ?\n std::numeric_limits::infinity() :\n precision * kernel.normalizer2()(0,0) * kernel.normalizer2()(0,0);\n\n std::vector vec_residuals(nData); \/\/ [residual,index]\n std::vector vec_residuals_(nData);\n std::vector vec_sample(sizeSample); \/\/ Sample indices\n\n \/\/ Possible sampling indices [0,..,nData] (will change in the optimization phase)\n std::vector vec_index(nData);\n std::iota(vec_index.begin(), vec_index.end(), 0);\n\n \/\/ Precompute log combi\n double loge0 = log10((double)Kernel::MAX_MODELS * (nData-sizeSample));\n std::vector vec_logc_n, vec_logc_k;\n makelogcombi_n(nData, vec_logc_n);\n makelogcombi_k(sizeSample, nData, vec_logc_k);\n\n \/\/ Output parameters\n double minNFA = std::numeric_limits::infinity();\n double errorMax = std::numeric_limits::infinity();\n\n \/\/ Reserve 10% of iterations for focused sampling\n size_t nIterReserve = nIter\/10;\n nIter -= nIterReserve;\n\n \/\/ Main estimation loop.\n for (size_t iter=0; iter < nIter; ++iter)\n {\n UniformSample(sizeSample, vec_index, &vec_sample); \/\/ Get random sample\n\n std::vector vec_models; \/\/ Up to max_models solutions\n kernel.Fit(vec_sample, &vec_models);\n\n \/\/ Evaluate models\n bool better = false;\n for (size_t k = 0; k < vec_models.size(); ++k)\n {\n \/\/ Residuals computation and ordering\n kernel.Errors(vec_models[k], vec_residuals_);\n for (size_t i = 0; i < nData; ++i)\n {\n const double error = vec_residuals_[i];\n vec_residuals[i] = ErrorIndex(error, i);\n }\n std::sort(vec_residuals.begin(), vec_residuals.end());\n\n \/\/ Most meaningful discrimination inliers\/outliers\n const ErrorIndex best = bestNFA(\n sizeSample,\n kernel.logalpha0(),\n vec_residuals,\n loge0,\n maxThreshold,\n vec_logc_n,\n vec_logc_k,\n kernel.multError());\n\n if (best.first < minNFA \/*&& vec_residuals[best.second-1].first < errorMax*\/)\n {\n \/\/ A better model was found\n better = true;\n minNFA = best.first;\n vec_inliers.resize(best.second);\n for (size_t i=0; i(std::cout, \",\"));\n std::cout << \")\" <= 0)\n vec_inliers.clear();\n\n if (!vec_inliers.empty())\n {\n if (model)\n kernel.Unnormalize(model);\n errorMax = kernel.unormalizeError(errorMax);\n }\n\n return std::make_pair(errorMax, minNFA);\n}\n\n} \/\/ namespace robust\n} \/\/ namespace openMVG\n#endif \/\/ OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_\n[robust_estimator] partial fix for acransac (ce0850d)\n\/\/ Copyright (c) 2012, 2013 Lionel MOISAN.\n\/\/ Copyright (c) 2012, 2013 Pascal MONASSE.\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_\n#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_\n\n\/\/-------------------\n\/\/ Generic implementation of ACRANSAC\n\/\/-------------------\n\/\/ The A contrario parametrization have been first explained in [1] and\n\/\/ later extended to generic model estimation in [2] (with a demonstration for\n\/\/ the homography) and extended and use at large scale for Structure from\n\/\/ Motion in [3].\n\/\/\n\/\/--\n\/\/ [1] Lionel Moisan, Berenger Stival,\n\/\/ A probalistic criterion to detect rigid point matches between\n\/\/ two images and estimate the fundamental matrix.\n\/\/ IJCV 04.\n\/\/--\n\/\/ [2] Lionel Moisan, Pierre Moulon, Pascal Monasse.\n\/\/ Automatic Homographic Registration of a Pair of Images,\n\/\/ with A Contrario Elimination of Outliers\n\/\/ Image Processing On Line (IPOL), 2012.\n\/\/ http:\/\/dx.doi.org\/10.5201\/ipol.2012.mmm-oh\n\/\/--\n\/\/ [3] Pierre Moulon, Pascal Monasse and Renaud Marlet.\n\/\/ Adaptive Structure from Motion with a contrario mode estimation.\n\/\/ In 11th Asian Conference on Computer Vision (ACCV 2012)\n\/\/--\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"openMVG\/robust_estimation\/rand_sampling.hpp\"\n\nnamespace openMVG {\nnamespace robust{\n\n\/\/\/ logarithm (base 10) of binomial coefficient\nstatic double logcombi(size_t k, size_t n)\n{\n if (k>=n || k<=0) return(0.0);\n if (n-k\nstatic void makelogcombi_n(size_t n, std::vector & l)\n{\n l.resize(n+1);\n for (size_t k = 0; k <= n; k++)\n l[k] = static_cast( logcombi(k,n) );\n}\n\n\/\/\/ tabulate logcombi(k,.)\ntemplate\nstatic void makelogcombi_k(size_t k, size_t nmax, std::vector & l)\n{\n l.resize(nmax+1);\n for (size_t n = 0; n <= nmax; n++)\n l[n] = static_cast(logcombi(k,n));\n}\n\n\/\/\/ Distance and associated index\ntypedef std::pair ErrorIndex;\n\n\/\/\/ Find best NFA and its index wrt square error threshold in e.\nstatic ErrorIndex bestNFA(\n int startIndex, \/\/number of point required for estimation\n double logalpha0,\n const std::vector& e,\n double loge0,\n double maxThreshold,\n const std::vector &logc_n,\n const std::vector &logc_k,\n double multError = 1.0)\n{\n ErrorIndex bestIndex(std::numeric_limits::infinity(), startIndex);\n const size_t n = e.size();\n for(size_t k = startIndex + 1; k <= n && e[k - 1].first <= maxThreshold; ++k)\n {\n const double logalpha = logalpha0 + multError * log10(e[k - 1].first + std::numeric_limits::epsilon());\n ErrorIndex index(loge0 +\n logalpha * (double) (k - startIndex) +\n logc_n[k] +\n logc_k[k], k);\n\n if(index.first < bestIndex.first)\n bestIndex = index;\n }\n return bestIndex;\n}\n\n\/\/\/ Pick a random sample\n\/\/\/ \\param sizeSample The size of the sample.\n\/\/\/ \\param vec_index The possible data indices.\n\/\/\/ \\param sample The random sample of sizeSample indices (output).\nstatic void UniformSample(int sizeSample,\n const std::vector &vec_index,\n std::vector *sample)\n{\n sample->resize(sizeSample);\n random_sample(sizeSample, vec_index.size(), sample);\n for(int i = 0; i < sizeSample; ++i)\n (*sample)[i] = vec_index[ (*sample)[i] ];\n}\n\n\/**\n * @brief ACRANSAC routine (ErrorThreshold, NFA)\n *\n * @param[in] kernel model and metric object\n * @param[out] vec_inliers points that fit the estimated model\n * @param[in] nIter maximum number of consecutive iterations\n * @param[out] model returned model if found\n * @param[in] precision upper bound of the precision (squared error)\n * @param[in] bVerbose display console log\n *\n * @return (errorMax, minNFA)\n *\/\ntemplate\nstd::pair ACRANSAC(const Kernel &kernel,\n std::vector & vec_inliers,\n size_t nIter = 1024,\n typename Kernel::Model * model = NULL,\n double precision = std::numeric_limits::infinity(),\n bool bVerbose = false)\n{\n vec_inliers.clear();\n\n const size_t sizeSample = Kernel::MINIMUM_SAMPLES;\n const size_t nData = kernel.NumSamples();\n if(nData <= (size_t)sizeSample)\n return std::make_pair(0.0,0.0);\n\n const double maxThreshold = (precision==std::numeric_limits::infinity()) ?\n std::numeric_limits::infinity() :\n precision * kernel.normalizer2()(0,0) * kernel.normalizer2()(0,0);\n\n std::vector vec_residuals(nData); \/\/ [residual,index]\n std::vector vec_residuals_(nData);\n std::vector vec_sample(sizeSample); \/\/ Sample indices\n\n \/\/ Possible sampling indices [0,..,nData] (will change in the optimization phase)\n std::vector vec_index(nData);\n std::iota(vec_index.begin(), vec_index.end(), 0);\n\n \/\/ Precompute log combi\n double loge0 = log10((double)Kernel::MAX_MODELS * (nData-sizeSample));\n std::vector vec_logc_n, vec_logc_k;\n makelogcombi_n(nData, vec_logc_n);\n makelogcombi_k(sizeSample, nData, vec_logc_k);\n\n \/\/ Output parameters\n double minNFA = std::numeric_limits::infinity();\n double errorMax = std::numeric_limits::infinity();\n\n \/\/ Reserve 10% of iterations for focused sampling\n size_t nIterReserve = nIter\/10;\n nIter -= nIterReserve;\n\n \/\/ Main estimation loop.\n for (size_t iter=0; iter < nIter; ++iter)\n {\n UniformSample(sizeSample, vec_index, &vec_sample); \/\/ Get random sample\n\n std::vector vec_models; \/\/ Up to max_models solutions\n kernel.Fit(vec_sample, &vec_models);\n\n \/\/ Evaluate models\n bool better = false;\n for (size_t k = 0; k < vec_models.size(); ++k)\n {\n \/\/ Residuals computation and ordering\n kernel.Errors(vec_models[k], vec_residuals_);\n for (size_t i = 0; i < nData; ++i)\n {\n const double error = vec_residuals_[i];\n vec_residuals[i] = ErrorIndex(error, i);\n }\n std::sort(vec_residuals.begin(), vec_residuals.end());\n\n \/\/ Most meaningful discrimination inliers\/outliers\n const ErrorIndex best = bestNFA(\n sizeSample,\n kernel.logalpha0(),\n vec_residuals,\n loge0,\n maxThreshold,\n vec_logc_n,\n vec_logc_k,\n kernel.multError());\n\n if (best.first < minNFA \/*&& vec_residuals[best.second-1].first < errorMax*\/)\n {\n \/\/ A better model was found\n better = true;\n minNFA = best.first;\n vec_inliers.resize(best.second);\n for (size_t i=0; i(std::cout, \",\"));\n std::cout << \")\" <= 0)\n vec_inliers.clear();\n\n if (!vec_inliers.empty())\n {\n if (model)\n kernel.Unnormalize(model);\n errorMax = kernel.unormalizeError(errorMax);\n }\n\n return std::make_pair(errorMax, minNFA);\n}\n\n} \/\/ namespace robust\n} \/\/ namespace openMVG\n#endif \/\/ OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_\n<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ Intel License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000, Intel Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of Intel Corporation may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"gputest.hpp\"\n#include \n#include \n\n#include \n#include \n\nclass CV_GpuMeanShift : public CvTest\n{\n public:\n CV_GpuMeanShift();\n protected:\n void run(int);\n};\n\nCV_GpuMeanShift::CV_GpuMeanShift(): CvTest( \"GPU-MeanShift\", \"meanshift\" ){}\n\nvoid CV_GpuMeanShift::run(int )\n{\n int spatialRad = 30;\n int colorRad = 30;\n\n cv::Mat img = cv::imread(std::string(ts->get_data_path()) + \"meanshift\/con.png\");\n cv::Mat img_template = cv::imread(std::string(ts->get_data_path()) + \"meanshift\/con_result.png\");\n\n cv::Mat rgba;\n cvtColor(img, rgba, CV_BGR2BGRA);\n\n cv::gpu::GpuMat res;\n\n cv::gpu::meanShiftFiltering_GPU( cv::gpu::GpuMat(rgba), res, spatialRad, colorRad );\n\n res.convertTo(res, img_template.type());\n\n double norm = cv::norm(res, img_template, cv::NORM_INF);\n\n ts->set_failed_test_info((norm < 0.5) ? CvTS::OK : CvTS::FAIL_GENERIC);\n}\n\n\nCV_GpuMeanShift CV_GpuMeanShift_test;\nrename con.png to cones.png in test gpu\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ Intel License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000, Intel Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of Intel Corporation may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"gputest.hpp\"\n#include \n#include \n\n#include \n#include \n\nclass CV_GpuMeanShift : public CvTest\n{\n public:\n CV_GpuMeanShift();\n protected:\n void run(int);\n};\n\nCV_GpuMeanShift::CV_GpuMeanShift(): CvTest( \"GPU-MeanShift\", \"meanshift\" ){}\n\nvoid CV_GpuMeanShift::run(int )\n{\n int spatialRad = 30;\n int colorRad = 30;\n\n cv::Mat img = cv::imread(std::string(ts->get_data_path()) + \"meanshift\/cones.png\");\n cv::Mat img_template = cv::imread(std::string(ts->get_data_path()) + \"meanshift\/con_result.png\");\n\n cv::Mat rgba;\n cvtColor(img, rgba, CV_BGR2BGRA);\n\n cv::gpu::GpuMat res;\n\n cv::gpu::meanShiftFiltering_GPU( cv::gpu::GpuMat(rgba), res, spatialRad, colorRad );\n\n res.convertTo(res, img_template.type());\n\n double norm = cv::norm(res, img_template, cv::NORM_INF);\n\n ts->set_failed_test_info((norm < 0.5) ? CvTS::OK : CvTS::FAIL_GENERIC);\n}\n\n\nCV_GpuMeanShift CV_GpuMeanShift_test;\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \"rewriterview.h\"\n#include \"rewritingexception.h\"\n#include \"textmodifier.h\"\n#include \"texttomodelmerger.h\"\n#include \"modelnodepositionstorage.h\"\n#include \"modeltotextmerger.h\"\n#include \"nodelistproperty.h\"\n#include \"nodeproperty.h\"\n#include \"invalidmodelnodeexception.h\"\n\nusing namespace QmlDesigner::Internal;\n\nnamespace QmlDesigner {\n\nRewriterView::Error::Error():\n m_type(NoError),\n m_line(-1),\n m_column(-1)\n{\n}\n\nRewriterView::Error::Error(Exception *exception):\n m_type(InternalError),\n m_line(exception->line()),\n m_column(-1),\n m_description(exception->description()),\n m_url(exception->file())\n{\n}\n\nRewriterView::Error::Error(const QDeclarativeError &qmlError):\n m_type(ParseError),\n m_line(qmlError.line()),\n m_column(qmlError.column()),\n m_description(qmlError.description()),\n m_url(qmlError.url())\n{\n}\n\nQString RewriterView::Error::toString() const\n{\n QString str;\n\n if (m_type == ParseError)\n str += tr(\"Error parsing\");\n else if (m_type == InternalError)\n str += tr(\"Internal error\");\n\n if (url().isValid()) {\n if (!str.isEmpty())\n str += QLatin1Char(' ');\n\n str += tr(\"\\\"%1\\\"\").arg(url().toString());\n }\n\n if (line() != -1) {\n if (!str.isEmpty())\n str += QLatin1Char(' ');\n str += tr(\"line %1\").arg(line());\n }\n\n if(column() != -1) {\n if (!str.isEmpty())\n str += QLatin1Char(' ');\n\n str += tr(\"column %1\").arg(column());\n }\n\n if (!str.isEmpty())\n QLatin1String(\": \");\n str += description();\n\n return str;\n}\n\nRewriterView::RewriterView(DifferenceHandling differenceHandling, QObject *parent):\n AbstractView(parent),\n m_differenceHandling(differenceHandling),\n m_modificationGroupActive(false),\n m_positionStorage(new ModelNodePositionStorage),\n m_modelToTextMerger(new Internal::ModelToTextMerger(this)),\n m_textToModelMerger(new Internal::TextToModelMerger(this)),\n m_textModifier(0),\n transactionLevel(0)\n{\n}\n\nRewriterView::~RewriterView()\n{\n delete m_positionStorage;\n}\n\nInternal::ModelToTextMerger *RewriterView::modelToTextMerger() const\n{\n return m_modelToTextMerger.data();\n}\n\nInternal::TextToModelMerger *RewriterView::textToModelMerger() const\n{\n return m_textToModelMerger.data();\n}\n\nvoid RewriterView::modelAttached(Model *model)\n{\n AbstractView::modelAttached(model);\n\n ModelAmender differenceHandler(m_textToModelMerger.data());\n const QString qmlSource = m_textModifier->text();\n if (m_textToModelMerger->load(qmlSource.toUtf8(), differenceHandler)) {\n lastCorrectQmlSource = qmlSource;\n }\n}\n\nvoid RewriterView::modelAboutToBeDetached(Model * \/*model*\/)\n{\n m_positionStorage->clear();\n}\n\nvoid RewriterView::nodeCreated(const ModelNode &createdNode)\n{\n Q_ASSERT(textModifier());\n m_positionStorage->setNodeOffset(createdNode, ModelNodePositionStorage::INVALID_LOCATION);\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeCreated(createdNode);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::nodeAboutToBeRemoved(const ModelNode &\/*removedNode*\/)\n{\n}\n\nvoid RewriterView::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeRemoved(removedNode, parentProperty, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::propertiesAdded(const ModelNode &\/*node*\/, const QList& \/*propertyList*\/)\n{\n Q_ASSERT(0);\n}\n\nvoid RewriterView::propertiesAboutToBeRemoved(const QList &propertyList)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n\n foreach (const AbstractProperty &property, propertyList) {\n if (property.isDefaultProperty() && property.isNodeListProperty()) {\n m_removeDefaultPropertyTransaction = beginRewriterTransaction();\n\n foreach (const ModelNode &node, property.toNodeListProperty().toModelNodeList()) {\n modelToTextMerger()->nodeRemoved(node, property.toNodeAbstractProperty(), AbstractView::NoAdditionalChanges);\n }\n }\n }\n}\n\nvoid RewriterView::propertiesRemoved(const QList& propertyList)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->propertiesRemoved(propertyList);\n\n if (m_removeDefaultPropertyTransaction.isValid())\n m_removeDefaultPropertyTransaction.commit();\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::variantPropertiesChanged(const QList& propertyList, PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n QList usefulPropertyList;\n foreach (const VariantProperty &property, propertyList)\n usefulPropertyList.append(property);\n\n modelToTextMerger()->propertiesChanged(usefulPropertyList, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::bindingPropertiesChanged(const QList& propertyList, PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n QList usefulPropertyList;\n foreach (const BindingProperty &property, propertyList)\n usefulPropertyList.append(property);\n\n modelToTextMerger()->propertiesChanged(usefulPropertyList, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::importAdded(const Import &import)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->addImport(import);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::importRemoved(const Import &import)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->removeImport(import);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::fileUrlChanged(const QUrl &\/*oldUrl*\/, const QUrl &\/*newUrl*\/)\n{\n}\n\nvoid RewriterView::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeIdChanged(node, newId, oldId);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int \/*oldIndex*\/)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n const QList nodes = listProperty.toModelNodeList();\n\n ModelNode trailingNode;\n int newIndex = nodes.indexOf(movedNode);\n if (newIndex + 1 < nodes.size())\n trailingNode = nodes.at(newIndex + 1);\n modelToTextMerger()->nodeSlidAround(movedNode, trailingNode);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeTypeChanged(rootModelNode(), type, majorVersion, minorVersion);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::customNotification(const AbstractView * \/*view*\/, const QString &identifier, const QList & \/* nodeList *\/, const QList & \/*data *\/)\n{\n if (identifier == StartRewriterAmend || identifier == EndRewriterAmend)\n return; \/\/ we emitted this ourselves, so just ignore these notifications.\n\n if (identifier == (\"__start rewriter transaction__\")) {\n transactionLevel++;\n setModificationGroupActive(true);\n }\n else if (identifier == (\"__end rewriter transaction__\")) {\n transactionLevel--;\n Q_ASSERT(transactionLevel >= 0);\n\n }\n if (transactionLevel == 0)\n {\n setModificationGroupActive(false);\n applyModificationGroupChanges();\n }\n}\n\nvoid RewriterView::selectedNodesChanged(const QList & \/* selectedNodeList, *\/, const QList & \/*lastSelectedNodeList *\/)\n{\n}\n\nbool RewriterView::isModificationGroupActive() const\n{\n return m_modificationGroupActive;\n}\n\nvoid RewriterView::setModificationGroupActive(bool active)\n{\n m_modificationGroupActive = active;\n}\n\nTextModifier *RewriterView::textModifier() const\n{\n return m_textModifier;\n}\n\nvoid RewriterView::setTextModifier(TextModifier *textModifier)\n{\n if (m_textModifier)\n disconnect(m_textModifier, SIGNAL(textChanged()), this, SLOT(qmlTextChanged()));\n\n m_textModifier = textModifier;\n\n if (m_textModifier)\n connect(m_textModifier, SIGNAL(textChanged()), this, SLOT(qmlTextChanged()));\n}\n\nQString RewriterView::textModifierContent() const\n{\n if (textModifier())\n return textModifier()->text();\n\n return QString();\n}\n\nvoid RewriterView::applyModificationGroupChanges()\n{\n Q_ASSERT(transactionLevel == 0);\n applyChanges();\n}\n\nvoid RewriterView::applyChanges()\n{\n if (modelToTextMerger()->hasNoPendingChanges())\n return; \/\/ quick exit: nothing to be done.\n\n clearErrors();\n\n if (inErrorState()) {\n qDebug() << \"RewriterView::applyChanges() got called while in error state. Will do a quick-exit now.\";\n throw RewritingException(__LINE__, __FUNCTION__, __FILE__, \"RewriterView::applyChanges() already in error state\", textModifierContent());\n }\n\n try {\n modelToTextMerger()->applyChanges();\n if (!errors().isEmpty()) {\n enterErrorState(errors().first().description());\n }\n } catch (Exception &e) {\n enterErrorState(e.description());\n }\n\n if (inErrorState()) {\n throw RewritingException(__LINE__, __FUNCTION__, __FILE__, m_rewritingErrorMessage, textModifierContent());\n }\n}\n\nQList RewriterView::errors() const\n{\n return m_errors;\n}\n\nvoid RewriterView::clearErrors()\n{\n m_errors.clear();\n emit errorsChanged(m_errors);\n}\n\nvoid RewriterView::setErrors(const QList &errors)\n{\n m_errors = errors;\n emit errorsChanged(m_errors);\n}\n\nvoid RewriterView::addError(const RewriterView::Error &error)\n{\n m_errors.append(error);\n emit errorsChanged(m_errors);\n}\n\nvoid RewriterView::enterErrorState(const QString &errorMessage)\n{\n m_rewritingErrorMessage = errorMessage;\n}\n\nvoid RewriterView::resetToLastCorrectQml()\n{\n m_textModifier->textDocument()->undo();\n m_textModifier->textDocument()->clearUndoRedoStacks(QTextDocument::RedoStack);\n ModelAmender differenceHandler(m_textToModelMerger.data());\n m_textToModelMerger->load(m_textModifier->text().toUtf8(), differenceHandler);\n\n leaveErrorState();\n}\n\nQMap RewriterView::extractText(const QList &nodes) const\n{\n QmlDesigner::ASTObjectTextExtractor extract(m_textModifier->text());\n QMap result;\n\n foreach (const ModelNode &node, nodes) {\n const int nodeLocation = m_positionStorage->nodeOffset(node);\n\n if (nodeLocation == ModelNodePositionStorage::INVALID_LOCATION)\n result.insert(node, QString());\n else\n result.insert(node, extract(nodeLocation));\n }\n\n return result;\n}\n\nint RewriterView::nodeOffset(const ModelNode &node) const\n{\n return m_positionStorage->nodeOffset(node);\n}\n\n\/**\n * \\return the length of the node's text, or -1 if it wasn't found or if an error\n * occurred.\n *\/\nint RewriterView::nodeLength(const ModelNode &node) const\n{\n ObjectLengthCalculator objectLengthCalculator;\n unsigned length;\n if (objectLengthCalculator(m_textModifier->text(), nodeOffset(node), length))\n return (int) length;\n else\n return -1;\n}\n\nint RewriterView::firstDefinitionInsideOffset(const ModelNode &node) const\n{\n FirstDefinitionFinder firstDefinitionFinder(m_textModifier->text());\n return firstDefinitionFinder(nodeOffset(node));\n}\n\nint RewriterView::firstDefinitionInsideLength(const ModelNode &node) const\n{\n FirstDefinitionFinder firstDefinitionFinder(m_textModifier->text());\n const int offset = firstDefinitionFinder(nodeOffset(node));\n\n ObjectLengthCalculator objectLengthCalculator;\n unsigned length;\n if (objectLengthCalculator(m_textModifier->text(), offset, length))\n return length;\n else\n return -1;\n}\n\nbool RewriterView::modificationGroupActive()\n{\n return m_modificationGroupActive;\n}\n\nvoid RewriterView::qmlTextChanged()\n{\n if (inErrorState())\n return;\n\n if (m_textToModelMerger && m_textModifier) {\n const QString newQmlText = m_textModifier->text();\n\n\/\/ qDebug() << \"qmlTextChanged:\" << newQmlText;\n\n switch (m_differenceHandling) {\n case Validate: {\n ModelValidator differenceHandler(m_textToModelMerger.data());\n if (m_textToModelMerger->load(newQmlText.toUtf8(), differenceHandler)) {\n lastCorrectQmlSource = newQmlText;\n }\n break;\n }\n\n case Amend:\n default: {\n emitCustomNotification(StartRewriterAmend);\n ModelAmender differenceHandler(m_textToModelMerger.data());\n if (m_textToModelMerger->load(newQmlText, differenceHandler)) {\n lastCorrectQmlSource = newQmlText;\n }\n emitCustomNotification(EndRewriterAmend);\n break;\n }\n }\n }\n}\n\n} \/\/QmlDesigner\nAdded more debugging info to rewriterview\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \"rewriterview.h\"\n#include \"rewritingexception.h\"\n#include \"textmodifier.h\"\n#include \"texttomodelmerger.h\"\n#include \"modelnodepositionstorage.h\"\n#include \"modeltotextmerger.h\"\n#include \"nodelistproperty.h\"\n#include \"nodeproperty.h\"\n#include \"invalidmodelnodeexception.h\"\n\nusing namespace QmlDesigner::Internal;\n\nnamespace QmlDesigner {\n\nRewriterView::Error::Error():\n m_type(NoError),\n m_line(-1),\n m_column(-1)\n{\n}\n\nRewriterView::Error::Error(Exception *exception):\n m_type(InternalError),\n m_line(exception->line()),\n m_column(-1),\n m_description(exception->description()),\n m_url(exception->file())\n{\n}\n\nRewriterView::Error::Error(const QDeclarativeError &qmlError):\n m_type(ParseError),\n m_line(qmlError.line()),\n m_column(qmlError.column()),\n m_description(qmlError.description()),\n m_url(qmlError.url())\n{\n}\n\nQString RewriterView::Error::toString() const\n{\n QString str;\n\n if (m_type == ParseError)\n str += tr(\"Error parsing\");\n else if (m_type == InternalError)\n str += tr(\"Internal error\");\n\n if (url().isValid()) {\n if (!str.isEmpty())\n str += QLatin1Char(' ');\n\n str += tr(\"\\\"%1\\\"\").arg(url().toString());\n }\n\n if (line() != -1) {\n if (!str.isEmpty())\n str += QLatin1Char(' ');\n str += tr(\"line %1\").arg(line());\n }\n\n if(column() != -1) {\n if (!str.isEmpty())\n str += QLatin1Char(' ');\n\n str += tr(\"column %1\").arg(column());\n }\n\n if (!str.isEmpty())\n QLatin1String(\": \");\n str += description();\n\n return str;\n}\n\nRewriterView::RewriterView(DifferenceHandling differenceHandling, QObject *parent):\n AbstractView(parent),\n m_differenceHandling(differenceHandling),\n m_modificationGroupActive(false),\n m_positionStorage(new ModelNodePositionStorage),\n m_modelToTextMerger(new Internal::ModelToTextMerger(this)),\n m_textToModelMerger(new Internal::TextToModelMerger(this)),\n m_textModifier(0),\n transactionLevel(0)\n{\n}\n\nRewriterView::~RewriterView()\n{\n delete m_positionStorage;\n}\n\nInternal::ModelToTextMerger *RewriterView::modelToTextMerger() const\n{\n return m_modelToTextMerger.data();\n}\n\nInternal::TextToModelMerger *RewriterView::textToModelMerger() const\n{\n return m_textToModelMerger.data();\n}\n\nvoid RewriterView::modelAttached(Model *model)\n{\n AbstractView::modelAttached(model);\n\n ModelAmender differenceHandler(m_textToModelMerger.data());\n const QString qmlSource = m_textModifier->text();\n if (m_textToModelMerger->load(qmlSource.toUtf8(), differenceHandler)) {\n lastCorrectQmlSource = qmlSource;\n }\n}\n\nvoid RewriterView::modelAboutToBeDetached(Model * \/*model*\/)\n{\n m_positionStorage->clear();\n}\n\nvoid RewriterView::nodeCreated(const ModelNode &createdNode)\n{\n Q_ASSERT(textModifier());\n m_positionStorage->setNodeOffset(createdNode, ModelNodePositionStorage::INVALID_LOCATION);\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeCreated(createdNode);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::nodeAboutToBeRemoved(const ModelNode &\/*removedNode*\/)\n{\n}\n\nvoid RewriterView::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeRemoved(removedNode, parentProperty, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::propertiesAdded(const ModelNode &\/*node*\/, const QList& \/*propertyList*\/)\n{\n Q_ASSERT(0);\n}\n\nvoid RewriterView::propertiesAboutToBeRemoved(const QList &propertyList)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n\n foreach (const AbstractProperty &property, propertyList) {\n if (property.isDefaultProperty() && property.isNodeListProperty()) {\n m_removeDefaultPropertyTransaction = beginRewriterTransaction();\n\n foreach (const ModelNode &node, property.toNodeListProperty().toModelNodeList()) {\n modelToTextMerger()->nodeRemoved(node, property.toNodeAbstractProperty(), AbstractView::NoAdditionalChanges);\n }\n }\n }\n}\n\nvoid RewriterView::propertiesRemoved(const QList& propertyList)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->propertiesRemoved(propertyList);\n\n if (m_removeDefaultPropertyTransaction.isValid())\n m_removeDefaultPropertyTransaction.commit();\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::variantPropertiesChanged(const QList& propertyList, PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n QList usefulPropertyList;\n foreach (const VariantProperty &property, propertyList)\n usefulPropertyList.append(property);\n\n modelToTextMerger()->propertiesChanged(usefulPropertyList, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::bindingPropertiesChanged(const QList& propertyList, PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n QList usefulPropertyList;\n foreach (const BindingProperty &property, propertyList)\n usefulPropertyList.append(property);\n\n modelToTextMerger()->propertiesChanged(usefulPropertyList, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::importAdded(const Import &import)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->addImport(import);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::importRemoved(const Import &import)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->removeImport(import);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::fileUrlChanged(const QUrl &\/*oldUrl*\/, const QUrl &\/*newUrl*\/)\n{\n}\n\nvoid RewriterView::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeIdChanged(node, newId, oldId);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int \/*oldIndex*\/)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n const QList nodes = listProperty.toModelNodeList();\n\n ModelNode trailingNode;\n int newIndex = nodes.indexOf(movedNode);\n if (newIndex + 1 < nodes.size())\n trailingNode = nodes.at(newIndex + 1);\n modelToTextMerger()->nodeSlidAround(movedNode, trailingNode);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)\n{\n Q_ASSERT(textModifier());\n if (textToModelMerger()->isActive())\n return;\n\n modelToTextMerger()->nodeTypeChanged(rootModelNode(), type, majorVersion, minorVersion);\n\n if (!isModificationGroupActive())\n applyChanges();\n}\n\nvoid RewriterView::customNotification(const AbstractView * \/*view*\/, const QString &identifier, const QList & \/* nodeList *\/, const QList & \/*data *\/)\n{\n if (identifier == StartRewriterAmend || identifier == EndRewriterAmend)\n return; \/\/ we emitted this ourselves, so just ignore these notifications.\n\n if (identifier == (\"__start rewriter transaction__\")) {\n transactionLevel++;\n setModificationGroupActive(true);\n }\n else if (identifier == (\"__end rewriter transaction__\")) {\n transactionLevel--;\n Q_ASSERT(transactionLevel >= 0);\n\n }\n if (transactionLevel == 0)\n {\n setModificationGroupActive(false);\n applyModificationGroupChanges();\n }\n}\n\nvoid RewriterView::selectedNodesChanged(const QList & \/* selectedNodeList, *\/, const QList & \/*lastSelectedNodeList *\/)\n{\n}\n\nbool RewriterView::isModificationGroupActive() const\n{\n return m_modificationGroupActive;\n}\n\nvoid RewriterView::setModificationGroupActive(bool active)\n{\n m_modificationGroupActive = active;\n}\n\nTextModifier *RewriterView::textModifier() const\n{\n return m_textModifier;\n}\n\nvoid RewriterView::setTextModifier(TextModifier *textModifier)\n{\n if (m_textModifier)\n disconnect(m_textModifier, SIGNAL(textChanged()), this, SLOT(qmlTextChanged()));\n\n m_textModifier = textModifier;\n\n if (m_textModifier)\n connect(m_textModifier, SIGNAL(textChanged()), this, SLOT(qmlTextChanged()));\n}\n\nQString RewriterView::textModifierContent() const\n{\n if (textModifier())\n return textModifier()->text();\n\n return QString();\n}\n\nvoid RewriterView::applyModificationGroupChanges()\n{\n Q_ASSERT(transactionLevel == 0);\n applyChanges();\n}\n\nvoid RewriterView::applyChanges()\n{\n if (modelToTextMerger()->hasNoPendingChanges())\n return; \/\/ quick exit: nothing to be done.\n\n clearErrors();\n\n if (inErrorState()) {\n const QString content = textModifierContent();\n qDebug() << \"RewriterView::applyChanges() got called while in error state. Will do a quick-exit now.\";\n qDebug() << \"Content:\" << content;\n throw RewritingException(__LINE__, __FUNCTION__, __FILE__, \"RewriterView::applyChanges() already in error state\", content);\n }\n\n try {\n modelToTextMerger()->applyChanges();\n if (!errors().isEmpty()) {\n enterErrorState(errors().first().description());\n }\n } catch (Exception &e) {\n const QString content = textModifierContent();\n qDebug() << \"RewriterException:\" << m_rewritingErrorMessage;\n qDebug() << \"Content:\" << content;\n enterErrorState(e.description());\n }\n\n if (inErrorState()) {\n const QString content = textModifierContent();\n qDebug() << \"RewriterException:\" << m_rewritingErrorMessage;\n qDebug() << \"Content:\" << content;\n throw RewritingException(__LINE__, __FUNCTION__, __FILE__, m_rewritingErrorMessage, content);\n }\n}\n\nQList RewriterView::errors() const\n{\n return m_errors;\n}\n\nvoid RewriterView::clearErrors()\n{\n m_errors.clear();\n emit errorsChanged(m_errors);\n}\n\nvoid RewriterView::setErrors(const QList &errors)\n{\n m_errors = errors;\n emit errorsChanged(m_errors);\n}\n\nvoid RewriterView::addError(const RewriterView::Error &error)\n{\n m_errors.append(error);\n emit errorsChanged(m_errors);\n}\n\nvoid RewriterView::enterErrorState(const QString &errorMessage)\n{\n m_rewritingErrorMessage = errorMessage;\n}\n\nvoid RewriterView::resetToLastCorrectQml()\n{\n m_textModifier->textDocument()->undo();\n m_textModifier->textDocument()->clearUndoRedoStacks(QTextDocument::RedoStack);\n ModelAmender differenceHandler(m_textToModelMerger.data());\n m_textToModelMerger->load(m_textModifier->text().toUtf8(), differenceHandler);\n\n leaveErrorState();\n}\n\nQMap RewriterView::extractText(const QList &nodes) const\n{\n QmlDesigner::ASTObjectTextExtractor extract(m_textModifier->text());\n QMap result;\n\n foreach (const ModelNode &node, nodes) {\n const int nodeLocation = m_positionStorage->nodeOffset(node);\n\n if (nodeLocation == ModelNodePositionStorage::INVALID_LOCATION)\n result.insert(node, QString());\n else\n result.insert(node, extract(nodeLocation));\n }\n\n return result;\n}\n\nint RewriterView::nodeOffset(const ModelNode &node) const\n{\n return m_positionStorage->nodeOffset(node);\n}\n\n\/**\n * \\return the length of the node's text, or -1 if it wasn't found or if an error\n * occurred.\n *\/\nint RewriterView::nodeLength(const ModelNode &node) const\n{\n ObjectLengthCalculator objectLengthCalculator;\n unsigned length;\n if (objectLengthCalculator(m_textModifier->text(), nodeOffset(node), length))\n return (int) length;\n else\n return -1;\n}\n\nint RewriterView::firstDefinitionInsideOffset(const ModelNode &node) const\n{\n FirstDefinitionFinder firstDefinitionFinder(m_textModifier->text());\n return firstDefinitionFinder(nodeOffset(node));\n}\n\nint RewriterView::firstDefinitionInsideLength(const ModelNode &node) const\n{\n FirstDefinitionFinder firstDefinitionFinder(m_textModifier->text());\n const int offset = firstDefinitionFinder(nodeOffset(node));\n\n ObjectLengthCalculator objectLengthCalculator;\n unsigned length;\n if (objectLengthCalculator(m_textModifier->text(), offset, length))\n return length;\n else\n return -1;\n}\n\nbool RewriterView::modificationGroupActive()\n{\n return m_modificationGroupActive;\n}\n\nvoid RewriterView::qmlTextChanged()\n{\n if (inErrorState())\n return;\n\n if (m_textToModelMerger && m_textModifier) {\n const QString newQmlText = m_textModifier->text();\n\n\/\/ qDebug() << \"qmlTextChanged:\" << newQmlText;\n\n switch (m_differenceHandling) {\n case Validate: {\n ModelValidator differenceHandler(m_textToModelMerger.data());\n if (m_textToModelMerger->load(newQmlText.toUtf8(), differenceHandler)) {\n lastCorrectQmlSource = newQmlText;\n }\n break;\n }\n\n case Amend:\n default: {\n emitCustomNotification(StartRewriterAmend);\n ModelAmender differenceHandler(m_textToModelMerger.data());\n if (m_textToModelMerger->load(newQmlText, differenceHandler)) {\n lastCorrectQmlSource = newQmlText;\n }\n emitCustomNotification(EndRewriterAmend);\n break;\n }\n }\n }\n}\n\n} \/\/QmlDesigner\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsPageSelector.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2006-04-06 16:20:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"controller\/SlsPageSelector.hxx\"\n\n#include \"SlideSorterViewShell.hxx\"\n#include \"controller\/SlideSorterController.hxx\"\n#include \"model\/SlsPageDescriptor.hxx\"\n#include \"model\/SlsPageEnumeration.hxx\"\n#include \"model\/SlideSorterModel.hxx\"\n#include \"view\/SlideSorterView.hxx\"\n\n#include \"sdpage.hxx\"\n#include \"ViewShell.hxx\"\n#include \"DrawViewShell.hxx\"\n#include \"ViewShellBase.hxx\"\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::sd::slidesorter::model;\nusing namespace ::sd::slidesorter::view;\n\nnamespace sd { namespace slidesorter { namespace controller {\n\n\nPageSelector::PageSelector (\n model::SlideSorterModel& rModel,\n SlideSorterController& rController)\n : mrModel(rModel),\n mrController (rController),\n mnSelectedPageCount(0),\n mnBroadcastDisableLevel(0),\n mbSelectionChangeBroadcastPending(false),\n mpMostRecentlySelectedPage(),\n mpSelectionAnchor()\n{\n CountSelectedPages ();\n}\n\n\n\n\nvoid PageSelector::SelectAllPages (void)\n{\n int nPageCount = mrModel.GetPageCount();\n for (int nPageIndex=0; nPageIndexUpdateSelection())\n {\n mrController.GetView().RequestRepaint(pDescriptor);\n if (mnBroadcastDisableLevel > 0)\n mbSelectionChangeBroadcastPending = true;\n else\n mrController.SelectionHasChanged();\n }\n\n if (pDescriptor->IsSelected())\n mnSelectedPageCount++;\n }\n}\n\n\n\n\nvoid PageSelector::SelectPage (int nPageIndex)\n{\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n SelectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::SelectPage (const SdPage* pPage)\n{\n int nPageIndex = (pPage->GetPageNum()-1) \/ 2;\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get()!=NULL && pDescriptor->GetPage()==pPage)\n SelectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::SelectPage (const SharedPageDescriptor& rpDescriptor)\n{\n if (rpDescriptor.get()!=NULL && rpDescriptor->Select())\n {\n mnSelectedPageCount ++;\n mrController.GetView().RequestRepaint(rpDescriptor);\n\n mpMostRecentlySelectedPage = rpDescriptor;\n if (mpSelectionAnchor == NULL)\n mpSelectionAnchor = rpDescriptor;\n\n if (mnBroadcastDisableLevel > 0)\n mbSelectionChangeBroadcastPending = true;\n else\n mrController.SelectionHasChanged();\n }\n}\n\n\n\n\nvoid PageSelector::DeselectPage (int nPageIndex)\n{\n model::SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n DeselectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::DeselectPage (const SdPage* pPage)\n{\n int nPageIndex = (pPage->GetPageNum()-1) \/ 2;\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get()!=NULL && pDescriptor->GetPage()==pPage)\n DeselectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::DeselectPage (const SharedPageDescriptor& rpDescriptor)\n{\n if (rpDescriptor.get()!=NULL && rpDescriptor->Deselect())\n {\n mnSelectedPageCount --;\n mrController.GetView().RequestRepaint(rpDescriptor);\n if (mpMostRecentlySelectedPage == rpDescriptor)\n mpMostRecentlySelectedPage.reset();\n if (mnBroadcastDisableLevel > 0)\n mbSelectionChangeBroadcastPending = true;\n else\n mrController.SelectionHasChanged();\n }\n}\n\n\n\n\nbool PageSelector::IsPageSelected (int nPageIndex)\n{\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n return pDescriptor->IsSelected();\n else\n return false;\n}\n\n\n\n\nvoid PageSelector::SetCurrentPage (const SharedPageDescriptor& rpDescriptor)\n{\n \/\/ Set current page. At the moment we have to do this in two different\n \/\/ ways. The UNO way is the preferable one but, alas, it does not work\n \/\/ always correctly (after some kinds of model changes). Therefore, we\n \/\/ call DrawViewShell::SwitchPage(), too.\n try\n {\n \/\/ First the traditional way.\n DrawViewShell* pDrawViewShell = dynamic_cast(\n mrController.GetViewShell().GetViewShellBase().GetMainViewShell());\n if (pDrawViewShell != NULL)\n {\n USHORT nPageNumber = (rpDescriptor->GetPage()->GetPageNum()-1)\/2;\n pDrawViewShell->SwitchPage(nPageNumber);\n pDrawViewShell->GetPageTabControl()->SetCurPageId(nPageNumber+1);\n }\n\n \/\/ Now the UNO way.\n do\n {\n Reference xSet (\n mrController.GetViewShell().GetViewShellBase().GetController(),\n UNO_QUERY);\n if ( ! xSet.is())\n break;\n\n Any aPage;\n aPage <<= rpDescriptor->GetPage()->getUnoPage();\n xSet->setPropertyValue (\n String::CreateFromAscii(\"CurrentPage\"),\n aPage);\n }\n while (false);\n }\n catch (beans::UnknownPropertyException aException)\n {\n \/\/ We have not been able to set the current page at the main view.\n \/\/ This is sad but still leaves us in a valid state. Therefore,\n \/\/ this exception is silently ignored.\n }\n}\n\n\n\n\nvoid PageSelector::SetCurrentPage (const SdPage* pPage)\n{\n int nPageIndex = (pPage->GetPageNum()-1) \/ 2;\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get()!=NULL && pDescriptor->GetPage()==pPage)\n SetCurrentPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::SetCurrentPage (int nPageIndex)\n{\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n SetCurrentPage(pDescriptor);\n}\n\n\n\n\nint PageSelector::GetPageCount (void) const\n{\n return mrModel.GetPageCount();\n}\n\n\n\n\nint PageSelector::GetSelectedPageCount (void) const\n{\n return mnSelectedPageCount;\n}\n\n\n\n\nvoid PageSelector::PrepareModelChange (void)\n{\n DeselectAllPages ();\n}\n\n\n\n\nvoid PageSelector::HandleModelChange (void)\n{\n UpdateAllPages();\n}\n\n\n\n\nSharedPageDescriptor PageSelector::GetMostRecentlySelectedPage (void) const\n{\n return mpMostRecentlySelectedPage;\n}\n\n\n\n\nSharedPageDescriptor PageSelector::GetSelectionAnchor (void) const\n{\n return mpSelectionAnchor;\n}\n\n\n\n\nvoid PageSelector::CountSelectedPages (void)\n{\n mnSelectedPageCount = 0;\n model::SlideSorterModel::Enumeration aSelectedPages (\n mrModel.GetSelectedPagesEnumeration());\n while (aSelectedPages.HasMoreElements())\n {\n mnSelectedPageCount++;\n aSelectedPages.GetNextElement();\n }\n}\n\n\n\n\nvoid PageSelector::EnableBroadcasting (bool bMakeSelectionVisible)\n{\n if (mnBroadcastDisableLevel > 0)\n mnBroadcastDisableLevel --;\n if (mnBroadcastDisableLevel==0 && mbSelectionChangeBroadcastPending)\n {\n mrController.SelectionHasChanged(bMakeSelectionVisible);\n mbSelectionChangeBroadcastPending = false;\n }\n}\n\n\n\n\nvoid PageSelector::DisableBroadcasting (void)\n{\n mnBroadcastDisableLevel ++;\n}\n\n\n\n\n::std::auto_ptr\n PageSelector::GetPageSelection (void)\n{\n ::std::auto_ptr pSelection (new PageSelection());\n\n int nPageCount = GetPageCount();\n for (int nIndex=0; nIndexinsert (nIndex);\n }\n\n return pSelection;\n}\n\n\n\n\nvoid PageSelector::SetPageSelection (const PageSelection& rSelection)\n{\n PageSelection::const_iterator iIndex;\n for (iIndex=rSelection.begin(); iIndex!=rSelection.end(); ++iIndex)\n SelectPage (*iIndex);\n}\n\n} } } \/\/ end of namespace ::sd::slidesorter::controller\nINTEGRATION: CWS pchfix02 (1.7.122); FILE MERGED 2006\/09\/01 17:37:17 kaib 1.7.122.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsPageSelector.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 19:06:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"controller\/SlsPageSelector.hxx\"\n\n#include \"SlideSorterViewShell.hxx\"\n#include \"controller\/SlideSorterController.hxx\"\n#include \"model\/SlsPageDescriptor.hxx\"\n#include \"model\/SlsPageEnumeration.hxx\"\n#include \"model\/SlideSorterModel.hxx\"\n#include \"view\/SlideSorterView.hxx\"\n\n#include \"sdpage.hxx\"\n#include \"ViewShell.hxx\"\n#include \"DrawViewShell.hxx\"\n#include \"ViewShellBase.hxx\"\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::sd::slidesorter::model;\nusing namespace ::sd::slidesorter::view;\n\nnamespace sd { namespace slidesorter { namespace controller {\n\n\nPageSelector::PageSelector (\n model::SlideSorterModel& rModel,\n SlideSorterController& rController)\n : mrModel(rModel),\n mrController (rController),\n mnSelectedPageCount(0),\n mnBroadcastDisableLevel(0),\n mbSelectionChangeBroadcastPending(false),\n mpMostRecentlySelectedPage(),\n mpSelectionAnchor()\n{\n CountSelectedPages ();\n}\n\n\n\n\nvoid PageSelector::SelectAllPages (void)\n{\n int nPageCount = mrModel.GetPageCount();\n for (int nPageIndex=0; nPageIndexUpdateSelection())\n {\n mrController.GetView().RequestRepaint(pDescriptor);\n if (mnBroadcastDisableLevel > 0)\n mbSelectionChangeBroadcastPending = true;\n else\n mrController.SelectionHasChanged();\n }\n\n if (pDescriptor->IsSelected())\n mnSelectedPageCount++;\n }\n}\n\n\n\n\nvoid PageSelector::SelectPage (int nPageIndex)\n{\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n SelectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::SelectPage (const SdPage* pPage)\n{\n int nPageIndex = (pPage->GetPageNum()-1) \/ 2;\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get()!=NULL && pDescriptor->GetPage()==pPage)\n SelectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::SelectPage (const SharedPageDescriptor& rpDescriptor)\n{\n if (rpDescriptor.get()!=NULL && rpDescriptor->Select())\n {\n mnSelectedPageCount ++;\n mrController.GetView().RequestRepaint(rpDescriptor);\n\n mpMostRecentlySelectedPage = rpDescriptor;\n if (mpSelectionAnchor == NULL)\n mpSelectionAnchor = rpDescriptor;\n\n if (mnBroadcastDisableLevel > 0)\n mbSelectionChangeBroadcastPending = true;\n else\n mrController.SelectionHasChanged();\n }\n}\n\n\n\n\nvoid PageSelector::DeselectPage (int nPageIndex)\n{\n model::SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n DeselectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::DeselectPage (const SdPage* pPage)\n{\n int nPageIndex = (pPage->GetPageNum()-1) \/ 2;\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get()!=NULL && pDescriptor->GetPage()==pPage)\n DeselectPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::DeselectPage (const SharedPageDescriptor& rpDescriptor)\n{\n if (rpDescriptor.get()!=NULL && rpDescriptor->Deselect())\n {\n mnSelectedPageCount --;\n mrController.GetView().RequestRepaint(rpDescriptor);\n if (mpMostRecentlySelectedPage == rpDescriptor)\n mpMostRecentlySelectedPage.reset();\n if (mnBroadcastDisableLevel > 0)\n mbSelectionChangeBroadcastPending = true;\n else\n mrController.SelectionHasChanged();\n }\n}\n\n\n\n\nbool PageSelector::IsPageSelected (int nPageIndex)\n{\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n return pDescriptor->IsSelected();\n else\n return false;\n}\n\n\n\n\nvoid PageSelector::SetCurrentPage (const SharedPageDescriptor& rpDescriptor)\n{\n \/\/ Set current page. At the moment we have to do this in two different\n \/\/ ways. The UNO way is the preferable one but, alas, it does not work\n \/\/ always correctly (after some kinds of model changes). Therefore, we\n \/\/ call DrawViewShell::SwitchPage(), too.\n try\n {\n \/\/ First the traditional way.\n DrawViewShell* pDrawViewShell = dynamic_cast(\n mrController.GetViewShell().GetViewShellBase().GetMainViewShell());\n if (pDrawViewShell != NULL)\n {\n USHORT nPageNumber = (rpDescriptor->GetPage()->GetPageNum()-1)\/2;\n pDrawViewShell->SwitchPage(nPageNumber);\n pDrawViewShell->GetPageTabControl()->SetCurPageId(nPageNumber+1);\n }\n\n \/\/ Now the UNO way.\n do\n {\n Reference xSet (\n mrController.GetViewShell().GetViewShellBase().GetController(),\n UNO_QUERY);\n if ( ! xSet.is())\n break;\n\n Any aPage;\n aPage <<= rpDescriptor->GetPage()->getUnoPage();\n xSet->setPropertyValue (\n String::CreateFromAscii(\"CurrentPage\"),\n aPage);\n }\n while (false);\n }\n catch (beans::UnknownPropertyException aException)\n {\n \/\/ We have not been able to set the current page at the main view.\n \/\/ This is sad but still leaves us in a valid state. Therefore,\n \/\/ this exception is silently ignored.\n }\n}\n\n\n\n\nvoid PageSelector::SetCurrentPage (const SdPage* pPage)\n{\n int nPageIndex = (pPage->GetPageNum()-1) \/ 2;\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get()!=NULL && pDescriptor->GetPage()==pPage)\n SetCurrentPage(pDescriptor);\n}\n\n\n\n\nvoid PageSelector::SetCurrentPage (int nPageIndex)\n{\n SharedPageDescriptor pDescriptor (mrModel.GetPageDescriptor(nPageIndex));\n if (pDescriptor.get() != NULL)\n SetCurrentPage(pDescriptor);\n}\n\n\n\n\nint PageSelector::GetPageCount (void) const\n{\n return mrModel.GetPageCount();\n}\n\n\n\n\nint PageSelector::GetSelectedPageCount (void) const\n{\n return mnSelectedPageCount;\n}\n\n\n\n\nvoid PageSelector::PrepareModelChange (void)\n{\n DeselectAllPages ();\n}\n\n\n\n\nvoid PageSelector::HandleModelChange (void)\n{\n UpdateAllPages();\n}\n\n\n\n\nSharedPageDescriptor PageSelector::GetMostRecentlySelectedPage (void) const\n{\n return mpMostRecentlySelectedPage;\n}\n\n\n\n\nSharedPageDescriptor PageSelector::GetSelectionAnchor (void) const\n{\n return mpSelectionAnchor;\n}\n\n\n\n\nvoid PageSelector::CountSelectedPages (void)\n{\n mnSelectedPageCount = 0;\n model::SlideSorterModel::Enumeration aSelectedPages (\n mrModel.GetSelectedPagesEnumeration());\n while (aSelectedPages.HasMoreElements())\n {\n mnSelectedPageCount++;\n aSelectedPages.GetNextElement();\n }\n}\n\n\n\n\nvoid PageSelector::EnableBroadcasting (bool bMakeSelectionVisible)\n{\n if (mnBroadcastDisableLevel > 0)\n mnBroadcastDisableLevel --;\n if (mnBroadcastDisableLevel==0 && mbSelectionChangeBroadcastPending)\n {\n mrController.SelectionHasChanged(bMakeSelectionVisible);\n mbSelectionChangeBroadcastPending = false;\n }\n}\n\n\n\n\nvoid PageSelector::DisableBroadcasting (void)\n{\n mnBroadcastDisableLevel ++;\n}\n\n\n\n\n::std::auto_ptr\n PageSelector::GetPageSelection (void)\n{\n ::std::auto_ptr pSelection (new PageSelection());\n\n int nPageCount = GetPageCount();\n for (int nIndex=0; nIndexinsert (nIndex);\n }\n\n return pSelection;\n}\n\n\n\n\nvoid PageSelector::SetPageSelection (const PageSelection& rSelection)\n{\n PageSelection::const_iterator iIndex;\n for (iIndex=rSelection.begin(); iIndex!=rSelection.end(); ++iIndex)\n SelectPage (*iIndex);\n}\n\n} } } \/\/ end of namespace ::sd::slidesorter::controller\n<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __CGROUPS_ISOLATOR_CONSTANTS_HPP__\n#define __CGROUPS_ISOLATOR_CONSTANTS_HPP__\n\n#include \n#include \n\nnamespace mesos {\nnamespace internal {\nnamespace slave {\n\n\/\/ CPU subsystem constants.\nconst uint64_t CPU_SHARES_PER_CPU = 1024;\nconst uint64_t MIN_CPU_SHARES = 10;\nconst Duration CPU_CFS_PERIOD = Milliseconds(100); \/\/ Linux default.\nconst Duration MIN_CPU_CFS_QUOTA = Milliseconds(1);\n\n\n\/\/ Memory subsystem constants.\nconst Bytes MIN_MEMORY = Megabytes(32);\n\n} \/\/ namespace slave {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __CGROUPS_ISOLATOR_CONSTANTS_HPP__\nChanged the MIN_CPU_SHARES to match the kernel constant.\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __CGROUPS_ISOLATOR_CONSTANTS_HPP__\n#define __CGROUPS_ISOLATOR_CONSTANTS_HPP__\n\n#include \n#include \n\nnamespace mesos {\nnamespace internal {\nnamespace slave {\n\n\/\/ CPU subsystem constants.\nconst uint64_t CPU_SHARES_PER_CPU = 1024;\nconst uint64_t MIN_CPU_SHARES = 2; \/\/ Linux constant.\nconst Duration CPU_CFS_PERIOD = Milliseconds(100); \/\/ Linux default.\nconst Duration MIN_CPU_CFS_QUOTA = Milliseconds(1);\n\n\n\/\/ Memory subsystem constants.\nconst Bytes MIN_MEMORY = Megabytes(32);\n\n} \/\/ namespace slave {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __CGROUPS_ISOLATOR_CONSTANTS_HPP__\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n#include \n#include \n\n#include \n#include \n\nusing namespace Hearthstonepp;\n\nTEST(CombatTask, GetTaskID)\n{\n TaskAgent agent;\n BasicTasks::CombatTask combat(agent);\n EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT);\n}\n\nTEST(CombatTask, CombatDefault)\n{\n TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);\n GameAgent agent(gen.player1, gen.player2);\n TestUtils::AutoResponder resp(agent);\n\n BasicTasks::InitAttackCountTask init;\n BasicTasks::CombatTask combat(agent.GetTaskAgent());\n\n auto attack = [&](size_t src, size_t dst) {\n init.Run(gen.player1, gen.player2);\n init.Run(gen.player2, gen.player1);\n\n auto target = resp.Target(src, dst);\n MetaData result = combat.Run(gen.player1, gen.player2);\n EXPECT_EQ(result, MetaData::COMBAT_SUCCESS);\n\n TaskMeta meta = target.get();\n EXPECT_EQ(meta.id, +TaskID::REQUIRE);\n };\n\n auto card1 = TestUtils::GenerateMinion(\"minion1\", 3, 6);\n auto card2 = TestUtils::GenerateMinion(\"minion2\", 5, 4);\n\n Character minion1(card1.get());\n Character minion2(card2.get());\n\n gen.player1.field.emplace_back(&minion1);\n gen.player2.field.emplace_back(&minion2);\n\n attack(1, 0);\n EXPECT_EQ(gen.player1.field[0]->health, gen.player1.field[0]->maxHealth);\n EXPECT_EQ(gen.player2.hero->health, gen.player2.hero->maxHealth - gen.player1.field[0]->attack);\n\n attack(1, 1);\n EXPECT_EQ(gen.player1.field[0]->health, static_cast(1));\n EXPECT_EQ(gen.player2.field[0]->health, static_cast(1));\n\n attack(1, 1);\n EXPECT_EQ(gen.player1.field.size(), static_cast(0));\n EXPECT_EQ(gen.player2.field.size(), static_cast(0));\n}\n\nTEST(CombatTask, CombatTaunt)\n{\n\n}\n\nTEST(CombatTask, CombatStealth)\n{\n\n}\n\nTEST(CombatTask, CombatImmune)\n{\n\n}\n\nTEST(CombatTask, CombatAttackCount)\n{\n\n}\n\nTEST(CombatTask, CombatDivineShield)\n{\n\n}\n\nTEST(CombatTask, Poisonous)\n{\n\n}\nUpdate CombatTaskTests - Add Default Test Case of exclusive one exhaust#include \"gtest\/gtest.h\"\n#include \n#include \n\n#include \n#include \n\nusing namespace Hearthstonepp;\n\nTEST(CombatTask, GetTaskID)\n{\n TaskAgent agent;\n BasicTasks::CombatTask combat(agent);\n EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT);\n}\n\nTEST(CombatTask, CombatDefault)\n{\n TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);\n GameAgent agent(gen.player1, gen.player2);\n TestUtils::AutoResponder resp(agent);\n\n BasicTasks::InitAttackCountTask init;\n BasicTasks::CombatTask combat(agent.GetTaskAgent());\n\n auto attack = [&](size_t src, size_t dst) {\n init.Run(gen.player1, gen.player2);\n init.Run(gen.player2, gen.player1);\n\n auto target = resp.Target(src, dst);\n MetaData result = combat.Run(gen.player1, gen.player2);\n EXPECT_EQ(result, MetaData::COMBAT_SUCCESS);\n\n TaskMeta meta = target.get();\n EXPECT_EQ(meta.id, +TaskID::REQUIRE);\n };\n\n auto card1 = TestUtils::GenerateMinion(\"minion1\", 3, 6);\n auto card2 = TestUtils::GenerateMinion(\"minion2\", 5, 4);\n\n Character minion1(card1.get());\n Character minion2(card2.get());\n\n gen.player1.field.emplace_back(&minion1);\n gen.player2.field.emplace_back(&minion2);\n\n attack(1, 0);\n EXPECT_EQ(gen.player1.field[0]->health, gen.player1.field[0]->maxHealth);\n EXPECT_EQ(gen.player2.hero->health, gen.player2.hero->maxHealth - gen.player1.field[0]->attack);\n\n attack(1, 1);\n EXPECT_EQ(gen.player1.field[0]->health, static_cast(1));\n EXPECT_EQ(gen.player2.field[0]->health, static_cast(1));\n\n attack(1, 1);\n EXPECT_EQ(gen.player1.field.size(), static_cast(0));\n EXPECT_EQ(gen.player2.field.size(), static_cast(0));\n\n card1->attack = 5;\n Character minion3(card1.get());\n\n gen.player1.field.emplace_back(&minion3);\n gen.player2.field.emplace_back(&minion2);\n\n attack(1, 1);\n EXPECT_EQ(gen.player1.field[0]->health, static_cast(1));\n EXPECT_EQ(gen.player2.field.size(), static_cast(0));\n\n gen.player1.field[0]->attack = 1;\n gen.player2.field.emplace_back(&minion2);\n\n attack(1, 1);\n EXPECT_EQ(gen.player1.field.size(), static_cast(0));\n EXPECT_EQ(gen.player2.field[0]->health, static_cast(3));\n}\n\nTEST(CombatTask, CombatTaunt)\n{\n\n}\n\nTEST(CombatTask, CombatStealth)\n{\n\n}\n\nTEST(CombatTask, CombatImmune)\n{\n\n}\n\nTEST(CombatTask, CombatAttackCount)\n{\n\n}\n\nTEST(CombatTask, CombatDivineShield)\n{\n\n}\n\nTEST(CombatTask, Poisonous)\n{\n\n}\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n* @file covariance.cpp\n* @author Christoph Dinh ;\n* Matti Hamalainen \n* @version 1.0\n* @date February, 2013\n*\n* @section LICENSE\n*\n* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Contains the implementation of the Covariance class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"covariance.h\"\n#include \"FormFiles\/covariancesetupwidget.h\"\n#include \"FormFiles\/covariancesettingswidget.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace CovariancePlugin;\nusing namespace MNEX;\nusing namespace XMEASLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nCovariance::Covariance()\n: m_bIsRunning(false)\n, m_bProcessData(false)\n, m_pCovarianceInput(NULL)\n, m_pCovarianceOutput(NULL)\n, m_pCovarianceBuffer(CircularMatrixBuffer::SPtr())\n, m_iEstimationSamples(5000)\n{\n m_pActionShowAdjustment = new QAction(QIcon(\":\/images\/covariance.png\"), tr(\"Covariance Adjustments\"),this);\n\/\/ m_pActionSetupProject->setShortcut(tr(\"F12\"));\n m_pActionShowAdjustment->setStatusTip(tr(\"Covariance Adjustments\"));\n connect(m_pActionShowAdjustment, &QAction::triggered, this, &Covariance::showCovarianceWidget);\n addPluginAction(m_pActionShowAdjustment);\n m_pActionShowAdjustment->setVisible(false);\n}\n\n\n\/\/*************************************************************************************************************\n\nCovariance::~Covariance()\n{\n if(this->isRunning())\n stop();\n}\n\n\n\/\/*************************************************************************************************************\n\nQSharedPointer Covariance::clone() const\n{\n QSharedPointer pCovarianceClone(new Covariance);\n return pCovarianceClone;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Creating required display instances and set configurations\n\/\/=============================================================================================================\n\nvoid Covariance::init()\n{\n \/\/ Input\n m_pCovarianceInput = PluginInputData::create(this, \"CovarianceIn\", \"Covariance input data\");\n connect(m_pCovarianceInput.data(), &PluginInputConnector::notify, this, &Covariance::update, Qt::DirectConnection);\n m_inputConnectors.append(m_pCovarianceInput);\n\n \/\/ Output\n m_pCovarianceOutput = PluginOutputData::create(this, \"CovarianceOut\", \"Covariance output data\");\n m_outputConnectors.append(m_pCovarianceOutput);\n\n \/\/Delete Buffer - will be initailzed with first incoming data\n if(!m_pCovarianceBuffer.isNull())\n m_pCovarianceBuffer = CircularMatrixBuffer::SPtr();\n}\n\n\n\/\/*************************************************************************************************************\n\nbool Covariance::start()\n{\n \/\/Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.\n if(this->isRunning())\n QThread::wait();\n\n m_bIsRunning = true;\n\n \/\/ Start threads\n QThread::start();\n\n return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nbool Covariance::stop()\n{\n \/\/Wait until this thread is stopped\n m_bIsRunning = false;\n\n \/\/In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement)\n m_pCovarianceBuffer->releaseFromPop();\n\n m_pCovarianceBuffer->clear();\n\n return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nIPlugin::PluginType Covariance::getType() const\n{\n return _IAlgorithm;\n}\n\n\n\/\/*************************************************************************************************************\n\nQString Covariance::getName() const\n{\n return \"Covariance\";\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::showCovarianceWidget()\n{\n m_pCovarianceWidget = CovarianceSettingsWidget::SPtr(new CovarianceSettingsWidget(this));\n m_pCovarianceWidget->show();\n}\n\n\n\/\/*************************************************************************************************************\n\nQWidget* Covariance::setupWidget()\n{\n CovarianceSetupWidget* setupWidget = new CovarianceSetupWidget(this);\/\/widget is later distroyed by CentralWidget - so it has to be created everytime new\n return setupWidget;\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::update(XMEASLIB::NewMeasurement::SPtr pMeasurement)\n{\n QSharedPointer pRTMSA = pMeasurement.dynamicCast();\n\n if(pRTMSA)\n {\n \/\/Check if buffer initialized\n if(!m_pCovarianceBuffer)\n m_pCovarianceBuffer = CircularMatrixBuffer::SPtr(new CircularMatrixBuffer(64, pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize()));\n\n \/\/Fiff information\n if(!m_pFiffInfo)\n {\n m_pFiffInfo = pRTMSA->getFiffInfo();\n emit fiffInfoAvailable();\n }\n\n\n if(m_bProcessData)\n {\n MatrixXd t_mat(pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize());\n\n for(qint32 i = 0; i < pRTMSA->getMultiArraySize(); ++i)\n t_mat.col(i) = pRTMSA->getMultiSampleArray()[i];\n\n m_pCovarianceBuffer->push(&t_mat);\n }\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::appendCovariance(FiffCov::SPtr p_pCovariance)\n{\n mutex.lock();\n m_qVecCovData.push_back(p_pCovariance);\n mutex.unlock();\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::changeSamples(qint32 samples)\n{\n m_iEstimationSamples = samples;\n if(m_pRtCov)\n m_pRtCov->setSamples(m_iEstimationSamples);\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::run()\n{\n \/\/\n \/\/ Read Fiff Info\n \/\/\n while(!m_pFiffInfo)\n msleep(10);\/\/ Wait for fiff Info\n\n m_pActionShowAdjustment->setVisible(true);\n\n \/\/\n \/\/ Init Real-Time Covariance estimator\n \/\/\n m_pRtCov = RtCov::SPtr(new RtCov(m_iEstimationSamples, m_pFiffInfo));\n connect(m_pRtCov.data(), &RtCov::covCalculated, this, &Covariance::appendCovariance);\n\n \/\/\n \/\/ Start the rt helpers\n \/\/\n m_pRtCov->start();\n\n \/\/\n \/\/ start processing data\n \/\/\n m_bProcessData = true;\n\n while (m_bIsRunning)\n {\n if(m_bProcessData)\n {\n \/* Dispatch the inputs *\/\n MatrixXd t_mat = m_pCovarianceBuffer->pop();\n\n \/\/Add to covariance estimation\n m_pRtCov->append(t_mat);\n\n if(m_qVecCovData.size() > 0)\n {\n mutex.lock();\n m_pCovarianceOutput->data()->setValue(*m_qVecCovData[0]);\n\n m_qVecCovData.pop_front();\n mutex.unlock();\n }\n }\n }\n\n m_pActionShowAdjustment->setVisible(false);\n\n m_pRtCov->stop();\n}\n\nchanged adjustments icon\/\/=============================================================================================================\n\/**\n* @file covariance.cpp\n* @author Christoph Dinh ;\n* Matti Hamalainen \n* @version 1.0\n* @date February, 2013\n*\n* @section LICENSE\n*\n* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Contains the implementation of the Covariance class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"covariance.h\"\n#include \"FormFiles\/covariancesetupwidget.h\"\n#include \"FormFiles\/covariancesettingswidget.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace CovariancePlugin;\nusing namespace MNEX;\nusing namespace XMEASLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nCovariance::Covariance()\n: m_bIsRunning(false)\n, m_bProcessData(false)\n, m_pCovarianceInput(NULL)\n, m_pCovarianceOutput(NULL)\n, m_pCovarianceBuffer(CircularMatrixBuffer::SPtr())\n, m_iEstimationSamples(5000)\n{\n m_pActionShowAdjustment = new QAction(QIcon(\":\/images\/covadjustments.png\"), tr(\"Covariance Adjustments\"),this);\n\/\/ m_pActionSetupProject->setShortcut(tr(\"F12\"));\n m_pActionShowAdjustment->setStatusTip(tr(\"Covariance Adjustments\"));\n connect(m_pActionShowAdjustment, &QAction::triggered, this, &Covariance::showCovarianceWidget);\n addPluginAction(m_pActionShowAdjustment);\n m_pActionShowAdjustment->setVisible(false);\n}\n\n\n\/\/*************************************************************************************************************\n\nCovariance::~Covariance()\n{\n if(this->isRunning())\n stop();\n}\n\n\n\/\/*************************************************************************************************************\n\nQSharedPointer Covariance::clone() const\n{\n QSharedPointer pCovarianceClone(new Covariance);\n return pCovarianceClone;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Creating required display instances and set configurations\n\/\/=============================================================================================================\n\nvoid Covariance::init()\n{\n \/\/ Input\n m_pCovarianceInput = PluginInputData::create(this, \"CovarianceIn\", \"Covariance input data\");\n connect(m_pCovarianceInput.data(), &PluginInputConnector::notify, this, &Covariance::update, Qt::DirectConnection);\n m_inputConnectors.append(m_pCovarianceInput);\n\n \/\/ Output\n m_pCovarianceOutput = PluginOutputData::create(this, \"CovarianceOut\", \"Covariance output data\");\n m_outputConnectors.append(m_pCovarianceOutput);\n\n \/\/Delete Buffer - will be initailzed with first incoming data\n if(!m_pCovarianceBuffer.isNull())\n m_pCovarianceBuffer = CircularMatrixBuffer::SPtr();\n}\n\n\n\/\/*************************************************************************************************************\n\nbool Covariance::start()\n{\n \/\/Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.\n if(this->isRunning())\n QThread::wait();\n\n m_bIsRunning = true;\n\n \/\/ Start threads\n QThread::start();\n\n return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nbool Covariance::stop()\n{\n \/\/Wait until this thread is stopped\n m_bIsRunning = false;\n\n \/\/In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement)\n m_pCovarianceBuffer->releaseFromPop();\n\n m_pCovarianceBuffer->clear();\n\n return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nIPlugin::PluginType Covariance::getType() const\n{\n return _IAlgorithm;\n}\n\n\n\/\/*************************************************************************************************************\n\nQString Covariance::getName() const\n{\n return \"Covariance\";\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::showCovarianceWidget()\n{\n m_pCovarianceWidget = CovarianceSettingsWidget::SPtr(new CovarianceSettingsWidget(this));\n m_pCovarianceWidget->show();\n}\n\n\n\/\/*************************************************************************************************************\n\nQWidget* Covariance::setupWidget()\n{\n CovarianceSetupWidget* setupWidget = new CovarianceSetupWidget(this);\/\/widget is later distroyed by CentralWidget - so it has to be created everytime new\n return setupWidget;\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::update(XMEASLIB::NewMeasurement::SPtr pMeasurement)\n{\n QSharedPointer pRTMSA = pMeasurement.dynamicCast();\n\n if(pRTMSA)\n {\n \/\/Check if buffer initialized\n if(!m_pCovarianceBuffer)\n m_pCovarianceBuffer = CircularMatrixBuffer::SPtr(new CircularMatrixBuffer(64, pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize()));\n\n \/\/Fiff information\n if(!m_pFiffInfo)\n {\n m_pFiffInfo = pRTMSA->getFiffInfo();\n emit fiffInfoAvailable();\n }\n\n\n if(m_bProcessData)\n {\n MatrixXd t_mat(pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize());\n\n for(qint32 i = 0; i < pRTMSA->getMultiArraySize(); ++i)\n t_mat.col(i) = pRTMSA->getMultiSampleArray()[i];\n\n m_pCovarianceBuffer->push(&t_mat);\n }\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::appendCovariance(FiffCov::SPtr p_pCovariance)\n{\n mutex.lock();\n m_qVecCovData.push_back(p_pCovariance);\n mutex.unlock();\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::changeSamples(qint32 samples)\n{\n m_iEstimationSamples = samples;\n if(m_pRtCov)\n m_pRtCov->setSamples(m_iEstimationSamples);\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid Covariance::run()\n{\n \/\/\n \/\/ Read Fiff Info\n \/\/\n while(!m_pFiffInfo)\n msleep(10);\/\/ Wait for fiff Info\n\n m_pActionShowAdjustment->setVisible(true);\n\n \/\/\n \/\/ Init Real-Time Covariance estimator\n \/\/\n m_pRtCov = RtCov::SPtr(new RtCov(m_iEstimationSamples, m_pFiffInfo));\n connect(m_pRtCov.data(), &RtCov::covCalculated, this, &Covariance::appendCovariance);\n\n \/\/\n \/\/ Start the rt helpers\n \/\/\n m_pRtCov->start();\n\n \/\/\n \/\/ start processing data\n \/\/\n m_bProcessData = true;\n\n while (m_bIsRunning)\n {\n if(m_bProcessData)\n {\n \/* Dispatch the inputs *\/\n MatrixXd t_mat = m_pCovarianceBuffer->pop();\n\n \/\/Add to covariance estimation\n m_pRtCov->append(t_mat);\n\n if(m_qVecCovData.size() > 0)\n {\n mutex.lock();\n m_pCovarianceOutput->data()->setValue(*m_qVecCovData[0]);\n\n m_qVecCovData.pop_front();\n mutex.unlock();\n }\n }\n }\n\n m_pActionShowAdjustment->setVisible(false);\n\n m_pRtCov->stop();\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\n#include \"weights.h\"\n#include \"rule_lexer.h\"\n#include \"trule.h\"\n#include \"filelib.h\"\n#include \"tdict.h\"\n#include \"lm\/model.hh\"\n#include \"lm\/enumerate_vocab.hh\"\n#include \"wordid.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\n\nvector word_map;\nlm::ngram::ProbingModel* ngram;\nstruct VMapper : public lm::ngram::EnumerateVocab {\n VMapper(vector* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); }\n void Add(lm::WordIndex index, const StringPiece &str) {\n const WordID cdec_id = TD::Convert(str.as_string());\n if (cdec_id >= out_->size())\n out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN);\n (*out_)[cdec_id] = index;\n }\n vector* out_;\n const lm::WordIndex kLM_UNKNOWN_TOKEN;\n};\n\nbool InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n po::options_description opts(\"Configuration options\");\n opts.add_options()\n (\"source_lm,l\",po::value(),\"Source language LM (KLM)\")\n (\"collapse_weights,w\",po::value(), \"Collapse weights into a single feature X using the coefficients from this weights file\")\n (\"add_shape_types,s\", \"Add rule shape types\");\n po::options_description clo(\"Command line options\");\n clo.add_options()\n (\"config\", po::value(), \"Configuration file\")\n (\"help,h\", \"Print this help message and exit\");\n po::options_description dconfig_options, dcmdline_options;\n dconfig_options.add(opts);\n dcmdline_options.add(opts).add(clo);\n \n po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n if (conf->count(\"config\")) {\n ifstream config((*conf)[\"config\"].as().c_str());\n po::store(po::parse_config_file(config, dconfig_options), *conf);\n }\n po::notify(*conf);\n\n if (conf->count(\"help\")) {\n cerr << \"Usage \" << argv[0] << \" [OPTIONS]\\n\";\n cerr << dcmdline_options << endl;\n return false;\n }\n return true;\n}\n\nlm::WordIndex kSOS;\n\ntemplate float Score(const vector& str, const Model &model) {\n typename Model::State state, out;\n lm::FullScoreReturn ret;\n float total = 0.0f;\n state = model.NullContextState();\n\n for (int i = 0; i < str.size(); ++i) {\n lm::WordIndex vocab = ((str[i] < word_map.size() && str[i] > 0) ? word_map[str[i]] : 0);\n if (vocab == kSOS) {\n state = model.BeginSentenceState();\n } else {\n ret = model.FullScore(state, vocab, out);\n total += ret.prob;\n state = out;\n }\n }\n return total;\n}\n\nint kSrcLM;\nvector col_weights;\n\nstatic void RuleHelper(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) {\n static const int kSrcLM = FD::Convert(\"SrcLM\");\n static const int kPC = FD::Convert(\"PC\");\n static const int kX = FD::Convert(\"X\");\n TRule r(*new_rule);\n if (ngram) r.scores_.set_value(kSrcLM, Score(r.f_, *ngram));\n r.scores_.set_value(kPC, 1.0);\n if (col_weights.size()) {\n double score = r.scores_.dot(col_weights);\n r.scores_.clear();\n r.scores_.set_value(kX, score);\n }\n cout << r << endl;\n}\n\n\nint main(int argc, char** argv) {\n po::variables_map conf;\n if (!InitCommandLine(argc, argv, &conf)) return 1;\n if (conf.count(\"source_lm\")) {\n lm::ngram::Config kconf;\n VMapper vm(&word_map);\n kconf.enumerate_vocab = &vm; \n ngram = new lm::ngram::ProbingModel(conf[\"source_lm\"].as().c_str(), kconf);\n kSOS = word_map[TD::Convert(\"\")];\n cerr << \"Loaded \" << (int)ngram->Order() << \"-gram KenLM (MapSize=\" << word_map.size() << \")\\n\";\n cerr << \" = \" << kSOS << endl;\n } else { ngram = NULL; }\n if (conf.count(\"collapse_weights\")) {\n Weights w;\n w.InitFromFile(conf[\"collapse_weights\"].as());\n w.InitVector(&col_weights);\n }\n RuleLexer::ReadRules(&cin, &RuleHelper, NULL);\n return 0;\n}\n\nreplace files option to prevent reloading LM each time#include \n#include \n\n#include \n#include \n\n#include \"weights.h\"\n#include \"rule_lexer.h\"\n#include \"trule.h\"\n#include \"filelib.h\"\n#include \"tdict.h\"\n#include \"lm\/model.hh\"\n#include \"lm\/enumerate_vocab.hh\"\n#include \"wordid.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\n\nvector word_map;\nlm::ngram::ProbingModel* ngram;\nstruct VMapper : public lm::ngram::EnumerateVocab {\n VMapper(vector* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); }\n void Add(lm::WordIndex index, const StringPiece &str) {\n const WordID cdec_id = TD::Convert(str.as_string());\n if (cdec_id >= out_->size())\n out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN);\n (*out_)[cdec_id] = index;\n }\n vector* out_;\n const lm::WordIndex kLM_UNKNOWN_TOKEN;\n};\n\nbool InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n po::options_description opts(\"Configuration options\");\n opts.add_options()\n (\"source_lm,l\",po::value(),\"Source language LM (KLM)\")\n (\"collapse_weights,w\",po::value(), \"Collapse weights into a single feature X using the coefficients from this weights file\")\n (\"add_shape_types,s\", \"Add rule shape types\")\n (\"replace_files,r\", \"Replace files with transformed variants (requires loading full grammar into memory)\")\n (\"grammar,g\", po::value >(), \"Input (also output) grammar file(s)\");\n po::options_description clo(\"Command line options\");\n clo.add_options()\n (\"config\", po::value(), \"Configuration file\")\n (\"help,h\", \"Print this help message and exit\");\n po::options_description dconfig_options, dcmdline_options;\n po::positional_options_description p;\n p.add(\"grammar\", -1);\n \n dconfig_options.add(opts);\n dcmdline_options.add(opts).add(clo);\n\n po::store(po::command_line_parser(argc, argv).options(dcmdline_options).positional(p).run(), *conf);\n if (conf->count(\"config\")) {\n ifstream config((*conf)[\"config\"].as().c_str());\n po::store(po::parse_config_file(config, dconfig_options), *conf);\n }\n po::notify(*conf);\n\n if (conf->count(\"help\") || conf->count(\"grammar\")==0) {\n cerr << \"Usage \" << argv[0] << \" [OPTIONS] file.scfg [file2.scfg...]\\n\";\n cerr << dcmdline_options << endl;\n return false;\n }\n return true;\n}\n\nlm::WordIndex kSOS;\n\ntemplate float Score(const vector& str, const Model &model) {\n typename Model::State state, out;\n lm::FullScoreReturn ret;\n float total = 0.0f;\n state = model.NullContextState();\n\n for (int i = 0; i < str.size(); ++i) {\n lm::WordIndex vocab = ((str[i] < word_map.size() && str[i] > 0) ? word_map[str[i]] : 0);\n if (vocab == kSOS) {\n state = model.BeginSentenceState();\n } else {\n ret = model.FullScore(state, vocab, out);\n total += ret.prob;\n state = out;\n }\n }\n return total;\n}\n\nint kSrcLM;\nvector col_weights;\nbool gather_rules;\nvector rules;\n\nstatic void RuleHelper(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) {\n static const int kSrcLM = FD::Convert(\"SrcLM\");\n static const int kPC = FD::Convert(\"PC\");\n static const int kX = FD::Convert(\"X\");\n TRulePtr r; r.reset(new TRule(*new_rule));\n if (ngram) r->scores_.set_value(kSrcLM, Score(r->f_, *ngram));\n r->scores_.set_value(kPC, 1.0);\n if (col_weights.size()) {\n double score = r->scores_.dot(col_weights);\n r->scores_.clear();\n r->scores_.set_value(kX, score);\n }\n if (gather_rules) {\n rules.push_back(r);\n } else {\n cout << *r << endl;\n }\n}\n\n\nint main(int argc, char** argv) {\n po::variables_map conf;\n if (!InitCommandLine(argc, argv, &conf)) return 1;\n if (conf.count(\"source_lm\")) {\n lm::ngram::Config kconf;\n VMapper vm(&word_map);\n kconf.enumerate_vocab = &vm; \n ngram = new lm::ngram::ProbingModel(conf[\"source_lm\"].as().c_str(), kconf);\n kSOS = word_map[TD::Convert(\"\")];\n cerr << \"Loaded \" << (int)ngram->Order() << \"-gram KenLM (MapSize=\" << word_map.size() << \")\\n\";\n cerr << \" = \" << kSOS << endl;\n } else { ngram = NULL; }\n if (conf.count(\"collapse_weights\")) {\n Weights w;\n w.InitFromFile(conf[\"collapse_weights\"].as());\n w.InitVector(&col_weights);\n }\n gather_rules = false;\n bool replace_files = conf.count(\"replace_files\");\n if (replace_files) gather_rules = true;\n vector files = conf[\"grammar\"].as >();\n for (int i=0; i < files.size(); ++i) {\n cerr << \"Processing \" << files[i] << \" ...\" << endl;\n if (true) {\n ReadFile rf(files[i]);\n rules.clear();\n RuleLexer::ReadRules(rf.stream(), &RuleHelper, NULL);\n }\n if (replace_files) {\n WriteFile wf(files[i]);\n for (int i = 0; i < rules.size(); ++i) { (*wf.stream()) << *rules[i] << endl; }\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: export2.cxx,v $\n *\n * $Revision: 1.25 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 13:51:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include \"export.hxx\"\n#include \"utf8conv.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/\n\/\/ class ResData();\n\/\/\n\n\/*****************************************************************************\/\nResData::~ResData()\n\/*****************************************************************************\/\n{\n if ( pStringList ) {\n \/\/ delete existing res. of type StringList\n for ( ULONG i = 0; i < pStringList->Count(); i++ ) {\n ExportListEntry* test = pStringList->GetObject( i );\n if( test != NULL ) delete test;\n }\n delete pStringList;\n }\n if ( pFilterList ) {\n \/\/ delete existing res. of type FilterList\n for ( ULONG i = 0; i < pFilterList->Count(); i++ ) {\n ExportListEntry* test = pFilterList->GetObject( i );\n delete test;\n }\n delete pFilterList;\n }\n if ( pItemList ) {\n \/\/ delete existing res. of type ItemList\n for ( ULONG i = 0; i < pItemList->Count(); i++ ) {\n ExportListEntry* test = pItemList->GetObject( i );\n delete test;\n }\n delete pItemList;\n }\n if ( pUIEntries ) {\n \/\/ delete existing res. of type UIEntries\n for ( ULONG i = 0; i < pUIEntries->Count(); i++ ) {\n ExportListEntry* test = pUIEntries->GetObject( i );\n delete test;\n }\n delete pUIEntries;\n }\n}\n\n\/\/\n\/\/ class Export\n\/\/\n\n\/*****************************************************************************\/\nByteString Export::sLanguages;\nByteString Export::sIsoCode99;\n\/*****************************************************************************\/\n\n\n\/*****************************************************************************\/\nUSHORT Export::GetLangIndex( USHORT nLangId )\n\/*****************************************************************************\/\n{\n \/\/ removeme\n return 0xFFFF;\n}\n\n\/*****************************************************************************\/\nCharSet Export::GetCharSet( USHORT nLangId )\n\/*****************************************************************************\/\n{\n \/\/ removeme\n \/\/return Langcode2TextEncoding( nLangId );\n return 0;\n}\n\n\/*****************************************************************************\/\nUSHORT Export::GetLangByIsoLang( const ByteString &rIsoLang )\n\/*****************************************************************************\/\n{\n ByteString sLang( rIsoLang );\n sLang.ToUpperAscii();\n return 0xFFFF;\n}\n\/*****************************************************************************\/\nvoid Export::SetLanguages( std::vector val ){\n\/*****************************************************************************\/\n aLanguages = val;\n isInitialized = true;\n}\n\/*****************************************************************************\/\nstd::vector Export::GetLanguages(){\n\/*****************************************************************************\/\n return aLanguages;\n}\n\nstd::vector Export::aLanguages = std::vector();\n\n\/*****************************************************************************\/\nByteString Export::GetIsoLangByIndex( USHORT nIndex )\n\/*****************************************************************************\/\n{\n\/\/ remove me\n return \"\";\n}\n\n\/*****************************************************************************\/\nvoid Export::QuotHTML( ByteString &rString )\n\/*****************************************************************************\/\n{\n ByteString sReturn;\n BOOL bBreak = FALSE;\n for ( USHORT i = 0; i < rString.Len(); i++ ) {\n ByteString sTemp = rString.Copy( i );\n if ( sTemp.Search( \"' ) {\n sReturn += \">\";\n i++;\n }\n }\n if ( i < rString.Len()) {\n switch ( rString.GetChar( i )) {\n case '<':\n sReturn += \"<\";\n break;\n\n case '>':\n sReturn += \">\";\n break;\n\n case '\\\"':\n sReturn += \""\";\n break;\n\n case '\\'':\n sReturn += \"'\";\n break;\n\n case '&':\n if ((( i + 4 ) < rString.Len()) &&\n ( rString.Copy( i, 5 ) == \"&\" ))\n sReturn += rString.GetChar( i );\n else\n sReturn += \"&\";\n break;\n\n default:\n sReturn += rString.GetChar( i );\n break;\n }\n }\n }\n rString = sReturn;\n}\n\n\/*****************************************************************************\/\nvoid Export::UnquotHTML( ByteString &rString )\n\/*****************************************************************************\/\n{\n ByteString sReturn;\n while ( rString.Len()) {\n if ( rString.Copy( 0, 5 ) == \"&\" ) {\n sReturn += \"&\";\n rString.Erase( 0, 5 );\n }\n else if ( rString.Copy( 0, 4 ) == \"<\" ) {\n sReturn += \"<\";\n rString.Erase( 0, 4 );\n }\n else if ( rString.Copy( 0, 4 ) == \">\" ) {\n sReturn += \">\";\n rString.Erase( 0, 4 );\n }\n else if ( rString.Copy( 0, 6 ) == \""\" ) {\n sReturn += \"\\\"\";\n rString.Erase( 0, 6 );\n }\n else if ( rString.Copy( 0, 6 ) == \"'\" ) {\n sReturn += \"\\'\";\n rString.Erase( 0, 6 );\n }\n else {\n sReturn += rString.GetChar( 0 );\n rString.Erase( 0, 1 );\n }\n }\n rString = sReturn;\n}\n\n\/*****************************************************************************\/\nbool Export::LanguageAllowed( const ByteString &nLanguage )\n\/*****************************************************************************\/\n{\n return std::find( aLanguages.begin() , aLanguages.end() , nLanguage ) != aLanguages.end();\n}\n\nbool Export::isInitialized = false;\n\n\/*****************************************************************************\/\nvoid Export::InitLanguages( bool bMergeMode ){\n\/*****************************************************************************\/\n ByteString sTmp;\n ByteStringBoolHashMap aEnvLangs;\n for ( USHORT x = 0; x < sLanguages.GetTokenCount( ',' ); x++ ){\n sTmp = sLanguages.GetToken( x, ',' ).GetToken( 0, '=' );\n sTmp.EraseLeadingAndTrailingChars();\n if( bMergeMode && ( sTmp.EqualsIgnoreCaseAscii(\"de\") || sTmp.EqualsIgnoreCaseAscii(\"en-US\") )){}\n else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) )\n aLanguages.push_back( sTmp );\n }\n isInitialized = true;\n}\n\n\n\/*****************************************************************************\/\nByteString Export::GetFallbackLanguage( const ByteString nLanguage )\n\/*****************************************************************************\/\n{\n ByteString sFallback=nLanguage;\n GetIsoFallback( sFallback );\n return sFallback;\n}\n\n\/*****************************************************************************\/\nvoid Export::FillInFallbacks( ResData *pResData )\n\/*****************************************************************************\/\n{\n ByteString sCur;\n for( long int n = 0; n < aLanguages.size(); n++ ){\n sCur = aLanguages[ n ];\n if( !sCur.EqualsIgnoreCaseAscii(\"de\") && !sCur.EqualsIgnoreCaseAscii(\"en-US\") ){\n ByteString nFallbackIndex = GetFallbackLanguage( sCur );\n if( nFallbackIndex.Len() ){\n if ( !pResData->sText[ sCur ].Len())\n pResData->sText[ sCur ] =\n pResData->sText[ nFallbackIndex ];\n\n if ( !pResData->sHelpText[ sCur ].Len())\n pResData->sHelpText[ sCur ] =\n pResData->sHelpText[ nFallbackIndex ];\n\n if ( !pResData->sQuickHelpText[ sCur ].Len())\n pResData->sQuickHelpText[ sCur ] =\n pResData->sQuickHelpText[ nFallbackIndex ];\n\n if ( !pResData->sTitle[ sCur ].Len())\n pResData->sTitle[ sCur ] =\n pResData->sTitle[ nFallbackIndex ];\n\n if ( pResData->pStringList )\n FillInListFallbacks(\n pResData->pStringList, sCur, nFallbackIndex );\n\n if ( pResData->pFilterList )\n FillInListFallbacks(\n pResData->pFilterList, sCur, nFallbackIndex );\n\n if ( pResData->pItemList )\n FillInListFallbacks(\n pResData->pItemList, sCur, nFallbackIndex );\n\n if ( pResData->pUIEntries )\n FillInListFallbacks(\n pResData->pUIEntries, sCur, nFallbackIndex );\n }\n }\n }\n}\n\n\/*****************************************************************************\/\nvoid Export::FillInListFallbacks(\n ExportList *pList, const ByteString &nSource, const ByteString &nFallback )\n\/*****************************************************************************\/\n{\n\n for ( ULONG i = 0; i < pList->Count(); i++ ) {\n ExportListEntry *pEntry = pList->GetObject( i );\n if ( !( *pEntry )[ nSource ].Len())\n ( *pEntry )[ nSource ] = ( *pEntry )[ nFallback ];\n }\n}\n\n\/*****************************************************************************\/\nByteString Export::GetTimeStamp()\n\/*****************************************************************************\/\n{\n\/\/ return \"xx.xx.xx\";\n char buf[20];\n Time aTime;\n\n snprintf(buf, sizeof(buf), \"%8d %02d:%02d:%02d\", Date().GetDate(),\n aTime.GetHour(), aTime.GetMin(), aTime.GetSec());\n return ByteString(buf);\n}\n\n\/*****************************************************************************\/\nBOOL Export::ConvertLineEnds(\n ByteString sSource, ByteString sDestination )\n\/*****************************************************************************\/\n{\n String sSourceFile( sSource, RTL_TEXTENCODING_ASCII_US );\n String sDestinationFile( sDestination, RTL_TEXTENCODING_ASCII_US );\n\n SvFileStream aSource( sSourceFile, STREAM_READ );\n if ( !aSource.IsOpen())\n return FALSE;\n SvFileStream aDestination( sDestinationFile, STREAM_STD_WRITE | STREAM_TRUNC );\n if ( !aDestination.IsOpen()) {\n aSource.Close();\n return FALSE;\n }\n\n ByteString sLine;\n\n while ( !aSource.IsEof()) {\n aSource.ReadLine( sLine );\n if ( !aSource.IsEof()) {\n sLine.EraseAllChars( '\\r' );\n aDestination.WriteLine( sLine );\n }\n else\n aDestination.WriteByteString( sLine );\n }\n\n aSource.Close();\n aDestination.Close();\n\n return TRUE;\n}\n\n\/*****************************************************************************\/\nByteString Export::GetNativeFile( ByteString sSource )\n\/*****************************************************************************\/\n{\n DirEntry aTemp( GetTempFile());\n ByteString sReturn( aTemp.GetFull(), RTL_TEXTENCODING_ASCII_US );\n\n for ( USHORT i = 0; i < 10; i++ )\n if ( ConvertLineEnds( sSource, sReturn ))\n return sReturn;\n\n return \"\";\n}\n\n\/*****************************************************************************\/\nDirEntry Export::GetTempFile()\n\/*****************************************************************************\/\n{\n#ifdef WNT\n String sTempDir( GetEnv( \"TEMP\" ), RTL_TEXTENCODING_ASCII_US );\n#else\n\/\/ String sTempDir( GetEnv( \"HOME\" ), RTL_TEXTENCODING_ASCII_US );\n String sTempDir( String::CreateFromAscii( \"\/tmp\" ));\n#endif\n\n rtl::OUString* sTempFilename = new rtl::OUString();\n int nRC = osl::FileBase::createTempFile( 0 , 0 , sTempFilename );\n if( nRC ) printf(\" osl::FileBase::createTempFile RC = %d\",nRC);\n ByteString sTmp( sTempFilename->getStr() , RTL_TEXTENCODING_UTF8 );\n#ifdef WNT\n sTmp.SearchAndReplace(\"file:\/\/\/\",\"\");\n sTmp.SearchAndReplaceAll('\/','\\\\');\n#else\n sTmp.SearchAndReplace(\"file:\/\/\",\"\");\n#endif\n DirEntry aDirEntry( sTmp );\n delete sTempFilename;\n return aDirEntry;\n}\nINTEGRATION: CWS help2 (1.23.12); FILE MERGED 2004\/07\/13 16:49:11 ihi 1.23.12.4: #104752# Forced Language switch 2004\/07\/07 17:21:51 ihi 1.23.12.3: RESYNC: (1.23-1.24); FILE MERGED 2004\/06\/01 11:28:58 ihi 1.23.12.2: #i27675# '\\n' removed from GetTimeStamp method 2004\/05\/18 16:32:32 ihi 1.23.12.1: Assertion log fix \/ mergebuild join\/*************************************************************************\n *\n * $RCSfile: export2.cxx,v $\n *\n * $Revision: 1.26 $\n *\n * last change: $Author: kz $ $Date: 2004-08-30 17:30:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include \"export.hxx\"\n#include \"utf8conv.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/\n\/\/ class ResData();\n\/\/\n\n\/*****************************************************************************\/\nResData::~ResData()\n\/*****************************************************************************\/\n{\n if ( pStringList ) {\n \/\/ delete existing res. of type StringList\n for ( ULONG i = 0; i < pStringList->Count(); i++ ) {\n ExportListEntry* test = pStringList->GetObject( i );\n if( test != NULL ) delete test;\n }\n delete pStringList;\n }\n if ( pFilterList ) {\n \/\/ delete existing res. of type FilterList\n for ( ULONG i = 0; i < pFilterList->Count(); i++ ) {\n ExportListEntry* test = pFilterList->GetObject( i );\n delete test;\n }\n delete pFilterList;\n }\n if ( pItemList ) {\n \/\/ delete existing res. of type ItemList\n for ( ULONG i = 0; i < pItemList->Count(); i++ ) {\n ExportListEntry* test = pItemList->GetObject( i );\n delete test;\n }\n delete pItemList;\n }\n if ( pUIEntries ) {\n \/\/ delete existing res. of type UIEntries\n for ( ULONG i = 0; i < pUIEntries->Count(); i++ ) {\n ExportListEntry* test = pUIEntries->GetObject( i );\n delete test;\n }\n delete pUIEntries;\n }\n}\n\n\/\/\n\/\/ class Export\n\/\/\n\n\/*****************************************************************************\/\nByteString Export::sLanguages;\nByteString Export::sForcedLanguages;\nByteString Export::sIsoCode99;\n\/*****************************************************************************\/\n\n\n\/*****************************************************************************\/\nUSHORT Export::GetLangIndex( USHORT nLangId )\n\/*****************************************************************************\/\n{\n \/\/ removeme\n return 0xFFFF;\n}\n\n\/*****************************************************************************\/\nCharSet Export::GetCharSet( USHORT nLangId )\n\/*****************************************************************************\/\n{\n \/\/ removeme\n \/\/return Langcode2TextEncoding( nLangId );\n return 0;\n}\n\n\/*****************************************************************************\/\nUSHORT Export::GetLangByIsoLang( const ByteString &rIsoLang )\n\/*****************************************************************************\/\n{\n \/\/ removeme\n ByteString sLang( rIsoLang );\n sLang.ToUpperAscii();\n return 0xFFFF;\n}\n\/*****************************************************************************\/\nvoid Export::SetLanguages( std::vector val ){\n\/*****************************************************************************\/\n aLanguages = val;\n isInitialized = true;\n}\n\/*****************************************************************************\/\nstd::vector Export::GetLanguages(){\n\/*****************************************************************************\/\n return aLanguages;\n}\n\/*****************************************************************************\/\nstd::vector Export::GetForcedLanguages(){\n\/*****************************************************************************\/\n return aForcedLanguages;\n}\nstd::vector Export::aLanguages = std::vector();\nstd::vector Export::aForcedLanguages = std::vector();\n\n\/*****************************************************************************\/\nByteString Export::GetIsoLangByIndex( USHORT nIndex )\n\/*****************************************************************************\/\n{\n\/\/ remove me\n return \"\";\n}\n\n\/*****************************************************************************\/\nvoid Export::QuotHTML( ByteString &rString )\n\/*****************************************************************************\/\n{\n ByteString sReturn;\n BOOL bBreak = FALSE;\n for ( USHORT i = 0; i < rString.Len(); i++ ) {\n ByteString sTemp = rString.Copy( i );\n if ( sTemp.Search( \"' ) {\n sReturn += \">\";\n i++;\n }\n }\n if ( i < rString.Len()) {\n switch ( rString.GetChar( i )) {\n case '<':\n sReturn += \"<\";\n break;\n\n case '>':\n sReturn += \">\";\n break;\n\n case '\\\"':\n sReturn += \""\";\n break;\n\n case '\\'':\n sReturn += \"'\";\n break;\n\n case '&':\n if ((( i + 4 ) < rString.Len()) &&\n ( rString.Copy( i, 5 ) == \"&\" ))\n sReturn += rString.GetChar( i );\n else\n sReturn += \"&\";\n break;\n\n default:\n sReturn += rString.GetChar( i );\n break;\n }\n }\n }\n rString = sReturn;\n}\n\n\/*****************************************************************************\/\nvoid Export::UnquotHTML( ByteString &rString )\n\/*****************************************************************************\/\n{\n ByteString sReturn;\n while ( rString.Len()) {\n if ( rString.Copy( 0, 5 ) == \"&\" ) {\n sReturn += \"&\";\n rString.Erase( 0, 5 );\n }\n else if ( rString.Copy( 0, 4 ) == \"<\" ) {\n sReturn += \"<\";\n rString.Erase( 0, 4 );\n }\n else if ( rString.Copy( 0, 4 ) == \">\" ) {\n sReturn += \">\";\n rString.Erase( 0, 4 );\n }\n else if ( rString.Copy( 0, 6 ) == \""\" ) {\n sReturn += \"\\\"\";\n rString.Erase( 0, 6 );\n }\n else if ( rString.Copy( 0, 6 ) == \"'\" ) {\n sReturn += \"\\'\";\n rString.Erase( 0, 6 );\n }\n else {\n sReturn += rString.GetChar( 0 );\n rString.Erase( 0, 1 );\n }\n }\n rString = sReturn;\n}\n\n\/*****************************************************************************\/\nbool Export::LanguageAllowed( const ByteString &nLanguage )\n\/*****************************************************************************\/\n{\n return std::find( aLanguages.begin() , aLanguages.end() , nLanguage ) != aLanguages.end();\n}\n\nbool Export::isInitialized = false;\n\n\/*****************************************************************************\/\nvoid Export::InitLanguages( bool bMergeMode ){\n\/*****************************************************************************\/\n ByteString sTmp;\n ByteStringBoolHashMap aEnvLangs;\n for ( USHORT x = 0; x < sLanguages.GetTokenCount( ',' ); x++ ){\n sTmp = sLanguages.GetToken( x, ',' ).GetToken( 0, '=' );\n sTmp.EraseLeadingAndTrailingChars();\n if( bMergeMode && ( sTmp.EqualsIgnoreCaseAscii(\"de\") || sTmp.EqualsIgnoreCaseAscii(\"en-US\") )){}\n else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) )\n aLanguages.push_back( sTmp );\n }\n InitForcedLanguages( bMergeMode );\n isInitialized = true;\n}\n\/*****************************************************************************\/\nvoid Export::InitForcedLanguages( bool bMergeMode ){\n\/*****************************************************************************\/\n ByteString sTmp;\n ByteStringBoolHashMap aEnvLangs;\n for ( USHORT x = 0; x < sForcedLanguages.GetTokenCount( ',' ); x++ ){\n sTmp = sForcedLanguages.GetToken( x, ',' ).GetToken( 0, '=' );\n sTmp.EraseLeadingAndTrailingChars();\n if( bMergeMode && ( sTmp.EqualsIgnoreCaseAscii(\"de\") || sTmp.EqualsIgnoreCaseAscii(\"en-US\") )){}\n else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) )\n aForcedLanguages.push_back( sTmp );\n }\n}\n\n\/*****************************************************************************\/\nByteString Export::GetFallbackLanguage( const ByteString nLanguage )\n\/*****************************************************************************\/\n{\n ByteString sFallback=nLanguage;\n GetIsoFallback( sFallback );\n return sFallback;\n}\n\n\/*****************************************************************************\/\nvoid Export::FillInFallbacks( ResData *pResData )\n\/*****************************************************************************\/\n{\n ByteString sCur;\n for( long int n = 0; n < aLanguages.size(); n++ ){\n sCur = aLanguages[ n ];\n if( !sCur.EqualsIgnoreCaseAscii(\"de\") && !sCur.EqualsIgnoreCaseAscii(\"en-US\") ){\n ByteString nFallbackIndex = GetFallbackLanguage( sCur );\n if( nFallbackIndex.Len() ){\n if ( !pResData->sText[ sCur ].Len())\n pResData->sText[ sCur ] =\n pResData->sText[ nFallbackIndex ];\n\n if ( !pResData->sHelpText[ sCur ].Len())\n pResData->sHelpText[ sCur ] =\n pResData->sHelpText[ nFallbackIndex ];\n\n if ( !pResData->sQuickHelpText[ sCur ].Len())\n pResData->sQuickHelpText[ sCur ] =\n pResData->sQuickHelpText[ nFallbackIndex ];\n\n if ( !pResData->sTitle[ sCur ].Len())\n pResData->sTitle[ sCur ] =\n pResData->sTitle[ nFallbackIndex ];\n\n if ( pResData->pStringList )\n FillInListFallbacks(\n pResData->pStringList, sCur, nFallbackIndex );\n\n if ( pResData->pFilterList )\n FillInListFallbacks(\n pResData->pFilterList, sCur, nFallbackIndex );\n\n if ( pResData->pItemList )\n FillInListFallbacks(\n pResData->pItemList, sCur, nFallbackIndex );\n\n if ( pResData->pUIEntries )\n FillInListFallbacks(\n pResData->pUIEntries, sCur, nFallbackIndex );\n }\n }\n }\n}\n\n\/*****************************************************************************\/\nvoid Export::FillInListFallbacks(\n ExportList *pList, const ByteString &nSource, const ByteString &nFallback )\n\/*****************************************************************************\/\n{\n\n for ( ULONG i = 0; i < pList->Count(); i++ ) {\n ExportListEntry *pEntry = pList->GetObject( i );\n if ( !( *pEntry )[ nSource ].Len())\n ( *pEntry )[ nSource ] = ( *pEntry )[ nFallback ];\n }\n}\n\n\/*****************************************************************************\/\nByteString Export::GetTimeStamp()\n\/*****************************************************************************\/\n{\n\/\/ return \"xx.xx.xx\";\n char buf[20];\n Time aTime;\n\n snprintf(buf, sizeof(buf), \"%8d %02d:%02d:%02d\", Date().GetDate(),\n aTime.GetHour(), aTime.GetMin(), aTime.GetSec());\n return ByteString(buf);\n}\n\n\/*****************************************************************************\/\nBOOL Export::ConvertLineEnds(\n ByteString sSource, ByteString sDestination )\n\/*****************************************************************************\/\n{\n String sSourceFile( sSource, RTL_TEXTENCODING_ASCII_US );\n String sDestinationFile( sDestination, RTL_TEXTENCODING_ASCII_US );\n\n SvFileStream aSource( sSourceFile, STREAM_READ );\n if ( !aSource.IsOpen())\n return FALSE;\n SvFileStream aDestination( sDestinationFile, STREAM_STD_WRITE | STREAM_TRUNC );\n if ( !aDestination.IsOpen()) {\n aSource.Close();\n return FALSE;\n }\n\n ByteString sLine;\n\n while ( !aSource.IsEof()) {\n aSource.ReadLine( sLine );\n if ( !aSource.IsEof()) {\n sLine.EraseAllChars( '\\r' );\n aDestination.WriteLine( sLine );\n }\n else\n aDestination.WriteByteString( sLine );\n }\n\n aSource.Close();\n aDestination.Close();\n\n return TRUE;\n}\n\n\/*****************************************************************************\/\nByteString Export::GetNativeFile( ByteString sSource )\n\/*****************************************************************************\/\n{\n DirEntry aTemp( GetTempFile());\n ByteString sReturn( aTemp.GetFull(), RTL_TEXTENCODING_ASCII_US );\n\n for ( USHORT i = 0; i < 10; i++ )\n if ( ConvertLineEnds( sSource, sReturn ))\n return sReturn;\n\n return \"\";\n}\n\n\/*****************************************************************************\/\nDirEntry Export::GetTempFile()\n\/*****************************************************************************\/\n{\n#ifdef WNT\n String sTempDir( GetEnv( \"TEMP\" ), RTL_TEXTENCODING_ASCII_US );\n#else\n\/\/ String sTempDir( GetEnv( \"HOME\" ), RTL_TEXTENCODING_ASCII_US );\n String sTempDir( String::CreateFromAscii( \"\/tmp\" ));\n#endif\n\n rtl::OUString* sTempFilename = new rtl::OUString();\n int nRC = osl::FileBase::createTempFile( 0 , 0 , sTempFilename );\n if( nRC ) printf(\" osl::FileBase::createTempFile RC = %d\",nRC);\n ByteString sTmp( sTempFilename->getStr() , RTL_TEXTENCODING_UTF8 );\n#ifdef WNT\n sTmp.SearchAndReplace(\"file:\/\/\/\",\"\");\n sTmp.SearchAndReplaceAll('\/','\\\\');\n#else\n sTmp.SearchAndReplace(\"file:\/\/\",\"\");\n#endif\n DirEntry aDirEntry( sTmp );\n delete sTempFilename;\n return aDirEntry;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: srciter.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2007-10-30 12:29:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_transex3.hxx\"\n\n#include \"srciter.hxx\"\n#include \n\n\/\/\n\/\/ class SourceTreeIterator\n\/\/\n\n\/*****************************************************************************\/\nSourceTreeIterator::SourceTreeIterator(\n const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in )\n\/*****************************************************************************\/\n : bInExecute( FALSE ) , bLocal( bLocal_in )\n{\n (void) rVersion ;\n\n if(!bLocal){\n rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 );\n aRootDirectory = transex::Directory( sRootDirectory );\n }\n}\n\n\/*****************************************************************************\/\nSourceTreeIterator::~SourceTreeIterator()\n\/*****************************************************************************\/\n{\n}\n\n\/*****************************************************************************\/\nvoid SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory )\n\/*****************************************************************************\/\n{\n if ( bInExecute ) {\n rtl::OUString sDirName = aDirectory.getDirectoryName();\n\n static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( \"unxlngi\" ) );\n static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( \"unxsoli\" ) );\n static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( \"wntmsci\" ) );\n static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( \"unxsols\" ) );\n static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( \"common\" ) );\n static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( \"unxmacx\" ) );\n static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( \"unxlngx\" ) );\n static rtl::OUString WCARD8 ( rtl::OUString::createFromAscii( \"unxsolsx\" ) );\n static rtl::OUString WCARD9 ( rtl::OUString::createFromAscii( \"unxsolsu\" ) );\n static rtl::OUString WCARD10 ( rtl::OUString::createFromAscii( \"wntmscx\" ) );\n\n\n if( sDirName.indexOf( WCARD1 , 0 ) > -1 ||\n sDirName.indexOf( WCARD2 , 0 ) > -1 ||\n sDirName.indexOf( WCARD3 , 0 ) > -1 ||\n sDirName.indexOf( WCARD4 , 0 ) > -1 ||\n sDirName.indexOf( WCARD5 , 0 ) > -1 ||\n sDirName.indexOf( WCARD6 , 0 ) > -1 ||\n sDirName.indexOf( WCARD7 , 0 ) > -1 ||\n sDirName.indexOf( WCARD8 , 0 ) > -1 ||\n sDirName.indexOf( WCARD9 , 0 ) > -1 ||\n sDirName.indexOf( WCARD10 , 0 ) > -1\n ) return;\n \/\/printf(\"**** %s \\n\", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );\n aDirectory.setSkipLinks( bSkipLinks );\n aDirectory.readDirectory();\n OnExecuteDirectory( aDirectory.getFullName() );\n if ( aDirectory.getSubDirectories().size() )\n for ( ULONG i=0;i < aDirectory.getSubDirectories().size();i++ )\n ExecuteDirectory( aDirectory.getSubDirectories()[ i ] );\n }\n}\n\n\/*****************************************************************************\/\nBOOL SourceTreeIterator::StartExecute()\n\/*****************************************************************************\/\n{\n\n bInExecute = TRUE; \/\/ FIXME\n ExecuteDirectory( aRootDirectory );\n\n if ( bInExecute ) { \/\/ FIXME\n bInExecute = FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n\/*****************************************************************************\/\nvoid SourceTreeIterator::EndExecute()\n\/*****************************************************************************\/\n{\n bInExecute = FALSE;\n}\n\n\/*****************************************************************************\/\nvoid SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory )\n\/*****************************************************************************\/\n{\n fprintf( stdout, \"%s\\n\", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() );\n}\nINTEGRATION: CWS l10ntooling11 (1.9.20); FILE MERGED 2008\/02\/11 16:52:29 ihi 1.9.20.1: #i85733# skip all sub dirs if the file no_localization is found\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: srciter.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2008-02-18 15:10:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_transex3.hxx\"\n\n#include \"srciter.hxx\"\n#include \n#include \n\n\/\/\n\/\/ class SourceTreeIterator\n\/\/\n\n\/*****************************************************************************\/\nSourceTreeIterator::SourceTreeIterator(\n const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in )\n\/*****************************************************************************\/\n : bInExecute( FALSE ) , bLocal( bLocal_in )\n{\n (void) rVersion ;\n\n if(!bLocal){\n rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 );\n aRootDirectory = transex::Directory( sRootDirectory );\n }\n}\n\n\/*****************************************************************************\/\nSourceTreeIterator::~SourceTreeIterator()\n\/*****************************************************************************\/\n{\n}\n\n\/*****************************************************************************\/\nvoid SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory )\n\/*****************************************************************************\/\n{\n if ( bInExecute ) {\n rtl::OUString sDirName = aDirectory.getDirectoryName();\n\n static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( \"unxlngi\" ) );\n static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( \"unxsoli\" ) );\n static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( \"wntmsci\" ) );\n static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( \"unxsols\" ) );\n static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( \"common\" ) );\n static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( \"unxmacx\" ) );\n static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( \"unxlngx\" ) );\n static rtl::OUString WCARD8 ( rtl::OUString::createFromAscii( \"unxsolsx\" ) );\n static rtl::OUString WCARD9 ( rtl::OUString::createFromAscii( \"unxsolsu\" ) );\n static rtl::OUString WCARD10 ( rtl::OUString::createFromAscii( \"wntmscx\" ) );\n\n\n if( sDirName.indexOf( WCARD1 , 0 ) > -1 ||\n sDirName.indexOf( WCARD2 , 0 ) > -1 ||\n sDirName.indexOf( WCARD3 , 0 ) > -1 ||\n sDirName.indexOf( WCARD4 , 0 ) > -1 ||\n sDirName.indexOf( WCARD5 , 0 ) > -1 ||\n sDirName.indexOf( WCARD6 , 0 ) > -1 ||\n sDirName.indexOf( WCARD7 , 0 ) > -1 ||\n sDirName.indexOf( WCARD8 , 0 ) > -1 ||\n sDirName.indexOf( WCARD9 , 0 ) > -1 ||\n sDirName.indexOf( WCARD10 , 0 ) > -1\n ) return;\n \/\/printf(\"**** %s \\n\", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );\n\n rtl::OUString sDirNameTmp = aDirectory.getFullName();\n ByteString sDirNameTmpB( OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );\n\n#ifdef WNT\n sDirNameTmpB.Append( ByteString(\"\\\\no_localization\") );\n#else\n sDirNameTmpB.Append( ByteString(\"\/no_localization\") );\n#endif\n \/\/printf(\"**** %s \\n\", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );\n\n DirEntry aDE( sDirNameTmpB.GetBuffer() );\n if( aDE.Exists() )\n {\n \/\/printf(\"#### no_localization file found ... skipping\");\n return;\n }\n\n aDirectory.setSkipLinks( bSkipLinks );\n aDirectory.readDirectory();\n OnExecuteDirectory( aDirectory.getFullName() );\n if ( aDirectory.getSubDirectories().size() )\n for ( ULONG i=0;i < aDirectory.getSubDirectories().size();i++ )\n ExecuteDirectory( aDirectory.getSubDirectories()[ i ] );\n }\n}\n\n\/*****************************************************************************\/\nBOOL SourceTreeIterator::StartExecute()\n\/*****************************************************************************\/\n{\n\n bInExecute = TRUE; \/\/ FIXME\n ExecuteDirectory( aRootDirectory );\n\n if ( bInExecute ) { \/\/ FIXME\n bInExecute = FALSE;\n return TRUE;\n }\n return FALSE;\n}\n\n\/*****************************************************************************\/\nvoid SourceTreeIterator::EndExecute()\n\/*****************************************************************************\/\n{\n bInExecute = FALSE;\n}\n\n\/*****************************************************************************\/\nvoid SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory )\n\/*****************************************************************************\/\n{\n fprintf( stdout, \"%s\\n\", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() );\n}\n<|endoftext|>"} {"text":"#include \"mega.h\"\n#include \"gtest\/gtest.h\"\n#include \"test.h\"\n#include \n#include \n\nbool gRunningInCI = false;\nbool gTestingInvalidArgs = false;\nstd::string USER_AGENT = \"Integration Tests with GoogleTest framework\";\n\nnamespace {\n\nclass MegaLogger : public mega::Logger\n{\npublic:\n void log(const char* time, int loglevel, const char* source, const char* message)\n {\n std::ostringstream os;\n\n os << \"[\";\n if (time)\n {\n os << time;\n }\n else\n {\n auto t = std::time(NULL);\n char ts[50];\n if (!std::strftime(ts, sizeof(ts), \"%H:%M:%S\", std::gmtime(&t)))\n {\n ts[0] = '\\0';\n }\n os << ts;\n }\n os << \"] \" << mega::SimpleLogger::toStr(static_cast(loglevel)) << \": \" << message;\n\n if (source)\n {\n os << \" (\" << source << \")\";\n }\n os << std::endl;\n\n if (loglevel <= mega::SimpleLogger::logCurrentLevel)\n {\n if (gRunningInCI)\n {\n if (!mLogFile.is_open())\n {\n mLogFile.open(\"test_integration.log\");\n }\n mLogFile << os.str() << std::flush;\n }\n else\n {\n#ifndef _WIN32\n std::cout << os.str() << std::flush;\n#endif\n if (!gTestingInvalidArgs)\n {\n ASSERT_NE(loglevel, mega::logError) << os.str();\n }\n }\n#ifdef _WIN32\n OutputDebugStringA(os.str().c_str());\n#endif\n }\n }\n\nprivate:\n std::ofstream mLogFile;\n};\n\n} \/\/ anonymous\n\nint main (int argc, char *argv[])\n{\n if (!getenv(\"MEGA_EMAIL\") || !getenv(\"MEGA_PWD\") || !getenv(\"MEGA_EMAIL_AUX\") || !getenv(\"MEGA_PWD_AUX\"))\n {\n std::cout << \"please set username and password env variables for test\" << std::endl;\n return 1;\n }\n\n std::vector myargv1(argv, argv + argc);\n std::vector myargv2;\n\n for (auto it = myargv1.begin(); it != myargv1.end(); ++it)\n {\n if (std::string(*it) == \"--CI\")\n {\n gRunningInCI = true;\n argc -= 1;\n }\n else if (std::string(*it).substr(0, 12) == \"--USERAGENT:\")\n {\n USER_AGENT = std::string(*it).substr(12);\n argc -= 1;\n }\n else if (std::string(*it).substr(0, 9) == \"--APIURL:\")\n {\n mega::MegaClient::APIURL = std::string(*it).substr(9);\n argc -= 1;\n }\n else\n {\n myargv2.push_back(*it);\n }\n }\n\n MegaLogger megaLogger;\n\n mega::SimpleLogger::setLogLevel(mega::logMax);\n mega::SimpleLogger::setOutputClass(&megaLogger);\n\n#if defined(_WIN32) && defined(NO_READLINE)\n using namespace mega;\n WinConsole* wc = new CONSOLE_CLASS;\n wc->setShellConsole();\n#endif\n\n ::testing::InitGoogleTest(&argc, myargv2.data());\n return RUN_ALL_TESTS();\n}\nuse mega::m_gmtime for thread safety#include \"mega.h\"\n#include \"gtest\/gtest.h\"\n#include \"test.h\"\n#include \n#include \n\nbool gRunningInCI = false;\nbool gTestingInvalidArgs = false;\nstd::string USER_AGENT = \"Integration Tests with GoogleTest framework\";\n\nnamespace {\n\nclass MegaLogger : public mega::Logger\n{\npublic:\n void log(const char* time, int loglevel, const char* source, const char* message)\n {\n std::ostringstream os;\n\n os << \"[\";\n if (time)\n {\n os << time;\n }\n else\n {\n auto t = std::time(NULL);\n char ts[50];\n struct tm dt;\n mega::m_gmtime(t, &dt);\n if (!std::strftime(ts, sizeof(ts), \"%H:%M:%S\", &dt))\n {\n ts[0] = '\\0';\n }\n os << ts;\n }\n os << \"] \" << mega::SimpleLogger::toStr(static_cast(loglevel)) << \": \" << message;\n\n if (source)\n {\n os << \" (\" << source << \")\";\n }\n os << std::endl;\n\n if (loglevel <= mega::SimpleLogger::logCurrentLevel)\n {\n if (gRunningInCI)\n {\n if (!mLogFile.is_open())\n {\n mLogFile.open(\"test_integration.log\");\n }\n mLogFile << os.str() << std::flush;\n }\n else\n {\n#ifndef _WIN32\n std::cout << os.str() << std::flush;\n#endif\n if (!gTestingInvalidArgs)\n {\n ASSERT_NE(loglevel, mega::logError) << os.str();\n }\n }\n#ifdef _WIN32\n OutputDebugStringA(os.str().c_str());\n#endif\n }\n }\n\nprivate:\n std::ofstream mLogFile;\n};\n\n} \/\/ anonymous\n\nint main (int argc, char *argv[])\n{\n if (!getenv(\"MEGA_EMAIL\") || !getenv(\"MEGA_PWD\") || !getenv(\"MEGA_EMAIL_AUX\") || !getenv(\"MEGA_PWD_AUX\"))\n {\n std::cout << \"please set username and password env variables for test\" << std::endl;\n return 1;\n }\n\n std::vector myargv1(argv, argv + argc);\n std::vector myargv2;\n\n for (auto it = myargv1.begin(); it != myargv1.end(); ++it)\n {\n if (std::string(*it) == \"--CI\")\n {\n gRunningInCI = true;\n argc -= 1;\n }\n else if (std::string(*it).substr(0, 12) == \"--USERAGENT:\")\n {\n USER_AGENT = std::string(*it).substr(12);\n argc -= 1;\n }\n else if (std::string(*it).substr(0, 9) == \"--APIURL:\")\n {\n mega::MegaClient::APIURL = std::string(*it).substr(9);\n argc -= 1;\n }\n else\n {\n myargv2.push_back(*it);\n }\n }\n\n MegaLogger megaLogger;\n\n mega::SimpleLogger::setLogLevel(mega::logMax);\n mega::SimpleLogger::setOutputClass(&megaLogger);\n\n#if defined(_WIN32) && defined(NO_READLINE)\n using namespace mega;\n WinConsole* wc = new CONSOLE_CLASS;\n wc->setShellConsole();\n#endif\n\n ::testing::InitGoogleTest(&argc, myargv2.data());\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n* File: dir.cpp\n* Purpose: Implementation of class 'wxExDir'\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#include \n\nclass wxExDirTraverser: public wxDirTraverser\n{\npublic:\n wxExDirTraverser(wxExDir& dir)\n : m_Dir(dir)\n {}\n\n virtual wxDirTraverseResult OnDir(const wxString& dirname)\n {\n if (m_Dir.Cancelled())\n {\n return wxDIR_STOP;\n }\n\n if (m_Dir.GetFlags() & wxDIR_DIRS)\n {\n m_Dir.OnDir(dirname);\n }\n\n if (wxIsMainThread())\n {\n if (wxTheApp != NULL)\n {\n wxTheApp->Yield();\n }\n }\n else\n {\n wxThread::This()->Yield();\n }\n\n return wxDIR_CONTINUE;\n }\n\n virtual wxDirTraverseResult OnFile(const wxString& filename)\n {\n if (m_Dir.Cancelled())\n {\n return wxDIR_STOP;\n }\n\n wxFileName file(filename);\n\n if (wxExMatchesOneOf(file, m_Dir.GetFileSpec()))\n {\n m_Dir.OnFile(filename);\n }\n\n if (wxIsMainThread())\n {\n if (wxTheApp != NULL)\n {\n wxTheApp->Yield();\n }\n }\n else\n {\n wxThread::This()->Yield();\n }\n\n return wxDIR_CONTINUE;\n }\n\nprivate:\n wxExDir& m_Dir;\n};\n\nwxExDir::wxExDir(const wxString& fullpath, const wxString& filespec, int flags)\n : wxDir(fullpath)\n , m_FileSpec(filespec)\n , m_Flags(flags)\n{\n}\n\nsize_t wxExDir::FindFiles()\n{\n if (!IsOpened()) return 0;\n\n \/\/ Using m_FileSpec here does not work, as it might\n \/\/ contain several specs (*.cpp;*.h), wxDir does not handle that.\n \/\/ Do not combine into one, Ubuntu complains.\n wxExDirTraverser traverser(*this);\n return Traverse(traverser, wxEmptyString, m_Flags);\n}\nsimplified OnFile\/******************************************************************************\\\n* File: dir.cpp\n* Purpose: Implementation of class 'wxExDir'\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#include \n\nclass wxExDirTraverser: public wxDirTraverser\n{\npublic:\n wxExDirTraverser(wxExDir& dir)\n : m_Dir(dir)\n {}\n\n virtual wxDirTraverseResult OnDir(const wxString& dirname)\n {\n if (m_Dir.Cancelled())\n {\n return wxDIR_STOP;\n }\n\n if (m_Dir.GetFlags() & wxDIR_DIRS)\n {\n m_Dir.OnDir(dirname);\n }\n\n if (wxIsMainThread())\n {\n if (wxTheApp != NULL)\n {\n wxTheApp->Yield();\n }\n }\n else\n {\n wxThread::This()->Yield();\n }\n\n return wxDIR_CONTINUE;\n }\n\n virtual wxDirTraverseResult OnFile(const wxString& filename)\n {\n if (m_Dir.Cancelled())\n {\n return wxDIR_STOP;\n }\n\n if (wxExMatchesOneOf(filename, m_Dir.GetFileSpec()))\n {\n m_Dir.OnFile(filename);\n }\n\n if (wxIsMainThread())\n {\n if (wxTheApp != NULL)\n {\n wxTheApp->Yield();\n }\n }\n else\n {\n wxThread::This()->Yield();\n }\n\n return wxDIR_CONTINUE;\n }\n\nprivate:\n wxExDir& m_Dir;\n};\n\nwxExDir::wxExDir(const wxString& fullpath, const wxString& filespec, int flags)\n : wxDir(fullpath)\n , m_FileSpec(filespec)\n , m_Flags(flags)\n{\n}\n\nsize_t wxExDir::FindFiles()\n{\n if (!IsOpened()) return 0;\n\n \/\/ Using m_FileSpec here does not work, as it might\n \/\/ contain several specs (*.cpp;*.h), wxDir does not handle that.\n \/\/ Do not combine into one, Ubuntu complains.\n wxExDirTraverser traverser(*this);\n return Traverse(traverser, wxEmptyString, m_Flags);\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n* File: svn.cpp\n* Purpose: Implementation of wxExSVN class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#if wxUSE_GUI\n\nwxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;\n\nwxExSVN::wxExSVN(int command_id, const wxString& fullpath)\n : m_Type(GetType(command_id))\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\nwxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)\n : m_Type(type)\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\nvoid wxExSVN::Cleanup()\n{\n delete m_STCEntryDialog;\n}\n\nbool wxExSVN::DirExists(const wxFileName& filename)\n{\n wxFileName path(filename);\n path.AppendDir(\".svn\");\n return path.DirExists();\n}\n\nwxStandardID wxExSVN::Execute(wxWindow* parent)\n{\n const wxString svn_flags_name = wxString::Format(\"svn\/flags%d\", m_Type);\n const wxString svn_flags_contents = wxConfigBase::Get()->Read(svn_flags_name);\n\n if (parent != NULL)\n {\n std::vector v;\n\n if (m_Type == SVN_COMMIT)\n {\n v.push_back(wxExConfigItem(\n _(\"Revision comment\"), \n CONFIG_COMBOBOX,\n wxEmptyString,\n true)); \/\/ required\n }\n\n if (m_FullPath.empty() && m_Type != SVN_HELP)\n {\n v.push_back(wxExConfigItem(\n _(\"Base folder\"), \n CONFIG_COMBOBOXDIR, \n wxEmptyString, \n true)); \/\/ required\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(_(\"Flags\"), svn_flags_contents);\n v.push_back(wxExConfigItem(_(\"Flags\")));\n }\n\n if (UseSubcommand())\n {\n v.push_back(wxExConfigItem(_(\"Subcommand\")));\n }\n\n m_ReturnCode = (wxStandardID)wxExConfigDialog(parent,\n v,\n m_Caption).ShowModal();\n\n if (m_ReturnCode == wxID_CANCEL)\n {\n return m_ReturnCode;\n }\n }\n\n const wxString cwd = wxGetCwd();\n\n wxString file;\n\n if (m_FullPath.empty())\n {\n wxSetWorkingDirectory(wxExConfigFirstOf(wxConfigBase::Get()->Read(_(\"Base folder\"))));\n }\n else\n {\n file = \" \\\"\" + m_FullPath + \"\\\"\";\n }\n\n wxString comment;\n\n if (m_Type == SVN_COMMIT)\n {\n comment = \n \" -m \\\"\" + wxExConfigFirstOf(wxConfigBase::Get()->Read(_(\"Revision comment\"))) \n + \"\\\"\";\n }\n\n wxString flags;\n wxString subcommand;\n \n if (UseSubcommand())\n {\n subcommand = wxConfigBase::Get()->Read(_(\"Subcommand\"));\n\n if (!subcommand.empty())\n {\n subcommand = \" \" + subcommand;\n }\n }\n\n if (UseFlags())\n {\n flags = wxConfigBase::Get()->Read(_(\"Flags\"));\n\n wxConfigBase::Get()->Write(svn_flags_name, flags);\n\n m_CommandWithFlags = m_Command + \" \" + flags;\n\n if (!flags.empty())\n {\n flags += \" \";\n }\n }\n\n const wxString command = \n \"svn \" + flags + m_Command + subcommand + comment + file;\n\n wxArrayString output;\n wxArrayString errors;\n m_Output.clear();\n\n if (wxExecute(\n command,\n output,\n errors) == -1)\n {\n if (m_Output.empty())\n {\n m_Output = \"Could not execute: \" + command;\n }\n\n m_ReturnCode = wxID_ABORT;\n return m_ReturnCode;\n }\n\n wxExLog::Get()->Log(command);\n\n if (m_FullPath.empty())\n {\n wxSetWorkingDirectory(cwd);\n }\n\n \/\/ First output the errors.\n for (size_t i = 0; i < errors.GetCount(); i++)\n {\n m_Output += errors[i] + \"\\n\";\n }\n\n \/\/ Then the normal output, will be empty if there are errors.\n for (size_t j = 0; j < output.GetCount(); j++)\n {\n m_Output += output[j] + \"\\n\";\n }\n\n return wxID_OK;\n}\n\nwxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent)\n{\n \/\/ If an error occurred, already shown by wxExecute itself.\n if (Execute(parent) == wxID_OK)\n {\n ShowOutput(parent);\n }\n\n return m_ReturnCode;\n}\n\nwxExSVNType wxExSVN::GetType(int command_id) const\n{\n switch (command_id)\n {\n case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;\n case ID_EDIT_SVN_CAT: return SVN_CAT; break;\n case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;\n case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;\n case ID_EDIT_SVN_HELP: return SVN_HELP; break;\n case ID_EDIT_SVN_INFO: return SVN_INFO; break;\n case ID_EDIT_SVN_LOG: return SVN_LOG; break;\n case ID_EDIT_SVN_REVERT: return SVN_REVERT; break;\n case ID_EDIT_SVN_STAT: return SVN_STAT; break;\n case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break;\n default:\n wxFAIL;\n return SVN_STAT;\n break;\n }\n}\n\nvoid wxExSVN::Initialize()\n{\n switch (m_Type)\n {\n case SVN_BLAME: m_Caption = \"SVN Blame\"; break;\n case SVN_CAT: m_Caption = \"SVN Cat\"; break;\n case SVN_COMMIT: m_Caption = \"SVN Commit\"; break;\n case SVN_DIFF: m_Caption = \"SVN Diff\"; break;\n case SVN_HELP: m_Caption = \"SVN Help\"; break;\n case SVN_INFO: m_Caption = \"SVN Info\"; break;\n case SVN_LOG: m_Caption = \"SVN Log\"; break;\n case SVN_REVERT: m_Caption = \"SVN Revert\"; break;\n case SVN_STAT: m_Caption = \"SVN Stat\"; break;\n case SVN_UPDATE: m_Caption = \"SVN Update\"; break;\n default:\n wxFAIL;\n break;\n }\n\n m_Command = m_Caption.AfterFirst(' ').Lower();\n\n \/\/ Currently no flags, as no command was executed.\n m_CommandWithFlags = m_Command;\n\n m_Output.clear();\n m_ReturnCode = wxID_NONE;\n}\n\nvoid wxExSVN::ShowOutput(wxWindow* parent) const\n{\n switch (m_ReturnCode)\n {\n case wxID_CANCEL:\n break;\n\n case wxID_ABORT:\n wxMessageBox(m_Output);\n break;\n\n case wxID_OK:\n {\n const wxString caption = m_Caption +\n (!m_FullPath.empty() ? \" \" + \n wxFileName(m_FullPath).GetFullName(): \n wxString(wxEmptyString));\n\n \/\/ Create a dialog for contents.\n if (m_STCEntryDialog == NULL)\n {\n m_STCEntryDialog = new wxExSTCEntryDialog(\n parent,\n caption,\n m_Output,\n wxEmptyString,\n wxOK,\n wxID_ANY,\n wxDefaultPosition, wxSize(575, 250));\n }\n else\n {\n m_STCEntryDialog->SetText(m_Output);\n m_STCEntryDialog->SetTitle(caption);\n \n \/\/ Reset a previous lexer.\n if (!m_STCEntryDialog->GetLexer().empty())\n {\n m_STCEntryDialog->SetLexer(wxEmptyString);\n }\n }\n\n \/\/ Add a lexer if we specified a path, asked for cat or blame \n \/\/ and there is a lexer.\n if (\n !m_FullPath.empty() &&\n (m_Type == SVN_CAT || m_Type == SVN_BLAME))\n {\n const wxExFileName fn(m_FullPath);\n \n if (!fn.GetLexer().GetScintillaLexer().empty())\n {\n m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());\n }\n }\n\n m_STCEntryDialog->Show();\n }\n break;\n\n default:\n wxFAIL;\n break;\n }\n}\n\nbool wxExSVN::UseFlags() const\n{\n return m_Type != SVN_UPDATE && m_Type != SVN_HELP;\n}\n\nbool wxExSVN::UseSubcommand() const\n{\n return m_Type == SVN_HELP;\n}\n\n#endif\nadd assert on the parent\/******************************************************************************\\\n* File: svn.cpp\n* Purpose: Implementation of wxExSVN class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#if wxUSE_GUI\n\nwxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;\n\nwxExSVN::wxExSVN(int command_id, const wxString& fullpath)\n : m_Type(GetType(command_id))\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\nwxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)\n : m_Type(type)\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\nvoid wxExSVN::Cleanup()\n{\n delete m_STCEntryDialog;\n}\n\nbool wxExSVN::DirExists(const wxFileName& filename)\n{\n wxFileName path(filename);\n path.AppendDir(\".svn\");\n return path.DirExists();\n}\n\nwxStandardID wxExSVN::Execute(wxWindow* parent)\n{\n const wxString svn_flags_name = wxString::Format(\"svn\/flags%d\", m_Type);\n const wxString svn_flags_contents = wxConfigBase::Get()->Read(svn_flags_name);\n\n if (parent != NULL)\n {\n std::vector v;\n\n if (m_Type == SVN_COMMIT)\n {\n v.push_back(wxExConfigItem(\n _(\"Revision comment\"), \n CONFIG_COMBOBOX,\n wxEmptyString,\n true)); \/\/ required\n }\n\n if (m_FullPath.empty() && m_Type != SVN_HELP)\n {\n v.push_back(wxExConfigItem(\n _(\"Base folder\"), \n CONFIG_COMBOBOXDIR, \n wxEmptyString, \n true)); \/\/ required\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(_(\"Flags\"), svn_flags_contents);\n v.push_back(wxExConfigItem(_(\"Flags\")));\n }\n\n if (UseSubcommand())\n {\n v.push_back(wxExConfigItem(_(\"Subcommand\")));\n }\n\n m_ReturnCode = (wxStandardID)wxExConfigDialog(parent,\n v,\n m_Caption).ShowModal();\n\n if (m_ReturnCode == wxID_CANCEL)\n {\n return m_ReturnCode;\n }\n }\n\n const wxString cwd = wxGetCwd();\n\n wxString file;\n\n if (m_FullPath.empty())\n {\n wxSetWorkingDirectory(wxExConfigFirstOf(wxConfigBase::Get()->Read(_(\"Base folder\"))));\n }\n else\n {\n file = \" \\\"\" + m_FullPath + \"\\\"\";\n }\n\n wxString comment;\n\n if (m_Type == SVN_COMMIT)\n {\n comment = \n \" -m \\\"\" + wxExConfigFirstOf(wxConfigBase::Get()->Read(_(\"Revision comment\"))) \n + \"\\\"\";\n }\n\n wxString flags;\n wxString subcommand;\n \n if (UseSubcommand())\n {\n subcommand = wxConfigBase::Get()->Read(_(\"Subcommand\"));\n\n if (!subcommand.empty())\n {\n subcommand = \" \" + subcommand;\n }\n }\n\n if (UseFlags())\n {\n flags = wxConfigBase::Get()->Read(_(\"Flags\"));\n\n wxConfigBase::Get()->Write(svn_flags_name, flags);\n\n m_CommandWithFlags = m_Command + \" \" + flags;\n\n if (!flags.empty())\n {\n flags += \" \";\n }\n }\n\n const wxString command = \n \"svn \" + flags + m_Command + subcommand + comment + file;\n\n wxArrayString output;\n wxArrayString errors;\n m_Output.clear();\n\n if (wxExecute(\n command,\n output,\n errors) == -1)\n {\n if (m_Output.empty())\n {\n m_Output = \"Could not execute: \" + command;\n }\n\n m_ReturnCode = wxID_ABORT;\n return m_ReturnCode;\n }\n\n wxExLog::Get()->Log(command);\n\n if (m_FullPath.empty())\n {\n wxSetWorkingDirectory(cwd);\n }\n\n \/\/ First output the errors.\n for (size_t i = 0; i < errors.GetCount(); i++)\n {\n m_Output += errors[i] + \"\\n\";\n }\n\n \/\/ Then the normal output, will be empty if there are errors.\n for (size_t j = 0; j < output.GetCount(); j++)\n {\n m_Output += output[j] + \"\\n\";\n }\n\n return wxID_OK;\n}\n\nwxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent)\n{\n \/\/ We must have a parent.\n wxASSERT(parent != NULL);\n\n \/\/ If an error occurred, already shown by wxExecute itself.\n if (Execute(parent) == wxID_OK)\n {\n ShowOutput(parent);\n }\n\n return m_ReturnCode;\n}\n\nwxExSVNType wxExSVN::GetType(int command_id) const\n{\n switch (command_id)\n {\n case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;\n case ID_EDIT_SVN_CAT: return SVN_CAT; break;\n case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;\n case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;\n case ID_EDIT_SVN_HELP: return SVN_HELP; break;\n case ID_EDIT_SVN_INFO: return SVN_INFO; break;\n case ID_EDIT_SVN_LOG: return SVN_LOG; break;\n case ID_EDIT_SVN_REVERT: return SVN_REVERT; break;\n case ID_EDIT_SVN_STAT: return SVN_STAT; break;\n case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break;\n default:\n wxFAIL;\n return SVN_STAT;\n break;\n }\n}\n\nvoid wxExSVN::Initialize()\n{\n switch (m_Type)\n {\n case SVN_BLAME: m_Caption = \"SVN Blame\"; break;\n case SVN_CAT: m_Caption = \"SVN Cat\"; break;\n case SVN_COMMIT: m_Caption = \"SVN Commit\"; break;\n case SVN_DIFF: m_Caption = \"SVN Diff\"; break;\n case SVN_HELP: m_Caption = \"SVN Help\"; break;\n case SVN_INFO: m_Caption = \"SVN Info\"; break;\n case SVN_LOG: m_Caption = \"SVN Log\"; break;\n case SVN_REVERT: m_Caption = \"SVN Revert\"; break;\n case SVN_STAT: m_Caption = \"SVN Stat\"; break;\n case SVN_UPDATE: m_Caption = \"SVN Update\"; break;\n default:\n wxFAIL;\n break;\n }\n\n m_Command = m_Caption.AfterFirst(' ').Lower();\n\n \/\/ Currently no flags, as no command was executed.\n m_CommandWithFlags = m_Command;\n\n m_Output.clear();\n m_ReturnCode = wxID_NONE;\n}\n\nvoid wxExSVN::ShowOutput(wxWindow* parent) const\n{\n switch (m_ReturnCode)\n {\n case wxID_CANCEL:\n break;\n\n case wxID_ABORT:\n wxMessageBox(m_Output);\n break;\n\n case wxID_OK:\n {\n const wxString caption = m_Caption +\n (!m_FullPath.empty() ? \" \" + \n wxFileName(m_FullPath).GetFullName(): \n wxString(wxEmptyString));\n\n \/\/ Create a dialog for contents.\n if (m_STCEntryDialog == NULL)\n {\n m_STCEntryDialog = new wxExSTCEntryDialog(\n parent,\n caption,\n m_Output,\n wxEmptyString,\n wxOK,\n wxID_ANY,\n wxDefaultPosition, wxSize(575, 250));\n }\n else\n {\n m_STCEntryDialog->SetText(m_Output);\n m_STCEntryDialog->SetTitle(caption);\n \n \/\/ Reset a previous lexer.\n if (!m_STCEntryDialog->GetLexer().empty())\n {\n m_STCEntryDialog->SetLexer(wxEmptyString);\n }\n }\n\n \/\/ Add a lexer if we specified a path, asked for cat or blame \n \/\/ and there is a lexer.\n if (\n !m_FullPath.empty() &&\n (m_Type == SVN_CAT || m_Type == SVN_BLAME))\n {\n const wxExFileName fn(m_FullPath);\n \n if (!fn.GetLexer().GetScintillaLexer().empty())\n {\n m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());\n }\n }\n\n m_STCEntryDialog->Show();\n }\n break;\n\n default:\n wxFAIL;\n break;\n }\n}\n\nbool wxExSVN::UseFlags() const\n{\n return m_Type != SVN_UPDATE && m_Type != SVN_HELP;\n}\n\nbool wxExSVN::UseSubcommand() const\n{\n return m_Type == SVN_HELP;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/breakpad_win.h\"\n\n#include \n#include \n#include \n\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/file_version_info.h\"\n#include \"base\/registry.h\"\n#include \"base\/string_util.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/app\/google_update_client.h\"\n#include \"chrome\/app\/hard_error_handler_win.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"breakpad\/src\/client\/windows\/handler\/exception_handler.h\"\n\nnamespace {\n\nconst wchar_t kGoogleUpdatePipeName[] = L\"\\\\\\\\.\\\\pipe\\\\GoogleCrashServices\\\\\";\nconst wchar_t kChromePipeName[] = L\"\\\\\\\\.\\\\pipe\\\\ChromeCrashServices\";\n\n\/\/ This is the well known SID for the system principal.\nconst wchar_t kSystemPrincipalSid[] =L\"S-1-5-18\";\n\ngoogle_breakpad::ExceptionHandler* g_breakpad = NULL;\n\nstd::vector* url_chunks = NULL;\n\n\/\/ Dumps the current process memory.\nextern \"C\" void __declspec(dllexport) __cdecl DumpProcess() {\n if (g_breakpad)\n g_breakpad->WriteMinidump();\n}\n\n\/\/ Returns the custom info structure based on the dll in parameter and the\n\/\/ process type.\nstatic google_breakpad::CustomClientInfo* custom_info = NULL;\ngoogle_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& dll_path,\n const std::wstring& type) {\n scoped_ptr\n version_info(FileVersionInfo::CreateFileVersionInfo(dll_path));\n\n std::wstring version, product;\n if (version_info.get()) {\n \/\/ Get the information from the file.\n product = version_info->product_short_name();\n version = version_info->product_version();\n if (!version_info->is_official_build())\n version.append(L\"-devel\");\n } else {\n \/\/ No version info found. Make up the values.\n product = L\"Chrome\";\n version = L\"0.0.0.0-devel\";\n }\n\n google_breakpad::CustomInfoEntry ver_entry(L\"ver\", version.c_str());\n google_breakpad::CustomInfoEntry prod_entry(L\"prod\", product.c_str());\n google_breakpad::CustomInfoEntry plat_entry(L\"plat\", L\"Win32\");\n google_breakpad::CustomInfoEntry type_entry(L\"ptype\", type.c_str());\n\n if (type == L\"renderer\") {\n \/\/ If we're a renderer create entries for the URL. Currently we only allow\n \/\/ each chunk to be 64 characters, which isn't enough for a URL. As a hack\n \/\/ we create 8 entries and split the URL across the entries.\n google_breakpad::CustomInfoEntry url1(L\"url-chunk-1\", L\"\");\n google_breakpad::CustomInfoEntry url2(L\"url-chunk-2\", L\"\");\n google_breakpad::CustomInfoEntry url3(L\"url-chunk-3\", L\"\");\n google_breakpad::CustomInfoEntry url4(L\"url-chunk-4\", L\"\");\n google_breakpad::CustomInfoEntry url5(L\"url-chunk-5\", L\"\");\n google_breakpad::CustomInfoEntry url6(L\"url-chunk-6\", L\"\");\n google_breakpad::CustomInfoEntry url7(L\"url-chunk-7\", L\"\");\n google_breakpad::CustomInfoEntry url8(L\"url-chunk-8\", L\"\");\n\n static google_breakpad::CustomInfoEntry entries[] =\n { ver_entry, prod_entry, plat_entry, type_entry, url1, url2, url3,\n url4, url5, url6, url7, url8 };\n\n std::vector* tmp_url_chunks = new std::vector(8);\n for (size_t i = 0; i < 8; ++i)\n (*tmp_url_chunks)[i] = entries[4 + i].value;\n url_chunks = tmp_url_chunks;\n\n static google_breakpad::CustomClientInfo custom_info = {entries,\n arraysize(entries)};\n\n return &custom_info;\n }\n static google_breakpad::CustomInfoEntry entries[] = {ver_entry,\n prod_entry,\n plat_entry,\n type_entry};\n\n static google_breakpad::CustomClientInfo custom_info = {entries,\n arraysize(entries)};\n\n return &custom_info;\n}\n\n\/\/ Contains the information needed by the worker thread.\nstruct CrashReporterInfo {\n google_breakpad::CustomClientInfo* custom_info;\n std::wstring dll_path;\n std::wstring process_type;\n};\n\n\/\/ This callback is executed when the browser process has crashed, after\n\/\/ the crash dump has been created. We need to minimize the amount of work\n\/\/ done here since we have potentially corrupted process. Our job is to\n\/\/ spawn another instance of chrome which will show a 'chrome has crashed'\n\/\/ dialog. This code needs to live in the exe and thus has no access to\n\/\/ facilities such as the i18n helpers.\nbool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,\n EXCEPTION_POINTERS* ex_info,\n MDRawAssertionInfo*, bool) {\n \/\/ If the exception is because there was a problem loading a delay-loaded\n \/\/ module, then show the user a dialog explaining the problem and then exit.\n if (DelayLoadFailureExceptionMessageBox(ex_info))\n return true;\n\n \/\/ We set CHROME_CRASHED env var. If the CHROME_RESTART is present.\n \/\/ This signals the child process to show the 'chrome has crashed' dialog.\n if (!::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0))\n return true;\n ::SetEnvironmentVariableW(env_vars::kShowRestart, L\"1\");\n \/\/ Now we just start chrome browser with the same command line.\n STARTUPINFOW si = {sizeof(si)};\n PROCESS_INFORMATION pi;\n if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,\n CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {\n ::CloseHandle(pi.hProcess);\n ::CloseHandle(pi.hThread);\n }\n \/\/ After this return we will be terminated. The actual return value is\n \/\/ not used at all.\n return true;\n}\n\n\/\/ Previous unhandled filter. Will be called if not null when we\n\/\/ intercept a crash.\nLPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;\n\n\/\/ Exception filter used when breakpad is not enabled. We just display\n\/\/ the \"Do you want to restart\" message and then we call the previous filter.\nlong WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {\n DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);\n\n if (previous_filter)\n return previous_filter(info);\n\n return EXCEPTION_EXECUTE_HANDLER;\n}\n\nextern \"C\" void __declspec(dllexport) __cdecl SetActiveRendererURL(\n const wchar_t* url_cstring) {\n DCHECK(url_cstring);\n if (!url_chunks)\n return;\n\n std::wstring url(url_cstring);\n size_t num_chunks = url_chunks->size();\n size_t chunk_index = 0;\n size_t url_size = url.size();\n\n \/\/ Split the url across all the chunks.\n for (size_t url_offset = 0;\n chunk_index < num_chunks && url_offset < url_size; ++chunk_index) {\n size_t current_chunk_size = std::min(url_size - url_offset,\n static_cast(\n google_breakpad::CustomInfoEntry::kValueMaxLength - 1));\n url._Copy_s((*url_chunks)[chunk_index],\n google_breakpad::CustomInfoEntry::kValueMaxLength,\n current_chunk_size, url_offset);\n (*url_chunks)[chunk_index][current_chunk_size] = L'\\0';\n url_offset += current_chunk_size;\n }\n\n \/\/ And null terminate any unneeded chunks.\n for (; chunk_index < num_chunks; ++chunk_index)\n (*url_chunks)[chunk_index][0] = L'\\0';\n}\n\n} \/\/ namespace\n\n\/\/ This function is executed by the child process that DumpDoneCallback()\n\/\/ spawned and basically just shows the 'chrome has crashed' dialog if\n\/\/ the CHROME_CRASHED environment variable is present.\nbool ShowRestartDialogIfCrashed(bool* exit_now) {\n if (!::GetEnvironmentVariableW(env_vars::kShowRestart, NULL, 0))\n return false;\n\n DWORD len = ::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0);\n if (!len)\n return true;\n\n \/\/ We wrap the call to MessageBoxW with a SEH handler because it some\n \/\/ machines with CursorXP, PeaDict or with FontExplorer installed it crashes\n \/\/ uncontrollably here. Being this a best effort deal we better go away.\n#pragma warning(push)\n#pragma warning(disable:4509) \/\/ warning: SEH used but dlg_strings has a dtor.\n __try {\n wchar_t* restart_data = new wchar_t[len + 1];\n ::GetEnvironmentVariableW(env_vars::kRestartInfo, restart_data, len);\n restart_data[len] = 0;\n \/\/ The CHROME_RESTART var contains the dialog strings separated by '|'.\n \/\/ See PrepareRestartOnCrashEnviroment() function for details.\n std::vector dlg_strings;\n SplitString(restart_data, L'|', &dlg_strings);\n delete[] restart_data;\n if (dlg_strings.size() < 3)\n return true;\n\n \/\/ If the UI layout is right-to-left, we need to pass the appropriate MB_XXX\n \/\/ flags so that an RTL message box is displayed.\n UINT flags = MB_OKCANCEL | MB_ICONWARNING;\n if (dlg_strings[2] == env_vars::kRtlLocale)\n flags |= MB_RIGHT | MB_RTLREADING;\n\n \/\/ Show the dialog now. It is ok if another chrome is started by the\n \/\/ user since we have not initialized the databases.\n *exit_now = (IDOK != ::MessageBoxW(NULL, dlg_strings[1].c_str(),\n dlg_strings[0].c_str(), flags));\n } __except(EXCEPTION_EXECUTE_HANDLER) {\n \/\/ Its not safe to continue executing, exit silently here.\n ::ExitProcess(ResultCodes::RESPAWN_FAILED);\n }\n#pragma warning(pop)\n return true;\n}\n\nstatic DWORD __stdcall InitCrashReporterThread(void* param) {\n CrashReporterInfo* info = reinterpret_cast(param);\n\n \/\/ GetCustomInfo can take a few milliseconds to get the file information, so\n \/\/ we do it here so it can run in a separate thread.\n info->custom_info = GetCustomInfo(info->dll_path, info->process_type);\n\n const CommandLine& command = *CommandLine::ForCurrentProcess();\n bool full_dump = command.HasSwitch(switches::kFullMemoryCrashReport);\n bool use_crash_service = command.HasSwitch(switches::kNoErrorDialogs) ||\n GetEnvironmentVariable(L\"CHROME_HEADLESS\", NULL, 0);\n\n google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;\n\n if (info->process_type == L\"browser\") {\n \/\/ We install the post-dump callback only for the browser process. It\n \/\/ spawns a new browser process.\n callback = &DumpDoneCallback;\n }\n\n std::wstring pipe_name;\n if (use_crash_service) {\n \/\/ Crash reporting is done by crash_service.exe.\n pipe_name = kChromePipeName;\n } else {\n \/\/ We want to use the Google Update crash reporting. We need to check if the\n \/\/ user allows it first.\n if (!GoogleUpdateSettings::GetCollectStatsConsent()) {\n \/\/ The user did not allow Google Update to send crashes, we need to use\n \/\/ our default crash handler instead, but only for the browser process.\n if (callback)\n InitDefaultCrashCallback();\n return 0;\n }\n\n \/\/ Build the pipe name. It can be either:\n \/\/ System-wide install: \"NamedPipe\\GoogleCrashServices\\S-1-5-18\"\n \/\/ Per-user install: \"NamedPipe\\GoogleCrashServices\\\"\n std::wstring user_sid;\n if (InstallUtil::IsPerUserInstall(info->dll_path.c_str())) {\n if (!win_util::GetUserSidString(&user_sid)) {\n delete info;\n return -1;\n }\n } else {\n user_sid = kSystemPrincipalSid;\n }\n\n pipe_name = kGoogleUpdatePipeName;\n pipe_name += user_sid;\n }\n\n \/\/ Get the alternate dump directory. We use the temp path.\n wchar_t temp_dir[MAX_PATH] = {0};\n ::GetTempPathW(MAX_PATH, temp_dir);\n\n MINIDUMP_TYPE dump_type = full_dump ? MiniDumpWithFullMemory : MiniDumpNormal;\n\n g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, NULL, callback,\n NULL, google_breakpad::ExceptionHandler::HANDLER_ALL,\n dump_type, pipe_name.c_str(), info->custom_info);\n\n if (!g_breakpad->IsOutOfProcess()) {\n \/\/ The out-of-process handler is unavailable.\n ::SetEnvironmentVariable(env_vars::kNoOOBreakpad,\n info->process_type.c_str());\n } else {\n \/\/ Tells breakpad to handle breakpoint and single step exceptions.\n \/\/ This might break JIT debuggers, but at least it will always\n \/\/ generate a crashdump for these exceptions.\n g_breakpad->set_handle_debug_exceptions(true);\n }\n\n delete info;\n return 0;\n}\n\nvoid InitDefaultCrashCallback() {\n previous_filter = SetUnhandledExceptionFilter(ChromeExceptionFilter);\n}\n\nvoid InitCrashReporterWithDllPath(const std::wstring& dll_path) {\n const CommandLine& command = *CommandLine::ForCurrentProcess();\n if (!command.HasSwitch(switches::kDisableBreakpad)) {\n \/\/ Disable the message box for assertions.\n _CrtSetReportMode(_CRT_ASSERT, 0);\n\n \/\/ Query the custom_info now because if we do it in the thread it's going to\n \/\/ fail in the sandbox. The thread will delete this object.\n CrashReporterInfo* info = new CrashReporterInfo;\n info->process_type = command.GetSwitchValue(switches::kProcessType);\n if (info->process_type.empty())\n info->process_type = L\"browser\";\n\n info->dll_path = dll_path;\n\n \/\/ If this is not the browser, we can't be sure that we will be able to\n \/\/ initialize the crash_handler in another thread, so we run it right away.\n \/\/ This is important to keep the thread for the browser process because\n \/\/ it may take some times to initialize the crash_service process. We use\n \/\/ the Windows worker pool to make better reuse of the thread.\n if (info->process_type != L\"browser\") {\n InitCrashReporterThread(info);\n } else {\n if (QueueUserWorkItem(\n &InitCrashReporterThread, info, WT_EXECUTELONGFUNCTION) == 0) {\n \/\/ We failed to queue to the worker pool, initialize in this thread.\n InitCrashReporterThread(info);\n }\n }\n }\n}\nAdding chrome start-up parameters to information passed back in breakpad crash - we collect the first two params : switch-1 and switch-2 - up to 64 chars, then it truncates\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/breakpad_win.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/file_version_info.h\"\n#include \"base\/registry.h\"\n#include \"base\/string_util.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/app\/google_update_client.h\"\n#include \"chrome\/app\/hard_error_handler_win.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"breakpad\/src\/client\/windows\/handler\/exception_handler.h\"\n\nnamespace {\n\nconst wchar_t kGoogleUpdatePipeName[] = L\"\\\\\\\\.\\\\pipe\\\\GoogleCrashServices\\\\\";\nconst wchar_t kChromePipeName[] = L\"\\\\\\\\.\\\\pipe\\\\ChromeCrashServices\";\n\n\/\/ This is the well known SID for the system principal.\nconst wchar_t kSystemPrincipalSid[] =L\"S-1-5-18\";\n\ngoogle_breakpad::ExceptionHandler* g_breakpad = NULL;\n\nstd::vector* g_url_chunks = NULL;\n\n\/\/ Dumps the current process memory.\nextern \"C\" void __declspec(dllexport) __cdecl DumpProcess() {\n if (g_breakpad)\n g_breakpad->WriteMinidump();\n}\n\n\/\/ Reduces the size of the string |str| to a max of 64 chars. Required because\n\/\/ breakpad's CustomInfoEntry raises an invalid_parameter error if the string\n\/\/ we want to set is longer.\nstd::wstring TrimToBreakpadMax(const std::wstring& str) {\n std::wstring shorter(str);\n return shorter.substr(0,\n google_breakpad::CustomInfoEntry::kValueMaxLength - 1);\n}\n\n\/\/ Returns the custom info structure based on the dll in parameter and the\n\/\/ process type.\nstatic google_breakpad::CustomClientInfo* custom_info = NULL;\ngoogle_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& dll_path,\n const std::wstring& type) {\n scoped_ptr\n version_info(FileVersionInfo::CreateFileVersionInfo(dll_path));\n\n std::wstring version, product;\n if (version_info.get()) {\n \/\/ Get the information from the file.\n product = version_info->product_short_name();\n version = version_info->product_version();\n if (!version_info->is_official_build())\n version.append(L\"-devel\");\n } else {\n \/\/ No version info found. Make up the values.\n product = L\"Chrome\";\n version = L\"0.0.0.0-devel\";\n }\n\n \/\/ Common entries.\n google_breakpad::CustomInfoEntry ver_entry(L\"ver\", version.c_str());\n google_breakpad::CustomInfoEntry prod_entry(L\"prod\", product.c_str());\n google_breakpad::CustomInfoEntry plat_entry(L\"plat\", L\"Win32\");\n google_breakpad::CustomInfoEntry type_entry(L\"ptype\", type.c_str());\n\n if (type == L\"renderer\") {\n \/\/ If we're a renderer create entries for the URL. Currently we only allow\n \/\/ each chunk to be 64 characters, which isn't enough for a URL. As a hack\n \/\/ we create 8 entries and split the URL across the entries.\n google_breakpad::CustomInfoEntry url1(L\"url-chunk-1\", L\"\");\n google_breakpad::CustomInfoEntry url2(L\"url-chunk-2\", L\"\");\n google_breakpad::CustomInfoEntry url3(L\"url-chunk-3\", L\"\");\n google_breakpad::CustomInfoEntry url4(L\"url-chunk-4\", L\"\");\n google_breakpad::CustomInfoEntry url5(L\"url-chunk-5\", L\"\");\n google_breakpad::CustomInfoEntry url6(L\"url-chunk-6\", L\"\");\n google_breakpad::CustomInfoEntry url7(L\"url-chunk-7\", L\"\");\n google_breakpad::CustomInfoEntry url8(L\"url-chunk-8\", L\"\");\n\n static google_breakpad::CustomInfoEntry entries[] =\n { ver_entry, prod_entry, plat_entry, type_entry,\n url1, url2, url3, url4, url5, url6, url7, url8 };\n\n std::vector* tmp_url_chunks = new std::vector(8);\n for (size_t i = 0; i < 8; ++i)\n (*tmp_url_chunks)[i] = entries[4 + i].value;\n g_url_chunks = tmp_url_chunks;\n\n static google_breakpad::CustomClientInfo custom_info_renderer\n = {entries, arraysize(entries)};\n return &custom_info_renderer;\n }\n\n \/\/ Browser-specific entries.\n google_breakpad::CustomInfoEntry switch1(L\"switch-1\", L\"\");\n google_breakpad::CustomInfoEntry switch2(L\"switch-2\", L\"\");\n\n \/\/ Get the first two command line switches if they exist. The CommandLine\n \/\/ class does not allow to enumerate the switches so we do it by hand.\n int num_args = 0;\n wchar_t** args = ::CommandLineToArgvW(::GetCommandLineW(), &num_args);\n if (args) {\n if (num_args > 1)\n switch1.set_value(TrimToBreakpadMax(args[1]).c_str());\n if (num_args > 2)\n switch2.set_value(TrimToBreakpadMax(args[2]).c_str());\n }\n\n static google_breakpad::CustomInfoEntry entries[] =\n {ver_entry, prod_entry, plat_entry, type_entry, switch1, switch2};\n static google_breakpad::CustomClientInfo custom_info_browser =\n {entries, arraysize(entries)};\n return &custom_info_browser;\n}\n\n\/\/ Contains the information needed by the worker thread.\nstruct CrashReporterInfo {\n google_breakpad::CustomClientInfo* custom_info;\n std::wstring dll_path;\n std::wstring process_type;\n};\n\n\/\/ This callback is executed when the browser process has crashed, after\n\/\/ the crash dump has been created. We need to minimize the amount of work\n\/\/ done here since we have potentially corrupted process. Our job is to\n\/\/ spawn another instance of chrome which will show a 'chrome has crashed'\n\/\/ dialog. This code needs to live in the exe and thus has no access to\n\/\/ facilities such as the i18n helpers.\nbool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,\n EXCEPTION_POINTERS* ex_info,\n MDRawAssertionInfo*, bool) {\n \/\/ If the exception is because there was a problem loading a delay-loaded\n \/\/ module, then show the user a dialog explaining the problem and then exit.\n if (DelayLoadFailureExceptionMessageBox(ex_info))\n return true;\n\n \/\/ We set CHROME_CRASHED env var. If the CHROME_RESTART is present.\n \/\/ This signals the child process to show the 'chrome has crashed' dialog.\n if (!::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0))\n return true;\n ::SetEnvironmentVariableW(env_vars::kShowRestart, L\"1\");\n \/\/ Now we just start chrome browser with the same command line.\n STARTUPINFOW si = {sizeof(si)};\n PROCESS_INFORMATION pi;\n if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,\n CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {\n ::CloseHandle(pi.hProcess);\n ::CloseHandle(pi.hThread);\n }\n \/\/ After this return we will be terminated. The actual return value is\n \/\/ not used at all.\n return true;\n}\n\n\/\/ Previous unhandled filter. Will be called if not null when we\n\/\/ intercept a crash.\nLPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;\n\n\/\/ Exception filter used when breakpad is not enabled. We just display\n\/\/ the \"Do you want to restart\" message and then we call the previous filter.\nlong WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {\n DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);\n\n if (previous_filter)\n return previous_filter(info);\n\n return EXCEPTION_EXECUTE_HANDLER;\n}\n\nextern \"C\" void __declspec(dllexport) __cdecl SetActiveRendererURL(\n const wchar_t* url_cstring) {\n DCHECK(url_cstring);\n if (!g_url_chunks)\n return;\n\n std::wstring url(url_cstring);\n size_t num_chunks = g_url_chunks->size();\n size_t chunk_index = 0;\n size_t url_size = url.size();\n\n \/\/ Split the url across all the chunks.\n for (size_t url_offset = 0;\n chunk_index < num_chunks && url_offset < url_size; ++chunk_index) {\n size_t current_chunk_size = std::min(url_size - url_offset,\n static_cast(\n google_breakpad::CustomInfoEntry::kValueMaxLength - 1));\n url._Copy_s((*g_url_chunks)[chunk_index],\n google_breakpad::CustomInfoEntry::kValueMaxLength,\n current_chunk_size, url_offset);\n (*g_url_chunks)[chunk_index][current_chunk_size] = L'\\0';\n url_offset += current_chunk_size;\n }\n\n \/\/ And null terminate any unneeded chunks.\n for (; chunk_index < num_chunks; ++chunk_index)\n (*g_url_chunks)[chunk_index][0] = L'\\0';\n}\n\n} \/\/ namespace\n\n\/\/ This function is executed by the child process that DumpDoneCallback()\n\/\/ spawned and basically just shows the 'chrome has crashed' dialog if\n\/\/ the CHROME_CRASHED environment variable is present.\nbool ShowRestartDialogIfCrashed(bool* exit_now) {\n if (!::GetEnvironmentVariableW(env_vars::kShowRestart, NULL, 0))\n return false;\n\n DWORD len = ::GetEnvironmentVariableW(env_vars::kRestartInfo, NULL, 0);\n if (!len)\n return true;\n\n \/\/ We wrap the call to MessageBoxW with a SEH handler because it some\n \/\/ machines with CursorXP, PeaDict or with FontExplorer installed it crashes\n \/\/ uncontrollably here. Being this a best effort deal we better go away.\n#pragma warning(push)\n#pragma warning(disable:4509) \/\/ warning: SEH used but dlg_strings has a dtor.\n __try {\n wchar_t* restart_data = new wchar_t[len + 1];\n ::GetEnvironmentVariableW(env_vars::kRestartInfo, restart_data, len);\n restart_data[len] = 0;\n \/\/ The CHROME_RESTART var contains the dialog strings separated by '|'.\n \/\/ See PrepareRestartOnCrashEnviroment() function for details.\n std::vector dlg_strings;\n SplitString(restart_data, L'|', &dlg_strings);\n delete[] restart_data;\n if (dlg_strings.size() < 3)\n return true;\n\n \/\/ If the UI layout is right-to-left, we need to pass the appropriate MB_XXX\n \/\/ flags so that an RTL message box is displayed.\n UINT flags = MB_OKCANCEL | MB_ICONWARNING;\n if (dlg_strings[2] == env_vars::kRtlLocale)\n flags |= MB_RIGHT | MB_RTLREADING;\n\n \/\/ Show the dialog now. It is ok if another chrome is started by the\n \/\/ user since we have not initialized the databases.\n *exit_now = (IDOK != ::MessageBoxW(NULL, dlg_strings[1].c_str(),\n dlg_strings[0].c_str(), flags));\n } __except(EXCEPTION_EXECUTE_HANDLER) {\n \/\/ Its not safe to continue executing, exit silently here.\n ::ExitProcess(ResultCodes::RESPAWN_FAILED);\n }\n#pragma warning(pop)\n return true;\n}\n\nstatic DWORD __stdcall InitCrashReporterThread(void* param) {\n CrashReporterInfo* info = reinterpret_cast(param);\n\n \/\/ GetCustomInfo can take a few milliseconds to get the file information, so\n \/\/ we do it here so it can run in a separate thread.\n info->custom_info = GetCustomInfo(info->dll_path, info->process_type);\n\n const CommandLine& command = *CommandLine::ForCurrentProcess();\n bool full_dump = command.HasSwitch(switches::kFullMemoryCrashReport);\n bool use_crash_service = command.HasSwitch(switches::kNoErrorDialogs) ||\n GetEnvironmentVariable(L\"CHROME_HEADLESS\", NULL, 0);\n\n google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;\n\n if (info->process_type == L\"browser\") {\n \/\/ We install the post-dump callback only for the browser process. It\n \/\/ spawns a new browser process.\n callback = &DumpDoneCallback;\n }\n\n std::wstring pipe_name;\n if (use_crash_service) {\n \/\/ Crash reporting is done by crash_service.exe.\n pipe_name = kChromePipeName;\n } else {\n \/\/ We want to use the Google Update crash reporting. We need to check if the\n \/\/ user allows it first.\n if (!GoogleUpdateSettings::GetCollectStatsConsent()) {\n \/\/ The user did not allow Google Update to send crashes, we need to use\n \/\/ our default crash handler instead, but only for the browser process.\n if (callback)\n InitDefaultCrashCallback();\n return 0;\n }\n\n \/\/ Build the pipe name. It can be either:\n \/\/ System-wide install: \"NamedPipe\\GoogleCrashServices\\S-1-5-18\"\n \/\/ Per-user install: \"NamedPipe\\GoogleCrashServices\\\"\n std::wstring user_sid;\n if (InstallUtil::IsPerUserInstall(info->dll_path.c_str())) {\n if (!win_util::GetUserSidString(&user_sid)) {\n delete info;\n return -1;\n }\n } else {\n user_sid = kSystemPrincipalSid;\n }\n\n pipe_name = kGoogleUpdatePipeName;\n pipe_name += user_sid;\n }\n\n \/\/ Get the alternate dump directory. We use the temp path.\n wchar_t temp_dir[MAX_PATH] = {0};\n ::GetTempPathW(MAX_PATH, temp_dir);\n\n MINIDUMP_TYPE dump_type = full_dump ? MiniDumpWithFullMemory : MiniDumpNormal;\n\n g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, NULL, callback,\n NULL, google_breakpad::ExceptionHandler::HANDLER_ALL,\n dump_type, pipe_name.c_str(), info->custom_info);\n\n if (!g_breakpad->IsOutOfProcess()) {\n \/\/ The out-of-process handler is unavailable.\n ::SetEnvironmentVariable(env_vars::kNoOOBreakpad,\n info->process_type.c_str());\n } else {\n \/\/ Tells breakpad to handle breakpoint and single step exceptions.\n \/\/ This might break JIT debuggers, but at least it will always\n \/\/ generate a crashdump for these exceptions.\n g_breakpad->set_handle_debug_exceptions(true);\n }\n\n delete info;\n return 0;\n}\n\nvoid InitDefaultCrashCallback() {\n previous_filter = SetUnhandledExceptionFilter(ChromeExceptionFilter);\n}\n\nvoid InitCrashReporterWithDllPath(const std::wstring& dll_path) {\n const CommandLine& command = *CommandLine::ForCurrentProcess();\n if (!command.HasSwitch(switches::kDisableBreakpad)) {\n \/\/ Disable the message box for assertions.\n _CrtSetReportMode(_CRT_ASSERT, 0);\n\n \/\/ Query the custom_info now because if we do it in the thread it's going to\n \/\/ fail in the sandbox. The thread will delete this object.\n CrashReporterInfo* info = new CrashReporterInfo;\n info->process_type = command.GetSwitchValue(switches::kProcessType);\n if (info->process_type.empty())\n info->process_type = L\"browser\";\n\n info->dll_path = dll_path;\n\n \/\/ If this is not the browser, we can't be sure that we will be able to\n \/\/ initialize the crash_handler in another thread, so we run it right away.\n \/\/ This is important to keep the thread for the browser process because\n \/\/ it may take some times to initialize the crash_service process. We use\n \/\/ the Windows worker pool to make better reuse of the thread.\n if (info->process_type != L\"browser\") {\n InitCrashReporterThread(info);\n } else {\n if (QueueUserWorkItem(\n &InitCrashReporterThread, info, WT_EXECUTELONGFUNCTION) == 0) {\n \/\/ We failed to queue to the worker pool, initialize in this thread.\n InitCrashReporterThread(info);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n* File: vcs.cpp\n* Purpose: Implementation of wxExVCS class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nwxExVCS* wxExVCS::m_Self = NULL;\n#if wxUSE_GUI\nwxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;\n#endif\n\nwxExVCS::wxExVCS()\n : m_Command(VCS_NO_COMMAND)\n , m_FileName(wxExFileName())\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(int command_id, const wxExFileName& filename)\n : m_Command(GetType(command_id))\n , m_FileName(filename)\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename)\n : m_Command(type)\n , m_FileName(filename)\n{\n Initialize();\n}\n\n#if wxUSE_GUI\nint wxExVCS::ConfigDialog(\n wxWindow* parent,\n const wxString& title) const\n{\n std::vector v;\n\n std::map choices;\n choices.insert(std::make_pair(VCS_NONE, _(\"None\")));\n choices.insert(std::make_pair(VCS_GIT, \"GIT\"));\n choices.insert(std::make_pair(VCS_SVN, \"SVN\"));\n v.push_back(wxExConfigItem(\"VCS\", choices));\n\n v.push_back(wxExConfigItem(\"GIT\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(\"SVN\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(_(\"Comparator\"), CONFIG_FILEPICKERCTRL));\n\n return wxExConfigDialog(parent, v, title).ShowModal();\n}\n#endif\n\nbool wxExVCS::DirExists(const wxFileName& filename) const\n{\n switch (GetVCS())\n {\n case VCS_GIT: \n {\n \/\/ The .git dir only exists in the root, so check all components.\n wxFileName root(filename.GetPath());\n\n while (root.DirExists() && root.GetDirCount() > 0)\n {\n wxFileName path(root);\n path.AppendDir(\".git\");\n\n if (path.DirExists())\n {\n return true;\n }\n\n root.RemoveLastDir();\n }\n }\n break;\n\n case VCS_NONE: break; \/\/ prevent wxFAIL\n \n case VCS_SVN: \n {\n \/\/ these cannot be combined, as AppendDir is a void (2.9.1).\n wxFileName path(filename);\n path.AppendDir(\".svn\");\n return path.DirExists();\n }\n break;\n\n default: wxFAIL;\n }\n\n return false;\n}\n\nlong wxExVCS::Execute()\n{\n wxASSERT(m_Command != VCS_NO_COMMAND);\n\n wxString cwd;\n wxString file;\n\n if (!m_FileName.IsOk())\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(wxExConfigFirstOf(_(\"Base folder\")));\n\n if (m_Command == VCS_ADD)\n {\n file = \" \" + wxExConfigFirstOf(_(\"Path\"));\n }\n }\n else\n {\n if (GetVCS() == VCS_GIT)\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(m_FileName.GetPath());\n file = \" \\\"\" + m_FileName.GetFullName() + \"\\\"\";\n }\n else\n {\n file = \" \\\"\" + m_FileName.GetFullPath() + \"\\\"\";\n }\n }\n\n wxString comment;\n\n if (m_Command == VCS_COMMIT)\n {\n comment = \n \" -m \\\"\" + wxExConfigFirstOf(_(\"Revision comment\")) + \"\\\"\";\n }\n\n wxString subcommand;\n \n if (UseSubcommand())\n {\n subcommand = wxConfigBase::Get()->Read(_(\"Subcommand\"));\n\n if (!subcommand.empty())\n {\n subcommand = \" \" + subcommand;\n }\n }\n\n wxString flags;\n\n if (UseFlags())\n {\n flags = wxConfigBase::Get()->Read(_(\"Flags\"));\n\n if (!flags.empty())\n {\n flags = \" \" + flags;\n }\n }\n\n m_CommandWithFlags = m_CommandString + flags;\n\n wxString vcs_bin;\n\n switch (GetVCS())\n {\n case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read(\"GIT\", \"git\"); break;\n case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read(\"SVN\", \"svn\"); break;\n default: wxFAIL;\n }\n\n if (vcs_bin.empty())\n {\n wxLogError(GetVCSName() + \" \" + _(\"path is empty\"));\n return -1;\n }\n\n const wxString commandline = \n vcs_bin + \" \" + m_CommandString + subcommand + flags + comment + file;\n\n#if wxUSE_STATUSBAR\n wxExFrame::StatusText(commandline);\n#endif\n\n wxArrayString output;\n wxArrayString errors;\n long retValue;\n\n if ((retValue = wxExecute(\n commandline,\n output,\n errors)) == -1)\n {\n \/\/ See also process, same log is shown.\n wxLogError(_(\"Cannot execute\") + \": \" + commandline);\n }\n else\n {\n wxExLog::Get()->Log(commandline);\n }\n\n if (!cwd.empty())\n {\n wxSetWorkingDirectory(cwd);\n }\n\n m_Output.clear();\n\n \/\/ First output the errors.\n for (\n size_t i = 0;\n i < errors.GetCount();\n i++)\n {\n m_Output += errors[i] + \"\\n\";\n }\n\n \/\/ Then the normal output, will be empty if there are errors.\n for (\n size_t j = 0;\n j < output.GetCount();\n j++)\n {\n m_Output += output[j] + \"\\n\";\n }\n\n return retValue;\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)\n{\n if (ShowDialog(parent) == wxID_CANCEL)\n {\n return wxID_CANCEL;\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(m_FlagsKey, \n wxConfigBase::Get()->Read(_(\"Flags\")));\n }\n\n const auto retValue = Execute();\n \n return (retValue != -1 ? wxID_OK: wxID_CANCEL);\n}\n#endif\n\nwxExVCS* wxExVCS::Get(bool createOnDemand)\n{\n if (m_Self == NULL && createOnDemand)\n {\n m_Self = new wxExVCS;\n\n \/\/ Add default VCS.\n if (!wxConfigBase::Get()->Exists(\"VCS\"))\n {\n \/\/ TODO: Add SVN only if svn bin exists on linux.\n wxConfigBase::Get()->Write(\"VCS\", (long)VCS_SVN);\n }\n }\n\n return m_Self;\n}\n\nwxExVCS::wxExCommand wxExVCS::GetType(int command_id) const\n{\n if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_VCS_LOWEST);\n }\n else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST);\n }\n else\n {\n wxFAIL;\n return VCS_NO_COMMAND;\n }\n}\n\nlong wxExVCS::GetVCS() const\n{\n return wxConfigBase::Get()->ReadLong(\"VCS\", VCS_SVN);\n}\n\nconst wxString wxExVCS::GetVCSName() const\n{\n wxString text;\n\n switch (GetVCS())\n {\n case VCS_GIT: text = \"GIT\"; break;\n case VCS_SVN: text = \"SVN\"; break;\n default: wxFAIL;\n }\n\n return text;\n}\n\nvoid wxExVCS::Initialize()\n{\n if (Use() && m_Command != VCS_NO_COMMAND)\n {\n switch (GetVCS())\n {\n case VCS_GIT:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: break;\n case VCS_PROPLIST: break;\n case VCS_PROPSET: break;\n case VCS_PUSH: m_CommandString = \"push\"; break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: m_CommandString = \"show\"; break;\n case VCS_STAT: m_CommandString = \"status\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n case VCS_SVN:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: m_CommandString = \"cat\"; break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: m_CommandString = \"info\"; break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: m_CommandString = \"ls\"; break;\n case VCS_PROPLIST: m_CommandString = \"proplist\"; break;\n case VCS_PROPSET: m_CommandString = \"propset\"; break;\n case VCS_PUSH: break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: break;\n case VCS_STAT: m_CommandString = \"stat\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n default: wxFAIL;\n }\n\n m_Caption = GetVCSName() + \" \" + m_CommandString;\n\n \/\/ Currently no flags, as no command was executed.\n m_CommandWithFlags = m_CommandString;\n\n \/\/ Use general key.\n m_FlagsKey = wxString::Format(\"cvsflags\/name%d\", m_Command);\n }\n\n m_Output.clear();\n}\n\nbool wxExVCS::IsOpenCommand() const\n{\n return \n m_Command == wxExVCS::VCS_BLAME ||\n m_Command == wxExVCS::VCS_CAT ||\n m_Command == wxExVCS::VCS_DIFF;\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::Request(wxWindow* parent)\n{\n wxStandardID retValue;\n\n if ((retValue = ExecuteDialog(parent)) == wxID_OK)\n {\n ShowOutput(parent);\n }\n\n return retValue;\n}\n#endif\n\nwxExVCS* wxExVCS::Set(wxExVCS* vcs)\n{\n wxExVCS* old = m_Self;\n m_Self = vcs;\n return old;\n}\n\n#if wxUSE_GUI\nint wxExVCS::ShowDialog(wxWindow* parent)\n{\n std::vector v;\n\n if (m_Command == VCS_COMMIT)\n {\n v.push_back(wxExConfigItem(\n _(\"Revision comment\"), \n CONFIG_COMBOBOX,\n wxEmptyString,\n true)); \/\/ required\n }\n\n if (!m_FileName.IsOk() && m_Command != VCS_HELP)\n {\n v.push_back(wxExConfigItem(\n _(\"Base folder\"), \n CONFIG_COMBOBOXDIR, \n wxEmptyString, \n true,\n 1000));\n\n if (m_Command == VCS_ADD)\n {\n v.push_back(wxExConfigItem(\n _(\"Path\"), \n CONFIG_COMBOBOX,\n wxEmptyString, \n true)); \/\/ required\n }\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(\n _(\"Flags\"), \n wxConfigBase::Get()->Read(m_FlagsKey));\n\n v.push_back(wxExConfigItem(_(\"Flags\")));\n }\n\n if (UseSubcommand())\n {\n v.push_back(wxExConfigItem(_(\"Subcommand\")));\n }\n\n return wxExConfigDialog(parent,\n v,\n m_Caption).ShowModal();\n}\n#endif\n\n#if wxUSE_GUI\nvoid wxExVCS::ShowOutput(wxWindow* parent) const\n{\n wxString caption = m_Caption;\n \n if (m_Command != VCS_HELP)\n {\n caption += \" \" + (m_FileName.IsOk() ? \n m_FileName.GetFullName(): \n wxExConfigFirstOf(_(\"Base folder\")));\n }\n\n \/\/ Create a dialog for contents.\n if (m_STCEntryDialog == NULL)\n {\n m_STCEntryDialog = new wxExSTCEntryDialog(\n parent,\n caption,\n m_Output,\n wxEmptyString,\n wxOK,\n wxID_ANY,\n wxDefaultPosition,\n wxSize(350, 50));\n }\n else\n {\n m_STCEntryDialog->SetText(m_Output);\n m_STCEntryDialog->SetTitle(caption);\n }\n\n \/\/ Add a lexer when appropriate.\n if (m_Command == VCS_CAT || m_Command == VCS_BLAME)\n {\n if (m_FileName.GetLexer().IsOk())\n {\n m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer());\n }\n }\n else if (m_Command == VCS_DIFF)\n {\n m_STCEntryDialog->SetLexer(\"diff\");\n }\n else\n {\n m_STCEntryDialog->SetLexer(wxEmptyString);\n }\n\n m_STCEntryDialog->Show();\n}\n#endif\n\nbool wxExVCS::Use() const\n{\n return GetVCS() != VCS_NONE;\n}\n\nbool wxExVCS::UseFlags() const\n{\n return m_Command != VCS_UPDATE && m_Command != VCS_HELP;\n}\n\nbool wxExVCS::UseSubcommand() const\n{\n return m_Command == VCS_HELP;\n}\nif help flag is specified do not add file argument\/******************************************************************************\\\n* File: vcs.cpp\n* Purpose: Implementation of wxExVCS class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nwxExVCS* wxExVCS::m_Self = NULL;\n#if wxUSE_GUI\nwxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;\n#endif\n\nwxExVCS::wxExVCS()\n : m_Command(VCS_NO_COMMAND)\n , m_FileName(wxExFileName())\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(int command_id, const wxExFileName& filename)\n : m_Command(GetType(command_id))\n , m_FileName(filename)\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename)\n : m_Command(type)\n , m_FileName(filename)\n{\n Initialize();\n}\n\n#if wxUSE_GUI\nint wxExVCS::ConfigDialog(\n wxWindow* parent,\n const wxString& title) const\n{\n std::vector v;\n\n std::map choices;\n choices.insert(std::make_pair(VCS_NONE, _(\"None\")));\n choices.insert(std::make_pair(VCS_GIT, \"GIT\"));\n choices.insert(std::make_pair(VCS_SVN, \"SVN\"));\n v.push_back(wxExConfigItem(\"VCS\", choices));\n\n v.push_back(wxExConfigItem(\"GIT\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(\"SVN\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(_(\"Comparator\"), CONFIG_FILEPICKERCTRL));\n\n return wxExConfigDialog(parent, v, title).ShowModal();\n}\n#endif\n\nbool wxExVCS::DirExists(const wxFileName& filename) const\n{\n switch (GetVCS())\n {\n case VCS_GIT: \n {\n \/\/ The .git dir only exists in the root, so check all components.\n wxFileName root(filename.GetPath());\n\n while (root.DirExists() && root.GetDirCount() > 0)\n {\n wxFileName path(root);\n path.AppendDir(\".git\");\n\n if (path.DirExists())\n {\n return true;\n }\n\n root.RemoveLastDir();\n }\n }\n break;\n\n case VCS_NONE: break; \/\/ prevent wxFAIL\n \n case VCS_SVN: \n {\n \/\/ these cannot be combined, as AppendDir is a void (2.9.1).\n wxFileName path(filename);\n path.AppendDir(\".svn\");\n return path.DirExists();\n }\n break;\n\n default: wxFAIL;\n }\n\n return false;\n}\n\nlong wxExVCS::Execute()\n{\n wxASSERT(m_Command != VCS_NO_COMMAND);\n\n wxString cwd;\n wxString file;\n\n if (!m_FileName.IsOk())\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(wxExConfigFirstOf(_(\"Base folder\")));\n\n if (m_Command == VCS_ADD)\n {\n file = \" \" + wxExConfigFirstOf(_(\"Path\"));\n }\n }\n else\n {\n if (GetVCS() == VCS_GIT)\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(m_FileName.GetPath());\n file = \" \\\"\" + m_FileName.GetFullName() + \"\\\"\";\n }\n else\n {\n file = \" \\\"\" + m_FileName.GetFullPath() + \"\\\"\";\n }\n }\n\n wxString comment;\n\n if (m_Command == VCS_COMMIT)\n {\n comment = \n \" -m \\\"\" + wxExConfigFirstOf(_(\"Revision comment\")) + \"\\\"\";\n }\n\n wxString subcommand;\n \n if (UseSubcommand())\n {\n subcommand = wxConfigBase::Get()->Read(_(\"Subcommand\"));\n\n if (!subcommand.empty())\n {\n subcommand = \" \" + subcommand;\n }\n }\n\n wxString flags;\n\n if (UseFlags())\n {\n flags = wxConfigBase::Get()->Read(_(\"Flags\"));\n\n if (!flags.empty())\n {\n flags = \" \" + flags;\n\n \/\/ If we specified help flags, we do not need a file argument. \n if (flags.Contains(\"help\"))\n {\n file.clear();\n }\n }\n }\n\n m_CommandWithFlags = m_CommandString + flags;\n\n wxString vcs_bin;\n\n switch (GetVCS())\n {\n case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read(\"GIT\", \"git\"); break;\n case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read(\"SVN\", \"svn\"); break;\n default: wxFAIL;\n }\n\n if (vcs_bin.empty())\n {\n wxLogError(GetVCSName() + \" \" + _(\"path is empty\"));\n return -1;\n }\n\n const wxString commandline = \n vcs_bin + \" \" + m_CommandString + subcommand + flags + comment + file;\n\n#if wxUSE_STATUSBAR\n wxExFrame::StatusText(commandline);\n#endif\n\n wxArrayString output;\n wxArrayString errors;\n long retValue;\n\n \/\/ Call wxExcute to execute the cvs command and\n \/\/ collect the output and the errors.\n if ((retValue = wxExecute(\n commandline,\n output,\n errors)) == -1)\n {\n \/\/ See also process, same log is shown.\n wxLogError(_(\"Cannot execute\") + \": \" + commandline);\n }\n else\n {\n wxExLog::Get()->Log(commandline);\n }\n\n if (!cwd.empty())\n {\n wxSetWorkingDirectory(cwd);\n }\n\n m_Output.clear();\n\n \/\/ First output the errors.\n for (\n size_t i = 0;\n i < errors.GetCount();\n i++)\n {\n m_Output += errors[i] + \"\\n\";\n }\n\n \/\/ Then the normal output, will be empty if there are errors.\n for (\n size_t j = 0;\n j < output.GetCount();\n j++)\n {\n m_Output += output[j] + \"\\n\";\n }\n\n return retValue;\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)\n{\n if (ShowDialog(parent) == wxID_CANCEL)\n {\n return wxID_CANCEL;\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(m_FlagsKey, \n wxConfigBase::Get()->Read(_(\"Flags\")));\n }\n\n const auto retValue = Execute();\n \n return (retValue != -1 ? wxID_OK: wxID_CANCEL);\n}\n#endif\n\nwxExVCS* wxExVCS::Get(bool createOnDemand)\n{\n if (m_Self == NULL && createOnDemand)\n {\n m_Self = new wxExVCS;\n\n \/\/ Add default VCS.\n if (!wxConfigBase::Get()->Exists(\"VCS\"))\n {\n \/\/ TODO: Add SVN only if svn bin exists on linux.\n wxConfigBase::Get()->Write(\"VCS\", (long)VCS_SVN);\n }\n }\n\n return m_Self;\n}\n\nwxExVCS::wxExCommand wxExVCS::GetType(int command_id) const\n{\n if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_VCS_LOWEST);\n }\n else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST);\n }\n else\n {\n wxFAIL;\n return VCS_NO_COMMAND;\n }\n}\n\nlong wxExVCS::GetVCS() const\n{\n return wxConfigBase::Get()->ReadLong(\"VCS\", VCS_SVN);\n}\n\nconst wxString wxExVCS::GetVCSName() const\n{\n wxString text;\n\n switch (GetVCS())\n {\n case VCS_GIT: text = \"GIT\"; break;\n case VCS_SVN: text = \"SVN\"; break;\n default: wxFAIL;\n }\n\n return text;\n}\n\nvoid wxExVCS::Initialize()\n{\n if (Use() && m_Command != VCS_NO_COMMAND)\n {\n switch (GetVCS())\n {\n case VCS_GIT:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: break;\n case VCS_PROPLIST: break;\n case VCS_PROPSET: break;\n case VCS_PUSH: m_CommandString = \"push\"; break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: m_CommandString = \"show\"; break;\n case VCS_STAT: m_CommandString = \"status\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n case VCS_SVN:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: m_CommandString = \"cat\"; break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: m_CommandString = \"info\"; break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: m_CommandString = \"ls\"; break;\n case VCS_PROPLIST: m_CommandString = \"proplist\"; break;\n case VCS_PROPSET: m_CommandString = \"propset\"; break;\n case VCS_PUSH: break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: break;\n case VCS_STAT: m_CommandString = \"stat\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n default: wxFAIL;\n }\n\n m_Caption = GetVCSName() + \" \" + m_CommandString;\n\n \/\/ Currently no flags, as no command was executed.\n m_CommandWithFlags = m_CommandString;\n\n \/\/ Use general key.\n m_FlagsKey = wxString::Format(\"cvsflags\/name%d\", m_Command);\n }\n\n m_Output.clear();\n}\n\nbool wxExVCS::IsOpenCommand() const\n{\n return \n m_Command == wxExVCS::VCS_BLAME ||\n m_Command == wxExVCS::VCS_CAT ||\n m_Command == wxExVCS::VCS_DIFF;\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::Request(wxWindow* parent)\n{\n wxStandardID retValue;\n\n if ((retValue = ExecuteDialog(parent)) == wxID_OK)\n {\n ShowOutput(parent);\n }\n\n return retValue;\n}\n#endif\n\nwxExVCS* wxExVCS::Set(wxExVCS* vcs)\n{\n wxExVCS* old = m_Self;\n m_Self = vcs;\n return old;\n}\n\n#if wxUSE_GUI\nint wxExVCS::ShowDialog(wxWindow* parent)\n{\n std::vector v;\n\n if (m_Command == VCS_COMMIT)\n {\n v.push_back(wxExConfigItem(\n _(\"Revision comment\"), \n CONFIG_COMBOBOX,\n wxEmptyString,\n true)); \/\/ required\n }\n\n if (!m_FileName.IsOk() && m_Command != VCS_HELP)\n {\n v.push_back(wxExConfigItem(\n _(\"Base folder\"), \n CONFIG_COMBOBOXDIR, \n wxEmptyString, \n true,\n 1000));\n\n if (m_Command == VCS_ADD)\n {\n v.push_back(wxExConfigItem(\n _(\"Path\"), \n CONFIG_COMBOBOX,\n wxEmptyString, \n true)); \/\/ required\n }\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(\n _(\"Flags\"), \n wxConfigBase::Get()->Read(m_FlagsKey));\n\n v.push_back(wxExConfigItem(_(\"Flags\")));\n }\n\n if (UseSubcommand())\n {\n v.push_back(wxExConfigItem(_(\"Subcommand\")));\n }\n\n return wxExConfigDialog(parent,\n v,\n m_Caption).ShowModal();\n}\n#endif\n\n#if wxUSE_GUI\nvoid wxExVCS::ShowOutput(wxWindow* parent) const\n{\n wxString caption = m_Caption;\n \n if (m_Command != VCS_HELP)\n {\n caption += \" \" + (m_FileName.IsOk() ? \n m_FileName.GetFullName(): \n wxExConfigFirstOf(_(\"Base folder\")));\n }\n\n \/\/ Create a dialog for contents.\n if (m_STCEntryDialog == NULL)\n {\n m_STCEntryDialog = new wxExSTCEntryDialog(\n parent,\n caption,\n m_Output,\n wxEmptyString,\n wxOK,\n wxID_ANY,\n wxDefaultPosition,\n wxSize(350, 50));\n }\n else\n {\n m_STCEntryDialog->SetText(m_Output);\n m_STCEntryDialog->SetTitle(caption);\n }\n\n \/\/ Add a lexer when appropriate.\n if (m_Command == VCS_CAT || m_Command == VCS_BLAME)\n {\n if (m_FileName.GetLexer().IsOk())\n {\n m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer());\n }\n }\n else if (m_Command == VCS_DIFF)\n {\n m_STCEntryDialog->SetLexer(\"diff\");\n }\n else\n {\n m_STCEntryDialog->SetLexer(wxEmptyString);\n }\n\n m_STCEntryDialog->Show();\n}\n#endif\n\nbool wxExVCS::Use() const\n{\n return GetVCS() != VCS_NONE;\n}\n\nbool wxExVCS::UseFlags() const\n{\n return m_Command != VCS_UPDATE && m_Command != VCS_HELP;\n}\n\nbool wxExVCS::UseSubcommand() const\n{\n return m_Command == VCS_HELP;\n}\n<|endoftext|>"} {"text":"\/* \/% C %\/ *\/\n\/***********************************************************************\n * cint (C\/C++ interpreter)\n ************************************************************************\n * Source file bc_debug.cxx\n ************************************************************************\n * Description:\n * debugging features\n ************************************************************************\n * Copyright(c) 2004~2004 Masaharu Goto \n *\n * For the licensing terms see the file COPYING\n *\n ************************************************************************\/\n\n#include \"bc_debug.h\"\n\n\/***********************************************************************\n * G__bc_funccall\n ***********************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct G__input_file G__bc_funccall::getifile() const {\n struct G__input_file ifile;\n ifile.str = 0;\n \/\/ ifile.pos = 0;\n ifile.vindex = 0;\n\n if(!m_bytecode) {\n ifile=G__ifile;\n }\n else {\n struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;\n int ifn = m_bytecode->ifn;\n ifile.filenum = ifunc->pentry[ifn]->filenum;\n ifile.fp = G__srcfile[ifile.filenum].fp;\n ifile.line_number = m_line_number;\n strcpy(ifile.name,G__srcfile[ifile.filenum].filename);\n }\n\n return(ifile);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccall::setstackenv(struct G__view* pview) const {\n \/\/ todo, need some review\n pview->file = getifile();\n if(!m_bytecode) {\n pview->var_local = G__p_local;\n pview->struct_offset = G__store_struct_offset;\n pview->tagnum = G__tagnum;\n pview->exec_memberfunc = G__exec_memberfunc;\n pview->localmem = 0;\n return(0);\n }\n else {\n struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;\n \/\/int ifn = m_bytecode->ifn;\n pview->var_local = m_bytecode->var;\n pview->struct_offset = m_struct_offset;\n pview->tagnum = ifunc->tagnum;\n pview->exec_memberfunc=(-1!=ifunc->tagnum)?1:0; \n pview->localmem = m_localmem;\n return(1);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccall::disp(FILE* fout) const {\n \/\/ todo, need some review\n if(!m_bytecode) return(0);\n G__FastAllocString msg(G__LONGLINE);\n struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;\n int ifn = m_bytecode->ifn;\n int tagnum=ifunc->tagnum;\n int filenum = ifunc->pentry[ifn]->filenum;\n struct G__param* libp=m_libp;\n\n \/\/ class name if member function\n if(-1!=tagnum) {\n msg.Format(\"%s::\",G__struct.name[tagnum]);\n if(G__more(fout,msg())) return(1);\n }\n\n \/\/ function name\n msg.Format(\"%s(\",ifunc->funcname[ifn]);\n if(G__more(fout,msg())) return(1);\n\n \/\/ function parameter\n for(int temp1=0;temp1paran;temp1++) {\n if(temp1) {\n msg = \",\";\n if(G__more(fout,msg())) return(1);\n }\n G__valuemonitor(libp->para[temp1],msg);\n if(G__more(fout,msg())) return(1);\n }\n if(-1!=filenum) {\n msg.Format(\") [%s:%d]\\n\" \n\t ,G__stripfilename(G__srcfile[filenum].filename)\n\t ,m_line_number);\n if(G__more(fout,msg())) return(1);\n }\n else {\n if(G__more(fout,\") [entry]\\n\")) return(1);\n }\n\n return(0);\n}\n\n\n\/***********************************************************************\n * G__bc_funccallstack\n ***********************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nG__bc_funccallstack::G__bc_funccallstack() { \n \/\/m_funccallstack.push_front(G__bc_funccall()); \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nG__bc_funccallstack::~G__bc_funccallstack() { \n \/\/ do nothing\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nG__bc_funccall& G__bc_funccallstack::getStackPosition(int i) {\n if(0==m_funccallstack.size()) return(m_staticenv);\n if(i<0 || i>=(int)m_funccallstack.size()) {\n \/\/ error, stack isn't that deep\n G__fprinterr(G__serr,\"!!!Function call stack isn't that deep!!!\\n\");\n return(m_staticenv);\n }\n return(m_funccallstack[i]);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccallstack::setstackenv(int i,struct G__view* pview) {\n return(getStackPosition(i).setstackenv(pview));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccallstack::disp(FILE* fout) const {\n \/\/deque::iterator i;\n G__FastAllocString msg(100);\n for(int i=0;i<(int)m_funccallstack.size();++i) {\n msg.Format(\"%d \",i);\n if(G__more(fout,msg())) return(1);\n if(m_funccallstack[i].disp(fout)) return(1);\n }\n return(0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/***********************************************************************\n * static objects\n ***********************************************************************\/\nG__bc_funccallstack G__bc_funccallstack_obj;\n\n\/***********************************************************************\n * C function wrappers\n ***********************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" int G__bc_setdebugview(int i,struct G__view* pview) {\n return(G__bc_funccallstack_obj.setstackenv(i,pview));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" int G__bc_showstack(FILE* fout) {\n return(G__bc_funccallstack_obj.disp(fout));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" void G__bc_setlinenum(int line) {\n G__bc_funccallstack_obj.setlinenum(line);\n}\n\nMissing member initialization (G__ifile's pos); strcpy (Coverity)\/* \/% C %\/ *\/\n\/***********************************************************************\n * cint (C\/C++ interpreter)\n ************************************************************************\n * Source file bc_debug.cxx\n ************************************************************************\n * Description:\n * debugging features\n ************************************************************************\n * Copyright(c) 2004~2004 Masaharu Goto \n *\n * For the licensing terms see the file COPYING\n *\n ************************************************************************\/\n\n#include \"bc_debug.h\"\n\n\/***********************************************************************\n * G__bc_funccall\n ***********************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct G__input_file G__bc_funccall::getifile() const {\n struct G__input_file ifile;\n ifile.str = 0;\n ifile.pos = 0;\n ifile.vindex = 0;\n\n if(!m_bytecode) {\n ifile=G__ifile;\n }\n else {\n struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;\n int ifn = m_bytecode->ifn;\n ifile.filenum = ifunc->pentry[ifn]->filenum;\n ifile.fp = G__srcfile[ifile.filenum].fp;\n ifile.line_number = m_line_number;\n strncpy(ifile.name,G__srcfile[ifile.filenum].filename, sizeof(ifile.name) - 1);\n }\n\n return(ifile);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccall::setstackenv(struct G__view* pview) const {\n \/\/ todo, need some review\n pview->file = getifile();\n if(!m_bytecode) {\n pview->var_local = G__p_local;\n pview->struct_offset = G__store_struct_offset;\n pview->tagnum = G__tagnum;\n pview->exec_memberfunc = G__exec_memberfunc;\n pview->localmem = 0;\n return(0);\n }\n else {\n struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;\n \/\/int ifn = m_bytecode->ifn;\n pview->var_local = m_bytecode->var;\n pview->struct_offset = m_struct_offset;\n pview->tagnum = ifunc->tagnum;\n pview->exec_memberfunc=(-1!=ifunc->tagnum)?1:0; \n pview->localmem = m_localmem;\n return(1);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccall::disp(FILE* fout) const {\n \/\/ todo, need some review\n if(!m_bytecode) return(0);\n G__FastAllocString msg(G__LONGLINE);\n struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;\n int ifn = m_bytecode->ifn;\n int tagnum=ifunc->tagnum;\n int filenum = ifunc->pentry[ifn]->filenum;\n struct G__param* libp=m_libp;\n\n \/\/ class name if member function\n if(-1!=tagnum) {\n msg.Format(\"%s::\",G__struct.name[tagnum]);\n if(G__more(fout,msg())) return(1);\n }\n\n \/\/ function name\n msg.Format(\"%s(\",ifunc->funcname[ifn]);\n if(G__more(fout,msg())) return(1);\n\n \/\/ function parameter\n for(int temp1=0;temp1paran;temp1++) {\n if(temp1) {\n msg = \",\";\n if(G__more(fout,msg())) return(1);\n }\n G__valuemonitor(libp->para[temp1],msg);\n if(G__more(fout,msg())) return(1);\n }\n if(-1!=filenum) {\n msg.Format(\") [%s:%d]\\n\" \n\t ,G__stripfilename(G__srcfile[filenum].filename)\n\t ,m_line_number);\n if(G__more(fout,msg())) return(1);\n }\n else {\n if(G__more(fout,\") [entry]\\n\")) return(1);\n }\n\n return(0);\n}\n\n\n\/***********************************************************************\n * G__bc_funccallstack\n ***********************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nG__bc_funccallstack::G__bc_funccallstack() { \n \/\/m_funccallstack.push_front(G__bc_funccall()); \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nG__bc_funccallstack::~G__bc_funccallstack() { \n \/\/ do nothing\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nG__bc_funccall& G__bc_funccallstack::getStackPosition(int i) {\n if(0==m_funccallstack.size()) return(m_staticenv);\n if(i<0 || i>=(int)m_funccallstack.size()) {\n \/\/ error, stack isn't that deep\n G__fprinterr(G__serr,\"!!!Function call stack isn't that deep!!!\\n\");\n return(m_staticenv);\n }\n return(m_funccallstack[i]);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccallstack::setstackenv(int i,struct G__view* pview) {\n return(getStackPosition(i).setstackenv(pview));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint G__bc_funccallstack::disp(FILE* fout) const {\n \/\/deque::iterator i;\n G__FastAllocString msg(100);\n for(int i=0;i<(int)m_funccallstack.size();++i) {\n msg.Format(\"%d \",i);\n if(G__more(fout,msg())) return(1);\n if(m_funccallstack[i].disp(fout)) return(1);\n }\n return(0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/***********************************************************************\n * static objects\n ***********************************************************************\/\nG__bc_funccallstack G__bc_funccallstack_obj;\n\n\/***********************************************************************\n * C function wrappers\n ***********************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" int G__bc_setdebugview(int i,struct G__view* pview) {\n return(G__bc_funccallstack_obj.setstackenv(i,pview));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" int G__bc_showstack(FILE* fout) {\n return(G__bc_funccallstack_obj.disp(fout));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" void G__bc_setlinenum(int line) {\n G__bc_funccallstack_obj.setlinenum(line);\n}\n\n<|endoftext|>"} {"text":"\/\/ A JetEvent emulates 2 detectors A and B producing each\n\/\/ a TClonesArray of Hit objects.\n\/\/ A TClonesArray of Track objects is built with Hits objects\n\/\/ of detectors A and B. Eack Track object has a TRefArray of hits.\n\/\/ A TClonesArray of Jets is made with a subset of the Track objects\n\/\/ also stored in a TRefArray.\n\/\/ see $ROOTSYS\/tutorials\/jets.C for an example creating a Tree\n\/\/ with JetEvents.\n \n#include \"TRandom.h\" \n#include \"JetEvent.h\"\n\nClassImp(Jet)\nClassImp(Track)\nClassImp(Hit)\nClassImp(JetEvent)\n\nTClonesArray *JetEvent::fgJets = 0;\nTClonesArray *JetEvent::fgTracks = 0;\nTClonesArray *JetEvent::fgHitsA = 0;\nTClonesArray *JetEvent::fgHitsB = 0;\n\n\/\/______________________________________________________________________________\nJetEvent::JetEvent()\n{\n \/\/ Create a JetEvent object.\n \/\/ When the constructor is invoked for the first time, the class static\n \/\/ variables fgxxx are 0 and the TClonesArray fgxxx are created.\n\n if (!fgTracks) fgTracks = new TClonesArray(\"Track\", 100);\n if (!fgJets) fgJets = new TClonesArray(\"Jet\", 10);\n if (!fgHitsA) fgHitsA = new TClonesArray(\"Hit\", 10000);\n if (!fgHitsB) fgHitsB = new TClonesArray(\"Hit\", 1000);\n fJets = fgJets;\n fTracks = fgTracks;\n fHitsA = fgHitsA;\n fHitsB = fgHitsB;\n}\n\n\/\/______________________________________________________________________________\nJetEvent::~JetEvent()\n{\n Reset();\n}\n\n\/\/______________________________________________________________________________\nvoid JetEvent::Build(Int_t jetm, Int_t trackm, Int_t hitam, Int_t hitbm) {\n \/\/Build one event\n \n \/\/Save current Object count\n Int_t ObjectNumber = TProcessID::GetObjectCount();\n Clear();\n\n Hit *hit;\n Track *track;\n Jet *jet;\n fNjet = fNtrack = fNhitA = fNhitB = 0;\n \n fVertex.SetXYZ(gRandom->Gaus(0,0.1),\n gRandom->Gaus(0,0.2),\n gRandom->Gaus(0,10));\n \n Int_t njets = (Int_t)gRandom->Gaus(jetm,1); if (njets < 1) njets = 1;\n for (Int_t j=0;jfPt = gRandom->Gaus(0,10);\n jet->fPhi = 2*TMath::Pi()*gRandom->Rndm();\n Int_t ntracks = (Int_t)gRandom->Gaus(trackm,3); if (ntracks < 1) ntracks = 1;\n for (Int_t t=0;tfPx = gRandom->Gaus(0,1);\n track->fPy = gRandom->Gaus(0,1);\n track->fPz = gRandom->Gaus(0,5);\n\t jet->fTracks.Add(track);\n Int_t nhitsA = (Int_t)gRandom->Gaus(hitam,5);\n for (Int_t ha=0;hafX = 10000*j + 100*t +ha;\n hit->fY = 10000*j + 100*t +ha+0.1;\n hit->fZ = 10000*j + 100*t +ha+0.2;\n\t track->fHits.Add(hit);\n }\n Int_t nhitsB = (Int_t)gRandom->Gaus(hitbm,2);\n for (Int_t hb=0;hbfX = 20000*j + 100*t +hb+0.3;\n hit->fY = 20000*j + 100*t +hb+0.4;\n hit->fZ = 20000*j + 100*t +hb+0.5;\n\t track->fHits.Add(hit);\n }\n track->fNhit = nhitsA + nhitsB;\n }\n } \n \/\/Restore Object count \n \/\/To save space in the table keeping track of all referenced objects\n \/\/we assume that our events do not address each other. We reset the \n \/\/object count to what it was at the beginning of the event.\n TProcessID::SetObjectCount(ObjectNumber);\n}\n\n\n\/\/______________________________________________________________________________\nJet *JetEvent::AddJet()\n{\n \/\/ Add a new Jet to the list of tracks for this event.\n\n TClonesArray &jets = *fJets;\n Jet *jet = new(jets[fNjet++]) Jet();\n return jet;\n}\n\n\n\/\/______________________________________________________________________________\nTrack *JetEvent::AddTrack()\n{\n \/\/ Add a new track to the list of tracks for this event.\n\n TClonesArray &tracks = *fTracks;\n Track *track = new(tracks[fNtrack++]) Track();\n return track;\n}\n\n\n\/\/______________________________________________________________________________\nHit *JetEvent::AddHitA()\n{\n \/\/ Add a new hit to the list of hits in detector A\n\n TClonesArray &hitsA = *fHitsA;\n Hit *hit = new(hitsA[fNhitA++]) Hit();\n return hit;\n}\n\n\/\/______________________________________________________________________________\nHit *JetEvent::AddHitB()\n{\n \/\/ Add a new hit to the list of hits in detector B\n\n TClonesArray &hitsB = *fHitsB;\n Hit *hit = new(hitsB[fNhitB++]) Hit();\n return hit;\n}\n\n\/\/______________________________________________________________________________\nvoid JetEvent::Clear(Option_t *option)\n{\n fJets->Clear(option);\n fTracks->Clear(option);\n fHitsA->Clear(option);\n fHitsB->Clear(option);\n}\n\n\/\/______________________________________________________________________________\nvoid JetEvent::Reset(Option_t *)\n{\n\/\/ Static function to reset all static objects for this event\n\n delete fgJets; fgJets = 0;\n delete fgTracks; fgTracks = 0;\n delete fgHitsA; fgHitsA = 0;\n delete fgHitsB; fgHitsB = 0;\n}\n\n\n\n\n\n\nAdd missing include TMath.h\/\/ A JetEvent emulates 2 detectors A and B producing each\n\/\/ a TClonesArray of Hit objects.\n\/\/ A TClonesArray of Track objects is built with Hits objects\n\/\/ of detectors A and B. Eack Track object has a TRefArray of hits.\n\/\/ A TClonesArray of Jets is made with a subset of the Track objects\n\/\/ also stored in a TRefArray.\n\/\/ see $ROOTSYS\/tutorials\/jets.C for an example creating a Tree\n\/\/ with JetEvents.\n \n#include \"TMath.h\" \n#include \"TRandom.h\" \n#include \"JetEvent.h\"\n\nClassImp(Jet)\nClassImp(Track)\nClassImp(Hit)\nClassImp(JetEvent)\n\nTClonesArray *JetEvent::fgJets = 0;\nTClonesArray *JetEvent::fgTracks = 0;\nTClonesArray *JetEvent::fgHitsA = 0;\nTClonesArray *JetEvent::fgHitsB = 0;\n\n\/\/______________________________________________________________________________\nJetEvent::JetEvent()\n{\n \/\/ Create a JetEvent object.\n \/\/ When the constructor is invoked for the first time, the class static\n \/\/ variables fgxxx are 0 and the TClonesArray fgxxx are created.\n\n if (!fgTracks) fgTracks = new TClonesArray(\"Track\", 100);\n if (!fgJets) fgJets = new TClonesArray(\"Jet\", 10);\n if (!fgHitsA) fgHitsA = new TClonesArray(\"Hit\", 10000);\n if (!fgHitsB) fgHitsB = new TClonesArray(\"Hit\", 1000);\n fJets = fgJets;\n fTracks = fgTracks;\n fHitsA = fgHitsA;\n fHitsB = fgHitsB;\n}\n\n\/\/______________________________________________________________________________\nJetEvent::~JetEvent()\n{\n Reset();\n}\n\n\/\/______________________________________________________________________________\nvoid JetEvent::Build(Int_t jetm, Int_t trackm, Int_t hitam, Int_t hitbm) {\n \/\/Build one event\n \n \/\/Save current Object count\n Int_t ObjectNumber = TProcessID::GetObjectCount();\n Clear();\n\n Hit *hit;\n Track *track;\n Jet *jet;\n fNjet = fNtrack = fNhitA = fNhitB = 0;\n \n fVertex.SetXYZ(gRandom->Gaus(0,0.1),\n gRandom->Gaus(0,0.2),\n gRandom->Gaus(0,10));\n \n Int_t njets = (Int_t)gRandom->Gaus(jetm,1); if (njets < 1) njets = 1;\n for (Int_t j=0;jfPt = gRandom->Gaus(0,10);\n jet->fPhi = 2*TMath::Pi()*gRandom->Rndm();\n Int_t ntracks = (Int_t)gRandom->Gaus(trackm,3); if (ntracks < 1) ntracks = 1;\n for (Int_t t=0;tfPx = gRandom->Gaus(0,1);\n track->fPy = gRandom->Gaus(0,1);\n track->fPz = gRandom->Gaus(0,5);\n\t jet->fTracks.Add(track);\n Int_t nhitsA = (Int_t)gRandom->Gaus(hitam,5);\n for (Int_t ha=0;hafX = 10000*j + 100*t +ha;\n hit->fY = 10000*j + 100*t +ha+0.1;\n hit->fZ = 10000*j + 100*t +ha+0.2;\n\t track->fHits.Add(hit);\n }\n Int_t nhitsB = (Int_t)gRandom->Gaus(hitbm,2);\n for (Int_t hb=0;hbfX = 20000*j + 100*t +hb+0.3;\n hit->fY = 20000*j + 100*t +hb+0.4;\n hit->fZ = 20000*j + 100*t +hb+0.5;\n\t track->fHits.Add(hit);\n }\n track->fNhit = nhitsA + nhitsB;\n }\n } \n \/\/Restore Object count \n \/\/To save space in the table keeping track of all referenced objects\n \/\/we assume that our events do not address each other. We reset the \n \/\/object count to what it was at the beginning of the event.\n TProcessID::SetObjectCount(ObjectNumber);\n}\n\n\n\/\/______________________________________________________________________________\nJet *JetEvent::AddJet()\n{\n \/\/ Add a new Jet to the list of tracks for this event.\n\n TClonesArray &jets = *fJets;\n Jet *jet = new(jets[fNjet++]) Jet();\n return jet;\n}\n\n\n\/\/______________________________________________________________________________\nTrack *JetEvent::AddTrack()\n{\n \/\/ Add a new track to the list of tracks for this event.\n\n TClonesArray &tracks = *fTracks;\n Track *track = new(tracks[fNtrack++]) Track();\n return track;\n}\n\n\n\/\/______________________________________________________________________________\nHit *JetEvent::AddHitA()\n{\n \/\/ Add a new hit to the list of hits in detector A\n\n TClonesArray &hitsA = *fHitsA;\n Hit *hit = new(hitsA[fNhitA++]) Hit();\n return hit;\n}\n\n\/\/______________________________________________________________________________\nHit *JetEvent::AddHitB()\n{\n \/\/ Add a new hit to the list of hits in detector B\n\n TClonesArray &hitsB = *fHitsB;\n Hit *hit = new(hitsB[fNhitB++]) Hit();\n return hit;\n}\n\n\/\/______________________________________________________________________________\nvoid JetEvent::Clear(Option_t *option)\n{\n fJets->Clear(option);\n fTracks->Clear(option);\n fHitsA->Clear(option);\n fHitsB->Clear(option);\n}\n\n\/\/______________________________________________________________________________\nvoid JetEvent::Reset(Option_t *)\n{\n\/\/ Static function to reset all static objects for this event\n\n delete fgJets; fgJets = 0;\n delete fgTracks; fgTracks = 0;\n delete fgHitsA; fgHitsA = 0;\n delete fgHitsB; fgHitsB = 0;\n}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsViewOverlay.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2006-04-06 16:25:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_VIEW_OVERLAY_HXX\n#define SD_SLIDESORTER_VIEW_OVERLAY_HXX\n\n#include \"model\/SlsSharedPageDescriptor.hxx\"\n\n#include \n#include \n#include \n#include \n\nclass OutputDevice;\nclass Region;\n\nnamespace sd { namespace slidesorter {\nclass SlideSorterViewShell;\n} }\n\nnamespace sd { namespace slidesorter { namespace model {\nclass PageEnumeration;\n} } }\n\nnamespace sd { namespace slidesorter { namespace controller {\nclass SlideSorterController;\n} } }\n\nnamespace sd { namespace slidesorter { namespace view {\n\n\nclass ViewOverlay;\nclass SelectionRectangleOverlay;\nclass InsertionIndicatorOverlay;\nclass SubstitutionOverlay;\n\n\/** This base class of overlay graphics keeps track of the visibility of\n graphical objects that possibly are drawn in XOR paint mode. This makes\n it possibly to switch such an overlay on or off without knowing whether\n it is visible.\n*\/\nclass OverlayBase\n{\npublic:\n OverlayBase (ViewOverlay& rViewOverlay);\n virtual ~OverlayBase (void);\n\n virtual void Paint (void);\n\n virtual void Show (void);\n virtual void Hide (void);\n void Toggle (void);\n bool IsShowing (void);\n ViewOverlay& GetViewOverlay (void);\n\nprotected:\n ::osl::Mutex maMutex;\n\n ViewOverlay& mrViewOverlay;\n\n bool mbIsShowing;\n};\n\n\n\n\n\/** This class manages the substitution display of the page objects. This\n subsitution is used to visualize the selected page objects during a\n mouse drag operation.\n*\/\nclass SubstitutionOverlay\n : public OverlayBase\n{\npublic:\n SubstitutionOverlay (ViewOverlay& rViewOverlay);\n virtual ~SubstitutionOverlay (void);\n\n virtual void Paint (void);\n\n \/** Setup the substitution display of the given set of selected pages.\n The given mouse position is remembered so that it later can be\n returned by GetPosition(). This is a convenience feature.\n *\/\n void Create (\n model::PageEnumeration& rSelection,\n const Point& rPosition);\n\n \/** Clear the substitution display. Until the next call of Create() no\n substution is painted.\n *\/\n void Clear (void);\n\n \/** Move the substitution display by the given amount of pixels.\n *\/\n void Move (const Point& rOffset);\n void SetPosition (const Point& rPosition);\n const Point& GetPosition (void) const;\n\nprivate:\n \/\/\/ List of page object substitution displays.\n typedef ::std::vector SubstitutionShapeList;\n SubstitutionShapeList maShapes;\n Point maPosition;\n};\n\n\n\n\nclass SelectionRectangleOverlay\n : public OverlayBase\n{\npublic:\n SelectionRectangleOverlay (ViewOverlay& rViewOverlay);\n\n virtual void Paint (void);\n\n virtual void Show (void);\n virtual void Hide (void);\n\n void Start (const Point& rAnchor);\n void Update (const Point& rSecondCorner);\n\n Rectangle GetSelectionRectangle (void);\n\nprivate:\n Point maAnchor;\n Point maSecondCorner;\n};\n\n\n\n\n\/** The insertion indicator is painted as a vertical or horizonal bar\n in the space between slides.\n*\/\nclass InsertionIndicatorOverlay\n : public OverlayBase\n{\npublic:\n InsertionIndicatorOverlay (ViewOverlay& rViewOverlay);\n\n void SetPositionAndSize (const Rectangle& rBoundingBox);\n\n virtual void Paint (void);\n\n \/** Given a position in model coordinates this method calculates the\n insertion marker both as an index in the document and as a rectangle\n used for drawing the insertion indicator.\n *\/\n void SetPosition (const Point& rPosition);\n\n sal_Int32 GetInsertionPageIndex (void) const;\n\nprivate:\n Rectangle maBoundingBox;\n sal_Int32 mnInsertionIndex;\n};\n\n\n\n\n\/** Paint a frame around the slide preview under the mouse. The actual\n painting is done by the PageObjectViewObjectContact of the slidesorter.\n This class is responsible for the coordination of the right time for the\n painting.\n*\/\nclass MouseOverIndicatorOverlay\n : public OverlayBase\n{\npublic:\n MouseOverIndicatorOverlay (ViewOverlay& rViewOverlay);\n\n \/** Set the page object for which to paint a mouse over indicator.\n @param pContact\n A value of indicates to not paint the mouse over indicator.\n *\/\n void SetSlideUnderMouse (const model::SharedPageDescriptor& rpDescriptor);\n\n virtual void Paint (void);\n\nprivate:\n \/** The page under the mouse is stored as weak shared pointer so that\n model changes can be handled without having the SlideSorterModel\n inform this class explicitly.\n *\/\n ::boost::weak_ptr mpPageUnderMouse;\n};\n\n\n\n\n\/** The view overlay manages and paints some indicators that are painted on\n top of the regular view content (the page objects). It is separated\n from the view to allow the indicators to be altered in position and size\n without to repaint the whole view content (inside that the bounding box\n of the indicator). One technique to achive this is to use XOR-painting.\n\n The view overlay itself simply provides the more specialized classes\n that handle individual indicators.\n\n*\/\nclass ViewOverlay\n{\npublic:\n ViewOverlay (SlideSorterViewShell& rViewShell);\n ~ViewOverlay (void);\n\n SelectionRectangleOverlay& GetSelectionRectangleOverlay (void);\n MouseOverIndicatorOverlay& GetMouseOverIndicatorOverlay (void);\n InsertionIndicatorOverlay& GetInsertionIndicatorOverlay (void);\n SubstitutionOverlay& GetSubstitutionOverlay (void);\n\n void Paint (void);\n\n \/** The overlay paint type describes how an overlay is painted. That can be\n either by using XOR operation or by doing a regular paint.\n *\/\n enum OverlayPaintType { OPT_ALL, OPT_XOR, OPT_PAINT };\n\n \/** As a preparation for draw operations that are not caused by the\n overlays this method saves the current state of all overlays so that\n the next call to Restore() can restore them. After that it hides\n the overlays so they do not interfere with the drawing operations.\n @param eType\n This parameter specifies what overlays to hide.\n *\/\n void HideAndSave (OverlayPaintType eType = OPT_ALL);\n\n \/** Restore the state of the overlays that has been saved in an earlier\n call of HideAndSave().\n *\/\n void Restore (void);\n\n controller::SlideSorterController& GetController (void);\n SlideSorterViewShell& GetViewShell (void);\n\nprivate:\n SlideSorterViewShell& mrViewShell;\n SelectionRectangleOverlay maSelectionRectangleOverlay;\n MouseOverIndicatorOverlay maMouseOverIndicatorOverlay;\n InsertionIndicatorOverlay maInsertionIndicatorOverlay;\n SubstitutionOverlay maSubstitutionOverlay;\n\n OverlayPaintType meSavedStateType;\n\n bool mbSelectionRectangleWasVisible;\n bool mbMouseOverIndicatorWasVisible;\n bool mbInsertionIndicatorWasVisible;\n bool mbSubstitutionDisplayWasVisible;\n\n \/** The number HideAndSave() has been called more than Restore(). Only\n when the value is 1 does Restore() really restore the overlays.\n *\/\n int mnHideAndSaveLevel;\n};\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n#endif\nINTEGRATION: CWS aw054 (1.7.374); FILE MERGED 2007\/10\/17 13:22:12 af 1.7.374.1: #i82710# Using overlay support of drawing layer for painting overlays.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsViewOverlay.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: vg $ $Date: 2008-02-12 16:28:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_VIEW_OVERLAY_HXX\n#define SD_SLIDESORTER_VIEW_OVERLAY_HXX\n\n#include \"model\/SlsSharedPageDescriptor.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass OutputDevice;\nclass Region;\n\nnamespace sd { namespace slidesorter {\nclass SlideSorterViewShell;\n} }\n\nnamespace sd { namespace slidesorter { namespace model {\nclass PageEnumeration;\n} } }\n\nnamespace sd { namespace slidesorter { namespace controller {\nclass SlideSorterController;\n} } }\n\nnamespace sdr { namespace overlay {\nclass OverlayManager;\n} }\n\nnamespace sd { namespace slidesorter { namespace view {\n\n\nclass InsertionIndicatorOverlay;\nclass PageObjectViewObjectContact;\nclass SelectionRectangleOverlay;\nclass SubstitutionOverlay;\nclass ViewOverlay;\n\n\/** This base class of slide sorter overlays uses the drawing layer overlay\n support for the display.\n*\/\nclass OverlayBase\n : private ::boost::noncopyable,\n public sdr::overlay::OverlayObject\n{\npublic:\n OverlayBase (ViewOverlay& rViewOverlay);\n virtual ~OverlayBase (void);\n\n virtual void Paint (void);\n\n virtual void Show (void);\n virtual void Hide (void);\n void Toggle (void);\n bool IsShowing (void);\n ViewOverlay& GetViewOverlay (void);\n\nprotected:\n ::osl::Mutex maMutex;\n\n ViewOverlay& mrViewOverlay;\n\n virtual void transform (const basegfx::B2DHomMatrix& rMatrix);\n\n \/** Make sure that the overlay object is registered at the\n OverlayManager. This registration is done on demand.\n *\/\n void EnsureRegistration (void);\n};\n\n\n\n\n\/** During internal drag and drop the outlines of the selected slides are\n painted at the mouse position in dashed lines.\n*\/\nclass SubstitutionOverlay\n : public OverlayBase\n{\npublic:\n SubstitutionOverlay (ViewOverlay& rViewOverlay);\n virtual ~SubstitutionOverlay (void);\n\n \/** Setup the substitution display of the given set of selected pages.\n The given mouse position is remembered so that it later can be\n returned by GetPosition(). This is a convenience feature.\n *\/\n void Create (\n model::PageEnumeration& rSelection,\n const Point& rPosition);\n\n \/** Clear the substitution display. Until the next call of Create() no\n substution is painted.\n *\/\n void Clear (void);\n\n \/** Move the substitution display by the given amount of pixels.\n *\/\n void Move (const Point& rOffset);\n void SetPosition (const Point& rPosition);\n Point GetPosition (void) const;\n\nprotected:\n virtual void drawGeometry (OutputDevice& rOutputDevice);\n virtual void createBaseRange (OutputDevice& rOutputDevice);\n\nprivate:\n Point maPosition;\n basegfx::B2DRange maBoundingBox;\n basegfx::B2DPolyPolygon maShapes;\n};\n\n\n\n\n\/** Slides can be selected by drawing a selection rectangle in the slide\n sorter. When the left mouse button is released all slides that are at\n least partially in the rectangle are selected.\n*\/\nclass SelectionRectangleOverlay\n : public OverlayBase\n{\npublic:\n SelectionRectangleOverlay (ViewOverlay& rViewOverlay);\n\n void Start (const Point& rAnchor);\n void Update (const Point& rSecondCorner);\n\n Rectangle GetSelectionRectangle (void);\n\nprotected:\n virtual void drawGeometry (OutputDevice& rOutputDevice);\n virtual void createBaseRange (OutputDevice& rOutputDevice);\n\nprivate:\n Point maAnchor;\n Point maSecondCorner;\n};\n\n\n\n\n\/** The insertion indicator is painted as a vertical or horizonal bar\n in the space between slides.\n*\/\nclass InsertionIndicatorOverlay\n : public OverlayBase\n{\npublic:\n InsertionIndicatorOverlay (\n ViewOverlay& rViewOverlay,\n SlideSorterViewShell& mrViewShell);\n\n \/** Given a position in model coordinates this method calculates the\n insertion marker both as an index in the document and as a rectangle\n used for drawing the insertion indicator.\n *\/\n void SetPosition (const Point& rPosition);\n\n sal_Int32 GetInsertionPageIndex (void) const;\n\nprotected:\n virtual void drawGeometry (OutputDevice& rOutputDevice);\n virtual void createBaseRange (OutputDevice& rOutputDevice);\n\nprivate:\n SlideSorterViewShell& mrViewShell;\n sal_Int32 mnInsertionIndex;\n Rectangle maBoundingBox;\n\n void SetPositionAndSize (const Rectangle& rBoundingBox);\n};\n\n\n\n\n\/** Paint a frame around the slide preview under the mouse. The actual\n painting is done by the PageObjectViewObjectContact of the slidesorter.\n*\/\nclass MouseOverIndicatorOverlay\n : public OverlayBase\n{\npublic:\n MouseOverIndicatorOverlay (\n ViewOverlay& rViewOverlay,\n SlideSorterViewShell& mrViewShell);\n virtual ~MouseOverIndicatorOverlay (void);\n\n \/** Set the page object for which to paint a mouse over indicator.\n @param pContact\n A value of indicates to not paint the mouse over indicator.\n *\/\n void SetSlideUnderMouse (const model::SharedPageDescriptor& rpDescriptor);\n\nprotected:\n virtual void drawGeometry (OutputDevice& rOutputDevice);\n virtual void createBaseRange (OutputDevice& rOutputDevice);\n\nprivate:\n class MouseOverIndicator;\n\n SlideSorterViewShell& mrViewShell;\n\n \/** The page under the mouse is stored as weak shared pointer so that\n model changes can be handled without having the SlideSorterModel\n inform this class explicitly.\n *\/\n ::boost::weak_ptr mpPageUnderMouse;\n\n view::PageObjectViewObjectContact* GetViewObjectContact (void) const;\n};\n\n\n\n\n\/** The view overlay manages and paints some indicators that are painted on\n top of the regular view content (the page objects). It is separated\n from the view to allow the indicators to be altered in position and size\n without repainting the whole view content (inside that the bounding box\n of the indicator). This is achieved by using the drawing layer overlay\n support.\n\n The view overlay itself simply gives access to the more specialized\n classes that handle individual indicators.\n\n*\/\nclass ViewOverlay\n{\npublic:\n ViewOverlay (SlideSorterViewShell& rViewShell);\n ~ViewOverlay (void);\n\n SelectionRectangleOverlay& GetSelectionRectangleOverlay (void);\n MouseOverIndicatorOverlay& GetMouseOverIndicatorOverlay (void);\n InsertionIndicatorOverlay& GetInsertionIndicatorOverlay (void);\n SubstitutionOverlay& GetSubstitutionOverlay (void);\n\n sdr::overlay::OverlayManager* GetOverlayManager (void) const;\n\nprivate:\n SlideSorterViewShell& mrViewShell;\n SelectionRectangleOverlay maSelectionRectangleOverlay;\n MouseOverIndicatorOverlay maMouseOverIndicatorOverlay;\n InsertionIndicatorOverlay maInsertionIndicatorOverlay;\n SubstitutionOverlay maSubstitutionOverlay;\n};\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n#endif\n<|endoftext|>"} {"text":"#ifndef SUBGRIDLIST_HH\n#define SUBGRIDLIST_HH\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/\/ \/ done\n\nnamespace Dune {\ntemplate< class HostDiscreteFunctionImp, class SubGridImp, class MacroMicroGridSpecifierImp >\nclass SubGridList\n{\npublic:\n \/\/ ! ---------------- typedefs for the HostDiscreteFunctionSpace -----------------------\n\n typedef MacroMicroGridSpecifierImp MacroMicroGridSpecifierType;\n\n typedef HostDiscreteFunctionImp HostDiscreteFunctionType;\n\n \/\/ ! type of discrete function space\n typedef typename HostDiscreteFunctionType::DiscreteFunctionSpaceType\n HostDiscreteFunctionSpaceType;\n\n \/\/ ! type of (non-discrete )function space\n typedef typename HostDiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;\n\n \/\/ ! type of grid partition\n typedef typename HostDiscreteFunctionSpaceType::GridPartType HostGridPartType;\n\n \/\/ ! type of grid\n typedef typename HostDiscreteFunctionSpaceType::GridType HostGridType;\n\n typedef typename HostGridType::Traits::LeafIndexSet HostGridLeafIndexSet;\n\n typedef typename HostDiscreteFunctionSpaceType::IteratorType HostGridEntityIteratorType;\n\n typedef typename HostGridEntityIteratorType::Entity HostEntityType;\n\n typedef typename HostEntityType::EntityPointer HostEntityPointerType;\n\n \/\/ old:\n #if 0\n typedef typename HostGridType::template Codim< 0 >::template Partition< All_Partition >::LevelIterator\n HostgridLevelEntityIteratorType;\n typedef typename HostGridType::Traits::LevelIndexSet\n HostGridLevelIndexSet;\n\n \/\/ usage:\n \/\/ const HostGridLevelIndexSet& hostGridLevelIndexSet = hostGrid.levelIndexSet(computational_level_);\n \/\/ int father_index = hostGridLevelIndexSet.index( *level_it );\n #endif \/\/ if 0\n\n typedef typename HostEntityType::template Codim< 2 >::EntityPointer HostNodePointer;\n\n typedef typename HostGridPartType::IntersectionIteratorType HostIntersectionIterator;\n\n \/\/ ! ---------------- typedefs for the SubgridDiscreteFunctionSpace -----------------------\n \/\/ ( typedefs for the local grid and the corresponding local ('sub') )discrete space )\n\n \/\/ ! type of grid\n typedef SubGridImp SubGridType;\n\n \/\/ ! type of grid part\n typedef LeafGridPart< SubGridType > SubGridPartType;\n\n template< typename EntityPointerCollectionType >\n bool entity_patch_in_subgrid(HostEntityPointerType& hit,\n const HostGridPartType& hostGridPart,\n SubGridType& subGrid,\n EntityPointerCollectionType& entities_sharing_same_node) {\n bool patch_in_subgrid_ = true;\n\n \/\/ loop over the nodes of the enity\n for (int i = 0; i < (*hit).template count< 2 >(); i += 1)\n {\n const HostNodePointer node = (*hit).template subEntity< 2 >(i);\n\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n for (int j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)\n {\n if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )\n {\n patch_in_subgrid_ = false;\n }\n }\n }\n return patch_in_subgrid_;\n } \/\/ entity_patch_in_subgrid\n\n template< typename EntityPointerCollectionType >\n void enrichment(HostEntityPointerType& hit,\n HostEntityPointerType& level_father_it,\n MacroMicroGridSpecifierType& specifier,\n int& father_index,\n const HostGridPartType& hostGridPart,\n SubGridType& subGrid,\n EntityPointerCollectionType& entities_sharing_same_node,\n int& layer,\n bool***& enriched) {\n \/\/ difference in levels between coarse and fine grid\n int level_difference = specifier.getLevelDifference();\n HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();\n\n const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();\n\n const HostGridLeafIndexSet& hostGridLeafIndexSet = hostSpace_.gridPart().grid().leafIndexSet();\n\n for (int l = 0; l <= layer; l += 1)\n {\n enriched[father_index][hostGridLeafIndexSet.index(*hit)][l] = true;\n }\n\n layer -= 1;\n\n \/\/ loop over the nodes of the enity\n for (int i = 0; i < (*hit).template count< 2 >(); i += 1)\n {\n const HostNodePointer node = (*hit).template subEntity< 2 >(i);\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n for (size_t j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)\n {\n if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )\n {\n subGrid.insertPartial(*entities_sharing_same_node[global_index_node][j]);\n }\n\n if (layer > 0)\n {\n HostEntityPointerType father = entities_sharing_same_node[global_index_node][j];\n for (int lev = 0; lev < level_difference; ++lev)\n father = father->father();\n\n HostEntityPointerType coarse_father_test = father;\n bool father_found = false;\n while (father_found == false)\n {\n if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)\n {\n father = coarse_father_test;\n }\n\n if (coarse_father_test->hasFather() == false)\n { father_found = true; } else\n { coarse_father_test = coarse_father_test->father(); }\n }\n\n if ( !(father == level_father_it) )\n {\n if (enriched[father_index][hostGridLeafIndexSet.index(*entities_sharing_same_node[global_index_node][j])][\n layer] == false)\n {\n enrichment(entities_sharing_same_node[global_index_node][j], level_father_it,\n specifier, father_index,\n hostGridPart, subGrid, entities_sharing_same_node, layer, enriched);\n\n layer += 1;\n }\n }\n }\n }\n }\n } \/\/ enrichment\n\n SubGridList(MacroMicroGridSpecifierType& specifier, bool silent = true)\n : hostSpace_( specifier.fineSpace() )\n , specifier_(specifier)\n , silent_(silent) {\n std::cout << \"Starting creation of subgrids.\" << std::endl << std::endl;\n\n HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();\n\n const HostGridPartType& hostGridPart = hostSpace_.gridPart();\n\n HostGridType& hostGrid = hostSpace_.gridPart().grid();\n\n int number_of_nodes = hostGrid.size(2 \/*codim*\/);\n\n \/\/ -------- identify the entities that share a certain node -------\n\n std::vector< std::vector< HostEntityPointerType > > entities_sharing_same_node(number_of_nodes);\n\n for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)\n {\n int number_of_nodes_in_entity = (*it).template count< 2 >();\n for (int i = 0; i < number_of_nodes_in_entity; i += 1)\n {\n const HostNodePointer node = (*it).template subEntity< 2 >(i);\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );\n }\n }\n\n int max_num_layers = 0;\n for (int i = 0; i < specifier_.getNumOfCoarseEntities(); i += 1)\n {\n if (specifier_.getLayer(i) > max_num_layers)\n { max_num_layers = specifier_.getLayer(i); }\n }\n\n \/\/ difference in levels between coarse and fine grid\n int level_difference = specifier.getLevelDifference();\n\n \/\/ number of coarse grid entities (of codim 0).\n int number_of_coarse_grid_entities = specifier.getNumOfCoarseEntities();\n\n std::cout << \"number_of_coarse_grid_entities = \" << number_of_coarse_grid_entities << std::endl;\n\n subGrid = new SubGridType *[number_of_coarse_grid_entities];\n\n \/\/ ! ----------- create subgrids --------------------\n\n const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();\n\n for (HostGridEntityIteratorType coarse_it = coarseSpace.begin(); coarse_it != coarseSpace.end(); ++coarse_it)\n {\n int coarse_index = coarseGridLeafIndexSet.index(*coarse_it);\n\n subGrid[coarse_index] = new SubGridType(hostGrid);\n subGrid[coarse_index]->createBegin();\n }\n\n for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)\n {\n int number_of_nodes_in_entity = (*it).template count< 2 >();\n for (int i = 0; i < number_of_nodes_in_entity; i += 1)\n {\n const HostNodePointer node = (*it).template subEntity< 2 >(i);\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );\n }\n }\n\n bool*** enriched = new bool**[number_of_coarse_grid_entities];\n for (int k = 0; k < number_of_coarse_grid_entities; k += 1)\n {\n enriched[k] = new bool*[hostGrid.size(0 \/*codim*\/)];\n for (int m = 0; m < hostGrid.size(0 \/*codim*\/); m += 1)\n {\n enriched[k][m] = new bool[max_num_layers + 1];\n }\n }\n\n for (int k = 0; k < number_of_coarse_grid_entities; k += 1)\n {\n for (int m = 0; m < hostGrid.size(0 \/*codim*\/); m += 1)\n {\n for (int l = 0; l < max_num_layers + 1; l += 1)\n enriched[k][m][l] = false;\n }\n }\n\n \/\/ a fine grid iterator for the codim 0 hostgrid entities:\n HostGridEntityIteratorType host_endit = hostSpace_.end();\n for (HostGridEntityIteratorType host_it = hostSpace_.begin();\n host_it != host_endit;\n ++host_it)\n {\n const HostEntityType& host_entity = *host_it;\n\n int DUNE_UNUSED(number_of_nodes_in_entity) = (*host_it).template count< 2 >();\n\n \/\/ get the coarse-grid-father of host_entity (which is a maxlevel entity)\n HostEntityPointerType level_father_entity = HostEntityPointerType(*host_it);\n\n for (int lev = 0; lev < level_difference; ++lev)\n level_father_entity = level_father_entity->father();\n\n \/\/ changed 'contains'-method in 'indexset.hh'\n \/\/ we use: \"return ( (subIndex >= 0) && (subIndex < size( codim )) );\"\n \/\/ instead of \"return (subIndex >= 0);\"\n HostEntityPointerType coarse_father_test = level_father_entity;\n bool father_found = false;\n while (father_found == false)\n {\n if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)\n { level_father_entity = coarse_father_test; }\n\n if (coarse_father_test->hasFather() == false)\n { father_found = true; } else\n { coarse_father_test = coarse_father_test->father(); }\n }\n\n int father_index = coarseGridLeafIndexSet.index(*level_father_entity);\n\n if ( !( subGrid[father_index]->template contains< 0 >(host_entity) ) )\n { subGrid[father_index]->insertPartial(host_entity); }\n\n \/\/ check the neighbor entities and look if they belong to the same father\n \/\/ if yes, continue\n \/\/ if not, enrichement with 'n(T)'-layers\n bool all_neighbors_have_same_father = true;\n const HostIntersectionIterator iend = hostGridPart.iend(host_entity);\n for (HostIntersectionIterator iit = hostGridPart.ibegin(host_entity); iit != iend; ++iit)\n {\n if ( iit->neighbor() ) \/\/ if there is a neighbor entity\n {\n \/\/ check if the neighbor entity is in the subgrid\n const HostEntityPointerType neighborHostEntityPointer = iit->outside();\n const HostEntityType& DUNE_UNUSED(neighborHostEntity) = *neighborHostEntityPointer;\n\n HostEntityPointerType level_father_neighbor_entity = neighborHostEntityPointer;\n for (int lev = 0; lev < level_difference; ++lev)\n level_father_neighbor_entity = level_father_neighbor_entity->father();\n\n HostEntityPointerType coarse_father_test = level_father_neighbor_entity;\n\n bool father_found = false;\n while (father_found == false)\n {\n if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)\n { level_father_neighbor_entity = coarse_father_test; }\n\n if (coarse_father_test->hasFather() == false)\n { father_found = true; } else\n { coarse_father_test = coarse_father_test->father(); }\n }\n\n if ( !(level_father_neighbor_entity == level_father_entity) )\n {\n all_neighbors_have_same_father = false;\n }\n } else {\n all_neighbors_have_same_father = false;\n }\n }\n\n if (all_neighbors_have_same_father == true)\n { continue; }\n\n int layers = specifier_.getLayer(father_index);\n if (layers > 0)\n {\n HostEntityPointerType hep(*host_it);\n enrichment(hep, level_father_entity, specifier, father_index,\n hostGridPart, *subGrid[father_index], entities_sharing_same_node, layers, enriched);\n }\n }\n\n for (int i = 0; i < number_of_coarse_grid_entities; ++i)\n {\n subGrid[i]->createEnd();\n if (!silent_)\n {\n std::cout << \"Subgrid \" << i << \":\" << std::endl;\n subGrid[i]->report();\n }\n\n if (subGrid[i]->size(2) == 0)\n {\n std::cout << \"Error.\" << std::endl;\n std::cout << \"Error. Created Subgrid with 0 nodes.\" << std::endl;\n\n for (HostGridEntityIteratorType coarse_it = specifier_.coarseSpace().begin();\n coarse_it != specifier_.coarseSpace().end(); ++coarse_it)\n {\n const HostEntityType& coarse_entity = *coarse_it;\n int index = coarseGridLeafIndexSet.index(coarse_entity);\n if (i == index)\n {\n std::cout << \"We have a problem with the following coarse-grid element:\" << std::endl;\n std::cout << \"coarse element corner(0) = \" << coarse_it->geometry().corner(0) << std::endl;\n std::cout << \"coarse element corner(1) = \" << coarse_it->geometry().corner(1) << std::endl;\n std::cout << \"coarse element corner(2) = \" << coarse_it->geometry().corner(2) << std::endl << std::endl;\n }\n }\n abort();\n }\n }\n\n \/\/ ! ----------- end create subgrids --------------------\n }\n\n SubGridType& getSubGrid(int i) {\n const int size = specifier_.getNumOfCoarseEntities();\n\n if (i >= size)\n {\n DUNE_THROW(Dune::RangeError, \"Error. Subgrid-Index too large.\");\n }\n return *(subGrid[i]);\n } \/\/ getSubGrid\n\nprivate:\n SubGridList(const SubGridList& list);\n const HostDiscreteFunctionSpaceType& hostSpace_;\n MacroMicroGridSpecifierType& specifier_;\n\n bool silent_;\n\n SubGridType** subGrid;\n\npublic:\n \/\/ Destruktor (Dynamisch angeforderter Speicher wird wieder freigegeben)\n ~SubGridList() {\n const int size = specifier_.getNumOfCoarseEntities();\n\n for (int i = 0; i < size; ++i)\n delete subGrid[i];\n delete[] subGrid;\n }\n};\n}\n\n#endif \/\/ #ifndef SUBGRIDLIST_HH\nfix parameters shadowing member var in subgrid list#ifndef SUBGRIDLIST_HH\n#define SUBGRIDLIST_HH\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ \/ done\n\nnamespace Dune {\ntemplate< class HostDiscreteFunctionImp, class SubGridImp, class MacroMicroGridSpecifierImp >\nclass SubGridList : boost::noncopyable\n{\npublic:\n \/\/ ! ---------------- typedefs for the HostDiscreteFunctionSpace -----------------------\n\n typedef MacroMicroGridSpecifierImp MacroMicroGridSpecifierType;\n\n typedef HostDiscreteFunctionImp HostDiscreteFunctionType;\n\n \/\/ ! type of discrete function space\n typedef typename HostDiscreteFunctionType::DiscreteFunctionSpaceType\n HostDiscreteFunctionSpaceType;\n\n \/\/ ! type of (non-discrete )function space\n typedef typename HostDiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;\n\n \/\/ ! type of grid partition\n typedef typename HostDiscreteFunctionSpaceType::GridPartType HostGridPartType;\n\n \/\/ ! type of grid\n typedef typename HostDiscreteFunctionSpaceType::GridType HostGridType;\n\n typedef typename HostGridType::Traits::LeafIndexSet HostGridLeafIndexSet;\n\n typedef typename HostDiscreteFunctionSpaceType::IteratorType HostGridEntityIteratorType;\n\n typedef typename HostGridEntityIteratorType::Entity HostEntityType;\n\n typedef typename HostEntityType::EntityPointer HostEntityPointerType;\n\n typedef typename HostEntityType::template Codim< 2 >::EntityPointer HostNodePointer;\n\n typedef typename HostGridPartType::IntersectionIteratorType HostIntersectionIterator;\n\n \/\/ ! ---------------- typedefs for the SubgridDiscreteFunctionSpace -----------------------\n \/\/ ( typedefs for the local grid and the corresponding local ('sub') )discrete space )\n\n \/\/ ! type of grid\n typedef SubGridImp SubGridType;\n\n \/\/ ! type of grid part\n typedef LeafGridPart< SubGridType > SubGridPartType;\n\n template< typename EntityPointerCollectionType >\n bool entity_patch_in_subgrid(HostEntityPointerType& hit,\n const HostGridPartType& hostGridPart,\n const SubGridType& subGrid,\n EntityPointerCollectionType& entities_sharing_same_node) {\n bool patch_in_subgrid_ = true;\n\n \/\/ loop over the nodes of the enity\n for (int i = 0; i < (*hit).template count< 2 >(); i += 1)\n {\n const HostNodePointer node = (*hit).template subEntity< 2 >(i);\n\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n for (int j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)\n {\n if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )\n {\n patch_in_subgrid_ = false;\n }\n }\n }\n return patch_in_subgrid_;\n } \/\/ entity_patch_in_subgrid\n\n template< typename EntityPointerCollectionType >\n void enrichment(HostEntityPointerType& hit,\n HostEntityPointerType& level_father_it,\n MacroMicroGridSpecifierType& specifier,\n int& father_index,\n const HostGridPartType& hostGridPart,\n SubGridType& subGrid,\n EntityPointerCollectionType& entities_sharing_same_node,\n int& layer,\n bool***& enriched) {\n \/\/ difference in levels between coarse and fine grid\n int level_difference = specifier.getLevelDifference();\n HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();\n\n const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();\n\n const HostGridLeafIndexSet& hostGridLeafIndexSet = hostSpace_.gridPart().grid().leafIndexSet();\n\n for (int l = 0; l <= layer; l += 1)\n {\n enriched[father_index][hostGridLeafIndexSet.index(*hit)][l] = true;\n }\n\n layer -= 1;\n\n \/\/ loop over the nodes of the enity\n for (int i = 0; i < (*hit).template count< 2 >(); i += 1)\n {\n const HostNodePointer node = (*hit).template subEntity< 2 >(i);\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n for (size_t j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)\n {\n if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )\n {\n subGrid.insertPartial(*entities_sharing_same_node[global_index_node][j]);\n }\n\n if (layer > 0)\n {\n HostEntityPointerType father = entities_sharing_same_node[global_index_node][j];\n for (int lev = 0; lev < level_difference; ++lev)\n father = father->father();\n\n HostEntityPointerType coarse_father_test = father;\n bool father_found = false;\n while (father_found == false)\n {\n if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)\n {\n father = coarse_father_test;\n }\n\n if (coarse_father_test->hasFather() == false)\n { father_found = true; } else\n { coarse_father_test = coarse_father_test->father(); }\n }\n\n if ( !(father == level_father_it) )\n {\n if (enriched[father_index][hostGridLeafIndexSet.index(*entities_sharing_same_node[global_index_node][j])][\n layer] == false)\n {\n enrichment(entities_sharing_same_node[global_index_node][j], level_father_it,\n specifier, father_index,\n hostGridPart, subGrid, entities_sharing_same_node, layer, enriched);\n\n layer += 1;\n }\n }\n }\n }\n }\n } \/\/ enrichment\n\n SubGridList(MacroMicroGridSpecifierType& specifier, bool silent = true)\n : hostSpace_( specifier.fineSpace() )\n , specifier_(specifier)\n , silent_(silent) {\n std::cout << \"Starting creation of subgrids.\" << std::endl << std::endl;\n\n HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();\n\n const HostGridPartType& hostGridPart = hostSpace_.gridPart();\n\n HostGridType& hostGrid = hostSpace_.gridPart().grid();\n\n int number_of_nodes = hostGrid.size(2 \/*codim*\/);\n\n \/\/ -------- identify the entities that share a certain node -------\n\n std::vector< std::vector< HostEntityPointerType > > entities_sharing_same_node(number_of_nodes);\n\n for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)\n {\n int number_of_nodes_in_entity = (*it).template count< 2 >();\n for (int i = 0; i < number_of_nodes_in_entity; i += 1)\n {\n const HostNodePointer node = (*it).template subEntity< 2 >(i);\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );\n }\n }\n\n int max_num_layers = 0;\n for (int i = 0; i < specifier_.getNumOfCoarseEntities(); i += 1)\n {\n if (specifier_.getLayer(i) > max_num_layers)\n { max_num_layers = specifier_.getLayer(i); }\n }\n\n \/\/ difference in levels between coarse and fine grid\n int level_difference = specifier.getLevelDifference();\n\n \/\/ number of coarse grid entities (of codim 0).\n int number_of_coarse_grid_entities = specifier.getNumOfCoarseEntities();\n\n std::cout << \"number_of_coarse_grid_entities = \" << number_of_coarse_grid_entities << std::endl;\n\n subGridList_ = new SubGridType *[number_of_coarse_grid_entities];\n\n \/\/ ! ----------- create subgrids --------------------\n\n const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();\n\n for (HostGridEntityIteratorType coarse_it = coarseSpace.begin(); coarse_it != coarseSpace.end(); ++coarse_it)\n {\n int coarse_index = coarseGridLeafIndexSet.index(*coarse_it);\n\n subGridList_[coarse_index] = new SubGridType(hostGrid);\n subGridList_[coarse_index]->createBegin();\n }\n\n for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)\n {\n int number_of_nodes_in_entity = (*it).template count< 2 >();\n for (int i = 0; i < number_of_nodes_in_entity; i += 1)\n {\n const HostNodePointer node = (*it).template subEntity< 2 >(i);\n int global_index_node = hostGridPart.indexSet().index(*node);\n\n entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );\n }\n }\n\n bool*** enriched = new bool**[number_of_coarse_grid_entities];\n for (int k = 0; k < number_of_coarse_grid_entities; k += 1)\n {\n enriched[k] = new bool*[hostGrid.size(0 \/*codim*\/)];\n for (int m = 0; m < hostGrid.size(0 \/*codim*\/); m += 1)\n {\n enriched[k][m] = new bool[max_num_layers + 1];\n }\n }\n\n for (int k = 0; k < number_of_coarse_grid_entities; k += 1)\n {\n for (int m = 0; m < hostGrid.size(0 \/*codim*\/); m += 1)\n {\n for (int l = 0; l < max_num_layers + 1; l += 1)\n enriched[k][m][l] = false;\n }\n }\n\n \/\/ a fine grid iterator for the codim 0 hostgrid entities:\n HostGridEntityIteratorType host_endit = hostSpace_.end();\n for (HostGridEntityIteratorType host_it = hostSpace_.begin();\n host_it != host_endit;\n ++host_it)\n {\n const HostEntityType& host_entity = *host_it;\n\n int DUNE_UNUSED(number_of_nodes_in_entity) = (*host_it).template count< 2 >();\n\n \/\/ get the coarse-grid-father of host_entity (which is a maxlevel entity)\n HostEntityPointerType level_father_entity = HostEntityPointerType(*host_it);\n\n for (int lev = 0; lev < level_difference; ++lev)\n level_father_entity = level_father_entity->father();\n\n \/\/ changed 'contains'-method in 'indexset.hh'\n \/\/ we use: \"return ( (subIndex >= 0) && (subIndex < size( codim )) );\"\n \/\/ instead of \"return (subIndex >= 0);\"\n HostEntityPointerType coarse_father_test = level_father_entity;\n bool father_found = false;\n while (father_found == false)\n {\n if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)\n { level_father_entity = coarse_father_test; }\n\n if (coarse_father_test->hasFather() == false)\n { father_found = true; } else\n { coarse_father_test = coarse_father_test->father(); }\n }\n\n int father_index = coarseGridLeafIndexSet.index(*level_father_entity);\n\n if ( !( subGridList_[father_index]->template contains< 0 >(host_entity) ) )\n { subGridList_[father_index]->insertPartial(host_entity); }\n\n \/\/ check the neighbor entities and look if they belong to the same father\n \/\/ if yes, continue\n \/\/ if not, enrichement with 'n(T)'-layers\n bool all_neighbors_have_same_father = true;\n const HostIntersectionIterator iend = hostGridPart.iend(host_entity);\n for (HostIntersectionIterator iit = hostGridPart.ibegin(host_entity); iit != iend; ++iit)\n {\n if ( iit->neighbor() ) \/\/ if there is a neighbor entity\n {\n \/\/ check if the neighbor entity is in the subgrid\n const HostEntityPointerType neighborHostEntityPointer = iit->outside();\n const HostEntityType& DUNE_UNUSED(neighborHostEntity) = *neighborHostEntityPointer;\n\n HostEntityPointerType level_father_neighbor_entity = neighborHostEntityPointer;\n for (int lev = 0; lev < level_difference; ++lev)\n level_father_neighbor_entity = level_father_neighbor_entity->father();\n\n HostEntityPointerType coarse_father_test = level_father_neighbor_entity;\n\n bool father_found = false;\n while (father_found == false)\n {\n if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)\n { level_father_neighbor_entity = coarse_father_test; }\n\n if (coarse_father_test->hasFather() == false)\n { father_found = true; } else\n { coarse_father_test = coarse_father_test->father(); }\n }\n\n if ( !(level_father_neighbor_entity == level_father_entity) )\n {\n all_neighbors_have_same_father = false;\n }\n } else {\n all_neighbors_have_same_father = false;\n }\n }\n\n if (all_neighbors_have_same_father == true)\n { continue; }\n\n int layers = specifier_.getLayer(father_index);\n if (layers > 0)\n {\n HostEntityPointerType hep(*host_it);\n enrichment(hep, level_father_entity, specifier, father_index,\n hostGridPart, *subGridList_[father_index], entities_sharing_same_node, layers, enriched);\n }\n }\n\n for (int i = 0; i < number_of_coarse_grid_entities; ++i)\n {\n subGridList_[i]->createEnd();\n if (!silent_)\n {\n std::cout << \"Subgrid \" << i << \":\" << std::endl;\n subGridList_[i]->report();\n }\n\n if (subGridList_[i]->size(2) == 0)\n {\n std::cout << \"Error.\" << std::endl;\n std::cout << \"Error. Created Subgrid with 0 nodes.\" << std::endl;\n\n for (HostGridEntityIteratorType coarse_it = specifier_.coarseSpace().begin();\n coarse_it != specifier_.coarseSpace().end(); ++coarse_it)\n {\n const HostEntityType& coarse_entity = *coarse_it;\n int index = coarseGridLeafIndexSet.index(coarse_entity);\n if (i == index)\n {\n std::cout << \"We have a problem with the following coarse-grid element:\" << std::endl;\n std::cout << \"coarse element corner(0) = \" << coarse_it->geometry().corner(0) << std::endl;\n std::cout << \"coarse element corner(1) = \" << coarse_it->geometry().corner(1) << std::endl;\n std::cout << \"coarse element corner(2) = \" << coarse_it->geometry().corner(2) << std::endl << std::endl;\n }\n }\n abort();\n }\n }\n\n \/\/ ! ----------- end create subgrids --------------------\n }\n\n SubGridType& getSubGrid(int i) {\n const int size = specifier_.getNumOfCoarseEntities();\n\n if (i >= size)\n {\n DUNE_THROW(Dune::RangeError, \"Error. Subgrid-Index too large.\");\n }\n return *(subGridList_[i]);\n } \/\/ getSubGrid\n\nprivate:\n const HostDiscreteFunctionSpaceType& hostSpace_;\n MacroMicroGridSpecifierType& specifier_;\n\n bool silent_;\n\n SubGridType** subGridList_;\n\npublic:\n \/\/ Destruktor (Dynamisch angeforderter Speicher wird wieder freigegeben)\n ~SubGridList() {\n const int size = specifier_.getNumOfCoarseEntities();\n\n for (int i = 0; i < size; ++i)\n delete subGridList_[i];\n delete[] subGridList_;\n }\n};\n}\n\n#endif \/\/ #ifndef SUBGRIDLIST_HH\n<|endoftext|>"} {"text":"\/* Copyright 2016 Carnegie Mellon University\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"scanner\/evaluators\/caffe\/default\/default_input_evaluator.h\"\n#include \"scanner\/util\/memory.h\"\n\nnamespace scanner {\n\nDefaultInputEvaluator::DefaultInputEvaluator(DeviceType device_type,\n i32 device_id,\n const NetDescriptor& descriptor,\n i32 batch_size)\n : device_type_(device_type),\n device_id_(device_id),\n descriptor_(descriptor),\n batch_size_(batch_size)\n#ifdef HAVE_CUDA\n ,\n num_cuda_streams_(32),\n streams_(num_cuda_streams_)\n#endif\n\n{\n if (descriptor_.input_width != -1) {\n net_input_width_ = descriptor_.input_width;\n net_input_height_ = descriptor_.input_height;\n } else {\n net_input_width_ = -1;\n net_input_height_ = -1;\n }\n\n if (device_type_ == DeviceType::CPU) {\n std::vector& mean_colors = descriptor_.mean_colors;\n caffe::TransformationParameter param;\n param.set_force_color(true);\n param.set_scale(1.0 \/ 255.0);\n for (i32 i = 0; i < mean_colors.size(); i++) {\n param.add_mean_value(mean_colors[i]);\n }\n transformer_ =\n std::make_unique>(param, caffe::TEST);\n }\n}\n\nvoid DefaultInputEvaluator::configure(const VideoMetadata& metadata) {\n metadata_ = metadata;\n\n i32 width = metadata.width();\n i32 height = metadata.height();\n if (net_input_width_ == -1) {\n net_input_width_ = width;\n net_input_height_ = height;\n }\n\n output_blob_.Reshape(batch_size_, 3, net_input_height_, net_input_width_);\n\n if (device_type_ == DeviceType::GPU) {\n#ifdef HAVE_CUDA\n cv::cuda::setDevice(device_id_);\n cudaSetDevice(device_id_);\n\n mean_mat_g_ = cv::cuda::GpuMat(\n net_input_height_, net_input_width_, CV_32FC3,\n cv::Scalar(descriptor_.mean_colors[0], descriptor_.mean_colors[1],\n descriptor_.mean_colors[2]));\n\n frame_input_g_.clear();\n float_input_g_.clear();\n normalized_input_g_.clear();\n input_planes_g_.clear();\n planar_input_g_.clear();\n for (size_t i = 0; i < num_cuda_streams_; ++i) {\n frame_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n float_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n meanshifted_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n normalized_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n std::vector planes;\n for (i32 i = 0; i < 3; ++i) {\n planes.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC1));\n }\n input_planes_g_.push_back(planes);\n planar_input_g_.push_back(\n cv::cuda::GpuMat(net_input_width_ * 3, net_input_height_, CV_32FC1));\n }\n#else\n LOG(FATAL) << \"Not built with Cuda support.\";\n#endif\n } else {\n resized_input_c_ = cv::Mat(net_input_height_, net_input_width_, CV_8UC3);\n for (i32 i = 0; i < batch_size_; ++i) {\n input_mats_c_.emplace_back(\n cv::Mat(net_input_height_, net_input_width_, CV_8UC3));\n }\n }\n}\n\nvoid DefaultInputEvaluator::evaluate(\n const std::vector>& input_buffers,\n const std::vector>& input_sizes,\n std::vector>& output_buffers,\n std::vector>& output_sizes) {\n auto eval_start = now();\n\n size_t frame_size = net_input_width_ * net_input_height_ * 3 * sizeof(float);\n i32 input_count = input_buffers[0].size();\n\n if (device_type_ == DeviceType::GPU) {\n#ifdef HAVE_CUDA\n streams_.resize(0);\n streams_.resize(num_cuda_streams_);\n\n for (i32 frame = 0; frame < input_count; frame += batch_size_) {\n i32 batch_count = std::min(input_count - frame, batch_size_);\n\n f32* net_input = nullptr;\n i32 net_input_size = frame_size * batch_count;\n cudaMalloc((void**)&net_input, net_input_size);\n\n for (i32 i = 0; i < batch_count; ++i) {\n int sid = i % num_cuda_streams_;\n cv::cuda::Stream& cv_stream = streams_[sid];\n\n u8* buffer = input_buffers[0][frame + i];\n frame_input_g_[sid] = cv::cuda::GpuMat(\n net_input_height_, net_input_width_, CV_8UC3, buffer);\n cv::cuda::cvtColor(frame_input_g_[sid], frame_input_g_[sid],\n CV_RGB2BGR);\n frame_input_g_[sid].convertTo(float_input_g_[sid], CV_32FC3, cv_stream);\n cv::cuda::subtract(float_input_g_[sid], mean_mat_g_,\n meanshifted_input_g_[sid], cv::noArray(), -1,\n cv_stream);\n cv::cuda::divide(meanshifted_input_g_[sid], 255.0,\n normalized_input_g_[sid]);\n \/\/ Changed from interleaved RGB to planar RGB\n cv::cuda::split(normalized_input_g_[sid], input_planes_g_[sid],\n cv_stream);\n auto& plane1 = input_planes_g_[sid][0];\n auto& plane2 = input_planes_g_[sid][1];\n auto& plane3 = input_planes_g_[sid][2];\n auto& planar_input = planar_input_g_[sid];\n plane1.copyTo(planar_input(cv::Rect(\n 0, net_input_width_ * 0, net_input_height_, net_input_width_)));\n plane2.copyTo(planar_input(cv::Rect(\n 0, net_input_width_ * 1, net_input_height_, net_input_width_)));\n plane3.copyTo(planar_input(cv::Rect(\n 0, net_input_width_ * 2, net_input_height_, net_input_width_)));\n assert(planar_input.cols == net_input_height_);\n cudaStream_t s = cv::cuda::StreamAccessor::getStream(cv_stream);\n CU_CHECK(cudaMemcpy2DAsync(\n net_input + i * (net_input_width_ * net_input_height_ * 3),\n net_input_height_ * sizeof(float), planar_input.data,\n planar_input.step, net_input_height_ * sizeof(float),\n net_input_width_ * 3, cudaMemcpyDeviceToDevice, s));\n }\n for (cv::cuda::Stream& s : streams_) {\n s.waitForCompletion();\n }\n\n output_buffers[0].push_back((u8*)net_input);\n output_sizes[0].push_back(net_input_size);\n }\n\n i32 num_batches = output_buffers[0].size();\n for (i32 i = 0; i < input_buffers[0].size() - num_batches; ++i) {\n void* buf;\n cudaMalloc(&buf, 1);\n output_buffers[0].push_back((u8*)buf);\n output_sizes[0].push_back(1);\n }\n#else\n LOG(FATAL) << \"Not built with CUDA support.\";\n#endif \/\/ HAVE_CUDA\n } else {\n for (i32 frame = 0; frame < input_count; frame += batch_size_) {\n i32 batch_count = std::min(input_count - frame, batch_size_);\n\n i32 frame_width = metadata_.width();\n i32 frame_height = metadata_.height();\n\n for (i32 i = 0; i < batch_count; ++i) {\n u8* buffer = input_buffers[0][frame + i];\n cv::Mat input_mat(frame_height, frame_width, CV_8UC3, buffer);\n\n cv::resize(input_mat, resized_input_c_,\n cv::Size(net_input_width_, net_input_height_), 0, 0,\n cv::INTER_LINEAR);\n cv::cvtColor(resized_input_c_, input_mats_c_[i], CV_RGB2BGR);\n }\n\n std::vector input_mats_slice(\n input_mats_c_.begin(), input_mats_c_.begin() + batch_count);\n\n u8* net_input = new u8[frame_size * batch_count];\n output_blob_.set_cpu_data((f32*)net_input);\n output_blob_.Reshape(input_mats_slice.size(), output_blob_.shape(1),\n output_blob_.shape(2), output_blob_.shape(3));\n transformer_->Transform(input_mats_slice, &output_blob_);\n\n output_buffers[0].push_back(net_input);\n output_sizes[0].push_back(frame_size * batch_count);\n }\n\n i32 num_batches = output_buffers[0].size();\n for (i32 i = 0; i < input_buffers[0].size() - num_batches; ++i) {\n output_buffers[0].push_back(new u8[1]);\n output_sizes[0].push_back(1);\n }\n }\n\n for (i32 i = 0; i < input_buffers[0].size(); ++i) {\n size_t size = input_sizes[0][i];\n u8* buffer = new_buffer(device_type_, device_id_, size);\n memcpy_buffer(buffer, device_type_, device_id_, input_buffers[0][i],\n device_type_, device_id_, size);\n output_buffers[1].push_back(buffer);\n output_sizes[1].push_back(size);\n }\n\n if (profiler_) {\n profiler_->add_interval(\"caffe:transform_input\", eval_start, now());\n }\n}\n\nDefaultInputEvaluatorFactory::DefaultInputEvaluatorFactory(\n DeviceType device_type, const NetDescriptor& descriptor, i32 batch_size)\n : device_type_(device_type),\n net_descriptor_(descriptor),\n batch_size_(batch_size) {}\n\nEvaluatorCapabilities DefaultInputEvaluatorFactory::get_capabilities() {\n EvaluatorCapabilities caps;\n caps.device_type = device_type_;\n if (device_type_ == DeviceType::GPU) {\n caps.max_devices = 1;\n } else {\n caps.max_devices = EvaluatorCapabilities::UnlimitedDevices;\n }\n caps.warmup_size = 0;\n return caps;\n}\n\nstd::vector DefaultInputEvaluatorFactory::get_output_names() {\n return {\"net_input\", \"frame\"};\n}\n\nEvaluator* DefaultInputEvaluatorFactory::new_evaluator(\n const EvaluatorConfig& config) {\n return new DefaultInputEvaluator(device_type_, config.device_ids[0],\n net_descriptor_, batch_size_);\n}\n}\nmake_unique only supported by C++14 compilers\/* Copyright 2016 Carnegie Mellon University\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"scanner\/evaluators\/caffe\/default\/default_input_evaluator.h\"\n#include \"scanner\/util\/memory.h\"\n\n#ifdef HAVE_CUDA\n#include \n#endif\n\nnamespace scanner {\n\nDefaultInputEvaluator::DefaultInputEvaluator(DeviceType device_type,\n i32 device_id,\n const NetDescriptor& descriptor,\n i32 batch_size)\n : device_type_(device_type),\n device_id_(device_id),\n descriptor_(descriptor),\n batch_size_(batch_size)\n#ifdef HAVE_CUDA\n ,\n num_cuda_streams_(32),\n streams_(num_cuda_streams_)\n#endif\n\n{\n if (descriptor_.input_width != -1) {\n net_input_width_ = descriptor_.input_width;\n net_input_height_ = descriptor_.input_height;\n } else {\n net_input_width_ = -1;\n net_input_height_ = -1;\n }\n\n if (device_type_ == DeviceType::CPU) {\n std::vector& mean_colors = descriptor_.mean_colors;\n caffe::TransformationParameter param;\n param.set_force_color(true);\n param.set_scale(1.0 \/ 255.0);\n for (i32 i = 0; i < mean_colors.size(); i++) {\n param.add_mean_value(mean_colors[i]);\n }\n transformer_.reset(new caffe::DataTransformer(param, caffe::TEST));\n }\n}\n\nvoid DefaultInputEvaluator::configure(const VideoMetadata& metadata) {\n metadata_ = metadata;\n\n i32 width = metadata.width();\n i32 height = metadata.height();\n if (net_input_width_ == -1) {\n net_input_width_ = width;\n net_input_height_ = height;\n }\n\n output_blob_.Reshape(batch_size_, 3, net_input_height_, net_input_width_);\n\n if (device_type_ == DeviceType::GPU) {\n#ifdef HAVE_CUDA\n cv::cuda::setDevice(device_id_);\n cudaSetDevice(device_id_);\n\n mean_mat_g_ = cv::cuda::GpuMat(\n net_input_height_, net_input_width_, CV_32FC3,\n\n cv::Scalar(descriptor_.mean_colors[0], descriptor_.mean_colors[1],\n descriptor_.mean_colors[2]));\n\n frame_input_g_.clear();\n float_input_g_.clear();\n normalized_input_g_.clear();\n input_planes_g_.clear();\n planar_input_g_.clear();\n for (size_t i = 0; i < num_cuda_streams_; ++i) {\n frame_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n float_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n meanshifted_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n normalized_input_g_.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC3));\n std::vector planes;\n for (i32 i = 0; i < 3; ++i) {\n planes.push_back(\n cv::cuda::GpuMat(net_input_height_, net_input_width_, CV_32FC1));\n }\n input_planes_g_.push_back(planes);\n planar_input_g_.push_back(\n cv::cuda::GpuMat(net_input_width_ * 3, net_input_height_, CV_32FC1));\n }\n#else\n LOG(FATAL) << \"Not built with Cuda support.\";\n#endif\n } else {\n resized_input_c_ = cv::Mat(net_input_height_, net_input_width_, CV_8UC3);\n for (i32 i = 0; i < batch_size_; ++i) {\n input_mats_c_.emplace_back(\n cv::Mat(net_input_height_, net_input_width_, CV_8UC3));\n }\n }\n}\n\nvoid DefaultInputEvaluator::evaluate(\n const std::vector>& input_buffers,\n const std::vector>& input_sizes,\n std::vector>& output_buffers,\n std::vector>& output_sizes) {\n auto eval_start = now();\n\n size_t frame_size = net_input_width_ * net_input_height_ * 3 * sizeof(float);\n i32 input_count = input_buffers[0].size();\n\n if (device_type_ == DeviceType::GPU) {\n#ifdef HAVE_CUDA\n streams_.resize(0);\n streams_.resize(num_cuda_streams_);\n\n for (i32 frame = 0; frame < input_count; frame += batch_size_) {\n i32 batch_count = std::min(input_count - frame, batch_size_);\n\n f32* net_input = nullptr;\n i32 net_input_size = frame_size * batch_count;\n cudaMalloc((void**)&net_input, net_input_size);\n\n for (i32 i = 0; i < batch_count; ++i) {\n int sid = i % num_cuda_streams_;\n cv::cuda::Stream& cv_stream = streams_[sid];\n\n u8* buffer = input_buffers[0][frame + i];\n frame_input_g_[sid] = cv::cuda::GpuMat(\n net_input_height_, net_input_width_, CV_8UC3, buffer);\n cv::cuda::cvtColor(frame_input_g_[sid], frame_input_g_[sid],\n CV_RGB2BGR);\n frame_input_g_[sid].convertTo(float_input_g_[sid], CV_32FC3, cv_stream);\n cv::cuda::subtract(float_input_g_[sid], mean_mat_g_,\n meanshifted_input_g_[sid], cv::noArray(), -1,\n cv_stream);\n cv::cuda::divide(meanshifted_input_g_[sid], 255.0,\n normalized_input_g_[sid]);\n \/\/ Changed from interleaved RGB to planar RGB\n cv::cuda::split(normalized_input_g_[sid], input_planes_g_[sid],\n cv_stream);\n auto& plane1 = input_planes_g_[sid][0];\n auto& plane2 = input_planes_g_[sid][1];\n auto& plane3 = input_planes_g_[sid][2];\n auto& planar_input = planar_input_g_[sid];\n plane1.copyTo(planar_input(cv::Rect(\n 0, net_input_width_ * 0, net_input_height_, net_input_width_)));\n plane2.copyTo(planar_input(cv::Rect(\n 0, net_input_width_ * 1, net_input_height_, net_input_width_)));\n plane3.copyTo(planar_input(cv::Rect(\n 0, net_input_width_ * 2, net_input_height_, net_input_width_)));\n assert(planar_input.cols == net_input_height_);\n cudaStream_t s = cv::cuda::StreamAccessor::getStream(cv_stream);\n CU_CHECK(cudaMemcpy2DAsync(\n net_input + i * (net_input_width_ * net_input_height_ * 3),\n net_input_height_ * sizeof(float), planar_input.data,\n planar_input.step, net_input_height_ * sizeof(float),\n net_input_width_ * 3, cudaMemcpyDeviceToDevice, s));\n }\n for (cv::cuda::Stream& s : streams_) {\n s.waitForCompletion();\n }\n\n output_buffers[0].push_back((u8*)net_input);\n output_sizes[0].push_back(net_input_size);\n }\n\n i32 num_batches = output_buffers[0].size();\n for (i32 i = 0; i < input_buffers[0].size() - num_batches; ++i) {\n void* buf;\n cudaMalloc(&buf, 1);\n output_buffers[0].push_back((u8*)buf);\n output_sizes[0].push_back(1);\n }\n#else\n LOG(FATAL) << \"Not built with CUDA support.\";\n#endif \/\/ HAVE_CUDA\n } else {\n for (i32 frame = 0; frame < input_count; frame += batch_size_) {\n i32 batch_count = std::min(input_count - frame, batch_size_);\n\n i32 frame_width = metadata_.width();\n i32 frame_height = metadata_.height();\n\n for (i32 i = 0; i < batch_count; ++i) {\n u8* buffer = input_buffers[0][frame + i];\n cv::Mat input_mat(frame_height, frame_width, CV_8UC3, buffer);\n\n cv::resize(input_mat, resized_input_c_,\n cv::Size(net_input_width_, net_input_height_), 0, 0,\n cv::INTER_LINEAR);\n cv::cvtColor(resized_input_c_, input_mats_c_[i], CV_RGB2BGR);\n }\n\n std::vector input_mats_slice(\n input_mats_c_.begin(), input_mats_c_.begin() + batch_count);\n\n u8* net_input = new u8[frame_size * batch_count];\n output_blob_.set_cpu_data((f32*)net_input);\n output_blob_.Reshape(input_mats_slice.size(), output_blob_.shape(1),\n output_blob_.shape(2), output_blob_.shape(3));\n transformer_->Transform(input_mats_slice, &output_blob_);\n\n output_buffers[0].push_back(net_input);\n output_sizes[0].push_back(frame_size * batch_count);\n }\n\n i32 num_batches = output_buffers[0].size();\n for (i32 i = 0; i < input_buffers[0].size() - num_batches; ++i) {\n output_buffers[0].push_back(new u8[1]);\n output_sizes[0].push_back(1);\n }\n }\n\n for (i32 i = 0; i < input_buffers[0].size(); ++i) {\n size_t size = input_sizes[0][i];\n u8* buffer = new_buffer(device_type_, device_id_, size);\n memcpy_buffer(buffer, device_type_, device_id_, input_buffers[0][i],\n device_type_, device_id_, size);\n output_buffers[1].push_back(buffer);\n output_sizes[1].push_back(size);\n }\n\n if (profiler_) {\n profiler_->add_interval(\"caffe:transform_input\", eval_start, now());\n }\n}\n\nDefaultInputEvaluatorFactory::DefaultInputEvaluatorFactory(\n DeviceType device_type, const NetDescriptor& descriptor, i32 batch_size)\n : device_type_(device_type),\n net_descriptor_(descriptor),\n batch_size_(batch_size) {}\n\nEvaluatorCapabilities DefaultInputEvaluatorFactory::get_capabilities() {\n EvaluatorCapabilities caps;\n caps.device_type = device_type_;\n if (device_type_ == DeviceType::GPU) {\n caps.max_devices = 1;\n } else {\n caps.max_devices = EvaluatorCapabilities::UnlimitedDevices;\n }\n caps.warmup_size = 0;\n return caps;\n}\n\nstd::vector DefaultInputEvaluatorFactory::get_output_names() {\n return {\"net_input\", \"frame\"};\n}\n\nEvaluator* DefaultInputEvaluatorFactory::new_evaluator(\n const EvaluatorConfig& config) {\n return new DefaultInputEvaluator(device_type_, config.device_ids[0],\n net_descriptor_, batch_size_);\n}\n}\n<|endoftext|>"} {"text":"\/\/ \n\/\/ Copyright (C) 2006 SIPfoundry Inc. \n\/\/ Licensed by SIPfoundry under the LGPL license. \n\/\/ \n\/\/ Copyright (C) 2006 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/ \n\/\/ $$ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\n#include \n#include \n#include \n\n#include \"mp\/MpInputDeviceManager.h\"\n#include \"mp\/MprFromInputDevice.h\"\n#include \"mp\/MpOutputDeviceManager.h\"\n#include \"mp\/MprToOutputDevice.h\"\n#include \"mp\/MpFlowGraphBase.h\"\n#include \"mp\/MpMisc.h\"\n#include \"os\/OsTask.h\"\n#ifdef RTL_ENABLED\n# include \n#else\n# define RTL_BLOCK(x)\n# define RTL_EVENT(x,y)\n#endif\n\n#include \n\n#define TEST_TIME_MS 10000 \/\/\/< Time to runs test (in milliseconds)\n#define AUDIO_BUFS_NUM 500 \/\/\/< Number of buffers in buffer pool we'll use.\n#define BUFFERS_TO_BUFFER_ON_INPUT 3 \/\/\/< Number of buffers to buffer in input manager.\n#define BUFFERS_TO_BUFFER_ON_OUTPUT 0 \/\/\/< Number of buffers to buffer in output manager.\n\n#define TEST_SAMPLES_PER_FRAME 80 \/\/\/< in samples\n#define TEST_SAMPLES_PER_SECOND 8000 \/\/\/< in samples\/sec (Hz)\n\n#define BUFFER_ON_OUTPUT_MS (BUFFERS_TO_BUFFER_ON_OUTPUT*TEST_SAMPLES_PER_FRAME*1000\/TEST_SAMPLES_PER_SECOND)\n \/\/\/< Buffer size in output manager in milliseconds.\n\n\/\/#define USE_TEST_INPUT_DRIVER\n\/\/#define USE_TEST_OUTPUT_DRIVER\n\n#ifdef USE_TEST_INPUT_DRIVER \/\/ USE_TEST_DRIVER [\n#error Not supported platform!\n\n#elif defined(WIN32) \/\/ USE_TEST_DRIVER ][ WIN32\n#include \n#define INPUT_DRIVER MpInputDeviceDriverWnt\n#define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) \"SoundMAX HD Audio\", (manager)\n\n#elif defined(__pingtel_on_posix__) \/\/ WIN32 ][ __pingtel_on_posix__\n#include \n#define INPUT_DRIVER MpidOSS\n#define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) \"\/dev\/dsp\", (manager)\n\n#else \/\/ __pingtel_on_possix__ ]\n#error Unknown platform!\n#endif\n\n#ifdef USE_TEST_OUTPUT_DRIVER \/\/ USE_TEST_DRIVER [\n#include \n#define OUTPUT_DRIVER MpodBufferRecorder\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"default\", TEST_TIME_MS\n\n#elif defined(WIN32) \/\/ USE_TEST_DRIVER ][ WIN32\n#error No output driver for Windows exist!\n\n#elif defined(__pingtel_on_posix__) \/\/ WIN32 ][ __pingtel_on_posix__\n#include \n#define OUTPUT_DRIVER MpodOSS\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"\/dev\/dsp\"\n\n#else \/\/ __pingtel_on_possix__ ]\n#error Unknown platform!\n#endif\n\n\n\/\/\/ Unit test for MprSplitter\nclass MpInputOutputFrameworkTest : public CppUnit::TestCase\n{\n CPPUNIT_TEST_SUITE(MpInputOutputFrameworkTest);\n CPPUNIT_TEST(testShortCircuit);\n CPPUNIT_TEST_SUITE_END();\n\nprotected:\n MpFlowGraphBase* mpFlowGraph; \/\/\/< Flowgraph for our fromInputDevice and\n \/\/\/< toOutputDevice resources.\n\npublic:\n\n void setUp()\n {\n \/\/ Setup media task\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n mpStartUp(TEST_SAMPLES_PER_SECOND, TEST_SAMPLES_PER_FRAME, 6*10, 0));\n\n mpFlowGraph = new MpFlowGraphBase( TEST_SAMPLES_PER_FRAME\n , TEST_SAMPLES_PER_SECOND);\n CPPUNIT_ASSERT(mpFlowGraph != NULL);\n }\n\n void tearDown()\n {\n \/\/ This should normally be done by haltFramework, but if we aborted due\n \/\/ to an assertion the flowgraph will need to be shutdown here\n if (mpFlowGraph && mpFlowGraph->isStarted())\n {\n osPrintf(\"WARNING: flowgraph found still running, shutting down\\n\");\n\n \/\/ ignore the result and keep going\n mpFlowGraph->stop();\n\n \/\/ Request processing of another frame so that the STOP_FLOWGRAPH\n \/\/ message gets handled\n mpFlowGraph->processNextFrame();\n }\n\n \/\/ Free flowgraph resources\n delete mpFlowGraph;\n mpFlowGraph = NULL;\n\n \/\/ Clear all Media Tasks data\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpShutdown());\n }\n\n void testShortCircuit()\n {\n#ifdef RTL_ENABLED\n RTL_START(1000000);\n#endif\n\n \/\/ Create input and output device managers\n MpInputDeviceManager inputDeviceManager(TEST_SAMPLES_PER_FRAME, \n TEST_SAMPLES_PER_SECOND,\n BUFFERS_TO_BUFFER_ON_INPUT,\n *MpMisc.RawAudioPool);\n MpOutputDeviceManager outputDeviceManager(TEST_SAMPLES_PER_FRAME,\n TEST_SAMPLES_PER_SECOND,\n BUFFER_ON_OUTPUT_MS);\n\n\n \/\/ Create source (input) device and add it to manager.\n INPUT_DRIVER sourceDevice(INPUT_DRIVER_CONSTRUCTOR_PARAMS(inputDeviceManager));\n MpInputDeviceHandle sourceDeviceId = inputDeviceManager.addDevice(sourceDevice);\n CPPUNIT_ASSERT(sourceDeviceId > 0);\n CPPUNIT_ASSERT(!inputDeviceManager.isDeviceEnabled(sourceDeviceId));\n\n \/\/ Create sink (output) device and add it to manager.\n OUTPUT_DRIVER sinkDevice(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n MpOutputDeviceHandle sinkDeviceId = outputDeviceManager.addDevice(&sinkDevice);\n CPPUNIT_ASSERT(sinkDeviceId > 0);\n CPPUNIT_ASSERT(!outputDeviceManager.isDeviceEnabled(sinkDeviceId));\n\n \/\/ Create source (input) and sink (output) resources.\n MprFromInputDevice pSource(\"MprFromInputDevice\",\n TEST_SAMPLES_PER_FRAME,\n TEST_SAMPLES_PER_SECOND,\n &inputDeviceManager,\n sourceDeviceId);\n MprToOutputDevice pSink(\"MprToOutputDevice\",\n TEST_SAMPLES_PER_FRAME,\n TEST_SAMPLES_PER_SECOND,\n &outputDeviceManager,\n sinkDeviceId);\n\n \/\/ Add source and sink resources to flowgraph and link them together.\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSource));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSink));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addLink(pSource, 0, pSink, 0));\n\n \/\/ Enable devices\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n inputDeviceManager.enableDevice(sourceDeviceId));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n outputDeviceManager.enableDevice(sinkDeviceId));\n \n \/\/ Enable resources\n CPPUNIT_ASSERT(pSource.enable());\n CPPUNIT_ASSERT(pSink.enable());\n\n mpFlowGraph->start();\n\n \/\/ Run test!\n for (int i=0; i i=%d\\n\",i);\n OsTask::delay(TEST_SAMPLES_PER_FRAME*1000\/TEST_SAMPLES_PER_SECOND-2);\n RTL_EVENT(\"test loop body\", 2);\n mpFlowGraph->processNextFrame();\n }\n\n \/\/ Disable resources\n CPPUNIT_ASSERT(pSource.disable());\n CPPUNIT_ASSERT(pSink.disable());\n mpFlowGraph->processNextFrame();\n\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->stop());\n mpFlowGraph->processNextFrame();\n\n#ifdef USE_TEST_OUTPUT_DRIVER \/\/ [\n OsFile::openAndWrite(\"capture.raw\",\n (const char*)sinkDevice.getBufferData(),\n sinkDevice.getBufferLength()*sizeof(MpAudioSample));\n#endif \/\/ USE_TEST_OUTPUT_DRIVER ]\n\n \/\/ Disable devices\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n inputDeviceManager.disableDevice(sourceDeviceId));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n outputDeviceManager.disableDevice(sinkDeviceId));\n\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSink));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSource));\n mpFlowGraph->processNextFrame();\n\n OsTask::delay(10);\n\n#ifdef RTL_ENABLED\n RTL_WRITE(\"testShortCircuit.rtl\");\n#endif\n\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(MpInputOutputFrameworkTest);\nMpInputOutputFrameworkTest updated to support new native flowgraph ticker.\/\/ \n\/\/ Copyright (C) 2006 SIPfoundry Inc. \n\/\/ Licensed by SIPfoundry under the LGPL license. \n\/\/ \n\/\/ Copyright (C) 2006 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/ \n\/\/ $$ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\n#include \n#include \n#include \n\n#include \"mp\/MpInputDeviceManager.h\"\n#include \"mp\/MprFromInputDevice.h\"\n#include \"mp\/MpOutputDeviceManager.h\"\n#include \"mp\/MprToOutputDevice.h\"\n#include \"mp\/MpFlowGraphBase.h\"\n#include \"mp\/MpMisc.h\"\n#include \"mp\/MpMediaTask.h\"\n#include \"os\/OsTask.h\"\n#ifdef RTL_ENABLED\n# include \n#else\n# define RTL_BLOCK(x)\n# define RTL_EVENT(x,y)\n#endif\n\n#include \n\n#define TEST_TIME_MS 10000 \/\/\/< Time to runs test (in milliseconds)\n#define AUDIO_BUFS_NUM 500 \/\/\/< Number of buffers in buffer pool we'll use.\n#define BUFFERS_TO_BUFFER_ON_INPUT 3 \/\/\/< Number of buffers to buffer in input manager.\n#define BUFFERS_TO_BUFFER_ON_OUTPUT 0 \/\/\/< Number of buffers to buffer in output manager.\n\n#define TEST_SAMPLES_PER_FRAME 80 \/\/\/< in samples\n#define TEST_SAMPLES_PER_SECOND 8000 \/\/\/< in samples\/sec (Hz)\n\n#define BUFFER_ON_OUTPUT_MS (BUFFERS_TO_BUFFER_ON_OUTPUT*TEST_SAMPLES_PER_FRAME*1000\/TEST_SAMPLES_PER_SECOND)\n \/\/\/< Buffer size in output manager in milliseconds.\n\n\/\/#define USE_TEST_INPUT_DRIVER\n\/\/#define USE_TEST_OUTPUT_DRIVER\n\n#ifdef USE_TEST_INPUT_DRIVER \/\/ USE_TEST_DRIVER [\n#error Not supported platform!\n\n#elif defined(WIN32) \/\/ USE_TEST_DRIVER ][ WIN32\n#include \n#define INPUT_DRIVER MpInputDeviceDriverWnt\n#define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) \"SoundMAX HD Audio\", (manager)\n\n#elif defined(__pingtel_on_posix__) \/\/ WIN32 ][ __pingtel_on_posix__\n#include \n#define INPUT_DRIVER MpidOSS\n#define INPUT_DRIVER_CONSTRUCTOR_PARAMS(manager) \"\/dev\/dsp\", (manager)\n\n#else \/\/ __pingtel_on_possix__ ]\n#error Unknown platform!\n#endif\n\n#ifdef USE_TEST_OUTPUT_DRIVER \/\/ USE_TEST_DRIVER [\n#include \n#define OUTPUT_DRIVER MpodBufferRecorder\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"default\", TEST_TIME_MS\n\n#elif defined(WIN32) \/\/ USE_TEST_DRIVER ][ WIN32\n#error No output driver for Windows exist!\n\n#elif defined(__pingtel_on_posix__) \/\/ WIN32 ][ __pingtel_on_posix__\n#include \n#define OUTPUT_DRIVER MpodOSS\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"\/dev\/dsp\"\n\n#else \/\/ __pingtel_on_possix__ ]\n#error Unknown platform!\n#endif\n\n\n\/\/\/ Unit test for MprSplitter\nclass MpInputOutputFrameworkTest : public CppUnit::TestCase\n{\n CPPUNIT_TEST_SUITE(MpInputOutputFrameworkTest);\n CPPUNIT_TEST(testShortCircuit);\n CPPUNIT_TEST_SUITE_END();\n\nprotected:\n MpFlowGraphBase* mpFlowGraph; \/\/\/< Flowgraph for our fromInputDevice and\n \/\/\/< toOutputDevice resources.\n\npublic:\n\n void setUp()\n {\n \/\/ Setup media task\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n mpStartUp(TEST_SAMPLES_PER_SECOND, TEST_SAMPLES_PER_FRAME, 6*10, 0));\n\n mpFlowGraph = new MpFlowGraphBase( TEST_SAMPLES_PER_FRAME\n , TEST_SAMPLES_PER_SECOND);\n CPPUNIT_ASSERT(mpFlowGraph != NULL);\n\n \/\/ Call getMediaTask() which causes the task to get instantiated\n CPPUNIT_ASSERT(MpMediaTask::getMediaTask(10) != NULL);\n }\n\n void tearDown()\n {\n \/\/ This should normally be done by haltFramework, but if we aborted due\n \/\/ to an assertion the flowgraph will need to be shutdown here\n if (mpFlowGraph && mpFlowGraph->isStarted())\n {\n osPrintf(\"WARNING: flowgraph found still running, shutting down\\n\");\n\n \/\/ ignore the result and keep going\n mpFlowGraph->stop();\n\n \/\/ Request processing of another frame so that the STOP_FLOWGRAPH\n \/\/ message gets handled\n mpFlowGraph->processNextFrame();\n }\n\n \/\/ Free flowgraph resources\n delete mpFlowGraph;\n mpFlowGraph = NULL;\n\n \/\/ Clear all Media Tasks data\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpShutdown());\n }\n\n void testShortCircuit()\n {\n enableConsoleOutput(1);\n\n#ifdef RTL_ENABLED\n RTL_START(1000000);\n#endif\n\n \/\/ Get media processing task.\n MpMediaTask *pMediaTask = MpMediaTask::getMediaTask(10);\n\n \/\/ Create input and output device managers\n MpInputDeviceManager inputDeviceManager(TEST_SAMPLES_PER_FRAME, \n TEST_SAMPLES_PER_SECOND,\n BUFFERS_TO_BUFFER_ON_INPUT,\n *MpMisc.RawAudioPool);\n MpOutputDeviceManager outputDeviceManager(TEST_SAMPLES_PER_FRAME,\n TEST_SAMPLES_PER_SECOND,\n BUFFER_ON_OUTPUT_MS);\n\n\n \/\/ Create source (input) device and add it to manager.\n INPUT_DRIVER sourceDevice(INPUT_DRIVER_CONSTRUCTOR_PARAMS(inputDeviceManager));\n MpInputDeviceHandle sourceDeviceId = inputDeviceManager.addDevice(sourceDevice);\n CPPUNIT_ASSERT(sourceDeviceId > 0);\n CPPUNIT_ASSERT(!inputDeviceManager.isDeviceEnabled(sourceDeviceId));\n\n \/\/ Create sink (output) device and add it to manager.\n OUTPUT_DRIVER sinkDevice(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n MpOutputDeviceHandle sinkDeviceId = outputDeviceManager.addDevice(&sinkDevice);\n CPPUNIT_ASSERT(sinkDeviceId > 0);\n CPPUNIT_ASSERT(!outputDeviceManager.isDeviceEnabled(sinkDeviceId));\n\n \/\/ Create source (input) and sink (output) resources.\n MprFromInputDevice pSource(\"MprFromInputDevice\",\n TEST_SAMPLES_PER_FRAME,\n TEST_SAMPLES_PER_SECOND,\n &inputDeviceManager,\n sourceDeviceId);\n MprToOutputDevice pSink(\"MprToOutputDevice\",\n TEST_SAMPLES_PER_FRAME,\n TEST_SAMPLES_PER_SECOND,\n &outputDeviceManager,\n sinkDeviceId);\n\n \/\/ Add source and sink resources to flowgraph and link them together.\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSource));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(pSink));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addLink(pSource, 0, pSink, 0));\n\n \/\/ Enable devices\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n inputDeviceManager.enableDevice(sourceDeviceId));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n outputDeviceManager.enableDevice(sinkDeviceId));\n\n \/\/ Set flowgraph ticker\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n outputDeviceManager.setFlowgraphTickerSource(sinkDeviceId));\n \n \/\/ Enable resources\n CPPUNIT_ASSERT(pSource.enable());\n CPPUNIT_ASSERT(pSink.enable());\n\n \/\/ Manage flowgraph with media task.\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->manageFlowGraph(*mpFlowGraph));\n\n \/\/ Start flowgraph\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->startFlowGraph(*mpFlowGraph));\n\n \/\/ Run test!\n OsTask::delay(TEST_TIME_MS);\n\/* for (int i=0; i i=%d\\n\",i);\n OsTask::delay(TEST_SAMPLES_PER_FRAME*1000\/TEST_SAMPLES_PER_SECOND-2);\n RTL_EVENT(\"test loop body\", 2);\n MpMediaTask::signalFrameStart();\n }\n*\/\n\n \/\/ Stop flowgraph\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->stopFlowGraph(*mpFlowGraph));\n OsTask::delay(20);\n\n \/\/ Unmanage flowgraph with media task.\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMediaTask->unmanageFlowGraph(*mpFlowGraph));\n\n \/\/ Disable resources\n CPPUNIT_ASSERT(pSource.disable());\n CPPUNIT_ASSERT(pSink.disable());\n mpFlowGraph->processNextFrame();\n\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->stop());\n mpFlowGraph->processNextFrame();\n\n#ifdef USE_TEST_OUTPUT_DRIVER \/\/ [\n OsFile::openAndWrite(\"capture.raw\",\n (const char*)sinkDevice.getBufferData(),\n sinkDevice.getBufferLength()*sizeof(MpAudioSample));\n#endif \/\/ USE_TEST_OUTPUT_DRIVER ]\n\n \/\/ Disable devices\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n inputDeviceManager.disableDevice(sourceDeviceId));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n outputDeviceManager.disableDevice(sinkDeviceId));\n\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSink));\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(pSource));\n mpFlowGraph->processNextFrame();\n\n OsTask::delay(10);\n\n#ifdef RTL_ENABLED\n RTL_WRITE(\"testShortCircuit.rtl\");\n#endif\n\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(MpInputOutputFrameworkTest);\n<|endoftext|>"} {"text":"#include \"iostream\"\n#include \"class_double_list.h\"\n\n\nint main(){\n List*head, *cur;\n int num;\n cout << \"a= \";\n cin >> num;\n head = createlist(num);\n cur = head;\n for (int i = 0; i < 9; i++) {\n cout << \"a = \";\n cin >> num;\n cur = addToend(cur, num);\n }\n printlist(head);\n cout << endl;\n \/\/ Удаляем элемент со значением 3\n deleteElem(&head, 3);\n printlist(head);\n cout << endl;\n \/\/Добавление элемента co значением 4 после элемента со значением 6\n addTomiddle(&head, 4, 6);\n printlist(head);\n cout << endl;\n \/\/ Сортировка элементов по возрастанию\n sort(&head);\n printlist(head);\n\n \n return 0;\n}\n\nmake new code#include \"stdafx.h\"\n#include \"double_linked_list.h\"\n\n\nint main()\n{\n\tint num;\n\tdouble_linked_list list;\n\tfor (int i = 1; i < 10; i++){\n\t\tcout << \"a= \";\n\t\tcin >> num;\n\t\tlist.append(num);\n\t}\n\tlist.printlist();\n\t\/\/Удаляем элемент со значением 4;\n\tlist.deleteElem(4);\n\tlist.printlist();\n\t\/\/Добавление элемента со значением 9 после 5;\n\tlist.insert(9, 5);\n\tlist.printlist();\n\t\/\/Сортировка списка по возрастанию\n\tlist.sort();\n\tlist.printlist();\n\tsystem(\"pause\");\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Vulkan\n *\n * Copyright (C) 2015 LunarG, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"loader_platform.h\"\n#include \"vk_dispatch_table_helper.h\"\n#include \"vkLayer.h\"\n\/\/ The following is #included again to catch certain OS-specific functions\n\/\/ being used:\n#include \"loader_platform.h\"\n\n#include \"SPIRV\/spirv.h\"\n\nstatic std::unordered_map tableMap;\n\n\nstruct shader_source {\n std::vector words;\n\n shader_source(VkShaderCreateInfo const *pCreateInfo) :\n words((uint32_t *)pCreateInfo->pCode, (uint32_t *)pCreateInfo->pCode + pCreateInfo->codeSize \/ sizeof(uint32_t)) {\n }\n};\n\n\nstatic std::unordered_map shader_map;\n\n\nstatic VkLayerDispatchTable * initLayerTable(const VkBaseLayerObject *gpuw)\n{\n VkLayerDispatchTable *pTable;\n\n assert(gpuw);\n std::unordered_map::const_iterator it = tableMap.find((void *) gpuw->baseObject);\n if (it == tableMap.end())\n {\n pTable = new VkLayerDispatchTable;\n tableMap[(void *) gpuw->baseObject] = pTable;\n } else\n {\n return it->second;\n }\n\n layer_initialize_dispatch_table(pTable, gpuw->pGPA, (VkPhysicalGpu) gpuw->nextObject);\n\n return pTable;\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalGpu gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice)\n{\n VkLayerDispatchTable* pTable = tableMap[gpu];\n VkResult result = pTable->CreateDevice(gpu, pCreateInfo, pDevice);\n \/\/ create a mapping for the device object into the dispatch table\n tableMap.emplace(*pDevice, pTable);\n return result;\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkEnumerateLayers(VkPhysicalGpu gpu, size_t maxLayerCount, size_t maxStringSize, size_t* pOutLayerCount, char* const* pOutLayers, void* pReserved)\n{\n if (pOutLayerCount == NULL || pOutLayers == NULL || pOutLayers[0] == NULL || pOutLayers[1] == NULL || pReserved == NULL)\n return VK_ERROR_INVALID_POINTER;\n\n if (maxLayerCount < 1)\n return VK_ERROR_INITIALIZATION_FAILED;\n *pOutLayerCount = 1;\n strncpy((char *) pOutLayers[0], \"ShaderChecker\", maxStringSize);\n return VK_SUCCESS;\n}\n\n\nstruct extProps {\n uint32_t version;\n const char * const name;\n};\n#define SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE 1\nstatic const struct extProps shaderCheckerExts[SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE] = {\n \/\/ TODO what is the version?\n 0x10, \"ShaderChecker\",\n};\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionInfo(\n VkExtensionInfoType infoType,\n uint32_t extensionIndex,\n size_t* pDataSize,\n void* pData)\n{\n VkResult result;\n\n \/* This entrypoint is NOT going to init it's own dispatch table since loader calls here early *\/\n VkExtensionProperties *ext_props;\n uint32_t *count;\n\n if (pDataSize == NULL)\n return VK_ERROR_INVALID_POINTER;\n\n switch (infoType) {\n case VK_EXTENSION_INFO_TYPE_COUNT:\n *pDataSize = sizeof(uint32_t);\n if (pData == NULL)\n return VK_SUCCESS;\n count = (uint32_t *) pData;\n *count = SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE;\n break;\n case VK_EXTENSION_INFO_TYPE_PROPERTIES:\n *pDataSize = sizeof(VkExtensionProperties);\n if (pData == NULL)\n return VK_SUCCESS;\n if (extensionIndex >= SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE)\n return VK_ERROR_INVALID_VALUE;\n ext_props = (VkExtensionProperties *) pData;\n ext_props->version = shaderCheckerExts[extensionIndex].version;\n strncpy(ext_props->extName, shaderCheckerExts[extensionIndex].name,\n VK_MAX_EXTENSION_NAME);\n ext_props->extName[VK_MAX_EXTENSION_NAME - 1] = '\\0';\n break;\n default:\n return VK_ERROR_INVALID_VALUE;\n };\n\n return VK_SUCCESS;\n}\n\n\nstatic int\nvalue_or_default(std::unordered_map const &map, unsigned id, int def)\n{\n auto it = map.find(id);\n if (it == map.end())\n return def;\n else\n return it->second;\n}\n\n\nstruct interface_var {\n uint32_t id;\n uint32_t type_id;\n \/* TODO: collect the name, too? Isn't required to be present. *\/\n};\n\n\nstatic void\ncollect_interface_by_location(shader_source const *src, spv::StorageClass interface,\n std::map &out,\n std::map &builtins_out)\n{\n unsigned int const *code = (unsigned int const *)&src->words[0];\n size_t size = src->words.size();\n\n if (code[0] != spv::MagicNumber) {\n printf(\"Invalid magic.\\n\");\n return;\n }\n\n std::unordered_map var_locations;\n std::unordered_map var_builtins;\n\n unsigned word = 5;\n while (word < size) {\n\n unsigned opcode = code[word] & 0x0ffffu;\n unsigned oplen = (code[word] & 0xffff0000u) >> 16;\n\n \/* We consider two interface models: SSO rendezvous-by-location, and\n * builtins. Complain about anything that fits neither model.\n *\/\n if (opcode == spv::OpDecorate) {\n if (code[word+2] == spv::DecLocation) {\n var_locations[code[word+1]] = code[word+3];\n }\n\n if (code[word+2] == spv::DecBuiltIn) {\n var_builtins[code[word+1]] = code[word+3];\n }\n }\n\n \/* TODO: handle grouped decorations *\/\n \/* TODO: handle index=1 dual source outputs from FS -- two vars will\n * have the same location, and we DONT want to clobber. *\/\n\n if (opcode == spv::OpVariable && code[word+3] == interface) {\n int location = value_or_default(var_locations, code[word+2], -1);\n int builtin = value_or_default(var_builtins, code[word+2], -1);\n\n if (location == -1 && builtin == -1) {\n \/* No location defined, and not bound to an API builtin.\n * The spec says nothing about how this case works (or doesn't)\n * for interface matching.\n *\/\n printf(\"WARN: var %d (type %d) in %s interface has no Location or Builtin decoration\\n\",\n code[word+2], code[word+1], interface == spv::StorageInput ? \"input\" : \"output\");\n }\n else if (location != -1) {\n \/* A user-defined interface variable, with a location. *\/\n interface_var v;\n v.id = code[word+2];\n v.type_id = code[word+1];\n out[location] = v;\n }\n else {\n \/* A builtin interface variable *\/\n interface_var v;\n v.id = code[word+2];\n v.type_id = code[word+1];\n builtins_out[builtin] = v;\n }\n }\n\n word += oplen;\n }\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkCreateShader(VkDevice device, const VkShaderCreateInfo *pCreateInfo,\n VkShader *pShader)\n{\n VkLayerDispatchTable* pTable = tableMap[(VkBaseLayerObject *)device];\n VkResult res = pTable->CreateShader(device, pCreateInfo, pShader);\n\n shader_map[(VkBaseLayerObject *) *pShader] = new shader_source(pCreateInfo);\n return res;\n}\n\n\nstatic void\nvalidate_interface_between_stages(shader_source const *producer, char const *producer_name,\n shader_source const *consumer, char const *consumer_name)\n{\n std::map outputs;\n std::map inputs;\n\n std::map builtin_outputs;\n std::map builtin_inputs;\n\n printf(\"Begin validate_interface_between_stages %s -> %s\\n\",\n producer_name, consumer_name);\n\n collect_interface_by_location(producer, spv::StorageOutput, outputs, builtin_outputs);\n collect_interface_by_location(consumer, spv::StorageInput, inputs, builtin_inputs);\n\n auto a_it = outputs.begin();\n auto b_it = inputs.begin();\n\n \/* maps sorted by key (location); walk them together to find mismatches *\/\n while (a_it != outputs.end() || b_it != inputs.end()) {\n if (b_it == inputs.end() || a_it->first < b_it->first) {\n printf(\" WARN: %s writes to output location %d which is not consumed by %s\\n\",\n producer_name, a_it->first, consumer_name);\n a_it++;\n }\n else if (a_it == outputs.end() || a_it->first > b_it->first) {\n printf(\" ERR: %s consumes input location %d which is not written by %s\\n\",\n consumer_name, b_it->first, producer_name);\n b_it++;\n }\n else {\n printf(\" OK: match on location %d\\n\",\n a_it->first);\n \/* TODO: typecheck *\/\n a_it++;\n b_it++;\n }\n }\n\n printf(\"End validate_interface_between_stages\\n\");\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkCreateGraphicsPipeline(VkDevice device,\n const VkGraphicsPipelineCreateInfo *pCreateInfo,\n VkPipeline *pPipeline)\n{\n \/* TODO: run cross-stage validation *\/\n \/* - Validate vertex fetch -> VS interface *\/\n \/* - Validate FS output -> CB *\/\n \/* - Support GS, TCS, TES stages *\/\n\n \/* We seem to allow pipeline stages to be specified out of order, so collect and identify them\n * before trying to do anything more: *\/\n\n shader_source const *vs_source = 0;\n shader_source const *fs_source = 0;\n VkPipelineCbStateCreateInfo const *cb = 0;\n VkPipelineVertexInputCreateInfo const *vi = 0;\n\n for (auto stage = pCreateInfo; stage; stage = (decltype(stage))stage->pNext) {\n if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO) {\n auto shader_stage = (VkPipelineShaderStageCreateInfo const *)stage;\n\n if (shader_stage->shader.stage == VK_SHADER_STAGE_VERTEX)\n vs_source = shader_map[(void *)(shader_stage->shader.shader)];\n else if (shader_stage->shader.stage == VK_SHADER_STAGE_FRAGMENT)\n fs_source = shader_map[(void *)(shader_stage->shader.shader)];\n else\n printf(\"Unknown shader stage %d\\n\", shader_stage->shader.stage);\n }\n else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_CB_STATE_CREATE_INFO) {\n cb = (VkPipelineCbStateCreateInfo const *)stage;\n }\n else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_CREATE_INFO) {\n vi = (VkPipelineVertexInputCreateInfo const *)stage;\n }\n }\n\n printf(\"Pipeline: vi=%p vs=%p fs=%p cb=%p\\n\", vi, vs_source, fs_source, cb);\n\n if (vs_source && fs_source) {\n validate_interface_between_stages(vs_source, \"vertex shader\",\n fs_source, \"fragment shader\");\n }\n\n VkLayerDispatchTable *pTable = tableMap[(VkBaseLayerObject *)device];\n VkResult res = pTable->CreateGraphicsPipeline(device, pCreateInfo, pPipeline);\n return res;\n}\n\n\nVK_LAYER_EXPORT void * VKAPI vkGetProcAddr(VkPhysicalGpu gpu, const char* pName)\n{\n if (gpu == NULL)\n return NULL;\n\n initLayerTable((const VkBaseLayerObject *) gpu);\n\n#define ADD_HOOK(fn) \\\n if (!strncmp(#fn, pName, sizeof(#fn))) \\\n return (void *) fn\n\n ADD_HOOK(vkGetProcAddr);\n ADD_HOOK(vkEnumerateLayers);\n ADD_HOOK(vkCreateDevice);\n ADD_HOOK(vkCreateShader);\n ADD_HOOK(vkCreateGraphicsPipeline);\n\n VkBaseLayerObject* gpuw = (VkBaseLayerObject *) gpu;\n if (gpuw->pGPA == NULL)\n return NULL;\n return gpuw->pGPA((VkPhysicalGpu) gpuw->nextObject, pName);\n}\nshader_checker: validate vertex attribs against vs inputs\/*\n * Vulkan\n *\n * Copyright (C) 2015 LunarG, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"loader_platform.h\"\n#include \"vk_dispatch_table_helper.h\"\n#include \"vkLayer.h\"\n\/\/ The following is #included again to catch certain OS-specific functions\n\/\/ being used:\n#include \"loader_platform.h\"\n\n#include \"SPIRV\/spirv.h\"\n\nstatic std::unordered_map tableMap;\n\n\nstruct shader_source {\n std::vector words;\n\n shader_source(VkShaderCreateInfo const *pCreateInfo) :\n words((uint32_t *)pCreateInfo->pCode, (uint32_t *)pCreateInfo->pCode + pCreateInfo->codeSize \/ sizeof(uint32_t)) {\n }\n};\n\n\nstatic std::unordered_map shader_map;\n\n\nstatic VkLayerDispatchTable * initLayerTable(const VkBaseLayerObject *gpuw)\n{\n VkLayerDispatchTable *pTable;\n\n assert(gpuw);\n std::unordered_map::const_iterator it = tableMap.find((void *) gpuw->baseObject);\n if (it == tableMap.end())\n {\n pTable = new VkLayerDispatchTable;\n tableMap[(void *) gpuw->baseObject] = pTable;\n } else\n {\n return it->second;\n }\n\n layer_initialize_dispatch_table(pTable, gpuw->pGPA, (VkPhysicalGpu) gpuw->nextObject);\n\n return pTable;\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalGpu gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice)\n{\n VkLayerDispatchTable* pTable = tableMap[gpu];\n VkResult result = pTable->CreateDevice(gpu, pCreateInfo, pDevice);\n \/\/ create a mapping for the device object into the dispatch table\n tableMap.emplace(*pDevice, pTable);\n return result;\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkEnumerateLayers(VkPhysicalGpu gpu, size_t maxLayerCount, size_t maxStringSize, size_t* pOutLayerCount, char* const* pOutLayers, void* pReserved)\n{\n if (pOutLayerCount == NULL || pOutLayers == NULL || pOutLayers[0] == NULL || pOutLayers[1] == NULL || pReserved == NULL)\n return VK_ERROR_INVALID_POINTER;\n\n if (maxLayerCount < 1)\n return VK_ERROR_INITIALIZATION_FAILED;\n *pOutLayerCount = 1;\n strncpy((char *) pOutLayers[0], \"ShaderChecker\", maxStringSize);\n return VK_SUCCESS;\n}\n\n\nstruct extProps {\n uint32_t version;\n const char * const name;\n};\n#define SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE 1\nstatic const struct extProps shaderCheckerExts[SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE] = {\n \/\/ TODO what is the version?\n 0x10, \"ShaderChecker\",\n};\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionInfo(\n VkExtensionInfoType infoType,\n uint32_t extensionIndex,\n size_t* pDataSize,\n void* pData)\n{\n VkResult result;\n\n \/* This entrypoint is NOT going to init it's own dispatch table since loader calls here early *\/\n VkExtensionProperties *ext_props;\n uint32_t *count;\n\n if (pDataSize == NULL)\n return VK_ERROR_INVALID_POINTER;\n\n switch (infoType) {\n case VK_EXTENSION_INFO_TYPE_COUNT:\n *pDataSize = sizeof(uint32_t);\n if (pData == NULL)\n return VK_SUCCESS;\n count = (uint32_t *) pData;\n *count = SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE;\n break;\n case VK_EXTENSION_INFO_TYPE_PROPERTIES:\n *pDataSize = sizeof(VkExtensionProperties);\n if (pData == NULL)\n return VK_SUCCESS;\n if (extensionIndex >= SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE)\n return VK_ERROR_INVALID_VALUE;\n ext_props = (VkExtensionProperties *) pData;\n ext_props->version = shaderCheckerExts[extensionIndex].version;\n strncpy(ext_props->extName, shaderCheckerExts[extensionIndex].name,\n VK_MAX_EXTENSION_NAME);\n ext_props->extName[VK_MAX_EXTENSION_NAME - 1] = '\\0';\n break;\n default:\n return VK_ERROR_INVALID_VALUE;\n };\n\n return VK_SUCCESS;\n}\n\n\nstatic int\nvalue_or_default(std::unordered_map const &map, unsigned id, int def)\n{\n auto it = map.find(id);\n if (it == map.end())\n return def;\n else\n return it->second;\n}\n\n\nstruct interface_var {\n uint32_t id;\n uint32_t type_id;\n \/* TODO: collect the name, too? Isn't required to be present. *\/\n};\n\n\nstatic void\ncollect_interface_by_location(shader_source const *src, spv::StorageClass interface,\n std::map &out,\n std::map &builtins_out)\n{\n unsigned int const *code = (unsigned int const *)&src->words[0];\n size_t size = src->words.size();\n\n if (code[0] != spv::MagicNumber) {\n printf(\"Invalid magic.\\n\");\n return;\n }\n\n std::unordered_map var_locations;\n std::unordered_map var_builtins;\n\n unsigned word = 5;\n while (word < size) {\n\n unsigned opcode = code[word] & 0x0ffffu;\n unsigned oplen = (code[word] & 0xffff0000u) >> 16;\n\n \/* We consider two interface models: SSO rendezvous-by-location, and\n * builtins. Complain about anything that fits neither model.\n *\/\n if (opcode == spv::OpDecorate) {\n if (code[word+2] == spv::DecLocation) {\n var_locations[code[word+1]] = code[word+3];\n }\n\n if (code[word+2] == spv::DecBuiltIn) {\n var_builtins[code[word+1]] = code[word+3];\n }\n }\n\n \/* TODO: handle grouped decorations *\/\n \/* TODO: handle index=1 dual source outputs from FS -- two vars will\n * have the same location, and we DONT want to clobber. *\/\n\n if (opcode == spv::OpVariable && code[word+3] == interface) {\n int location = value_or_default(var_locations, code[word+2], -1);\n int builtin = value_or_default(var_builtins, code[word+2], -1);\n\n if (location == -1 && builtin == -1) {\n \/* No location defined, and not bound to an API builtin.\n * The spec says nothing about how this case works (or doesn't)\n * for interface matching.\n *\/\n printf(\"WARN: var %d (type %d) in %s interface has no Location or Builtin decoration\\n\",\n code[word+2], code[word+1], interface == spv::StorageInput ? \"input\" : \"output\");\n }\n else if (location != -1) {\n \/* A user-defined interface variable, with a location. *\/\n interface_var v;\n v.id = code[word+2];\n v.type_id = code[word+1];\n out[location] = v;\n }\n else {\n \/* A builtin interface variable *\/\n interface_var v;\n v.id = code[word+2];\n v.type_id = code[word+1];\n builtins_out[builtin] = v;\n }\n }\n\n word += oplen;\n }\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkCreateShader(VkDevice device, const VkShaderCreateInfo *pCreateInfo,\n VkShader *pShader)\n{\n VkLayerDispatchTable* pTable = tableMap[(VkBaseLayerObject *)device];\n VkResult res = pTable->CreateShader(device, pCreateInfo, pShader);\n\n shader_map[(VkBaseLayerObject *) *pShader] = new shader_source(pCreateInfo);\n return res;\n}\n\n\nstatic void\nvalidate_interface_between_stages(shader_source const *producer, char const *producer_name,\n shader_source const *consumer, char const *consumer_name)\n{\n std::map outputs;\n std::map inputs;\n\n std::map builtin_outputs;\n std::map builtin_inputs;\n\n printf(\"Begin validate_interface_between_stages %s -> %s\\n\",\n producer_name, consumer_name);\n\n collect_interface_by_location(producer, spv::StorageOutput, outputs, builtin_outputs);\n collect_interface_by_location(consumer, spv::StorageInput, inputs, builtin_inputs);\n\n auto a_it = outputs.begin();\n auto b_it = inputs.begin();\n\n \/* maps sorted by key (location); walk them together to find mismatches *\/\n while (a_it != outputs.end() || b_it != inputs.end()) {\n if (b_it == inputs.end() || a_it->first < b_it->first) {\n printf(\" WARN: %s writes to output location %d which is not consumed by %s\\n\",\n producer_name, a_it->first, consumer_name);\n a_it++;\n }\n else if (a_it == outputs.end() || a_it->first > b_it->first) {\n printf(\" ERR: %s consumes input location %d which is not written by %s\\n\",\n consumer_name, b_it->first, producer_name);\n b_it++;\n }\n else {\n printf(\" OK: match on location %d\\n\",\n a_it->first);\n \/* TODO: typecheck *\/\n a_it++;\n b_it++;\n }\n }\n\n printf(\"End validate_interface_between_stages\\n\");\n}\n\n\nstatic void\nvalidate_vi_against_vs_inputs(VkPipelineVertexInputCreateInfo const *vi, shader_source const *vs)\n{\n std::map inputs;\n \/* we collect builtin inputs, but they will never appear in the VI state --\n * the vs builtin inputs are generated in the pipeline, not sourced from buffers (VertexID, etc)\n *\/\n std::map builtin_inputs;\n\n printf(\"Begin validate_vi_against_vs_inputs\\n\");\n\n collect_interface_by_location(vs, spv::StorageInput, inputs, builtin_inputs);\n\n \/* Build index by location *\/\n std::map attribs;\n for (int i = 0; i < vi->attributeCount; i++)\n attribs[vi->pVertexAttributeDescriptions[i].location] = &vi->pVertexAttributeDescriptions[i];\n\n auto it_a = attribs.begin();\n auto it_b = inputs.begin();\n\n while (it_a != attribs.end() || it_b != inputs.end()) {\n if (it_b == inputs.end() || it_a->first < it_b->first) {\n printf(\" WARN: attribute at location %d not consumed by the vertex shader\\n\",\n it_a->first);\n it_a++;\n }\n else if (it_a == attribs.end() || it_b->first < it_a->first) {\n printf(\" ERR: vertex shader consumes input at location %d but not provided\\n\",\n it_b->first);\n it_b++;\n }\n else {\n \/* TODO: type check *\/\n printf(\" OK: match on attribute location %d\\n\",\n it_a->first);\n it_a++;\n it_b++;\n }\n }\n\n printf(\"End validate_vi_against_vs_inputs\\n\");\n}\n\n\nVK_LAYER_EXPORT VkResult VKAPI vkCreateGraphicsPipeline(VkDevice device,\n const VkGraphicsPipelineCreateInfo *pCreateInfo,\n VkPipeline *pPipeline)\n{\n \/* TODO: run cross-stage validation *\/\n \/* - Validate FS output -> CB *\/\n \/* - Support GS, TCS, TES stages *\/\n\n \/* We seem to allow pipeline stages to be specified out of order, so collect and identify them\n * before trying to do anything more: *\/\n\n shader_source const *vs_source = 0;\n shader_source const *fs_source = 0;\n VkPipelineCbStateCreateInfo const *cb = 0;\n VkPipelineVertexInputCreateInfo const *vi = 0;\n\n for (auto stage = pCreateInfo; stage; stage = (decltype(stage))stage->pNext) {\n if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO) {\n auto shader_stage = (VkPipelineShaderStageCreateInfo const *)stage;\n\n if (shader_stage->shader.stage == VK_SHADER_STAGE_VERTEX)\n vs_source = shader_map[(void *)(shader_stage->shader.shader)];\n else if (shader_stage->shader.stage == VK_SHADER_STAGE_FRAGMENT)\n fs_source = shader_map[(void *)(shader_stage->shader.shader)];\n else\n printf(\"Unknown shader stage %d\\n\", shader_stage->shader.stage);\n }\n else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_CB_STATE_CREATE_INFO) {\n cb = (VkPipelineCbStateCreateInfo const *)stage;\n }\n else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_CREATE_INFO) {\n vi = (VkPipelineVertexInputCreateInfo const *)stage;\n }\n }\n\n printf(\"Pipeline: vi=%p vs=%p fs=%p cb=%p\\n\", vi, vs_source, fs_source, cb);\n\n if (vi && vs_source) {\n validate_vi_against_vs_inputs(vi, vs_source);\n }\n\n if (vs_source && fs_source) {\n validate_interface_between_stages(vs_source, \"vertex shader\",\n fs_source, \"fragment shader\");\n }\n\n VkLayerDispatchTable *pTable = tableMap[(VkBaseLayerObject *)device];\n VkResult res = pTable->CreateGraphicsPipeline(device, pCreateInfo, pPipeline);\n return res;\n}\n\n\nVK_LAYER_EXPORT void * VKAPI vkGetProcAddr(VkPhysicalGpu gpu, const char* pName)\n{\n if (gpu == NULL)\n return NULL;\n\n initLayerTable((const VkBaseLayerObject *) gpu);\n\n#define ADD_HOOK(fn) \\\n if (!strncmp(#fn, pName, sizeof(#fn))) \\\n return (void *) fn\n\n ADD_HOOK(vkGetProcAddr);\n ADD_HOOK(vkEnumerateLayers);\n ADD_HOOK(vkCreateDevice);\n ADD_HOOK(vkCreateShader);\n ADD_HOOK(vkCreateGraphicsPipeline);\n\n VkBaseLayerObject* gpuw = (VkBaseLayerObject *) gpu;\n if (gpuw->pGPA == NULL)\n return NULL;\n return gpuw->pGPA((VkPhysicalGpu) gpuw->nextObject, pName);\n}\n<|endoftext|>"} {"text":"\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\n\/\/\/\n\/\/\/ @file InterfaceWithTetGen.cc\n\/\/\/ @author Martin Cole\n\/\/\/ @date Wed Mar 22 07:56:22 2006\n\/\/\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#define TETLIBRARY \/\/ Required definition for use of tetgen library\n#include \n\n#include \n\n#include \n\nusing namespace SCIRun;\nusing namespace Dataflow::Networks;\nusing namespace Modules::Fields;\nusing namespace Core::Thread;\nusing namespace Core::Geometry;\n\nnamespace SCIRun {\nnamespace Modules {\nnamespace Fields {\nnamespace detail {\n\n\/\/\/ @class InterfaceWithTetGen\n\/\/\/ @brief This module interfaces with TetGen.\n\nclass InterfaceWithTetGenImplImpl \/\/: public AlgorithmBase\n{\n public:\n explicit InterfaceWithTetGenImplImpl(Module* mod);\n\n FieldHandle runImpl(const std::deque& surfaces,\n FieldHandle points, FieldHandle region_attribs, const InterfaceWithTetGenInput& input) const;\n\n private:\n \/\/ translate the ui variables into the string with options\n \/\/ that TetGen uses\n Module* module_;\n static Mutex TetGenMutex;\n};\n\nMutex InterfaceWithTetGenImplImpl::TetGenMutex(\"Protect TetGen from running in parallel\");\n}}}}\n\ndetail::InterfaceWithTetGenImplImpl::InterfaceWithTetGenImplImpl(Module* module) : module_(module)\n{}\n\nstd::string InterfaceWithTetGenInput::fillCommandOptions(bool addPoints) const\n{\n \/\/ Collect the options in this output string stream\n std::ostringstream oss;\n if (addPoints)\n {\n oss << \"i\";\n }\n\n if (piecewiseFlag_)\n {\n oss << \"p\";\n }\n\n if (suppressSplitFlag_)\n {\n if (setSplitFlag_)\n {\n oss << \"YY\";\n }\n else\n {\n oss << \"Y\";\n }\n }\n\n \/\/ Always use zero indexing that is the only thing SCIRun knows....\n oss << \"z\";\n\n if (qualityFlag_)\n {\n oss << \"q\";\n if (setRatioFlag_)\n {\n oss << minRadius_;\n }\n }\n if (volConstraintFlag_)\n {\n oss << \"a\";\n if (setMaxVolConstraintFlag_)\n {\n oss << maxVolConstraint_;\n }\n }\n if (detectIntersectionsFlag_)\n {\n oss << \"d\";\n }\n if (assignFlag_)\n {\n if (setNonzeroAttributeFlag_)\n {\n oss << \"AA\";\n }\n else\n {\n oss << \"A\";\n }\n }\n\n \/\/ Add in whatever the user wants to add additionally.\n oss << moreSwitches_;\n return oss.str();\n}\n\n\nFieldHandle detail::InterfaceWithTetGenImplImpl::runImpl(const std::deque& surfaces,\n FieldHandle points, FieldHandle region_attribs, const InterfaceWithTetGenInput& input) const\n{\n#if 0\n if (inputs_changed_ || piecewiseFlag_.changed() ||\n assignFlag_.changed() || setNonzeroAttributeFlag_.changed() ||\n suppressSplitFlag_.changed() || setSplitFlag_.changed() ||\n qualityFlag_.changed() || setRatioFlag_.changed() ||\n volConstraintFlag_.changed() || setMaxVolConstraintFlag_.changed() ||\n minRadius_.changed() || maxVolConstraint_.changed() ||\n detectIntersectionsFlag_.changed() || moreSwitches_.changed() ||\n !oport_cached(\"TetVol\"))\n #endif\n \/\/{\n \/\/ Tell SCIRun we are actually doing some work\n\/\/ update_state(Executing);\n\n \/\/TODO DAN: check for proper memory management with these classes.\n tetgenio in, addin, out;\n\n bool add_points = false;\n if (points)\n {\n VMesh* mesh = points->vmesh();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n\n addin.numberofpoints = num_nodes;\n addin.pointlist = new REAL[num_nodes*3];\n for(VMesh::Node::index_type idx=0; idxget_center(p, idx);\n addin.pointlist[idx * 3] = p.x();\n addin.pointlist[idx * 3 + 1] = p.y();\n addin.pointlist[idx * 3 + 2] = p.z();\n }\n add_points = true;\n module_->remark(\"Added extra interior points from Points port.\");\n }\n\n if (region_attribs)\n {\n VMesh* mesh = region_attribs->vmesh();\n VField* field = region_attribs->vfield();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n\n in.regionlist = new REAL[num_nodes*5];\n in.numberofregions = num_nodes;\n for(VMesh::Node::index_type idx=0; idxget_center(p, idx);\n in.regionlist[idx * 5] = p.x();\n in.regionlist[idx * 5 + 1] = p.y();\n in.regionlist[idx * 5 + 2] = p.z();\n in.regionlist[idx * 5 + 3] = idx;\n field->get_value(val, idx);\n in.regionlist[idx * 5 + 4] = val;\n }\n }\n\n\n \/\/ indices start from 0.\n in.firstnumber = 0;\n in.mesh_dim = 3;\n\n int marker = -10;\n\n VMesh::size_type tot_num_nodes = 0;\n VMesh::size_type tot_num_elems = 0;\n\n for (size_t j=0; j< surfaces.size(); j++)\n {\n VMesh* mesh = surfaces[j]->vmesh();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n VMesh::Elem::size_type num_elems = mesh->num_elems();\n\n tot_num_nodes += num_nodes;\n tot_num_elems += num_elems;\n }\n\n in.pointlist = new REAL[(tot_num_nodes) * 3];\n in.numberofpoints = tot_num_nodes;\n\n in.facetlist = new tetgenio::facet[tot_num_elems];\n in.facetmarkerlist = new int[tot_num_elems];\n in.numberoffacets = tot_num_elems;\n\n VMesh::index_type idx = 0;\n VMesh::index_type fidx = 0;\n VMesh::index_type off;\n\n for (size_t j=0; j< surfaces.size(); j++)\n {\n VMesh* mesh = surfaces[j]->vmesh();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n VMesh::Elem::size_type num_elems = mesh->num_elems();\n\n off = idx;\n for(VMesh::Node::index_type nidx=0; nidxget_center(p, nidx);\n in.pointlist[idx * 3] = p.x();\n in.pointlist[idx * 3 + 1] = p.y();\n in.pointlist[idx * 3 + 2] = p.z();\n ++idx;\n }\n\n unsigned int vert_per_face = mesh->num_nodes_per_elem();\n\n \/\/ iterate over faces.\n VMesh::Node::array_type nodes;\n\n for (VMesh::Elem::index_type eidx = 0; eidx < num_elems; ++eidx)\n {\n if (vert_per_face > 0)\n {\n tetgenio::facet *f = &in.facetlist[fidx];\n f->numberofpolygons = 1;\n f->polygonlist = new tetgenio::polygon[1];\n f->numberofholes = 0;\n f->holelist = nullptr;\n tetgenio::polygon *p = &f->polygonlist[0];\n p->numberofvertices = vert_per_face;\n\n p->vertexlist = new int[p->numberofvertices];\n mesh->get_nodes(nodes, eidx);\n for (size_t i = 0; i < nodes.size(); i++)\n {\n p->vertexlist[i] = VMesh::index_type(nodes[i]) + off;\n }\n }\n else\n {\n tetgenio::facet *f = &in.facetlist[fidx];\n f->numberofpolygons = 0;\n f->polygonlist = nullptr;\n f->numberofholes = 0;\n f->holelist = nullptr;\n }\n in.facetmarkerlist[fidx] = marker;\n ++fidx;\n }\n\n marker *= 2;\n }\n\n module_->getUpdaterFunc()(.2);\n \/\/ Save files for later debugging.\n \/\/ std::string filename = std::string(sci_getenv(\"SCIRUN_TMP_DIR\")) + \"\/tgIN\";\n \/\/ in.save_nodes((char*)filename.c_str());\n \/\/ in.save_poly((char*)filename.c_str());\n\n std::string cmmd_ln = input.fillCommandOptions(add_points);\n #if DEBUG\n std::cerr << \"\\nTetgen command line: \" << cmmd_ln << std::endl;\n #endif\n tetgenio *addtgio = nullptr;\n if (add_points)\n {\n addtgio = &addin;\n }\n \/\/ Create the new mesh.\n\n \/\/ Make sure only one thread accesses TetGen\n \/\/ It is not thread safe :)\n {\n Guard g(TetGenMutex.get());\n try\n {\n tetrahedralize(const_cast(cmmd_ln.c_str()), &in, &out, addtgio);\n }\n catch(std::exception& e)\n {\n module_->error(std::string(\"TetGen failed to generate a mesh: \") + e.what());\n return nullptr;\n }\n catch (...)\n {\n module_->error(\"TetGen failed to generate a mesh\");\n return nullptr;\n }\n }\n\n module_->getUpdaterFunc()(.9);\n FieldInformation fi(TETVOLMESH_E,CONSTANTDATA_E,DOUBLE_E);\n FieldHandle tetvol_out = CreateField(fi);\n \/\/ Convert to a SCIRun TetVol.\n\n VMesh* mesh = tetvol_out->vmesh();\n VField* field = tetvol_out->vfield();\n for (int i = 0; i < out.numberofpoints; i++)\n {\n Point p(out.pointlist[i*3], out.pointlist[i*3+1], out.pointlist[i*3+2]);\n mesh->add_point(p);\n }\n\n VMesh::Node::size_type numnodes = mesh->num_nodes();\n VMesh::Node::array_type nodes(4);\n for (int i = 0; i < out.numberoftetrahedra; i++)\n {\n nodes[0] = out.tetrahedronlist[i*4];\n nodes[1] = out.tetrahedronlist[i*4+1];\n nodes[2] = out.tetrahedronlist[i*4+2];\n nodes[3] = out.tetrahedronlist[i*4+3];\n\n if (nodes[0] >= numnodes ||nodes[1] >= numnodes ||\n nodes[2] >= numnodes ||nodes[3] >= numnodes )\n {\n module_->error(\"TetGen failed to produce a valid tetrahedralization\");\n return nullptr;\n }\n mesh->add_elem(nodes);\n }\n\n field->resize_values();\n\n int atts = out.numberoftetrahedronattributes;\n\n for (int i = 0; i < out.numberoftetrahedra; i++)\n {\n for (int j = 0; j < atts; j++)\n {\n double val = out.tetrahedronattributelist[i * atts + j];\n field->set_value(val, VMesh::Elem::index_type(i));\n }\n }\n\n module_->getUpdaterFunc()(1.0);\n return tetvol_out;\n}\n\nInterfaceWithTetGenInput::InterfaceWithTetGenInput() :\npiecewiseFlag_(true),\nassignFlag_(true),\nsetNonzeroAttributeFlag_(false),\nsuppressSplitFlag_(true),\nsetSplitFlag_(false),\nqualityFlag_(true),\nsetRatioFlag_(false),\nvolConstraintFlag_(false),\nsetMaxVolConstraintFlag_(false),\n\/\/ see TetGen documentation for \"-q\" switch: default is 2.0\nminRadius_(2.0),\nmaxVolConstraint_(0.1),\ndetectIntersectionsFlag_(false),\nmoreSwitches_(\"\")\n{\n}\n\nInterfaceWithTetGenImpl::InterfaceWithTetGenImpl(Module* module, const InterfaceWithTetGenInput& input) :\n impl_(new detail::InterfaceWithTetGenImplImpl(module)),\n inputFlags_(input)\n{}\n\nFieldHandle InterfaceWithTetGenImpl::runImpl(const std::deque& surfaces, FieldHandle points, FieldHandle region_attribs) const\n{\n return impl_->runImpl(surfaces, points, region_attribs, inputFlags_);\n}\nTetgen build fix\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\n\/\/\/\n\/\/\/ @file InterfaceWithTetGen.cc\n\/\/\/ @author Martin Cole\n\/\/\/ @date Wed Mar 22 07:56:22 2006\n\/\/\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#define TETLIBRARY \/\/ Required definition for use of tetgen library\n#include \n\n#include \n\n#include \n\nusing namespace SCIRun;\nusing namespace Dataflow::Networks;\nusing namespace Modules::Fields;\nusing namespace Core::Thread;\nusing namespace Core::Geometry;\n\nnamespace SCIRun {\nnamespace Modules {\nnamespace Fields {\nnamespace detail {\n\n\/\/\/ @class InterfaceWithTetGen\n\/\/\/ @brief This module interfaces with TetGen.\n\nclass InterfaceWithTetGenImplImpl \/\/: public AlgorithmBase\n{\n public:\n explicit InterfaceWithTetGenImplImpl(Module* mod);\n\n FieldHandle runImpl(const std::deque& surfaces,\n FieldHandle points, FieldHandle region_attribs, const InterfaceWithTetGenInput& input) const;\n\n private:\n \/\/ translate the ui variables into the string with options\n \/\/ that TetGen uses\n Module* module_;\n static Mutex TetGenMutex;\n};\n\nMutex InterfaceWithTetGenImplImpl::TetGenMutex(\"Protect TetGen from running in parallel\");\n}}}}\n\ndetail::InterfaceWithTetGenImplImpl::InterfaceWithTetGenImplImpl(Module* module) : module_(module)\n{}\n\nstd::string InterfaceWithTetGenInput::fillCommandOptions(bool addPoints) const\n{\n \/\/ Collect the options in this output string stream\n std::ostringstream oss;\n if (addPoints)\n {\n oss << \"i\";\n }\n\n if (piecewiseFlag_)\n {\n oss << \"p\";\n }\n\n if (suppressSplitFlag_)\n {\n if (setSplitFlag_)\n {\n oss << \"YY\";\n }\n else\n {\n oss << \"Y\";\n }\n }\n\n \/\/ Always use zero indexing that is the only thing SCIRun knows....\n oss << \"z\";\n\n if (qualityFlag_)\n {\n oss << \"q\";\n if (setRatioFlag_)\n {\n oss << minRadius_;\n }\n }\n if (volConstraintFlag_)\n {\n oss << \"a\";\n if (setMaxVolConstraintFlag_)\n {\n oss << maxVolConstraint_;\n }\n }\n if (detectIntersectionsFlag_)\n {\n oss << \"d\";\n }\n if (assignFlag_)\n {\n if (setNonzeroAttributeFlag_)\n {\n oss << \"AA\";\n }\n else\n {\n oss << \"A\";\n }\n }\n\n \/\/ Add in whatever the user wants to add additionally.\n oss << moreSwitches_;\n return oss.str();\n}\n\n\nFieldHandle detail::InterfaceWithTetGenImplImpl::runImpl(const std::deque& surfaces,\n FieldHandle points, FieldHandle region_attribs, const InterfaceWithTetGenInput& input) const\n{\n#if 0\n if (inputs_changed_ || piecewiseFlag_.changed() ||\n assignFlag_.changed() || setNonzeroAttributeFlag_.changed() ||\n suppressSplitFlag_.changed() || setSplitFlag_.changed() ||\n qualityFlag_.changed() || setRatioFlag_.changed() ||\n volConstraintFlag_.changed() || setMaxVolConstraintFlag_.changed() ||\n minRadius_.changed() || maxVolConstraint_.changed() ||\n detectIntersectionsFlag_.changed() || moreSwitches_.changed() ||\n !oport_cached(\"TetVol\"))\n #endif\n \/\/{\n \/\/ Tell SCIRun we are actually doing some work\n\/\/ update_state(Executing);\n\n \/\/TODO DAN: check for proper memory management with these classes.\n tetgenio in, addin, out;\n\n bool add_points = false;\n if (points)\n {\n VMesh* mesh = points->vmesh();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n\n addin.numberofpoints = num_nodes;\n addin.pointlist = new REAL[num_nodes*3];\n for(VMesh::Node::index_type idx=0; idxget_center(p, idx);\n addin.pointlist[idx * 3] = p.x();\n addin.pointlist[idx * 3 + 1] = p.y();\n addin.pointlist[idx * 3 + 2] = p.z();\n }\n add_points = true;\n module_->remark(\"Added extra interior points from Points port.\");\n }\n\n if (region_attribs)\n {\n VMesh* mesh = region_attribs->vmesh();\n VField* field = region_attribs->vfield();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n\n in.regionlist = new REAL[num_nodes*5];\n in.numberofregions = num_nodes;\n for(VMesh::Node::index_type idx=0; idxget_center(p, idx);\n in.regionlist[idx * 5] = p.x();\n in.regionlist[idx * 5 + 1] = p.y();\n in.regionlist[idx * 5 + 2] = p.z();\n in.regionlist[idx * 5 + 3] = idx;\n field->get_value(val, idx);\n in.regionlist[idx * 5 + 4] = val;\n }\n }\n\n\n \/\/ indices start from 0.\n in.firstnumber = 0;\n in.mesh_dim = 3;\n\n int marker = -10;\n\n VMesh::size_type tot_num_nodes = 0;\n VMesh::size_type tot_num_elems = 0;\n\n for (size_t j=0; j< surfaces.size(); j++)\n {\n VMesh* mesh = surfaces[j]->vmesh();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n VMesh::Elem::size_type num_elems = mesh->num_elems();\n\n tot_num_nodes += num_nodes;\n tot_num_elems += num_elems;\n }\n\n in.pointlist = new REAL[(tot_num_nodes) * 3];\n in.numberofpoints = tot_num_nodes;\n\n in.facetlist = new tetgenio::facet[tot_num_elems];\n in.facetmarkerlist = new int[tot_num_elems];\n in.numberoffacets = tot_num_elems;\n\n VMesh::index_type idx = 0;\n VMesh::index_type fidx = 0;\n VMesh::index_type off;\n\n for (size_t j=0; j< surfaces.size(); j++)\n {\n VMesh* mesh = surfaces[j]->vmesh();\n VMesh::Node::size_type num_nodes = mesh->num_nodes();\n VMesh::Elem::size_type num_elems = mesh->num_elems();\n\n off = idx;\n for(VMesh::Node::index_type nidx=0; nidxget_center(p, nidx);\n in.pointlist[idx * 3] = p.x();\n in.pointlist[idx * 3 + 1] = p.y();\n in.pointlist[idx * 3 + 2] = p.z();\n ++idx;\n }\n\n unsigned int vert_per_face = mesh->num_nodes_per_elem();\n\n \/\/ iterate over faces.\n VMesh::Node::array_type nodes;\n\n for (VMesh::Elem::index_type eidx = 0; eidx < num_elems; ++eidx)\n {\n if (vert_per_face > 0)\n {\n tetgenio::facet *f = &in.facetlist[fidx];\n f->numberofpolygons = 1;\n f->polygonlist = new tetgenio::polygon[1];\n f->numberofholes = 0;\n f->holelist = nullptr;\n tetgenio::polygon *p = &f->polygonlist[0];\n p->numberofvertices = vert_per_face;\n\n p->vertexlist = new int[p->numberofvertices];\n mesh->get_nodes(nodes, eidx);\n for (size_t i = 0; i < nodes.size(); i++)\n {\n p->vertexlist[i] = VMesh::index_type(nodes[i]) + off;\n }\n }\n else\n {\n tetgenio::facet *f = &in.facetlist[fidx];\n f->numberofpolygons = 0;\n f->polygonlist = nullptr;\n f->numberofholes = 0;\n f->holelist = nullptr;\n }\n in.facetmarkerlist[fidx] = marker;\n ++fidx;\n }\n\n marker *= 2;\n }\n\n module_->getUpdaterFunc()(.2);\n \/\/ Save files for later debugging.\n \/\/ std::string filename = std::string(sci_getenv(\"SCIRUN_TMP_DIR\")) + \"\/tgIN\";\n \/\/ in.save_nodes((char*)filename.c_str());\n \/\/ in.save_poly((char*)filename.c_str());\n\n std::string cmmd_ln = input.fillCommandOptions(add_points);\n #if DEBUG\n std::cerr << \"\\nTetgen command line: \" << cmmd_ln << std::endl;\n #endif\n tetgenio *addtgio = nullptr;\n if (add_points)\n {\n addtgio = &addin;\n }\n \/\/ Create the new mesh.\n\n \/\/ Make sure only one thread accesses TetGen\n \/\/ It is not thread safe :)\n {\n Guard g(TetGenMutex.get());\n try\n {\n tetrahedralize(const_cast(cmmd_ln.c_str()), &in, &out, addtgio);\n }\n catch(std::exception& e)\n {\n module_->error(std::string(\"TetGen failed to generate a mesh: \") + e.what());\n return nullptr;\n }\n catch (...)\n {\n module_->error(\"TetGen failed to generate a mesh\");\n return nullptr;\n }\n }\n\n module_->getUpdaterFunc()(.9);\n FieldInformation fi(mesh_info_type::TETVOLMESH_E, databasis_info_type::CONSTANTDATA_E, data_info_type::DOUBLE_E);\n FieldHandle tetvol_out = CreateField(fi);\n \/\/ Convert to a SCIRun TetVol.\n\n VMesh* mesh = tetvol_out->vmesh();\n VField* field = tetvol_out->vfield();\n for (int i = 0; i < out.numberofpoints; i++)\n {\n Point p(out.pointlist[i*3], out.pointlist[i*3+1], out.pointlist[i*3+2]);\n mesh->add_point(p);\n }\n\n VMesh::Node::size_type numnodes = mesh->num_nodes();\n VMesh::Node::array_type nodes(4);\n for (int i = 0; i < out.numberoftetrahedra; i++)\n {\n nodes[0] = out.tetrahedronlist[i*4];\n nodes[1] = out.tetrahedronlist[i*4+1];\n nodes[2] = out.tetrahedronlist[i*4+2];\n nodes[3] = out.tetrahedronlist[i*4+3];\n\n if (nodes[0] >= numnodes ||nodes[1] >= numnodes ||\n nodes[2] >= numnodes ||nodes[3] >= numnodes )\n {\n module_->error(\"TetGen failed to produce a valid tetrahedralization\");\n return nullptr;\n }\n mesh->add_elem(nodes);\n }\n\n field->resize_values();\n\n int atts = out.numberoftetrahedronattributes;\n\n for (int i = 0; i < out.numberoftetrahedra; i++)\n {\n for (int j = 0; j < atts; j++)\n {\n double val = out.tetrahedronattributelist[i * atts + j];\n field->set_value(val, VMesh::Elem::index_type(i));\n }\n }\n\n module_->getUpdaterFunc()(1.0);\n return tetvol_out;\n}\n\nInterfaceWithTetGenInput::InterfaceWithTetGenInput() :\npiecewiseFlag_(true),\nassignFlag_(true),\nsetNonzeroAttributeFlag_(false),\nsuppressSplitFlag_(true),\nsetSplitFlag_(false),\nqualityFlag_(true),\nsetRatioFlag_(false),\nvolConstraintFlag_(false),\nsetMaxVolConstraintFlag_(false),\n\/\/ see TetGen documentation for \"-q\" switch: default is 2.0\nminRadius_(2.0),\nmaxVolConstraint_(0.1),\ndetectIntersectionsFlag_(false),\nmoreSwitches_(\"\")\n{\n}\n\nInterfaceWithTetGenImpl::InterfaceWithTetGenImpl(Module* module, const InterfaceWithTetGenInput& input) :\n impl_(new detail::InterfaceWithTetGenImplImpl(module)),\n inputFlags_(input)\n{}\n\nFieldHandle InterfaceWithTetGenImpl::runImpl(const std::deque& surfaces, FieldHandle points, FieldHandle region_attribs) const\n{\n return impl_->runImpl(surfaces, points, region_attribs, inputFlags_);\n}\n<|endoftext|>"} {"text":"\/** \\file RobotCarVel.cc\n This domain is a simulation of velocity control for the Austin Robot \n Technology autonomous vehicle. \n This vehicle is described in:\n Beeson et al, \"Multiagent Interactions in Urban Driving,\" Journal of Physical Agents, March 2008.\n The velocity control task is described in:\n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*\/\n\n#include \n\n\/\/ normal: true values of each\nRobotCarVel::RobotCarVel(Random &rand, bool randomVel, bool upVel, bool tenToSix, bool lag):\n rng(rand),\n s(6),\n junk(0),\n targetVel(s[0]),\n currVel(s[1]),\n trueThrottle(s[2]),\n trueBrake(s[3]),\n throttleTarget(s[4]),\n brakeTarget(s[5]),\n randomVel(randomVel),\n upVel(upVel),\n tenToSix(tenToSix),\n lag(lag)\n{\n reset();\n}\n \n\n\nRobotCarVel::~RobotCarVel() { }\n\nconst std::vector &RobotCarVel::sensation() const { \n return s; \n}\n\nfloat RobotCarVel::apply(int action) {\n\n float HZ = 10.0;\n\n actNum++;\n\n \/\/ figure out reward based on target\/curr vel\n float reward = -10.0 * fabs(currVel - targetVel);\n\n float throttleChangePct = 1.0;\/\/0.9; \/\/1.0;\n float brakeChangePct = 1.0;\/\/0.9; \/\/1.0;\n if (lag){\n brakeChangePct = brakePosVel \/ HZ;\n float brakeVelTarget = 3.0*(brakeTarget - trueBrake);\n brakePosVel += (brakeVelTarget - brakePosVel) * 3.0 \/ HZ;\n trueBrake += brakeChangePct;\n } else {\n trueBrake += (brakeTarget-trueBrake) * brakeChangePct;\n }\n trueBrake = bound(trueBrake, 0.0, 1.0);\n\n \/\/ figure out the change of true brake\/throttle position based on last targets\n trueThrottle += (throttleTarget-trueThrottle) * throttleChangePct;\n trueThrottle = bound(trueThrottle, 0.0, 0.4);\n\n \/\/ figure out new velocity based on those positions \n \/\/ from the stage simulation\n float g = 9.81; \/\/ acceleration due to gravity\n float throttle_accel = g;\n float brake_decel = g;\n float rolling_resistance = 0.01 * g;\n float drag_coeff = 0.01;\n float idle_accel = (rolling_resistance\n + drag_coeff * 3.1 * 3.1);\n float wind_resistance = drag_coeff * currVel * currVel;\n float accel = (idle_accel\n + trueThrottle * throttle_accel\n - trueBrake * brake_decel\n - rolling_resistance\n - wind_resistance);\n currVel += (accel \/ HZ);\n currVel = bound(currVel, 0.0, 12.0);\n \n\n \/\/ figure out action's adjustment to throttle\/brake targets\n if (action == THROTTLE_UP){\n brakeTarget = 0.0;\n if (throttleTarget < 0.4)\n throttleTarget += 0.1;\n }\n else if (action == THROTTLE_DOWN){\n brakeTarget = 0.0;\n if (throttleTarget > 0.0)\n throttleTarget -= 0.1;\n }\n else if (action == BRAKE_UP){\n throttleTarget = 0.0;\n if (brakeTarget < 1.0)\n brakeTarget += 0.1;\n }\n else if (action == BRAKE_DOWN){\n throttleTarget = 0.0;\n if (brakeTarget > 0.0)\n brakeTarget -= 0.1;\n }\n else if (action != NOTHING){\n cout << \"invalid action \" << action << endl;\n }\n throttleTarget = bound(throttleTarget, 0.0, 0.4);\n brakeTarget = bound(brakeTarget, 0.0, 1.0);\n throttleTarget = 0.1 * (float)((int)(throttleTarget*10.0));\n brakeTarget = 0.1 * (float)((int)(brakeTarget*10.0));\n \n \/*\n cout << action << \", throt: \" << throttleTarget << \", brake: \" << brakeTarget\n << \", trueBrake: \" << trueBrake \n << \", currVel: \" << currVel << \", reward: \" << reward << endl;\n *\/\n\n return reward;\n\n}\n\n\nbool RobotCarVel::terminal() const {\n return false;\n}\n\n\n\nvoid RobotCarVel::reset() {\n\n \/\/ for now\n if (randomVel){\n targetVel = rng.uniformDiscrete(0, 11);\n currVel = rng.uniformDiscrete(0, 11);\n } else {\n if (tenToSix){ \/\/ 10 to 6\n if (upVel){\n targetVel = 10.0;\n currVel = 6.0;\n } else {\n targetVel = 6.0;\n currVel = 10.0;\n } \n } else { \/\/ 7 to 2\n if (upVel){\n targetVel = 7.0;\n currVel = 2.0;\n } else {\n targetVel = 2.0;\n currVel = 7.0;\n } \n }\n }\n\n actNum = 0;\n throttleTarget = rng.uniformDiscrete(0,4) * 0.1;\n brakeTarget = 0.0;\n trueThrottle = throttleTarget;\n trueBrake = brakeTarget;\n brakePosVel = 0.0;\n\n}\n\n\n\nint RobotCarVel::getNumActions(){\n return 5;\n}\n\n\nvoid RobotCarVel::setSensation(std::vector newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = newS[i];\n }\n}\n\nstd::vector RobotCarVel::getSeedings() {\n\n \/\/ return seedings\n std::vector seeds;\n \/\/return seeds;\n\n \n reset();\n\n \/*\n \/\/ seeds of perfect velocity\n if (randomVel){\n for (int i = 0; i < 12; i++){\n \/\/ 3 random of each\n for (int j = 0; j < 3; j++)\n seeds.push_back(getRandomVelSeed(i));\n } \n } else {\n \/\/ just for target velocity\n \/\/ 5 random seeds\n for (int j = 0; j < 5; j++){\n seeds.push_back(getRandomVelSeed(targetVel));\n }\n }\n *\/\n\n \n \/\/ some completely random (non target)\n for (int i = 0; i < 25; i++){\n float vel = rng.uniform(0,11);\n\n float throt = 0;\n float brake = 0;\n if (rng.bernoulli(0.5)){\n throt = rng.uniformDiscrete(0,4)*0.1;\n } else {\n brake = rng.uniformDiscrete(0,9)*0.1;\n } \n int act = i%getNumActions();\n seeds.push_back(getExp(targetVel,vel,throt,brake,act));\n }\n\n reset();\n\n return seeds;\n}\n\nexperience RobotCarVel::getRandomVelSeed(float target){\n float throt = 0;\n float brake = 0;\n if (rng.bernoulli(0.5)){\n throt = rng.uniformDiscrete(0,4)*0.1;\n } else {\n brake = rng.uniformDiscrete(0,4)*0.1;\n } \n\n return getExp(target, target, throt, brake, rng.uniformDiscrete(0,4));\n}\n\nexperience RobotCarVel::getExp(float s0, float s1, float s2, float s3, int a){\n\n if (!randomVel) s0 = targetVel;\n\n experience e;\n\n e.s.resize(4, 0.0);\n e.next.resize(4, 0.0);\n\n targetVel = s0;\n currVel = s1;\n throttleTarget = s2;\n brakeTarget = s3;\n trueThrottle = throttleTarget;\n trueBrake = brakeTarget;\n brakePosVel = 0.0;\n\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n \/*\n cout << \"seed from state: \";\n for (unsigned i = 0; i < e.s.size(); i++){\n cout << e.s[i] << \", \";\n } \n cout << \"act: \" << e.act << \" reward: \" << e.reward << \" next: \";\n for (unsigned i = 0; i < e.next.size(); i++){\n cout << e.next[i] << \", \";\n } \n cout << endl;\n *\/\n\n reset();\n\n return e;\n}\n\n\nvoid RobotCarVel::getMinMaxFeatures(std::vector *minFeat,\n std::vector *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 12.0);\n\n (*maxFeat)[2] = 0.4;\n (*maxFeat)[3] = 1.0;\n (*maxFeat)[4] = 0.4;\n (*maxFeat)[5] = 1.0;\n\n}\n\nvoid RobotCarVel::getMinMaxReward(float *minR,\n float *maxR){\n \n *minR = -120.0;\n *maxR = 0.0; \n \n}\n\nfloat RobotCarVel::bound(float val, float min, float max){\n if (val < min)\n return min;\n if (val > max)\n return max;\n return val;\n}\nchanged robot vel control simulation to give just brake\/throttle targets\/** \\file RobotCarVel.cc\n This domain is a simulation of velocity control for the Austin Robot \n Technology autonomous vehicle. \n This vehicle is described in:\n Beeson et al, \"Multiagent Interactions in Urban Driving,\" Journal of Physical Agents, March 2008.\n The velocity control task is described in:\n Hester, Quinlan, and Stone, \"A Real-Time Model-Based Reinforcement Learning Architecture for Robot Control\", arXiv 1105.1749, 2011.\n \\author Todd Hester\n*\/\n\n#include \n\n\/\/ normal: true values of each\nRobotCarVel::RobotCarVel(Random &rand, bool randomVel, bool upVel, bool tenToSix, bool lag):\n rng(rand),\n s(4),\n junk(2),\n targetVel(s[0]),\n currVel(s[1]),\n trueThrottle(junk[0]),\n trueBrake(junk[1]),\n throttleTarget(s[2]),\n brakeTarget(s[3]),\n randomVel(randomVel),\n upVel(upVel),\n tenToSix(tenToSix),\n lag(lag)\n{\n reset();\n}\n \n\n\nRobotCarVel::~RobotCarVel() { }\n\nconst std::vector &RobotCarVel::sensation() const { \n return s; \n}\n\nfloat RobotCarVel::apply(int action) {\n\n float HZ = 10.0;\n\n actNum++;\n\n \/\/ figure out reward based on target\/curr vel\n float reward = -10.0 * fabs(currVel - targetVel);\n\n float throttleChangePct = 1.0;\/\/0.9; \/\/1.0;\n float brakeChangePct = 1.0;\/\/0.9; \/\/1.0;\n if (lag){\n brakeChangePct = brakePosVel \/ HZ;\n float brakeVelTarget = 3.0*(brakeTarget - trueBrake);\n brakePosVel += (brakeVelTarget - brakePosVel) * 3.0 \/ HZ;\n trueBrake += brakeChangePct;\n } else {\n trueBrake += (brakeTarget-trueBrake) * brakeChangePct;\n }\n trueBrake = bound(trueBrake, 0.0, 1.0);\n\n \/\/ figure out the change of true brake\/throttle position based on last targets\n trueThrottle += (throttleTarget-trueThrottle) * throttleChangePct;\n trueThrottle = bound(trueThrottle, 0.0, 0.4);\n\n \/\/ figure out new velocity based on those positions \n \/\/ from the stage simulation\n float g = 9.81; \/\/ acceleration due to gravity\n float throttle_accel = g;\n float brake_decel = g;\n float rolling_resistance = 0.01 * g;\n float drag_coeff = 0.01;\n float idle_accel = (rolling_resistance\n + drag_coeff * 3.1 * 3.1);\n float wind_resistance = drag_coeff * currVel * currVel;\n float accel = (idle_accel\n + trueThrottle * throttle_accel\n - trueBrake * brake_decel\n - rolling_resistance\n - wind_resistance);\n currVel += (accel \/ HZ);\n currVel = bound(currVel, 0.0, 12.0);\n \n\n \/\/ figure out action's adjustment to throttle\/brake targets\n if (action == THROTTLE_UP){\n brakeTarget = 0.0;\n if (throttleTarget < 0.4)\n throttleTarget += 0.1;\n }\n else if (action == THROTTLE_DOWN){\n brakeTarget = 0.0;\n if (throttleTarget > 0.0)\n throttleTarget -= 0.1;\n }\n else if (action == BRAKE_UP){\n throttleTarget = 0.0;\n if (brakeTarget < 1.0)\n brakeTarget += 0.1;\n }\n else if (action == BRAKE_DOWN){\n throttleTarget = 0.0;\n if (brakeTarget > 0.0)\n brakeTarget -= 0.1;\n }\n else if (action != NOTHING){\n cout << \"invalid action \" << action << endl;\n }\n throttleTarget = bound(throttleTarget, 0.0, 0.4);\n brakeTarget = bound(brakeTarget, 0.0, 1.0);\n throttleTarget = 0.1 * (float)((int)(throttleTarget*10.0));\n brakeTarget = 0.1 * (float)((int)(brakeTarget*10.0));\n \n \/*\n cout << action << \", throt: \" << throttleTarget << \", brake: \" << brakeTarget\n << \", trueBrake: \" << trueBrake \n << \", currVel: \" << currVel << \", reward: \" << reward << endl;\n *\/\n\n return reward;\n\n}\n\n\nbool RobotCarVel::terminal() const {\n return false;\n}\n\n\n\nvoid RobotCarVel::reset() {\n\n \/\/ for now\n if (randomVel){\n targetVel = rng.uniformDiscrete(0, 11);\n currVel = rng.uniformDiscrete(0, 11);\n } else {\n if (tenToSix){ \/\/ 10 to 6\n if (upVel){\n targetVel = 10.0;\n currVel = 6.0;\n } else {\n targetVel = 6.0;\n currVel = 10.0;\n } \n } else { \/\/ 7 to 2\n if (upVel){\n targetVel = 7.0;\n currVel = 2.0;\n } else {\n targetVel = 2.0;\n currVel = 7.0;\n } \n }\n }\n\n actNum = 0;\n throttleTarget = rng.uniformDiscrete(0,4) * 0.1;\n brakeTarget = 0.0;\n trueThrottle = throttleTarget;\n trueBrake = brakeTarget;\n brakePosVel = 0.0;\n\n}\n\n\n\nint RobotCarVel::getNumActions(){\n return 5;\n}\n\n\nvoid RobotCarVel::setSensation(std::vector newS){\n if (s.size() != newS.size()){\n cerr << \"Error in sensation sizes\" << endl;\n }\n\n for (unsigned i = 0; i < newS.size(); i++){\n s[i] = newS[i];\n }\n}\n\nstd::vector RobotCarVel::getSeedings() {\n\n \/\/ return seedings\n std::vector seeds;\n \/\/return seeds;\n\n \n reset();\n\n \/*\n \/\/ seeds of perfect velocity\n if (randomVel){\n for (int i = 0; i < 12; i++){\n \/\/ 3 random of each\n for (int j = 0; j < 3; j++)\n seeds.push_back(getRandomVelSeed(i));\n } \n } else {\n \/\/ just for target velocity\n \/\/ 5 random seeds\n for (int j = 0; j < 5; j++){\n seeds.push_back(getRandomVelSeed(targetVel));\n }\n }\n *\/\n\n \n \/\/ some completely random (non target)\n for (int i = 0; i < 25; i++){\n float vel = rng.uniform(0,11);\n\n float throt = 0;\n float brake = 0;\n if (rng.bernoulli(0.5)){\n throt = rng.uniformDiscrete(0,4)*0.1;\n } else {\n brake = rng.uniformDiscrete(0,9)*0.1;\n } \n int act = i%getNumActions();\n seeds.push_back(getExp(targetVel,vel,throt,brake,act));\n }\n\n reset();\n\n return seeds;\n}\n\nexperience RobotCarVel::getRandomVelSeed(float target){\n float throt = 0;\n float brake = 0;\n if (rng.bernoulli(0.5)){\n throt = rng.uniformDiscrete(0,4)*0.1;\n } else {\n brake = rng.uniformDiscrete(0,4)*0.1;\n } \n\n return getExp(target, target, throt, brake, rng.uniformDiscrete(0,4));\n}\n\nexperience RobotCarVel::getExp(float s0, float s1, float s2, float s3, int a){\n\n if (!randomVel) s0 = targetVel;\n\n experience e;\n\n e.s.resize(4, 0.0);\n e.next.resize(4, 0.0);\n\n targetVel = s0;\n currVel = s1;\n throttleTarget = s2;\n brakeTarget = s3;\n trueThrottle = throttleTarget;\n trueBrake = brakeTarget;\n brakePosVel = 0.0;\n\n e.act = a;\n e.s = sensation();\n e.reward = apply(e.act);\n\n e.terminal = terminal();\n e.next = sensation();\n\n \/*\n cout << \"seed from state: \";\n for (unsigned i = 0; i < e.s.size(); i++){\n cout << e.s[i] << \", \";\n } \n cout << \"act: \" << e.act << \" reward: \" << e.reward << \" next: \";\n for (unsigned i = 0; i < e.next.size(); i++){\n cout << e.next[i] << \", \";\n } \n cout << endl;\n *\/\n\n reset();\n\n return e;\n}\n\n\nvoid RobotCarVel::getMinMaxFeatures(std::vector *minFeat,\n std::vector *maxFeat){\n \n minFeat->resize(s.size(), 0.0);\n maxFeat->resize(s.size(), 12.0);\n\n (*maxFeat)[2] = 0.4;\n (*maxFeat)[3] = 1.0;\n\n}\n\nvoid RobotCarVel::getMinMaxReward(float *minR,\n float *maxR){\n \n *minR = -120.0;\n *maxR = 0.0; \n \n}\n\nfloat RobotCarVel::bound(float val, float min, float max){\n if (val < min)\n return min;\n if (val > max)\n return max;\n return val;\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n * @copyright defined in eos\/LICENSE.txt\n *\/\n#pragma once\n#include \n#include \n#include \n#include \n\nnamespace eosio { namespace chain {\n\n\/**\n * This data structure should store context-free cached data about a transaction such as\n * packed\/unpacked\/compressed and recovered keys\n *\/\nclass transaction_metadata {\n public:\n transaction_id_type id;\n transaction_id_type signed_id;\n signed_transaction trx;\n packed_transaction packed_trx;\n optional>> signing_keys;\n std::future> signing_keys_future;\n bool accepted = false;\n bool implicit = false;\n bool scheduled = false;\n\n explicit transaction_metadata( const signed_transaction& t, packed_transaction::compression_type c = packed_transaction::none )\n :trx(t),packed_trx(t, c) {\n id = trx.id();\n \/\/raw_packed = fc::raw::pack( static_cast(trx) );\n signed_id = digest_type::hash(packed_trx);\n }\n\n explicit transaction_metadata( const packed_transaction& ptrx )\n :trx( ptrx.get_signed_transaction() ), packed_trx(ptrx) {\n id = trx.id();\n \/\/raw_packed = fc::raw::pack( static_cast(trx) );\n signed_id = digest_type::hash(packed_trx);\n }\n\n const flat_set& recover_keys( const chain_id_type& chain_id ) {\n if( !signing_keys || signing_keys->first != chain_id ) {\/\/ Unlikely for more than one chain_id to be used in one nodeos instance\n if( signing_keys_future.valid() ) {\n signing_keys = std::make_pair( chain_id, signing_keys_future.get());\n } else {\n signing_keys = std::make_pair( chain_id, trx.get_signature_keys( chain_id ));\n }\n }\n return signing_keys->second;\n }\n\n uint32_t total_actions()const { return trx.context_free_actions.size() + trx.actions.size(); }\n};\n\nusing transaction_metadata_ptr = std::shared_ptr;\n\n} } \/\/ eosio::chain\nVerify chain_id even though there is no way for it to be different\/**\n * @file\n * @copyright defined in eos\/LICENSE.txt\n *\/\n#pragma once\n#include \n#include \n#include \n#include \n\nnamespace eosio { namespace chain {\n\n\/**\n * This data structure should store context-free cached data about a transaction such as\n * packed\/unpacked\/compressed and recovered keys\n *\/\nclass transaction_metadata {\n public:\n transaction_id_type id;\n transaction_id_type signed_id;\n signed_transaction trx;\n packed_transaction packed_trx;\n optional>> signing_keys;\n std::future>> signing_keys_future;\n bool accepted = false;\n bool implicit = false;\n bool scheduled = false;\n\n explicit transaction_metadata( const signed_transaction& t, packed_transaction::compression_type c = packed_transaction::none )\n :trx(t),packed_trx(t, c) {\n id = trx.id();\n \/\/raw_packed = fc::raw::pack( static_cast(trx) );\n signed_id = digest_type::hash(packed_trx);\n }\n\n explicit transaction_metadata( const packed_transaction& ptrx )\n :trx( ptrx.get_signed_transaction() ), packed_trx(ptrx) {\n id = trx.id();\n \/\/raw_packed = fc::raw::pack( static_cast(trx) );\n signed_id = digest_type::hash(packed_trx);\n }\n\n const flat_set& recover_keys( const chain_id_type& chain_id ) {\n \/\/ Unlikely for more than one chain_id to be used in one nodeos instance\n if( !signing_keys || signing_keys->first != chain_id ) {\n if( signing_keys_future.valid() ) {\n signing_keys = signing_keys_future.get();\n if( signing_keys->first == chain_id ) {\n return signing_keys->second;\n }\n }\n signing_keys = std::make_pair( chain_id, trx.get_signature_keys( chain_id ));\n }\n return signing_keys->second;\n }\n\n uint32_t total_actions()const { return trx.context_free_actions.size() + trx.actions.size(); }\n};\n\nusing transaction_metadata_ptr = std::shared_ptr;\n\n} } \/\/ eosio::chain\n<|endoftext|>"} {"text":"\/*\n * test_imu.cpp\n *\n * Created on: May 24, 2013\n * Author: drc\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"lcmtypes\/drc_lcmtypes.hpp\"\n#include \n#include \n#include \n#include \"QuaternionLib.h\"\n\n#define PI 3.14159265358979323\n\n\nusing namespace std;\nusing namespace InertialOdometry;\n\nvoid signalHandler( int signum ){\n cout << \"Interrupt signal (\" << signum << \") received.\\n\";\n\n \/\/ cleanup and close up\n try{\n cout << \"Exiting.\\n\";\n } catch (std::exception &e){\n std::cout << \"Exception occurred during close out\\n\";\n }\n \/\/ terminate program\n\n exit(signum);\n\n}\n\n\n\nclass HandleIMU {\nprivate:\n\tboost::shared_ptr _lcm;\n\n\tEigen::Quaterniond imu_orientation;\n\tdouble max;\n\tunsigned long long prev_msg_utime;\n\tunsigned long long fall_utime;\n\t\n\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\tHandleIMU(boost::shared_ptr &_lcm) : _lcm(_lcm) {\n\t\tcout << \"New handler\\n\";\n\t\tmax = 0;\n\t\t_lcm->subscribe(\"TRUE_ROBOT_STATE\",&HandleIMU::true_state_handler,this);\n\t\t_lcm->subscribe(\"TORSO_IMU\",&HandleIMU::torso_state_handler,this);\n\n\t\tprev_msg_utime = 0;\n\t\tfall_utime = 0;\n\n\t}\n\n\tvoid true_state_handler(const lcm::ReceiveBuffer* rbuf,\n\t\t\t\t\t\t\tconst std::string& channel,\n\t\t\t\t\t\t\tconst drc::robot_state_t* msg) {\n\n\t\tEigen::Quaterniond tp_q(msg->origin_position.rotation.w,\n\t\t\t\t\t\t\t\tmsg->origin_position.rotation.x,\n\t\t\t\t\t\t\t\tmsg->origin_position.rotation.y,\n\t\t\t\t\t\t\t\tmsg->origin_position.rotation.z);\n\n\n\t\t\/\/cout << \"\" << (msg->utime - prev_msg_utime)\/1000. << endl;\n\n\t\tprev_msg_utime = msg->utime;\n\n\t\tEigen::Vector3d err_angles;\n\n\t\tEigen::Matrix3d C;\n\t\tC = q2C(tp_q);\n\n\t\terr_angles = C2e(C) - q2e_new(imu_orientation);\n\n\t\tif (err_angles.norm()>max) {\n\t\t\tmax = err_angles.norm();\n\t\t}\n\n\t\tif (err_angles.norm() > 1E-2) {\n\t\t\t\/\/cout << fixed << max*57.29 << \" | \" << err_angles.norm()*57.29 << endl;\n\t\t}\n\t\t\/\/cout << \"Receiving state\\n\";\n\n\t\t\/\/cout << \"num_joints: \" << msg->num_joints << endl;\n\n\t}\n\n\tvoid torso_state_handler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::imu_t* msg) {\n\n\t\tEigen::Quaterniond q(msg->orientation[0],msg->orientation[1],msg->orientation[2],msg->orientation[3]);\n\n\t\timu_orientation = q;\n\n\t\tEigen::Vector4d check_conv;\n\t\tEigen::Quaterniond __q;\n\n\t\t__q = e2q(q2e_new(q));\n\n\t\t\/\/std::cout << \"IMU_ANGLES: \" << q2e_new(q).transpose() << std::endl;\n\n\t\tEigen::Vector3d E;\n\t\tE = q2e_new(q);\n\n\t\t\/\/ fall detector\n\t\tif ((E(1) > 20*PI\/180. || E(0) > 20*PI\/180.) && (msg->utime - fall_utime) > 30000000) {\n\t\t\tfall_utime = msg->utime;\n\t\t\tsystem(\"notify-send ROBOT_FELL_OVER\");\n\t\t}\n\n\t\tcheck_conv(0) = __q.w() - q.w();\n\t\tcheck_conv(1) = __q.x() - q.x();\n\t\tcheck_conv(2) = __q.y() - q.y();\n\t\tcheck_conv(3) = __q.z() - q.z();\n\n\n\t\t\/\/cout << \"Checking additive norm~: \" << check_conv.norm() << endl;\n\n\t\t\/\/cout << \"Receiving IMU\\n\";\n\n\t}\n\n};\n\nint main() {\n\n \/\/Eigen::Matrix3d test;\n\n \/\/test << 1,2,3,4,5,6,7,8,9;\n\n \/\/cout << test(2,1) << endl;\n\n \/\/cout << \"Got here\\n\";\n\n\n \/\/ register signal SIGINT and signal handler\n signal(SIGINT, signalHandler);\n\n system(\"notify-send FallDetectorStarted\");\n\n boost::shared_ptr lcm(new lcm::LCM);\n if(!lcm->good())\n return 1;\n\n HandleIMU handler(lcm);\n\n\n while(0 == lcm->handle());\n\n return 0;\n}\n\n\n\n\n\n\n\n\n\nupdated a timeout flag for fall notification\/*\n * test_imu.cpp\n *\n * Created on: May 24, 2013\n * Author: drc\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"lcmtypes\/drc_lcmtypes.hpp\"\n#include \n#include \n#include \n#include \"QuaternionLib.h\"\n\n#define PI 3.14159265358979323\n\n\nusing namespace std;\nusing namespace InertialOdometry;\n\nvoid signalHandler( int signum ){\n cout << \"Interrupt signal (\" << signum << \") received.\\n\";\n\n \/\/ cleanup and close up\n try{\n cout << \"Exiting.\\n\";\n } catch (std::exception &e){\n std::cout << \"Exception occurred during close out\\n\";\n }\n \/\/ terminate program\n\n exit(signum);\n\n}\n\n\n\nclass HandleIMU {\nprivate:\n\tboost::shared_ptr _lcm;\n\n\tEigen::Quaterniond imu_orientation;\n\tdouble max;\n\tunsigned long long prev_msg_utime;\n\tunsigned long long fall_utime;\n\t\n\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\tHandleIMU(boost::shared_ptr &_lcm) : _lcm(_lcm) {\n\t\tcout << \"New handler\\n\";\n\t\tmax = 0;\n\t\t_lcm->subscribe(\"TRUE_ROBOT_STATE\",&HandleIMU::true_state_handler,this);\n\t\t_lcm->subscribe(\"TORSO_IMU\",&HandleIMU::torso_state_handler,this);\n\n\t\tprev_msg_utime = 0;\n\t\tfall_utime = 0;\n\n\t}\n\n\tvoid true_state_handler(const lcm::ReceiveBuffer* rbuf,\n\t\t\t\t\t\t\tconst std::string& channel,\n\t\t\t\t\t\t\tconst drc::robot_state_t* msg) {\n\n\t\tEigen::Quaterniond tp_q(msg->origin_position.rotation.w,\n\t\t\t\t\t\t\t\tmsg->origin_position.rotation.x,\n\t\t\t\t\t\t\t\tmsg->origin_position.rotation.y,\n\t\t\t\t\t\t\t\tmsg->origin_position.rotation.z);\n\n\n\t\t\/\/cout << \"\" << (msg->utime - prev_msg_utime)\/1000. << endl;\n\n\t\tprev_msg_utime = msg->utime;\n\n\t\tEigen::Vector3d err_angles;\n\n\t\tEigen::Matrix3d C;\n\t\tC = q2C(tp_q);\n\n\t\terr_angles = C2e(C) - q2e_new(imu_orientation);\n\n\t\tif (err_angles.norm()>max) {\n\t\t\tmax = err_angles.norm();\n\t\t}\n\n\t\tif (err_angles.norm() > 1E-2) {\n\t\t\t\/\/cout << fixed << max*57.29 << \" | \" << err_angles.norm()*57.29 << endl;\n\t\t}\n\t\t\/\/cout << \"Receiving state\\n\";\n\n\t\t\/\/cout << \"num_joints: \" << msg->num_joints << endl;\n\n\t}\n\n\tvoid torso_state_handler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::imu_t* msg) {\n\n\t\tEigen::Quaterniond q(msg->orientation[0],msg->orientation[1],msg->orientation[2],msg->orientation[3]);\n\n\t\timu_orientation = q;\n\n\t\tEigen::Vector4d check_conv;\n\t\tEigen::Quaterniond __q;\n\n\t\t__q = e2q(q2e_new(q));\n\n\t\t\/\/std::cout << \"IMU_ANGLES: \" << q2e_new(q).transpose() << std::endl;\n\n\t\tEigen::Vector3d E;\n\t\tE = q2e_new(q);\n\n\t\t\/\/ fall detector\n\n\t\tif (E(1) > 20*PI\/180. || E(0) > 20*PI\/180.) {\n\t\t\t\/\/std::cout << \"Falling\\n\";\n\t\t\tif ((msg->utime - fall_utime) > 1200000) {\n\t\t\t\tstd::cout << \"Timeout.\\n\";\t\t\t\t\n\t\t\t\tfall_utime = msg->utime;\n\t\t\t\tsystem(\"notify-send ROBOT_FELL_OVER\");\n\t\t\t}\n\t\t}\n\n\t\tcheck_conv(0) = __q.w() - q.w();\n\t\tcheck_conv(1) = __q.x() - q.x();\n\t\tcheck_conv(2) = __q.y() - q.y();\n\t\tcheck_conv(3) = __q.z() - q.z();\n\n\n\t\t\/\/cout << \"Checking additive norm~: \" << check_conv.norm() << endl;\n\n\t\t\/\/cout << \"Receiving IMU\\n\";\n\n\t}\n\n};\n\nint main() {\n\n \/\/Eigen::Matrix3d test;\n\n \/\/test << 1,2,3,4,5,6,7,8,9;\n\n \/\/cout << test(2,1) << endl;\n\n \/\/cout << \"Got here\\n\";\n\n\n \/\/ register signal SIGINT and signal handler\n signal(SIGINT, signalHandler);\n\n system(\"notify-send FallDetectorStarted\");\n\n boost::shared_ptr lcm(new lcm::LCM);\n if(!lcm->good())\n return 1;\n\n HandleIMU handler(lcm);\n\n\n while(0 == lcm->handle());\n\n return 0;\n}\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"FIX: Add softmax to MLP multi-class output<|endoftext|>"} {"text":"\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/cublas_pad_for_gemms.h\"\n\n#include \"tensorflow\/compiler\/xla\/literal_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_casting_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instructions.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/compiler\/xla\/window_util.h\"\n\nnamespace xla {\nnamespace gpu {\n\nstatic StatusOr PadForGemm(HloDotInstruction* dot, PrimitiveType datatype,\n int pad_to_multiple_of) {\n auto* lhs = dot->mutable_operand(0);\n auto* rhs = dot->mutable_operand(1);\n\n Shape lshape = lhs->shape();\n Shape rshape = rhs->shape();\n Shape result_shape = dot->shape();\n\n if (lshape.element_type() != datatype || rshape.element_type() != datatype) {\n return false;\n }\n\n auto pad_dim = [&](Shape& s, int dim) {\n s.set_dimensions(dim,\n RoundUpTo(s.dimensions(dim), pad_to_multiple_of));\n };\n\n auto pad_matrix_dims = [&pad_dim](Shape s) {\n \/\/ Since the dot instruction is canonicalized, the last two dimensions for\n \/\/ each operand represent non-batch dimensions, and the others are the same\n \/\/ for both operands and correspond to batch dimensions.\n pad_dim(s, s.rank() - 2);\n pad_dim(s, s.rank() - 1);\n return s;\n };\n\n Shape new_lshape = pad_matrix_dims(lshape);\n Shape new_rshape = pad_matrix_dims(rshape);\n Shape new_result_shape = pad_matrix_dims(result_shape);\n\n if (new_lshape == lshape && new_rshape == rshape) {\n return false;\n }\n\n VLOG(3) << \"old shape: \" << lshape << \" \" << rshape << \" \" << result_shape;\n VLOG(3) << \"new shape: \" << new_lshape << \" \" << new_rshape << \" \"\n << new_result_shape;\n\n auto create_padding_config = [](Shape& shape, Shape& new_shape) {\n PaddingConfig padding_config;\n for (int i = 0; i < shape.rank(); ++i) {\n auto dimension = padding_config.add_dimensions();\n dimension->set_edge_padding_high(new_shape.dimensions()[i] -\n shape.dimensions()[i]);\n dimension->set_edge_padding_low(0);\n dimension->set_interior_padding(0);\n }\n return padding_config;\n };\n\n auto l_padding_config = create_padding_config(lshape, new_lshape);\n auto r_padding_config = create_padding_config(rshape, new_rshape);\n\n HloComputation* parent = dot->parent();\n\n HloInstruction* zero_float = parent->AddInstruction(\n HloInstruction::CreateConstant(LiteralUtil::Zero(datatype)));\n zero_float->set_metadata(dot->metadata());\n\n HloInstruction* lpad = parent->AddInstruction(\n HloInstruction::CreatePad(new_lshape, lhs, zero_float, l_padding_config));\n lpad->set_metadata(dot->metadata());\n\n HloInstruction* rpad = parent->AddInstruction(\n HloInstruction::CreatePad(new_rshape, rhs, zero_float, r_padding_config));\n rpad->set_metadata(dot->metadata());\n\n HloInstruction* new_dot = parent->AddInstruction(\n dot->CloneWithNewOperands(new_result_shape, {lpad, rpad}));\n\n std::vector start_indices(result_shape.rank(), 0);\n std::vector strides(result_shape.rank(), 1);\n HloInstruction* slice = parent->AddInstruction(\n HloInstruction::CreateSlice(result_shape, new_dot, start_indices,\n result_shape.dimensions(), strides));\n slice->set_metadata(dot->metadata());\n\n bool is_root = dot->user_count() == 0;\n\n TF_CHECK_OK(parent->ReplaceInstruction(dot, slice));\n\n if (is_root) {\n parent->set_root_instruction(slice);\n }\n\n return true;\n}\n\nnamespace {\n\n\/\/ We need this check because PadForGemm works in the assumption that\n\/\/ the dot instruction is canonicalized.\nbool CheckCanonical(HloDotInstruction* dot) {\n auto dimension_numbers = dot->dot_dimension_numbers();\n\n if (dimension_numbers.lhs_batch_dimensions_size() + 2 !=\n dot->operand(0)->shape().rank() ||\n dimension_numbers.rhs_batch_dimensions_size() + 2 !=\n dot->operand(1)->shape().rank()) {\n LOG(ERROR) << \"Dot is not canonical: Expected all dimensions but 2 to be \"\n \"batch_dimensions.\";\n return false;\n }\n\n std::vector canonical_batch_dims(\n dimension_numbers.lhs_batch_dimensions_size());\n absl::c_iota(canonical_batch_dims, 0);\n if (!absl::c_equal(dimension_numbers.lhs_batch_dimensions(),\n canonical_batch_dims) ||\n !absl::c_equal(dimension_numbers.rhs_batch_dimensions(),\n canonical_batch_dims)) {\n LOG(ERROR) << \"Dot is not canonical: Expected batch dimensions to be all \"\n \"dimensions except for the last 2 ones.\";\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nstatic std::vector GetRelevantDots(HloComputation* comp,\n PrimitiveType datatype) {\n std::vector gemms;\n\n for (HloInstruction* instr : comp->instructions()) {\n if (IsMatrixMultiplication(*instr)) {\n HloDotInstruction* dot = Cast(instr);\n if (instr->operand(0)->shape().element_type() == datatype &&\n CheckCanonical(dot)) {\n gemms.push_back(dot);\n }\n }\n }\n return gemms;\n}\n\nStatusOr CublasPadForGemms::Run(\n HloModule* module,\n const absl::flat_hash_set& execution_threads) {\n bool changed = false;\n for (HloComputation* comp :\n module->MakeNonfusionComputations(execution_threads)) {\n for (HloDotInstruction* dot : GetRelevantDots(comp, datatype_)) {\n TF_ASSIGN_OR_RETURN(bool result,\n PadForGemm(dot, datatype_, pad_to_multiple_of_));\n changed |= result;\n }\n }\n return changed;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\nReplace error with VLOG\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/cublas_pad_for_gemms.h\"\n\n#include \"tensorflow\/compiler\/xla\/literal_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_casting_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instructions.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/compiler\/xla\/window_util.h\"\n\nnamespace xla {\nnamespace gpu {\n\nstatic StatusOr PadForGemm(HloDotInstruction* dot, PrimitiveType datatype,\n int pad_to_multiple_of) {\n auto* lhs = dot->mutable_operand(0);\n auto* rhs = dot->mutable_operand(1);\n\n Shape lshape = lhs->shape();\n Shape rshape = rhs->shape();\n Shape result_shape = dot->shape();\n\n if (lshape.element_type() != datatype || rshape.element_type() != datatype) {\n return false;\n }\n\n auto pad_dim = [&](Shape& s, int dim) {\n s.set_dimensions(dim,\n RoundUpTo(s.dimensions(dim), pad_to_multiple_of));\n };\n\n auto pad_matrix_dims = [&pad_dim](Shape s) {\n \/\/ Since the dot instruction is canonicalized, the last two dimensions for\n \/\/ each operand represent non-batch dimensions, and the others are the same\n \/\/ for both operands and correspond to batch dimensions.\n pad_dim(s, s.rank() - 2);\n pad_dim(s, s.rank() - 1);\n return s;\n };\n\n Shape new_lshape = pad_matrix_dims(lshape);\n Shape new_rshape = pad_matrix_dims(rshape);\n Shape new_result_shape = pad_matrix_dims(result_shape);\n\n if (new_lshape == lshape && new_rshape == rshape) {\n return false;\n }\n\n VLOG(3) << \"old shape: \" << lshape << \" \" << rshape << \" \" << result_shape;\n VLOG(3) << \"new shape: \" << new_lshape << \" \" << new_rshape << \" \"\n << new_result_shape;\n\n auto create_padding_config = [](Shape& shape, Shape& new_shape) {\n PaddingConfig padding_config;\n for (int i = 0; i < shape.rank(); ++i) {\n auto dimension = padding_config.add_dimensions();\n dimension->set_edge_padding_high(new_shape.dimensions()[i] -\n shape.dimensions()[i]);\n dimension->set_edge_padding_low(0);\n dimension->set_interior_padding(0);\n }\n return padding_config;\n };\n\n auto l_padding_config = create_padding_config(lshape, new_lshape);\n auto r_padding_config = create_padding_config(rshape, new_rshape);\n\n HloComputation* parent = dot->parent();\n\n HloInstruction* zero_float = parent->AddInstruction(\n HloInstruction::CreateConstant(LiteralUtil::Zero(datatype)));\n zero_float->set_metadata(dot->metadata());\n\n HloInstruction* lpad = parent->AddInstruction(\n HloInstruction::CreatePad(new_lshape, lhs, zero_float, l_padding_config));\n lpad->set_metadata(dot->metadata());\n\n HloInstruction* rpad = parent->AddInstruction(\n HloInstruction::CreatePad(new_rshape, rhs, zero_float, r_padding_config));\n rpad->set_metadata(dot->metadata());\n\n HloInstruction* new_dot = parent->AddInstruction(\n dot->CloneWithNewOperands(new_result_shape, {lpad, rpad}));\n\n std::vector start_indices(result_shape.rank(), 0);\n std::vector strides(result_shape.rank(), 1);\n HloInstruction* slice = parent->AddInstruction(\n HloInstruction::CreateSlice(result_shape, new_dot, start_indices,\n result_shape.dimensions(), strides));\n slice->set_metadata(dot->metadata());\n\n bool is_root = dot->user_count() == 0;\n\n TF_CHECK_OK(parent->ReplaceInstruction(dot, slice));\n\n if (is_root) {\n parent->set_root_instruction(slice);\n }\n\n return true;\n}\n\nnamespace {\n\n\/\/ We need this check because PadForGemm works in the assumption that\n\/\/ the dot instruction is canonicalized.\nbool CheckCanonical(HloDotInstruction* dot) {\n auto dimension_numbers = dot->dot_dimension_numbers();\n\n if (dimension_numbers.lhs_batch_dimensions_size() + 2 !=\n dot->operand(0)->shape().rank() ||\n dimension_numbers.rhs_batch_dimensions_size() + 2 !=\n dot->operand(1)->shape().rank()) {\n VLOG(2)\n << dot->ToString()\n << \" is not canonical: Expected all dimensions but 2 to be \"\n \"batch_dimensions. Hence, this dot is not a candidate for padding.\";\n return false;\n }\n\n std::vector canonical_batch_dims(\n dimension_numbers.lhs_batch_dimensions_size());\n absl::c_iota(canonical_batch_dims, 0);\n if (!absl::c_equal(dimension_numbers.lhs_batch_dimensions(),\n canonical_batch_dims) ||\n !absl::c_equal(dimension_numbers.rhs_batch_dimensions(),\n canonical_batch_dims)) {\n VLOG(2)\n dot->ToString()\n << \" is not canonical: Expected batch dimensions to be all \"\n \"dimensions except for the last 2 ones. Hence, this dot is not a \"\n \"candidate for padding.\";\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nstatic std::vector GetRelevantDots(HloComputation* comp,\n PrimitiveType datatype) {\n std::vector gemms;\n\n for (HloInstruction* instr : comp->instructions()) {\n if (IsMatrixMultiplication(*instr)) {\n HloDotInstruction* dot = Cast(instr);\n if (instr->operand(0)->shape().element_type() == datatype &&\n CheckCanonical(dot)) {\n gemms.push_back(dot);\n }\n }\n }\n return gemms;\n}\n\nStatusOr CublasPadForGemms::Run(\n HloModule* module,\n const absl::flat_hash_set& execution_threads) {\n bool changed = false;\n for (HloComputation* comp :\n module->MakeNonfusionComputations(execution_threads)) {\n for (HloDotInstruction* dot : GetRelevantDots(comp, datatype_)) {\n TF_ASSIGN_OR_RETURN(bool result,\n PadForGemm(dot, datatype_, pad_to_multiple_of_));\n changed |= result;\n }\n }\n return changed;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ This test verifies behavior specified by [atomics.types.operations.req]\/21:\n\/\/\n\/\/ When only one memory_order argument is supplied, the value of success is\n\/\/ order, and the value of failure is order except that a value of\n\/\/ memory_order_acq_rel shall be replaced by the value memory_order_acquire\n\/\/ and a value of memory_order_release shall be replaced by the value\n\/\/ memory_order_relaxed.\n\/\/\n\/\/ Clang's atomic intrinsics do this for us, but GCC's do not. We don't actually\n\/\/ have visibility to see what these memory orders are lowered to, but we can at\n\/\/ least check that they are lowered at all (otherwise there is a compile\n\/\/ failure with GCC).\n\n#include \n\nint main() {\n std::atomic i;\n volatile std::atomic v;\n int exp;\n\n i.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);\n i.compare_exchange_weak(exp, 0, std::memory_order_release);\n i.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);\n i.compare_exchange_strong(exp, 0, std::memory_order_release);\n\n v.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);\n v.compare_exchange_weak(exp, 0, std::memory_order_release);\n v.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);\n v.compare_exchange_strong(exp, 0, std::memory_order_release);\n\n return 0;\n}\nAppease MSAN buildbots.\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ This test verifies behavior specified by [atomics.types.operations.req]\/21:\n\/\/\n\/\/ When only one memory_order argument is supplied, the value of success is\n\/\/ order, and the value of failure is order except that a value of\n\/\/ memory_order_acq_rel shall be replaced by the value memory_order_acquire\n\/\/ and a value of memory_order_release shall be replaced by the value\n\/\/ memory_order_relaxed.\n\/\/\n\/\/ Clang's atomic intrinsics do this for us, but GCC's do not. We don't actually\n\/\/ have visibility to see what these memory orders are lowered to, but we can at\n\/\/ least check that they are lowered at all (otherwise there is a compile\n\/\/ failure with GCC).\n\n#include \n\nint main() {\n std::atomic i;\n volatile std::atomic v;\n int exp = 0;\n\n i.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);\n i.compare_exchange_weak(exp, 0, std::memory_order_release);\n i.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);\n i.compare_exchange_strong(exp, 0, std::memory_order_release);\n\n v.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);\n v.compare_exchange_weak(exp, 0, std::memory_order_release);\n v.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);\n v.compare_exchange_strong(exp, 0, std::memory_order_release);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"integrators\/embedded_explicit_runge_kutta_nyström_integrator.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"geometry\/sign.hpp\"\n#include \"glog\/logging.h\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace integrators {\nnamespace internal_embedded_explicit_runge_kutta_nyström_integrator {\n\nusing base::make_not_null_unique;\nusing geometry::Sign;\nusing numerics::DoublePrecision;\nusing quantities::DebugString;\nusing quantities::Difference;\nusing quantities::Quotient;\n\ntemplate\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nEmbeddedExplicitRungeKuttaNyströmIntegrator()\n : AdaptiveStepSizeIntegrator<\n SpecialSecondOrderDifferentialEquation>(Method::kind) {\n \/\/ the first node is always 0 in an explicit method.\n CHECK_EQ(0.0, c_[0]);\n if (first_same_as_last) {\n \/\/ Check that the conditions for the FSAL property are satisfied, see for\n \/\/ instance Dormand, El-Mikkawy and Prince (1986),\n \/\/ Families of Runge-Kutta-Nyström formulae, equation 3.1.\n CHECK_EQ(1.0, c_[stages_ - 1]);\n CHECK_EQ(0.0, b_hat_[stages_ - 1]);\n for (int j = 0; j < stages_ - 1; ++j) {\n CHECK_EQ(b_hat_[j], a_[stages_ - 1][j]);\n }\n }\n}\n\ntemplate\nStatus EmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::Solve(Instant const& t_final) {\n using Displacement = typename ODE::Displacement;\n using Velocity = typename ODE::Velocity;\n using Acceleration = typename ODE::Acceleration;\n\n auto const& a = integrator_.a_;\n auto const& b_hat = integrator_.b_hat_;\n auto const& b_prime_hat = integrator_.b_prime_hat_;\n auto const& b = integrator_.b_;\n auto const& b_prime = integrator_.b_prime_;\n auto const& c = integrator_.c_;\n\n auto& append_state = this->append_state_;\n auto& current_state = this->current_state_;\n auto& first_use = this->first_use_;\n auto& parameters = this->parameters_;\n auto const& equation = this->equation_;\n\n \/\/ |current_state| gets updated as the integration progresses to allow\n \/\/ restartability.\n\n \/\/ State before the last, truncated step.\n std::experimental::optional final_state;\n\n \/\/ Argument checks.\n int const dimension = current_state.positions.size();\n Sign const integration_direction = Sign(parameters.first_time_step);\n if (integration_direction.Positive()) {\n \/\/ Integrating forward.\n CHECK_LT(current_state.time.value, t_final);\n } else {\n \/\/ Integrating backward.\n CHECK_GT(current_state.time.value, t_final);\n }\n CHECK(first_use || !parameters.last_step_is_exact)\n << \"Cannot reuse an instance where the last step is exact\";\n first_use = false;\n\n \/\/ Time step. Updated as the integration progresses to allow restartability.\n Time& h = this->time_step_;\n \/\/ Current time. This is a non-const reference whose purpose is to make the\n \/\/ equations more readable.\n DoublePrecision& t = current_state.time;\n\n \/\/ Position increment (high-order).\n std::vector Δq_hat(dimension);\n \/\/ Velocity increment (high-order).\n std::vector Δv_hat(dimension);\n \/\/ Current position. This is a non-const reference whose purpose is to make\n \/\/ the equations more readable.\n std::vector>& q_hat = current_state.positions;\n \/\/ Current velocity. This is a non-const reference whose purpose is to make\n \/\/ the equations more readable.\n std::vector>& v_hat = current_state.velocities;\n\n \/\/ Difference between the low- and high-order approximations.\n typename ODE::SystemStateError error_estimate;\n error_estimate.position_error.resize(dimension);\n error_estimate.velocity_error.resize(dimension);\n\n \/\/ Current Runge-Kutta-Nyström stage.\n std::vector q_stage(dimension);\n \/\/ Accelerations at each stage.\n \/\/ TODO(egg): this is a rectangular container, use something more appropriate.\n std::vector> g(stages_);\n for (auto& g_stage : g) {\n g_stage.resize(dimension);\n }\n\n bool at_end = false;\n double tolerance_to_error_ratio;\n\n \/\/ The first stage of the Runge-Kutta-Nyström iteration. In the FSAL case,\n \/\/ |first_stage == 1| after the first step, since the first RHS evaluation has\n \/\/ already occured in the previous step. In the non-FSAL case and in the\n \/\/ first step of the FSAL case, |first_stage == 0|.\n int first_stage = 0;\n\n \/\/ The number of steps already performed.\n std::int64_t step_count = 0;\n\n Status status;\n\n \/\/ No step size control on the first step. If this instance is being\n \/\/ restarted we already have a value of |h| suitable for the next step, based\n \/\/ on the computation of |tolerance_to_error_ratio_| during the last\n \/\/ invocation.\n goto runge_kutta_nyström_step;\n\n while (!at_end) {\n \/\/ Compute the next step with decreasing step sizes until the error is\n \/\/ tolerable.\n do {\n \/\/ Adapt step size.\n \/\/ TODO(egg): find out whether there's a smarter way to compute that root,\n \/\/ especially since we make the order compile-time.\n h *= parameters.safety_factor *\n std::pow(tolerance_to_error_ratio, 1.0 \/ (lower_order + 1));\n \/\/ TODO(egg): should we check whether it vanishes in double precision\n \/\/ instead?\n if (t.value + (t.error + h) == t.value) {\n return Status(termination_condition::VanishingStepSize,\n \"At time \" + DebugString(t.value) +\n \", step size is effectively zero. Singularity or \"\n \"stiff system suspected.\");\n }\n\n runge_kutta_nyström_step:\n \/\/ Termination condition.\n if (parameters.last_step_is_exact) {\n Time const time_to_end = (t_final - t.value) - t.error;\n at_end = integration_direction * h >=\n integration_direction * time_to_end;\n if (at_end) {\n \/\/ The chosen step size will overshoot. Clip it to just reach the\n \/\/ end, and terminate if the step is accepted.\n h = time_to_end;\n final_state = current_state;\n }\n }\n\n \/\/ Runge-Kutta-Nyström iteration; fills |g|.\n for (int i = first_stage; i < stages_; ++i) {\n Instant const t_stage = t.value + (t.error + c[i] * h);\n for (int k = 0; k < dimension; ++k) {\n Acceleration Σj_a_ij_g_jk{};\n for (int j = 0; j < i; ++j) {\n Σj_a_ij_g_jk += a[i][j] * g[j][k];\n }\n q_stage[k] = q_hat[k].value +\n h * (c[i] * v_hat[k].value + h * Σj_a_ij_g_jk);\n }\n status.Update(equation.compute_acceleration(t_stage, q_stage, g[i]));\n }\n\n \/\/ Increment computation and step size control.\n for (int k = 0; k < dimension; ++k) {\n Acceleration Σi_b_hat_i_g_ik{};\n Acceleration Σi_b_i_g_ik{};\n Acceleration Σi_b_prime_hat_i_g_ik{};\n Acceleration Σi_b_prime_i_g_ik{};\n \/\/ Please keep the eight assigments below aligned, they become illegible\n \/\/ otherwise.\n for (int i = 0; i < stages_; ++i) {\n Σi_b_hat_i_g_ik += b_hat[i] * g[i][k];\n Σi_b_i_g_ik += b[i] * g[i][k];\n Σi_b_prime_hat_i_g_ik += b_prime_hat[i] * g[i][k];\n Σi_b_prime_i_g_ik += b_prime[i] * g[i][k];\n }\n \/\/ The hat-less Δq and Δv are the low-order increments.\n Δq_hat[k] = h * (h * (Σi_b_hat_i_g_ik) + v_hat[k].value);\n Displacement const Δq_k = h * (h * (Σi_b_i_g_ik) + v_hat[k].value);\n Δv_hat[k] = h * Σi_b_prime_hat_i_g_ik;\n Velocity const Δv_k = h * Σi_b_prime_i_g_ik;\n\n error_estimate.position_error[k] = Δq_k - Δq_hat[k];\n error_estimate.velocity_error[k] = Δv_k - Δv_hat[k];\n }\n tolerance_to_error_ratio =\n this->tolerance_to_error_ratio_(h, error_estimate);\n } while (tolerance_to_error_ratio < 1.0);\n\n if (!parameters.last_step_is_exact && t.value + (t.error + h) > t_final) {\n \/\/ We did overshoot. Drop the point that we just computed and exit.\n final_state = current_state;\n break;\n }\n\n if (first_same_as_last) {\n using std::swap;\n swap(g.front(), g.back());\n first_stage = 1;\n }\n\n \/\/ Increment the solution with the high-order approximation.\n t.Increment(h);\n for (int k = 0; k < dimension; ++k) {\n q_hat[k].Increment(Δq_hat[k]);\n v_hat[k].Increment(Δv_hat[k]);\n }\n append_state(current_state);\n ++step_count;\n if (step_count == parameters.max_steps && !at_end) {\n return Status(termination_condition::ReachedMaximalStepCount,\n \"Reached maximum step count \" +\n std::to_string(parameters.max_steps) +\n \" at time \" + DebugString(t.value) +\n \"; requested t_final is \" + DebugString(t_final) +\n \".\");\n }\n }\n \/\/ The resolution is restartable from the last non-truncated state.\n CHECK(final_state);\n current_state = *final_state;\n return status;\n}\n\ntemplate\nEmbeddedExplicitRungeKuttaNyströmIntegrator const&\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::integrator() const {\n return integrator_;\n}\n\ntemplate\nnot_null>::Instance>>\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::Clone() const {\n return std::unique_ptr(new Instance(*this));\n}\n\ntemplate\nvoid EmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::WriteToMessage(\n not_null message) const {\n AdaptiveStepSizeIntegrator::Instance::WriteToMessage(message);\n auto* const extension =\n message\n ->MutableExtension(\n serialization::AdaptiveStepSizeIntegratorInstance::extension)\n ->MutableExtension(\n serialization::\n EmbeddedExplicitRungeKuttaNystromIntegratorInstance::\n extension);\n}\n\ntemplate\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::Instance(\n IntegrationProblem const& problem,\n AppendState const& append_state,\n ToleranceToErrorRatio const& tolerance_to_error_ratio,\n Parameters const& parameters,\n EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator)\n : AdaptiveStepSizeIntegrator::Instance(\n problem, append_state, tolerance_to_error_ratio, parameters),\n integrator_(integrator) {}\n\ntemplate\nnot_null>::Instance>>\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nNewInstance(IntegrationProblem const& problem,\n AppendState const& append_state,\n ToleranceToErrorRatio const& tolerance_to_error_ratio,\n Parameters const& parameters) const {\n \/\/ Cannot use |make_not_null_unique| because the constructor of |Instance| is\n \/\/ private.\n return std::unique_ptr(new Instance(problem,\n append_state,\n tolerance_to_error_ratio,\n parameters,\n *this));\n}\n\ntemplate\nnot_null>::Instance>>\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nReadFromMessage(\n serialization::AdaptiveStepSizeIntegratorInstance const& message,\n IntegrationProblem const& problem,\n AppendState const& append_state,\n ToleranceToErrorRatio const& tolerance_to_error_ratio,\n Parameters const& parameters) const {\n CHECK(message.HasExtension(\n serialization::EmbeddedExplicitRungeKuttaNystromIntegratorInstance::\n extension))\n << message.DebugString();\n\n \/\/ Cannot use |make_not_null_unique| because the constructor of |Instance| is\n \/\/ private.\n return std::unique_ptr::Instance>(\n new Instance(problem,\n append_state,\n tolerance_to_error_ratio,\n parameters,\n *this));\n}\n\n} \/\/ namespace internal_embedded_explicit_runge_kutta_nyström_integrator\n\ntemplate\ninternal_embedded_explicit_runge_kutta_nyström_integrator::\n EmbeddedExplicitRungeKuttaNyströmIntegrator const&\nEmbeddedExplicitRungeKuttaNyströmIntegrator() {\n static_assert(\n std::is_base_of::value,\n \"Method must be derived from EmbeddedExplicitRungeKuttaNyström\");\n static internal_embedded_explicit_runge_kutta_nyström_integrator::\n EmbeddedExplicitRungeKuttaNyströmIntegrator const\n integrator;\n return integrator;\n}\n\n} \/\/ namespace integrators\n} \/\/ namespace principia\nLint.\n#pragma once\n\n#include \"integrators\/embedded_explicit_runge_kutta_nyström_integrator.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"geometry\/sign.hpp\"\n#include \"glog\/logging.h\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace integrators {\nnamespace internal_embedded_explicit_runge_kutta_nyström_integrator {\n\nusing base::make_not_null_unique;\nusing geometry::Sign;\nusing numerics::DoublePrecision;\nusing quantities::DebugString;\nusing quantities::Difference;\nusing quantities::Quotient;\n\ntemplate\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nEmbeddedExplicitRungeKuttaNyströmIntegrator()\n : AdaptiveStepSizeIntegrator<\n SpecialSecondOrderDifferentialEquation>(Method::kind) {\n \/\/ the first node is always 0 in an explicit method.\n CHECK_EQ(0.0, c_[0]);\n if (first_same_as_last) {\n \/\/ Check that the conditions for the FSAL property are satisfied, see for\n \/\/ instance Dormand, El-Mikkawy and Prince (1986),\n \/\/ Families of Runge-Kutta-Nyström formulae, equation 3.1.\n CHECK_EQ(1.0, c_[stages_ - 1]);\n CHECK_EQ(0.0, b_hat_[stages_ - 1]);\n for (int j = 0; j < stages_ - 1; ++j) {\n CHECK_EQ(b_hat_[j], a_[stages_ - 1][j]);\n }\n }\n}\n\ntemplate\nStatus EmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::Solve(Instant const& t_final) {\n using Displacement = typename ODE::Displacement;\n using Velocity = typename ODE::Velocity;\n using Acceleration = typename ODE::Acceleration;\n\n auto const& a = integrator_.a_;\n auto const& b_hat = integrator_.b_hat_;\n auto const& b_prime_hat = integrator_.b_prime_hat_;\n auto const& b = integrator_.b_;\n auto const& b_prime = integrator_.b_prime_;\n auto const& c = integrator_.c_;\n\n auto& append_state = this->append_state_;\n auto& current_state = this->current_state_;\n auto& first_use = this->first_use_;\n auto& parameters = this->parameters_;\n auto const& equation = this->equation_;\n\n \/\/ |current_state| gets updated as the integration progresses to allow\n \/\/ restartability.\n\n \/\/ State before the last, truncated step.\n std::experimental::optional final_state;\n\n \/\/ Argument checks.\n int const dimension = current_state.positions.size();\n Sign const integration_direction = Sign(parameters.first_time_step);\n if (integration_direction.Positive()) {\n \/\/ Integrating forward.\n CHECK_LT(current_state.time.value, t_final);\n } else {\n \/\/ Integrating backward.\n CHECK_GT(current_state.time.value, t_final);\n }\n CHECK(first_use || !parameters.last_step_is_exact)\n << \"Cannot reuse an instance where the last step is exact\";\n first_use = false;\n\n \/\/ Time step. Updated as the integration progresses to allow restartability.\n Time& h = this->time_step_;\n \/\/ Current time. This is a non-const reference whose purpose is to make the\n \/\/ equations more readable.\n DoublePrecision& t = current_state.time;\n\n \/\/ Position increment (high-order).\n std::vector Δq_hat(dimension);\n \/\/ Velocity increment (high-order).\n std::vector Δv_hat(dimension);\n \/\/ Current position. This is a non-const reference whose purpose is to make\n \/\/ the equations more readable.\n std::vector>& q_hat = current_state.positions;\n \/\/ Current velocity. This is a non-const reference whose purpose is to make\n \/\/ the equations more readable.\n std::vector>& v_hat = current_state.velocities;\n\n \/\/ Difference between the low- and high-order approximations.\n typename ODE::SystemStateError error_estimate;\n error_estimate.position_error.resize(dimension);\n error_estimate.velocity_error.resize(dimension);\n\n \/\/ Current Runge-Kutta-Nyström stage.\n std::vector q_stage(dimension);\n \/\/ Accelerations at each stage.\n \/\/ TODO(egg): this is a rectangular container, use something more appropriate.\n std::vector> g(stages_);\n for (auto& g_stage : g) {\n g_stage.resize(dimension);\n }\n\n bool at_end = false;\n double tolerance_to_error_ratio;\n\n \/\/ The first stage of the Runge-Kutta-Nyström iteration. In the FSAL case,\n \/\/ |first_stage == 1| after the first step, since the first RHS evaluation has\n \/\/ already occured in the previous step. In the non-FSAL case and in the\n \/\/ first step of the FSAL case, |first_stage == 0|.\n int first_stage = 0;\n\n \/\/ The number of steps already performed.\n std::int64_t step_count = 0;\n\n Status status;\n\n \/\/ No step size control on the first step. If this instance is being\n \/\/ restarted we already have a value of |h| suitable for the next step, based\n \/\/ on the computation of |tolerance_to_error_ratio_| during the last\n \/\/ invocation.\n goto runge_kutta_nyström_step;\n\n while (!at_end) {\n \/\/ Compute the next step with decreasing step sizes until the error is\n \/\/ tolerable.\n do {\n \/\/ Adapt step size.\n \/\/ TODO(egg): find out whether there's a smarter way to compute that root,\n \/\/ especially since we make the order compile-time.\n h *= parameters.safety_factor *\n std::pow(tolerance_to_error_ratio, 1.0 \/ (lower_order + 1));\n \/\/ TODO(egg): should we check whether it vanishes in double precision\n \/\/ instead?\n if (t.value + (t.error + h) == t.value) {\n return Status(termination_condition::VanishingStepSize,\n \"At time \" + DebugString(t.value) +\n \", step size is effectively zero. Singularity or \"\n \"stiff system suspected.\");\n }\n\n runge_kutta_nyström_step:\n \/\/ Termination condition.\n if (parameters.last_step_is_exact) {\n Time const time_to_end = (t_final - t.value) - t.error;\n at_end = integration_direction * h >=\n integration_direction * time_to_end;\n if (at_end) {\n \/\/ The chosen step size will overshoot. Clip it to just reach the\n \/\/ end, and terminate if the step is accepted.\n h = time_to_end;\n final_state = current_state;\n }\n }\n\n \/\/ Runge-Kutta-Nyström iteration; fills |g|.\n for (int i = first_stage; i < stages_; ++i) {\n Instant const t_stage = t.value + (t.error + c[i] * h);\n for (int k = 0; k < dimension; ++k) {\n Acceleration Σj_a_ij_g_jk{};\n for (int j = 0; j < i; ++j) {\n Σj_a_ij_g_jk += a[i][j] * g[j][k];\n }\n q_stage[k] = q_hat[k].value +\n h * (c[i] * v_hat[k].value + h * Σj_a_ij_g_jk);\n }\n status.Update(equation.compute_acceleration(t_stage, q_stage, g[i]));\n }\n\n \/\/ Increment computation and step size control.\n for (int k = 0; k < dimension; ++k) {\n Acceleration Σi_b_hat_i_g_ik{};\n Acceleration Σi_b_i_g_ik{};\n Acceleration Σi_b_prime_hat_i_g_ik{};\n Acceleration Σi_b_prime_i_g_ik{};\n \/\/ Please keep the eight assigments below aligned, they become illegible\n \/\/ otherwise.\n for (int i = 0; i < stages_; ++i) {\n Σi_b_hat_i_g_ik += b_hat[i] * g[i][k];\n Σi_b_i_g_ik += b[i] * g[i][k];\n Σi_b_prime_hat_i_g_ik += b_prime_hat[i] * g[i][k];\n Σi_b_prime_i_g_ik += b_prime[i] * g[i][k];\n }\n \/\/ The hat-less Δq and Δv are the low-order increments.\n Δq_hat[k] = h * (h * (Σi_b_hat_i_g_ik) + v_hat[k].value);\n Displacement const Δq_k = h * (h * (Σi_b_i_g_ik) + v_hat[k].value);\n Δv_hat[k] = h * Σi_b_prime_hat_i_g_ik;\n Velocity const Δv_k = h * Σi_b_prime_i_g_ik;\n\n error_estimate.position_error[k] = Δq_k - Δq_hat[k];\n error_estimate.velocity_error[k] = Δv_k - Δv_hat[k];\n }\n tolerance_to_error_ratio =\n this->tolerance_to_error_ratio_(h, error_estimate);\n } while (tolerance_to_error_ratio < 1.0);\n\n if (!parameters.last_step_is_exact && t.value + (t.error + h) > t_final) {\n \/\/ We did overshoot. Drop the point that we just computed and exit.\n final_state = current_state;\n break;\n }\n\n if (first_same_as_last) {\n using std::swap;\n swap(g.front(), g.back());\n first_stage = 1;\n }\n\n \/\/ Increment the solution with the high-order approximation.\n t.Increment(h);\n for (int k = 0; k < dimension; ++k) {\n q_hat[k].Increment(Δq_hat[k]);\n v_hat[k].Increment(Δv_hat[k]);\n }\n append_state(current_state);\n ++step_count;\n if (step_count == parameters.max_steps && !at_end) {\n return Status(termination_condition::ReachedMaximalStepCount,\n \"Reached maximum step count \" +\n std::to_string(parameters.max_steps) +\n \" at time \" + DebugString(t.value) +\n \"; requested t_final is \" + DebugString(t_final) +\n \".\");\n }\n }\n \/\/ The resolution is restartable from the last non-truncated state.\n CHECK(final_state);\n current_state = *final_state;\n return status;\n}\n\ntemplate\nEmbeddedExplicitRungeKuttaNyströmIntegrator const&\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::integrator() const {\n return integrator_;\n}\n\ntemplate\nnot_null>::Instance>>\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::Clone() const {\n return std::unique_ptr(new Instance(*this));\n}\n\ntemplate\nvoid EmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::WriteToMessage(\n not_null message) const {\n AdaptiveStepSizeIntegrator::Instance::WriteToMessage(message);\n auto* const extension =\n message\n ->MutableExtension(\n serialization::AdaptiveStepSizeIntegratorInstance::extension)\n ->MutableExtension(\n serialization::\n EmbeddedExplicitRungeKuttaNystromIntegratorInstance::\n extension);\n}\n\ntemplate\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nInstance::Instance(\n IntegrationProblem const& problem,\n AppendState const& append_state,\n ToleranceToErrorRatio const& tolerance_to_error_ratio,\n Parameters const& parameters,\n EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator)\n : AdaptiveStepSizeIntegrator::Instance(\n problem, append_state, tolerance_to_error_ratio, parameters),\n integrator_(integrator) {}\n\ntemplate\nnot_null>::Instance>>\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nNewInstance(IntegrationProblem const& problem,\n AppendState const& append_state,\n ToleranceToErrorRatio const& tolerance_to_error_ratio,\n Parameters const& parameters) const {\n \/\/ Cannot use |make_not_null_unique| because the constructor of |Instance| is\n \/\/ private.\n return std::unique_ptr(new Instance(problem,\n append_state,\n tolerance_to_error_ratio,\n parameters,\n *this));\n}\n\ntemplate\nnot_null>::Instance>>\nEmbeddedExplicitRungeKuttaNyströmIntegrator::\nReadFromMessage(\n serialization::AdaptiveStepSizeIntegratorInstance const& message,\n IntegrationProblem const& problem,\n AppendState const& append_state,\n ToleranceToErrorRatio const& tolerance_to_error_ratio,\n Parameters const& parameters) const {\n CHECK(message.HasExtension(\n serialization::EmbeddedExplicitRungeKuttaNystromIntegratorInstance::\n extension))\n << message.DebugString();\n\n \/\/ Cannot use |make_not_null_unique| because the constructor of |Instance| is\n \/\/ private.\n return std::unique_ptr::Instance>(\n new Instance(problem,\n append_state,\n tolerance_to_error_ratio,\n parameters,\n *this));\n}\n\n} \/\/ namespace internal_embedded_explicit_runge_kutta_nyström_integrator\n\ntemplate\ninternal_embedded_explicit_runge_kutta_nyström_integrator::\n EmbeddedExplicitRungeKuttaNyströmIntegrator const&\nEmbeddedExplicitRungeKuttaNyströmIntegrator() {\n static_assert(\n std::is_base_of::value,\n \"Method must be derived from EmbeddedExplicitRungeKuttaNyström\");\n static internal_embedded_explicit_runge_kutta_nyström_integrator::\n EmbeddedExplicitRungeKuttaNyströmIntegrator const\n integrator;\n return integrator;\n}\n\n} \/\/ namespace integrators\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\/*\n Copyright 2005-2007 Adobe Systems Incorporated\n Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt\n or a copy at http:\/\/stlab.adobe.com\/licenses.html)\n*\/\n\n\/****************************************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\n\/****************************************************************************************************\/\n\nnamespace {\n\n\/****************************************************************************************************\/\n\n\/\/ TODO: Put this into StyleFactory.\nclass Window :\n public GG::Wnd\n{\npublic:\n static const unsigned int BEVEL = 2;\n\n Window(adobe::window_t& imp) :\n Wnd(GG::X0, GG::Y0, GG::X1, GG::Y1, imp.flags_m),\n m_imp(imp),\n m_title(0)\n {\n if (!m_imp.name_m.empty()) {\n m_title = adobe::implementation::Factory().NewTextControl(\n BEVEL_OFFSET.x, BEVEL_OFFSET.y - adobe::implementation::CharHeight(),\n m_imp.name_m, adobe::implementation::DefaultFont()\n );\n AttachChild(m_title);\n }\n }\n\n virtual GG::Pt ClientUpperLeft() const\n { return UpperLeft() + BEVEL_OFFSET + GG::Pt(GG::X0, m_title ? m_title->Height() : GG::Y0); }\n\n virtual GG::Pt ClientLowerRight() const\n { return LowerRight() - BEVEL_OFFSET; }\n\n virtual GG::WndRegion WindowRegion(const GG::Pt& pt) const\n {\n enum {LEFT = 0, MIDDLE = 1, RIGHT = 2};\n enum {TOP = 0, BOTTOM = 2};\n\n \/\/ window regions look like this:\n \/\/ 0111112\n \/\/ 3444445 \/\/ 4 is client area, 0,2,6,8 are corners\n \/\/ 3444445\n \/\/ 6777778\n\n int x_pos = MIDDLE; \/\/ default & typical case is that the mouse is over the (non-border) client area\n int y_pos = MIDDLE;\n\n GG::Pt ul = UpperLeft() + BEVEL_OFFSET, lr = LowerRight() - BEVEL_OFFSET;\n\n if (pt.x < ul.x)\n x_pos = LEFT;\n else if (pt.x > lr.x)\n x_pos = RIGHT;\n\n if (pt.y < ul.y)\n y_pos = TOP;\n else if (pt.y > lr.y)\n y_pos = BOTTOM;\n\n return (Resizable() ? GG::WndRegion(x_pos + 3 * y_pos) : GG::WR_NONE);\n }\n\n virtual void SizeMove(const GG::Pt& ul, const GG::Pt& lr)\n {\n GG::Pt client_size = ClientSize();\n\n if (!m_imp.debounce_m && !m_imp.resize_proc_m.empty()) {\n m_imp.debounce_m = true;\n\n if (adobe::width(m_imp.place_data_m) != Value(client_size.x) ||\n adobe::height(m_imp.place_data_m) != Value(client_size.y)) {\n m_imp.resize_proc_m(Value(client_size.x), Value(client_size.y));\n\n adobe::width(m_imp.place_data_m) = Value(client_size.x);\n adobe::height(m_imp.place_data_m) = Value(client_size.y);\n }\n\n m_imp.debounce_m = false;\n }\n\n GG::Wnd::SizeMove(ul, lr);\n\n GG::Pt new_title_size((LowerRight() - UpperLeft()).x - BEVEL_OFFSET.x * 2, m_title->Height());\n m_title->Resize(new_title_size);\n }\n\n virtual void Render()\n { GG::BeveledRectangle(UpperLeft(), LowerRight(), GG::CLR_GRAY, GG::CLR_GRAY, true, BEVEL); }\n\n virtual void KeyPress(GG::Key key, boost::uint32_t key_code_point,\n GG::Flags mod_keys)\n {\n adobe::keyboard_t::get().dispatch(adobe::key_type(key, key_code_point),\n true,\n adobe::modifier_state(),\n adobe::any_regular_t(this));\n }\n\n virtual void KeyRelease(GG::Key key, boost::uint32_t key_code_point,\n GG::Flags mod_keys)\n {\n adobe::keyboard_t::get().dispatch(adobe::key_type(key, key_code_point),\n false,\n adobe::modifier_state(),\n adobe::any_regular_t(this));\n }\n\nprivate:\n adobe::window_t& m_imp;\n GG::TextControl* m_title;\n\n static const int FRAME_WIDTH;\n static const GG::Pt BEVEL_OFFSET;\n};\n\nconst int Window::FRAME_WIDTH = 2;\nconst GG::Pt Window::BEVEL_OFFSET(GG::X(Window::FRAME_WIDTH), GG::Y(Window::FRAME_WIDTH));\n\n\/****************************************************************************************************\/\n\n} \/\/ namespace\n\n\/****************************************************************************************************\/\n\nnamespace adobe {\n\n\/****************************************************************************************************\/\n\nwindow_t::window_t(const std::string& name,\n GG::Flags flags,\n theme_t theme) :\n window_m(0),\n flags_m(flags),\n name_m(name),\n theme_m(theme),\n debounce_m(false),\n placed_once_m(false)\n{ }\n\n\/****************************************************************************************************\/\n\nwindow_t::~window_t()\n{ delete window_m; }\n\n\/****************************************************************************************************\/\n\nvoid window_t::measure(extents_t& result)\n{\n assert(window_m);\n\n if (name_m.empty())\n {\n result.height() = 15;\n result.width() = 15;\n\n return;\n }\n\n \/\/ REVISIT (fbrereto) : A lot of static metrics values added here\n\n boost::shared_ptr style = GG::GUI::GetGUI()->GetStyleFactory();\n result = metrics::measure_text(name_m, style->DefaultFont());\n\n result.width() = static_cast(result.width() * 1.5);\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::place(const place_data_t& place_data)\n{\n assert(window_m);\n\n if (placed_once_m)\n {\n set_size(point_2d_t(width(place_data), height(place_data)));\n }\n else\n {\n placed_once_m = true;\n\n place_data_m = place_data;\n\n GG::Pt ul(GG::X(left(place_data)), GG::Y(top(place_data)));\n GG::Pt size(\n GG::Pt(GG::X(width(place_data)), GG::Y(height(place_data))) +\n implementation::NonClientSize(*window_m)\n );\n\n window_m->SetMinSize(size);\n\n window_m->SizeMove(ul, ul + size);\n }\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::set_size(const point_2d_t& size)\n{\n assert(window_m);\n\n if (debounce_m)\n return;\n\n debounce_m = true;\n\n width(place_data_m) = size.x_m;\n height(place_data_m) = size.y_m;\n\n window_m->Resize(\n GG::Pt(GG::X(width(place_data_m)), GG::Y(height(place_data_m))) +\n implementation::NonClientSize(*window_m)\n );\n\n debounce_m = false;\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::reposition()\n{\n assert(window_m);\n\n const GG::X width(window_m->Width());\n const GG::Y height(window_m->Height());\n\n GG::X app_width(GG::GUI::GetGUI()->AppWidth());\n GG::Y app_height(GG::GUI::GetGUI()->AppHeight());\n \n GG::X left(std::max(GG::X(10), (app_width - width) \/ 2));\n GG::Y top(std::max(GG::Y(10), (app_height - height) \/ 2));\n\n window_m->MoveTo(GG::Pt(left, top));\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::set_visible(bool make_visible)\n{\n assert(window_m);\n\n if (!window_m->Visible())\n reposition();\n\n set_control_visible(window_m, make_visible);\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::monitor_resize(const window_resize_proc_t& proc)\n{ resize_proc_m = proc; }\n\n\/****************************************************************************************************\/\n\nany_regular_t window_t::underlying_handler()\n{ return any_regular_t(window_m); }\n\n\/****************************************************************************************************\/\n\nbool window_t::handle_key(key_type key, bool pressed, modifiers_t modifiers)\n{ return false; }\n\n\/****************************************************************************************************\/\n\ntemplate <>\nplatform_display_type insert(display_t& display,\n platform_display_type& parent,\n window_t& element)\n{\n assert(!element.window_m);\n assert(!parent);\n\n element.window_m = new Window(element);\n\n return display.insert(parent, element.window_m);\n}\n\n\/****************************************************************************************************\/\n\n} \/\/ namespace adobe\n\n\/****************************************************************************************************\/\nFixed platform_window.cpp's Window::SizeMove().\/*\n Copyright 2005-2007 Adobe Systems Incorporated\n Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt\n or a copy at http:\/\/stlab.adobe.com\/licenses.html)\n*\/\n\n\/****************************************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\n\/****************************************************************************************************\/\n\nnamespace {\n\n\/****************************************************************************************************\/\n\n\/\/ TODO: Put this into StyleFactory.\nclass Window :\n public GG::Wnd\n{\npublic:\n static const unsigned int BEVEL = 2;\n\n Window(adobe::window_t& imp) :\n Wnd(GG::X0, GG::Y0, GG::X1, GG::Y1, imp.flags_m),\n m_imp(imp),\n m_title(0)\n {\n if (!m_imp.name_m.empty()) {\n m_title = adobe::implementation::Factory().NewTextControl(\n BEVEL_OFFSET.x, BEVEL_OFFSET.y - adobe::implementation::CharHeight(),\n m_imp.name_m, adobe::implementation::DefaultFont()\n );\n AttachChild(m_title);\n }\n }\n\n virtual GG::Pt ClientUpperLeft() const\n { return UpperLeft() + BEVEL_OFFSET + GG::Pt(GG::X0, m_title ? m_title->Height() : GG::Y0); }\n\n virtual GG::Pt ClientLowerRight() const\n { return LowerRight() - BEVEL_OFFSET; }\n\n virtual GG::WndRegion WindowRegion(const GG::Pt& pt) const\n {\n enum {LEFT = 0, MIDDLE = 1, RIGHT = 2};\n enum {TOP = 0, BOTTOM = 2};\n\n \/\/ window regions look like this:\n \/\/ 0111112\n \/\/ 3444445 \/\/ 4 is client area, 0,2,6,8 are corners\n \/\/ 3444445\n \/\/ 6777778\n\n int x_pos = MIDDLE; \/\/ default & typical case is that the mouse is over the (non-border) client area\n int y_pos = MIDDLE;\n\n GG::Pt ul = UpperLeft() + BEVEL_OFFSET, lr = LowerRight() - BEVEL_OFFSET;\n\n if (pt.x < ul.x)\n x_pos = LEFT;\n else if (pt.x > lr.x)\n x_pos = RIGHT;\n\n if (pt.y < ul.y)\n y_pos = TOP;\n else if (pt.y > lr.y)\n y_pos = BOTTOM;\n\n return (Resizable() ? GG::WndRegion(x_pos + 3 * y_pos) : GG::WR_NONE);\n }\n\n virtual void SizeMove(const GG::Pt& ul, const GG::Pt& lr)\n {\n GG::Wnd::SizeMove(ul, lr);\n\n GG::Pt client_size = ClientSize();\n\n if (!m_imp.debounce_m && !m_imp.resize_proc_m.empty()) {\n m_imp.debounce_m = true;\n\n if (adobe::width(m_imp.place_data_m) != Value(client_size.x) ||\n adobe::height(m_imp.place_data_m) != Value(client_size.y)) {\n m_imp.resize_proc_m(Value(client_size.x), Value(client_size.y));\n\n adobe::width(m_imp.place_data_m) = Value(client_size.x);\n adobe::height(m_imp.place_data_m) = Value(client_size.y);\n }\n\n m_imp.debounce_m = false;\n }\n\n GG::Pt new_title_size((LowerRight() - UpperLeft()).x - BEVEL_OFFSET.x * 2, m_title->Height());\n m_title->Resize(new_title_size);\n }\n\n virtual void Render()\n { GG::BeveledRectangle(UpperLeft(), LowerRight(), GG::CLR_GRAY, GG::CLR_GRAY, true, BEVEL); }\n\n virtual void KeyPress(GG::Key key, boost::uint32_t key_code_point,\n GG::Flags mod_keys)\n {\n adobe::keyboard_t::get().dispatch(adobe::key_type(key, key_code_point),\n true,\n adobe::modifier_state(),\n adobe::any_regular_t(this));\n }\n\n virtual void KeyRelease(GG::Key key, boost::uint32_t key_code_point,\n GG::Flags mod_keys)\n {\n adobe::keyboard_t::get().dispatch(adobe::key_type(key, key_code_point),\n false,\n adobe::modifier_state(),\n adobe::any_regular_t(this));\n }\n\nprivate:\n adobe::window_t& m_imp;\n GG::TextControl* m_title;\n\n static const int FRAME_WIDTH;\n static const GG::Pt BEVEL_OFFSET;\n};\n\nconst int Window::FRAME_WIDTH = 2;\nconst GG::Pt Window::BEVEL_OFFSET(GG::X(Window::FRAME_WIDTH), GG::Y(Window::FRAME_WIDTH));\n\n\/****************************************************************************************************\/\n\n} \/\/ namespace\n\n\/****************************************************************************************************\/\n\nnamespace adobe {\n\n\/****************************************************************************************************\/\n\nwindow_t::window_t(const std::string& name,\n GG::Flags flags,\n theme_t theme) :\n window_m(0),\n flags_m(flags),\n name_m(name),\n theme_m(theme),\n debounce_m(false),\n placed_once_m(false)\n{ }\n\n\/****************************************************************************************************\/\n\nwindow_t::~window_t()\n{ delete window_m; }\n\n\/****************************************************************************************************\/\n\nvoid window_t::measure(extents_t& result)\n{\n assert(window_m);\n\n if (name_m.empty())\n {\n result.height() = 15;\n result.width() = 15;\n\n return;\n }\n\n \/\/ REVISIT (fbrereto) : A lot of static metrics values added here\n\n boost::shared_ptr style = GG::GUI::GetGUI()->GetStyleFactory();\n result = metrics::measure_text(name_m, style->DefaultFont());\n\n result.width() = static_cast(result.width() * 1.5);\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::place(const place_data_t& place_data)\n{\n assert(window_m);\n\n if (placed_once_m)\n {\n set_size(point_2d_t(width(place_data), height(place_data)));\n }\n else\n {\n placed_once_m = true;\n\n place_data_m = place_data;\n\n GG::Pt ul(GG::X(left(place_data)), GG::Y(top(place_data)));\n GG::Pt size(\n GG::Pt(GG::X(width(place_data)), GG::Y(height(place_data))) +\n implementation::NonClientSize(*window_m)\n );\n\n window_m->SetMinSize(size);\n\n window_m->SizeMove(ul, ul + size);\n }\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::set_size(const point_2d_t& size)\n{\n assert(window_m);\n\n if (debounce_m)\n return;\n\n debounce_m = true;\n\n width(place_data_m) = size.x_m;\n height(place_data_m) = size.y_m;\n\n window_m->Resize(\n GG::Pt(GG::X(width(place_data_m)), GG::Y(height(place_data_m))) +\n implementation::NonClientSize(*window_m)\n );\n\n debounce_m = false;\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::reposition()\n{\n assert(window_m);\n\n const GG::X width(window_m->Width());\n const GG::Y height(window_m->Height());\n\n GG::X app_width(GG::GUI::GetGUI()->AppWidth());\n GG::Y app_height(GG::GUI::GetGUI()->AppHeight());\n \n GG::X left(std::max(GG::X(10), (app_width - width) \/ 2));\n GG::Y top(std::max(GG::Y(10), (app_height - height) \/ 2));\n\n window_m->MoveTo(GG::Pt(left, top));\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::set_visible(bool make_visible)\n{\n assert(window_m);\n\n if (!window_m->Visible())\n reposition();\n\n set_control_visible(window_m, make_visible);\n}\n\n\/****************************************************************************************************\/\n\nvoid window_t::monitor_resize(const window_resize_proc_t& proc)\n{ resize_proc_m = proc; }\n\n\/****************************************************************************************************\/\n\nany_regular_t window_t::underlying_handler()\n{ return any_regular_t(window_m); }\n\n\/****************************************************************************************************\/\n\nbool window_t::handle_key(key_type key, bool pressed, modifiers_t modifiers)\n{ return false; }\n\n\/****************************************************************************************************\/\n\ntemplate <>\nplatform_display_type insert(display_t& display,\n platform_display_type& parent,\n window_t& element)\n{\n assert(!element.window_m);\n assert(!parent);\n\n element.window_m = new Window(element);\n\n return display.insert(parent, element.window_m);\n}\n\n\/****************************************************************************************************\/\n\n} \/\/ namespace adobe\n\n\/****************************************************************************************************\/\n<|endoftext|>"} {"text":" \/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n License for the specific language governing rights and limitations under\r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace SCIRun::Core::Datatypes;\r\nusing namespace SCIRun::Core::Algorithms::Math;\r\nusing namespace SCIRun::Core::Algorithms;\r\nusing namespace SCIRun::TestUtils;\r\nusing namespace SCIRun;\r\nusing namespace ::testing;\r\n\r\nnamespace\r\n{\r\n const int size = 1000;\r\n SparseRowMatrixHandle matrix1() \r\n {\r\n SparseRowMatrixHandle m(new SparseRowMatrix(size,size));\r\n m->insert(0,0) = 1;\r\n m->insert(1,2) = -1;\r\n m->insert(size-1,size-1) = 2;\r\n return m;\r\n }\r\n\r\n SparseRowMatrix matrix2() \r\n {\r\n SparseRowMatrix m(size,size);\r\n m.insert(0,1) = -2;\r\n m.insert(1,1) = 0.5;\r\n m.insert(size-1,size-1) = 4;\r\n return m;\r\n }\r\n\r\n SparseRowMatrix matrix3() \r\n {\r\n SparseRowMatrix m(size,size);\r\n m.insert(0,0) = -1;\r\n m.insert(1,2) = 1;\r\n m.insert(size-1,size-1) = -2;\r\n return m;\r\n }\r\n\r\n DenseColumnMatrixHandle vector1()\r\n {\r\n DenseColumnMatrixHandle v(new DenseColumnMatrix(size));\r\n v->setZero();\r\n *v << 1, 2, 4;\r\n (*v)[size-1] = -1;\r\n return v;\r\n }\r\n\r\n DenseColumnMatrixHandle vector2()\r\n {\r\n DenseColumnMatrixHandle v(new DenseColumnMatrix(size));\r\n v->setZero();\r\n *v << -1, -2, -4;\r\n (*v)[size-1] = 1;\r\n return v;\r\n }\r\n\r\n DenseColumnMatrixHandle vector3()\r\n {\r\n DenseColumnMatrixHandle v(new DenseColumnMatrix(size));\r\n v->setZero();\r\n *v << 0, 1, 0;\r\n (*v)[size-1] = -7;\r\n return v;\r\n }\r\n\r\n unsigned int numProcs()\r\n {\r\n return boost::thread::hardware_concurrency();\r\n }\r\n\r\n SolverInputs getDummySystem()\r\n {\r\n SolverInputs system;\r\n system.A = matrix1();\r\n system.b = vector1();\r\n system.x = vector2();\r\n system.x0 = vector3();\r\n return system;\r\n }\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCreateEmptyParallelVector)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v;\r\n EXPECT_TRUE(pla.new_vector(v));\r\n\r\n EXPECT_EQ(size, v.size_);\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCreateParallelVectorFromVectorAsShallowReference)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v;\r\n auto v1 = vector1();\r\n EXPECT_TRUE(pla.add_vector(v1, v));\r\n\r\n EXPECT_EQ(v1->nrows(), v.size_);\r\n for (size_t i = 0; i < size; ++i)\r\n EXPECT_EQ((*v1)[i], v.data_[i]);\r\n\r\n EXPECT_EQ(0, (*v1)[100]);\r\n v.data_[100]++;\r\n EXPECT_EQ(1, (*v1)[100]);\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCopyParallelSparseMatrixAsShallowReference)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelMatrix m;\r\n auto m1 = matrix1();\r\n EXPECT_TRUE(pla.add_matrix(m1, m));\r\n\r\n EXPECT_EQ(m1->nrows(), m.m_);\r\n EXPECT_EQ(m1->ncols(), m.n_);\r\n EXPECT_EQ(m1->nonZeros(), m.nnz_);\r\n EXPECT_EQ(m1->coeff(1,2), m.data_[1]);\r\n\r\n EXPECT_EQ(1, m1->coeff(0,0));\r\n m.data_[0]++;\r\n EXPECT_EQ(2, m1->coeff(0,0));\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCopyContentsOfVector)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v1;\r\n pla.new_vector(v1);\r\n \r\n ParallelLinearAlgebra::ParallelVector v2;\r\n auto vec2 = vector2();\r\n pla.add_vector(vec2, v2);\r\n \r\n pla.copy(v2, v1);\r\n\r\n EXPECT_EQ(v1.size_, v2.size_);\r\n for (size_t i = 0; i < size; ++i)\r\n {\r\n EXPECT_EQ(v2.data_[i], v1.data_[i]);\r\n }\r\n v1.data_[7]++;\r\n EXPECT_NE(v1.data_[7], v2.data_[7]);\r\n}\r\n\r\nstruct Copy\r\n{\r\n Copy(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1, ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle vec2copy) : \r\n data_(data), v1_(v1), v2_(v2), proc_(proc), vec2copy_(vec2copy) {}\r\n\r\n ParallelLinearAlgebraSharedData& data_;\r\n int proc_;\r\n ParallelLinearAlgebra::ParallelVector& v1_;\r\n ParallelLinearAlgebra::ParallelVector& v2_;\r\n DenseColumnMatrixHandle vec2copy_;\r\n\r\n void operator()()\r\n {\r\n std::cout << proc_ << \" starting\" << std::endl;\r\n ParallelLinearAlgebra pla(data_, proc_);\r\n \r\n pla.new_vector(v1_);\r\n std::cout << \"pla\" << proc_ << \" new vector\" << std::endl;\r\n \r\n pla.add_vector(vec2copy_, v2_);\r\n std::cout << \"pla\" << proc_ << \" add vector\" << std::endl;\r\n\r\n pla.copy(v2_, v1_);\r\n std::cout << \"pla\" << proc_ << \" copy\" << std::endl;\r\n }\r\n};\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCopyContentsOfVectorMulti)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\r\n \r\n ParallelLinearAlgebra::ParallelVector v1, v2;\r\n\r\n auto vec2copy = vector2();\r\n Copy c0(data, v1, v2, 0, vec2copy);\r\n Copy c1(data, v1, v2, 1, vec2copy);\r\n \r\n boost::thread t1 = boost::thread(boost::ref(c0));\r\n boost::thread t2 = boost::thread(boost::ref(c1));\r\n t1.join();\r\n t2.join();\r\n\r\n EXPECT_EQ(v1.size_, v2.size_);\r\n for (size_t i = 0; i < size; ++i)\r\n {\r\n EXPECT_EQ(v2.data_[i], v1.data_[i]);\r\n }\r\n v1.data_[7]++;\r\n EXPECT_NE(v1.data_[7], v2.data_[7]);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonal)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonalMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\nTEST(ParallelArithmeticTests, CanComputeMaxOfVector)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v1;\r\n auto vec1 = vector1();\r\n pla.add_vector(vec1, v1);\r\n double max1 = pla.max(v1);\r\n ParallelLinearAlgebra::ParallelVector v2;\r\n auto vec2 = vector2();\r\n pla.add_vector(vec2, v2);\r\n double max2 = pla.max(v2);\r\n \r\n EXPECT_EQ(4, max1);\r\n EXPECT_EQ(1, max2);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanComputeMaxOfVectorMulti)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 4);\r\n ParallelLinearAlgebra pla(data, 1);\r\n\r\n \/\/pla.max()\r\n\r\n\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThreshold)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThresholdMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelLinearAlgebraTests, CanFillVectorWithOnes)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyMatrixByVector)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyMatrixByVectorMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanSubtractVectors)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanCompute2Norm)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWise)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanComputeDotProduct)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanSubtractVectorsMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanCompute2NormMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWiseMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanComputeDotProductMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\nMacro out TODO unit tests for @ajwaller. \/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n License for the specific language governing rights and limitations under\r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace SCIRun::Core::Datatypes;\r\nusing namespace SCIRun::Core::Algorithms::Math;\r\nusing namespace SCIRun::Core::Algorithms;\r\nusing namespace SCIRun::TestUtils;\r\nusing namespace SCIRun;\r\nusing namespace ::testing;\r\n\r\nnamespace\r\n{\r\n const int size = 1000;\r\n SparseRowMatrixHandle matrix1() \r\n {\r\n SparseRowMatrixHandle m(new SparseRowMatrix(size,size));\r\n m->insert(0,0) = 1;\r\n m->insert(1,2) = -1;\r\n m->insert(size-1,size-1) = 2;\r\n return m;\r\n }\r\n\r\n SparseRowMatrix matrix2() \r\n {\r\n SparseRowMatrix m(size,size);\r\n m.insert(0,1) = -2;\r\n m.insert(1,1) = 0.5;\r\n m.insert(size-1,size-1) = 4;\r\n return m;\r\n }\r\n\r\n SparseRowMatrix matrix3() \r\n {\r\n SparseRowMatrix m(size,size);\r\n m.insert(0,0) = -1;\r\n m.insert(1,2) = 1;\r\n m.insert(size-1,size-1) = -2;\r\n return m;\r\n }\r\n\r\n DenseColumnMatrixHandle vector1()\r\n {\r\n DenseColumnMatrixHandle v(new DenseColumnMatrix(size));\r\n v->setZero();\r\n *v << 1, 2, 4;\r\n (*v)[size-1] = -1;\r\n return v;\r\n }\r\n\r\n DenseColumnMatrixHandle vector2()\r\n {\r\n DenseColumnMatrixHandle v(new DenseColumnMatrix(size));\r\n v->setZero();\r\n *v << -1, -2, -4;\r\n (*v)[size-1] = 1;\r\n return v;\r\n }\r\n\r\n DenseColumnMatrixHandle vector3()\r\n {\r\n DenseColumnMatrixHandle v(new DenseColumnMatrix(size));\r\n v->setZero();\r\n *v << 0, 1, 0;\r\n (*v)[size-1] = -7;\r\n return v;\r\n }\r\n\r\n unsigned int numProcs()\r\n {\r\n return boost::thread::hardware_concurrency();\r\n }\r\n\r\n SolverInputs getDummySystem()\r\n {\r\n SolverInputs system;\r\n system.A = matrix1();\r\n system.b = vector1();\r\n system.x = vector2();\r\n system.x0 = vector3();\r\n return system;\r\n }\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCreateEmptyParallelVector)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v;\r\n EXPECT_TRUE(pla.new_vector(v));\r\n\r\n EXPECT_EQ(size, v.size_);\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCreateParallelVectorFromVectorAsShallowReference)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v;\r\n auto v1 = vector1();\r\n EXPECT_TRUE(pla.add_vector(v1, v));\r\n\r\n EXPECT_EQ(v1->nrows(), v.size_);\r\n for (size_t i = 0; i < size; ++i)\r\n EXPECT_EQ((*v1)[i], v.data_[i]);\r\n\r\n EXPECT_EQ(0, (*v1)[100]);\r\n v.data_[100]++;\r\n EXPECT_EQ(1, (*v1)[100]);\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCopyParallelSparseMatrixAsShallowReference)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelMatrix m;\r\n auto m1 = matrix1();\r\n EXPECT_TRUE(pla.add_matrix(m1, m));\r\n\r\n EXPECT_EQ(m1->nrows(), m.m_);\r\n EXPECT_EQ(m1->ncols(), m.n_);\r\n EXPECT_EQ(m1->nonZeros(), m.nnz_);\r\n EXPECT_EQ(m1->coeff(1,2), m.data_[1]);\r\n\r\n EXPECT_EQ(1, m1->coeff(0,0));\r\n m.data_[0]++;\r\n EXPECT_EQ(2, m1->coeff(0,0));\r\n}\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCopyContentsOfVector)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v1;\r\n pla.new_vector(v1);\r\n \r\n ParallelLinearAlgebra::ParallelVector v2;\r\n auto vec2 = vector2();\r\n pla.add_vector(vec2, v2);\r\n \r\n pla.copy(v2, v1);\r\n\r\n EXPECT_EQ(v1.size_, v2.size_);\r\n for (size_t i = 0; i < size; ++i)\r\n {\r\n EXPECT_EQ(v2.data_[i], v1.data_[i]);\r\n }\r\n v1.data_[7]++;\r\n EXPECT_NE(v1.data_[7], v2.data_[7]);\r\n}\r\n\r\nstruct Copy\r\n{\r\n Copy(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1, ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle vec2copy) : \r\n data_(data), v1_(v1), v2_(v2), proc_(proc), vec2copy_(vec2copy) {}\r\n\r\n ParallelLinearAlgebraSharedData& data_;\r\n int proc_;\r\n ParallelLinearAlgebra::ParallelVector& v1_;\r\n ParallelLinearAlgebra::ParallelVector& v2_;\r\n DenseColumnMatrixHandle vec2copy_;\r\n\r\n void operator()()\r\n {\r\n std::cout << proc_ << \" starting\" << std::endl;\r\n ParallelLinearAlgebra pla(data_, proc_);\r\n \r\n pla.new_vector(v1_);\r\n std::cout << \"pla\" << proc_ << \" new vector\" << std::endl;\r\n \r\n pla.add_vector(vec2copy_, v2_);\r\n std::cout << \"pla\" << proc_ << \" add vector\" << std::endl;\r\n\r\n pla.copy(v2_, v1_);\r\n std::cout << \"pla\" << proc_ << \" copy\" << std::endl;\r\n }\r\n};\r\n\r\nTEST(ParallelLinearAlgebraTests, CanCopyContentsOfVectorMulti)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\r\n \r\n ParallelLinearAlgebra::ParallelVector v1, v2;\r\n\r\n auto vec2copy = vector2();\r\n Copy c0(data, v1, v2, 0, vec2copy);\r\n Copy c1(data, v1, v2, 1, vec2copy);\r\n \r\n boost::thread t1 = boost::thread(boost::ref(c0));\r\n boost::thread t2 = boost::thread(boost::ref(c1));\r\n t1.join();\r\n t2.join();\r\n\r\n EXPECT_EQ(v1.size_, v2.size_);\r\n for (size_t i = 0; i < size; ++i)\r\n {\r\n EXPECT_EQ(v2.data_[i], v1.data_[i]);\r\n }\r\n v1.data_[7]++;\r\n EXPECT_NE(v1.data_[7], v2.data_[7]);\r\n}\r\n\r\n\r\n\r\nTEST(ParallelArithmeticTests, CanComputeMaxOfVector)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\r\n ParallelLinearAlgebra pla(data, 0);\r\n\r\n ParallelLinearAlgebra::ParallelVector v1;\r\n auto vec1 = vector1();\r\n pla.add_vector(vec1, v1);\r\n double max1 = pla.max(v1);\r\n ParallelLinearAlgebra::ParallelVector v2;\r\n auto vec2 = vector2();\r\n pla.add_vector(vec2, v2);\r\n double max2 = pla.max(v2);\r\n \r\n EXPECT_EQ(4, max1);\r\n EXPECT_EQ(1, max2);\r\n}\r\n\r\n\/\/TODO FIX_UNIT_TESTS\r\n#if 0\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonal)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonalMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanComputeMaxOfVectorMulti)\r\n{\r\n ParallelLinearAlgebraSharedData data(getDummySystem(), 4);\r\n ParallelLinearAlgebra pla(data, 1);\r\n\r\n \/\/pla.max()\r\n\r\n\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThreshold)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThresholdMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelLinearAlgebraTests, CanFillVectorWithOnes)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyMatrixByVector)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyMatrixByVectorMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanSubtractVectors)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanCompute2Norm)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWise)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanComputeDotProduct)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanSubtractVectorsMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanCompute2NormMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWiseMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n\r\n\/\/TODO: by intern\r\nTEST(ParallelArithmeticTests, CanComputeDotProductMulti)\r\n{\r\n EXPECT_TRUE(false);\r\n}\r\n#endif\r\n<|endoftext|>"} {"text":"#include \"dobby_internal.h\"\n#include \"core\/arch\/Cpu.h\"\n#include \"PlatformUnifiedInterface\/ExecMemory\/ClearCacheTool.h\"\n#include \"UnifiedInterface\/platform.h\"\n\n#include \n\n#ifdef __APPLE__\n#include \n#include \n#include \n#include \n#include \"UserMode\/UnifiedInterface\/platform-darwin\/mach_vm.h\"\n#endif\n\n#if defined(__APPLE__)\n#include \n#include \n#endif\n\n#include \"logging\/check_logging.h\"\n\n#include \"platform_macro.h\"\n#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)\n#include \n#include \"bootstrap.h\"\n#include \"ExecMemory\/substrated\/mach_interface_support\/substrated_client.h\"\n\n#define KERN_ERROR_RETURN(err, failure) \\\n do { \\\n if (err != KERN_SUCCESS) { \\\n return failure; \\\n } \\\n } while (0);\n\nstatic mach_port_t substrated_server_port = MACH_PORT_NULL;\n\nmach_port_t connect_mach_service(const char *name) {\n mach_port_t port = MACH_PORT_NULL;\n kern_return_t kr;\n\n kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port);\n KERN_ERROR_RETURN(kr, MACH_PORT_NULL)\n\n kr = bootstrap_look_up(bootstrap_port, (char *)name, &port);\n KERN_ERROR_RETURN(kr, MACH_PORT_NULL);\n\n substrated_server_port = port;\n\n return port;\n}\n\nint code_remap_with_substrated(uint8_t *buffer, uint32_t buffer_size, addr_t address) {\n if (!MACH_PORT_VALID(substrated_server_port)) {\n substrated_server_port = connect_mach_service(\"cy:com.saurik.substrated\");\n }\n if (!MACH_PORT_VALID(substrated_server_port))\n return -1;\n\n kern_return_t kr;\n kr = substrated_mark(substrated_server_port, mach_task_self(), (mach_vm_address_t)buffer, buffer_size,\n (mach_vm_address_t *)&address);\n if (kr != KERN_SUCCESS) {\n return RT_FAILED;\n }\n return RT_SUCCESS;\n}\n#endif\n\nPUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) {\n kern_return_t kr;\n\n int page_size = (int)sysconf(_SC_PAGESIZE);\n addr_t page_aligned_address = ALIGN_FLOOR(address, page_size);\n int offset = (int)((addr_t)address - page_aligned_address);\n\n static mach_port_t self_port = mach_task_self();\n#ifdef __APPLE__\n\n#if 0 \/\/ REMOVE\n vm_prot_t prot;\n vm_inherit_t inherit;\n mach_port_t task_self = mach_task_self();\n vm_address_t region = (vm_address_t)page_aligned_address;\n vm_size_t region_size = 0;\n struct vm_region_submap_short_info_64 info;\n mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;\n natural_t max_depth = -1;\n kr = vm_region_recurse_64(task_self, ®ion, ®ion_size, &max_depth, (vm_region_recurse_info_t)&info, &info_count);\n if (kr != KERN_SUCCESS) {\n return kMemoryOperationError;\n }\n prot = info.protection;\n inherit = info.inheritance;\n#endif\n\n \/\/ try modify with substrated (steal from frida-gum)\n addr_t remap_dummy_page =\n (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0);\n if ((void *)remap_dummy_page == MAP_FAILED)\n return kMemoryOperationError;\n\n \/\/ copy original page\n memcpy((void *)remap_dummy_page, (void *)page_aligned_address, page_size);\n\n \/\/ patch buffer\n memcpy((void *)(remap_dummy_page + offset), buffer, buffer_size);\n\n \/\/ change permission\n mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_WRITE);\n\n int ret = RT_FAILED;\n#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)\n ret = code_remap_with_substrated((uint8_t *)remap_dummy_page, (uint32_t)page_size, (addr_t)page_aligned_address);\n if (0 && ret == RT_FAILED)\n DLOG(0, \"substrated failed, use vm_remap\");\n#endif\n if (ret == RT_FAILED) {\n mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_EXEC);\n mach_vm_address_t remap_dest_page = (mach_vm_address_t)page_aligned_address;\n vm_prot_t curr_protection, max_protection;\n kr = mach_vm_remap(self_port, (mach_vm_address_t *)&remap_dest_page, page_size, 0,\n VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_dummy_page, TRUE,\n &curr_protection, &max_protection, VM_INHERIT_COPY);\n if (kr != KERN_SUCCESS) {\n return kMemoryOperationError;\n }\n }\n\n \/\/ unmap the origin page\n int err = munmap((void *)remap_dummy_page, (mach_vm_address_t)page_size);\n if (err == -1) {\n return kMemoryOperationError;\n }\n\n#endif\n\n addr_t clear_start = (addr_t)page_aligned_address + offset;\n DCHECK_EQ(clear_start, (addr_t)address);\n\n ClearCache((void *)address, (void *)((addr_t)address + buffer_size));\n return kMemoryOperationSuccess;\n}\nDisable code patch with substrated at iOS 14.5 temporarily#include \"dobby_internal.h\"\n#include \"core\/arch\/Cpu.h\"\n#include \"PlatformUnifiedInterface\/ExecMemory\/ClearCacheTool.h\"\n#include \"UnifiedInterface\/platform.h\"\n\n#include \n\n#ifdef __APPLE__\n#include \n#include \n#include \n#include \n#include \"UserMode\/UnifiedInterface\/platform-darwin\/mach_vm.h\"\n#endif\n\n#if defined(__APPLE__)\n#include \n#include \n#endif\n\n#include \"logging\/check_logging.h\"\n\n#include \"platform_macro.h\"\n\n#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)\n#include \n#include \"bootstrap.h\"\n#include \"ExecMemory\/substrated\/mach_interface_support\/substrated_client.h\"\n\n#define KERN_ERROR_RETURN(err, failure) \\\n do { \\\n if (err != KERN_SUCCESS) { \\\n return failure; \\\n } \\\n } while (0);\n\nstatic mach_port_t substrated_server_port = MACH_PORT_NULL;\n\nstatic mach_port_t connect_mach_service(const char *name) {\n mach_port_t port = MACH_PORT_NULL;\n kern_return_t kr;\n\n#if 0\n kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port);\n KERN_ERROR_RETURN(kr, MACH_PORT_NULL)\n#endif\n\n kr = bootstrap_look_up(bootstrap_port, (char *)name, &port);\n KERN_ERROR_RETURN(kr, MACH_PORT_NULL);\n\n substrated_server_port = port;\n\n return port;\n}\n\nint code_remap_with_substrated(uint8_t *buffer, uint32_t buffer_size, addr_t address) {\n if (!MACH_PORT_VALID(substrated_server_port)) {\n substrated_server_port = connect_mach_service(\"cy:com.saurik.substrated\");\n }\n if (!MACH_PORT_VALID(substrated_server_port))\n return -1;\n\n kern_return_t kr;\n kr = substrated_mark(substrated_server_port, mach_task_self(), (mach_vm_address_t)buffer, buffer_size,\n (mach_vm_address_t *)&address);\n if (kr != KERN_SUCCESS) {\n return RT_FAILED;\n }\n return RT_SUCCESS;\n}\n#endif\n\nPUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) {\n kern_return_t kr;\n\n int page_size = (int)sysconf(_SC_PAGESIZE);\n addr_t page_aligned_address = ALIGN_FLOOR(address, page_size);\n int offset = (int)((addr_t)address - page_aligned_address);\n\n static mach_port_t self_port = mach_task_self();\n#ifdef __APPLE__\n \/\/ try modify with substrated (steal from frida-gum)\n addr_t remap_dummy_page =\n (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0);\n if ((void *)remap_dummy_page == MAP_FAILED)\n return kMemoryOperationError;\n\n \/\/ copy original page\n memcpy((void *)remap_dummy_page, (void *)page_aligned_address, page_size);\n\n \/\/ patch buffer\n memcpy((void *)(remap_dummy_page + offset), buffer, buffer_size);\n\n \/\/ change permission\n mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_WRITE);\n\n int ret = RT_FAILED;\n#if 0 && defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)\n ret = code_remap_with_substrated((uint8_t *)remap_dummy_page, (uint32_t)page_size, (addr_t)page_aligned_address);\n if (0 && ret == RT_FAILED)\n DLOG(0, \"substrated failed, use vm_remap\");\n#endif\n if (ret == RT_FAILED) {\n mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_EXEC);\n mach_vm_address_t remap_dest_page = (mach_vm_address_t)page_aligned_address;\n vm_prot_t curr_protection, max_protection;\n kr = mach_vm_remap(self_port, (mach_vm_address_t *)&remap_dest_page, page_size, 0,\n VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_dummy_page, TRUE,\n &curr_protection, &max_protection, VM_INHERIT_COPY);\n if (kr != KERN_SUCCESS) {\n return kMemoryOperationError;\n }\n }\n\n \/\/ unmap the origin page\n int err = munmap((void *)remap_dummy_page, (mach_vm_address_t)page_size);\n if (err == -1) {\n return kMemoryOperationError;\n }\n\n#endif\n\n addr_t clear_start = (addr_t)page_aligned_address + offset;\n DCHECK_EQ(clear_start, (addr_t)address);\n\n ClearCache((void *)address, (void *)((addr_t)address + buffer_size));\n return kMemoryOperationSuccess;\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"..\/generic_config\/ops\/ConfigParser.h\"\n#include \"..\/generic_config\/model\/Config.h\"\n#include \"Template.h\"\n#include \"TemplateContainerParser.h\"\n\n\nnamespace Quartz {\n\nTemplateContainerParser::TemplateContainerParser()\n{\n\n}\n\nTemplateContainerParser::~TemplateContainerParser()\n{\n\n}\n\nQVector> TemplateContainerParser::parse(\n const QString &content)\n{\n QVector> tmpls;\n if (content.isNull()) {\n QZ_ERROR(\"Qz:Cmn:Tmpl\")\n << \"Invalid content given to general param parser\";\n return tmpls;\n }\n QDomDocument doc;\n QString errorMsg(\"\");\n int errorLine = 0;\n if (doc.setContent(content, false, &errorMsg, &errorLine)) {\n auto root = doc.documentElement();\n if (root.tagName() == \"templates\") {\n auto tmplLists = root.elementsByTagName(\"template\");\n for (auto i = 0; i < tmplLists.size(); ++ i) {\n auto tmplNode = tmplLists.at(i);\n auto tmpl = parse(tmplNode.toElement());\n if (tmpl != nullptr) {\n std::shared_ptr