<commit_before>#include "Texture.h"
#include "saiga/vulkan/buffer/StagingBuffer.h"
#include "vkImageFormat.h"

namespace Saiga
{
namespace Vulkan
{
// Texture::~Texture()
//{
////    cout << "destroy texture" << endl;
//    destroy();
//}

void Texture::destroy()
{
    if (!base) {
        LOG(WARNING) << "Image was not initialized, do nothing";
        return;
    }
    if (image)
    {
        LOG(INFO) << "Destroying image: " << image;
        base->device.destroyImage(image);
        base->device.destroyImageView(imageView);
        base->device.destroySampler(sampler);
        image = nullptr;
    }

    if (memoryLocation)
    {
        base->memory.getImageAllocator(vk::MemoryPropertyFlagBits::eDeviceLocal).deallocate(memoryLocation);
    }
}

void Texture::transitionImageLayout(vk::CommandBuffer cmd, vk::ImageLayout newLayout)
{
    vk::ImageMemoryBarrier barrier          = {};
    barrier.oldLayout                       = imageLayout;
    barrier.newLayout                       = newLayout;
    barrier.srcQueueFamilyIndex             = VK_QUEUE_FAMILY_IGNORED;
    barrier.dstQueueFamilyIndex             = VK_QUEUE_FAMILY_IGNORED;
    barrier.image                           = image;
    barrier.subresourceRange.aspectMask     = vk::ImageAspectFlagBits::eColor;
    barrier.subresourceRange.baseMipLevel   = 0;
    barrier.subresourceRange.levelCount     = 1;
    barrier.subresourceRange.baseArrayLayer = 0;
    barrier.subresourceRange.layerCount     = 1;
    //        barrier.srcAccessMask = 0; // TODO
    //        barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite; // TODO

    vk::PipelineStageFlags sourceStage;
    vk::PipelineStageFlags destinationStage;

    if (imageLayout == vk::ImageLayout::eUndefined && newLayout == vk::ImageLayout::eTransferDstOptimal)
    {
        barrier.srcAccessMask = {};
        barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;

        sourceStage      = vk::PipelineStageFlagBits::eHost;
        destinationStage = vk::PipelineStageFlagBits::eTransfer;
    }
    else if (imageLayout == vk::ImageLayout::eTransferDstOptimal &&
             newLayout == vk::ImageLayout::eShaderReadOnlyOptimal)
    {
        barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
        barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;

        sourceStage      = vk::PipelineStageFlagBits::eTransfer;
        destinationStage = vk::PipelineStageFlagBits::eAllCommands;
    }
    else
    {
        //            throw std::invalid_argument("unsupported layout transition!");
        barrier.srcAccessMask = vk::AccessFlagBits::eShaderRead;
        barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
        sourceStage           = vk::PipelineStageFlagBits::eAllCommands;
        destinationStage      = vk::PipelineStageFlagBits::eAllCommands;
    }

    cmd.pipelineBarrier(sourceStage, destinationStage, vk::DependencyFlags(), 0, nullptr, 0, nullptr, 1, &barrier);

    imageLayout = newLayout;
}

vk::DescriptorImageInfo Texture::getDescriptorInfo()
{
    SAIGA_ASSERT(image);
    vk::DescriptorImageInfo descriptorInfo;
    descriptorInfo.imageLayout = imageLayout;
    descriptorInfo.imageView   = imageView;
    descriptorInfo.sampler     = sampler;
    SAIGA_ASSERT(imageView && sampler);
    return descriptorInfo;
}

void Texture2D::fromImage(VulkanBase& base, Image& img, vk::ImageUsageFlags usage, bool flipY)
{
    fromImage(base, img, base.transferQueue, base.commandPool, usage, flipY);
}

void Texture2D::uploadImage(Image &img, bool flipY)
{
    vk::CommandBuffer cmd = base->createAndBeginTransferCommand();

    transitionImageLayout(cmd, vk::ImageLayout::eTransferDstOptimal);

    StagingBuffer staging;

    if (flipY)
    {
        std::vector<char> data(img.pitchBytes * img.h);
        for (int i = 0; i < img.h; ++i)
        {
            memcpy(&data[i * img.pitchBytes], img.rowPtr(img.h - i - 1), img.pitchBytes);
        }

        staging.init(*base, data.size(), data.data());
    }
    else
    {
        staging.init(*base, img.size(), img.data());
    }

    vk::BufferImageCopy bufferCopyRegion             = staging.getBufferImageCopy(0);
    bufferCopyRegion.imageSubresource.aspectMask     = vk::ImageAspectFlagBits::eColor;
    bufferCopyRegion.imageSubresource.mipLevel       = 0;
    bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
    bufferCopyRegion.imageSubresource.layerCount     = 1;
    bufferCopyRegion.imageExtent.width               = width;
    bufferCopyRegion.imageExtent.height              = height;
    bufferCopyRegion.imageExtent.depth               = 1;

    staging.copyTo(cmd, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegion);

    transitionImageLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);

    base->endTransferWait(cmd);

    staging.destroy();
}

void Texture2D::fromImage(VulkanBase& _base, Image& img, Queue& queue, CommandPool& pool, vk::ImageUsageFlags usage,
                          bool flipY)
{
    destroy();
    this->base = &_base;

    mipLevels = 1;
    width     = img.width;
    height    = img.height;

    vk::Format format = getvkFormat(img.type);

    auto finalUsageFlags = usage | vk::ImageUsageFlagBits::eTransferDst;

    imageLayout = vk::ImageLayout::eUndefined;
    // Create optimal tiled target image
    vk::ImageCreateInfo imageCreateInfo;
    imageCreateInfo.imageType     = vk::ImageType::e2D;
    imageCreateInfo.format        = format;
    imageCreateInfo.mipLevels     = mipLevels;
    imageCreateInfo.arrayLayers   = 1;
    imageCreateInfo.samples       = vk::SampleCountFlagBits::e1;
    imageCreateInfo.tiling        = vk::ImageTiling::eOptimal;
    imageCreateInfo.sharingMode   = vk::SharingMode::eExclusive;
    imageCreateInfo.initialLayout = imageLayout;
    imageCreateInfo.extent        = vk::Extent3D{width, height, 1U};
    imageCreateInfo.usage         = finalUsageFlags;
    image                         = base->device.createImage(imageCreateInfo);
    SAIGA_ASSERT(image);

    LOG(INFO) << "Creating image synched: " << image;

    auto memReqs   = base->device.getImageMemoryRequirements(image);
    memoryLocation = base->memory.getImageAllocator(vk::MemoryPropertyFlagBits::eDeviceLocal).allocate(memReqs.size);
    base->device.bindImageMemory(image, memoryLocation.memory, memoryLocation.offset);

    vk::CommandBuffer cmd = pool.createAndBeginOneTimeBuffer();

    transitionImageLayout(cmd, vk::ImageLayout::eTransferDstOptimal);

    StagingBuffer staging;

    if (flipY)
    {
        std::vector<char> data(img.pitchBytes * img.h);
        for (int i = 0; i < img.h; ++i)
        {
            memcpy(&data[i * img.pitchBytes], img.rowPtr(img.h - i - 1), img.pitchBytes);
        }

        staging.init(*base, data.size(), data.data());
    }
    else
    {
        staging.init(*base, img.size(), img.data());
    }

    vk::BufferImageCopy bufferCopyRegion             = staging.getBufferImageCopy(0);
    bufferCopyRegion.imageSubresource.aspectMask     = vk::ImageAspectFlagBits::eColor;
    bufferCopyRegion.imageSubresource.mipLevel       = 0;
    bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
    bufferCopyRegion.imageSubresource.layerCount     = 1;
    bufferCopyRegion.imageExtent.width               = width;
    bufferCopyRegion.imageExtent.height              = height;
    bufferCopyRegion.imageExtent.depth               = 1;

    staging.copyTo(cmd, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegion);

    transitionImageLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);

    cmd.end();
    queue.submitAndWait(cmd);
    pool.freeCommandBuffer(cmd);

    staging.destroy();

    vk::ImageViewCreateInfo viewCreateInfo = {};
    viewCreateInfo.viewType                = vk::ImageViewType::e2D;
    viewCreateInfo.format                  = format;
    viewCreateInfo.subresourceRange        = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
    viewCreateInfo.image                   = image;
    imageView                              = base->device.createImageView(viewCreateInfo);
    SAIGA_ASSERT(imageView);

    // Create a defaultsampler
    vk::SamplerCreateInfo samplerCreateInfo = {};
    samplerCreateInfo.magFilter             = vk::Filter::eLinear;
    samplerCreateInfo.minFilter             = vk::Filter::eLinear;
    samplerCreateInfo.mipmapMode            = vk::SamplerMipmapMode::eLinear;
    samplerCreateInfo.addressModeU          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeV          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeW          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.mipLodBias            = 0.0f;
    samplerCreateInfo.compareOp             = vk::CompareOp::eNever;
    samplerCreateInfo.minLod                = 0.0f;
    // Max level-of-detail should match mip level count
    samplerCreateInfo.maxLod = 0.0f;
    // Only enable anisotropic filtering if enabled on the devicec
    samplerCreateInfo.maxAnisotropy    = 16;
    samplerCreateInfo.anisotropyEnable = VK_FALSE;
    samplerCreateInfo.borderColor      = vk::BorderColor::eIntOpaqueWhite;

    sampler = base->device.createSampler(samplerCreateInfo);
    SAIGA_ASSERT(sampler);
}

AsyncCommand Texture2D::fromStagingBuffer(VulkanBase& base, uint32_t width, uint32_t height, vk::Format format,
                                          Saiga::Vulkan::StagingBuffer& stagingBuffer, Queue& queue, CommandPool& pool,
                                          vk::ImageUsageFlags usage)
{
    destroy();
    this->base = &base;

    mipLevels = 1;
    //    width = img.width;
    //    height = img.height;

    //    vk::Format format = getvkFormat(img.type);

    auto finalUsageFlags = usage | vk::ImageUsageFlagBits::eTransferDst;

    imageLayout = vk::ImageLayout::eUndefined;
    // Create optimal tiled target image
    vk::ImageCreateInfo imageCreateInfo;
    imageCreateInfo.imageType     = vk::ImageType::e2D;
    imageCreateInfo.format        = format;
    imageCreateInfo.mipLevels     = mipLevels;
    imageCreateInfo.arrayLayers   = 1;
    imageCreateInfo.samples       = vk::SampleCountFlagBits::e1;
    imageCreateInfo.tiling        = vk::ImageTiling::eOptimal;
    imageCreateInfo.sharingMode   = vk::SharingMode::eExclusive;
    imageCreateInfo.initialLayout = imageLayout;
    imageCreateInfo.extent        = vk::Extent3D{width, height, 1U};
    imageCreateInfo.usage         = finalUsageFlags;
    image                         = base.device.createImage(imageCreateInfo);

    LOG(INFO) << "Creating image: " << image;
    SAIGA_ASSERT(image);

    auto memReqs   = base.device.getImageMemoryRequirements(image);
    memoryLocation = base.memory.getImageAllocator(vk::MemoryPropertyFlagBits::eDeviceLocal).allocate(memReqs.size);
    base.device.bindImageMemory(image, memoryLocation.memory, memoryLocation.offset);

    vk::CommandBuffer cmd = pool.createAndBeginOneTimeBuffer();

    transitionImageLayout(cmd, vk::ImageLayout::eTransferDstOptimal);

    vk::BufferImageCopy bufferCopyRegion             = stagingBuffer.getBufferImageCopy(0);
    bufferCopyRegion.imageSubresource.aspectMask     = vk::ImageAspectFlagBits::eColor;
    bufferCopyRegion.imageSubresource.mipLevel       = 0;
    bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
    bufferCopyRegion.imageSubresource.layerCount     = 1;
    bufferCopyRegion.imageExtent.width               = width;
    bufferCopyRegion.imageExtent.height              = height;
    bufferCopyRegion.imageExtent.depth               = 1;

    //    StagingBuffer staging;
    //
    //    staging.init(base,img.size(),img.data());

    stagingBuffer.copyTo(cmd, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegion);

    transitionImageLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);

    cmd.end();

    //    queue.submitAndWait(cmd);
    //    pool.freeCommandBuffer(cmd);

    vk::ImageViewCreateInfo viewCreateInfo = {};
    viewCreateInfo.viewType                = vk::ImageViewType::e2D;
    viewCreateInfo.format                  = format;
    viewCreateInfo.subresourceRange        = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
    viewCreateInfo.image                   = image;
    imageView                              = base.device.createImageView(viewCreateInfo);
    SAIGA_ASSERT(imageView);

    // Create a defaultsampler
    vk::SamplerCreateInfo samplerCreateInfo = {};
    samplerCreateInfo.magFilter             = vk::Filter::eLinear;
    samplerCreateInfo.minFilter             = vk::Filter::eLinear;
    samplerCreateInfo.mipmapMode            = vk::SamplerMipmapMode::eLinear;
    samplerCreateInfo.addressModeU          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeV          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeW          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.mipLodBias            = 0.0f;
    samplerCreateInfo.compareOp             = vk::CompareOp::eNever;
    samplerCreateInfo.minLod                = 0.0f;
    // Max level-of-detail should match mip level count
    samplerCreateInfo.maxLod = 0.0f;
    // Only enable anisotropic filtering if enabled on the devicec
    samplerCreateInfo.maxAnisotropy    = 16;
    samplerCreateInfo.anisotropyEnable = VK_FALSE;
    samplerCreateInfo.borderColor      = vk::BorderColor::eIntOpaqueWhite;

    sampler = base.device.createSampler(samplerCreateInfo);
    SAIGA_ASSERT(sampler);

    auto fence = queue.submit(cmd);
    return AsyncCommand{cmd, fence};
}

}  // namespace Vulkan
}  // namespace Saiga
<commit_msg>Remove warning when destroying image<commit_after>#include "Texture.h"
#include "saiga/vulkan/buffer/StagingBuffer.h"
#include "vkImageFormat.h"

namespace Saiga
{
namespace Vulkan
{
void Texture::destroy()
{
    if (!base)
    {
        return;
    }
    if (image)
    {
        LOG(INFO) << "Destroying image: " << image;
        base->device.destroyImage(image);
        base->device.destroyImageView(imageView);
        base->device.destroySampler(sampler);
        image = nullptr;
    }

    if (memoryLocation)
    {
        base->memory.getImageAllocator(vk::MemoryPropertyFlagBits::eDeviceLocal).deallocate(memoryLocation);
    }
}

void Texture::transitionImageLayout(vk::CommandBuffer cmd, vk::ImageLayout newLayout)
{
    vk::ImageMemoryBarrier barrier          = {};
    barrier.oldLayout                       = imageLayout;
    barrier.newLayout                       = newLayout;
    barrier.srcQueueFamilyIndex             = VK_QUEUE_FAMILY_IGNORED;
    barrier.dstQueueFamilyIndex             = VK_QUEUE_FAMILY_IGNORED;
    barrier.image                           = image;
    barrier.subresourceRange.aspectMask     = vk::ImageAspectFlagBits::eColor;
    barrier.subresourceRange.baseMipLevel   = 0;
    barrier.subresourceRange.levelCount     = 1;
    barrier.subresourceRange.baseArrayLayer = 0;
    barrier.subresourceRange.layerCount     = 1;
    //        barrier.srcAccessMask = 0; // TODO
    //        barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite; // TODO

    vk::PipelineStageFlags sourceStage;
    vk::PipelineStageFlags destinationStage;

    if (imageLayout == vk::ImageLayout::eUndefined && newLayout == vk::ImageLayout::eTransferDstOptimal)
    {
        barrier.srcAccessMask = {};
        barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;

        sourceStage      = vk::PipelineStageFlagBits::eHost;
        destinationStage = vk::PipelineStageFlagBits::eTransfer;
    }
    else if (imageLayout == vk::ImageLayout::eTransferDstOptimal &&
             newLayout == vk::ImageLayout::eShaderReadOnlyOptimal)
    {
        barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
        barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;

        sourceStage      = vk::PipelineStageFlagBits::eTransfer;
        destinationStage = vk::PipelineStageFlagBits::eAllCommands;
    }
    else
    {
        //            throw std::invalid_argument("unsupported layout transition!");
        barrier.srcAccessMask = vk::AccessFlagBits::eShaderRead;
        barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
        sourceStage           = vk::PipelineStageFlagBits::eAllCommands;
        destinationStage      = vk::PipelineStageFlagBits::eAllCommands;
    }

    cmd.pipelineBarrier(sourceStage, destinationStage, vk::DependencyFlags(), 0, nullptr, 0, nullptr, 1, &barrier);

    imageLayout = newLayout;
}

vk::DescriptorImageInfo Texture::getDescriptorInfo()
{
    SAIGA_ASSERT(image);
    vk::DescriptorImageInfo descriptorInfo;
    descriptorInfo.imageLayout = imageLayout;
    descriptorInfo.imageView   = imageView;
    descriptorInfo.sampler     = sampler;
    SAIGA_ASSERT(imageView && sampler);
    return descriptorInfo;
}

void Texture2D::fromImage(VulkanBase& base, Image& img, vk::ImageUsageFlags usage, bool flipY)
{
    fromImage(base, img, base.transferQueue, base.commandPool, usage, flipY);
}

void Texture2D::uploadImage(Image& img, bool flipY)
{
    vk::CommandBuffer cmd = base->createAndBeginTransferCommand();

    transitionImageLayout(cmd, vk::ImageLayout::eTransferDstOptimal);

    StagingBuffer staging;

    if (flipY)
    {
        std::vector<char> data(img.pitchBytes * img.h);
        for (int i = 0; i < img.h; ++i)
        {
            memcpy(&data[i * img.pitchBytes], img.rowPtr(img.h - i - 1), img.pitchBytes);
        }

        staging.init(*base, data.size(), data.data());
    }
    else
    {
        staging.init(*base, img.size(), img.data());
    }

    vk::BufferImageCopy bufferCopyRegion             = staging.getBufferImageCopy(0);
    bufferCopyRegion.imageSubresource.aspectMask     = vk::ImageAspectFlagBits::eColor;
    bufferCopyRegion.imageSubresource.mipLevel       = 0;
    bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
    bufferCopyRegion.imageSubresource.layerCount     = 1;
    bufferCopyRegion.imageExtent.width               = width;
    bufferCopyRegion.imageExtent.height              = height;
    bufferCopyRegion.imageExtent.depth               = 1;

    staging.copyTo(cmd, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegion);

    transitionImageLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);

    base->endTransferWait(cmd);

    staging.destroy();
}

void Texture2D::fromImage(VulkanBase& _base, Image& img, Queue& queue, CommandPool& pool, vk::ImageUsageFlags usage,
                          bool flipY)
{
    destroy();
    this->base = &_base;

    mipLevels = 1;
    width     = img.width;
    height    = img.height;

    vk::Format format = getvkFormat(img.type);

    auto finalUsageFlags = usage | vk::ImageUsageFlagBits::eTransferDst;

    imageLayout = vk::ImageLayout::eUndefined;
    // Create optimal tiled target image
    vk::ImageCreateInfo imageCreateInfo;
    imageCreateInfo.imageType     = vk::ImageType::e2D;
    imageCreateInfo.format        = format;
    imageCreateInfo.mipLevels     = mipLevels;
    imageCreateInfo.arrayLayers   = 1;
    imageCreateInfo.samples       = vk::SampleCountFlagBits::e1;
    imageCreateInfo.tiling        = vk::ImageTiling::eOptimal;
    imageCreateInfo.sharingMode   = vk::SharingMode::eExclusive;
    imageCreateInfo.initialLayout = imageLayout;
    imageCreateInfo.extent        = vk::Extent3D{width, height, 1U};
    imageCreateInfo.usage         = finalUsageFlags;
    image                         = base->device.createImage(imageCreateInfo);
    SAIGA_ASSERT(image);

    LOG(INFO) << "Creating image synched: " << image;

    auto memReqs   = base->device.getImageMemoryRequirements(image);
    memoryLocation = base->memory.getImageAllocator(vk::MemoryPropertyFlagBits::eDeviceLocal).allocate(memReqs.size);
    base->device.bindImageMemory(image, memoryLocation.memory, memoryLocation.offset);

    vk::CommandBuffer cmd = pool.createAndBeginOneTimeBuffer();

    transitionImageLayout(cmd, vk::ImageLayout::eTransferDstOptimal);

    StagingBuffer staging;

    if (flipY)
    {
        std::vector<char> data(img.pitchBytes * img.h);
        for (int i = 0; i < img.h; ++i)
        {
            memcpy(&data[i * img.pitchBytes], img.rowPtr(img.h - i - 1), img.pitchBytes);
        }

        staging.init(*base, data.size(), data.data());
    }
    else
    {
        staging.init(*base, img.size(), img.data());
    }

    vk::BufferImageCopy bufferCopyRegion             = staging.getBufferImageCopy(0);
    bufferCopyRegion.imageSubresource.aspectMask     = vk::ImageAspectFlagBits::eColor;
    bufferCopyRegion.imageSubresource.mipLevel       = 0;
    bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
    bufferCopyRegion.imageSubresource.layerCount     = 1;
    bufferCopyRegion.imageExtent.width               = width;
    bufferCopyRegion.imageExtent.height              = height;
    bufferCopyRegion.imageExtent.depth               = 1;

    staging.copyTo(cmd, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegion);

    transitionImageLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);

    cmd.end();
    queue.submitAndWait(cmd);
    pool.freeCommandBuffer(cmd);

    staging.destroy();

    vk::ImageViewCreateInfo viewCreateInfo = {};
    viewCreateInfo.viewType                = vk::ImageViewType::e2D;
    viewCreateInfo.format                  = format;
    viewCreateInfo.subresourceRange        = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
    viewCreateInfo.image                   = image;
    imageView                              = base->device.createImageView(viewCreateInfo);
    SAIGA_ASSERT(imageView);

    // Create a defaultsampler
    vk::SamplerCreateInfo samplerCreateInfo = {};
    samplerCreateInfo.magFilter             = vk::Filter::eLinear;
    samplerCreateInfo.minFilter             = vk::Filter::eLinear;
    samplerCreateInfo.mipmapMode            = vk::SamplerMipmapMode::eLinear;
    samplerCreateInfo.addressModeU          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeV          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeW          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.mipLodBias            = 0.0f;
    samplerCreateInfo.compareOp             = vk::CompareOp::eNever;
    samplerCreateInfo.minLod                = 0.0f;
    // Max level-of-detail should match mip level count
    samplerCreateInfo.maxLod = 0.0f;
    // Only enable anisotropic filtering if enabled on the devicec
    samplerCreateInfo.maxAnisotropy    = 16;
    samplerCreateInfo.anisotropyEnable = VK_FALSE;
    samplerCreateInfo.borderColor      = vk::BorderColor::eIntOpaqueWhite;

    sampler = base->device.createSampler(samplerCreateInfo);
    SAIGA_ASSERT(sampler);
}

AsyncCommand Texture2D::fromStagingBuffer(VulkanBase& base, uint32_t width, uint32_t height, vk::Format format,
                                          Saiga::Vulkan::StagingBuffer& stagingBuffer, Queue& queue, CommandPool& pool,
                                          vk::ImageUsageFlags usage)
{
    destroy();
    this->base = &base;

    mipLevels = 1;
    //    width = img.width;
    //    height = img.height;

    //    vk::Format format = getvkFormat(img.type);

    auto finalUsageFlags = usage | vk::ImageUsageFlagBits::eTransferDst;

    imageLayout = vk::ImageLayout::eUndefined;
    // Create optimal tiled target image
    vk::ImageCreateInfo imageCreateInfo;
    imageCreateInfo.imageType     = vk::ImageType::e2D;
    imageCreateInfo.format        = format;
    imageCreateInfo.mipLevels     = mipLevels;
    imageCreateInfo.arrayLayers   = 1;
    imageCreateInfo.samples       = vk::SampleCountFlagBits::e1;
    imageCreateInfo.tiling        = vk::ImageTiling::eOptimal;
    imageCreateInfo.sharingMode   = vk::SharingMode::eExclusive;
    imageCreateInfo.initialLayout = imageLayout;
    imageCreateInfo.extent        = vk::Extent3D{width, height, 1U};
    imageCreateInfo.usage         = finalUsageFlags;
    image                         = base.device.createImage(imageCreateInfo);

    LOG(INFO) << "Creating image: " << image;
    SAIGA_ASSERT(image);

    auto memReqs   = base.device.getImageMemoryRequirements(image);
    memoryLocation = base.memory.getImageAllocator(vk::MemoryPropertyFlagBits::eDeviceLocal).allocate(memReqs.size);
    base.device.bindImageMemory(image, memoryLocation.memory, memoryLocation.offset);

    vk::CommandBuffer cmd = pool.createAndBeginOneTimeBuffer();

    transitionImageLayout(cmd, vk::ImageLayout::eTransferDstOptimal);

    vk::BufferImageCopy bufferCopyRegion             = stagingBuffer.getBufferImageCopy(0);
    bufferCopyRegion.imageSubresource.aspectMask     = vk::ImageAspectFlagBits::eColor;
    bufferCopyRegion.imageSubresource.mipLevel       = 0;
    bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
    bufferCopyRegion.imageSubresource.layerCount     = 1;
    bufferCopyRegion.imageExtent.width               = width;
    bufferCopyRegion.imageExtent.height              = height;
    bufferCopyRegion.imageExtent.depth               = 1;

    //    StagingBuffer staging;
    //
    //    staging.init(base,img.size(),img.data());

    stagingBuffer.copyTo(cmd, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegion);

    transitionImageLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);

    cmd.end();

    //    queue.submitAndWait(cmd);
    //    pool.freeCommandBuffer(cmd);

    vk::ImageViewCreateInfo viewCreateInfo = {};
    viewCreateInfo.viewType                = vk::ImageViewType::e2D;
    viewCreateInfo.format                  = format;
    viewCreateInfo.subresourceRange        = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
    viewCreateInfo.image                   = image;
    imageView                              = base.device.createImageView(viewCreateInfo);
    SAIGA_ASSERT(imageView);

    // Create a defaultsampler
    vk::SamplerCreateInfo samplerCreateInfo = {};
    samplerCreateInfo.magFilter             = vk::Filter::eLinear;
    samplerCreateInfo.minFilter             = vk::Filter::eLinear;
    samplerCreateInfo.mipmapMode            = vk::SamplerMipmapMode::eLinear;
    samplerCreateInfo.addressModeU          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeV          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.addressModeW          = vk::SamplerAddressMode::eRepeat;
    samplerCreateInfo.mipLodBias            = 0.0f;
    samplerCreateInfo.compareOp             = vk::CompareOp::eNever;
    samplerCreateInfo.minLod                = 0.0f;
    // Max level-of-detail should match mip level count
    samplerCreateInfo.maxLod = 0.0f;
    // Only enable anisotropic filtering if enabled on the devicec
    samplerCreateInfo.maxAnisotropy    = 16;
    samplerCreateInfo.anisotropyEnable = VK_FALSE;
    samplerCreateInfo.borderColor      = vk::BorderColor::eIntOpaqueWhite;

    sampler = base.device.createSampler(samplerCreateInfo);
    SAIGA_ASSERT(sampler);

    auto fence = queue.submit(cmd);
    return AsyncCommand{cmd, fence};
}

}  // namespace Vulkan
}  // namespace Saiga
<|endoftext|>


<commit_before>#ifndef STAN_LANG_AST_FUNCTION_ARG_TYPE_DEF_HPP
#define STAN_LANG_AST_FUNCTION_ARG_TYPE_DEF_HPP

#include <stan/lang/ast/expr_type.hpp>
#include <cstddef>

namespace stan {
  namespace lang {

    function_arg_type::function_arg_type() : data_only_(false) { }

    function_arg_type::function_arg_type(const expr_type expr_type)
      : expr_type_(expr_type), data_only_(false) { }

    function_arg_type::function_arg_type(const expr_type expr_type,
                                         bool data_only)
      : expr_type_(expr_type), data_only_(data_only) { }

    bool function_arg_type::operator==(const function_arg_type& fat) const {
      return expr_type_ == fat.expr_type_;
    }

    bool function_arg_type::operator!=(const function_arg_type& fat) const {
      return expr_type_ != fat.expr_type_;
    }

    bool function_arg_type::operator<(const function_arg_type& fat) const {
      return (expr_type_ < fat.expr_type_);
    }

    bool function_arg_type::operator<=(const function_arg_type& fat) const {
      return (expr_type_ <= fat.expr_type_);
    }

    bool function_arg_type::operator>(const function_arg_type& fat) const {
      return (expr_type_ > fat.expr_type_);
    }

    bool function_arg_type::operator>=(const function_arg_type& fat) const {
      return (expr_type_ >= fat.expr_type_);
    }

  }
}
#endif
<commit_msg>headers fix<commit_after>#ifndef STAN_LANG_AST_FUNCTION_ARG_TYPE_DEF_HPP
#define STAN_LANG_AST_FUNCTION_ARG_TYPE_DEF_HPP

#include <stan/lang/ast/expr_type.hpp>
#include <stan/lang/ast/sigs/function_arg_type.hpp>
#include <cstddef>

namespace stan {
  namespace lang {

    function_arg_type::function_arg_type() : data_only_(false) { }

    function_arg_type::function_arg_type(const expr_type expr_type)
      : expr_type_(expr_type), data_only_(false) { }

    function_arg_type::function_arg_type(const expr_type expr_type,
                                         bool data_only)
      : expr_type_(expr_type), data_only_(data_only) { }

    bool function_arg_type::operator==(const function_arg_type& fat) const {
      return expr_type_ == fat.expr_type_;
    }

    bool function_arg_type::operator!=(const function_arg_type& fat) const {
      return expr_type_ != fat.expr_type_;
    }

    bool function_arg_type::operator<(const function_arg_type& fat) const {
      return (expr_type_ < fat.expr_type_);
    }

    bool function_arg_type::operator<=(const function_arg_type& fat) const {
      return (expr_type_ <= fat.expr_type_);
    }

    bool function_arg_type::operator>(const function_arg_type& fat) const {
      return (expr_type_ > fat.expr_type_);
    }

    bool function_arg_type::operator>=(const function_arg_type& fat) const {
      return (expr_type_ >= fat.expr_type_);
    }

  }
}
#endif
<|endoftext|>


<commit_before>#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>

#include <iostream>
#include <stdexcept>
#include <stdlib.h>
#include <time.h>

#include "creature.h"
#include "display.h"
#include "dungeon.h"
#include "entity.h"
#include "game_context.h"

using namespace std;

int main(int argc, char** argv)
{
    srand(time(NULL));

    GameContext* game_context = new GameContext();
    game_context->game_loop();

    return 0;
}
<commit_msg>Removed unneeded includes from file.<commit_after>#include <stdlib.h>
#include <time.h>

#include "game_context.h"

using namespace std;

int main(int argc, char** argv)
{
    srand(time(NULL));

    GameContext* game_context = new GameContext();
    game_context->game_loop();

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: confapifactory.hxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-07 10:08:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_API_FACTORY_HXX_
#define CONFIGMGR_API_FACTORY_HXX_

#include <sal/types.h>

namespace com { namespace sun { namespace star {
    namespace uno
    {
        class XInterface;
        template <class> class Reference;
        class XComponentContext;
    }
    namespace lang
    {
        class XSingleComponentFactory;
    }
} } }
namespace rtl { class OUString; }

namespace configmgr
{
    namespace uno  = ::com::sun::star::uno;
    namespace lang = ::com::sun::star::lang;

    extern
    uno::Reference< lang::XSingleComponentFactory > SAL_CALL
        createProviderFactory(
            ::rtl::OUString const & aImplementationName,
            bool bAdmin
        )
        SAL_THROW( () );

    struct ServiceRegistrationInfo;
    struct SingletonRegistrationInfo;

    typedef uno::Reference< uno::XComponentContext >        CreationContext;

// provider instantiation
    uno::Reference<uno::XInterface> SAL_CALL
        getDefaultConfigProviderSingleton( CreationContext const& xContext );

    uno::Reference<uno::XInterface> SAL_CALL
        instantiateDefaultProvider( CreationContext const& xContext );

// provider service info
    const SingletonRegistrationInfo * getDefaultProviderSingletonInfo();
    const ServiceRegistrationInfo   * getConfigurationProviderServiceInfo();
    const ServiceRegistrationInfo   * getDefaultProviderServiceInfo();
    const ServiceRegistrationInfo   * getAdminProviderServiceInfo();

// other services - instantiation and info
    uno::Reference< uno::XInterface > SAL_CALL
        instantiateConfigRegistry( CreationContext const& xContext );

    const ServiceRegistrationInfo* getConfigurationRegistryServiceInfo();

// bootstrap context support
    uno::Reference<uno::XInterface> SAL_CALL
        instantiateBootstrapContext( CreationContext const& xContext );

    const SingletonRegistrationInfo * getBootstrapContextSingletonInfo();
    const ServiceRegistrationInfo   * getBootstrapContextServiceInfo();

    namespace xml
    {
        uno::Reference< uno::XInterface > SAL_CALL instantiateSchemaParser
        ( CreationContext const& xContext );
        uno::Reference< uno::XInterface > SAL_CALL instantiateLayerParser
        ( CreationContext const& xContext );
        uno::Reference< uno::XInterface > SAL_CALL instantiateLayerWriter
        ( CreationContext const& xContext );

        const ServiceRegistrationInfo* getSchemaParserServiceInfo();
        const ServiceRegistrationInfo* getLayerParserServiceInfo();
        const ServiceRegistrationInfo* getLayerWriterServiceInfo();
    }
    namespace backend
    {
        uno::Reference<uno::XInterface> SAL_CALL
            getDefaultBackendSingleton( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateDefaultBackend( CreationContext const& xContext );

        uno::Reference< uno::XInterface > SAL_CALL
            instantiateUpdateMerger( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateSingleBackendAdapter( CreationContext const& xContext );

        uno::Reference< uno::XInterface > SAL_CALL
            instantiateMergeImporter( CreationContext const& xContext );

        uno::Reference< uno::XInterface > SAL_CALL
            instantiateCopyImporter( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateMultiStratumBackend( CreationContext const& xContext );

        const SingletonRegistrationInfo * getDefaultBackendSingletonInfo();
        const ServiceRegistrationInfo   * getDefaultBackendServiceInfo();

        const ServiceRegistrationInfo * getUpdateMergerServiceInfo();
        const ServiceRegistrationInfo * getSingleBackendAdapterServiceInfo();
        const ServiceRegistrationInfo * getMergeImportServiceInfo();
        const ServiceRegistrationInfo * getCopyImportServiceInfo();
        const ServiceRegistrationInfo * getMultiStratumBackendServiceInfo();
    }
    namespace localbe
    {
        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalBackend( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalDataImporter( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalHierarchyBrowser( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalSchemaSupplier( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalLegacyStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalDataStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalReadonlyStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalResourceStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalMultiStratum( CreationContext const& xContext );

        const ServiceRegistrationInfo * getLocalBackendServiceInfo();
        const ServiceRegistrationInfo * getLocalDataImportServiceInfo();
        const ServiceRegistrationInfo * getLocalHierarchyBrowserServiceInfo();
        const ServiceRegistrationInfo * getLocalSchemaSupplierServiceInfo();
        const ServiceRegistrationInfo * getLocalLegacyStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalDataStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalReadonlyStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalResourceStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalMultiStratumServiceInfo();
    } // localbe

} //  namespace configmgr

#endif // CONFIGMGR_API_FACTORY_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.17.46); FILE MERGED 2005/09/05 17:04:22 rt 1.17.46.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: confapifactory.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:44:44 $
 *
 *  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 CONFIGMGR_API_FACTORY_HXX_
#define CONFIGMGR_API_FACTORY_HXX_

#include <sal/types.h>

namespace com { namespace sun { namespace star {
    namespace uno
    {
        class XInterface;
        template <class> class Reference;
        class XComponentContext;
    }
    namespace lang
    {
        class XSingleComponentFactory;
    }
} } }
namespace rtl { class OUString; }

namespace configmgr
{
    namespace uno  = ::com::sun::star::uno;
    namespace lang = ::com::sun::star::lang;

    extern
    uno::Reference< lang::XSingleComponentFactory > SAL_CALL
        createProviderFactory(
            ::rtl::OUString const & aImplementationName,
            bool bAdmin
        )
        SAL_THROW( () );

    struct ServiceRegistrationInfo;
    struct SingletonRegistrationInfo;

    typedef uno::Reference< uno::XComponentContext >        CreationContext;

// provider instantiation
    uno::Reference<uno::XInterface> SAL_CALL
        getDefaultConfigProviderSingleton( CreationContext const& xContext );

    uno::Reference<uno::XInterface> SAL_CALL
        instantiateDefaultProvider( CreationContext const& xContext );

// provider service info
    const SingletonRegistrationInfo * getDefaultProviderSingletonInfo();
    const ServiceRegistrationInfo   * getConfigurationProviderServiceInfo();
    const ServiceRegistrationInfo   * getDefaultProviderServiceInfo();
    const ServiceRegistrationInfo   * getAdminProviderServiceInfo();

// other services - instantiation and info
    uno::Reference< uno::XInterface > SAL_CALL
        instantiateConfigRegistry( CreationContext const& xContext );

    const ServiceRegistrationInfo* getConfigurationRegistryServiceInfo();

// bootstrap context support
    uno::Reference<uno::XInterface> SAL_CALL
        instantiateBootstrapContext( CreationContext const& xContext );

    const SingletonRegistrationInfo * getBootstrapContextSingletonInfo();
    const ServiceRegistrationInfo   * getBootstrapContextServiceInfo();

    namespace xml
    {
        uno::Reference< uno::XInterface > SAL_CALL instantiateSchemaParser
        ( CreationContext const& xContext );
        uno::Reference< uno::XInterface > SAL_CALL instantiateLayerParser
        ( CreationContext const& xContext );
        uno::Reference< uno::XInterface > SAL_CALL instantiateLayerWriter
        ( CreationContext const& xContext );

        const ServiceRegistrationInfo* getSchemaParserServiceInfo();
        const ServiceRegistrationInfo* getLayerParserServiceInfo();
        const ServiceRegistrationInfo* getLayerWriterServiceInfo();
    }
    namespace backend
    {
        uno::Reference<uno::XInterface> SAL_CALL
            getDefaultBackendSingleton( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateDefaultBackend( CreationContext const& xContext );

        uno::Reference< uno::XInterface > SAL_CALL
            instantiateUpdateMerger( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateSingleBackendAdapter( CreationContext const& xContext );

        uno::Reference< uno::XInterface > SAL_CALL
            instantiateMergeImporter( CreationContext const& xContext );

        uno::Reference< uno::XInterface > SAL_CALL
            instantiateCopyImporter( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateMultiStratumBackend( CreationContext const& xContext );

        const SingletonRegistrationInfo * getDefaultBackendSingletonInfo();
        const ServiceRegistrationInfo   * getDefaultBackendServiceInfo();

        const ServiceRegistrationInfo * getUpdateMergerServiceInfo();
        const ServiceRegistrationInfo * getSingleBackendAdapterServiceInfo();
        const ServiceRegistrationInfo * getMergeImportServiceInfo();
        const ServiceRegistrationInfo * getCopyImportServiceInfo();
        const ServiceRegistrationInfo * getMultiStratumBackendServiceInfo();
    }
    namespace localbe
    {
        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalBackend( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalDataImporter( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalHierarchyBrowser( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalSchemaSupplier( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalLegacyStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalDataStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalReadonlyStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalResourceStratum( CreationContext const& xContext );

        uno::Reference<uno::XInterface> SAL_CALL
            instantiateLocalMultiStratum( CreationContext const& xContext );

        const ServiceRegistrationInfo * getLocalBackendServiceInfo();
        const ServiceRegistrationInfo * getLocalDataImportServiceInfo();
        const ServiceRegistrationInfo * getLocalHierarchyBrowserServiceInfo();
        const ServiceRegistrationInfo * getLocalSchemaSupplierServiceInfo();
        const ServiceRegistrationInfo * getLocalLegacyStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalDataStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalReadonlyStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalResourceStratumServiceInfo();
        const ServiceRegistrationInfo * getLocalMultiStratumServiceInfo();
    } // localbe

} //  namespace configmgr

#endif // CONFIGMGR_API_FACTORY_HXX_

<|endoftext|>


<commit_before>/*
 * PyClaw.cpp
 *
 *  Created on: Feb 18, 2012
 *      Author: kristof
 */

#include "peanoclaw/native/SWEKernel.h"
#include "peanoclaw/Patch.h"
#include "tarch/timing/Watch.h"
#include "tarch/parallel/Node.h"

#include "peanoclaw/native/SWE_WavePropagationBlock_patch.hh"

tarch::logging::Log peanoclaw::native::SWEKernel::_log("peanoclaw::native::SWEKernel");

peanoclaw::native::SWEKernel::SWEKernel(
  SWEKernelScenario& scenario,
  peanoclaw::interSubgridCommunication::Interpolation*  interpolation,
  peanoclaw::interSubgridCommunication::Restriction*    restriction,
  peanoclaw::interSubgridCommunication::FluxCorrection* fluxCorrection
) : Numerics(interpolation, restriction, fluxCorrection),
_scenario(scenario),
_totalSolverCallbackTime(0.0)
{
  //import_array();
}

peanoclaw::native::SWEKernel::~SWEKernel()
{
}

double peanoclaw::native::SWEKernel::initializePatch(
  Patch& patch
) {
  logTraceIn( "initializePatch(...)");

  _scenario.initializePatch(patch);
  double demandedMeshWidth = _scenario.computeDemandedMeshWidth(patch);

  logTraceOutWith1Argument( "initializePatch(...)", demandedMeshWidth);
  return demandedMeshWidth;
}

double peanoclaw::native::SWEKernel::solveTimestep(Patch& patch, double maximumTimestepSize, bool useDimensionalSplitting) {
  logTraceInWith2Arguments( "solveTimestep(...)", maximumTimestepSize, useDimensionalSplitting);

  assertion2(tarch::la::greater(maximumTimestepSize, 0.0), "Timestepsize == 0 should be checked outside.", patch.getMinimalNeighborTimeConstraint());

  tarch::timing::Watch pyclawWatch("", "", false);
  pyclawWatch.startTimer();
  double dtAndEstimatedNextDt[2];

  SWE_WavePropagationBlock_patch swe(patch);

  swe.computeNumericalFluxes();

  double dt = fmin(swe.getMaxTimestep(), maximumTimestepSize);
  double estimatedNextTimestepSize = swe.getMaxTimestep();

  swe.updateUnknowns(dt);

  pyclawWatch.stopTimer();
  _totalSolverCallbackTime += pyclawWatch.getCalendarTime();

  assertion4(
      tarch::la::greater(patch.getTimeIntervals().getTimestepSize(), 0.0)
      || tarch::la::greater(estimatedNextTimestepSize, 0.0)
      || tarch::la::equals(maximumTimestepSize, 0.0)
      || tarch::la::equals(patch.getEstimatedNextTimestepSize(), 0.0),
      patch, maximumTimestepSize, estimatedNextTimestepSize, patch.toStringUNew());
  assertion(patch.getTimeIntervals().getTimestepSize() < std::numeric_limits<double>::infinity());

  if (tarch::la::greater(dt, 0.0)) {
    patch.advanceInTime();
    patch.setTimestepSize(dt);
  }
  patch.setEstimatedNextTimestepSize(estimatedNextTimestepSize);

  logTraceOut( "solveTimestep(...)");
  return _scenario.computeDemandedMeshWidth(patch);
}

void peanoclaw::native::SWEKernel::addPatchToSolution(Patch& patch) {
}

void peanoclaw::native::SWEKernel::fillBoundaryLayer(Patch& patch, int dimension, bool setUpper) {
  logTraceInWith3Arguments("fillBoundaryLayerInPyClaw", patch, dimension, setUpper);

  logDebug("fillBoundaryLayerInPyClaw", "Setting left boundary for " << patch.getPosition() << ", dim=" << dimension << ", setUpper=" << setUpper);

   //std::cout << "------ setUpper " << setUpper << " dimension " << dimension << std::endl;
   //std::cout << patch << std::endl;
   //std::cout << "++++++" << std::endl;
   //std::cout << patch.toStringUOldWithGhostLayer() << std::endl;
   //std::cout << "||||||" << std::endl;

  // implement a wall boundary
    tarch::la::Vector<DIMENSIONS, int> src_subcellIndex;
    tarch::la::Vector<DIMENSIONS, int> dest_subcellIndex;

    if (dimension == 0) {
        for (int yi = -1; yi < patch.getSubdivisionFactor()(1)+1; yi++) {
            int xi = setUpper ? patch.getSubdivisionFactor()(0) : -1;
            src_subcellIndex(0) = xi;
            src_subcellIndex(1) = yi;
            src_subcellIndex(dimension) += setUpper ? -1 : +1;

            dest_subcellIndex(0) = xi;
            dest_subcellIndex(1) = yi;

            for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
                double q = patch.getValueUOld(src_subcellIndex, unknown);

                if (unknown == dimension + 1) {
                    patch.setValueUOld(dest_subcellIndex, unknown, -q);
                } else {
                    patch.setValueUOld(dest_subcellIndex, unknown, q);
                }
            }
        }

    } else {
        for (int xi = -1; xi < patch.getSubdivisionFactor()(0)+1; xi++) {
            int yi = setUpper ? patch.getSubdivisionFactor()(1) : -1;
            src_subcellIndex(0) = xi;
            src_subcellIndex(1) = yi;
            src_subcellIndex(dimension) += setUpper ? -1 : +1;

            dest_subcellIndex(0) = xi;
            dest_subcellIndex(1) = yi;

            for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
                double q = patch.getValueUOld(src_subcellIndex, unknown);

                if (unknown == dimension + 1) {
                    patch.setValueUOld(dest_subcellIndex, unknown, -q);
                } else {
                    patch.setValueUOld(dest_subcellIndex, unknown, q);
                }
            }
        }
    }

   //std::cout << "++++++" << std::endl;
   //std::cout << patch.toStringUOldWithGhostLayer() << std::endl;
   //std::cout << "||||||" << std::endl;

      logTraceOut("fillBoundaryLayerInPyClaw");
    }

<commit_msg>fixed refactoring for TimeIntervals<commit_after>/*
 * PyClaw.cpp
 *
 *  Created on: Feb 18, 2012
 *      Author: kristof
 */

#include "peanoclaw/native/SWEKernel.h"
#include "peanoclaw/Patch.h"
#include "tarch/timing/Watch.h"
#include "tarch/parallel/Node.h"

#include "peanoclaw/native/SWE_WavePropagationBlock_patch.hh"

tarch::logging::Log peanoclaw::native::SWEKernel::_log("peanoclaw::native::SWEKernel");

peanoclaw::native::SWEKernel::SWEKernel(
  SWEKernelScenario& scenario,
  peanoclaw::interSubgridCommunication::Interpolation*  interpolation,
  peanoclaw::interSubgridCommunication::Restriction*    restriction,
  peanoclaw::interSubgridCommunication::FluxCorrection* fluxCorrection
) : Numerics(interpolation, restriction, fluxCorrection),
_scenario(scenario),
_totalSolverCallbackTime(0.0)
{
  //import_array();
}

peanoclaw::native::SWEKernel::~SWEKernel()
{
}

double peanoclaw::native::SWEKernel::initializePatch(
  Patch& patch
) {
  logTraceIn( "initializePatch(...)");

  _scenario.initializePatch(patch);
  double demandedMeshWidth = _scenario.computeDemandedMeshWidth(patch);

  logTraceOutWith1Argument( "initializePatch(...)", demandedMeshWidth);
  return demandedMeshWidth;
}

double peanoclaw::native::SWEKernel::solveTimestep(Patch& patch, double maximumTimestepSize, bool useDimensionalSplitting) {
  logTraceInWith2Arguments( "solveTimestep(...)", maximumTimestepSize, useDimensionalSplitting);

  assertion2(tarch::la::greater(maximumTimestepSize, 0.0), "Timestepsize == 0 should be checked outside.", patch.getTimeIntervals().getMinimalNeighborTimeConstraint());

  tarch::timing::Watch pyclawWatch("", "", false);
  pyclawWatch.startTimer();
  double dtAndEstimatedNextDt[2];

  SWE_WavePropagationBlock_patch swe(patch);

  swe.computeNumericalFluxes();

  double dt = fmin(swe.getMaxTimestep(), maximumTimestepSize);
  double estimatedNextTimestepSize = swe.getMaxTimestep();

  swe.updateUnknowns(dt);

  pyclawWatch.stopTimer();
  _totalSolverCallbackTime += pyclawWatch.getCalendarTime();

  assertion4(
      tarch::la::greater(patch.getTimeIntervals().getTimestepSize(), 0.0)
      || tarch::la::greater(estimatedNextTimestepSize, 0.0)
      || tarch::la::equals(maximumTimestepSize, 0.0)
      || tarch::la::equals(patch.getTimeIntervals().getEstimatedNextTimestepSize(), 0.0),
      patch, maximumTimestepSize, estimatedNextTimestepSize, patch.toStringUNew());
  assertion(patch.getTimeIntervals().getTimestepSize() < std::numeric_limits<double>::infinity());

  if (tarch::la::greater(dt, 0.0)) {
    patch.getTimeIntervals().advanceInTime();
    patch.getTimeIntervals().setTimestepSize(dt);
  }
  patch.getTimeIntervals().setEstimatedNextTimestepSize(estimatedNextTimestepSize);

  logTraceOut( "solveTimestep(...)");
  return _scenario.computeDemandedMeshWidth(patch);
}

void peanoclaw::native::SWEKernel::addPatchToSolution(Patch& patch) {
}

void peanoclaw::native::SWEKernel::fillBoundaryLayer(Patch& patch, int dimension, bool setUpper) {
  logTraceInWith3Arguments("fillBoundaryLayerInPyClaw", patch, dimension, setUpper);

  logDebug("fillBoundaryLayerInPyClaw", "Setting left boundary for " << patch.getPosition() << ", dim=" << dimension << ", setUpper=" << setUpper);

   //std::cout << "------ setUpper " << setUpper << " dimension " << dimension << std::endl;
   //std::cout << patch << std::endl;
   //std::cout << "++++++" << std::endl;
   //std::cout << patch.toStringUOldWithGhostLayer() << std::endl;
   //std::cout << "||||||" << std::endl;

  // implement a wall boundary
    tarch::la::Vector<DIMENSIONS, int> src_subcellIndex;
    tarch::la::Vector<DIMENSIONS, int> dest_subcellIndex;

    if (dimension == 0) {
        for (int yi = -1; yi < patch.getSubdivisionFactor()(1)+1; yi++) {
            int xi = setUpper ? patch.getSubdivisionFactor()(0) : -1;
            src_subcellIndex(0) = xi;
            src_subcellIndex(1) = yi;
            src_subcellIndex(dimension) += setUpper ? -1 : +1;

            dest_subcellIndex(0) = xi;
            dest_subcellIndex(1) = yi;

            for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
                double q = patch.getValueUOld(src_subcellIndex, unknown);

                if (unknown == dimension + 1) {
                    patch.setValueUOld(dest_subcellIndex, unknown, -q);
                } else {
                    patch.setValueUOld(dest_subcellIndex, unknown, q);
                }
            }
        }

    } else {
        for (int xi = -1; xi < patch.getSubdivisionFactor()(0)+1; xi++) {
            int yi = setUpper ? patch.getSubdivisionFactor()(1) : -1;
            src_subcellIndex(0) = xi;
            src_subcellIndex(1) = yi;
            src_subcellIndex(dimension) += setUpper ? -1 : +1;

            dest_subcellIndex(0) = xi;
            dest_subcellIndex(1) = yi;

            for (int unknown=0; unknown < patch.getUnknownsPerSubcell(); unknown++) {
                double q = patch.getValueUOld(src_subcellIndex, unknown);

                if (unknown == dimension + 1) {
                    patch.setValueUOld(dest_subcellIndex, unknown, -q);
                } else {
                    patch.setValueUOld(dest_subcellIndex, unknown, q);
                }
            }
        }
    }

   //std::cout << "++++++" << std::endl;
   //std::cout << patch.toStringUOldWithGhostLayer() << std::endl;
   //std::cout << "||||||" << std::endl;

      logTraceOut("fillBoundaryLayerInPyClaw");
    }

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: TConnection.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: oj $ $Date: 2002-10-25 09:05:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef CONNECTIVITY_CONNECTION_HXX
#define CONNECTIVITY_CONNECTION_HXX

#ifndef _RTL_TEXTENC_H
#include <rtl/textenc.h>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE4_HXX_
#include <cppuhelper/compbase4.hxx>
#endif
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif

namespace connectivity
{
    typedef ::cppu::WeakComponentImplHelper4<   ::com::sun::star::sdbc::XConnection,
                                                ::com::sun::star::sdbc::XWarningsSupplier,
                                                ::com::sun::star::lang::XServiceInfo,
                                                ::com::sun::star::lang::XUnoTunnel
                                            > OMetaConnection_BASE;

    class SAL_NO_VTABLE OMetaConnection : public OMetaConnection_BASE
    {
    protected:
        ::osl::Mutex        m_aMutex;
        ::rtl::OUString     m_sURL;
        rtl_TextEncoding    m_nTextEncoding; // the encoding which is used for all text conversions
    public:

        static ::dbtools::OPropertyMap& getPropMap();

        OMetaConnection() : OMetaConnection_BASE(m_aMutex) ,m_nTextEncoding(RTL_TEXTENCODING_MS_1252){}

        inline rtl_TextEncoding getTextEncoding() const { return m_nTextEncoding; }
        inline ::rtl::OUString  getURL() const  { return m_sURL; }
        inline void             setURL(const ::rtl::OUString& _rsUrl) { m_sURL = _rsUrl; }

        //XUnoTunnel
        virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
    };
}
#endif // CONNECTIVITY_CONNECTION_HXX

<commit_msg>INTEGRATION: CWS insight01 (1.9.92); FILE MERGED 2004/07/05 13:41:47 oj 1.9.92.1: remove sal_NO_VTABLE<commit_after>/*************************************************************************
 *
 *  $RCSfile: TConnection.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 17:11:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef CONNECTIVITY_CONNECTION_HXX
#define CONNECTIVITY_CONNECTION_HXX

#ifndef _RTL_TEXTENC_H
#include <rtl/textenc.h>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE4_HXX_
#include <cppuhelper/compbase4.hxx>
#endif
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif

namespace connectivity
{
    typedef ::cppu::WeakComponentImplHelper4<   ::com::sun::star::sdbc::XConnection,
                                                ::com::sun::star::sdbc::XWarningsSupplier,
                                                ::com::sun::star::lang::XServiceInfo,
                                                ::com::sun::star::lang::XUnoTunnel
                                            > OMetaConnection_BASE;

    class OMetaConnection : public OMetaConnection_BASE
    {
    protected:
        ::osl::Mutex        m_aMutex;
        ::rtl::OUString     m_sURL;
        rtl_TextEncoding    m_nTextEncoding; // the encoding which is used for all text conversions
    public:

        static ::dbtools::OPropertyMap& getPropMap();

        OMetaConnection() : OMetaConnection_BASE(m_aMutex) ,m_nTextEncoding(RTL_TEXTENCODING_MS_1252){}

        inline rtl_TextEncoding getTextEncoding() const { return m_nTextEncoding; }
        inline ::rtl::OUString  getURL() const  { return m_sURL; }
        inline void             setURL(const ::rtl::OUString& _rsUrl) { m_sURL = _rsUrl; }

        //XUnoTunnel
        virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);
        static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
    };
}
#endif // CONNECTIVITY_CONNECTION_HXX

<|endoftext|>


<commit_before>#include "GameController.h"

extern "C" {
#include "gba.h"
#include "renderers/video-software.h"
}

using namespace QGBA;

GameController::GameController(QObject* parent)
	: QObject(parent)
	, m_drawContext(256, 256, QImage::Format_RGB32)
	, m_audioContext(0)
{
	m_renderer = new GBAVideoSoftwareRenderer;
	GBAVideoSoftwareRendererCreate(m_renderer);
	m_renderer->outputBuffer = (color_t*) m_drawContext.bits();
	m_renderer->outputBufferStride = m_drawContext.bytesPerLine() / 4;
	m_threadContext.useDebugger = 0;
	m_threadContext.frameskip = 0;
	m_threadContext.renderer = &m_renderer->d;
	m_threadContext.frameskip = 0;
	m_threadContext.sync.videoFrameWait = 0;
	m_threadContext.sync.audioWait = 1;
	m_threadContext.startCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->audioDeviceAvailable(&context->gba->audio);
	};
	m_threadContext.cleanCallback = 0;
	m_threadContext.frameCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->frameAvailable(controller->m_drawContext);
	};
	m_threadContext.userData = this;
	m_threadContext.rewindBufferCapacity = 0;
}

GameController::~GameController() {
	GBAThreadEnd(&m_threadContext);
	GBAThreadJoin(&m_threadContext);
	delete m_renderer;
}

bool GameController::loadGame(const QString& path) {
	m_rom = new QFile(path);
	if (!m_rom->open(QIODevice::ReadOnly)) {
		delete m_rom;
		m_rom = 0;
		return false;
	}
	m_threadContext.fd = m_rom->handle();
	m_threadContext.fname = path.toLocal8Bit().constData();
	GBAThreadStart(&m_threadContext);
	return true;
}

void GameController::keyPressed(int key) {
	int mappedKey = 1 << key;
	m_threadContext.activeKeys |= mappedKey;
}

void GameController::keyReleased(int key) {
	int mappedKey = 1 << key;
	m_threadContext.activeKeys &= ~mappedKey;
}
<commit_msg>Use an initializer for GBAThread in Qt<commit_after>#include "GameController.h"

extern "C" {
#include "gba.h"
#include "renderers/video-software.h"
}

using namespace QGBA;

GameController::GameController(QObject* parent)
	: QObject(parent)
	, m_drawContext(256, 256, QImage::Format_RGB32)
	, m_audioContext(0)
{
	m_renderer = new GBAVideoSoftwareRenderer;
	GBAVideoSoftwareRendererCreate(m_renderer);
	m_renderer->outputBuffer = (color_t*) m_drawContext.bits();
	m_renderer->outputBufferStride = m_drawContext.bytesPerLine() / 4;
	m_threadContext = {
		.useDebugger = 0,
		.frameskip = 0,
		.biosFd = -1,
		.renderer = &m_renderer->d,
		.sync.videoFrameWait = 0,
		.sync.audioWait = 1,
		.userData = this,
		.rewindBufferCapacity = 0
	};
	m_threadContext.startCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->audioDeviceAvailable(&context->gba->audio);
	};
	m_threadContext.frameCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->frameAvailable(controller->m_drawContext);
	};
}

GameController::~GameController() {
	GBAThreadEnd(&m_threadContext);
	GBAThreadJoin(&m_threadContext);
	delete m_renderer;
}

bool GameController::loadGame(const QString& path) {
	m_rom = new QFile(path);
	if (!m_rom->open(QIODevice::ReadOnly)) {
		delete m_rom;
		m_rom = 0;
		return false;
	}
	m_threadContext.fd = m_rom->handle();
	m_threadContext.fname = path.toLocal8Bit().constData();
	GBAThreadStart(&m_threadContext);
	return true;
}

void GameController::keyPressed(int key) {
	int mappedKey = 1 << key;
	m_threadContext.activeKeys |= mappedKey;
}

void GameController::keyReleased(int key) {
	int mappedKey = 1 << key;
	m_threadContext.activeKeys &= ~mappedKey;
}
<|endoftext|>


<commit_before>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "compression_filter.h"

#include <vector>

#include "swganh/network/session.h"

using namespace swganh::network;
using swganh::ByteBuffer;

void CompressionFilter::operator()(Session* session, ByteBuffer* message)
{
    if(message->size() <= session->receive_buffer_size() - 20) {
        message->write<uint8_t>(0); // not compressed
        return;
    }

    // Determine the offset to begin compressing data at
    uint16_t offset = (message->peek<uint8_t>() == 0x00) ? 2 : 1;

    memset((void*)&zstream_, 0, sizeof(z_stream));

    zbuffer_.resize(session->receive_buffer_size());
    zbuffer_.write(0, message->data(), offset);

    deflateInit(&zstream_, Z_DEFAULT_COMPRESSION);

    zstream_.next_in = reinterpret_cast<Bytef *>(message->data() + offset);
    zstream_.avail_in = message->size() - offset;
    zstream_.next_out = reinterpret_cast<Bytef *>(zbuffer_.data() + offset);
    zstream_.avail_out = zbuffer_.size() - offset;

    deflate(&zstream_, Z_FINISH);

    zbuffer_.resize(zstream_.total_out);

    deflateEnd(&zstream_);

    message->swap(zbuffer_);
    message->write<uint8_t>(1);
}
<commit_msg>Fixed issue with sizes/offsets in compression<commit_after>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "compression_filter.h"

#include <vector>

#include "swganh/network/session.h"

using namespace swganh::network;
using swganh::ByteBuffer;

void CompressionFilter::operator()(Session* session, ByteBuffer* message)
{
    if(message->size() <= session->receive_buffer_size() - 20) {
        message->write<uint8_t>(0); // not compressed
        return;
    }

    // Determine the offset to begin compressing data at
    uint16_t offset = (message->peek<uint8_t>() == 0x00) ? 2 : 1;

    memset((void*)&zstream_, 0, sizeof(z_stream));

    zbuffer_.resize(session->receive_buffer_size());
    zbuffer_.write(0, message->data(), offset);

    deflateInit(&zstream_, Z_DEFAULT_COMPRESSION);

    zstream_.next_in = reinterpret_cast<Bytef *>(message->data() + offset);
    zstream_.avail_in = message->size() - offset;
    zstream_.next_out = reinterpret_cast<Bytef *>(zbuffer_.data() + offset);
    zstream_.avail_out = zbuffer_.size() - offset;

    deflate(&zstream_, Z_FINISH);

    zbuffer_.resize(zstream_.total_out + offset);

    deflateEnd(&zstream_);

    message->swap(zbuffer_);
    message->write_position(message->size());
    message->write<uint8_t>(1);
}
<|endoftext|>


<commit_before>#include <fstream>
#include <gtest/gtest.h>
#include <stdexcept>
#include <string>
#include <test/utility.hpp>

using cmdstan::test::convert_model_path;
using cmdstan::test::multiple_command_separator;
using cmdstan::test::run_command;
using cmdstan::test::run_command_output;

class CmdStan : public testing::Test {
public:
  void SetUp() {
    model_path.emplace_back("src");
    model_path.emplace_back("test");
    model_path.emplace_back("test-models");
    model_path.emplace_back("gq_model");

    data_file_path.emplace_back("src");
    data_file_path.emplace_back("test");
    data_file_path.emplace_back("test-models");
    data_file_path.emplace_back("gq_model.data.json");

    model_path_2.emplace_back("src");
    model_path_2.emplace_back("test");
    model_path_2.emplace_back("test-models");
    model_path_2.emplace_back("test_model");

    output_file_path.emplace_back("/dev");
    output_file_path.emplace_back("null");

    fitted_params_file_path.emplace_back("src");
    fitted_params_file_path.emplace_back("test");
    fitted_params_file_path.emplace_back("test-models");
    fitted_params_file_path.emplace_back("gq_model_output.csv");

    fitted_params_file_path_2.emplace_back("src");
    fitted_params_file_path_2.emplace_back("test");
    fitted_params_file_path_2.emplace_back("test-models");
    fitted_params_file_path_2.emplace_back("test_model_output.csv");

    fitted_params_file_path_empty.emplace_back("src");
    fitted_params_file_path_empty.emplace_back("test");
    fitted_params_file_path_empty.emplace_back("test-models");
    fitted_params_file_path_empty.emplace_back("empty.csv");
  }

  std::vector<std::string> model_path;
  std::vector<std::string> data_file_path;
  std::vector<std::string> model_path_2;
  std::vector<std::string> output_file_path;
  std::vector<std::string> fitted_params_file_path;
  std::vector<std::string> fitted_params_file_path_2;
  std::vector<std::string> fitted_params_file_path_empty;

};

TEST_F(CmdStan, generate_quantities_good) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path);
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_EQ(false, out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_nodata) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_empty)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_EQ(true, out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_no_gqs) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities "
     << " fitted_params=" << convert_model_path(fitted_params_file_path_2)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_EQ(true, out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_2)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_EQ(true, out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv_2) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_EQ(true, out.hasError);
}
<commit_msg>unit test fix - again<commit_after>#include <fstream>
#include <gtest/gtest.h>
#include <stdexcept>
#include <string>
#include <test/utility.hpp>

using cmdstan::test::convert_model_path;
using cmdstan::test::multiple_command_separator;
using cmdstan::test::run_command;
using cmdstan::test::run_command_output;

class CmdStan : public testing::Test {
public:
  void SetUp() {
    model_path.emplace_back("src");
    model_path.emplace_back("test");
    model_path.emplace_back("test-models");
    model_path.emplace_back("gq_model");

    data_file_path.emplace_back("src");
    data_file_path.emplace_back("test");
    data_file_path.emplace_back("test-models");
    data_file_path.emplace_back("gq_model.data.json");

    model_path_2.emplace_back("src");
    model_path_2.emplace_back("test");
    model_path_2.emplace_back("test-models");
    model_path_2.emplace_back("test_model");

    output_file_path.emplace_back("/dev");
    output_file_path.emplace_back("null");

    fitted_params_file_path.emplace_back("src");
    fitted_params_file_path.emplace_back("test");
    fitted_params_file_path.emplace_back("test-models");
    fitted_params_file_path.emplace_back("gq_model_output.csv");

    fitted_params_file_path_2.emplace_back("src");
    fitted_params_file_path_2.emplace_back("test");
    fitted_params_file_path_2.emplace_back("test-models");
    fitted_params_file_path_2.emplace_back("test_model_output.csv");

    fitted_params_file_path_empty.emplace_back("src");
    fitted_params_file_path_empty.emplace_back("test");
    fitted_params_file_path_empty.emplace_back("test-models");
    fitted_params_file_path_empty.emplace_back("empty.csv");
  }

  std::vector<std::string> model_path;
  std::vector<std::string> data_file_path;
  std::vector<std::string> model_path_2;
  std::vector<std::string> output_file_path;
  std::vector<std::string> fitted_params_file_path;
  std::vector<std::string> fitted_params_file_path_2;
  std::vector<std::string> fitted_params_file_path_empty;

};

TEST_F(CmdStan, generate_quantities_good) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path);
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_FALSE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_nodata) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_empty)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_no_gqs) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities "
     << " fitted_params=" << convert_model_path(fitted_params_file_path_2)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_2)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv_2) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}
<|endoftext|>


<commit_before>#include "../../SDP_Solver.hxx"

// The main solver loop

void cholesky_decomposition(const Block_Diagonal_Matrix &A,
                            Block_Diagonal_Matrix &L);

void print_header(const Verbosity &verbosity);
void print_iteration(
  const int &iteration, const El::BigFloat &mu,
  const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
  const El::BigFloat &beta_corrector, const SDP_Solver &sdp_solver,
  const std::chrono::time_point<std::chrono::high_resolution_clock>
    &solver_start_time,
  const Verbosity &verbosity);

void compute_objectives(const SDP &sdp, const Block_Vector &x,
                        const Block_Vector &y, El::BigFloat &primal_objective,
                        El::BigFloat &dual_objective,
                        El::BigFloat &duality_gap, Timers &timers);

void compute_bilinear_pairings(
  const Block_Diagonal_Matrix &X_cholesky, const Block_Diagonal_Matrix &Y,
  const std::vector<El::Matrix<El::BigFloat>> &bilinear_bases,
  std::vector<El::DistMatrix<El::BigFloat>> &workspace,
  Block_Diagonal_Matrix &bilinear_pairings_X_inv,
  Block_Diagonal_Matrix &bilinear_pairings_Y, Timers &timers);

void compute_feasible_and_termination(
  const SDP_Solver_Parameters &parameters, const El::BigFloat &primal_error,
  const El::BigFloat &dual_error, const El::BigFloat &duality_gap,
  const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
  const int &iteration,
  const std::chrono::time_point<std::chrono::high_resolution_clock>
    &solver_start_time,
  bool &is_primal_and_dual_feasible,
  SDP_Solver_Terminate_Reason &terminate_reason, bool &terminate_now);

void compute_dual_residues_and_error(
  const Block_Info &block_info, const SDP &sdp, const Block_Vector &y,
  const Block_Diagonal_Matrix &bilinear_pairings_Y,
  Block_Vector &dual_residues, El::BigFloat &dual_error, Timers &timers);

void compute_primal_residues_and_error_P_Ax_X(
  const Block_Info &block_info, const SDP &sdp, const Block_Vector &x,
  const Block_Diagonal_Matrix &X, Block_Diagonal_Matrix &primal_residues,
  El::BigFloat &primal_error_P, Timers &timers);

void compute_primal_residues_and_error_p_b_Bx(const Block_Info &block_info,
                                              const SDP &sdp,
                                              const Block_Vector &x,
                                              Block_Vector &primal_residue_p,
                                              El::BigFloat &primal_error_p);

SDP_Solver_Terminate_Reason
SDP_Solver::run(const SDP_Solver_Parameters &parameters,
                const Block_Info &block_info, const SDP &sdp,
                const El::Grid &grid, Timers &timers)
{
  SDP_Solver_Terminate_Reason terminate_reason(
    SDP_Solver_Terminate_Reason::MaxIterationsExceeded);
  auto &solver_timer(timers.add_and_start("Solver runtime"));
  auto &initialize_timer(timers.add_and_start("run.initialize"));

  El::BigFloat primal_step_length(0), dual_step_length(0);

  Block_Diagonal_Matrix X_cholesky(X), Y_cholesky(X);

  // Bilinear pairings needed for computing the Schur complement
  // matrix.  For example,
  //
  //   BilinearPairingsXInv.blocks[b].elt(
  //     (d_j+1) s + k1,
  //     (d_j+1) r + k2
  //   ) = v_{b,k1}^T (X.blocks[b]^{-1})^{(s,r)} v_{b,k2}
  //
  //     0 <= k1,k2 <= block_info.degrees[j] = d_j
  //     0 <= s,r < block_info.dimensions[j] = m_j
  //
  // where j corresponds to b and M^{(s,r)} denotes the (s,r)-th
  // (d_j+1)x(d_j+1) block of M.
  //
  // BilinearPairingsXInv has one block for each block of X.  The
  // dimension of BilinearPairingsXInv.block[b] is (d_j+1)*m_j.  See
  // SDP.h for more information on d_j and m_j.

  Block_Diagonal_Matrix bilinear_pairings_X_inv(
    block_info.bilinear_pairing_block_sizes, block_info.block_indices,
    block_info.schur_block_sizes.size(), grid);

  // BilinearPairingsY is analogous to BilinearPairingsXInv, with
  // X^{-1} -> Y.

  Block_Diagonal_Matrix bilinear_pairings_Y(bilinear_pairings_X_inv);

  // Additional workspace variables used in step_length()
  std::vector<El::DistMatrix<El::BigFloat>> bilinear_pairings_workspace;
  bilinear_pairings_workspace.reserve(X.blocks.size());
  {
    auto bilinear_pairings_X_inv_block(bilinear_pairings_X_inv.blocks.begin());
    for(auto &X_block : X.blocks)
      {
        bilinear_pairings_workspace.emplace_back(
          X_block.Height(), bilinear_pairings_X_inv_block->Width(), grid);
        ++bilinear_pairings_X_inv_block;
      }
  }
  print_header(parameters.verbosity);

  std::size_t total_psd_rows(
    std::accumulate(block_info.psd_matrix_block_sizes.begin(),
                    block_info.psd_matrix_block_sizes.end(), size_t(0)));

  initialize_timer.stop();
  auto last_checkpoint_time(std::chrono::high_resolution_clock::now());
  for(size_t iteration = 1;; ++iteration)
    {
      El::byte checkpoint_now(
        std::chrono::duration_cast<std::chrono::seconds>(
          std::chrono::high_resolution_clock::now() - last_checkpoint_time)
          .count()
        >= parameters.checkpoint_interval);
      // Time varies between cores, so follow the decision of the root.
      El::mpi::Broadcast(checkpoint_now, 0, El::mpi::COMM_WORLD);
      if(checkpoint_now == true)
        {
          save_checkpoint(parameters);
          last_checkpoint_time = std::chrono::high_resolution_clock::now();
        }

      compute_objectives(sdp, x, y, primal_objective, dual_objective,
                         duality_gap, timers);

      auto &cholesky_decomposition_timer(
        timers.add_and_start("run.choleskyDecomposition"));
      cholesky_decomposition(X, X_cholesky);
      cholesky_decomposition(Y, Y_cholesky);
      cholesky_decomposition_timer.stop();

      compute_bilinear_pairings(
        X_cholesky, Y, sdp.bilinear_bases_local, bilinear_pairings_workspace,
        bilinear_pairings_X_inv, bilinear_pairings_Y, timers);

      compute_dual_residues_and_error(block_info, sdp, y, bilinear_pairings_Y,
                                      dual_residues, dual_error, timers);
      compute_primal_residues_and_error_P_Ax_X(
        block_info, sdp, x, X, primal_residues, primal_error_P, timers);

      // use y to set the sizes of primal_residue_p.  The data is
      // overwritten in compute_primal_residues_and_error_p.
      Block_Vector primal_residue_p(y);
      compute_primal_residues_and_error_p_b_Bx(
        block_info, sdp, x, primal_residue_p, primal_error_p);

      bool terminate_now, is_primal_and_dual_feasible;
      compute_feasible_and_termination(
        parameters, primal_error(), dual_error, duality_gap,
        primal_step_length, dual_step_length, iteration,
        solver_timer.start_time, is_primal_and_dual_feasible, terminate_reason,
        terminate_now);
      if(terminate_now)
        {
          break;
        }

      El::BigFloat mu, beta_corrector;
      step(parameters, total_psd_rows, is_primal_and_dual_feasible, block_info,
           sdp, grid, X_cholesky, Y_cholesky, bilinear_pairings_X_inv,
           bilinear_pairings_Y, primal_residue_p, mu, beta_corrector,
           primal_step_length, dual_step_length, terminate_now, timers);
      if(terminate_now)
        {
          terminate_reason
            = SDP_Solver_Terminate_Reason::MaxComplementarityExceeded;
          break;
        }
      print_iteration(iteration, mu, primal_step_length, dual_step_length,
                      beta_corrector, *this, solver_timer.start_time,
                      parameters.verbosity);
    }

  // Never reached
  solver_timer.stop();
  return terminate_reason;
}
<commit_msg>Remove wrong comment<commit_after>#include "../../SDP_Solver.hxx"

// The main solver loop

void cholesky_decomposition(const Block_Diagonal_Matrix &A,
                            Block_Diagonal_Matrix &L);

void print_header(const Verbosity &verbosity);
void print_iteration(
  const int &iteration, const El::BigFloat &mu,
  const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
  const El::BigFloat &beta_corrector, const SDP_Solver &sdp_solver,
  const std::chrono::time_point<std::chrono::high_resolution_clock>
    &solver_start_time,
  const Verbosity &verbosity);

void compute_objectives(const SDP &sdp, const Block_Vector &x,
                        const Block_Vector &y, El::BigFloat &primal_objective,
                        El::BigFloat &dual_objective,
                        El::BigFloat &duality_gap, Timers &timers);

void compute_bilinear_pairings(
  const Block_Diagonal_Matrix &X_cholesky, const Block_Diagonal_Matrix &Y,
  const std::vector<El::Matrix<El::BigFloat>> &bilinear_bases,
  std::vector<El::DistMatrix<El::BigFloat>> &workspace,
  Block_Diagonal_Matrix &bilinear_pairings_X_inv,
  Block_Diagonal_Matrix &bilinear_pairings_Y, Timers &timers);

void compute_feasible_and_termination(
  const SDP_Solver_Parameters &parameters, const El::BigFloat &primal_error,
  const El::BigFloat &dual_error, const El::BigFloat &duality_gap,
  const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
  const int &iteration,
  const std::chrono::time_point<std::chrono::high_resolution_clock>
    &solver_start_time,
  bool &is_primal_and_dual_feasible,
  SDP_Solver_Terminate_Reason &terminate_reason, bool &terminate_now);

void compute_dual_residues_and_error(
  const Block_Info &block_info, const SDP &sdp, const Block_Vector &y,
  const Block_Diagonal_Matrix &bilinear_pairings_Y,
  Block_Vector &dual_residues, El::BigFloat &dual_error, Timers &timers);

void compute_primal_residues_and_error_P_Ax_X(
  const Block_Info &block_info, const SDP &sdp, const Block_Vector &x,
  const Block_Diagonal_Matrix &X, Block_Diagonal_Matrix &primal_residues,
  El::BigFloat &primal_error_P, Timers &timers);

void compute_primal_residues_and_error_p_b_Bx(const Block_Info &block_info,
                                              const SDP &sdp,
                                              const Block_Vector &x,
                                              Block_Vector &primal_residue_p,
                                              El::BigFloat &primal_error_p);

SDP_Solver_Terminate_Reason
SDP_Solver::run(const SDP_Solver_Parameters &parameters,
                const Block_Info &block_info, const SDP &sdp,
                const El::Grid &grid, Timers &timers)
{
  SDP_Solver_Terminate_Reason terminate_reason(
    SDP_Solver_Terminate_Reason::MaxIterationsExceeded);
  auto &solver_timer(timers.add_and_start("Solver runtime"));
  auto &initialize_timer(timers.add_and_start("run.initialize"));

  El::BigFloat primal_step_length(0), dual_step_length(0);

  Block_Diagonal_Matrix X_cholesky(X), Y_cholesky(X);

  // Bilinear pairings needed for computing the Schur complement
  // matrix.  For example,
  //
  //   BilinearPairingsXInv.blocks[b].elt(
  //     (d_j+1) s + k1,
  //     (d_j+1) r + k2
  //   ) = v_{b,k1}^T (X.blocks[b]^{-1})^{(s,r)} v_{b,k2}
  //
  //     0 <= k1,k2 <= block_info.degrees[j] = d_j
  //     0 <= s,r < block_info.dimensions[j] = m_j
  //
  // where j corresponds to b and M^{(s,r)} denotes the (s,r)-th
  // (d_j+1)x(d_j+1) block of M.
  //
  // BilinearPairingsXInv has one block for each block of X.  The
  // dimension of BilinearPairingsXInv.block[b] is (d_j+1)*m_j.  See
  // SDP.h for more information on d_j and m_j.

  Block_Diagonal_Matrix bilinear_pairings_X_inv(
    block_info.bilinear_pairing_block_sizes, block_info.block_indices,
    block_info.schur_block_sizes.size(), grid);

  // BilinearPairingsY is analogous to BilinearPairingsXInv, with
  // X^{-1} -> Y.

  Block_Diagonal_Matrix bilinear_pairings_Y(bilinear_pairings_X_inv);

  // Additional workspace variables used in step_length()
  std::vector<El::DistMatrix<El::BigFloat>> bilinear_pairings_workspace;
  bilinear_pairings_workspace.reserve(X.blocks.size());
  {
    auto bilinear_pairings_X_inv_block(bilinear_pairings_X_inv.blocks.begin());
    for(auto &X_block : X.blocks)
      {
        bilinear_pairings_workspace.emplace_back(
          X_block.Height(), bilinear_pairings_X_inv_block->Width(), grid);
        ++bilinear_pairings_X_inv_block;
      }
  }
  print_header(parameters.verbosity);

  std::size_t total_psd_rows(
    std::accumulate(block_info.psd_matrix_block_sizes.begin(),
                    block_info.psd_matrix_block_sizes.end(), size_t(0)));

  initialize_timer.stop();
  auto last_checkpoint_time(std::chrono::high_resolution_clock::now());
  for(size_t iteration = 1;; ++iteration)
    {
      El::byte checkpoint_now(
        std::chrono::duration_cast<std::chrono::seconds>(
          std::chrono::high_resolution_clock::now() - last_checkpoint_time)
          .count()
        >= parameters.checkpoint_interval);
      // Time varies between cores, so follow the decision of the root.
      El::mpi::Broadcast(checkpoint_now, 0, El::mpi::COMM_WORLD);
      if(checkpoint_now == true)
        {
          save_checkpoint(parameters);
          last_checkpoint_time = std::chrono::high_resolution_clock::now();
        }

      compute_objectives(sdp, x, y, primal_objective, dual_objective,
                         duality_gap, timers);

      auto &cholesky_decomposition_timer(
        timers.add_and_start("run.choleskyDecomposition"));
      cholesky_decomposition(X, X_cholesky);
      cholesky_decomposition(Y, Y_cholesky);
      cholesky_decomposition_timer.stop();

      compute_bilinear_pairings(
        X_cholesky, Y, sdp.bilinear_bases_local, bilinear_pairings_workspace,
        bilinear_pairings_X_inv, bilinear_pairings_Y, timers);

      compute_dual_residues_and_error(block_info, sdp, y, bilinear_pairings_Y,
                                      dual_residues, dual_error, timers);
      compute_primal_residues_and_error_P_Ax_X(
        block_info, sdp, x, X, primal_residues, primal_error_P, timers);

      // use y to set the sizes of primal_residue_p.  The data is
      // overwritten in compute_primal_residues_and_error_p.
      Block_Vector primal_residue_p(y);
      compute_primal_residues_and_error_p_b_Bx(
        block_info, sdp, x, primal_residue_p, primal_error_p);

      bool terminate_now, is_primal_and_dual_feasible;
      compute_feasible_and_termination(
        parameters, primal_error(), dual_error, duality_gap,
        primal_step_length, dual_step_length, iteration,
        solver_timer.start_time, is_primal_and_dual_feasible, terminate_reason,
        terminate_now);
      if(terminate_now)
        {
          break;
        }

      El::BigFloat mu, beta_corrector;
      step(parameters, total_psd_rows, is_primal_and_dual_feasible, block_info,
           sdp, grid, X_cholesky, Y_cholesky, bilinear_pairings_X_inv,
           bilinear_pairings_Y, primal_residue_p, mu, beta_corrector,
           primal_step_length, dual_step_length, terminate_now, timers);
      if(terminate_now)
        {
          terminate_reason
            = SDP_Solver_Terminate_Reason::MaxComplementarityExceeded;
          break;
        }
      print_iteration(iteration, mu, primal_step_length, dual_step_length,
                      beta_corrector, *this, solver_timer.start_time,
                      parameters.verbosity);
    }
  solver_timer.stop();
  return terminate_reason;
}
<|endoftext|>