<commit_before>/* -------------------------------------------------------------------------- *
 *                         OpenSim:  mainFatigue.cpp                          *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Peter Loan, Ajay Seth, Ayman Habib                              *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

/*
 *  Below is an example of an OpenSim main() routine.
 *  This program is a forward simulation of a tug-of-war between two muscles
 *  pulling on a block. One of the muscles fatigues and the other does not.
 */

//=============================================================================
//=============================================================================
#include <OpenSim/OpenSim.h>
#include "FatigableMuscle.h"
#include <OpenSim/Common/IO.h>
#include "OpenSim/Common/MOTFileAdapter.h"

using namespace OpenSim;
using namespace SimTK;

//_____________________________________________________________________________
/**
 * Run a simulation of a sliding block being pulled by two muscle
 */
int main()
{
    std::clock_t startTime = std::clock();

    try {
        ///////////////////////////////////////////////
        // DEFINE THE SIMULATION START AND END TIMES //
        ///////////////////////////////////////////////
        // Define the initial and final simulation times
        double initialTime = 0.0;
        double finalTime = 10.0;

        ///////////////////////////////////////////
        // DEFINE BODIES AND JOINTS OF THE MODEL //
        ///////////////////////////////////////////
        // Create an OpenSim model and set its name
        Model osimModel;
        osimModel.setName("tugOfWar");

        // GROUND FRAME

        // Get a reference to the model's ground body
        Ground& ground = osimModel.updGround();

        // Add display geometry to the ground to visualize in the GUI
        ground.attachMeshGeometry("ground.vtp");
        ground.attachMeshGeometry("anchor1.vtp");
        ground.attachMeshGeometry("anchor2.vtp");

        // BLOCK BODY

        // Specify properties of a 20 kg, 10cm length block body
        double blockMass = 20.0, blockSideLength = 0.1;
        Vec3 blockMassCenter(0);
        Inertia blockInertia = blockMass*Inertia::brick(blockSideLength,
            blockSideLength, blockSideLength);

        // Create a new block body with the specified properties
        OpenSim::Body *block = new OpenSim::Body("block", blockMass,
            blockMassCenter, blockInertia);

        // Add display geometry to the block to visualize in the GUI
        block->attachMeshGeometry("block.vtp");

        // FREE JOINT

        // Create a new free joint with 6 degrees-of-freedom (coordinates)
        // between the block and ground bodies
        double halfLength = blockSideLength/2.0;
        Vec3 locationInParent(0, halfLength, 0), orientationInParent(0);
        Vec3 locationInBody(0, halfLength, 0), orientationInBody(0);
        FreeJoint *blockToGround = new FreeJoint("blockToGround", ground,
            locationInParent, orientationInParent,
            *block, locationInBody, orientationInBody);

        // Get a reference to the coordinate set (6 degrees-of-freedom)
        // between the block and ground bodies
        CoordinateSet& jointCoordinateSet = blockToGround->upd_CoordinateSet();

        // Set the angle and position ranges for the coordinate set
        double angleRange[2] = {-SimTK::Pi/2, SimTK::Pi/2};
        double positionRange[2] = {-1, 1};
        jointCoordinateSet[0].setRange(angleRange);
        jointCoordinateSet[1].setRange(angleRange);
        jointCoordinateSet[2].setRange(angleRange);
        jointCoordinateSet[3].setRange(positionRange);
        jointCoordinateSet[4].setRange(positionRange);
        jointCoordinateSet[5].setRange(positionRange);

        // Add the block body to the model
        osimModel.addBody(block);
        osimModel.addJoint(blockToGround);

        ///////////////////////////////////////
        // DEFINE FORCES ACTING ON THE MODEL //
        ///////////////////////////////////////
        // MUSCLE FORCES

        // Create two new muscles
        double maxIsometricForce = 1000.0, optimalFiberLength = 0.2,
               tendonSlackLength = 0.1,    pennationAngle = 0.0,
               fatigueFactor = 0.30, recoveryFactor = 0.20;

        // fatigable muscle (Millard2012EquilibriumMuscle with fatigue)
        FatigableMuscle* fatigable = new FatigableMuscle("fatigable",
            maxIsometricForce, optimalFiberLength, tendonSlackLength,
            pennationAngle, fatigueFactor, recoveryFactor);

        // original muscle model (muscle without fatigue)
        Millard2012EquilibriumMuscle* original =
            new Millard2012EquilibriumMuscle("original",
                maxIsometricForce, optimalFiberLength, tendonSlackLength,
                pennationAngle);

        // Define the path of the muscles
        fatigable->addNewPathPoint("fatigable-point1", ground,
            Vec3(0.0, halfLength, -0.35));
        fatigable->addNewPathPoint("fatigable-point2", *block,
            Vec3(0.0, halfLength, -halfLength));

        original->addNewPathPoint("original-point1", ground,
            Vec3(0.0, halfLength, 0.35));
        original->addNewPathPoint("original-point2", *block,
            Vec3(0.0, halfLength, halfLength));

        // Define the default states for the two muscles
        // Activation
        fatigable->setDefaultActivation(0.01);
        original->setDefaultActivation(0.01);
        // Fiber length
        fatigable->setDefaultFiberLength(optimalFiberLength);
        original->setDefaultFiberLength(optimalFiberLength);

        // Add the two muscles (as forces) to the model
        osimModel.addForce(fatigable);
        osimModel.addForce(original);

        ///////////////////////////////////
        // DEFINE CONTROLS FOR THE MODEL //
        ///////////////////////////////////
        // Create a prescribed controller that simply supplies controls as
        // a function of time.
        // For muscles, controls are normalized motor-neuron excitations
        PrescribedController *muscleController = new PrescribedController();
        muscleController->setActuators(osimModel.updActuators());

        // Set the prescribed muscle controller to use the same muscle control function for each muscle
        muscleController->prescribeControlForActuator("fatigable", new Constant(1.0));
        muscleController->prescribeControlForActuator("original", new Constant(1.0));

        // Add the muscle controller to the model
        osimModel.addController(muscleController);

        // Add a Muscle analysis
        MuscleAnalysis* muscAnalysis = new MuscleAnalysis(&osimModel);
        Array<std::string> coords(jointCoordinateSet[5].getName(),1);
        muscAnalysis->setCoordinates(coords);
        muscAnalysis->setComputeMoments(false);
        osimModel.addAnalysis(muscAnalysis);

        // Turn on the visualizer to view the simulation run live.
        osimModel.setUseVisualizer(false);

        //////////////////////////
        // PERFORM A SIMULATION //
        //////////////////////////

        // Initialize the system and get the state
        SimTK::State& si = osimModel.initSystem();

        // Init coords to 0 and lock the rotational degrees of freedom so the block doesn't twist
        CoordinateSet& coordinates = osimModel.updCoordinateSet();
        coordinates[0].setValue(si, 0);
        coordinates[1].setValue(si, 0);
        coordinates[2].setValue(si, 0);
        coordinates[3].setValue(si, 0);
        coordinates[4].setValue(si, 0);
        coordinates[5].setValue(si, 0);
        coordinates[0].setLocked(si, true);
        coordinates[1].setLocked(si, true);
        coordinates[2].setLocked(si, true);
        // Last coordinate (index 5) is the Z translation of the block
        coordinates[4].setLocked(si, true);

        // Compute initial conditions for muscles
        osimModel.equilibrateMuscles(si);

        // Create the integrator, force reporter, and manager for the simulation.
        // Create the integrator
        SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
        integrator.setAccuracy(1.0e-6);

        // Create the force reporter
        ForceReporter* reporter = new ForceReporter(&osimModel);
        osimModel.updAnalysisSet().adoptAndAppend(reporter);
        // Create the manager
        Manager manager(osimModel, integrator);

        // Print out details of the model
        osimModel.printDetailedInfo(si, std::cout);

        // Integrate from initial time to final time
        manager.setInitialTime(initialTime);
        manager.setFinalTime(finalTime);
        std::cout<<"\nIntegrating from "<<initialTime<<" to "<<finalTime<<std::endl;
        manager.integrate(si);

        //////////////////////////////
        // SAVE THE RESULTS TO FILE //
        //////////////////////////////

        // Save the simulation results
        // Save the states
        auto statesTable = manager.getStatesTable();
        MOTFileAdapter::write(statesTable, "TugOfWar_fatigue_states.mot");

        auto forcesTable = reporter->getForcesTable();
        MOTFileAdapter::write(forcesTable, "TugOfWar_fatigue_forces.mot");

        // Save the muscle analysis results
        IO::makeDir("MuscleAnalysisResults");
        muscAnalysis->printResults("fatigue", "MuscleAnalysisResults");

        // Save the OpenSim model to a file
        osimModel.print("tugOfWar_fatigue_model.osim");
    }
    catch (const std::exception& ex)
    {
        std::cout << ex.what() << std::endl;
        return 1;
    }
    catch (...)
    {
        std::cout << "UNRECOGNIZED EXCEPTION" << std::endl;
        return 1;
    }

    std::cout << "main() routine time = " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n";

    std::cout << "OpenSim example completed successfully.\n";
    return 0;
}
<commit_msg>Change names of the files written to match the one in tests.<commit_after>/* -------------------------------------------------------------------------- *
 *                         OpenSim:  mainFatigue.cpp                          *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Peter Loan, Ajay Seth, Ayman Habib                              *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

/*
 *  Below is an example of an OpenSim main() routine.
 *  This program is a forward simulation of a tug-of-war between two muscles
 *  pulling on a block. One of the muscles fatigues and the other does not.
 */

//=============================================================================
//=============================================================================
#include <OpenSim/OpenSim.h>
#include "FatigableMuscle.h"
#include <OpenSim/Common/IO.h>
#include "OpenSim/Common/MOTFileAdapter.h"

using namespace OpenSim;
using namespace SimTK;

//_____________________________________________________________________________
/**
 * Run a simulation of a sliding block being pulled by two muscle
 */
int main()
{
    std::clock_t startTime = std::clock();

    try {
        ///////////////////////////////////////////////
        // DEFINE THE SIMULATION START AND END TIMES //
        ///////////////////////////////////////////////
        // Define the initial and final simulation times
        double initialTime = 0.0;
        double finalTime = 10.0;

        ///////////////////////////////////////////
        // DEFINE BODIES AND JOINTS OF THE MODEL //
        ///////////////////////////////////////////
        // Create an OpenSim model and set its name
        Model osimModel;
        osimModel.setName("tugOfWar");

        // GROUND FRAME

        // Get a reference to the model's ground body
        Ground& ground = osimModel.updGround();

        // Add display geometry to the ground to visualize in the GUI
        ground.attachMeshGeometry("ground.vtp");
        ground.attachMeshGeometry("anchor1.vtp");
        ground.attachMeshGeometry("anchor2.vtp");

        // BLOCK BODY

        // Specify properties of a 20 kg, 10cm length block body
        double blockMass = 20.0, blockSideLength = 0.1;
        Vec3 blockMassCenter(0);
        Inertia blockInertia = blockMass*Inertia::brick(blockSideLength,
            blockSideLength, blockSideLength);

        // Create a new block body with the specified properties
        OpenSim::Body *block = new OpenSim::Body("block", blockMass,
            blockMassCenter, blockInertia);

        // Add display geometry to the block to visualize in the GUI
        block->attachMeshGeometry("block.vtp");

        // FREE JOINT

        // Create a new free joint with 6 degrees-of-freedom (coordinates)
        // between the block and ground bodies
        double halfLength = blockSideLength/2.0;
        Vec3 locationInParent(0, halfLength, 0), orientationInParent(0);
        Vec3 locationInBody(0, halfLength, 0), orientationInBody(0);
        FreeJoint *blockToGround = new FreeJoint("blockToGround", ground,
            locationInParent, orientationInParent,
            *block, locationInBody, orientationInBody);

        // Get a reference to the coordinate set (6 degrees-of-freedom)
        // between the block and ground bodies
        CoordinateSet& jointCoordinateSet = blockToGround->upd_CoordinateSet();

        // Set the angle and position ranges for the coordinate set
        double angleRange[2] = {-SimTK::Pi/2, SimTK::Pi/2};
        double positionRange[2] = {-1, 1};
        jointCoordinateSet[0].setRange(angleRange);
        jointCoordinateSet[1].setRange(angleRange);
        jointCoordinateSet[2].setRange(angleRange);
        jointCoordinateSet[3].setRange(positionRange);
        jointCoordinateSet[4].setRange(positionRange);
        jointCoordinateSet[5].setRange(positionRange);

        // Add the block body to the model
        osimModel.addBody(block);
        osimModel.addJoint(blockToGround);

        ///////////////////////////////////////
        // DEFINE FORCES ACTING ON THE MODEL //
        ///////////////////////////////////////
        // MUSCLE FORCES

        // Create two new muscles
        double maxIsometricForce = 1000.0, optimalFiberLength = 0.2,
               tendonSlackLength = 0.1,    pennationAngle = 0.0,
               fatigueFactor = 0.30, recoveryFactor = 0.20;

        // fatigable muscle (Millard2012EquilibriumMuscle with fatigue)
        FatigableMuscle* fatigable = new FatigableMuscle("fatigable",
            maxIsometricForce, optimalFiberLength, tendonSlackLength,
            pennationAngle, fatigueFactor, recoveryFactor);

        // original muscle model (muscle without fatigue)
        Millard2012EquilibriumMuscle* original =
            new Millard2012EquilibriumMuscle("original",
                maxIsometricForce, optimalFiberLength, tendonSlackLength,
                pennationAngle);

        // Define the path of the muscles
        fatigable->addNewPathPoint("fatigable-point1", ground,
            Vec3(0.0, halfLength, -0.35));
        fatigable->addNewPathPoint("fatigable-point2", *block,
            Vec3(0.0, halfLength, -halfLength));

        original->addNewPathPoint("original-point1", ground,
            Vec3(0.0, halfLength, 0.35));
        original->addNewPathPoint("original-point2", *block,
            Vec3(0.0, halfLength, halfLength));

        // Define the default states for the two muscles
        // Activation
        fatigable->setDefaultActivation(0.01);
        original->setDefaultActivation(0.01);
        // Fiber length
        fatigable->setDefaultFiberLength(optimalFiberLength);
        original->setDefaultFiberLength(optimalFiberLength);

        // Add the two muscles (as forces) to the model
        osimModel.addForce(fatigable);
        osimModel.addForce(original);

        ///////////////////////////////////
        // DEFINE CONTROLS FOR THE MODEL //
        ///////////////////////////////////
        // Create a prescribed controller that simply supplies controls as
        // a function of time.
        // For muscles, controls are normalized motor-neuron excitations
        PrescribedController *muscleController = new PrescribedController();
        muscleController->setActuators(osimModel.updActuators());

        // Set the prescribed muscle controller to use the same muscle control function for each muscle
        muscleController->prescribeControlForActuator("fatigable", new Constant(1.0));
        muscleController->prescribeControlForActuator("original", new Constant(1.0));

        // Add the muscle controller to the model
        osimModel.addController(muscleController);

        // Add a Muscle analysis
        MuscleAnalysis* muscAnalysis = new MuscleAnalysis(&osimModel);
        Array<std::string> coords(jointCoordinateSet[5].getName(),1);
        muscAnalysis->setCoordinates(coords);
        muscAnalysis->setComputeMoments(false);
        osimModel.addAnalysis(muscAnalysis);

        // Turn on the visualizer to view the simulation run live.
        osimModel.setUseVisualizer(false);

        //////////////////////////
        // PERFORM A SIMULATION //
        //////////////////////////

        // Initialize the system and get the state
        SimTK::State& si = osimModel.initSystem();

        // Init coords to 0 and lock the rotational degrees of freedom so the block doesn't twist
        CoordinateSet& coordinates = osimModel.updCoordinateSet();
        coordinates[0].setValue(si, 0);
        coordinates[1].setValue(si, 0);
        coordinates[2].setValue(si, 0);
        coordinates[3].setValue(si, 0);
        coordinates[4].setValue(si, 0);
        coordinates[5].setValue(si, 0);
        coordinates[0].setLocked(si, true);
        coordinates[1].setLocked(si, true);
        coordinates[2].setLocked(si, true);
        // Last coordinate (index 5) is the Z translation of the block
        coordinates[4].setLocked(si, true);

        // Compute initial conditions for muscles
        osimModel.equilibrateMuscles(si);

        // Create the integrator, force reporter, and manager for the simulation.
        // Create the integrator
        SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
        integrator.setAccuracy(1.0e-6);

        // Create the force reporter
        ForceReporter* reporter = new ForceReporter(&osimModel);
        osimModel.updAnalysisSet().adoptAndAppend(reporter);
        // Create the manager
        Manager manager(osimModel, integrator);

        // Print out details of the model
        osimModel.printDetailedInfo(si, std::cout);

        // Integrate from initial time to final time
        manager.setInitialTime(initialTime);
        manager.setFinalTime(finalTime);
        std::cout<<"\nIntegrating from "<<initialTime<<" to "<<finalTime<<std::endl;
        manager.integrate(si);

        //////////////////////////////
        // SAVE THE RESULTS TO FILE //
        //////////////////////////////

        // Save the simulation results
        // Save the states
        auto statesTable = manager.getStatesTable();
        MOTFileAdapter::write(statesTable, "tugOfWar_fatigue_states.mot");

        auto forcesTable = reporter->getForcesTable();
        MOTFileAdapter::write(forcesTable, "tugOfWar_fatigue_forces.mot");

        // Save the muscle analysis results
        IO::makeDir("MuscleAnalysisResults");
        muscAnalysis->printResults("fatigue", "MuscleAnalysisResults");

        // Save the OpenSim model to a file
        osimModel.print("tugOfWar_fatigue_model.osim");
    }
    catch (const std::exception& ex)
    {
        std::cout << ex.what() << std::endl;
        return 1;
    }
    catch (...)
    {
        std::cout << "UNRECOGNIZED EXCEPTION" << std::endl;
        return 1;
    }

    std::cout << "main() routine time = " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n";

    std::cout << "OpenSim example completed successfully.\n";
    return 0;
}
<|endoftext|>


<commit_before>//
// Created by Sam on 9/25/2017.
//

#include <utility>

#include "../../../include/Game/Core/Player.h"
#include "../../../include/Game/Core/Board.h"
#include "../../../include/Network/Client.h"

void Player::playCard(const json& rawJSON)
{

}

Player::Player(std::shared_ptr<Client> client)
        : client(client),
          name(client->name),
          availableMana(1,1,1,1,1,1),
          totalMana(1,1,1,1,1,1)
{
    board = std::make_shared<Board>();
}

Player::~Player()
= default;
<commit_msg>Added a message in the playCard function on the player object for testing<commit_after>//
// Created by Sam on 9/25/2017.
//

#include <utility>
#include <iostream>

#include "../../../include/Game/Core/Player.h"
#include "../../../include/Game/Core/Board.h"
#include "../../../include/Network/Client.h"

void Player::playCard(const json& rawJSON)
{
    std::cout << "Hello from player class" << std::endl;
}

Player::Player(std::shared_ptr<Client> client)
        : client(client),
          name(client->name),
          availableMana(1,1,1,1,1,1),
          totalMana(1,1,1,1,1,1)
{
    board = std::make_shared<Board>();
}

Player::~Player()
= default;
<|endoftext|>


<commit_before>#include "GraphicsPipeline.hpp"

#include <iostream>
#include "default.vert.spv.hpp"
#include "default.geom.spv.hpp"
#include "default.frag.spv.hpp"

GraphicsPipeline::GraphicsPipeline(VkDevice device, VkExtent2D swapChainExtent, VkRenderPass renderPass) : vertexShader(DEFAULT_VERT_SPV, DEFAULT_VERT_SPV_LENGTH, device), geometryShader(DEFAULT_GEOM_SPV, DEFAULT_GEOM_SPV_LENGTH, device), fragmentShader(DEFAULT_FRAG_SPV, DEFAULT_FRAG_SPV_LENGTH, device) {
    this->device = device;

    // Create shader stages.
    VkPipelineShaderStageCreateInfo vertexShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_VERTEX_BIT, vertexShader.getModule());
    VkPipelineShaderStageCreateInfo geometryShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_GEOMETRY_BIT, geometryShader.getModule());
    VkPipelineShaderStageCreateInfo fragmentShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_FRAGMENT_BIT, fragmentShader.getModule());

    VkPipelineShaderStageCreateInfo shaderStages[] = {vertexShaderStageCreateInfo, geometryShaderStageCreateInfo, fragmentShaderStageCreateInfo};

    // Vertex input.
    VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
    vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    vertexInputInfo.vertexBindingDescriptionCount = 0;
    vertexInputInfo.pVertexBindingDescriptions = nullptr;
    vertexInputInfo.vertexAttributeDescriptionCount = 0;
    vertexInputInfo.pVertexAttributeDescriptions = nullptr;

    // Input assembly.
    VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
    inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
    inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
    inputAssembly.primitiveRestartEnable = VK_FALSE;

    // Viewport.
    VkViewport viewport = {};
    viewport.x = 0.0f;
    viewport.y = 0.0f;
    viewport.width = swapChainExtent.width;
    viewport.height = swapChainExtent.height;
    viewport.minDepth = 0.0f;
    viewport.maxDepth = 1.0f;

    // Scissor.
    VkRect2D scissor = {};
    scissor.offset = {0, 0};
    scissor.extent = swapChainExtent;

    // Viewport state info.
    VkPipelineViewportStateCreateInfo viewportState = {};
    viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
    viewportState.viewportCount = 1;
    viewportState.pViewports = &viewport;
    viewportState.scissorCount = 1;
    viewportState.pScissors = &scissor;

    // Rasterizer.
    VkPipelineRasterizationStateCreateInfo rasterizer = {};
    rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
    rasterizer.depthClampEnable = VK_FALSE;
    rasterizer.rasterizerDiscardEnable = VK_FALSE;
    rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
    rasterizer.lineWidth = 1.0f;
    rasterizer.cullMode = VK_CULL_MODE_NONE;
    rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
    rasterizer.depthBiasEnable = VK_FALSE;

    // Multisampling.
    VkPipelineMultisampleStateCreateInfo multisampling = {};
    multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
    multisampling.sampleShadingEnable = VK_FALSE;
    multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;

    // Depth.
    VkPipelineDepthStencilStateCreateInfo depthStencil = {};
    depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
    depthStencil.depthTestEnable = VK_FALSE;
    depthStencil.depthWriteEnable = VK_FALSE;
    depthStencil.depthBoundsTestEnable = VK_FALSE;
    depthStencil.minDepthBounds = 0.0f;
    depthStencil.maxDepthBounds = 1.0f;
    depthStencil.stencilTestEnable = VK_FALSE;

    // Color blending.
    VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
    colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
    colorBlendAttachment.blendEnable = VK_FALSE;

    VkPipelineColorBlendStateCreateInfo colorBlending = {};
    colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    colorBlending.logicOpEnable = VK_FALSE;
    colorBlending.attachmentCount = 1;
    colorBlending.pAttachments = &colorBlendAttachment;

    // Descriptor set layout.
    createDescriptorSetLayouts();

    // Pipeline layout.
    VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
    pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
    pipelineLayoutInfo.setLayoutCount = descriptorSetLayouts.size();
    pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data();

    if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline layout." << std::endl;
        exit(-1);
    }

    // Create pipeline.
    VkGraphicsPipelineCreateInfo pipelineInfo = {};
    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineInfo.stageCount = 3;
    pipelineInfo.pStages = shaderStages;
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    pipelineInfo.pDepthStencilState = &depthStencil;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.pDynamicState = nullptr;
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.renderPass = renderPass;
    pipelineInfo.subpass = 0;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

    if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline." << std::endl;
        exit(-1);
    }
}

GraphicsPipeline::~GraphicsPipeline() {
    vkDestroyPipeline(device, pipeline, nullptr);
    vkDestroyPipelineLayout(device, pipelineLayout, nullptr);

    for (VkDescriptorSetLayout layout : descriptorSetLayouts)
        vkDestroyDescriptorSetLayout(device, layout, nullptr);
}

VkPipeline GraphicsPipeline::getPipeline() const {
    return pipeline;
}

VkPipelineLayout GraphicsPipeline::getPipelineLayout() const {
    return pipelineLayout;
}

VkPipelineShaderStageCreateInfo GraphicsPipeline::createShaderStage(VkShaderStageFlagBits flags, VkShaderModule module) {
    VkPipelineShaderStageCreateInfo createInfo = {};
    createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    createInfo.stage = flags;
    createInfo.module = module;
    createInfo.pName = "main";

    return createInfo;
}

void GraphicsPipeline::createDescriptorSetLayouts() {
    VkDescriptorSetLayout layout;

    // Camera uniform buffer.
    VkDescriptorSetLayoutBinding layoutBinding = {};
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_GEOMETRY_BIT;

    VkDescriptorSetLayoutCreateInfo layoutInfo = {};
    layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
    layoutInfo.bindingCount = 1;
    layoutInfo.pBindings = &layoutBinding;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);
}
<commit_msg>Sampler descriptor layout<commit_after>#include "GraphicsPipeline.hpp"

#include <iostream>
#include "default.vert.spv.hpp"
#include "default.geom.spv.hpp"
#include "default.frag.spv.hpp"

GraphicsPipeline::GraphicsPipeline(VkDevice device, VkExtent2D swapChainExtent, VkRenderPass renderPass) : vertexShader(DEFAULT_VERT_SPV, DEFAULT_VERT_SPV_LENGTH, device), geometryShader(DEFAULT_GEOM_SPV, DEFAULT_GEOM_SPV_LENGTH, device), fragmentShader(DEFAULT_FRAG_SPV, DEFAULT_FRAG_SPV_LENGTH, device) {
    this->device = device;

    // Create shader stages.
    VkPipelineShaderStageCreateInfo vertexShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_VERTEX_BIT, vertexShader.getModule());
    VkPipelineShaderStageCreateInfo geometryShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_GEOMETRY_BIT, geometryShader.getModule());
    VkPipelineShaderStageCreateInfo fragmentShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_FRAGMENT_BIT, fragmentShader.getModule());

    VkPipelineShaderStageCreateInfo shaderStages[] = {vertexShaderStageCreateInfo, geometryShaderStageCreateInfo, fragmentShaderStageCreateInfo};

    // Vertex input.
    VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
    vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    vertexInputInfo.vertexBindingDescriptionCount = 0;
    vertexInputInfo.pVertexBindingDescriptions = nullptr;
    vertexInputInfo.vertexAttributeDescriptionCount = 0;
    vertexInputInfo.pVertexAttributeDescriptions = nullptr;

    // Input assembly.
    VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
    inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
    inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
    inputAssembly.primitiveRestartEnable = VK_FALSE;

    // Viewport.
    VkViewport viewport = {};
    viewport.x = 0.0f;
    viewport.y = 0.0f;
    viewport.width = swapChainExtent.width;
    viewport.height = swapChainExtent.height;
    viewport.minDepth = 0.0f;
    viewport.maxDepth = 1.0f;

    // Scissor.
    VkRect2D scissor = {};
    scissor.offset = {0, 0};
    scissor.extent = swapChainExtent;

    // Viewport state info.
    VkPipelineViewportStateCreateInfo viewportState = {};
    viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
    viewportState.viewportCount = 1;
    viewportState.pViewports = &viewport;
    viewportState.scissorCount = 1;
    viewportState.pScissors = &scissor;

    // Rasterizer.
    VkPipelineRasterizationStateCreateInfo rasterizer = {};
    rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
    rasterizer.depthClampEnable = VK_FALSE;
    rasterizer.rasterizerDiscardEnable = VK_FALSE;
    rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
    rasterizer.lineWidth = 1.0f;
    rasterizer.cullMode = VK_CULL_MODE_NONE;
    rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
    rasterizer.depthBiasEnable = VK_FALSE;

    // Multisampling.
    VkPipelineMultisampleStateCreateInfo multisampling = {};
    multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
    multisampling.sampleShadingEnable = VK_FALSE;
    multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;

    // Depth.
    VkPipelineDepthStencilStateCreateInfo depthStencil = {};
    depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
    depthStencil.depthTestEnable = VK_FALSE;
    depthStencil.depthWriteEnable = VK_FALSE;
    depthStencil.depthBoundsTestEnable = VK_FALSE;
    depthStencil.minDepthBounds = 0.0f;
    depthStencil.maxDepthBounds = 1.0f;
    depthStencil.stencilTestEnable = VK_FALSE;

    // Color blending.
    VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
    colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
    colorBlendAttachment.blendEnable = VK_FALSE;

    VkPipelineColorBlendStateCreateInfo colorBlending = {};
    colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    colorBlending.logicOpEnable = VK_FALSE;
    colorBlending.attachmentCount = 1;
    colorBlending.pAttachments = &colorBlendAttachment;

    // Descriptor set layout.
    createDescriptorSetLayouts();

    // Pipeline layout.
    VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
    pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
    pipelineLayoutInfo.setLayoutCount = descriptorSetLayouts.size();
    pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data();

    if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline layout." << std::endl;
        exit(-1);
    }

    // Create pipeline.
    VkGraphicsPipelineCreateInfo pipelineInfo = {};
    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineInfo.stageCount = 3;
    pipelineInfo.pStages = shaderStages;
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    pipelineInfo.pDepthStencilState = &depthStencil;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.pDynamicState = nullptr;
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.renderPass = renderPass;
    pipelineInfo.subpass = 0;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

    if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline." << std::endl;
        exit(-1);
    }
}

GraphicsPipeline::~GraphicsPipeline() {
    vkDestroyPipeline(device, pipeline, nullptr);
    vkDestroyPipelineLayout(device, pipelineLayout, nullptr);

    for (VkDescriptorSetLayout layout : descriptorSetLayouts)
        vkDestroyDescriptorSetLayout(device, layout, nullptr);
}

VkPipeline GraphicsPipeline::getPipeline() const {
    return pipeline;
}

VkPipelineLayout GraphicsPipeline::getPipelineLayout() const {
    return pipelineLayout;
}

VkPipelineShaderStageCreateInfo GraphicsPipeline::createShaderStage(VkShaderStageFlagBits flags, VkShaderModule module) {
    VkPipelineShaderStageCreateInfo createInfo = {};
    createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    createInfo.stage = flags;
    createInfo.module = module;
    createInfo.pName = "main";

    return createInfo;
}

void GraphicsPipeline::createDescriptorSetLayouts() {
    VkDescriptorSetLayout layout;

    // Camera uniform buffer.
    VkDescriptorSetLayoutBinding layoutBinding = {};
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_GEOMETRY_BIT;

    VkDescriptorSetLayoutCreateInfo layoutInfo = {};
    layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
    layoutInfo.bindingCount = 1;
    layoutInfo.pBindings = &layoutBinding;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);

    // Texture.
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);
}
<|endoftext|>


<commit_before>#include "GraphicsPipeline.hpp"

#include <iostream>
#include "default.vert.spv.hpp"
#include "default.geom.spv.hpp"
#include "default.frag.spv.hpp"

GraphicsPipeline::GraphicsPipeline(VkDevice device, VkExtent2D swapChainExtent, VkRenderPass renderPass) : vertexShader(DEFAULT_VERT_SPV, DEFAULT_VERT_SPV_LENGTH, device), geometryShader(DEFAULT_GEOM_SPV, DEFAULT_GEOM_SPV_LENGTH, device), fragmentShader(DEFAULT_FRAG_SPV, DEFAULT_FRAG_SPV_LENGTH, device) {
    this->device = device;

    // Create shader stages.
    VkPipelineShaderStageCreateInfo vertexShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_VERTEX_BIT, vertexShader.getModule());
    VkPipelineShaderStageCreateInfo geometryShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_GEOMETRY_BIT, geometryShader.getModule());
    VkPipelineShaderStageCreateInfo fragmentShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_FRAGMENT_BIT, fragmentShader.getModule());

    VkPipelineShaderStageCreateInfo shaderStages[] = {vertexShaderStageCreateInfo, geometryShaderStageCreateInfo, fragmentShaderStageCreateInfo};

    // Vertex input.
    VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
    vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    vertexInputInfo.vertexBindingDescriptionCount = 0;
    vertexInputInfo.pVertexBindingDescriptions = nullptr;
    vertexInputInfo.vertexAttributeDescriptionCount = 0;
    vertexInputInfo.pVertexAttributeDescriptions = nullptr;

    // Input assembly.
    VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
    inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
    inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
    inputAssembly.primitiveRestartEnable = VK_FALSE;

    // Viewport.
    VkViewport viewport = {};
    viewport.x = 0.0f;
    viewport.y = 0.0f;
    viewport.width = swapChainExtent.width;
    viewport.height = swapChainExtent.height;
    viewport.minDepth = 0.0f;
    viewport.maxDepth = 1.0f;

    // Scissor.
    VkRect2D scissor = {};
    scissor.offset = {0, 0};
    scissor.extent = swapChainExtent;

    // Viewport state info.
    VkPipelineViewportStateCreateInfo viewportState = {};
    viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
    viewportState.viewportCount = 1;
    viewportState.pViewports = &viewport;
    viewportState.scissorCount = 1;
    viewportState.pScissors = &scissor;

    // Rasterizer.
    VkPipelineRasterizationStateCreateInfo rasterizer = {};
    rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
    rasterizer.depthClampEnable = VK_FALSE;
    rasterizer.rasterizerDiscardEnable = VK_FALSE;
    rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
    rasterizer.lineWidth = 1.0f;
    rasterizer.cullMode = VK_CULL_MODE_NONE;
    rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
    rasterizer.depthBiasEnable = VK_FALSE;

    // Multisampling.
    VkPipelineMultisampleStateCreateInfo multisampling = {};
    multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
    multisampling.sampleShadingEnable = VK_FALSE;
    multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;

    // Depth.
    VkPipelineDepthStencilStateCreateInfo depthStencil = {};
    depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
    depthStencil.depthTestEnable = VK_FALSE;
    depthStencil.depthWriteEnable = VK_FALSE;
    depthStencil.depthBoundsTestEnable = VK_FALSE;
    depthStencil.minDepthBounds = 0.0f;
    depthStencil.maxDepthBounds = 1.0f;
    depthStencil.stencilTestEnable = VK_FALSE;

    // Color blending.
    VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
    colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
    colorBlendAttachment.blendEnable = VK_FALSE;

    VkPipelineColorBlendStateCreateInfo colorBlending = {};
    colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    colorBlending.logicOpEnable = VK_FALSE;
    colorBlending.attachmentCount = 1;
    colorBlending.pAttachments = &colorBlendAttachment;

    // Descriptor set layout.
    createDescriptorSetLayouts();

    // Pipeline layout.
    VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
    pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
    pipelineLayoutInfo.setLayoutCount = descriptorSetLayouts.size();
    pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data();

    if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline layout." << std::endl;
        exit(-1);
    }

    // Create pipeline.
    VkGraphicsPipelineCreateInfo pipelineInfo = {};
    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineInfo.stageCount = 3;
    pipelineInfo.pStages = shaderStages;
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    pipelineInfo.pDepthStencilState = &depthStencil;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.pDynamicState = nullptr;
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.renderPass = renderPass;
    pipelineInfo.subpass = 0;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

    if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline." << std::endl;
        exit(-1);
    }
}

GraphicsPipeline::~GraphicsPipeline() {
    vkDestroyPipeline(device, pipeline, nullptr);
    vkDestroyPipelineLayout(device, pipelineLayout, nullptr);

    for (VkDescriptorSetLayout layout : descriptorSetLayouts)
        vkDestroyDescriptorSetLayout(device, layout, nullptr);
}

VkPipeline GraphicsPipeline::getPipeline() const {
    return pipeline;
}

VkPipelineLayout GraphicsPipeline::getPipelineLayout() const {
    return pipelineLayout;
}

VkPipelineShaderStageCreateInfo GraphicsPipeline::createShaderStage(VkShaderStageFlagBits flags, VkShaderModule module) {
    VkPipelineShaderStageCreateInfo createInfo = {};
    createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    createInfo.stage = flags;
    createInfo.module = module;
    createInfo.pName = "main";

    return createInfo;
}

void GraphicsPipeline::createDescriptorSetLayouts() {
    VkDescriptorSetLayout layout;

    // Camera uniform buffer.
    VkDescriptorSetLayoutBinding layoutBinding = {};
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_GEOMETRY_BIT;

    VkDescriptorSetLayoutCreateInfo layoutInfo = {};
    layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
    layoutInfo.bindingCount = 1;
    layoutInfo.pBindings = &layoutBinding;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);

    // Texture.
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);
}
<commit_msg>Blending<commit_after>#include "GraphicsPipeline.hpp"

#include <iostream>
#include "default.vert.spv.hpp"
#include "default.geom.spv.hpp"
#include "default.frag.spv.hpp"

GraphicsPipeline::GraphicsPipeline(VkDevice device, VkExtent2D swapChainExtent, VkRenderPass renderPass) : vertexShader(DEFAULT_VERT_SPV, DEFAULT_VERT_SPV_LENGTH, device), geometryShader(DEFAULT_GEOM_SPV, DEFAULT_GEOM_SPV_LENGTH, device), fragmentShader(DEFAULT_FRAG_SPV, DEFAULT_FRAG_SPV_LENGTH, device) {
    this->device = device;

    // Create shader stages.
    VkPipelineShaderStageCreateInfo vertexShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_VERTEX_BIT, vertexShader.getModule());
    VkPipelineShaderStageCreateInfo geometryShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_GEOMETRY_BIT, geometryShader.getModule());
    VkPipelineShaderStageCreateInfo fragmentShaderStageCreateInfo = createShaderStage(VK_SHADER_STAGE_FRAGMENT_BIT, fragmentShader.getModule());

    VkPipelineShaderStageCreateInfo shaderStages[] = {vertexShaderStageCreateInfo, geometryShaderStageCreateInfo, fragmentShaderStageCreateInfo};

    // Vertex input.
    VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
    vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    vertexInputInfo.vertexBindingDescriptionCount = 0;
    vertexInputInfo.pVertexBindingDescriptions = nullptr;
    vertexInputInfo.vertexAttributeDescriptionCount = 0;
    vertexInputInfo.pVertexAttributeDescriptions = nullptr;

    // Input assembly.
    VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
    inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
    inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
    inputAssembly.primitiveRestartEnable = VK_FALSE;

    // Viewport.
    VkViewport viewport = {};
    viewport.x = 0.0f;
    viewport.y = 0.0f;
    viewport.width = swapChainExtent.width;
    viewport.height = swapChainExtent.height;
    viewport.minDepth = 0.0f;
    viewport.maxDepth = 1.0f;

    // Scissor.
    VkRect2D scissor = {};
    scissor.offset = {0, 0};
    scissor.extent = swapChainExtent;

    // Viewport state info.
    VkPipelineViewportStateCreateInfo viewportState = {};
    viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
    viewportState.viewportCount = 1;
    viewportState.pViewports = &viewport;
    viewportState.scissorCount = 1;
    viewportState.pScissors = &scissor;

    // Rasterizer.
    VkPipelineRasterizationStateCreateInfo rasterizer = {};
    rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
    rasterizer.depthClampEnable = VK_FALSE;
    rasterizer.rasterizerDiscardEnable = VK_FALSE;
    rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
    rasterizer.lineWidth = 1.0f;
    rasterizer.cullMode = VK_CULL_MODE_NONE;
    rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
    rasterizer.depthBiasEnable = VK_FALSE;

    // Multisampling.
    VkPipelineMultisampleStateCreateInfo multisampling = {};
    multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
    multisampling.sampleShadingEnable = VK_FALSE;
    multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;

    // Depth.
    VkPipelineDepthStencilStateCreateInfo depthStencil = {};
    depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
    depthStencil.depthTestEnable = VK_FALSE;
    depthStencil.depthWriteEnable = VK_FALSE;
    depthStencil.depthBoundsTestEnable = VK_FALSE;
    depthStencil.minDepthBounds = 0.0f;
    depthStencil.maxDepthBounds = 1.0f;
    depthStencil.stencilTestEnable = VK_FALSE;

    // Color blending.
    VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
    colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
    colorBlendAttachment.blendEnable = VK_TRUE;
    colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
    colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
    colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE;
    colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
    colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
    colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE;

    VkPipelineColorBlendStateCreateInfo colorBlending = {};
    colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    colorBlending.logicOpEnable = VK_FALSE;
    colorBlending.attachmentCount = 1;
    colorBlending.pAttachments = &colorBlendAttachment;

    // Descriptor set layout.
    createDescriptorSetLayouts();

    // Pipeline layout.
    VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
    pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
    pipelineLayoutInfo.setLayoutCount = descriptorSetLayouts.size();
    pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data();

    if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline layout." << std::endl;
        exit(-1);
    }

    // Create pipeline.
    VkGraphicsPipelineCreateInfo pipelineInfo = {};
    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineInfo.stageCount = 3;
    pipelineInfo.pStages = shaderStages;
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    pipelineInfo.pDepthStencilState = &depthStencil;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.pDynamicState = nullptr;
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.renderPass = renderPass;
    pipelineInfo.subpass = 0;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

    if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline) != VK_SUCCESS) {
        std::cerr << "Failed to create graphics pipeline." << std::endl;
        exit(-1);
    }
}

GraphicsPipeline::~GraphicsPipeline() {
    vkDestroyPipeline(device, pipeline, nullptr);
    vkDestroyPipelineLayout(device, pipelineLayout, nullptr);

    for (VkDescriptorSetLayout layout : descriptorSetLayouts)
        vkDestroyDescriptorSetLayout(device, layout, nullptr);
}

VkPipeline GraphicsPipeline::getPipeline() const {
    return pipeline;
}

VkPipelineLayout GraphicsPipeline::getPipelineLayout() const {
    return pipelineLayout;
}

VkPipelineShaderStageCreateInfo GraphicsPipeline::createShaderStage(VkShaderStageFlagBits flags, VkShaderModule module) {
    VkPipelineShaderStageCreateInfo createInfo = {};
    createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    createInfo.stage = flags;
    createInfo.module = module;
    createInfo.pName = "main";

    return createInfo;
}

void GraphicsPipeline::createDescriptorSetLayouts() {
    VkDescriptorSetLayout layout;

    // Camera uniform buffer.
    VkDescriptorSetLayoutBinding layoutBinding = {};
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_GEOMETRY_BIT;

    VkDescriptorSetLayoutCreateInfo layoutInfo = {};
    layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
    layoutInfo.bindingCount = 1;
    layoutInfo.pBindings = &layoutBinding;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);

    // Texture.
    layoutBinding.binding = 0;
    layoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
    layoutBinding.descriptorCount = 1;
    layoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;

    if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
        std::cerr << "Failed to create descriptor set layout." << std::endl;
        exit(-1);
    }

    descriptorSetLayouts.push_back(layout);
}
<|endoftext|>


<commit_before>// BrainCloudClient.cpp
// BrainCloudLib
// Copyright 2016 bitHeads, Inc. All Rights Reserved.

#include <cstring>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>

#include "braincloud/BrainCloudClient.h"

#include "braincloud/internal/Device.h"
#include "braincloud/internal/JsonUtil.h"
#include "braincloud/internal/URLRequestMethod.h"

namespace BrainCloud
{
    // Define all static member variables.
    bool BrainCloudClient::EnableSingletonMode = false;
    const char * BrainCloudClient::SingletonUseErrorMessage =
            "Singleton usage is disabled. If called by mistake, use your own variable that holds an instance of the bcWrapper/bcClient.";

    BrainCloudClient * BrainCloudClient::_instance = NULL;
    std::string BrainCloudClient::s_brainCloudClientVersion = "4.4.1";
    const char* BC_SERVER_URL = "https://sharedprod.braincloudservers.com/dispatcherv2";

    /**
     * Constructor
     */
    BrainCloudClient::BrainCloudClient() :
        _brainCloudComms(IBrainCloudComms::create(this)),
        _rttComms(new RTTComms(this)),
        _asyncMatchService(new BrainCloudAsyncMatch(this)),
        _authenticationService(new BrainCloudAuthentication(this)),
        _chatService(new BrainCloudChat(this)),
        _dataStreamService(new BrainCloudDataStream(this)),
        _entityService(new BrainCloudEntity(this)),
        _eventService(new BrainCloudEvent(this)),
        _fileService(new BrainCloudFile(this)),
        _globalFileService(new BrainCloudGlobalFile(this)),
        _friendService(new BrainCloudFriend(this)),
        _gamificationService(new BrainCloudGamification(this)),
        _globalAppService(new BrainCloudGlobalApp(this)),
        _globalEntityService(new BrainCloudGlobalEntity(this)),
        _globalStatisticsService(new BrainCloudGlobalStatistics(this)),
        _groupService(new BrainCloudGroup(this)),
        _identityService(new BrainCloudIdentity(this)),
        _lobbyService(new BrainCloudLobby(this)),
        _mailService(new BrainCloudMail(this)),
        _matchmakingService(new BrainCloudMatchmaking(this)),
        _messagingService(new BrainCloudMessaging(this)),
        _oneWayMatchService(new BrainCloudOneWayMatch(this)),
        _playbackStreamService(new BrainCloudPlaybackStream(this)),
        _playerStateService(new BrainCloudPlayerState(this)),
        _playerStatisticsService(new BrainCloudPlayerStatistics(this)),
        _playerStatisticsEventService(new BrainCloudPlayerStatisticsEvent(this)),
        _presenceService(new BrainCloudPresence(this)),
        _productService(new BrainCloudProduct(this)),
        _virtualCurrencyService(new BrainCloudVirtualCurrency(this)),
        _appStoreService(new BrainCloudAppStore(this)),
        _profanityService(new BrainCloudProfanity(this)),
        _pushNotificationService(new BrainCloudPushNotification(this)),
        _redemptionCodeService(new BrainCloudRedemptionCode(this)),
        _s3HandlingService(new BrainCloudS3Handling(this)),
        _scriptService(new BrainCloudScript(this)),
        _socialLeaderboardService(new BrainCloudSocialLeaderboard(this)),
        _steamService(new BrainCloudSteam(this)),
        _timeService(new BrainCloudTime(this)),
        _tournamentService(new BrainCloudTournament(this)),
        _customEntityService(new BrainCloudCustomEntity(this)),
        _itemCatalogService(new BrainCloudItemCatalog(this)),
        _userItemsService(new BrainCloudUserItems(this)),
        _releasePlatform(""),
        _appVersion(""),
        _timezoneOffset(0.0)
    {
        //needed this here otherwise out of scope compiler error
        _rttService = new BrainCloudRTT(_rttComms, this);
    }

    BrainCloudClient::~BrainCloudClient()
    {
        delete _rttService;
        delete _tournamentService;
        delete _customEntityService;
        delete _itemCatalogService;
        delete _timeService;
        delete _steamService;
        delete _socialLeaderboardService;
        delete _scriptService;
        delete _s3HandlingService;
        delete _redemptionCodeService;
        delete _pushNotificationService;
        delete _profanityService;
        delete _appStoreService;
        delete _virtualCurrencyService;
        delete _productService;
        delete _presenceService;
        delete _playerStatisticsEventService;
        delete _playerStatisticsService;
        delete _playerStateService;
        delete _playbackStreamService;
        delete _oneWayMatchService;
        delete _messagingService;
        delete _matchmakingService;
        delete _mailService;
        delete _lobbyService;
        delete _identityService;
        delete _groupService;
        delete _globalStatisticsService;
        delete _globalEntityService;
        delete _globalAppService;
        delete _gamificationService;
        delete _friendService;
        delete _fileService;
        delete _globalFileService;
        delete _eventService;
        delete _entityService;
        delete _dataStreamService;
        delete _chatService;
        delete _authenticationService;
        delete _asyncMatchService;
        delete _rttComms;
        delete _brainCloudComms;
    }

    ////////////////////////////////////////////////////
    // Public Methods
    ////////////////////////////////////////////////////

    const char * BrainCloudClient::getSessionId() const {
        return(_brainCloudComms->getSessionId().c_str());
    }

    const char * BrainCloudClient::getRttConnectionId() const{
        return(_rttComms->getConnectionId().c_str());
    }

    void BrainCloudClient::initializeComms(const char * in_serverURL, const char * in_appId, const std::map<std::string, std::string>& in_secretMap)
    {
        if (_brainCloudComms)
        {
            // automatically upgrade any older clients using "dispatcher" url
            // to "dispatcherv2" endpoint. Comms supports this now and otherwise
            // the change is transparent to the client.
            const char * urlToUse = in_serverURL;
            std::string url = in_serverURL;
            if (url.find("dispatcherv2") == std::string::npos)
            {
                size_t index = url.find("dispatcher");
                if (index != std::string::npos)
                {
                    url = url.substr(0, index);
                    url += "dispatcherv2";
                    urlToUse = url.c_str();
                }
            }
            _brainCloudComms->initializeWithApps(urlToUse, in_appId, in_secretMap);
        }

        if (_rttComms)
        {
            _rttComms->initialize();
        }
    }

    void BrainCloudClient::initialize(const char * in_serverURL, const char * in_secretKey, const char * in_appId, const char * in_appVersion)
    {
        std::string error = "";
        if (in_serverURL == NULL || strlen(in_serverURL) <= 0)
            error = "serverURL was null or empty";
        else if (in_secretKey == NULL || strlen(in_secretKey) <= 0)
            error = "secretKey was null or empty";
        else if (in_appId == NULL || strlen(in_appId) <= 0)
            error = "appId was null or empty";
        else if (in_appVersion == NULL || strlen(in_appVersion) <= 0)
            error = "appVersion was null or empty";

        if (error.length() > 0)
        {
            std::cout << "ERROR | Failed to initialize brainCloud - " << error;
            return;
        }

        std::map<std::string, std::string> secretMap;
        secretMap[in_appId] = in_secretKey;

        initializeComms(in_serverURL, in_appId, secretMap);
        setupOSLocaleData();

        _releasePlatform = Device::getPlatformName();
        _appVersion = in_appVersion;
    }

    void BrainCloudClient::initialize(const char * in_secretKey, const char * in_appId, const char * in_appVersion)
    {
        initialize(BC_SERVER_URL, in_secretKey, in_appId, in_appVersion);
    }

    void BrainCloudClient::initializeWithApps(const char * in_serverURL, const char * in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char * in_appVersion)
    {
        std::string error = "";
        if (in_serverURL == NULL || strlen(in_serverURL) <= 0)
            error = "serverURL was null or empty";
        else if (in_defaultAppId == NULL || strlen(in_defaultAppId) <= 0)
            error = "appId was null or empty";
        else if (in_appVersion == NULL || strlen(in_appVersion) <= 0)
            error = "appVersion was null or empty";
        else if (in_secretMap.find(in_defaultAppId) == in_secretMap.end())
            error = "not secretKey match for appid";

        if (error.length() > 0)
        {
            std::cout << "ERROR | Failed to initialize brainCloud - " << error;
            return;
        }

        initializeComms(in_serverURL, in_defaultAppId, in_secretMap);
        setupOSLocaleData();

        _releasePlatform = Device::getPlatformName();
        _appVersion = in_appVersion;
    }

    void BrainCloudClient::initializeWithApps(const char* in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char* in_appVersion)
    {
        initializeWithApps(BC_SERVER_URL, in_defaultAppId, in_secretMap, in_appVersion);
    }

    void BrainCloudClient::initializeIdentity(const char * in_profileId, const char * in_anonymousId)
    {
        _authenticationService->initialize(in_profileId, in_anonymousId);
    }

    void BrainCloudClient::runCallbacks()
    {
        _brainCloudComms->runCallbacks();
        _lobbyService->runPingCallbacks();
        _rttComms->runCallbacks();
    }

    void BrainCloudClient::registerEventCallback(IEventCallback *in_eventCallback)
    {
        _brainCloudComms->registerEventCallback(in_eventCallback);
    }

    void BrainCloudClient::deregisterEventCallback()
    {
        _brainCloudComms->deregisterEventCallback();
    }

    void BrainCloudClient::registerRewardCallback(IRewardCallback *in_rewardCallback)
    {
        _brainCloudComms->registerRewardCallback(in_rewardCallback);
    }

    void BrainCloudClient::deregisterRewardCallback()
    {
        _brainCloudComms->deregisterRewardCallback();
    }

    void BrainCloudClient::registerFileUploadCallback(IFileUploadCallback * in_fileUploadCallback)
    {
        _brainCloudComms->registerFileUploadCallback(in_fileUploadCallback);
    }

    void BrainCloudClient::deregisterFileUploadCallback()
    {
        _brainCloudComms->deregisterFileUploadCallback();
    }

    void BrainCloudClient::registerGlobalErrorCallback(IGlobalErrorCallback * in_globalErrorCallback)
    {
        _brainCloudComms->registerGlobalErrorCallback(in_globalErrorCallback);
    }

    void BrainCloudClient::deregisterGlobalErrorCallback()
    {
        _brainCloudComms->deregisterGlobalErrorCallback();
    }

    void BrainCloudClient::registerNetworkErrorCallback(INetworkErrorCallback * in_networkErrorCallback)
    {
        _brainCloudComms->registerNetworkErrorCallback(in_networkErrorCallback);
    }

    void BrainCloudClient::deregisterNetworkErrorCallback()
    {
        _brainCloudComms->deregisterNetworkErrorCallback();
    }

    void BrainCloudClient::enableLogging(bool shouldEnable)
    {
        _brainCloudComms->enableLogging(shouldEnable);
        _lobbyService->enableLogging(shouldEnable);
        _rttComms->enableLogging(shouldEnable);
    }

    /**
     * Heart beat to keep session(s) current, and retrieve any pending events...
     */
    void BrainCloudClient::heartbeat()
    {
        _brainCloudComms->sendHeartbeat();
    }

    void BrainCloudClient::sendRequest(ServerCall * in_serviceMessage)
    {
        _brainCloudComms->addToQueue(in_serviceMessage);
    }

    void BrainCloudClient::resetCommunication()
    {
        _rttComms->resetCommunication();
        _brainCloudComms->resetCommunication();
        _brainCloudComms->setSessionId("");
        _authenticationService->setProfileId("");
    }

    void BrainCloudClient::shutdown()
    {
        _rttComms->shutdown();
        _brainCloudComms->shutdown();
        _brainCloudComms->setSessionId("");
        _authenticationService->setProfileId("");
    }

    bool BrainCloudClient::isAuthenticated()
    {
        return _brainCloudComms->isAuthenticated();
    }

    bool BrainCloudClient::isInitialized()
    {
        return _brainCloudComms->isInitialized() && _rttComms->isInitialized();
    }

    void BrainCloudClient::setImmediateRetryOnError(bool value)
    {
        _brainCloudComms->setImmediateRetryOnError(value);
    }

    /**
     * Retrieve the pointer to the singleton BrainCloudClient instance.
     */
    BrainCloudClient * BrainCloudClient::getInstance()
    {
        if(EnableSingletonMode == false) {
            throw std::invalid_argument(SingletonUseErrorMessage);
        }

        if (_instance == NULL) {
            _instance = new BrainCloudClient();
        }
        return _instance;
    }

    void BrainCloudClient::setHeartbeatInterval(int in_intervalInMilliseconds) {
        _brainCloudComms->setHeartbeatInterval(in_intervalInMilliseconds);
    }

    const std::vector<int> & BrainCloudClient::getPacketTimeouts()
    {
        return _brainCloudComms->getPacketTimeouts();
    }

    void BrainCloudClient::setPacketTimeouts(const std::vector<int> & in_packetTimeouts)
    {
        _brainCloudComms->setPacketTimeouts(in_packetTimeouts);
    }

    void BrainCloudClient::setPacketTimeoutsToDefault()
    {
        _brainCloudComms->setPacketTimeoutsToDefault();
    }

    void BrainCloudClient::setAuthenticationPacketTimeout(int in_timeoutSecs)
    {
        _brainCloudComms->setAuthenticationPacketTimeout(in_timeoutSecs);
    }

    int BrainCloudClient::getAuthenticationPacketTimeout()
    {
        return _brainCloudComms->getAuthenticationPacketTimeout();
    }

    void BrainCloudClient::setOldStyleStatusMessageErrorCallback(bool in_enabled)
    {
        _brainCloudComms->setOldStyleStatusMessageErrorCallback(in_enabled);
    }

    void BrainCloudClient::setErrorCallbackOn202Status(bool in_isError)
    {
        _brainCloudComms->setErrorCallbackOn202Status(in_isError);
    }

    int BrainCloudClient::getUploadLowTransferRateTimeout()
    {
        return _brainCloudComms->getUploadLowTransferRateTimeout();
    }

    void BrainCloudClient::setUploadLowTransferRateTimeout(int in_timeoutSecs)
    {
        _brainCloudComms->setUploadLowTransferRateTimeout(in_timeoutSecs);
    }

    int BrainCloudClient::getUploadLowTransferRateThreshold()
    {
        return _brainCloudComms->getUploadLowTransferRateThreshold();
    }

    void BrainCloudClient::setUploadLowTransferRateThreshold(int in_bytesPerSec)
    {
        _brainCloudComms->setUploadLowTransferRateThreshold(in_bytesPerSec);
    }

    void BrainCloudClient::enableNetworkErrorMessageCaching(bool in_enabled)
    {
        _brainCloudComms->enableNetworkErrorMessageCaching(in_enabled);
    }

    void BrainCloudClient::retryCachedMessages()
    {
        _brainCloudComms->retryCachedMessages();
    }

    void BrainCloudClient::flushCachedMessages(bool in_sendApiErrorCallbacks)
    {
        _brainCloudComms->flushCachedMessages(in_sendApiErrorCallbacks);
    }

    void BrainCloudClient::insertEndOfMessageBundleMarker()
    {
        _brainCloudComms->insertEndOfMessageBundleMarker();
    }

    ////////////////////////////////////////////////////
    // Private Methods
    ////////////////////////////////////////////////////
    void BrainCloudClient::setupOSLocaleData()
    {
        Device::getLocale(&_timezoneOffset, &_languageCode, &_countryCode);
    }
}  // end namespace
<commit_msg>Updated version<commit_after>// BrainCloudClient.cpp
// BrainCloudLib
// Copyright 2016 bitHeads, Inc. All Rights Reserved.

#include <cstring>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>

#include "braincloud/BrainCloudClient.h"

#include "braincloud/internal/Device.h"
#include "braincloud/internal/JsonUtil.h"
#include "braincloud/internal/URLRequestMethod.h"

namespace BrainCloud
{
    // Define all static member variables.
    bool BrainCloudClient::EnableSingletonMode = false;
    const char * BrainCloudClient::SingletonUseErrorMessage =
            "Singleton usage is disabled. If called by mistake, use your own variable that holds an instance of the bcWrapper/bcClient.";

    BrainCloudClient * BrainCloudClient::_instance = NULL;
    std::string BrainCloudClient::s_brainCloudClientVersion = "4.5.0";
    const char* BC_SERVER_URL = "https://sharedprod.braincloudservers.com/dispatcherv2";

    /**
     * Constructor
     */
    BrainCloudClient::BrainCloudClient() :
        _brainCloudComms(IBrainCloudComms::create(this)),
        _rttComms(new RTTComms(this)),
        _asyncMatchService(new BrainCloudAsyncMatch(this)),
        _authenticationService(new BrainCloudAuthentication(this)),
        _chatService(new BrainCloudChat(this)),
        _dataStreamService(new BrainCloudDataStream(this)),
        _entityService(new BrainCloudEntity(this)),
        _eventService(new BrainCloudEvent(this)),
        _fileService(new BrainCloudFile(this)),
        _globalFileService(new BrainCloudGlobalFile(this)),
        _friendService(new BrainCloudFriend(this)),
        _gamificationService(new BrainCloudGamification(this)),
        _globalAppService(new BrainCloudGlobalApp(this)),
        _globalEntityService(new BrainCloudGlobalEntity(this)),
        _globalStatisticsService(new BrainCloudGlobalStatistics(this)),
        _groupService(new BrainCloudGroup(this)),
        _identityService(new BrainCloudIdentity(this)),
        _lobbyService(new BrainCloudLobby(this)),
        _mailService(new BrainCloudMail(this)),
        _matchmakingService(new BrainCloudMatchmaking(this)),
        _messagingService(new BrainCloudMessaging(this)),
        _oneWayMatchService(new BrainCloudOneWayMatch(this)),
        _playbackStreamService(new BrainCloudPlaybackStream(this)),
        _playerStateService(new BrainCloudPlayerState(this)),
        _playerStatisticsService(new BrainCloudPlayerStatistics(this)),
        _playerStatisticsEventService(new BrainCloudPlayerStatisticsEvent(this)),
        _presenceService(new BrainCloudPresence(this)),
        _productService(new BrainCloudProduct(this)),
        _virtualCurrencyService(new BrainCloudVirtualCurrency(this)),
        _appStoreService(new BrainCloudAppStore(this)),
        _profanityService(new BrainCloudProfanity(this)),
        _pushNotificationService(new BrainCloudPushNotification(this)),
        _redemptionCodeService(new BrainCloudRedemptionCode(this)),
        _s3HandlingService(new BrainCloudS3Handling(this)),
        _scriptService(new BrainCloudScript(this)),
        _socialLeaderboardService(new BrainCloudSocialLeaderboard(this)),
        _steamService(new BrainCloudSteam(this)),
        _timeService(new BrainCloudTime(this)),
        _tournamentService(new BrainCloudTournament(this)),
        _customEntityService(new BrainCloudCustomEntity(this)),
        _itemCatalogService(new BrainCloudItemCatalog(this)),
        _userItemsService(new BrainCloudUserItems(this)),
        _releasePlatform(""),
        _appVersion(""),
        _timezoneOffset(0.0)
    {
        //needed this here otherwise out of scope compiler error
        _rttService = new BrainCloudRTT(_rttComms, this);
    }

    BrainCloudClient::~BrainCloudClient()
    {
        delete _rttService;
        delete _tournamentService;
        delete _customEntityService;
        delete _itemCatalogService;
        delete _timeService;
        delete _steamService;
        delete _socialLeaderboardService;
        delete _scriptService;
        delete _s3HandlingService;
        delete _redemptionCodeService;
        delete _pushNotificationService;
        delete _profanityService;
        delete _appStoreService;
        delete _virtualCurrencyService;
        delete _productService;
        delete _presenceService;
        delete _playerStatisticsEventService;
        delete _playerStatisticsService;
        delete _playerStateService;
        delete _playbackStreamService;
        delete _oneWayMatchService;
        delete _messagingService;
        delete _matchmakingService;
        delete _mailService;
        delete _lobbyService;
        delete _identityService;
        delete _groupService;
        delete _globalStatisticsService;
        delete _globalEntityService;
        delete _globalAppService;
        delete _gamificationService;
        delete _friendService;
        delete _fileService;
        delete _globalFileService;
        delete _eventService;
        delete _entityService;
        delete _dataStreamService;
        delete _chatService;
        delete _authenticationService;
        delete _asyncMatchService;
        delete _rttComms;
        delete _brainCloudComms;
    }

    ////////////////////////////////////////////////////
    // Public Methods
    ////////////////////////////////////////////////////

    const char * BrainCloudClient::getSessionId() const {
        return(_brainCloudComms->getSessionId().c_str());
    }

    const char * BrainCloudClient::getRttConnectionId() const{
        return(_rttComms->getConnectionId().c_str());
    }

    void BrainCloudClient::initializeComms(const char * in_serverURL, const char * in_appId, const std::map<std::string, std::string>& in_secretMap)
    {
        if (_brainCloudComms)
        {
            // automatically upgrade any older clients using "dispatcher" url
            // to "dispatcherv2" endpoint. Comms supports this now and otherwise
            // the change is transparent to the client.
            const char * urlToUse = in_serverURL;
            std::string url = in_serverURL;
            if (url.find("dispatcherv2") == std::string::npos)
            {
                size_t index = url.find("dispatcher");
                if (index != std::string::npos)
                {
                    url = url.substr(0, index);
                    url += "dispatcherv2";
                    urlToUse = url.c_str();
                }
            }
            _brainCloudComms->initializeWithApps(urlToUse, in_appId, in_secretMap);
        }

        if (_rttComms)
        {
            _rttComms->initialize();
        }
    }

    void BrainCloudClient::initialize(const char * in_serverURL, const char * in_secretKey, const char * in_appId, const char * in_appVersion)
    {
        std::string error = "";
        if (in_serverURL == NULL || strlen(in_serverURL) <= 0)
            error = "serverURL was null or empty";
        else if (in_secretKey == NULL || strlen(in_secretKey) <= 0)
            error = "secretKey was null or empty";
        else if (in_appId == NULL || strlen(in_appId) <= 0)
            error = "appId was null or empty";
        else if (in_appVersion == NULL || strlen(in_appVersion) <= 0)
            error = "appVersion was null or empty";

        if (error.length() > 0)
        {
            std::cout << "ERROR | Failed to initialize brainCloud - " << error;
            return;
        }

        std::map<std::string, std::string> secretMap;
        secretMap[in_appId] = in_secretKey;

        initializeComms(in_serverURL, in_appId, secretMap);
        setupOSLocaleData();

        _releasePlatform = Device::getPlatformName();
        _appVersion = in_appVersion;
    }

    void BrainCloudClient::initialize(const char * in_secretKey, const char * in_appId, const char * in_appVersion)
    {
        initialize(BC_SERVER_URL, in_secretKey, in_appId, in_appVersion);
    }

    void BrainCloudClient::initializeWithApps(const char * in_serverURL, const char * in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char * in_appVersion)
    {
        std::string error = "";
        if (in_serverURL == NULL || strlen(in_serverURL) <= 0)
            error = "serverURL was null or empty";
        else if (in_defaultAppId == NULL || strlen(in_defaultAppId) <= 0)
            error = "appId was null or empty";
        else if (in_appVersion == NULL || strlen(in_appVersion) <= 0)
            error = "appVersion was null or empty";
        else if (in_secretMap.find(in_defaultAppId) == in_secretMap.end())
            error = "not secretKey match for appid";

        if (error.length() > 0)
        {
            std::cout << "ERROR | Failed to initialize brainCloud - " << error;
            return;
        }

        initializeComms(in_serverURL, in_defaultAppId, in_secretMap);
        setupOSLocaleData();

        _releasePlatform = Device::getPlatformName();
        _appVersion = in_appVersion;
    }

    void BrainCloudClient::initializeWithApps(const char* in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char* in_appVersion)
    {
        initializeWithApps(BC_SERVER_URL, in_defaultAppId, in_secretMap, in_appVersion);
    }

    void BrainCloudClient::initializeIdentity(const char * in_profileId, const char * in_anonymousId)
    {
        _authenticationService->initialize(in_profileId, in_anonymousId);
    }

    void BrainCloudClient::runCallbacks()
    {
        _brainCloudComms->runCallbacks();
        _lobbyService->runPingCallbacks();
        _rttComms->runCallbacks();
    }

    void BrainCloudClient::registerEventCallback(IEventCallback *in_eventCallback)
    {
        _brainCloudComms->registerEventCallback(in_eventCallback);
    }

    void BrainCloudClient::deregisterEventCallback()
    {
        _brainCloudComms->deregisterEventCallback();
    }

    void BrainCloudClient::registerRewardCallback(IRewardCallback *in_rewardCallback)
    {
        _brainCloudComms->registerRewardCallback(in_rewardCallback);
    }

    void BrainCloudClient::deregisterRewardCallback()
    {
        _brainCloudComms->deregisterRewardCallback();
    }

    void BrainCloudClient::registerFileUploadCallback(IFileUploadCallback * in_fileUploadCallback)
    {
        _brainCloudComms->registerFileUploadCallback(in_fileUploadCallback);
    }

    void BrainCloudClient::deregisterFileUploadCallback()
    {
        _brainCloudComms->deregisterFileUploadCallback();
    }

    void BrainCloudClient::registerGlobalErrorCallback(IGlobalErrorCallback * in_globalErrorCallback)
    {
        _brainCloudComms->registerGlobalErrorCallback(in_globalErrorCallback);
    }

    void BrainCloudClient::deregisterGlobalErrorCallback()
    {
        _brainCloudComms->deregisterGlobalErrorCallback();
    }

    void BrainCloudClient::registerNetworkErrorCallback(INetworkErrorCallback * in_networkErrorCallback)
    {
        _brainCloudComms->registerNetworkErrorCallback(in_networkErrorCallback);
    }

    void BrainCloudClient::deregisterNetworkErrorCallback()
    {
        _brainCloudComms->deregisterNetworkErrorCallback();
    }

    void BrainCloudClient::enableLogging(bool shouldEnable)
    {
        _brainCloudComms->enableLogging(shouldEnable);
        _lobbyService->enableLogging(shouldEnable);
        _rttComms->enableLogging(shouldEnable);
    }

    /**
     * Heart beat to keep session(s) current, and retrieve any pending events...
     */
    void BrainCloudClient::heartbeat()
    {
        _brainCloudComms->sendHeartbeat();
    }

    void BrainCloudClient::sendRequest(ServerCall * in_serviceMessage)
    {
        _brainCloudComms->addToQueue(in_serviceMessage);
    }

    void BrainCloudClient::resetCommunication()
    {
        _rttComms->resetCommunication();
        _brainCloudComms->resetCommunication();
        _brainCloudComms->setSessionId("");
        _authenticationService->setProfileId("");
    }

    void BrainCloudClient::shutdown()
    {
        _rttComms->shutdown();
        _brainCloudComms->shutdown();
        _brainCloudComms->setSessionId("");
        _authenticationService->setProfileId("");
    }

    bool BrainCloudClient::isAuthenticated()
    {
        return _brainCloudComms->isAuthenticated();
    }

    bool BrainCloudClient::isInitialized()
    {
        return _brainCloudComms->isInitialized() && _rttComms->isInitialized();
    }

    void BrainCloudClient::setImmediateRetryOnError(bool value)
    {
        _brainCloudComms->setImmediateRetryOnError(value);
    }

    /**
     * Retrieve the pointer to the singleton BrainCloudClient instance.
     */
    BrainCloudClient * BrainCloudClient::getInstance()
    {
        if(EnableSingletonMode == false) {
            throw std::invalid_argument(SingletonUseErrorMessage);
        }

        if (_instance == NULL) {
            _instance = new BrainCloudClient();
        }
        return _instance;
    }

    void BrainCloudClient::setHeartbeatInterval(int in_intervalInMilliseconds) {
        _brainCloudComms->setHeartbeatInterval(in_intervalInMilliseconds);
    }

    const std::vector<int> & BrainCloudClient::getPacketTimeouts()
    {
        return _brainCloudComms->getPacketTimeouts();
    }

    void BrainCloudClient::setPacketTimeouts(const std::vector<int> & in_packetTimeouts)
    {
        _brainCloudComms->setPacketTimeouts(in_packetTimeouts);
    }

    void BrainCloudClient::setPacketTimeoutsToDefault()
    {
        _brainCloudComms->setPacketTimeoutsToDefault();
    }

    void BrainCloudClient::setAuthenticationPacketTimeout(int in_timeoutSecs)
    {
        _brainCloudComms->setAuthenticationPacketTimeout(in_timeoutSecs);
    }

    int BrainCloudClient::getAuthenticationPacketTimeout()
    {
        return _brainCloudComms->getAuthenticationPacketTimeout();
    }

    void BrainCloudClient::setOldStyleStatusMessageErrorCallback(bool in_enabled)
    {
        _brainCloudComms->setOldStyleStatusMessageErrorCallback(in_enabled);
    }

    void BrainCloudClient::setErrorCallbackOn202Status(bool in_isError)
    {
        _brainCloudComms->setErrorCallbackOn202Status(in_isError);
    }

    int BrainCloudClient::getUploadLowTransferRateTimeout()
    {
        return _brainCloudComms->getUploadLowTransferRateTimeout();
    }

    void BrainCloudClient::setUploadLowTransferRateTimeout(int in_timeoutSecs)
    {
        _brainCloudComms->setUploadLowTransferRateTimeout(in_timeoutSecs);
    }

    int BrainCloudClient::getUploadLowTransferRateThreshold()
    {
        return _brainCloudComms->getUploadLowTransferRateThreshold();
    }

    void BrainCloudClient::setUploadLowTransferRateThreshold(int in_bytesPerSec)
    {
        _brainCloudComms->setUploadLowTransferRateThreshold(in_bytesPerSec);
    }

    void BrainCloudClient::enableNetworkErrorMessageCaching(bool in_enabled)
    {
        _brainCloudComms->enableNetworkErrorMessageCaching(in_enabled);
    }

    void BrainCloudClient::retryCachedMessages()
    {
        _brainCloudComms->retryCachedMessages();
    }

    void BrainCloudClient::flushCachedMessages(bool in_sendApiErrorCallbacks)
    {
        _brainCloudComms->flushCachedMessages(in_sendApiErrorCallbacks);
    }

    void BrainCloudClient::insertEndOfMessageBundleMarker()
    {
        _brainCloudComms->insertEndOfMessageBundleMarker();
    }

    ////////////////////////////////////////////////////
    // Private Methods
    ////////////////////////////////////////////////////
    void BrainCloudClient::setupOSLocaleData()
    {
        Device::getLocale(&_timezoneOffset, &_languageCode, &_countryCode);
    }
}  // end namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xinecommon.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 14:00:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XINECOMMON_HXX
#define _XINECOMMON_HXX

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef __RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/awt/KeyModifier.hpp>
#include <com/sun/star/awt/MouseButton.hpp>
#include <com/sun/star/media/XManager.hpp>

#define AVMEDIA_XINE_MANAGER_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.Manager_Xine"
#define AVMEDIA_XINE_MANAGER_SERVICENAME "com.sun.star.media.Manager_Xine"

#define AVMEDIA_XINE_PLAYER_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.Player_Xine"
#define AVMEDIA_XINE_PLAYER_SERVICENAME "com.sun.star.media.Player_Xine"

#define AVMEDIA_XINE_WINDOW_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.Window_Xine"
#define AVMEDIA_XINE_WINDOW_SERVICENAME "com.sun.star.media.Window_Xine"

#endif // _XINECOMMOM_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.86); FILE MERGED 2008/04/01 15:00:19 thb 1.4.86.2: #i85898# Stripping all external header guards 2008/03/28 16:04:01 rt 1.4.86.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xinecommon.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XINECOMMON_HXX
#define _XINECOMMON_HXX

#include <osl/mutex.hxx>
#ifndef __RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#include <tools/debug.hxx>
#include <tools/stream.hxx>
#include <tools/string.hxx>
#include <tools/urlobj.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/factory.hxx>

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/awt/KeyModifier.hpp>
#include <com/sun/star/awt/MouseButton.hpp>
#include <com/sun/star/media/XManager.hpp>

#define AVMEDIA_XINE_MANAGER_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.Manager_Xine"
#define AVMEDIA_XINE_MANAGER_SERVICENAME "com.sun.star.media.Manager_Xine"

#define AVMEDIA_XINE_PLAYER_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.Player_Xine"
#define AVMEDIA_XINE_PLAYER_SERVICENAME "com.sun.star.media.Player_Xine"

#define AVMEDIA_XINE_WINDOW_IMPLEMENTATIONNAME "com.sun.star.comp.avmedia.Window_Xine"
#define AVMEDIA_XINE_WINDOW_SERVICENAME "com.sun.star.media.Window_Xine"

#endif // _XINECOMMOM_HXX
<|endoftext|>


<commit_before>#include <sstream>

#include <Poco/Exception.h>
#include <Poco/Net/Context.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/Net/InvalidCertificateHandler.h>
#include <Poco/Net/AcceptCertificateHandler.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/NetException.h>
#include <Poco/StreamCopier.h>

#include "provider/OAuth2AuthProvider.h"
#include "ssl/SSLClient.h"
#include "Debug.h"

using namespace std;
using namespace BeeeOn;
using namespace Poco;
using namespace Poco::Net;

OAuth2AuthProvider::OAuth2AuthProvider(const string &name):
		AuthCodeAuthProvider(name),
		m_sslConfig(0)
{
}

void OAuth2AuthProvider::initSSL()
{
	if (m_sslConfig == 0)
		throw IllegalStateException(
				"missing sslConfig, cannot use OAuth");
}

SharedPtr<HTTPSClientSession> OAuth2AuthProvider::connectSecure(
		const std::string &host,
		unsigned int port)
{
	try {
		initSSL();
		return new HTTPSClientSession(
				host, port, m_sslConfig->context());
	} catch (const Exception &e) {
		logger().log(e, __FILE__, __LINE__);
		throw;
	}
}

string OAuth2AuthProvider::handleResponse(HTTPSClientSession &session)
{
	HTTPResponse response;
	istream &rs = session.receiveResponse(response);

	if (logger().debug()) {
		logger().debug("response status: "
			+ to_string(response.getStatus())
			+ " "
			+ response.getReason(), __FILE__, __LINE__);
	}

	string receiveResponse = convertResponseToString(rs);

	if (logger().debug()) {
		logger().debug("response: "
			+ receiveResponse, __FILE__, __LINE__);
	}

	if (response.getStatus() != HTTPResponse::HTTP_OK) {
		throw NotAuthenticatedException(
			"failed to retrieve access token from Google APIs");
	}

	return receiveResponse;
}

string OAuth2AuthProvider::convertResponseToString(istream &rs)
{
	string response;
	stringstream ss;
	StreamCopier::copyToString(rs, response);

	return response;
}
<commit_msg>OAuth2AuthProvider: remove unnecessary exception throw<commit_after>#include <sstream>

#include <Poco/Exception.h>
#include <Poco/Net/Context.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/Net/InvalidCertificateHandler.h>
#include <Poco/Net/AcceptCertificateHandler.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/NetException.h>
#include <Poco/StreamCopier.h>

#include "provider/OAuth2AuthProvider.h"
#include "ssl/SSLClient.h"
#include "Debug.h"

using namespace std;
using namespace BeeeOn;
using namespace Poco;
using namespace Poco::Net;

OAuth2AuthProvider::OAuth2AuthProvider(const string &name):
		AuthCodeAuthProvider(name),
		m_sslConfig(0)
{
}

void OAuth2AuthProvider::initSSL()
{
	if (m_sslConfig == 0)
		throw IllegalStateException(
				"missing sslConfig, cannot use OAuth");
}

SharedPtr<HTTPSClientSession> OAuth2AuthProvider::connectSecure(
		const std::string &host,
		unsigned int port)
{
	try {
		initSSL();
		return new HTTPSClientSession(
				host, port, m_sslConfig->context());
	} catch (const Exception &e) {
		logger().log(e, __FILE__, __LINE__);
		throw;
	}
}

string OAuth2AuthProvider::handleResponse(HTTPSClientSession &session)
{
	HTTPResponse response;
	istream &rs = session.receiveResponse(response);

	if (logger().debug()) {
		logger().debug("response status: "
			+ to_string(response.getStatus())
			+ " "
			+ response.getReason(), __FILE__, __LINE__);
	}

	string receiveResponse = convertResponseToString(rs);

	if (logger().debug()) {
		logger().debug("response: "
			+ receiveResponse, __FILE__, __LINE__);
	}

	return receiveResponse;
}

string OAuth2AuthProvider::convertResponseToString(istream &rs)
{
	string response;
	stringstream ss;
	StreamCopier::copyToString(rs, response);

	return response;
}
<|endoftext|>