<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextureResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace graphics
    {
        static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat)
        {
            switch (pixelFormat)
            {
                case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
                case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
                case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
                case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
                case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
                case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
                case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
                case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
                case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
                case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
                case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
                case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
                case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
                case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
                case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
                case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
                case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
                case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
                case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
                case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
                case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
                case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
                case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
                case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
                case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
                case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
                case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
                case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
                case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
                default: return DXGI_FORMAT_UNKNOWN;
            }
        }

        TextureResourceD3D11::TextureResourceD3D11()
        {
        }

        TextureResourceD3D11::~TextureResourceD3D11()
        {
            if (depthStencilTexture)
            {
                depthStencilTexture->Release();
            }

            if (depthStencilView)
            {
                depthStencilView->Release();
            }

            if (renderTargetView)
            {
                renderTargetView->Release();
            }

            if (resourceView)
            {
                resourceView->Release();
            }

            if (texture)
            {
                texture->Release();
            }

            if (samplerState)
            {
                samplerState->Release();
            }

            width = 0;
            height = 0;
        }

        bool TextureResourceD3D11::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());

                if (dirty & DIRTY_DATA)
                {
                    if (size.v[0] > 0 &&
                        size.v[1] > 0)
                    {
                        if (!texture ||
                            static_cast<UINT>(size.v[0]) != width ||
                            static_cast<UINT>(size.v[1]) != height)
                        {
                            if (texture)
                            {
                                texture->Release();
                            }

                            if (resourceView)
                            {
                                resourceView->Release();
                                resourceView = nullptr;
                            }

                            width = static_cast<UINT>(size.v[0]);
                            height = static_cast<UINT>(size.v[1]);

                            DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat);

                            if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN)
                            {
                                Log(Log::Level::ERR) << "Invalid pixel format";
                                return false;
                            }

                            D3D11_TEXTURE2D_DESC textureDesc;
                            textureDesc.Width = width;
                            textureDesc.Height = height;
                            textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
                            textureDesc.ArraySize = 1;
                            textureDesc.Format = d3d11PixelFormat;
                            textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
                            textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
                            textureDesc.SampleDesc.Count = sampleCount;
                            textureDesc.SampleDesc.Quality = 0;
                            textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
                            textureDesc.MiscFlags = 0;

                            HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture, error: " << hr;
                                return false;
                            }

                            D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
                            resourceViewDesc.Format = d3d11PixelFormat;
                            resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;

                            if (sampleCount == 1)
                            {
                                resourceViewDesc.Texture2D.MostDetailedMip = 0;
                                resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
                            }

                            hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view, error: " << hr;
                                return false;
                            }

                            if (renderTarget)
                            {
                                if (renderTargetView)
                                {
                                    renderTargetView->Release();
                                }

                                D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
                                renderTargetViewDesc.Format = d3d11PixelFormat;
                                renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;

                                if (sampleCount == 1)
                                {
                                    renderTargetViewDesc.Texture2D.MipSlice = 0;
                                }

                                hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view, error: " << hr;
                                    return false;
                                }
                            }

                            if (depth)
                            {
                                if (depthStencilTexture)
                                {
                                    depthStencilTexture->Release();
                                }

                                if (depthStencilView)
                                {
                                    depthStencilView->Release();
                                    depthStencilView = nullptr;
                                }

                                D3D11_TEXTURE2D_DESC depthStencilDesc;
                                depthStencilDesc.Width = width;
                                depthStencilDesc.Height = height;
                                depthStencilDesc.MipLevels = 1;
                                depthStencilDesc.ArraySize = 1;
                                depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
                                depthStencilDesc.SampleDesc.Count = sampleCount;
                                depthStencilDesc.SampleDesc.Quality = 0;
                                depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
                                depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
                                depthStencilDesc.CPUAccessFlags = 0;
                                depthStencilDesc.MiscFlags = 0;
                                hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture, error: " << hr;
                                    return false;
                                }

                                hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view, error: " << hr;
                                    return false;
                                }
                            }
                        }

                        if (!renderTarget)
                        {
                            if (dynamic)
                            {
                                for (size_t level = 0; level < levels.size(); ++level)
                                {
                                    if (!levels[level].data.empty())
                                    {
                                        D3D11_MAPPED_SUBRESOURCE mappedSubresource;
                                        mappedSubresource.pData = 0;
                                        mappedSubresource.RowPitch = 0;
                                        mappedSubresource.DepthPitch = 0;

                                        HRESULT hr = rendererD3D11->getContext()->Map(texture, static_cast<UINT>(level),
                                                                                (level == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE,
                                                                                0, &mappedSubresource);

                                        if (FAILED(hr))
                                        {
                                            Log(Log::Level::ERR) << "Failed to map Direct3D 11 texture, error: " << hr;
                                            return false;
                                        }

                                        uint8_t* target = reinterpret_cast<uint8_t*>(mappedSubresource.pData);

                                        if (mappedSubresource.RowPitch == levels[level].pitch)
                                        {
                                            std::copy(levels[level].data.begin(),
                                                      levels[level].data.end(),
                                                      target);
                                        }
                                        else
                                        {
                                            auto start = levels[level].data.begin();
                                            UINT currentWidth = static_cast<UINT>(levels[level].size.v[0]);
                                            UINT currentHeight = static_cast<UINT>(levels[level].size.v[1]);

                                            for (UINT row = 0; row < currentHeight; ++row)
                                            {
                                                std::copy(start,
                                                          start + currentWidth,
                                                          target);

                                                start += levels[level].pitch;
                                                target += mappedSubresource.RowPitch;
                                            }

                                            rendererD3D11->getContext()->Unmap(texture, static_cast<UINT>(level));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (size_t level = 0; level < levels.size(); ++level)
                                {
                                    if (!levels[level].data.empty())
                                    {
                                        rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
                                                                                nullptr, levels[level].data.data(),
                                                                                static_cast<UINT>(levels[level].pitch), 0);
                                    }
                                }
                            }
                        }
                    }
                }

                if (dirty & DIRTY_PARAMETERS)
                {
                    clearFrameBufferView = clearColorBuffer;
                    clearDepthBufferView = clearDepthBuffer;

                    frameBufferClearColor[0] = clearColor.normR();
                    frameBufferClearColor[1] = clearColor.normG();
                    frameBufferClearColor[2] = clearColor.normB();
                    frameBufferClearColor[3] = clearColor.normA();

                    if (samplerState) samplerState->Release();

                    RendererD3D11::SamplerStateDesc samplerDesc;
                    samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
                    samplerDesc.addressX = addressX;
                    samplerDesc.addressY = addressY;
                    samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;

                    samplerState = rendererD3D11->getSamplerState(samplerDesc);

                    if (!samplerState)
                    {
                        Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
                        return false;
                    }

                    samplerState->AddRef();
                }

                dirty = 0;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<commit_msg>Fix D3D11 texture unmap<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextureResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace graphics
    {
        static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat)
        {
            switch (pixelFormat)
            {
                case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
                case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
                case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
                case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
                case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
                case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
                case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
                case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
                case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
                case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
                case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
                case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
                case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
                case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
                case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
                case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
                case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
                case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
                case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
                case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
                case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
                case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
                case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
                case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
                case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
                case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
                case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
                case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
                case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
                default: return DXGI_FORMAT_UNKNOWN;
            }
        }

        TextureResourceD3D11::TextureResourceD3D11()
        {
        }

        TextureResourceD3D11::~TextureResourceD3D11()
        {
            if (depthStencilTexture)
            {
                depthStencilTexture->Release();
            }

            if (depthStencilView)
            {
                depthStencilView->Release();
            }

            if (renderTargetView)
            {
                renderTargetView->Release();
            }

            if (resourceView)
            {
                resourceView->Release();
            }

            if (texture)
            {
                texture->Release();
            }

            if (samplerState)
            {
                samplerState->Release();
            }

            width = 0;
            height = 0;
        }

        bool TextureResourceD3D11::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());

                if (dirty & DIRTY_DATA)
                {
                    if (size.v[0] > 0 &&
                        size.v[1] > 0)
                    {
                        if (!texture ||
                            static_cast<UINT>(size.v[0]) != width ||
                            static_cast<UINT>(size.v[1]) != height)
                        {
                            if (texture)
                            {
                                texture->Release();
                            }

                            if (resourceView)
                            {
                                resourceView->Release();
                                resourceView = nullptr;
                            }

                            width = static_cast<UINT>(size.v[0]);
                            height = static_cast<UINT>(size.v[1]);

                            DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat);

                            if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN)
                            {
                                Log(Log::Level::ERR) << "Invalid pixel format";
                                return false;
                            }

                            D3D11_TEXTURE2D_DESC textureDesc;
                            textureDesc.Width = width;
                            textureDesc.Height = height;
                            textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
                            textureDesc.ArraySize = 1;
                            textureDesc.Format = d3d11PixelFormat;
                            textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
                            textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
                            textureDesc.SampleDesc.Count = sampleCount;
                            textureDesc.SampleDesc.Quality = 0;
                            textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
                            textureDesc.MiscFlags = 0;

                            HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture, error: " << hr;
                                return false;
                            }

                            D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
                            resourceViewDesc.Format = d3d11PixelFormat;
                            resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;

                            if (sampleCount == 1)
                            {
                                resourceViewDesc.Texture2D.MostDetailedMip = 0;
                                resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
                            }

                            hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view, error: " << hr;
                                return false;
                            }

                            if (renderTarget)
                            {
                                if (renderTargetView)
                                {
                                    renderTargetView->Release();
                                }

                                D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
                                renderTargetViewDesc.Format = d3d11PixelFormat;
                                renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;

                                if (sampleCount == 1)
                                {
                                    renderTargetViewDesc.Texture2D.MipSlice = 0;
                                }

                                hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view, error: " << hr;
                                    return false;
                                }
                            }

                            if (depth)
                            {
                                if (depthStencilTexture)
                                {
                                    depthStencilTexture->Release();
                                }

                                if (depthStencilView)
                                {
                                    depthStencilView->Release();
                                    depthStencilView = nullptr;
                                }

                                D3D11_TEXTURE2D_DESC depthStencilDesc;
                                depthStencilDesc.Width = width;
                                depthStencilDesc.Height = height;
                                depthStencilDesc.MipLevels = 1;
                                depthStencilDesc.ArraySize = 1;
                                depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
                                depthStencilDesc.SampleDesc.Count = sampleCount;
                                depthStencilDesc.SampleDesc.Quality = 0;
                                depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
                                depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
                                depthStencilDesc.CPUAccessFlags = 0;
                                depthStencilDesc.MiscFlags = 0;
                                hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture, error: " << hr;
                                    return false;
                                }

                                hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view, error: " << hr;
                                    return false;
                                }
                            }
                        }

                        if (!renderTarget)
                        {
                            if (dynamic)
                            {
                                for (size_t level = 0; level < levels.size(); ++level)
                                {
                                    if (!levels[level].data.empty())
                                    {
                                        D3D11_MAPPED_SUBRESOURCE mappedSubresource;
                                        mappedSubresource.pData = 0;
                                        mappedSubresource.RowPitch = 0;
                                        mappedSubresource.DepthPitch = 0;

                                        HRESULT hr = rendererD3D11->getContext()->Map(texture, static_cast<UINT>(level),
                                                                                (level == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE,
                                                                                0, &mappedSubresource);

                                        if (FAILED(hr))
                                        {
                                            Log(Log::Level::ERR) << "Failed to map Direct3D 11 texture, error: " << hr;
                                            return false;
                                        }

                                        uint8_t* target = reinterpret_cast<uint8_t*>(mappedSubresource.pData);

                                        if (mappedSubresource.RowPitch == levels[level].pitch)
                                        {
                                            std::copy(levels[level].data.begin(),
                                                      levels[level].data.end(),
                                                      target);
                                        }
                                        else
                                        {
                                            auto start = levels[level].data.begin();
                                            UINT currentWidth = static_cast<UINT>(levels[level].size.v[0]);
                                            UINT currentHeight = static_cast<UINT>(levels[level].size.v[1]);

                                            for (UINT row = 0; row < currentHeight; ++row)
                                            {
                                                std::copy(start,
                                                          start + currentWidth,
                                                          target);

                                                start += levels[level].pitch;
                                                target += mappedSubresource.RowPitch;
                                            }
                                        }

                                        rendererD3D11->getContext()->Unmap(texture, static_cast<UINT>(level));
                                    }
                                }
                            }
                            else
                            {
                                for (size_t level = 0; level < levels.size(); ++level)
                                {
                                    if (!levels[level].data.empty())
                                    {
                                        rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
                                                                                nullptr, levels[level].data.data(),
                                                                                static_cast<UINT>(levels[level].pitch), 0);
                                    }
                                }
                            }
                        }
                    }
                }

                if (dirty & DIRTY_PARAMETERS)
                {
                    clearFrameBufferView = clearColorBuffer;
                    clearDepthBufferView = clearDepthBuffer;

                    frameBufferClearColor[0] = clearColor.normR();
                    frameBufferClearColor[1] = clearColor.normG();
                    frameBufferClearColor[2] = clearColor.normB();
                    frameBufferClearColor[3] = clearColor.normA();

                    if (samplerState) samplerState->Release();

                    RendererD3D11::SamplerStateDesc samplerDesc;
                    samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
                    samplerDesc.addressX = addressX;
                    samplerDesc.addressY = addressY;
                    samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;

                    samplerState = rendererD3D11->getSamplerState(samplerDesc);

                    if (!samplerState)
                    {
                        Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
                        return false;
                    }

                    samplerState->AddRef();
                }

                dirty = 0;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2021-present ScyllaDB
 */

/*
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include <seastar/core/coroutine.hh>

#include "consumer.hh"
#include "mutation_source_metadata.hh"
#include "service/priority_manager.hh"
#include "db/view/view_update_generator.hh"
#include "db/view/view_update_checks.hh"
#include "sstables/sstables.hh"
#include "sstables/sstables_manager.hh"

namespace streaming {

std::function<future<> (flat_mutation_reader_v2)> make_streaming_consumer(sstring origin,
        sharded<replica::database>& db,
        sharded<db::system_distributed_keyspace>& sys_dist_ks,
        sharded<db::view::view_update_generator>& vug,
        uint64_t estimated_partitions,
        stream_reason reason,
        sstables::offstrategy offstrategy) {
    return [&db, &sys_dist_ks, &vug, estimated_partitions, reason, offstrategy, origin = std::move(origin)] (flat_mutation_reader_v2 reader) -> future<> {
        std::exception_ptr ex;
        try {
            auto cf = db.local().find_column_family(reader.schema()).shared_from_this();
            auto use_view_update_path = co_await db::view::check_needs_view_update_path(sys_dist_ks.local(), *cf, reason);
            //FIXME: for better estimations this should be transmitted from remote
            auto metadata = mutation_source_metadata{};
            auto& cs = cf->get_compaction_strategy();
            const auto adjusted_estimated_partitions = cs.adjust_partition_estimate(metadata, estimated_partitions);
            auto make_interposer_consumer = [&cs, offstrategy] (const mutation_source_metadata& ms_meta, reader_consumer_v2 end_consumer) mutable {
                // postpone data segregation to off-strategy compaction if enabled
                if (offstrategy) {
                    return end_consumer;
                }
                return cs.make_interposer_consumer(ms_meta, std::move(end_consumer));
            };

            auto consumer = make_interposer_consumer(metadata,
                    [cf = std::move(cf), adjusted_estimated_partitions, use_view_update_path, &vug, origin = std::move(origin), offstrategy, reason] (flat_mutation_reader_v2 reader) {
                sstables::shared_sstable sst;
                try {
                    sst = use_view_update_path ? cf->make_streaming_staging_sstable() : cf->make_streaming_sstable_for_write();
                } catch (...) {
                    return current_exception_as_future().finally([reader = std::move(reader)] () mutable {
                        return reader.close();
                    });
                }
                schema_ptr s = reader.schema();
                auto& pc = service::get_local_streaming_priority();

                return sst->write_components(downgrade_to_v1(std::move(reader)), adjusted_estimated_partitions, s,
                                             cf->get_sstables_manager().configure_writer(origin),
                                             encoding_stats{}, pc).then([sst] {
                    return sst->open_data();
                }).then([cf, sst, offstrategy, reason] {
                    if (offstrategy && (reason == stream_reason::repair)) {
                        sstables::sstlog.debug("Enabled automatic off-strategy trigger for table {}.{}",
                                cf->schema()->ks_name(), cf->schema()->cf_name());
                        cf->enable_off_strategy_trigger();
                    }
                    return cf->add_sstable_and_update_cache(sst, offstrategy);
                }).then([cf, s, sst, use_view_update_path, &vug]() mutable -> future<> {
                    if (!use_view_update_path) {
                        return make_ready_future<>();
                    }
                    return vug.local().register_staging_sstable(sst, std::move(cf));
                });
            });
            co_return co_await consumer(std::move(reader));
        } catch (...) {
            ex = std::current_exception();
        }
        if (ex) {
            co_await reader.close();
            std::rethrow_exception(std::move(ex));
        }
    };
}

}
<commit_msg>streaming: migrate to v2 variant of sstable writer API<commit_after>/*
 * Copyright (C) 2021-present ScyllaDB
 */

/*
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include <seastar/core/coroutine.hh>

#include "consumer.hh"
#include "mutation_source_metadata.hh"
#include "service/priority_manager.hh"
#include "db/view/view_update_generator.hh"
#include "db/view/view_update_checks.hh"
#include "sstables/sstables.hh"
#include "sstables/sstables_manager.hh"

namespace streaming {

std::function<future<> (flat_mutation_reader_v2)> make_streaming_consumer(sstring origin,
        sharded<replica::database>& db,
        sharded<db::system_distributed_keyspace>& sys_dist_ks,
        sharded<db::view::view_update_generator>& vug,
        uint64_t estimated_partitions,
        stream_reason reason,
        sstables::offstrategy offstrategy) {
    return [&db, &sys_dist_ks, &vug, estimated_partitions, reason, offstrategy, origin = std::move(origin)] (flat_mutation_reader_v2 reader) -> future<> {
        std::exception_ptr ex;
        try {
            auto cf = db.local().find_column_family(reader.schema()).shared_from_this();
            auto use_view_update_path = co_await db::view::check_needs_view_update_path(sys_dist_ks.local(), *cf, reason);
            //FIXME: for better estimations this should be transmitted from remote
            auto metadata = mutation_source_metadata{};
            auto& cs = cf->get_compaction_strategy();
            const auto adjusted_estimated_partitions = cs.adjust_partition_estimate(metadata, estimated_partitions);
            auto make_interposer_consumer = [&cs, offstrategy] (const mutation_source_metadata& ms_meta, reader_consumer_v2 end_consumer) mutable {
                // postpone data segregation to off-strategy compaction if enabled
                if (offstrategy) {
                    return end_consumer;
                }
                return cs.make_interposer_consumer(ms_meta, std::move(end_consumer));
            };

            auto consumer = make_interposer_consumer(metadata,
                    [cf = std::move(cf), adjusted_estimated_partitions, use_view_update_path, &vug, origin = std::move(origin), offstrategy, reason] (flat_mutation_reader_v2 reader) {
                sstables::shared_sstable sst;
                try {
                    sst = use_view_update_path ? cf->make_streaming_staging_sstable() : cf->make_streaming_sstable_for_write();
                } catch (...) {
                    return current_exception_as_future().finally([reader = std::move(reader)] () mutable {
                        return reader.close();
                    });
                }
                schema_ptr s = reader.schema();
                auto& pc = service::get_local_streaming_priority();

                return sst->write_components(std::move(reader), adjusted_estimated_partitions, s,
                                             cf->get_sstables_manager().configure_writer(origin),
                                             encoding_stats{}, pc).then([sst] {
                    return sst->open_data();
                }).then([cf, sst, offstrategy, reason] {
                    if (offstrategy && (reason == stream_reason::repair)) {
                        sstables::sstlog.debug("Enabled automatic off-strategy trigger for table {}.{}",
                                cf->schema()->ks_name(), cf->schema()->cf_name());
                        cf->enable_off_strategy_trigger();
                    }
                    return cf->add_sstable_and_update_cache(sst, offstrategy);
                }).then([cf, s, sst, use_view_update_path, &vug]() mutable -> future<> {
                    if (!use_view_update_path) {
                        return make_ready_future<>();
                    }
                    return vug.local().register_staging_sstable(sst, std::move(cf));
                });
            });
            co_return co_await consumer(std::move(reader));
        } catch (...) {
            ex = std::current_exception();
        }
        if (ex) {
            co_await reader.close();
            std::rethrow_exception(std::move(ex));
        }
    };
}

}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DisplayMenu.h"

/* system implementation headers */
#include <string>
#include <vector>
#include <math.h>

/* common implementation headers */
#include "BzfDisplay.h"
#include "SceneRenderer.h"
#include "BZDBCache.h"
#include "FontManager.h"
#include "OpenGLTexture.h"

/* local implementation headers */
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "HUDuiControl.h"
#include "HUDuiList.h"
#include "HUDuiLabel.h"
#include "MainWindow.h"

/* FIXME - from playing.h */
BzfDisplay* getDisplay();
MainWindow* getMainWindow();
SceneRenderer* getSceneRenderer();
void setSceneDatabase();

DisplayMenu::DisplayMenu() : formatMenu(NULL)
{
  // add controls
  std::vector<std::string>* options;
  std::vector<HUDuiControl*>& list  = getControls();
  HUDuiList* option;

  // cache font face id
  int fontFace = MainMenu::getFontFace();

  HUDuiLabel* label = new HUDuiLabel;
  label->setFontFace(fontFace);
  label->setString("Display Settings");
  list.push_back(label);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Dithering:");
  option->setCallback(callback, (void*)"1");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Blending:");
  option->setCallback(callback, (void*)"2");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Smoothing:");
  option->setCallback(callback, (void*)"3");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Lighting:");
  option->setCallback(callback, (void*)"4");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Texturing:");
  option->setCallback(callback, (void*)"5");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("Nearest"));
  options->push_back(std::string("Linear"));
  options->push_back(std::string("Nearest Mipmap Nearest"));
  options->push_back(std::string("Linear Mipmap Nearest"));
  options->push_back(std::string("Nearest Mipmap Linear"));
  options->push_back(std::string("Linear Mipmap Linear"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Quality:");
  option->setCallback(callback, (void*)"6");
  options = &option->getList();
  options->push_back(std::string("Low"));
  options->push_back(std::string("Medium"));
  options->push_back(std::string("High"));
  options->push_back(std::string("Experimental"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Shadows:");
  option->setCallback(callback, (void*)"7");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Depth Buffer:");
  option->setCallback(callback, (void*)"8");
  options = &option->getList();
  GLint value;
  glGetIntegerv(GL_DEPTH_BITS, &value);
  if (value == 0) {
    options->push_back(std::string("Not available"));
  } else {
    options->push_back(std::string("Off"));
    options->push_back(std::string("On"));
  }
  option->update();
  list.push_back(option);

#if defined(DEBUG_RENDERING)
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Hidden Line:");
  option->setCallback(callback, (void*)"a");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Wireframe:");
  option->setCallback(callback, (void*)"b");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Depth Complexity:");
  option->setCallback(callback, (void*)"c");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Culling Tree:");
  option->setCallback(callback, (void*)"d");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);
#endif

  BzfWindow* window = getMainWindow()->getWindow();
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Brightness:");
  option->setCallback(callback, (void*)"g");
  if (window->hasGammaControl()) {
    option->createSlider(15);
  } else {
    options = &option->getList();
    options->push_back(std::string("Unavailable"));
  }
  option->update();
  list.push_back(option);

  BzfDisplay* display = getDisplay();
  int numFormats = display->getNumResolutions();
  if (numFormats < 2) {
    videoFormat = NULL;
  } else {
    videoFormat = label = new HUDuiLabel;
    label->setFontFace(fontFace);
    label->setLabel("Change Video Format");
    list.push_back(label);
  }

  initNavigation(list, 1,list.size()-1);
}

DisplayMenu::~DisplayMenu()
{
  delete formatMenu;
}

void			DisplayMenu::execute()
{
  HUDuiControl* focus = HUDui::getFocus();
  if (focus == videoFormat) {
    if (!formatMenu)
      formatMenu = new FormatMenu;
    HUDDialogStack::get()->push(formatMenu);
  }
}

void			DisplayMenu::resize(int width, int height)
{
  HUDDialog::resize(width, height);
  int i;

  // use a big font for title, smaller font for the rest
  const float titleFontSize = (float)height / 15.0f;
  const float fontSize = (float)height / 45.0f;
  FontManager &fm = FontManager::instance();
  int fontFace = MainMenu::getFontFace();

  // reposition title
  std::vector<HUDuiControl*>& list = getControls();
  HUDuiLabel* title = (HUDuiLabel*)list[0];
  title->setFontSize(titleFontSize);
  const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString());
  const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " ");
  float x = 0.5f * ((float)width - titleWidth);
  float y = (float)height - titleHeight;
  title->setPosition(x, y);

  // reposition options
  x = 0.5f * ((float)width);
  y -= 0.6f * titleHeight;
  const float h = fm.getStrHeight(fontFace, fontSize, " ");
  const int count = list.size();
  for (i = 1; i < count; i++) {
    list[i]->setFontSize(fontSize);
    list[i]->setPosition(x, y);
    y -= 1.0f * h;
  }

  i = 1;
  // load current settings
  SceneRenderer* renderer = getSceneRenderer();
  if (renderer) {
    HUDuiList* tex;
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("dither"));
    ((HUDuiList*)list[i++])->setIndex(BZDBCache::blend);
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("smooth"));
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("lighting"));
    tex = (HUDuiList*)list[i++];
    ((HUDuiList*)list[i++])->setIndex(renderer->useQuality());
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("shadows"));
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("zbuffer"));
#if defined(DEBUG_RENDERING)
    ((HUDuiList*)list[i++])->setIndex(renderer->useHiddenLine() ? 1 : 0);
    ((HUDuiList*)list[i++])->setIndex(renderer->useWireframe() ? 1 : 0);
    ((HUDuiList*)list[i++])->setIndex(renderer->useDepthComplexity() ? 1 : 0);
    ((HUDuiList*)list[i++])->setIndex(renderer->useCullingTree() ? 1 : 0);
#endif

    if (!BZDBCache::texture)
      tex->setIndex(0);
    else
      tex->setIndex(OpenGLTexture::getFilter());
  }

  // brightness
  BzfWindow* window = getMainWindow()->getWindow();
  if (window->hasGammaControl())
    ((HUDuiList*)list[i])->setIndex(gammaToIndex(window->getGamma()));
  i++;

}

int DisplayMenu::gammaToIndex(float gamma)
{
  return (int)(0.5f + 5.0f * (1.0f + logf(gamma) / logf(2.0)));
}

float DisplayMenu::indexToGamma(int index)
{
  // map index 5 to gamma 1.0 and index 0 to gamma 0.5
  return powf(2.0f, (float)index / 5.0f - 1.0f);
}

void			DisplayMenu::callback(HUDuiControl* w, void* data) {
  HUDuiList* list = (HUDuiList*)w;
  SceneRenderer* sceneRenderer = getSceneRenderer();
  switch (((const char*)data)[0]) {
  case '1':
    BZDB.set("dither", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '2':
    BZDB.set("blend", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '3':
    BZDB.set("smooth", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '4':
    BZDB.set("lighting", list->getIndex() ? "1" : "0");
    BZDB.set("_texturereplace", (!BZDB.isTrue("lighting") &&
				 sceneRenderer->useQuality() < 2) ? "1" : "0");
    BZDB.setPersistent("_texturereplace", false);
    sceneRenderer->notifyStyleChange();
    break;
  case '5':
#ifdef _MSC_VER
    // Suppose Pat want to remind himself
    { int somebody_get_tm_to_set_texture; }
#endif
    /*
      OpenGLTexture::setFilter((OpenGLTexture::Filter)list->getIndex());
      BZDB.set("texture", OpenGLTexture::getFilterName());
      sceneRenderer->notifyStyleChange();
    */
    break;
  case '6':
    sceneRenderer->setQuality(list->getIndex());
    BZDB.set("_texturereplace", (!BZDB.isTrue("lighting") &&
				 sceneRenderer->useQuality() < 2) ? "1" : "0");
    BZDB.setPersistent("_texturereplace", false);
    sceneRenderer->notifyStyleChange();
    break;
  case '7':
    BZDB.set("shadows", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '8':
    BZDB.set("zbuffer", list->getIndex() ? "1" : "0");
    // FIXME - test for whether the z buffer will work
    setSceneDatabase();
    sceneRenderer->notifyStyleChange();
    break;
#if defined(DEBUG_RENDERING)
  case 'a':
    sceneRenderer->setHiddenLine(list->getIndex() != 0);
    break;
  case 'b':
    sceneRenderer->setWireframe(list->getIndex() != 0);
    break;
  case 'c':
    sceneRenderer->setDepthComplexity(list->getIndex() != 0);
    break;
  case 'd':
    sceneRenderer->setCullingTree(list->getIndex() != 0);
    break;
#endif
  case 'g':
    BzfWindow* window = getMainWindow()->getWindow();
    if (window->hasGammaControl())
      window->setGamma(indexToGamma(list->getIndex()));
    break;
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>enable cull-tree display in non-debug builds<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DisplayMenu.h"

/* system implementation headers */
#include <string>
#include <vector>
#include <math.h>

/* common implementation headers */
#include "BzfDisplay.h"
#include "SceneRenderer.h"
#include "BZDBCache.h"
#include "FontManager.h"
#include "OpenGLTexture.h"

/* local implementation headers */
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "HUDuiControl.h"
#include "HUDuiList.h"
#include "HUDuiLabel.h"
#include "MainWindow.h"

/* FIXME - from playing.h */
BzfDisplay* getDisplay();
MainWindow* getMainWindow();
SceneRenderer* getSceneRenderer();
void setSceneDatabase();

DisplayMenu::DisplayMenu() : formatMenu(NULL)
{
  // add controls
  std::vector<std::string>* options;
  std::vector<HUDuiControl*>& list  = getControls();
  HUDuiList* option;

  // cache font face id
  int fontFace = MainMenu::getFontFace();

  HUDuiLabel* label = new HUDuiLabel;
  label->setFontFace(fontFace);
  label->setString("Display Settings");
  list.push_back(label);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Dithering:");
  option->setCallback(callback, (void*)"1");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Blending:");
  option->setCallback(callback, (void*)"2");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Smoothing:");
  option->setCallback(callback, (void*)"3");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Lighting:");
  option->setCallback(callback, (void*)"4");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Texturing:");
  option->setCallback(callback, (void*)"5");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("Nearest"));
  options->push_back(std::string("Linear"));
  options->push_back(std::string("Nearest Mipmap Nearest"));
  options->push_back(std::string("Linear Mipmap Nearest"));
  options->push_back(std::string("Nearest Mipmap Linear"));
  options->push_back(std::string("Linear Mipmap Linear"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Quality:");
  option->setCallback(callback, (void*)"6");
  options = &option->getList();
  options->push_back(std::string("Low"));
  options->push_back(std::string("Medium"));
  options->push_back(std::string("High"));
  options->push_back(std::string("Experimental"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Shadows:");
  option->setCallback(callback, (void*)"7");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Depth Buffer:");
  option->setCallback(callback, (void*)"8");
  options = &option->getList();
  GLint value;
  glGetIntegerv(GL_DEPTH_BITS, &value);
  if (value == 0) {
    options->push_back(std::string("Not available"));
  } else {
    options->push_back(std::string("Off"));
    options->push_back(std::string("On"));
  }
  option->update();
  list.push_back(option);

#if defined(DEBUG_RENDERING)
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Hidden Line:");
  option->setCallback(callback, (void*)"a");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Wireframe:");
  option->setCallback(callback, (void*)"b");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Depth Complexity:");
  option->setCallback(callback, (void*)"c");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);
#endif

  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Culling Tree:");
  option->setCallback(callback, (void*)"d");
  options = &option->getList();
  options->push_back(std::string("Off"));
  options->push_back(std::string("On"));
  option->update();
  list.push_back(option);

  BzfWindow* window = getMainWindow()->getWindow();
  option = new HUDuiList;
  option->setFontFace(fontFace);
  option->setLabel("Brightness:");
  option->setCallback(callback, (void*)"g");
  if (window->hasGammaControl()) {
    option->createSlider(15);
  } else {
    options = &option->getList();
    options->push_back(std::string("Unavailable"));
  }
  option->update();
  list.push_back(option);

  BzfDisplay* display = getDisplay();
  int numFormats = display->getNumResolutions();
  if (numFormats < 2) {
    videoFormat = NULL;
  } else {
    videoFormat = label = new HUDuiLabel;
    label->setFontFace(fontFace);
    label->setLabel("Change Video Format");
    list.push_back(label);
  }

  initNavigation(list, 1,list.size()-1);
}

DisplayMenu::~DisplayMenu()
{
  delete formatMenu;
}

void			DisplayMenu::execute()
{
  HUDuiControl* focus = HUDui::getFocus();
  if (focus == videoFormat) {
    if (!formatMenu)
      formatMenu = new FormatMenu;
    HUDDialogStack::get()->push(formatMenu);
  }
}

void			DisplayMenu::resize(int width, int height)
{
  HUDDialog::resize(width, height);
  int i;

  // use a big font for title, smaller font for the rest
  const float titleFontSize = (float)height / 15.0f;
  const float fontSize = (float)height / 45.0f;
  FontManager &fm = FontManager::instance();
  int fontFace = MainMenu::getFontFace();

  // reposition title
  std::vector<HUDuiControl*>& list = getControls();
  HUDuiLabel* title = (HUDuiLabel*)list[0];
  title->setFontSize(titleFontSize);
  const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString());
  const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " ");
  float x = 0.5f * ((float)width - titleWidth);
  float y = (float)height - titleHeight;
  title->setPosition(x, y);

  // reposition options
  x = 0.5f * ((float)width);
  y -= 0.6f * titleHeight;
  const float h = fm.getStrHeight(fontFace, fontSize, " ");
  const int count = list.size();
  for (i = 1; i < count; i++) {
    list[i]->setFontSize(fontSize);
    list[i]->setPosition(x, y);
    y -= 1.0f * h;
  }

  i = 1;
  // load current settings
  SceneRenderer* renderer = getSceneRenderer();
  if (renderer) {
    HUDuiList* tex;
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("dither"));
    ((HUDuiList*)list[i++])->setIndex(BZDBCache::blend);
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("smooth"));
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("lighting"));
    tex = (HUDuiList*)list[i++];
    ((HUDuiList*)list[i++])->setIndex(renderer->useQuality());
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("shadows"));
    ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("zbuffer"));
#if defined(DEBUG_RENDERING)
    ((HUDuiList*)list[i++])->setIndex(renderer->useHiddenLine() ? 1 : 0);
    ((HUDuiList*)list[i++])->setIndex(renderer->useWireframe() ? 1 : 0);
    ((HUDuiList*)list[i++])->setIndex(renderer->useDepthComplexity() ? 1 : 0);
#endif
    ((HUDuiList*)list[i++])->setIndex(renderer->useCullingTree() ? 1 : 0);

    if (!BZDBCache::texture)
      tex->setIndex(0);
    else
      tex->setIndex(OpenGLTexture::getFilter());
  }

  // brightness
  BzfWindow* window = getMainWindow()->getWindow();
  if (window->hasGammaControl())
    ((HUDuiList*)list[i])->setIndex(gammaToIndex(window->getGamma()));
  i++;

}

int DisplayMenu::gammaToIndex(float gamma)
{
  return (int)(0.5f + 5.0f * (1.0f + logf(gamma) / logf(2.0)));
}

float DisplayMenu::indexToGamma(int index)
{
  // map index 5 to gamma 1.0 and index 0 to gamma 0.5
  return powf(2.0f, (float)index / 5.0f - 1.0f);
}

void			DisplayMenu::callback(HUDuiControl* w, void* data) {
  HUDuiList* list = (HUDuiList*)w;
  SceneRenderer* sceneRenderer = getSceneRenderer();
  switch (((const char*)data)[0]) {
  case '1':
    BZDB.set("dither", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '2':
    BZDB.set("blend", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '3':
    BZDB.set("smooth", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '4':
    BZDB.set("lighting", list->getIndex() ? "1" : "0");
    BZDB.set("_texturereplace", (!BZDB.isTrue("lighting") &&
				 sceneRenderer->useQuality() < 2) ? "1" : "0");
    BZDB.setPersistent("_texturereplace", false);
    sceneRenderer->notifyStyleChange();
    break;
  case '5':
#ifdef _MSC_VER
    // Suppose Pat want to remind himself
    { int somebody_get_tm_to_set_texture; }
#endif
    /*
      OpenGLTexture::setFilter((OpenGLTexture::Filter)list->getIndex());
      BZDB.set("texture", OpenGLTexture::getFilterName());
      sceneRenderer->notifyStyleChange();
    */
    break;
  case '6':
    sceneRenderer->setQuality(list->getIndex());
    BZDB.set("_texturereplace", (!BZDB.isTrue("lighting") &&
				 sceneRenderer->useQuality() < 2) ? "1" : "0");
    BZDB.setPersistent("_texturereplace", false);
    sceneRenderer->notifyStyleChange();
    break;
  case '7':
    BZDB.set("shadows", list->getIndex() ? "1" : "0");
    sceneRenderer->notifyStyleChange();
    break;
  case '8':
    BZDB.set("zbuffer", list->getIndex() ? "1" : "0");
    // FIXME - test for whether the z buffer will work
    setSceneDatabase();
    sceneRenderer->notifyStyleChange();
    break;
#if defined(DEBUG_RENDERING)
  case 'a':
    sceneRenderer->setHiddenLine(list->getIndex() != 0);
    break;
  case 'b':
    sceneRenderer->setWireframe(list->getIndex() != 0);
    break;
  case 'c':
    sceneRenderer->setDepthComplexity(list->getIndex() != 0);
    break;
#endif
  case 'd':
    sceneRenderer->setCullingTree(list->getIndex() != 0);
    break;
  case 'g':
    BzfWindow* window = getMainWindow()->getWindow();
    if (window->hasGammaControl())
      window->setGamma(indexToGamma(list->getIndex()));
    break;
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/**
 * XMLRPCClient.cc
 *
 *      Author: Sara Vallero
 *      Author: Valentina Zaccolo
 */

#include "XMLRPCClient.h"
#include "FassLog.h"
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/client_simple.hpp>
#include <typeinfo>

#include <fstream>
#include <pwd.h>
#include <stdlib.h>
#include <stdexcept>
#include <set>

#include <limits.h>
#include <string.h>
#include <stdlib.h>

#include <sstream>

#include <unistd.h>
#include <sys/types.h>

XMLRPCClient * XMLRPCClient::_client = 0;

XMLRPCClient::XMLRPCClient(const string& secret, const string& endpoint, size_t message_size, unsigned int tout)
{
    //string error;
    //char * xmlrpc_env;

    _auth = secret;

    _endpoint = endpoint;

    //xmlrpc_limit_set(XMLRPC_XML_SIZE_LIMIT_ID, message_size);

    _timeout = tout * 1000;

    //FassLog::log("CLIENT", Log::DDDEBUG, _endpoint);
};

void XMLRPCClient::call_async(const std::string& method, const xmlrpc_c::paramList& plist, xmlrpc_c::value * const result)
{

    xmlrpc_c::clientXmlTransport_curl ctrans;
    xmlrpc_c::client_xml              client(&ctrans);

    xmlrpc_c::rpcPtr rpc(method, plist);
    xmlrpc_c::carriageParm_curl0 cparam(_endpoint);

    rpc->start(&client, &cparam);

    client.finishAsync(xmlrpc_c::timeout(_timeout));

    if (!rpc->isFinished())
    {
        rpc->finishErr(girerr::error("XMLRPC method " + method +
            " timeout, resetting call"));
    }

    if (rpc->isSuccessful())
    {
        *result = rpc->getResult();
    }
    else
    {
        xmlrpc_c::fault failure = rpc->getFault();

        girerr::error(failure.getDescription());
    }

};

void XMLRPCClient::call_sync(const std::string& method, const xmlrpc_c::paramList& plist, xmlrpc_c::value  * const result)
{
    FassLog::log("CLIENT", Log::INFO, _endpoint);
    xmlrpc_c::clientSimple myClient;
    xmlrpc_c::value res;
    myClient.call(_endpoint, method, plist, &res);
    * result = res;

};

void XMLRPCClient::call(const std::string& method, const xmlrpc_c::paramList& plist, xmlrpc_c::value * const result)
{

    //FassLog::log("SARA", Log::INFO, _auth);
    // appends the OpenNebula secret to the list of parameters
    xmlrpc_c::paramList s_plist;
    s_plist.add(xmlrpc_c::value_string(_auth));

    for(unsigned i=0; i < plist.size(); i++) {
        ostringstream oss;
        oss << xmlrpc_c::value_int(plist[i]) << "\n";
        s_plist.addc(plist[i]);
    }

    xmlrpc_c::value res;
    XMLRPCClient::call_async(method, s_plist, result);
    //XMLRPCClient::call_async(method, s_plist, &res);
    //* result = res;

};
<commit_msg>Update XMLRPCClient.cc<commit_after>/**
 * Copyright © 2017 INFN Torino - INDIGO-DataCloud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "XMLRPCClient.h"
#include "FassLog.h"
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/client_simple.hpp>
#include <typeinfo>

#include <fstream>
#include <pwd.h>
#include <stdlib.h>
#include <stdexcept>
#include <set>

#include <limits.h>
#include <string.h>
#include <stdlib.h>

#include <sstream>

#include <unistd.h>
#include <sys/types.h>

XMLRPCClient * XMLRPCClient::_client = 0;

XMLRPCClient::XMLRPCClient(const string& secret, const string& endpoint, size_t message_size, unsigned int tout)
{
    //string error;
    //char * xmlrpc_env;

    _auth = secret;

    _endpoint = endpoint;

    //xmlrpc_limit_set(XMLRPC_XML_SIZE_LIMIT_ID, message_size);

    _timeout = tout * 1000;

    //FassLog::log("CLIENT", Log::DDDEBUG, _endpoint);
};

void XMLRPCClient::call_async(const std::string& method, const xmlrpc_c::paramList& plist, xmlrpc_c::value * const result)
{

    xmlrpc_c::clientXmlTransport_curl ctrans;
    xmlrpc_c::client_xml              client(&ctrans);

    xmlrpc_c::rpcPtr rpc(method, plist);
    xmlrpc_c::carriageParm_curl0 cparam(_endpoint);

    rpc->start(&client, &cparam);

    client.finishAsync(xmlrpc_c::timeout(_timeout));

    if (!rpc->isFinished())
    {
        rpc->finishErr(girerr::error("XMLRPC method " + method +
            " timeout, resetting call"));
    }

    if (rpc->isSuccessful())
    {
        *result = rpc->getResult();
    }
    else
    {
        xmlrpc_c::fault failure = rpc->getFault();

        girerr::error(failure.getDescription());
    }

};

void XMLRPCClient::call_sync(const std::string& method, const xmlrpc_c::paramList& plist, xmlrpc_c::value  * const result)
{
    FassLog::log("CLIENT", Log::INFO, _endpoint);
    xmlrpc_c::clientSimple myClient;
    xmlrpc_c::value res;
    myClient.call(_endpoint, method, plist, &res);
    * result = res;

};

void XMLRPCClient::call(const std::string& method, const xmlrpc_c::paramList& plist, xmlrpc_c::value * const result)
{

    //FassLog::log("SARA", Log::INFO, _auth);
    // appends the OpenNebula secret to the list of parameters
    xmlrpc_c::paramList s_plist;
    s_plist.add(xmlrpc_c::value_string(_auth));

    for(unsigned i=0; i < plist.size(); i++) {
        ostringstream oss;
        oss << xmlrpc_c::value_int(plist[i]) << "\n";
        s_plist.addc(plist[i]);
    }

    xmlrpc_c::value res;
    XMLRPCClient::call_async(method, s_plist, result);
    //XMLRPCClient::call_async(method, s_plist, &res);
    //* result = res;

};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Egor Pugin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     1. Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *     2. Redistributions in binary form must reproduce the above copyright
 *        notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 *     3. Neither the name of the copyright holder nor the names of
 *        its contributors may be used to endorse or promote products
 *        derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "fix_imports.h"

#include <common.h>
#include <cppan.h>
#include <project_path.h>

#include <boost/algorithm/string.hpp>

#include <iostream>
#include <regex>
#include <vector>

using Lines = std::vector<String>;

Lines fix_imports(const Lines &lines_old, const String &old_target, const String new_target)
{
    auto lines = lines_old;
    for (auto &line : lines)
    {
        boost::algorithm::trim(line);
        line = line.substr(0, line.find(old_target)) + new_target + line.substr(line.find(old_target) + old_target.size());
        if (line.find("add_library") == 0 || line.find("add_executable") == 0)
            boost::algorithm::replace_all(line, "IMPORTED", "IMPORTED GLOBAL");
    }
    return lines;
}

void operator+=(String &s, const Lines &lines)
{
    for (auto &line : lines)
        s += line + "\n";
    s += "\n\n\n";
}

void fix_imports(const String &target, const path &aliases_file, const path &old_file, const path &new_file)
{
    auto s = read_file(old_file);
    auto aliases_s = read_file(aliases_file);
    auto dep = extractFromString(target);

    std::ofstream ofile(new_file.string());
    if (!ofile)
        throw std::runtime_error("Cannot open the output file for writing");

    if (dep.version.isBranch())
    {
        boost::algorithm::replace_all(s, "\r", "");
        ofile << s;
        return;
    }

    // finds all inside round brackets ()
    // also checks that closing bracket ) is not in quotes
    String basic = R"(\([^\)]*?\))";
    String add_library = "(add_library|add_executable|set_property|set_target_properties)" + basic;

    Lines lines;
    std::regex r(add_library);
    std::smatch m;
    while (std::regex_search(s, m, r))
    {
        lines.push_back(m.str());
        s = m.suffix();
    }

    String result;
    result += "if (TARGET " + dep.package.toString() + "-" + dep.version.toAnyVersion() + ")\n";
    result += "    return()\n";
    result += "endif()\n";

    {
        auto &d = dep;
        // add GLOBAL for default target
        result += fix_imports(lines, target, d.package.toString() + "-" + d.version.toAnyVersion());
        d.version.patch = -1;
        result += fix_imports(lines, target, d.package.toString() + "-" + d.version.toAnyVersion());
        d.version.minor = -1;
        result += fix_imports(lines, target, d.package.toString() + "-" + d.version.toAnyVersion());
        result += fix_imports(lines, target, d.package.toString());
    }
    {
        auto &d = dep;
        result += fix_imports(lines, target, d.package.toString("::") + "-" + d.version.toAnyVersion());
        d.version.patch = -1;
        result += fix_imports(lines, target, d.package.toString("::") + "-" + d.version.toAnyVersion());
        d.version.minor = -1;
        result += fix_imports(lines, target, d.package.toString("::") + "-" + d.version.toAnyVersion());
        result += fix_imports(lines, target, d.package.toString("::"));
    }
    {
        Lines aliases;
        boost::algorithm::trim(aliases_s);
        boost::algorithm::split(aliases, aliases_s, boost::is_any_of(";"));
        for (auto &a : aliases)
            boost::algorithm::trim(a);
        for (auto &a : aliases)
            if (!a.empty())
                result += fix_imports(lines, target, a);
    }

    boost::algorithm::replace_all(result, "\r", "");
    ofile << result;
}
<commit_msg>Add conditions to export targets.<commit_after>/*
 * Copyright (c) 2016, Egor Pugin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     1. Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *     2. Redistributions in binary form must reproduce the above copyright
 *        notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 *     3. Neither the name of the copyright holder nor the names of
 *        its contributors may be used to endorse or promote products
 *        derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "fix_imports.h"

#include <common.h>
#include <cppan.h>
#include <project_path.h>

#include <boost/algorithm/string.hpp>

#include <deque>
#include <iostream>
#include <regex>
#include <vector>

using Lines = std::deque<String>;

Lines fix_imports(const Lines &lines_old, const String &old_target, const String new_target)
{
    auto lines = lines_old;
    for (auto &line : lines)
    {
        boost::algorithm::trim(line);
        line = line.substr(0, line.find(old_target)) + new_target + line.substr(line.find(old_target) + old_target.size());
        if (line.find("add_library") == 0 || line.find("add_executable") == 0)
            boost::algorithm::replace_all(line, "IMPORTED", "IMPORTED GLOBAL");
    }
    lines.push_front("if (NOT TARGET " + new_target + ")");
    lines.push_back("endif()");
    return lines;
}

void operator+=(String &s, const Lines &lines)
{
    for (auto &line : lines)
        s += line + "\n";
    s += "\n\n\n";
}

void fix_imports(const String &target, const path &aliases_file, const path &old_file, const path &new_file)
{
    auto s = read_file(old_file);
    auto aliases_s = read_file(aliases_file);
    auto dep = extractFromString(target);

    std::ofstream ofile(new_file.string());
    if (!ofile)
        throw std::runtime_error("Cannot open the output file for writing");

    if (dep.version.isBranch())
    {
        boost::algorithm::replace_all(s, "\r", "");
        ofile << s;
        return;
    }

    // finds all inside round brackets ()
    // also checks that closing bracket ) is not in quotes
    String basic = R"(\([^\)]*?\))";
    String add_library = "(add_library|add_executable|set_property|set_target_properties)" + basic;

    Lines lines;
    std::regex r(add_library);
    std::smatch m;
    while (std::regex_search(s, m, r))
    {
        lines.push_back(m.str());
        s = m.suffix();
    }

    String result;
    {
        auto &d = dep;
        // add GLOBAL for default target
        result += fix_imports(lines, target, d.package.toString() + "-" + d.version.toAnyVersion());
        d.version.patch = -1;
        result += fix_imports(lines, target, d.package.toString() + "-" + d.version.toAnyVersion());
        d.version.minor = -1;
        result += fix_imports(lines, target, d.package.toString() + "-" + d.version.toAnyVersion());
        result += fix_imports(lines, target, d.package.toString());
    }
    {
        auto &d = dep;
        result += fix_imports(lines, target, d.package.toString("::") + "-" + d.version.toAnyVersion());
        d.version.patch = -1;
        result += fix_imports(lines, target, d.package.toString("::") + "-" + d.version.toAnyVersion());
        d.version.minor = -1;
        result += fix_imports(lines, target, d.package.toString("::") + "-" + d.version.toAnyVersion());
        result += fix_imports(lines, target, d.package.toString("::"));
    }
    {
        Lines aliases;
        boost::algorithm::trim(aliases_s);
        boost::algorithm::split(aliases, aliases_s, boost::is_any_of(";"));
        for (auto &a : aliases)
            boost::algorithm::trim(a);
        for (auto &a : aliases)
            if (!a.empty())
                result += fix_imports(lines, target, a);
    }

    boost::algorithm::replace_all(result, "\r", "");
    ofile << result;
}
<|endoftext|>


<commit_before>
#include "FMS.h"

namespace HFTE
{
	EngineState engineStateTransitionsMatrix[ENGINE_STATES_COUNT][ENGINE_ACTIONS_COUNT][SYSTEM_ACTIONS_COUNT];
	EngineAction engineActionFilterMatrix[ENGINE_STATES_COUNT][ENGINE_ACTIONS_COUNT][ENGINE_ACTIONS_COUNT];

	/*
	 * Initialization only switches
	 */
	EngineState SwitchEngineState(EngineState engineState, EngineAction engineAction, SystemAction systemAction)
	{
		switch (systemAction)
		{
		case SYSTEM_ACTION_LIMIT_SELL_FILLED: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_SELL_PLACE_SUCCESS: {
			if (engineAction == ENGINE_ACTION_LIMIT_SELL_PLACE)
				switch (engineState)
				{
				case ENGINE_STATE_ENTER: return ENGINE_STATE_LIMIT_SELL;
				case ENGINE_STATE_LIMIT_BUY: return ENGINE_STATE_LIMIT_SELLBUY;
				case ENGINE_STATE_TRADE_BUY: return ENGINE_STATE_LIMIT_SELL_COVER;
				default: break;
				}
			break;
		}
		case SYSTEM_ACTION_LIMIT_SELL_PLACE_FAILED: {
			if (engineAction == ENGINE_ACTION_LIMIT_SELL_PLACE)
				switch (engineState)
				{
				case ENGINE_STATE_ENTER: return ENGINE_STATE_ENTER;
				case ENGINE_STATE_LIMIT_BUY: return ENGINE_STATE_LIMIT_BUY;
				case ENGINE_STATE_TRADE_BUY: return ENGINE_STATE_TRADE_BUY;
				default: break;
				}
			break;
		}
		case SYSTEM_ACTION_LIMIT_SELL_MOVE_SUCCESS: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_SELL_MOVE_FAILED: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_SELL_CANCEL_SUCCESS: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_SELL_CANCEL_FAILED: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_CANCEL_SUCCESS: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_CANCEL_FAILED: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_MOVE_SUCCESS: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_MOVE_FAILED: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_PLACE_SUCCESS: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_PLACE_FAILED: {
			break;
		}
		case SYSTEM_ACTION_LIMIT_BUY_FILLED: {
			break;
		}
		default: break;
		}

		return ENGINE_STATE_NOSTATE;
	}
	EngineAction SwitchEngineAction(std::set<TradePolicy> &policies, EngineState engineState, EngineAction engineAction)
	{
		EngineAction action = EngineAction::ENGINE_ACTION_NOACTION;

		switch (engineState)
		{
		case ENGINE_STATE_NOSTATE: {
			break;
		}
		case ENGINE_STATE_ENTER: {
			if ((engineAction == ENGINE_ACTION_LIMIT_SELL_PLACE &&
				policies.find(TRADE_POLICY_ONLY_BUY) == policies.end()) ||
				(engineAction == ENGINE_ACTION_LIMIT_BUY_PLACE &&
				policies.find(TRADE_POLICY_ONLY_SELL) == policies.end()))
					action = engineAction;
			break;
		}
		case ENGINE_STATE_LIMIT_SELL: {
			if ((engineAction == ENGINE_ACTION_LIMIT_BUY_PLACE &&
				policies.find(TRADE_POLICY_NO_BIDIRECTION) == policies.end()) ||
				(engineAction == ENGINE_ACTION_LIMIT_SELL_MOVE ||
				engineAction == ENGINE_ACTION_LIMIT_SELL_CANCEL)) action = engineAction;
			break;
		}
		case ENGINE_STATE_TRADE_SELL: {
			if (engineAction == ENGINE_ACTION_LIMIT_BUY_PLACE) action = engineAction;
			break;
		}
		case ENGINE_STATE_LIMIT_BUY_COVER: {
			if (engineAction == ENGINE_ACTION_LIMIT_BUY_MOVE ||
				engineAction == ENGINE_ACTION_LIMIT_BUY_CANCEL) action = engineAction;
			break;
		}
		case ENGINE_STATE_LIMIT_SELLBUY: {
			if (engineAction == ENGINE_ACTION_LIMIT_SELL_MOVE ||
				engineAction == ENGINE_ACTION_LIMIT_SELL_CANCEL ||
				engineAction == ENGINE_ACTION_LIMIT_BUY_MOVE ||
				engineAction == ENGINE_ACTION_LIMIT_BUY_CANCEL) action = engineAction;
			break;
		}
		case ENGINE_STATE_LIMIT_BUY: {
			if (engineAction == ENGINE_ACTION_LIMIT_BUY_MOVE ||
				engineAction == ENGINE_ACTION_LIMIT_BUY_CANCEL) action = engineAction;
			break;
		}
		case ENGINE_STATE_TRADE_BUY: {
			if (engineAction == ENGINE_ACTION_LIMIT_SELL_PLACE) action = engineAction;
			break;
		}
		case ENGINE_STATE_LIMIT_SELL_COVER: {
			if (engineAction == ENGINE_ACTION_LIMIT_SELL_MOVE ||
				engineAction == ENGINE_ACTION_LIMIT_SELL_CANCEL) action = engineAction;
			break;
		}
		case ENGINE_STATE_EXIT: {
			break;
		}
		default: break;
		}

		return action;
	}

	/*
	 * Matricies initialization
	 */
	void InitFMSMatrices(std::set<TradePolicy> policies)
	{
		if (policies.size() == 0) LOGD("InitFMSMatrices() No trading policies");
		for (auto policy : policies) {
			LOGD("InitFMSMatrices() Adding trading policy {}", GetTradePolicyString(policy));
			assert(policy < TRADE_POLICIES_COUNT);
		}

		for (int engineState = ENGINE_STATE_NOSTATE; engineState < ENGINE_STATES_COUNT; engineState++)
		for (int engineAction = ENGINE_ACTION_NOACTION; engineAction < ENGINE_ACTIONS_COUNT; engineAction++)
		{
			for (int engineActionCurrent = ENGINE_ACTION_NOACTION; engineActionCurrent < ENGINE_ACTIONS_COUNT; engineActionCurrent++)
			{
				if (engineActionCurrent == ENGINE_ACTION_NOACTION)
				{
					engineActionFilterMatrix
						[EngineState(engineState)]
						[EngineAction(engineActionCurrent)]
						[EngineAction(engineAction)] =
							SwitchEngineAction(
								policies,
								EngineState(engineState),
								EngineAction(engineAction));
				} else {
					engineActionFilterMatrix
						[EngineState(engineState)]
						[EngineAction(engineActionCurrent)]
						[EngineAction(engineAction)] = ENGINE_ACTION_NOACTION;
				}
			}

			for (int systemAction = SYSTEM_ACTION_NOACTION; systemAction < SYSTEM_ACTIONS_COUNT; systemAction++)
			{
				engineStateTransitionsMatrix
					[EngineState(engineState)]
					[EngineAction(engineAction)]
					[SystemAction(systemAction)] =
						SwitchEngineState(
							EngineState(engineState),
							EngineAction(engineAction),
							SystemAction(systemAction));
			}
		}
	}
}
<commit_msg>Delete FMS.cpp<commit_after><|endoftext|>