<commit_before>// dear imgui - standalone example application for DirectX 11
// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp.

#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx11.h"
#include <d3d11.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>

// Data
static ID3D11Device*            g_pd3dDevice = NULL;
static ID3D11DeviceContext*     g_pd3dDeviceContext = NULL;
static IDXGISwapChain*          g_pSwapChain = NULL;
static ID3D11RenderTargetView*  g_mainRenderTargetView = NULL;

// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

// Main code
int main(int, char**)
{
    // Create application window
    //ImGui_ImplWin32_EnableDpiAwareness();
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
    ::RegisterClassEx(&wc);
    HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);

    // Initialize Direct3D
    if (!CreateDeviceD3D(hwnd))
    {
        CleanupDeviceD3D();
        ::UnregisterClass(wc.lpszClassName, wc.hInstance);
        return 1;
    }

    // Show the window
    ::ShowWindow(hwnd, SW_SHOWDEFAULT);
    ::UpdateWindow(hwnd);

    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Setup Platform/Renderer bindings
    ImGui_ImplWin32_Init(hwnd);
    ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'docs/FONTS.md' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    // Our state
    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    // Main loop
    MSG msg;
    ZeroMemory(&msg, sizeof(msg));
    while (msg.message != WM_QUIT)
    {
        // Poll and handle messages (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
        {
            ::TranslateMessage(&msg);
            ::DispatchMessage(&msg);
            continue;
        }

        // Start the Dear ImGui frame
        ImGui_ImplDX11_NewFrame();
        ImGui_ImplWin32_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);

        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
        {
            static float f = 0.0f;
            static int counter = 0;

            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.

            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f

            static float f2 = 0.0f;
            ImGui::DragFloat("f2 limit", &f2, 1.0f, 0.0f, 100.0f, NULL, ImGuiSliderFlags_ClampOnInput);
            ImGui::DragFloat("f2", &f2, 1.0f, 0.0f, 0.0f, NULL, ImGuiSliderFlags_ClampOnInput);

            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
            ImGui::End();
        }

        // 3. Show another simple window.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // Rendering
        ImGui::Render();
        g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
        g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color);
        ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());

        g_pSwapChain->Present(1, 0); // Present with vsync
        //g_pSwapChain->Present(0, 0); // Present without vsync
    }

    // Cleanup
    ImGui_ImplDX11_Shutdown();
    ImGui_ImplWin32_Shutdown();
    ImGui::DestroyContext();

    CleanupDeviceD3D();
    ::DestroyWindow(hwnd);
    ::UnregisterClass(wc.lpszClassName, wc.hInstance);

    return 0;
}

// Helper functions

bool CreateDeviceD3D(HWND hWnd)
{
    // Setup swap chain
    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory(&sd, sizeof(sd));
    sd.BufferCount = 2;
    sd.BufferDesc.Width = 0;
    sd.BufferDesc.Height = 0;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;
    sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    UINT createDeviceFlags = 0;
    //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
    D3D_FEATURE_LEVEL featureLevel;
    const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
    if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
        return false;

    CreateRenderTarget();
    return true;
}

void CleanupDeviceD3D()
{
    CleanupRenderTarget();
    if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
    if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
    if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}

void CreateRenderTarget()
{
    ID3D11Texture2D* pBackBuffer;
    g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
    g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
    pBackBuffer->Release();
}

void CleanupRenderTarget()
{
    if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
}

// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
        return true;

    switch (msg)
    {
    case WM_SIZE:
        if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
        {
            CleanupRenderTarget();
            g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
            CreateRenderTarget();
        }
        return 0;
    case WM_SYSCOMMAND:
        if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
            return 0;
        break;
    case WM_DESTROY:
        ::PostQuitMessage(0);
        return 0;
    }
    return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
<commit_msg>Revert leftovers from 4c201994d421089493a7a996978e8239ad619a20<commit_after>// dear imgui - standalone example application for DirectX 11
// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp.

#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx11.h"
#include <d3d11.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>

// Data
static ID3D11Device*            g_pd3dDevice = NULL;
static ID3D11DeviceContext*     g_pd3dDeviceContext = NULL;
static IDXGISwapChain*          g_pSwapChain = NULL;
static ID3D11RenderTargetView*  g_mainRenderTargetView = NULL;

// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

// Main code
int main(int, char**)
{
    // Create application window
    //ImGui_ImplWin32_EnableDpiAwareness();
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
    ::RegisterClassEx(&wc);
    HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);

    // Initialize Direct3D
    if (!CreateDeviceD3D(hwnd))
    {
        CleanupDeviceD3D();
        ::UnregisterClass(wc.lpszClassName, wc.hInstance);
        return 1;
    }

    // Show the window
    ::ShowWindow(hwnd, SW_SHOWDEFAULT);
    ::UpdateWindow(hwnd);

    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Setup Platform/Renderer bindings
    ImGui_ImplWin32_Init(hwnd);
    ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'docs/FONTS.md' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    // Our state
    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    // Main loop
    MSG msg;
    ZeroMemory(&msg, sizeof(msg));
    while (msg.message != WM_QUIT)
    {
        // Poll and handle messages (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
        {
            ::TranslateMessage(&msg);
            ::DispatchMessage(&msg);
            continue;
        }

        // Start the Dear ImGui frame
        ImGui_ImplDX11_NewFrame();
        ImGui_ImplWin32_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);

        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
        {
            static float f = 0.0f;
            static int counter = 0;

            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.

            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
            ImGui::End();
        }

        // 3. Show another simple window.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // Rendering
        ImGui::Render();
        g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
        g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color);
        ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());

        g_pSwapChain->Present(1, 0); // Present with vsync
        //g_pSwapChain->Present(0, 0); // Present without vsync
    }

    // Cleanup
    ImGui_ImplDX11_Shutdown();
    ImGui_ImplWin32_Shutdown();
    ImGui::DestroyContext();

    CleanupDeviceD3D();
    ::DestroyWindow(hwnd);
    ::UnregisterClass(wc.lpszClassName, wc.hInstance);

    return 0;
}

// Helper functions

bool CreateDeviceD3D(HWND hWnd)
{
    // Setup swap chain
    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory(&sd, sizeof(sd));
    sd.BufferCount = 2;
    sd.BufferDesc.Width = 0;
    sd.BufferDesc.Height = 0;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;
    sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    UINT createDeviceFlags = 0;
    //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
    D3D_FEATURE_LEVEL featureLevel;
    const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
    if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
        return false;

    CreateRenderTarget();
    return true;
}

void CleanupDeviceD3D()
{
    CleanupRenderTarget();
    if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
    if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
    if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}

void CreateRenderTarget()
{
    ID3D11Texture2D* pBackBuffer;
    g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
    g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
    pBackBuffer->Release();
}

void CleanupRenderTarget()
{
    if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
}

// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
        return true;

    switch (msg)
    {
    case WM_SIZE:
        if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
        {
            CleanupRenderTarget();
            g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
            CreateRenderTarget();
        }
        return 0;
    case WM_SYSCOMMAND:
        if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
            return 0;
        break;
    case WM_DESTROY:
        ::PostQuitMessage(0);
        return 0;
    }
    return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include "image-renderer.h"

#include <dali-toolkit/internal/controls/renderers/renderer-factory-impl.h>
#include <dali-toolkit/internal/controls/renderers/renderer-factory-cache.h>
#include <dali-toolkit/internal/controls/renderers/control-renderer-impl.h>
#include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
#include <dali/public-api/images/resource-image.h>

namespace Dali
{

namespace Toolkit
{

namespace Internal
{

namespace
{

const char * const IMAGE_URL_NAME("image-url");
const char * const IMAGE_FITTING_MODE("image-fitting-mode");
const char * const IMAGE_SAMPLING_MODE("image-sampling-mode");
const char * const IMAGE_DESIRED_WIDTH("image-desired-width");
const char * const IMAGE_DESIRED_HEIGHT("image-desired-height");

std::string TEXTURE_UNIFORM_NAME = "sTexture";

#define MAKE_SHADER(A)#A

const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
  attribute mediump vec2 aPosition;\n
  varying mediump vec2 vTexCoord;\n
  uniform mediump mat4 uMvpMatrix;\n
  uniform mediump vec3 uSize;\n
  \n
  void main()\n
  {\n
    mediump vec4 vertexPosition = vec4(aPosition, 0.0, 1.0);\n
    vertexPosition.xyz *= uSize;\n
    vertexPosition = uMvpMatrix * vertexPosition;\n
    \n
    vTexCoord = aPosition + vec2(0.5);\n
    gl_Position = vertexPosition;\n
  }\n
);

const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
  varying mediump vec2 vTexCoord;\n
  uniform sampler2D sTexture;\n
  uniform lowp vec4 uColor;\n
  \n
  void main()\n
  {\n
    gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
  }\n
);

} //unnamed namespace

ImageRenderer::ImageRenderer()
: ControlRenderer(),
  mDesiredSize(),
  mFittingMode( FittingMode::DEFAULT ),
  mSamplingMode( SamplingMode::DEFAULT )
{
}

ImageRenderer::~ImageRenderer()
{
}

void ImageRenderer::Initialize( RendererFactoryCache& factoryCache, const Property::Map& propertyMap )
{
  Initialize(factoryCache);

  Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
  if( imageURLValue )
  {
    imageURLValue->Get( mImageUrl );

    Property::Value* fittingValue = propertyMap.Find( IMAGE_FITTING_MODE );
    if( fittingValue )
    {
      std::string fitting;
      fittingValue->Get( fitting );

      mFittingMode = FittingMode::DEFAULT;
      if( fitting == "shrink-to-fit" )
      {
        mFittingMode = FittingMode::SHRINK_TO_FIT;
      }
      else if( fitting == "scale-to-fill" )
      {
        mFittingMode = FittingMode::SCALE_TO_FILL;
      }
      else if( fitting == "fit-width" )
      {
        mFittingMode = FittingMode::FIT_WIDTH;
      }
      else if( fitting == "fit-height" )
      {
        mFittingMode = FittingMode::FIT_HEIGHT;
      }
      else if( fitting == "default" )
      {
        mFittingMode = FittingMode::DEFAULT;
      }
      else
      {
        DALI_ASSERT_ALWAYS("Unknown fitting mode");
      }
    }

    Property::Value* samplingValue = propertyMap.Find( IMAGE_SAMPLING_MODE );
    if( samplingValue )
    {
      std::string sampling;
      samplingValue->Get( sampling );

      mSamplingMode = SamplingMode::DEFAULT;
      if( sampling == "box" )
      {
        mSamplingMode = SamplingMode::BOX;
      }
      else if( sampling == "nearest" )
      {
        mSamplingMode = SamplingMode::NEAREST;
      }
      else if( sampling == "linear" )
      {
        mSamplingMode = SamplingMode::LINEAR;
      }
      else if( sampling == "box-then-nearest" )
      {
        mSamplingMode = SamplingMode::BOX_THEN_NEAREST;
      }
      else if( sampling == "box-then-linear" )
      {
        mSamplingMode = SamplingMode::BOX_THEN_LINEAR;
      }
      else if( sampling == "no-filter" )
      {
        mSamplingMode = SamplingMode::NO_FILTER;
      }
      else if( sampling == "dont-care" )
      {
        mSamplingMode = SamplingMode::DONT_CARE;
      }
      else if( sampling == "default" )
      {
        mSamplingMode = SamplingMode::DEFAULT;
      }
      else
      {
        DALI_ASSERT_ALWAYS("Unknown sampling mode");
      }
    }

    int desiredWidth = 0;
    Property::Value* desiredWidthValue = propertyMap.Find( IMAGE_DESIRED_WIDTH );
    if( desiredWidthValue )
    {
      desiredWidthValue->Get( desiredWidth );
    }

    int desiredHeight = 0;
    Property::Value* desiredHeightValue = propertyMap.Find( IMAGE_DESIRED_HEIGHT );
    if( desiredHeightValue )
    {
      desiredHeightValue->Get( desiredHeight );
    }

    mDesiredSize = ImageDimensions( desiredWidth, desiredHeight );
  }

  mImage.Reset();
}

void ImageRenderer::SetSize( const Vector2& size )
{
  ControlRenderer::SetSize( size );
  // ToDo: renderer responds to the size change
}

void ImageRenderer::SetClipRect( const Rect<int>& clipRect )
{
  ControlRenderer::SetClipRect( clipRect );
  //ToDo: renderer responds to the clipRect change
}

void ImageRenderer::SetOffset( const Vector2& offset )
{
  //ToDo: renderer applies the offset
}

void ImageRenderer::DoSetOnStage( Actor& actor )
{
  if( !mImageUrl.empty() && !mImage )
  {
    mImage = Dali::ResourceImage::New( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode );
  }

  ApplyImageToSampler();
}

void ImageRenderer::DoSetOffStage( Actor& actor )
{
  //If we own the image then make sure we release it when we go off stage
  if( !mImageUrl.empty() )
  {
    mImage.Reset();
  }

  ControlRenderer::SetOffStage( actor );
}

void ImageRenderer::Initialize( RendererFactoryCache& factoryCache )
{
  mImpl->mGeometry = factoryCache.GetGeometry( RendererFactoryCache::QUAD_GEOMETRY );
  if( !(mImpl->mGeometry) )
  {
    mImpl->mGeometry =  factoryCache.CreateQuadGeometry();
    factoryCache.SaveGeometry( RendererFactoryCache::QUAD_GEOMETRY, mImpl->mGeometry );
  }

  mImpl->mShader = factoryCache.GetShader( RendererFactoryCache::IMAGE_SHADER );
  if( !mImpl->mShader )
  {
    mImpl->mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
    factoryCache.SaveShader( RendererFactoryCache::IMAGE_SHADER, mImpl->mShader );
  }

  mDesiredSize = ImageDimensions();
  mFittingMode = FittingMode::DEFAULT;
  mSamplingMode = SamplingMode::DEFAULT;
  mImageUrl.clear();
}

void ImageRenderer::SetImage( const std::string& imageUrl )
{
  SetImage( imageUrl, 0, 0, Dali::FittingMode::DEFAULT, Dali::SamplingMode::DEFAULT );
}

void ImageRenderer::SetImage( const std::string& imageUrl, int desiredWidth, int desiredHeight, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode )
{
  if( mImageUrl != imageUrl )
  {
    mImageUrl = imageUrl;
    mDesiredSize = ImageDimensions( desiredWidth, desiredHeight );
    mFittingMode = fittingMode;
    mSamplingMode = samplingMode;

    if( !mImageUrl.empty() && mImpl->mIsOnStage )
    {
      mImage = Dali::ResourceImage::New( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode );
      ApplyImageToSampler();
    }
    else
    {
      mImage.Reset();
    }
  }
}

void ImageRenderer::SetImage( Image image )
{
  if( mImage != image )
  {
    mImageUrl.clear();
    mDesiredSize = ImageDimensions();
    mFittingMode = FittingMode::DEFAULT;
    mSamplingMode = SamplingMode::DEFAULT;
    mImage = image;

    if( mImage && mImpl->mIsOnStage )
    {
      ApplyImageToSampler();
    }
  }
}

Image ImageRenderer::GetImage() const
{
  return mImage;
}

void ImageRenderer::ApplyImageToSampler()
{
  if( mImage )
  {
    Material material = mImpl->mRenderer.GetMaterial();
    if( material )
    {
      for( std::size_t i = 0; i < material.GetNumberOfSamplers(); ++i )
      {
        Sampler sampler = material.GetSamplerAt( i );
        if( sampler.GetUniformName() == TEXTURE_UNIFORM_NAME )
        {
          sampler.SetImage( mImage );
          return;
        }
      }

      Sampler sampler = Sampler::New( mImage, TEXTURE_UNIFORM_NAME );
      material.AddSampler( sampler );
    }
  }
}

} // namespace Internal

} // namespace Toolkit

} // namespace Dali
<commit_msg>Fixed ImageRenderer::DoSetOffStage inccorrectly calling ControlRenderer::SetOffStage.<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include "image-renderer.h"

#include <dali-toolkit/internal/controls/renderers/renderer-factory-impl.h>
#include <dali-toolkit/internal/controls/renderers/renderer-factory-cache.h>
#include <dali-toolkit/internal/controls/renderers/control-renderer-impl.h>
#include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
#include <dali/public-api/images/resource-image.h>

namespace Dali
{

namespace Toolkit
{

namespace Internal
{

namespace
{

const char * const IMAGE_URL_NAME("image-url");
const char * const IMAGE_FITTING_MODE("image-fitting-mode");
const char * const IMAGE_SAMPLING_MODE("image-sampling-mode");
const char * const IMAGE_DESIRED_WIDTH("image-desired-width");
const char * const IMAGE_DESIRED_HEIGHT("image-desired-height");

std::string TEXTURE_UNIFORM_NAME = "sTexture";

#define MAKE_SHADER(A)#A

const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
  attribute mediump vec2 aPosition;\n
  varying mediump vec2 vTexCoord;\n
  uniform mediump mat4 uMvpMatrix;\n
  uniform mediump vec3 uSize;\n
  \n
  void main()\n
  {\n
    mediump vec4 vertexPosition = vec4(aPosition, 0.0, 1.0);\n
    vertexPosition.xyz *= uSize;\n
    vertexPosition = uMvpMatrix * vertexPosition;\n
    \n
    vTexCoord = aPosition + vec2(0.5);\n
    gl_Position = vertexPosition;\n
  }\n
);

const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
  varying mediump vec2 vTexCoord;\n
  uniform sampler2D sTexture;\n
  uniform lowp vec4 uColor;\n
  \n
  void main()\n
  {\n
    gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
  }\n
);

} //unnamed namespace

ImageRenderer::ImageRenderer()
: ControlRenderer(),
  mDesiredSize(),
  mFittingMode( FittingMode::DEFAULT ),
  mSamplingMode( SamplingMode::DEFAULT )
{
}

ImageRenderer::~ImageRenderer()
{
}

void ImageRenderer::Initialize( RendererFactoryCache& factoryCache, const Property::Map& propertyMap )
{
  Initialize(factoryCache);

  Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
  if( imageURLValue )
  {
    imageURLValue->Get( mImageUrl );

    Property::Value* fittingValue = propertyMap.Find( IMAGE_FITTING_MODE );
    if( fittingValue )
    {
      std::string fitting;
      fittingValue->Get( fitting );

      mFittingMode = FittingMode::DEFAULT;
      if( fitting == "shrink-to-fit" )
      {
        mFittingMode = FittingMode::SHRINK_TO_FIT;
      }
      else if( fitting == "scale-to-fill" )
      {
        mFittingMode = FittingMode::SCALE_TO_FILL;
      }
      else if( fitting == "fit-width" )
      {
        mFittingMode = FittingMode::FIT_WIDTH;
      }
      else if( fitting == "fit-height" )
      {
        mFittingMode = FittingMode::FIT_HEIGHT;
      }
      else if( fitting == "default" )
      {
        mFittingMode = FittingMode::DEFAULT;
      }
      else
      {
        DALI_ASSERT_ALWAYS("Unknown fitting mode");
      }
    }

    Property::Value* samplingValue = propertyMap.Find( IMAGE_SAMPLING_MODE );
    if( samplingValue )
    {
      std::string sampling;
      samplingValue->Get( sampling );

      mSamplingMode = SamplingMode::DEFAULT;
      if( sampling == "box" )
      {
        mSamplingMode = SamplingMode::BOX;
      }
      else if( sampling == "nearest" )
      {
        mSamplingMode = SamplingMode::NEAREST;
      }
      else if( sampling == "linear" )
      {
        mSamplingMode = SamplingMode::LINEAR;
      }
      else if( sampling == "box-then-nearest" )
      {
        mSamplingMode = SamplingMode::BOX_THEN_NEAREST;
      }
      else if( sampling == "box-then-linear" )
      {
        mSamplingMode = SamplingMode::BOX_THEN_LINEAR;
      }
      else if( sampling == "no-filter" )
      {
        mSamplingMode = SamplingMode::NO_FILTER;
      }
      else if( sampling == "dont-care" )
      {
        mSamplingMode = SamplingMode::DONT_CARE;
      }
      else if( sampling == "default" )
      {
        mSamplingMode = SamplingMode::DEFAULT;
      }
      else
      {
        DALI_ASSERT_ALWAYS("Unknown sampling mode");
      }
    }

    int desiredWidth = 0;
    Property::Value* desiredWidthValue = propertyMap.Find( IMAGE_DESIRED_WIDTH );
    if( desiredWidthValue )
    {
      desiredWidthValue->Get( desiredWidth );
    }

    int desiredHeight = 0;
    Property::Value* desiredHeightValue = propertyMap.Find( IMAGE_DESIRED_HEIGHT );
    if( desiredHeightValue )
    {
      desiredHeightValue->Get( desiredHeight );
    }

    mDesiredSize = ImageDimensions( desiredWidth, desiredHeight );
  }

  mImage.Reset();
}

void ImageRenderer::SetSize( const Vector2& size )
{
  ControlRenderer::SetSize( size );
  // ToDo: renderer responds to the size change
}

void ImageRenderer::SetClipRect( const Rect<int>& clipRect )
{
  ControlRenderer::SetClipRect( clipRect );
  //ToDo: renderer responds to the clipRect change
}

void ImageRenderer::SetOffset( const Vector2& offset )
{
  //ToDo: renderer applies the offset
}

void ImageRenderer::DoSetOnStage( Actor& actor )
{
  if( !mImageUrl.empty() && !mImage )
  {
    mImage = Dali::ResourceImage::New( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode );
  }

  ApplyImageToSampler();
}

void ImageRenderer::DoSetOffStage( Actor& actor )
{
  //If we own the image then make sure we release it when we go off stage
  if( !mImageUrl.empty() )
  {
    mImage.Reset();
  }
}

void ImageRenderer::Initialize( RendererFactoryCache& factoryCache )
{
  mImpl->mGeometry = factoryCache.GetGeometry( RendererFactoryCache::QUAD_GEOMETRY );
  if( !(mImpl->mGeometry) )
  {
    mImpl->mGeometry =  factoryCache.CreateQuadGeometry();
    factoryCache.SaveGeometry( RendererFactoryCache::QUAD_GEOMETRY, mImpl->mGeometry );
  }

  mImpl->mShader = factoryCache.GetShader( RendererFactoryCache::IMAGE_SHADER );
  if( !mImpl->mShader )
  {
    mImpl->mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
    factoryCache.SaveShader( RendererFactoryCache::IMAGE_SHADER, mImpl->mShader );
  }

  mDesiredSize = ImageDimensions();
  mFittingMode = FittingMode::DEFAULT;
  mSamplingMode = SamplingMode::DEFAULT;
  mImageUrl.clear();
}

void ImageRenderer::SetImage( const std::string& imageUrl )
{
  SetImage( imageUrl, 0, 0, Dali::FittingMode::DEFAULT, Dali::SamplingMode::DEFAULT );
}

void ImageRenderer::SetImage( const std::string& imageUrl, int desiredWidth, int desiredHeight, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode )
{
  if( mImageUrl != imageUrl )
  {
    mImageUrl = imageUrl;
    mDesiredSize = ImageDimensions( desiredWidth, desiredHeight );
    mFittingMode = fittingMode;
    mSamplingMode = samplingMode;

    if( !mImageUrl.empty() && mImpl->mIsOnStage )
    {
      mImage = Dali::ResourceImage::New( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode );
      ApplyImageToSampler();
    }
    else
    {
      mImage.Reset();
    }
  }
}

void ImageRenderer::SetImage( Image image )
{
  if( mImage != image )
  {
    mImageUrl.clear();
    mDesiredSize = ImageDimensions();
    mFittingMode = FittingMode::DEFAULT;
    mSamplingMode = SamplingMode::DEFAULT;
    mImage = image;

    if( mImage && mImpl->mIsOnStage )
    {
      ApplyImageToSampler();
    }
  }
}

Image ImageRenderer::GetImage() const
{
  return mImage;
}

void ImageRenderer::ApplyImageToSampler()
{
  if( mImage )
  {
    Material material = mImpl->mRenderer.GetMaterial();
    if( material )
    {
      for( std::size_t i = 0; i < material.GetNumberOfSamplers(); ++i )
      {
        Sampler sampler = material.GetSamplerAt( i );
        if( sampler.GetUniformName() == TEXTURE_UNIFORM_NAME )
        {
          sampler.SetImage( mImage );
          return;
        }
      }

      Sampler sampler = Sampler::New( mImage, TEXTURE_UNIFORM_NAME );
      material.AddSampler( sampler );
    }
  }
}

} // namespace Internal

} // namespace Toolkit

} // namespace Dali
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright © 2017-2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
 * Debug
 * Helper facilities for debugging Skui, primarily meant for Skui development.
 */

#ifndef SKUI_CORE_DEBUG_H
#define SKUI_CORE_DEBUG_H

#include "core/utility.h++"

#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

#ifdef _WIN32
#include "core/utility.h++"
#ifndef WIN32_MEAN_AND_LEAN
#define WIN32_MEAN_AND_LEAN
#endif
#include <windows.h>
#undef WIN32_MEAN_AND_LEAN
#endif

namespace skui::core
{
  template<typename... ArgTypes>
#ifndef SKUI_DEBUG
  inline void debug_print(ArgTypes...)
  {}
#else
  inline void debug_print(ArgTypes... args)
  {
    using namespace std::chrono;
#ifdef _WIN32
    std::stringstream stream;
#else
    auto& stream = std::cerr;
#endif
    const auto now = system_clock::now();
    const auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
    const auto time = system_clock::to_time_t(now);
    const auto utc_time = std::gmtime(&time);

    core::ostream_format_keeper guard(stream);
    stream << std::put_time(utc_time, "%FT%T.")
           << std::setprecision(4) << std::setfill('0') << std::setw(3) << ms.count()
           << std::put_time(utc_time, "%z: ");
    ((stream << args), ...);

#ifdef _WIN32
    OutputDebugStringW(convert_to_utf16(stream.str()).c_str());
#endif
  }
#endif
}

#endif
<commit_msg>Let core::debug_print print booleans as true/false.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright © 2017-2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
 * Debug
 * Helper facilities for debugging Skui, primarily meant for Skui development.
 */

#ifndef SKUI_CORE_DEBUG_H
#define SKUI_CORE_DEBUG_H

#include "core/utility.h++"

#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

#ifdef _WIN32
#include "core/utility.h++"
#ifndef WIN32_MEAN_AND_LEAN
#define WIN32_MEAN_AND_LEAN
#endif
#include <windows.h>
#undef WIN32_MEAN_AND_LEAN
#endif

namespace skui::core
{
  template<typename... ArgTypes>
#ifndef SKUI_DEBUG
  inline void debug_print(ArgTypes...)
  {}
#else
  inline void debug_print(ArgTypes... args)
  {
    using namespace std::chrono;
#ifdef _WIN32
    std::stringstream stream;
#else
    auto& stream = std::cerr;
    core::ostream_format_keeper guard(stream);
#endif
    const auto now = system_clock::now();
    const auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
    const auto time = system_clock::to_time_t(now);
    const auto utc_time = std::gmtime(&time);

    stream << std::put_time(utc_time, "%FT%T.")
           << std::setprecision(4) << std::setfill('0') << std::setw(3) << ms.count()
           << std::put_time(utc_time, "%z: ");
    stream << std::boolalpha;
    ((stream << args), ...);

#ifdef _WIN32
    OutputDebugStringW(convert_to_utf16(stream.str()).c_str());
#endif
  }
#endif
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <getopt.h>
#include <algorithm>
#include <memory>

#include <zcm/zcm-cpp.hpp>

#include "zcm/json/json.h"

#include "zcm/util/TypeDb.hpp"

#include "IndexerPluginDb.hpp"

using namespace std;

struct Args
{
    string logfile     = "";
    string output      = "";
    string plugin_path = "";
    string type_path   = "";
    bool readable      = false;
    bool debug         = false;
    bool useDefault    = false;

    bool parse(int argc, char *argv[])
    {
        // set some defaults
        const char *optstring = "l:o:p:t:rdh";
        struct option long_opts[] = {
            { "log",         required_argument, 0, 'l' },
            { "output",      required_argument, 0, 'o' },
            { "plugin-path", required_argument, 0, 'p' },
            { "type-path",   required_argument, 0, 't' },
            { "readable",    no_argument,       0, 'r' },
            { "use-default", no_argument,       0, 'd' },
            { "debug",       no_argument,       0,  0  },
            { "help",        no_argument,       0, 'h' },
            { 0, 0, 0, 0 }
        };

        int c;
        while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) {
            switch (c) {
                case 'l': logfile     = string(optarg); break;
                case 'o': output      = string(optarg); break;
                case 'p': plugin_path = string(optarg); break;
                case 't': type_path   = string(optarg); break;
                case 'r': readable    = true;           break;
                case 'd': useDefault  = true;           break;
                case 'h':
                default:
                    if (string(argv[optind]) == "debug") {
                        debug = true;
                    } else return false;
            };
        }

        if (logfile == "") {
            cerr << "Please specify logfile input" << endl;
            return false;
        }

        if (output  == "") {
            cerr << "Please specify index file output" << endl;
            return false;
        }

        const char* type_path_env = getenv("ZCM_LOG_INDEXER_ZCMTYPES_PATH");
        if (type_path == "" && type_path_env) type_path = type_path_env;
        if (type_path == "") {
            cerr << "Please specify a zcmtypes.so path either through -t TYPE_PATH "
                    "or through the env var ZCM_LOG_INDEXER_ZCMTYPES_PATH" << endl;
            return false;
        }

        const char* plugin_path_env = getenv("ZCM_LOG_INDEXER_PLUGINS_PATH");
        if (plugin_path == "" && plugin_path_env) plugin_path = plugin_path_env;
        if (plugin_path == "") cerr << "Running with default timestamp indexer plugin" << endl;

        return true;
    }

    void usage()
    {
        cerr << "usage: zcm-log-indexer [options]" << endl
             << "" << endl
             << "    Load in a log file and write an index json file that" << endl
             << "    allows for faster log indexing." << endl
             << "" << endl
             << "Example:" << endl
             << "    zcm-log-indexer -l zcm.log -o index.dbz -t path/to/zcmtypes.so" << endl
             << "" << endl
             << "Options:" << endl
             << "" << endl
             << "  -h, --help              Shows this help text and exits" << endl
             << "  -l, --log=logfile       Input log to index for fast querying" << endl
             << "  -o, --output=indexfile  Output index file to be used with log" << endl
             << "  -p, --plugin-path=path  Path to shared library containing indexer plugins" << endl
             << "                          Can also be specified via the environment variable" << endl
             << "                          ZCM_LOG_INDEXER_ZCMTYPES_PATH" << endl
             << "  -t, --type-path=path    Path to shared library containing the zcmtypes" << endl
             << "                          Can also be specified via the environment variable" << endl
             << "                          ZCM_LOG_INDEXER_PLUGINS_PATH" << endl
             << "  -r, --readable          Don't minify the output index file. " << endl
             << "                          Leave it human readable" << endl
             << "  -d, --debug             Run a dry run to ensure proper indexer setup" << endl
             << endl << endl;
    }
};

int main(int argc, char* argv[])
{
    Args args;
    if (!args.parse(argc, argv)) {
        args.usage();
        return 1;
    }

    zcm::LogFile log(args.logfile, "r");
    if (!log.good()) {
        cerr << "Unable to open logfile: " << args.logfile << endl;
        return 1;
    }
    fseeko(log.getFilePtr(), 0, SEEK_END);
    // XXX Look into handling large logfiles
    off_t logSize = ftello(log.getFilePtr());

    ofstream output;
    output.open(args.output);
    if (!output.is_open()) {
        cerr << "Unable to open output file: " << args.output << endl;
        log.close();
        return 1;
    }

    vector<zcm::IndexerPlugin*> plugins;

    bool defaultShouldBeIncluded = true;
    zcm::IndexerPlugin* defaultPlugin = new zcm::IndexerPlugin();

    IndexerPluginDb pluginDb(args.plugin_path, args.debug);
    // Load plugins from path if specified
    if (args.plugin_path != "") {
        bool dependsOnDefault = false;
        vector<const zcm::IndexerPlugin*> dbPlugins = pluginDb.getPlugins();
        // casting away constness. Don't mess up.
        for (auto dbp : dbPlugins) {
            plugins.push_back((zcm::IndexerPlugin*) dbp);
            defaultShouldBeIncluded = false;
            auto deps = dbp->dependsOn();
            for (auto dep : deps) {
                if (dep == defaultPlugin->name()) {
                    dependsOnDefault = true;
                    break;
                }
            }
        }

        if (dependsOnDefault || args.useDefault)
            defaultShouldBeIncluded = true;
    }

    if (defaultShouldBeIncluded) plugins.push_back(defaultPlugin);

    for (size_t i = 0; i < plugins.size(); ++i) {
        for (size_t j = i + 1; j < plugins.size(); ++j) {
            if (args.debug)
                cout << plugins.data()[i] << "->name() == "
                     << plugins.data()[j] << "->name()" << endl;

            if (plugins[i]->name() == plugins[j]->name()) {
                cerr << "Plugins must have unique names. Collision: "
                     << plugins[i]->name() << endl;
                return 1;
            }
        }
    }

    TypeDb types(args.type_path, args.debug);

    if (args.debug) return 0;

    struct PluginRuntimeInfo {
        zcm::IndexerPlugin* plugin;
        bool runThroughLog;
    };

    auto buildPluginGroups = [] (vector<zcm::IndexerPlugin*> plugins) {
        vector<vector<PluginRuntimeInfo>> groups;
        vector<zcm::IndexerPlugin*> lastLoop = plugins;
        while (!plugins.empty()) {
            groups.resize(groups.size() + 1);
            for (auto p = plugins.begin(); p != plugins.end();) {
                auto deps = (*p)->dependsOn();

                bool skipUntilLater = false;
                for (auto* dep : plugins) {
                    if (find(deps.begin(), deps.end(), dep->name()) != deps.end()) {
                        skipUntilLater = true;
                        break;
                    }
                }
                for (auto dep : groups.back()) {
                    if (find(deps.begin(), deps.end(), dep.plugin->name()) != deps.end()) {
                        skipUntilLater = true;
                        break;
                    }
                }
                if (!skipUntilLater) {
                    groups.back().push_back({*p, false});
                    p = plugins.erase(p);
                } else {
                    ++p;
                }
            }

            // Check for dependency resolution failure
            if (plugins == lastLoop) {
                cerr << "Unable to resolve all plugin dependencies. "
                        "Plugins left to resolve:" << endl << endl;
                for (auto* p : plugins) {
                    cerr << p->name() << endl
                         << "  Depends on:" << endl;
                    for (auto d : p->dependsOn())
                         cerr << "    " << d << endl;
                    cerr << endl;
                }
                exit(1);
            }
            lastLoop = plugins;
        }
        return groups;
    };

    // We do not own all the memory in here. We only own the default prorgam
    vector<vector<PluginRuntimeInfo>> pluginGroups;
    pluginGroups = buildPluginGroups(plugins);
    if (pluginGroups.size() > 1) {
        cout << "Identified " << pluginGroups.size() << " indexer plugin groups" << endl
             << "Running through log " << pluginGroups.size()
             << " times to satisfy dependencies" << endl;
    }

    zcm::Json::Value index;

    size_t numEvents = 0;
    const zcm::LogEvent* evt;
    for (size_t i = 0; i < pluginGroups.size(); ++i) {
        if (pluginGroups.size() != 1) cout << "Plugin group " << (i + 1) << endl;
        off_t offset = 0;
        fseeko(log.getFilePtr(), 0, SEEK_SET);

        for (auto& p : pluginGroups[i])
            p.runThroughLog = p.plugin->setUp(index, index[p.plugin->name()], log);

        while (1) {
            offset = ftello(log.getFilePtr());

            static int lastPrintPercent = 0;
            int percent = (100.0 * offset / logSize) * 100;
            if (percent != lastPrintPercent) {
                cout << "\r" << "Percent Complete: " << (percent / 100) << flush;
                lastPrintPercent = percent;
            }

            evt = log.readNextEvent();
            if (evt == nullptr) break;

            int64_t msg_hash;
            __int64_t_decode_array(evt->data, 0, 8, &msg_hash, 1);
            const TypeMetadata* md = types.getByHash(msg_hash);
            if (!md) continue;

            for (auto& p : pluginGroups[i]) {
                assert(p.plugin);

                if (!p.runThroughLog) continue;

                p.plugin->indexEvent(index, index[p.plugin->name()],
                                     evt->channel, md->name,
                                     offset, evt->timestamp,
                                     (uint64_t) msg_hash,
                                     evt->data, evt->datalen);

                numEvents++;
            }
        }

        cout << endl;

        for (auto& p : pluginGroups[i])
            p.plugin->tearDown(index, index[p.plugin->name()], log);
    }

    delete defaultPlugin;
    defaultPlugin = nullptr;

    zcm::Json::StreamWriterBuilder builder;
    builder["indentation"] = args.readable ? "    " : "";
    std::unique_ptr<zcm::Json::StreamWriter> writer(builder.newStreamWriter());
    writer->write(index, &output);
    output << endl;
    output.close();

    cout << "Indexed " << numEvents << " events" << endl;
    return 0;
}
<commit_msg>reviewed<commit_after>#include <iostream>
#include <fstream>
#include <getopt.h>
#include <algorithm>
#include <memory>

#include <zcm/zcm-cpp.hpp>

#include "zcm/json/json.h"

#include "zcm/util/TypeDb.hpp"

#include "IndexerPluginDb.hpp"

using namespace std;

struct Args
{
    string logfile     = "";
    string output      = "";
    string plugin_path = "";
    string type_path   = "";
    bool readable      = false;
    bool debug         = false;
    bool useDefault    = false;

    bool parse(int argc, char *argv[])
    {
        // set some defaults
        const char *optstring = "l:o:p:t:rdh";
        struct option long_opts[] = {
            { "log",         required_argument, 0, 'l' },
            { "output",      required_argument, 0, 'o' },
            { "plugin-path", required_argument, 0, 'p' },
            { "type-path",   required_argument, 0, 't' },
            { "readable",    no_argument,       0, 'r' },
            { "use-default", no_argument,       0, 'd' },
            { "debug",       no_argument,       0,  0  },
            { "help",        no_argument,       0, 'h' },
            { 0, 0, 0, 0 }
        };

        int c;
        while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) {
            switch (c) {
                case 'l': logfile     = string(optarg); break;
                case 'o': output      = string(optarg); break;
                case 'p': plugin_path = string(optarg); break;
                case 't': type_path   = string(optarg); break;
                case 'r': readable    = true;           break;
                case 'd': useDefault  = true;           break;
                case 'h':
                default:
                    if (string(argv[optind]) == "debug") {
                        debug = true;
                    } else return false;
            };
        }

        if (logfile == "") {
            cerr << "Please specify logfile input" << endl;
            return false;
        }

        if (output  == "") {
            cerr << "Please specify index file output" << endl;
            return false;
        }

        const char* type_path_env = getenv("ZCM_LOG_INDEXER_ZCMTYPES_PATH");
        if (type_path == "" && type_path_env) type_path = type_path_env;
        if (type_path == "") {
            cerr << "Please specify a zcmtypes.so path either through -t TYPE_PATH "
                    "or through the env var ZCM_LOG_INDEXER_ZCMTYPES_PATH" << endl;
            return false;
        }

        const char* plugin_path_env = getenv("ZCM_LOG_INDEXER_PLUGINS_PATH");
        if (plugin_path == "" && plugin_path_env) plugin_path = plugin_path_env;
        if (plugin_path == "") cerr << "Running with default timestamp indexer plugin" << endl;

        return true;
    }

    void usage()
    {
        cerr << "usage: zcm-log-indexer [options]" << endl
             << "" << endl
             << "    Load in a log file and write an index json file that" << endl
             << "    allows for faster log indexing." << endl
             << "" << endl
             << "Example:" << endl
             << "    zcm-log-indexer -l zcm.log -o index.dbz -t path/to/zcmtypes.so" << endl
             << "" << endl
             << "Options:" << endl
             << "" << endl
             << "  -h, --help              Shows this help text and exits" << endl
             << "  -l, --log=logfile       Input log to index for fast querying" << endl
             << "  -o, --output=indexfile  Output index file to be used with log" << endl
             << "  -p, --plugin-path=path  Path to shared library containing indexer plugins" << endl
             << "                          Can also be specified via the environment variable" << endl
             << "                          ZCM_LOG_INDEXER_ZCMTYPES_PATH" << endl
             << "  -t, --type-path=path    Path to shared library containing the zcmtypes" << endl
             << "                          Can also be specified via the environment variable" << endl
             << "                          ZCM_LOG_INDEXER_PLUGINS_PATH" << endl
             << "  -r, --readable          Don't minify the output index file. " << endl
             << "                          Leave it human readable" << endl
             << "  -d, --debug             Run a dry run to ensure proper indexer setup" << endl
             << endl << endl;
    }
};

int main(int argc, char* argv[])
{
    Args args;
    if (!args.parse(argc, argv)) {
        args.usage();
        return 1;
    }

    zcm::LogFile log(args.logfile, "r");
    if (!log.good()) {
        cerr << "Unable to open logfile: " << args.logfile << endl;
        return 1;
    }
    fseeko(log.getFilePtr(), 0, SEEK_END);
    // XXX Look into handling large logfiles
    off_t logSize = ftello(log.getFilePtr());

    ofstream output;
    output.open(args.output);
    if (!output.is_open()) {
        cerr << "Unable to open output file: " << args.output << endl;
        log.close();
        return 1;
    }

    vector<zcm::IndexerPlugin*> plugins;

    bool defaultShouldBeIncluded = true;
    zcm::IndexerPlugin* defaultPlugin = new zcm::IndexerPlugin();

    IndexerPluginDb pluginDb(args.plugin_path, args.debug);
    // Load plugins from path if specified
    if (args.plugin_path != "") {
        bool dependsOnDefault = false;
        vector<const zcm::IndexerPlugin*> dbPlugins = pluginDb.getPlugins();
        if (!dbPlugins.empty()) defaultShouldBeIncluded = false;
        // casting away constness. Don't mess up.
        for (auto dbp : dbPlugins) {
            plugins.push_back((zcm::IndexerPlugin*) dbp);
            auto deps = dbp->dependsOn();
            for (auto dep : deps) {
                if (dep == defaultPlugin->name()) {
                    dependsOnDefault = true;
                    break;
                }
            }
        }

        if (dependsOnDefault || args.useDefault)
            defaultShouldBeIncluded = true;
    }

    if (defaultShouldBeIncluded) plugins.push_back(defaultPlugin);

    for (size_t i = 0; i < plugins.size(); ++i) {
        for (size_t j = i + 1; j < plugins.size(); ++j) {
            if (args.debug)
                cout << plugins.data()[i] << "->name() == "
                     << plugins.data()[j] << "->name()" << endl;

            if (plugins[i]->name() == plugins[j]->name()) {
                cerr << "Plugins must have unique names. Collision: "
                     << plugins[i]->name() << endl;
                return 1;
            }
        }
    }

    TypeDb types(args.type_path, args.debug);

    if (args.debug) return 0;

    struct PluginRuntimeInfo {
        zcm::IndexerPlugin* plugin;
        bool runThroughLog;
    };

    auto buildPluginGroups = [] (vector<zcm::IndexerPlugin*> plugins) {
        vector<vector<PluginRuntimeInfo>> groups;
        vector<zcm::IndexerPlugin*> lastLoop = plugins;
        while (!plugins.empty()) {
            groups.resize(groups.size() + 1);
            for (auto p = plugins.begin(); p != plugins.end();) {
                auto deps = (*p)->dependsOn();

                bool skipUntilLater = false;
                for (auto* dep : plugins) {
                    if (find(deps.begin(), deps.end(), dep->name()) != deps.end()) {
                        skipUntilLater = true;
                        break;
                    }
                }
                for (auto dep : groups.back()) {
                    if (find(deps.begin(), deps.end(), dep.plugin->name()) != deps.end()) {
                        skipUntilLater = true;
                        break;
                    }
                }
                if (!skipUntilLater) {
                    groups.back().push_back({*p, false});
                    p = plugins.erase(p);
                } else {
                    ++p;
                }
            }

            // Check for dependency resolution failure
            if (plugins == lastLoop) {
                cerr << "Unable to resolve all plugin dependencies. "
                        "Plugins left to resolve:" << endl << endl;
                for (auto* p : plugins) {
                    cerr << p->name() << endl
                         << "  Depends on:" << endl;
                    for (auto d : p->dependsOn())
                         cerr << "    " << d << endl;
                    cerr << endl;
                }
                exit(1);
            }
            lastLoop = plugins;
        }
        return groups;
    };

    // We do not own all the memory in here. We only own the default prorgam
    vector<vector<PluginRuntimeInfo>> pluginGroups;
    pluginGroups = buildPluginGroups(plugins);
    if (pluginGroups.size() > 1) {
        cout << "Identified " << pluginGroups.size() << " indexer plugin groups" << endl
             << "Running through log " << pluginGroups.size()
             << " times to satisfy dependencies" << endl;
    }

    zcm::Json::Value index;

    size_t numEvents = 0;
    const zcm::LogEvent* evt;
    for (size_t i = 0; i < pluginGroups.size(); ++i) {
        if (pluginGroups.size() != 1) cout << "Plugin group " << (i + 1) << endl;
        off_t offset = 0;
        fseeko(log.getFilePtr(), 0, SEEK_SET);

        for (auto& p : pluginGroups[i])
            p.runThroughLog = p.plugin->setUp(index, index[p.plugin->name()], log);

        while (1) {
            offset = ftello(log.getFilePtr());

            static int lastPrintPercent = 0;
            int percent = (100.0 * offset / logSize) * 100;
            if (percent != lastPrintPercent) {
                cout << "\r" << "Percent Complete: " << (percent / 100) << flush;
                lastPrintPercent = percent;
            }

            evt = log.readNextEvent();
            if (evt == nullptr) break;

            int64_t msg_hash;
            __int64_t_decode_array(evt->data, 0, 8, &msg_hash, 1);
            const TypeMetadata* md = types.getByHash(msg_hash);
            if (!md) continue;

            for (auto& p : pluginGroups[i]) {
                assert(p.plugin);

                if (!p.runThroughLog) continue;

                p.plugin->indexEvent(index, index[p.plugin->name()],
                                     evt->channel, md->name,
                                     offset, evt->timestamp,
                                     (uint64_t) msg_hash,
                                     evt->data, evt->datalen);

                numEvents++;
            }
        }

        cout << endl;

        for (auto& p : pluginGroups[i])
            p.plugin->tearDown(index, index[p.plugin->name()], log);
    }

    delete defaultPlugin;
    defaultPlugin = nullptr;

    zcm::Json::StreamWriterBuilder builder;
    builder["indentation"] = args.readable ? "    " : "";
    std::unique_ptr<zcm::Json::StreamWriter> writer(builder.newStreamWriter());
    writer->write(index, &output);
    output << endl;
    output.close();

    cout << "Indexed " << numEvents << " events" << endl;
    return 0;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/scominfo/p9_scominfo.H $           */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_scominfo.H
/// @brief P9 chip unit SCOM address platform translation code
///
/// HWP HWP Owner: jmcgill@us.ibm.com
/// HWP FW Owner: dcrowell@us.ibm.com
/// HWP Team: Infrastructure
/// HWP Level: 1
/// HWP Consumed by: FSP/HB
///

#ifndef P9_SCOMINFO_H
#define P9_SCOMINFO_H

// includes
#include <stdint.h>
#include <vector>
#include "p9_cu.H"

extern "C"
{
    typedef enum
    {
        STANDARD_MODE = 0
    } p9TranslationMode_t;

    typedef enum
    {
        FAILED_TRANSLATION = 0xFFFFFFFFFFFFFFF1ull
    } p9TranslationResult_t;

    /// @brief Creates the actual SCOM address based on the chip unit type, instance, and the input SCOM address (relative to chip unit instance 0)
    /// @param[in] i_p9CU Enumeration of the chip unit type
    /// @param[in] i_chipUnitNum Instance number of the chip unit
    /// @param[in] i_scomAddr The input SCOM address associated with the chip unit type
    /// @param[in] i_mode Used for special purposes, default to 0
    /// @retval uint64_t Actual SCOM address for the chip unit instance passed in
    uint64_t p9_scominfo_createChipUnitScomAddr(const p9ChipUnits_t i_p9CU, const uint8_t i_chipUnitNum,
            const uint64_t i_scomAddr, const uint32_t i_mode = 0);

    /// @brief Determine if the provided SCOM address correlates to any chip units (if so creates a list of chipUnitPairing structures which correspond)
    /// @param[in] i_scomAddr SCOM address to be tested
    /// @param[out] o_chipUnitRelated Returns true if SCOM address is associated with any chip units
    /// @param[out] o_chipUnitPairing Collection of chipUnitPairing enums
    /// @param[in] i_mode Used for special purposes, default to 0
    /// @retval uint32_t Return non-zero for error
    uint32_t p9_scominfo_isChipUnitScom(const uint64_t i_scomAddr, bool& o_chipUnitRelated,
                                        std::vector<p9_chipUnitPairing_t>& o_chipUnitPairing, const uint32_t i_mode = 0);

} // extern "C"

#endif /* P9_SCOMINFO_H */
<commit_msg>Various updates.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/scominfo/p9_scominfo.H $           */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_scominfo.H
/// @brief P9 chip unit SCOM address platform translation code
///
/// HWP HWP Owner: jmcgill@us.ibm.com
/// HWP FW Owner: dcrowell@us.ibm.com
/// HWP Team: Infrastructure
/// HWP Level: 1
/// HWP Consumed by: FSP/HB
///

#ifndef P9_SCOMINFO_H
#define P9_SCOMINFO_H

// includes
#include <stdint.h>
#include <vector>
#include "p9_cu.H"

extern "C"
{

    static const uint32_t PPE_MODE = 1;

    typedef enum
    {
        STANDARD_MODE = 0
    } p9TranslationMode_t;

    typedef enum
    {
        FAILED_TRANSLATION = 0xFFFFFFFFFFFFFFF1ull
    } p9TranslationResult_t;

    /// @brief Creates the actual SCOM address based on the chip unit type, instance, and the input SCOM address (relative to chip unit instance 0)
    /// @param[in] i_p9CU Enumeration of the chip unit type
    /// @param[in] i_chipUnitNum Instance number of the chip unit
    /// @param[in] i_scomAddr The input SCOM address associated with the chip unit type
    /// @param[in] i_mode Used for special purposes, default to 0
    /// @retval uint64_t Actual SCOM address for the chip unit instance passed in
    uint64_t p9_scominfo_createChipUnitScomAddr(const p9ChipUnits_t i_p9CU, const uint8_t i_chipUnitNum,
            const uint64_t i_scomAddr, const uint32_t i_mode = 0);

    /// @brief Determine if the provided SCOM address correlates to any chip units (if so creates a list of chipUnitPairing structures which correspond)
    /// @param[in] i_scomAddr SCOM address to be tested
    /// @param[out] o_chipUnitRelated Returns true if SCOM address is associated with any chip units
    /// @param[out] o_chipUnitPairing Collection of chipUnitPairing enums
    /// @param[in] i_mode Used for special purposes, default to 0
    /// @retval uint32_t Return non-zero for error
    uint32_t p9_scominfo_isChipUnitScom(const uint64_t i_scomAddr, bool& o_chipUnitRelated,
                                        std::vector<p9_chipUnitPairing_t>& o_chipUnitPairing, const uint32_t i_mode = 0);

} // extern "C"

#endif /* P9_SCOMINFO_H */
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/browser_client.h"

#include "browser/browser_context.h"
#include "browser/browser_main_parts.h"
#include "browser/media/media_capture_devices_dispatcher.h"
#include "browser/notification_presenter.h"

namespace brightray {

namespace {

BrowserClient* g_browser_client;

}

BrowserClient* BrowserClient::Get() {
  return g_browser_client;
}

BrowserClient::BrowserClient()
    : browser_main_parts_() {
  DCHECK(!g_browser_client);
  g_browser_client = this;
}

BrowserClient::~BrowserClient() {
}

BrowserContext* BrowserClient::browser_context() {
  return browser_main_parts_->browser_context();
}

NotificationPresenter* BrowserClient::notification_presenter() {
#if defined(OS_MACOSX)
  if (!notification_presenter_)
    notification_presenter_.reset(NotificationPresenter::Create());
#endif
  return notification_presenter_.get();
}

BrowserMainParts* BrowserClient::OverrideCreateBrowserMainParts(const content::MainFunctionParams&) {
  return new BrowserMainParts;
}

content::BrowserMainParts* BrowserClient::CreateBrowserMainParts(const content::MainFunctionParams& parameters) {
  DCHECK(!browser_main_parts_);
  browser_main_parts_ = OverrideCreateBrowserMainParts(parameters);
  return browser_main_parts_;
}

net::URLRequestContextGetter* BrowserClient::CreateRequestContext(content::BrowserContext* browser_context, content::ProtocolHandlerMap* protocol_handlers) {
  return static_cast<BrowserContext*>(browser_context)->CreateRequestContext(protocol_handlers);
}

void BrowserClient::ShowDesktopNotification(
    const content::ShowDesktopNotificationHostMsgParams& params,
    int render_process_id,
    int render_view_id,
    bool worker) {
  auto presenter = notification_presenter();
  if (!presenter)
    return;
  presenter->ShowNotification(params, render_process_id, render_view_id);
}

void BrowserClient::CancelDesktopNotification(
    int render_process_id,
    int render_view_id,
    int notification_id) {
  auto presenter = notification_presenter();
  if (!presenter)
    return;
  presenter->CancelNotification(render_process_id, render_view_id, notification_id);
}

content::MediaObserver* BrowserClient::GetMediaObserver() {
  return MediaCaptureDevicesDispatcher::GetInstance();
}

}
<commit_msg>Fix cpplint errors in browser_client.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/browser_client.h"

#include "browser/browser_context.h"
#include "browser/browser_main_parts.h"
#include "browser/media/media_capture_devices_dispatcher.h"
#include "browser/notification_presenter.h"

namespace brightray {

namespace {

BrowserClient* g_browser_client;

}

BrowserClient* BrowserClient::Get() {
  return g_browser_client;
}

BrowserClient::BrowserClient()
    : browser_main_parts_() {
  DCHECK(!g_browser_client);
  g_browser_client = this;
}

BrowserClient::~BrowserClient() {
}

BrowserContext* BrowserClient::browser_context() {
  return browser_main_parts_->browser_context();
}

NotificationPresenter* BrowserClient::notification_presenter() {
#if defined(OS_MACOSX)
  if (!notification_presenter_)
    notification_presenter_.reset(NotificationPresenter::Create());
#endif
  return notification_presenter_.get();
}

BrowserMainParts* BrowserClient::OverrideCreateBrowserMainParts(
    const content::MainFunctionParams&) {
  return new BrowserMainParts;
}

content::BrowserMainParts* BrowserClient::CreateBrowserMainParts(
    const content::MainFunctionParams& parameters) {
  DCHECK(!browser_main_parts_);
  browser_main_parts_ = OverrideCreateBrowserMainParts(parameters);
  return browser_main_parts_;
}

net::URLRequestContextGetter* BrowserClient::CreateRequestContext(
    content::BrowserContext* browser_context,
    content::ProtocolHandlerMap* protocol_handlers) {
  auto context = static_cast<BrowserContext*>(browser_context);
  return context->CreateRequestContext(protocol_handlers);
}

void BrowserClient::ShowDesktopNotification(
    const content::ShowDesktopNotificationHostMsgParams& params,
    int render_process_id,
    int render_view_id,
    bool worker) {
  auto presenter = notification_presenter();
  if (!presenter)
    return;
  presenter->ShowNotification(params, render_process_id, render_view_id);
}

void BrowserClient::CancelDesktopNotification(
    int render_process_id,
    int render_view_id,
    int notification_id) {
  auto presenter = notification_presenter();
  if (!presenter)
    return;
  presenter->CancelNotification(
      render_process_id, render_view_id, notification_id);
}

content::MediaObserver* BrowserClient::GetMediaObserver() {
  return MediaCaptureDevicesDispatcher::GetInstance();
}

}  // namespace brightray
<|endoftext|>


<commit_before>#include "Players/Iterative_Deepening_AI.h"

#include <cmath>
#include <chrono>
#include <vector>

#include "Game/Board.h"
#include "Game/Clock.h"
#include "Moves/Move.h"
#include "Players/Game_Tree_Node_Result.h"
#include "Players/Alpha_Beta_Value.h"

#include "Utility/Fixed_Capacity_Vector.h"

std::string Iterative_Deepening_AI::name() const noexcept
{
    return ai_name() + " (Iterative Deepening)";
}

const Move& Iterative_Deepening_AI::choose_move(const Board& board, const Clock& clock) const noexcept
{
    reset_search_stats(board);
    const auto effective_moves_per_turn = branching_factor(game_progress(board));
    const auto time_to_use = time_to_examine(board, clock);
    const auto time_start = std::chrono::steady_clock::now();

    auto principal_variation = std::vector<const Move*>{nullptr, nullptr};
    Game_Tree_Node_Result result;
    for(size_t depth = 1; true; ++depth)
    {
        // alpha = highest score found that opponent will allow
        auto alpha_start = Alpha_Beta_Value{Game_Tree_Node_Result::lose_score,
                                            board.whose_turn(),
                                            0};

        // beta = score that will cause opponent to choose a different prior move
        auto beta_start = Alpha_Beta_Value{Game_Tree_Node_Result::win_score,
                                           board.whose_turn(),
                                           0};

        current_variation_store current_variation;

        result = search_game_tree(board,
                                  Clock::seconds{std::numeric_limits<Clock::seconds::rep>::infinity()},
                                  depth,
                                  depth,
                                  clock,
                                  alpha_start,
                                  beta_start,
                                  principal_variation,
                                  current_variation);

        const auto time_used_so_far = std::chrono::steady_clock::now() - time_start;
        const auto time_left = time_to_use - time_used_so_far;
        if(time_used_so_far*effective_moves_per_turn < time_left)
        {
            principal_variation.resize(2);
            const auto& variation = result.variation_line();
            principal_variation.insert(principal_variation.end(), variation.begin(), variation.end());
        }
        else
        {
            report_final_search_stats(result, board);
            return *result.variation_line().front();
        }
    }
}
<commit_msg>Make sure AI never takes infinite time to choose a move<commit_after>#include "Players/Iterative_Deepening_AI.h"

#include <cmath>
#include <chrono>
#include <vector>

#include "Game/Board.h"
#include "Game/Clock.h"
#include "Moves/Move.h"
#include "Players/Game_Tree_Node_Result.h"
#include "Players/Alpha_Beta_Value.h"

#include "Utility/Fixed_Capacity_Vector.h"

std::string Iterative_Deepening_AI::name() const noexcept
{
    return ai_name() + " (Iterative Deepening)";
}

const Move& Iterative_Deepening_AI::choose_move(const Board& board, const Clock& clock) const noexcept
{
    reset_search_stats(board);
    const auto effective_moves_per_turn = branching_factor(game_progress(board));
    const auto time_to_use = std::min(time_to_examine(board, clock), clock.running_time_left());
    const auto time_start = std::chrono::steady_clock::now();

    auto principal_variation = std::vector<const Move*>{nullptr, nullptr};
    Game_Tree_Node_Result result;
    for(size_t depth = 1; true; ++depth)
    {
        // alpha = highest score found that opponent will allow
        auto alpha_start = Alpha_Beta_Value{Game_Tree_Node_Result::lose_score,
                                            board.whose_turn(),
                                            0};

        // beta = score that will cause opponent to choose a different prior move
        auto beta_start = Alpha_Beta_Value{Game_Tree_Node_Result::win_score,
                                           board.whose_turn(),
                                           0};

        current_variation_store current_variation;

        result = search_game_tree(board,
                                  Clock::seconds{std::numeric_limits<Clock::seconds::rep>::infinity()},
                                  depth,
                                  depth,
                                  clock,
                                  alpha_start,
                                  beta_start,
                                  principal_variation,
                                  current_variation);

        const auto time_used_so_far = std::chrono::steady_clock::now() - time_start;
        const auto time_left = time_to_use - time_used_so_far;
        if(time_used_so_far*effective_moves_per_turn < time_left)
        {
            principal_variation.resize(2);
            const auto& variation = result.variation_line();
            principal_variation.insert(principal_variation.end(), variation.begin(), variation.end());
        }
        else
        {
            report_final_search_stats(result, board);
            return *result.variation_line().front();
        }
    }
}
<|endoftext|>


<commit_before>#include "FOX_OSG_MDIView.h"

#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>

// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
	//________Message_Type_________		___ID___						________Message_Handler________
	FXMAPFUNC(SEL_CHORE,				FOX_OSG_MDIView::ID_CHORE,		FOX_OSG_MDIView::OnIdle)
};

FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))

FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
		FXIcon *ic, FXPopup *pup, FXuint opt,
		FXint x, FXint y, FXint w, FXint h)
		:   FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
	// A visual to drag OpenGL in double-buffered mode; note the glvisual is
	// shared between all windows which need the same depths and numbers of buffers
	// Thus, while the first visual may take some time to initialize, each subsequent
	// window can be created very quickly; we need to determine grpaphics hardware
	// characteristics only once.
	FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);

	m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, NULL, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );

	osgViewer::Viewer *viewer = new osgViewer::Viewer;
	viewer->getCamera()->setGraphicsContext(m_gwFox);
	viewer->getCamera()->setViewport(0,0,w,h);
	viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);

	// load the scene.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg");
	if (!loadedModel)
	{
		return ;
	}

	// add the stats handler
    viewer->addEventHandler(new osgViewer::StatsHandler);

	viewer->setSceneData(loadedModel.get());

	viewer->setCameraManipulator(new osgGA::TrackballManipulator);

	SetViewer(viewer);

	getApp()->addChore(this,ID_CHORE);

}

FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
}

long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
	m_osgViewer->frame();
	getApp()->addChore(this, ID_CHORE);
	return 1;
}

void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
	m_osgViewer = viewer;
}
<commit_msg>Fixed warning<commit_after>#include "FOX_OSG_MDIView.h"

#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>

// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
	//________Message_Type_________		___ID___						________Message_Handler________
	FXMAPFUNC(SEL_CHORE,				FOX_OSG_MDIView::ID_CHORE,		FOX_OSG_MDIView::OnIdle)
};

FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))

FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
		FXIcon *ic, FXPopup *pup, FXuint opt,
		FXint x, FXint y, FXint w, FXint h)
		:   FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
	// A visual to drag OpenGL in double-buffered mode; note the glvisual is
	// shared between all windows which need the same depths and numbers of buffers
	// Thus, while the first visual may take some time to initialize, each subsequent
	// window can be created very quickly; we need to determine grpaphics hardware
	// characteristics only once.
	FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);

	m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );

	osgViewer::Viewer *viewer = new osgViewer::Viewer;
	viewer->getCamera()->setGraphicsContext(m_gwFox);
	viewer->getCamera()->setViewport(0,0,w,h);
	viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);

	// load the scene.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg");
	if (!loadedModel)
	{
		return ;
	}

	// add the stats handler
    viewer->addEventHandler(new osgViewer::StatsHandler);

	viewer->setSceneData(loadedModel.get());

	viewer->setCameraManipulator(new osgGA::TrackballManipulator);

	SetViewer(viewer);

	getApp()->addChore(this,ID_CHORE);

}

FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
}

long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
	m_osgViewer->frame();
	getApp()->addChore(this, ID_CHORE);
	return 1;
}

void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
	m_osgViewer = viewer;
}
<|endoftext|>