Exemplo n.º 1
0
//==============================================================================
// Vulkan破棄
//==============================================================================
void destroyVulkan()
{
	for(auto& frameBuffer : g_frameBuffers)
	{
		vkDestroyFramebuffer(g_VulkanDevice, frameBuffer, nullptr);
	}

	if(g_depthBufferTexture.view)
	{
		vkDestroyImageView(g_VulkanDevice, g_depthBufferTexture.view, nullptr);
	}

	if(g_depthBufferTexture.image)
	{
		vkDestroyImage(g_VulkanDevice, g_depthBufferTexture.image, nullptr);
	}

	if(g_depthBufferTexture.memory)
	{
		vkFreeMemory(g_VulkanDevice, g_depthBufferTexture.memory, nullptr);
	}

	if(g_commandBuffers.empty() == false)
	{
		vkFreeCommandBuffers(g_VulkanDevice, g_VulkanCommandPool, SWAP_CHAIN_COUNT, g_commandBuffers.data());
	}

	if(g_VulkanCommandPool)
	{
		vkDestroyCommandPool(g_VulkanDevice, g_VulkanCommandPool, nullptr);
	}

	if(g_VulkanSemahoreRenderComplete)
	{
		vkDestroySemaphore(g_VulkanDevice, g_VulkanSemahoreRenderComplete, nullptr);
	}

	if(g_VulkanFence)
	{
		vkDestroyFence(g_VulkanDevice, g_VulkanFence, nullptr);
	}

	if(g_VulkanSwapChain)
	{
		vkDestroySwapchainKHR(g_VulkanDevice, g_VulkanSwapChain, nullptr);
	}

	if(g_VulkanSurface)
	{
		vkDestroySurfaceKHR(g_VulkanInstance, g_VulkanSurface, nullptr);
	}

	if(g_VulkanDevice)
	{
		vkDestroyDevice(g_VulkanDevice, nullptr);
	}

	if(g_VulkanInstance)
	{
		vkDestroyInstance(g_VulkanInstance, nullptr);
	}

	g_frameBuffers.clear();
	g_commandBuffers.clear();

	g_VulkanSurface = nullptr;
	g_VulkanSwapChain = nullptr;
	g_VulkanCommandPool = nullptr;
	g_VulkanSemahoreRenderComplete = nullptr;
	g_VulkanFence = nullptr;
	g_VulkanQueue = nullptr;
	g_VulkanDevice = nullptr;
	g_VulkanInstance = nullptr;
}
Exemplo n.º 2
0
    /// <summary>
    /// Parses information about endpoints from a WSDL document.
    /// </summary>
    /// <param name="wsdContent">Web service definition content previously loaded from a file.</param>
    /// <param name="bindings">The bindings assigned to the endpoints.</param>
    /// <param name="targetNamespace">Where to save the target namespace.</param>
    /// <param name="serviceName">Where to save the service name.</param>
    /// <param name="endpointsAddrs">Where to save the addresses of the endpoints.</param>
    /// <remarks>
    /// Assumes the usage of HTTP & SOAP, but does not check if the document is thoroughly
    /// well formed. Because this library is meant to integrate with wsutil.exe generated code,
    /// the WSDL document is expected to follow the specification in http://www.w3.org/TR/wsdl.
    /// Also, the bindings MUST BE declared in the target namespace using the prefix 'tns'.
    /// </remarks>
    static void ParseEndpointsFromWSD(
        const std::vector<char> &wsdContent,
        const ServiceBindings &bindings,
        string &targetNamespace,
        string &serviceName,
        std::vector<SvcEndpointInfo> &endpointsInfo)
    {
        using namespace Poco;

        CALL_STACK_TRACE;

        try
        {
            // If anything goes wrong, do not keep any previous content in the output:
            targetNamespace.clear();
            serviceName.clear();
            endpointsInfo.clear();

            // Fundamental namespaces URI's:
            static const string wsdlNs("http://schemas.xmlsoap.org/wsdl/"),
                                soapNs("http://schemas.xmlsoap.org/wsdl/soap/");

            XML::NamespaceSupport nsmap;
            nsmap.declarePrefix("wsdl", wsdlNs);
            nsmap.declarePrefix("soap", soapNs);

            // Parse XML from memory:
            XML::DOMParser parser;
            parser.setFeature(XML::SAXParser::FEATURE_NAMESPACE_PREFIXES, true);
            parser.setFeature(XML::SAXParser::FEATURE_NAMESPACES, true);
            AutoPtr<XML::Document> document = parser.parseMemory(wsdContent.data(), wsdContent.size());

            // Get /wsdl:definitions
            auto definitions = static_cast<XML::Element *> (
                document->getNodeByPathNS("/wsdl:definitions", nsmap)
            );

            if (definitions == nullptr)
            {
                throw AppException<std::runtime_error>(
                    "Web service definition is not compliant",
                    "The WSDL definitions element is missing"
                );
            }

            // Get /wsdl:definitions[@targetNamespace]
            auto attr = definitions->getAttributeNode("targetNamespace");
            if (attr != nullptr)
            {
                targetNamespace = attr->nodeValue();
                nsmap.declarePrefix("tns", targetNamespace);
            }
            else
            {
                throw AppException<std::runtime_error>(
                    "Web service definition is not compliant",
                    "The target namespace is missing from WSDL document"
                );
            }

            // Get /wsdl:definitions/wsdl:service
            auto svcElement = definitions->getChildElementNS(wsdlNs, "service");
            if (svcElement == nullptr)
            {
                throw AppException<std::runtime_error>(
                    "Web service definition is not compliant",
                    "The WSDL service element is missing from document"
                );
            }

            // Get /wsdl:definitions/wsdl:service[@name]
            attr = svcElement->getAttributeNode("name");
            if (attr != nullptr)
                serviceName = attr->nodeValue();
            else
            {
                throw AppException<std::runtime_error>(
                    "Web service definition is not compliant",
                    "The attribute \'name\' was missing from the WSDL service element"
                );
            }

            // Get the /wsdl:definitions/wsdl:service/wsdl:port' elements:
            AutoPtr<XML::NodeList> portNodes = svcElement->getElementsByTagNameNS(wsdlNs, "port");

            if (portNodes->length() == 0)
            {
                throw AppException<std::runtime_error>(
                    "Web service definition is not compliant",
                    "No valid specification for endpoint has been found"
                );
            }

            // Iterate over each endpoint specification:
            for (unsigned long idx = 0; idx < portNodes->length(); ++idx)
            {
                SvcEndpointInfo endpoint;

                auto portElement = static_cast<XML::Element *> (portNodes->item(idx));

                // Get /wsdl:definitions/wsdl:service/wsdl:port[@name]
                attr = portElement->getAttributeNode("name");
                if (attr != nullptr)
                    endpoint.portName = attr->nodeValue();
                else
                {
                    std::ostringstream oss;
                    oss << "Attribute \'name\' is missing from WSDL port element in service \'" << serviceName << '\'';
                    throw AppException<std::runtime_error>("Web service definition is not compliant", oss.str());
                }

                // Get /wsdl:definitions/wsdl:service/wsdl:port[@binding]
                attr = portElement->getAttributeNode("binding");
                if (attr == nullptr)
                {
                    std::ostringstream oss;
                    oss << "Attribute \'binding\' is missing from WSDL port \'" << endpoint.portName
                        << "\' in service \'" << serviceName << '\'';

                    throw AppException<std::runtime_error>("Web service definition is not compliant", oss.str());
                }

                if (nsmap.processName(attr->nodeValue(), endpoint.bindingNs, endpoint.bindingName, false) == false)
                {
                    std::ostringstream oss;
                    oss << "Could not resolve WSDL binding \'" << attr->nodeValue()
                        << "\' of port \'" << endpoint.portName
                        << "\' in service \'" << serviceName << '\'';

                    throw AppException<std::runtime_error>("Web service definition is not compliant", oss.str());
                }
                        
                // For the assigned binding, get the implementations
                auto svcForBind = bindings.GetImplementation(endpoint.bindingName);

                if (svcForBind.get() != nullptr)
                    endpoint.implementations.swap(svcForBind);
                else
                {// If no implementation has been found for the endpoint binding:
                    std::ostringstream oss;
                    oss << "The implementation sets provided for endpoint bindings "
                            "had no match for port \'" << endpoint.portName
                        << "\' with assigned binding \'" << endpoint.bindingName
                        << "\' in service \'" << serviceName
                        << "\', hence this endpoint cannot be created";

                    Logger::Write(oss.str(), Logger::PRIO_NOTICE);
                    continue; // skip to the next endpoint
                }

                // Get /wsdl:definitions/wsdl:service/wsdl:port/soap:address[@location]
                attr = static_cast<XML::Attr *> (portElement->getNodeByPath("/soap:address[@location]"));
                if (attr != nullptr)
                    endpoint.address = attr->nodeValue();
                else
                {
                    std::ostringstream oss;
                    oss << "Endpoint soap address not found for WSDL port \'" << endpoint.portName
                        << "\' in service \'" << serviceName << '\'';

                    throw AppException<std::runtime_error>("Web service definition is not compliant", oss.str());
                }

                endpointsInfo.push_back(std::move(endpoint));
            }// for loop end

            if (endpointsInfo.empty())
            {
                throw AppException<std::runtime_error>(
                    "No endpoints could be created from the provided WSDL "
                    "and mapped implementations for bindings"
                );
            }
        }
        catch (IAppException &)
        {
            throw; // just forward exceptions regarding errors known to have been previously handled
        }
        catch (Poco::Exception &ex)
        {
            std::ostringstream oss;
            oss << "POCO C++ library reported: " << ex.message();
            throw AppException<std::runtime_error>("Failed to parse web service definition", oss.str());
        }
        catch (std::exception &ex)
        {
            std::ostringstream oss;
            oss << "Generic failure when parsing web service definition: " << ex.what();
            throw AppException<std::runtime_error>(oss.str());
        }
    }
Exemplo n.º 3
0
void microfacetFourierSeries(Float mu_o, Float mu_i, std::complex<Float> eta_,
                             Float alpha, size_t n, Float relerr,
                             std::vector<Float> &result) {
    bool reflect = -mu_i * mu_o > 0;

    /* Compute the 'A' and 'B' constants, as well as the critical azimuth */
    Float A, B;
    Float sinMu2 = math::safe_sqrt((1 - mu_i * mu_i) * (1 - mu_o * mu_o));

    bool conductor = (eta_.imag() != 0.0f);
    std::complex<Float> eta =
        (-mu_i > 0 || conductor) ? eta_ : std::complex<Float>(1) / eta_;

    if (reflect) {
        Float temp = 1.0f / (alpha * (mu_i - mu_o));
        A = (mu_i * mu_i + mu_o * mu_o - 2) * temp * temp;
        B = 2 * sinMu2 * temp * temp;
    } else {
        if (conductor) {
            /* No refraction in conductors */
            result.clear();
            result.push_back(0.0f);
            return;
        } else {
            Float temp = 1.0f / (alpha * (mu_i - eta.real() * mu_o));
            A = (mu_i * mu_i - 1 + eta.real() * eta.real() * (mu_o * mu_o - 1)) * temp * temp;
            B = 2 * eta.real() * sinMu2 * temp * temp;
        }
    }

    /* Minor optimization: don't even bother computing the Fourier series
       if the contribution to the scattering model is miniscule */
    if (math::i0e(B) * std::exp(A+B) < 1e-10) {
        result.clear();
        result.push_back(0.0f);
        return;
    }

    Float B_max = Bmax(n, relerr);
    if (B > B_max) {
        A = A + B - B_max + std::log(math::i0e(B) / math::i0e(B_max));
        B = B_max;
    }

    std::vector<Float> lowfreq_coeffs, expcos_coeffs;

    /* Compute Fourier coefficients of the exponential term */
    expCosFourierSeries(A, B, relerr, expcos_coeffs);

    /* Compute Fourier coefficients of the low-frequency term
       Only fit in the region where the result is actually
       going to make some sort of difference given the convolution
       with expcos_coeffs */
    Float phiMax = math::safe_acos(1 + std::log(relerr) / B);

    microfacetNoExpFourierSeries(mu_o, mu_i, eta_, alpha,
                                 12, phiMax, lowfreq_coeffs);

    /* Perform discrete circular convolution of the two series */
    result.resize(lowfreq_coeffs.size() + expcos_coeffs.size() - 1);

    convolveFourier(lowfreq_coeffs.data(), lowfreq_coeffs.size(),
        expcos_coeffs.data(), expcos_coeffs.size(), result.data());

    /* Truncate the series if error bounds are satisfied */
    for (size_t i=0; i<result.size(); ++i) {
        assert(std::isfinite(result[i]));
        if (result[i] == 0 || std::abs(result[i]) < result[0] * relerr) {
            result.erase(result.begin() + i, result.end());
            break;
        }
    }
}
Exemplo n.º 4
0
void PNGCodec::decode(std::vector<uint8_t> &in,
	std::vector<uint8_t> *out, unsigned int *width, 
	unsigned int *height, ColorFormat *format, uint8_t level)
{
	if (level != 0)
	{
		// TODO: Error handling.
		return;
	}

	if (png_check_sig(in.data(), SIGNATURE_LENGTH) == false)
	{
		// TODO: Error handling.
		return;
	}

	png_structp pngPtr = png_create_read_struct(
		PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);

	if (pngPtr == nullptr)
	{
		// TODO: Error handling.
		return;
	}

	png_infop pngInfoPtr = png_create_info_struct(pngPtr);

	if (pngInfoPtr == nullptr)
	{
		// TODO: Error handling.
		png_destroy_read_struct(&pngPtr, nullptr, nullptr);
		return;
	}

	PNGVectorStream stream;
	stream.vec = &in;
	stream.offset = 0;

	png_set_read_fn(pngPtr, &stream, PNGReadCallback);
	png_read_info(pngPtr, pngInfoPtr);

	int bitDepth = 0;
	int colorType = -1;
	png_uint_32 retval = png_get_IHDR(pngPtr, pngInfoPtr,
		width,
		height,
		&bitDepth,
		&colorType,
		nullptr, nullptr, nullptr);

	if (retval != 1)
	{
		// TODO: Error handling.
		png_destroy_read_struct(&pngPtr, &pngInfoPtr, nullptr);
		return;
	}

	switch (colorType)
	{
	case PNG_COLOR_TYPE_RGB:
		*format = ColorFormat::RGB;
		break;

	case PNG_COLOR_TYPE_RGBA:
		*format = ColorFormat::RGBA;
		break;

	default:
		// TODO: Error handling.
		png_destroy_read_struct(&pngPtr, &pngInfoPtr, nullptr);
		return;
	}

	out->resize((*width) * (*height) * static_cast<unsigned int>(*format));

	for (unsigned int i = 0; i < *height; ++i)
		png_read_row(pngPtr, 
			&(*out)[i * (*width) * static_cast<unsigned int>(*format)], nullptr);

	png_destroy_read_struct(&pngPtr, &pngInfoPtr, nullptr);
}
Exemplo n.º 5
0
bool parseTransactionExtra(const std::vector<uint8_t> &transactionExtra, std::vector<TransactionExtraField> &transactionExtraFields) {
  transactionExtraFields.clear();

  if (transactionExtra.empty())
    return true;

  try {
    MemoryInputStream iss(transactionExtra.data(), transactionExtra.size());
    BinaryInputStreamSerializer ar(iss);

    int c = 0;

    while (!iss.endOfStream()) {
      c = read<uint8_t>(iss);
      switch (c) {
      case TX_EXTRA_TAG_PADDING: {
        size_t size = 1;
        for (; !iss.endOfStream() && size <= TX_EXTRA_PADDING_MAX_COUNT; ++size) {
          if (read<uint8_t>(iss) != 0) {
            return false; // all bytes should be zero
          }
        }

        if (size > TX_EXTRA_PADDING_MAX_COUNT) {
          return false;
        }

        transactionExtraFields.push_back(TransactionExtraPadding{ size });
        break;
      }

      case TX_EXTRA_TAG_PUBKEY: {
        TransactionExtraPublicKey extraPk;
        ar(extraPk.publicKey, "public_key");
        transactionExtraFields.push_back(extraPk);
        break;
      }

      case TX_EXTRA_NONCE: {
        TransactionExtraNonce extraNonce;
        uint8_t size = read<uint8_t>(iss);
        if (size > 0) {
          extraNonce.nonce.resize(size);
          read(iss, extraNonce.nonce.data(), extraNonce.nonce.size());
        }

        transactionExtraFields.push_back(extraNonce);
        break;
      }

      case TX_EXTRA_MERGE_MINING_TAG: {
        TransactionExtraMergeMiningTag mmTag;
        ar(mmTag, "mm_tag");
        transactionExtraFields.push_back(mmTag);
        break;
      }

      case TX_EXTRA_MESSAGE_TAG: {
        tx_extra_message message;
        ar(message.data, "message");
        transactionExtraFields.push_back(message);
        break;
      }

      case TX_EXTRA_TTL: {
        uint8_t size;
        readVarint(iss, size);
        TransactionExtraTTL ttl;
        readVarint(iss, ttl.ttl);
        transactionExtraFields.push_back(ttl);
        break;
      }
      }
    }
  } catch (std::exception &) {
    return false;
  }

  return true;
}
Exemplo n.º 6
0
 std::vector<byte> hash_bytes(const std::vector<byte, A>& v)
    {
    return hash_bytes(v.data(), v.size());
    }
Exemplo n.º 7
0
void CustomPostEffectShader::render(Camera* camera,
        RenderTexture* render_texture,
        PostEffectData* post_effect_data,
        std::vector<glm::vec3>& vertices, std::vector<glm::vec2>& tex_coords,
        std::vector<unsigned short>& triangles) {
    glUseProgram(program_->id());

#if _GVRF_USE_GLES3_
    GLuint tmpID;

    if(vaoID_ == 0)
    {
        glGenVertexArrays(1, &vaoID_);
        glBindVertexArray(vaoID_);

        glGenBuffers(1, &tmpID);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tmpID);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short)*triangles.size(), &triangles[0], GL_STATIC_DRAW);

        if (vertices.size())
        {
            glGenBuffers(1, &tmpID);
            glBindBuffer(GL_ARRAY_BUFFER, tmpID);
            glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*vertices.size(), &vertices[0], GL_STATIC_DRAW);
            glEnableVertexAttribArray(a_position_);
            glVertexAttribPointer(a_position_, 3, GL_FLOAT, 0, 0, 0);
        }

        if (tex_coords.size())
        {
            glGenBuffers(1, &tmpID);
            glBindBuffer(GL_ARRAY_BUFFER, tmpID);
            glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2)*tex_coords.size(), &tex_coords[0], GL_STATIC_DRAW);
            glEnableVertexAttribArray(a_tex_coord_);
            glVertexAttribPointer(a_tex_coord_, 2, GL_FLOAT, 0, 0, 0);
        }
    }

    int texture_index = 0;
    if (u_texture_ != -1) {
        glActiveTexture(getGLTexture(texture_index));
        glBindTexture(GL_TEXTURE_2D, render_texture->getId());
        glUniform1i(u_texture_, texture_index++);
    }

    if (u_projection_matrix_ != -1) {
        glm::mat4 view = camera->getViewMatrix();
        glUniformMatrix4fv(u_projection_matrix_, 1, GL_TRUE, glm::value_ptr(view));
    }

    if (u_right_eye_ != -1) {
        bool right = camera->render_mask() & RenderData::RenderMaskBit::Right;
        glUniform1i(u_right_eye_, right ? 1 : 0);
    }

    for (auto it = texture_keys_.begin(); it != texture_keys_.end(); ++it) {
        glActiveTexture(getGLTexture(texture_index));
        Texture* texture = post_effect_data->getTexture(it->second);
        glBindTexture(texture->getTarget(), texture->getId());
        glUniform1i(it->first, texture_index++);
    }

    for (auto it = float_keys_.begin(); it != float_keys_.end(); ++it) {
        glUniform1f(it->first, post_effect_data->getFloat(it->second));
    }

    for (auto it = vec2_keys_.begin(); it != vec2_keys_.end(); ++it) {
        glm::vec2 v = post_effect_data->getVec2(it->second);
        glUniform2f(it->first, v.x, v.y);
    }

    for (auto it = vec3_keys_.begin(); it != vec3_keys_.end(); ++it) {
        glm::vec3 v = post_effect_data->getVec3(it->second);
        glUniform3f(it->first, v.x, v.y, v.z);
    }

    for (auto it = vec4_keys_.begin(); it != vec4_keys_.end(); ++it) {
        glm::vec4 v = post_effect_data->getVec4(it->second);
        glUniform4f(it->first, v.x, v.y, v.z, v.w);
    }

    for (auto it = mat4_keys_.begin(); it != mat4_keys_.end(); ++it) {
        glm::mat4 m = post_effect_data->getMat4(it->second);
        glUniformMatrix4fv(it->first, 1, GL_FALSE, glm::value_ptr(m));
    }

    glBindVertexArray(vaoID_);
    glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_SHORT, 0);
    glBindVertexArray(0);

#else

    if (a_position_ != -1) {
        glVertexAttribPointer(a_position_, 3, GL_FLOAT, GL_FALSE, 0,
                vertices.data());
        glEnableVertexAttribArray(a_position_);
    }

    if (a_tex_coord_ != -1) {
        glVertexAttribPointer(a_tex_coord_, 2, GL_FLOAT, GL_FALSE, 0,
                tex_coords.data());
        glEnableVertexAttribArray(a_tex_coord_);
    }

    int texture_index = 0;

    if (u_texture_ != -1) {
        glActiveTexture(getGLTexture(texture_index));
        glBindTexture(GL_TEXTURE_2D, render_texture->getId());
        glUniform1i(u_texture_, texture_index++);
    }

    if (u_projection_matrix_ != -1) {
        glm::mat4 view = camera->getViewMatrix();
        glUniformMatrix4fv(u_projection_matrix_, 1, GL_TRUE, glm::value_ptr(view));
    }

    if (u_right_eye_ != -1) {
        bool right = camera->render_mask() & RenderData::RenderMaskBit::Right;
        glUniform1i(u_right_eye_, right ? 1 : 0);
    }

    for (auto it = texture_keys_.begin(); it != texture_keys_.end(); ++it) {
        glActiveTexture(getGLTexture(texture_index));
        Texture* texture = post_effect_data->getTexture(it->second);
        glBindTexture(texture->getTarget(), texture->getId());
        glUniform1i(it->first, texture_index++);
    }

    for (auto it = float_keys_.begin(); it != float_keys_.end(); ++it) {
        glUniform1f(it->first, post_effect_data->getFloat(it->second));
    }

    for (auto it = vec2_keys_.begin(); it != vec2_keys_.end(); ++it) {
        glm::vec2 v = post_effect_data->getVec2(it->second);
        glUniform2f(it->first, v.x, v.y);
    }

    for (auto it = vec3_keys_.begin(); it != vec3_keys_.end(); ++it) {
        glm::vec3 v = post_effect_data->getVec3(it->second);
        glUniform3f(it->first, v.x, v.y, v.z);
    }

    for (auto it = vec4_keys_.begin(); it != vec4_keys_.end(); ++it) {
        glm::vec4 v = post_effect_data->getVec4(it->second);
        glUniform4f(it->first, v.x, v.y, v.z, v.w);
    }

    for (auto it = mat4_keys_.begin(); it != mat4_keys_.end(); ++it) {
        glm::mat4 m = post_effect_data->getMat4(it->second);
        glUniformMatrix4fv(it->first, 1, GL_FALSE, glm::value_ptr(m));
    }

    glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_SHORT,
            triangles.data());
#endif
}
Exemplo n.º 8
0
base_blob<BITS>::base_blob(const std::vector<unsigned char>& vch)
{
    assert(vch.size() == sizeof(data));
    memcpy(data, vch.data(), sizeof(data));
}
Exemplo n.º 9
0
MemoryBuffer::MemoryBuffer(std::vector<unsigned char>& data) :
    AbstractFile(data.size()),
    buffer_(data.data()),
    readOnly_(false)
{
}
Exemplo n.º 10
0
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
    return EncodeBase58(vch.data(), vch.data() + vch.size());
}
Exemplo n.º 11
0
int main(int argc,char **argv)
{
   using std::cout;
   using std::endl;

   std::string output;
   int L = 0;
   int N = 0;
   double U = 0;
   bool momspace = false;

   struct option long_options[] =
   {
      {"output",  required_argument, 0, 'o'},
      {"interaction",  required_argument, 0, 'U'},
      {"sites",  required_argument, 0, 'L'},
      {"particles",  required_argument, 0, 'N'},
      {"momspace",  no_argument, 0, 'm'},
      {"help",  no_argument, 0, 'h'},
      {0, 0, 0, 0}
   };

   int i,j;

   while( (j = getopt_long (argc, argv, "ho:U:L:N:m", long_options, &i)) != -1)
      switch(j)
      {
         case 'h':
         case '?':
            cout << "Usage: " << argv[0] << " [OPTIONS]\n"
               "\n"
               "    -o, --output=output-filename    Set the output filename\n"
               "    -L, --sites=L                   Set the number of sites\n"
               "    -N, --particles=N               Set the number of particles\n"
               "    -U, --interaction=U             Set the on-site interaction\n"
               "    -m, --momspace                  Work in momentum space\n"
               "    -h, --help                      Display this help\n"
               "\n";
            return 0;
            break;
         case 'o':
            output = optarg;
            break;
         case 'U':
            U = atof(optarg);
            break;
         case 'L':
            L = atoi(optarg);
            break;
         case 'N':
            N = atoi(optarg);
            break;
         case 'm':
            momspace = true;
            break;
      }

   if(! (L && N))
   {
      std::cerr << "You need to specifiy the system!" << endl;
      return 1;
   }

   cout << "Creating for L= " << L << " N= " << N << " U= " << U << endl;

   const std::vector<int> orb2irrep (L, 0);

   CheMPS2::Hamiltonian ham(L, 0, orb2irrep.data());
   // put everything to zero
   ham.reset();
   ham.setNe(N);
   ham.setEconst(0);

   if(momspace)
   {
      // Don't forget: you cannot rotate states of different momentum!

      // one-particle integrals
      for(int i=0;i<L;i++)
         ham.setTmat(i, i, -2*std::cos(2*M_PI/(1.0*L)*i));

      // two-particle integrals
      for(int k1=0;k1<L;k1++)
         for(int k2=0;k2<L;k2++)
            for(int k3=0;k3<L;k3++)
               for(int k4=0;k4<L;k4++)
                  if((k1+k2)%L == (k3+k4)%L)
                     ham.setVmat(k1,k2,k3,k4, U*1.0/L);

   } else
   {
      // one-particle integrals
      for(int i=1;i<(L-1);i++)
      {
         ham.setTmat(i, i+1, -1);
         ham.setTmat(i, i-1, -1);
      }
      ham.setTmat(0, 1, -1);
      ham.setTmat(L-1, L-2, -1);

      // periodic boundary condition
      ham.setTmat(0, L-1, -1);
      ham.setTmat(L-1, 0, -1);

      // two-particle integrals
      for(int i=0;i<L;i++)
         ham.setVmat(i, i, i, i, U);
   }

   if(output.empty())
   {
      output = "hub-integrals-";
      if(momspace)
         output += "mom-";
      
      output += std::to_string(L) + "-" + std::to_string(N) + "-" + std::to_string(U) + ".h5";
   }

   cout << "Writing Hamiltonian to " << output << endl;

   ham.save2(output);

   return 0;
}
Exemplo n.º 12
0
int Socket::write(const std::vector<char> &data){
	return this->write((void*) data.data(), data.size());
}
Exemplo n.º 13
0
void read(IInputStream& in, std::vector<uint8_t>& data, size_t size) {
  data.resize(size);
  read(in, data.data(), size);
}
Exemplo n.º 14
0
void write(IOutputStream& out, const std::vector<uint8_t>& data) {
  write(out, data.data(), data.size());
}
Exemplo n.º 15
0
void DebugMessage::disableMessages(const GLenum source, const GLenum type, const GLenum severity, const std::vector<GLuint> & ids)
{
    disableMessages(source, type, severity, static_cast<int>(ids.size()), ids.data());
}
Exemplo n.º 16
0
MemoryBuffer::MemoryBuffer(const std::vector<unsigned char>& data) :
    AbstractFile(data.size()),
    buffer_((unsigned char *)data.data()), // TODO: const cast !!!
    readOnly_(true)
{
}
Exemplo n.º 17
0
    /// Solve for time-of-flight and a number of tracers.
    /// \param[in]  darcyflux         Array of signed face fluxes.
    /// \param[in]  porevolume        Array of pore volumes.
    /// \param[in]  source            Source term. Sign convention is:
    ///                                 (+) inflow flux,
    ///                                 (-) outflow flux.
    /// \param[in]  tracerheads       Table containing one row per tracer, and each
    ///                               row contains the source cells for that tracer.
    /// \param[out] tof               Array of time-of-flight values (1 per cell).
    /// \param[out] tracer            Array of tracer values. N per cell, where N is
    ///                               equalt to tracerheads.size().
    void TofReorder::solveTofTracer(const double* darcyflux,
                                    const double* porevolume,
                                    const double* source,
                                    const SparseTable<int>& tracerheads,
                                    std::vector<double>& tof,
                                    std::vector<double>& tracer)
    {
        darcyflux_ = darcyflux;
        porevolume_ = porevolume;
        source_ = source;
        const int num_cells = grid_.number_of_cells;
#ifndef NDEBUG
        // Sanity check for sources.
        const double cum_src = std::accumulate(source, source + num_cells, 0.0);
        if (std::fabs(cum_src) > *std::max_element(source, source + num_cells)*1e-2) {
            OPM_THROW(std::runtime_error, "Sources do not sum to zero: " << cum_src);
        }
#endif
        tof.resize(num_cells);
        std::fill(tof.begin(), tof.end(), 0.0);
        tof_ = &tof[0];

        if (use_multidim_upwind_) {
            face_tof_.resize(grid_.number_of_faces);
            std::fill(face_tof_.begin(), face_tof_.end(), 0.0);
            face_part_tof_.resize(grid_.face_nodepos[grid_.number_of_faces]);
            std::fill(face_part_tof_.begin(), face_part_tof_.end(), 0.0);
        }

        // Execute solve for tof
        compute_tracer_ = false;
        executeSolve();

        // Find the tracer heads (injectors).
        const int num_tracers = tracerheads.size();
        tracer.resize(num_cells*num_tracers);
        std::fill(tracer.begin(), tracer.end(), 0.0);
        if (num_tracers > 0) {
            tracerhead_by_cell_.clear();
            tracerhead_by_cell_.resize(num_cells, NoTracerHead);
        }
        for (int tr = 0; tr < num_tracers; ++tr) {
            const unsigned int tracerheadsSize = tracerheads[tr].size();
            for (unsigned int i = 0; i < tracerheadsSize; ++i) {
                const int cell = tracerheads[tr][i];
                tracer[num_cells * tr + cell] = 1.0;
                tracerhead_by_cell_[cell] = tr;
            }
        }

        // Execute solve for tracers.
        std::vector<double> fake_pv(num_cells, 0.0);
        porevolume_ = fake_pv.data();
        for (int tr = 0; tr < num_tracers; ++tr) {
            tof_ = tracer.data() + tr * num_cells;
            compute_tracer_ = true;
            executeSolve();
        }

        // Write output tracer data (transposing the computed data).
        std::vector<double> computed = tracer;
        for (int cell = 0; cell < num_cells; ++cell) {
            for (int tr = 0; tr < num_tracers; ++tr) {
                tracer[num_tracers * cell + tr] = computed[num_cells * tr + cell];
            }
        }
    }
void HorizontalFlipPostEffectShader::render(
        RenderTexture* render_texture,
        PostEffectData* post_effect_data,
        std::vector<glm::vec3>& vertices, std::vector<glm::vec2>& tex_coords,
        std::vector<unsigned short>& triangles) {
    glUseProgram(program_->id());

#if _GVRF_USE_GLES3_
    GLuint tmpID;

    if(vaoID_ == 0)
    {
        glGenVertexArrays(1, &vaoID_);
        glBindVertexArray(vaoID_);

        glGenBuffers(1, &tmpID);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tmpID);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short)*triangles.size(), &triangles[0], GL_STATIC_DRAW);

        if (vertices.size())
        {
            glGenBuffers(1, &tmpID);
            glBindBuffer(GL_ARRAY_BUFFER, tmpID);
            glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*vertices.size(), &vertices[0], GL_STATIC_DRAW);
            glEnableVertexAttribArray(a_position_);
            glVertexAttribPointer(a_position_, 3, GL_FLOAT, 0, 0, 0);
        }

        if (tex_coords.size())
        {
            glGenBuffers(1, &tmpID);
            glBindBuffer(GL_ARRAY_BUFFER, tmpID);
            glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2)*tex_coords.size(), &tex_coords[0], GL_STATIC_DRAW);
            glEnableVertexAttribArray(a_tex_coord_);
            glVertexAttribPointer(a_tex_coord_, 2, GL_FLOAT, 0, 0, 0);
        }
    }

    glActiveTexture (GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, render_texture->getId());
    glUniform1i(u_texture_, 0);

    glBindVertexArray(vaoID_);
    glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_SHORT, 0);
    glBindVertexArray(0);
#else
    glVertexAttribPointer(a_position_, 3, GL_FLOAT, GL_FALSE, 0,
            vertices.data());
    glEnableVertexAttribArray(a_position_);

    glVertexAttribPointer(a_tex_coord_, 2, GL_FLOAT, GL_FALSE, 0,
            tex_coords.data());
    glEnableVertexAttribArray(a_tex_coord_);

    glActiveTexture (GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, render_texture->getId());
    glUniform1i(u_texture_, 0);

    glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_SHORT,
            triangles.data());
#endif
    checkGlError("HorizontalFlipPostEffectShader::render");
}
Exemplo n.º 19
0
bool ptImageHelper::WriteExif(const QString              &AFileName,
                              const std::vector<uint8_t> &AExifBuffer,
                              Exiv2::IptcData            &AIptcData,
                              Exiv2::XmpData             &AXmpData) {
  try {
#if EXIV2_TEST_VERSION(0,17,91)   /* Exiv2 0.18-pre1 */

    Exiv2::ExifData hInExifData;

    Exiv2::ExifParser::decode(hInExifData,
                              AExifBuffer.data() + CExifHeader.size(),
                              AExifBuffer.size() - CExifHeader.size());

    // Reset orientation
    Exiv2::ExifData::iterator pos = hInExifData.begin();
    if ((pos = hInExifData.findKey(Exiv2::ExifKey("Exif.Image.Orientation"))) != hInExifData.end()) {
      pos->setValue("1"); // Normal orientation
    }

    // Adapted from UFRaw, necessary for Tiff files
    QStringList ExifKeys;
    ExifKeys  << "Exif.Image.ImageWidth"
              << "Exif.Image.ImageLength"
              << "Exif.Image.BitsPerSample"
              << "Exif.Image.Compression"
              << "Exif.Image.PhotometricInterpretation"
              << "Exif.Image.FillOrder"
              << "Exif.Image.SamplesPerPixel"
              << "Exif.Image.StripOffsets"
              << "Exif.Image.RowsPerStrip"
              << "Exif.Image.StripByteCounts"
              << "Exif.Image.XResolution"
              << "Exif.Image.YResolution"
              << "Exif.Image.PlanarConfiguration"
              << "Exif.Image.ResolutionUnit";

    for (short i = 0; i < ExifKeys.count(); i++) {
      if ((pos = hInExifData.findKey(Exiv2::ExifKey(ExifKeys.at(i).toLocal8Bit().data()))) != hInExifData.end())
        hInExifData.erase(pos);
    }

    if (Settings->GetInt("EraseExifThumbnail")) {
      Exiv2::ExifThumb Thumb(hInExifData);
      Thumb.erase();
    }

    QStringList JpegExtensions;
    JpegExtensions << "jpg" << "JPG" << "Jpg" << "jpeg" << "Jpeg" << "JPEG";
    bool deleteDNGdata = false;
    for (short i = 0; i < JpegExtensions.count(); i++) {
      if (!AFileName.endsWith(JpegExtensions.at(i))) deleteDNGdata = true;
    }

    Exiv2::Image::AutoPtr Exiv2Image = Exiv2::ImageFactory::open(AFileName.toLocal8Bit().data());

    Exiv2Image->readMetadata();
    Exiv2::ExifData outExifData = Exiv2Image->exifData();

    for (auto hPos = hInExifData.begin(); hPos != hInExifData.end(); hPos++) {
      if (!deleteDNGdata || (*hPos).key() != "Exif.Image.DNGPrivateData") {
        outExifData.add(*hPos);
      }
    }

    // IPTC data

    QStringList Tags        = Settings->GetStringList("TagsList");
    QStringList DigikamTags = Settings->GetStringList("DigikamTagsList");

    Exiv2::StringValue StringValue;
    for (int i = 0; i < Tags.size(); i++) {
      StringValue.read(Tags.at(i).toStdString());
      AIptcData.add(Exiv2::IptcKey("Iptc.Application2.Keywords"), &StringValue);
    }


    // XMP data

    for (int i = 0; i < Tags.size(); i++) {
      AXmpData["Xmp.dc.subject"] = Tags.at(i).toStdString();
    }
    for (int i = 0; i < DigikamTags.size(); i++) {
      AXmpData["Xmp.digiKam.TagsList"] = DigikamTags.at(i).toStdString();
    }

    // Image rating
    outExifData["Exif.Image.Rating"] = Settings->GetInt("ImageRating");
    AXmpData["Xmp.xmp.Rating"]       = Settings->GetInt("ImageRating");

    // Program name
    outExifData["Exif.Image.ProcessingSoftware"]  = ProgramName;
    outExifData["Exif.Image.Software"]            = ProgramName;
    AIptcData["Iptc.Application2.Program"]        = ProgramName;
    AIptcData["Iptc.Application2.ProgramVersion"] = "idle";
    AXmpData["Xmp.xmp.CreatorTool"]               = ProgramName;
    AXmpData["Xmp.tiff.Software"]                 = ProgramName;

    // Title
    QString TitleWorking = Settings->GetString("ImageTitle");
    StringClean(TitleWorking);
    if (TitleWorking != "") {
      outExifData["Exif.Photo.UserComment"]  = TitleWorking.toStdString();
      AIptcData["Iptc.Application2.Caption"] = TitleWorking.toStdString();
      AXmpData["Xmp.dc.description"]         = TitleWorking.toStdString();
      AXmpData["Xmp.exif.UserComment"]       = TitleWorking.toStdString();
      AXmpData["Xmp.tiff.ImageDescription"]  = TitleWorking.toStdString();
    }

    // Copyright
    QString CopyrightWorking = Settings->GetString("Copyright");
    StringClean(CopyrightWorking);
    if (CopyrightWorking != "") {
      outExifData["Exif.Image.Copyright"]      = CopyrightWorking.toStdString();
      AIptcData["Iptc.Application2.Copyright"] = CopyrightWorking.toStdString();
      AXmpData["Xmp.tiff.Copyright"]           = CopyrightWorking.toStdString();
    }

    Exiv2Image->setExifData(outExifData);
    Exiv2Image->setIptcData(AIptcData);
    Exiv2Image->setXmpData(AXmpData);
    Exiv2Image->writeMetadata();
    return true;
#endif
  } catch (Exiv2::AnyError& Error) {
    if (Settings->GetInt("JobMode") == 0) {
      ptMessageBox::warning(0 ,"Exiv2 Error","No exif data written!\nCaught Exiv2 exception '" + QString(Error.what()) + "'\n");
    } else {
      std::cout << "Caught Exiv2 exception '" << Error << "'\n";
    }
  }
  return false;
}
Exemplo n.º 20
0
void handleImage(const sensor_msgs::ImageConstPtr& img)
{
	ros::Time now = ros::Time::now();
	if(now - g_lastImageTime < g_minTimeBetweenImages)
		return;
	g_lastImageTime = now;

	ros::Time start = ros::Time::now();

	cv_bridge::CvImageConstPtr cvImg = cv_bridge::toCvShare(img, "bgr8");

	int height = g_width * cvImg->image.rows / cvImg->image.cols;

	cv::Mat resized;
	cv::resize(cvImg->image, resized, cv::Size(g_width, height), CV_INTER_AREA);

	if(!g_encoder)
	{
		x264_param_t params;
		x264_param_default(&params);
		x264_param_apply_profile(&params, "high");
		x264_param_default_preset(&params, "ultrafast", "zerolatency");

		params.i_width = g_width;
		params.i_height = height;
		params.b_repeat_headers = 1;
		params.b_intra_refresh = 1;
		params.i_fps_num = 1;
		params.i_fps_den = 10;
		params.i_frame_reference = 1;
		params.i_keyint_max = 20;
		params.i_bframe = 0;
		params.b_open_gop = 0;
	// 	params.rc.i_rc_method = X264_RC_CRF;
	// // 	params.rc.i_qp_min = params.rc.i_qp_max = 47;
	// 	params.rc.i_vbv_buffer_size = 6;
	// 	params.rc.i_vbv_max_bitrate = 6000;
	// 	params.rc.i_bitrate = 6;
		params.rc.i_rc_method = X264_RC_CRF;
		params.rc.i_vbv_buffer_size = 1000;
		params.rc.i_vbv_max_bitrate = 1000;
		params.rc.i_bitrate = 1000;
		params.i_threads = 4;

		g_encoder = x264_encoder_open(&params);

		x264_picture_init(&g_inputPicture);
		x264_picture_init(&g_outPicture);

		g_encoderConfiguredHeight = height;

		g_inBuf.resize(g_width*height + g_width*height/2);
	}
	else if(height != g_encoderConfiguredHeight)
	{
		ROS_ERROR("Image dimensions changed!");
		throw std::runtime_error("Image dimensions changed");
	}

	RGB_to_YUV420(resized.data, g_inBuf.data(), g_width, height);

	g_inputPicture.img.plane[0] = g_inBuf.data();
	g_inputPicture.img.plane[1] = g_inBuf.data() + g_width*height;
	g_inputPicture.img.plane[2] = g_inBuf.data() + g_width*height + g_width*height/4;

	g_inputPicture.img.i_stride[0] = g_width;
	g_inputPicture.img.i_stride[1] = g_width/2;
	g_inputPicture.img.i_stride[2] = g_width/2;

	g_inputPicture.img.i_csp = X264_CSP_I420;
	g_inputPicture.img.i_plane = 3;

	x264_nal_t* nals;
	int numNals;

	x264_encoder_encode(g_encoder, &nals, &numNals, &g_inputPicture, &g_outPicture);

	std::size_t size = 0;
	for(int i = 0; i < numNals; ++i)
		size += nals[i].i_payload;

	sensor_msgs::CompressedImagePtr msg(new sensor_msgs::CompressedImage);

	msg->header = img->header;
	msg->format = "h264";

	msg->data.resize(size);
	unsigned int off = 0;

	for(int i = 0; i < numNals; ++i)
	{
		memcpy(msg->data.data() + off, nals[i].p_payload, nals[i].i_payload);
		off += nals[i].i_payload;
	}

	g_pub.publish(msg);
	ROS_DEBUG("took %f", (ros::Time::now() - start).toSec());
}
Exemplo n.º 21
0
int LLVMFuzzerInitialize(int *argc, char ***argv) {
  // The command line is unusual compared to other fuzzers due to the need to
  // specify the target. Options like -triple, -mcpu, and -mattr work like
  // their counterparts in llvm-mc, while -fuzzer-args collects options for the
  // fuzzer itself.
  //
  // Examples:
  //
  // Fuzz the big-endian MIPS32R6 disassembler using 100,000 inputs of up to
  // 4-bytes each and use the contents of ./corpus as the test corpus:
  //   llvm-mc-fuzzer -triple mips-linux-gnu -mcpu=mips32r6 -disassemble \
  //       -fuzzer-args -max_len=4 -runs=100000 ./corpus
  //
  // Infinitely fuzz the little-endian MIPS64R2 disassembler with the MSA
  // feature enabled using up to 64-byte inputs:
  //   llvm-mc-fuzzer -triple mipsel-linux-gnu -mcpu=mips64r2 -mattr=msa \
  //       -disassemble -fuzzer-args ./corpus
  //
  // If your aim is to find instructions that are not tested, then it is
  // advisable to constrain the maximum input size to a single instruction
  // using -max_len as in the first example. This results in a test corpus of
  // individual instructions that test unique paths. Without this constraint,
  // there will be considerable redundancy in the corpus.

  char **OriginalArgv = *argv;

  LLVMInitializeAllTargetInfos();
  LLVMInitializeAllTargetMCs();
  LLVMInitializeAllAsmParsers();

  cl::ParseCommandLineOptions(*argc, OriginalArgv);

  // Rebuild the argv without the arguments llvm-mc-fuzzer consumed so that
  // the driver can parse its arguments.
  //
  // FuzzerArgs cannot provide the non-const pointer that OriginalArgv needs.
  // Re-use the strings from OriginalArgv instead of copying FuzzerArg to a
  // non-const buffer to avoid the need to clean up when the fuzzer terminates.
  ModifiedArgv.push_back(OriginalArgv[0]);
  for (const auto &FuzzerArg : FuzzerArgs) {
    for (int i = 1; i < *argc; ++i) {
      if (FuzzerArg == OriginalArgv[i])
        ModifiedArgv.push_back(OriginalArgv[i]);
    }
  }
  *argc = ModifiedArgv.size();
  *argv = ModifiedArgv.data();

  // Package up features to be passed to target/subtarget
  // We have to pass it via a global since the callback doesn't
  // permit any user data.
  if (MAttrs.size()) {
    SubtargetFeatures Features;
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  if (TripleName.empty())
    TripleName = sys::getDefaultTargetTriple();

  return 0;
}
Exemplo n.º 22
0
        /*
         *  \param i The exclusive index of the prefix range [0..i-1], so \f$i\in [0..size()]\f$.
         *  \param c The symbol to count the occurrences in the prefix.
         *    \returns The number of occurrences of symbol c in the prefix [0..i-1] of the BWT.
         *  \par Time complexity
         *        \f$ \Order{\log n t_{\Psi}} \f$
         */
        size_type rank_bwt(size_type i, const char_type c)const {
            comp_char_type cc = char2comp[c];
            if (cc==0 and c!=0)  // character is not in the text => return 0
                return 0;
            if (i == 0)
                return 0;
            assert(i <= size());

            size_type lower_b, upper_b; // lower_b inclusive, upper_b exclusive

            const size_type sd = m_psi.get_sample_dens();
            size_type lower_sb = (C[cc]+sd-1)/sd; // lower_sb inclusive
            size_type upper_sb = (C[cc+1]+sd-1)/sd; // upper_sb exclusive
            while (lower_sb+1 < upper_sb) {
                size_type mid = (lower_sb+upper_sb)/2;
                if (m_psi.sample(mid) >= i)
                    upper_sb = mid;
                else
                    lower_sb = mid;
            }

            if (lower_sb == upper_sb) { // the interval was smaller than sd
                lower_b = C[cc]; upper_b = C[cc+1];
            } else if (lower_sb > (C[cc]+sd-1)/sd) { // main case
// TODO: don't use get_inter_sampled_values if t_dens is really
//       large
                lower_b = lower_sb*sd;
                if (0 == m_psi_buf.size()) {
                    upper_b = std::min(upper_sb*sd, C[cc+1]);
                    goto finish;
                }
                uint64_t* p = m_psi_buf.data();
                // extract the psi values between two samples
                m_psi.get_inter_sampled_values(lower_sb, p);
                p = m_psi_buf.data();
                uint64_t smpl = m_psi.sample(lower_sb);
                // handle border cases
                if (lower_b + m_psi.get_sample_dens() >= C[cc+1])
                    m_psi_buf[ C[cc+1]-lower_b ] = size()-smpl;
                else
                    m_psi_buf[ m_psi.get_sample_dens() ] = size()-smpl;
                // search the result linear
                while ((*p++)+smpl < i);

                return p-1-m_psi_buf.data() + lower_b - C[cc];
            } else { // lower_b == (m_C[cc]+sd-1)/sd and lower_sb < upper_sb
                if (m_psi.sample(lower_sb) >= i) {
                    lower_b = C[cc];
                    upper_b = lower_sb * sd + 1;
                } else {
                    lower_b = lower_sb * sd;
                    upper_b = std::min(upper_sb*sd, C[cc+1]);
                }
            }
finish:
            // binary search the interval [C[cc]..C[cc+1]-1] for the result
//            size_type lower_b = m_C[cc], upper_b = m_C[cc+1]; // lower_b inclusive, upper_b exclusive
            while (lower_b+1 < upper_b) {
                size_type mid = (lower_b+upper_b)/2;
                if (m_psi[mid] >= i)
                    upper_b = mid;
                else
                    lower_b = mid;
            }
            if (lower_b > C[cc])
                return lower_b - C[cc] + 1;
            else { // lower_b == m_C[cc]
                return m_psi[lower_b] < i;// 1 if m_psi[lower_b]<i, 0 otherwise
            }
        }
Exemplo n.º 23
0
#include "test_functions.hpp"

BOOST_AFIO_AUTO_TEST_CASE(async_io_zero, "Tests async range content zeroing of sparse and compressed files", 60)
{
    using namespace BOOST_AFIO_V2_NAMESPACE;
    namespace asio = BOOST_AFIO_V2_NAMESPACE::asio;
    std::vector<char> buffer(1024*1024, 'n');
    ranctx ctx; raninit(&ctx, 1);
    u4 *buf=(u4 *) buffer.data();
    for(size_t n=0; n<buffer.size()/sizeof(*buf); n++)
      buf[n]=ranval(&ctx);
    auto dispatcher = make_dispatcher().get();
    std::cout << "\n\nTesting async range content zeroing of sparse and compressed files:\n";
    {
      // Create a 1Mb file
      auto mkdir(dispatcher->dir(path_req("testdir", file_flags::create)));
      auto mkfilesp(dispatcher->file(path_req::relative(mkdir, "sparse", file_flags::create | file_flags::read_write)));
      auto mkfilec(dispatcher->file(path_req::relative(mkdir, "compressed", file_flags::create | file_flags::create_compressed | file_flags::read_write)));
      auto resizefilesp(dispatcher->truncate(mkfilesp, buffer.size()));
      auto resizefilec(dispatcher->truncate(mkfilec, buffer.size()));
      auto writefilesp(dispatcher->write(make_io_req(resizefilesp, buffer, 0)));
      auto writefilec(dispatcher->write(make_io_req(resizefilec, buffer, 0)));
      // Need to fsync to work around lazy or delayed allocation
      auto syncfilesp1(dispatcher->sync(writefilesp));
      auto syncfilec1(dispatcher->sync(writefilec));
      BOOST_REQUIRE_NO_THROW(when_all_p(mkdir, mkfilesp, mkfilec, resizefilesp, resizefilec, writefilesp, writefilec, syncfilesp1, syncfilec1).get());
      
      // Verify they really does consume 1Mb of disc space
      stat_t beforezerostatsp=mkfilesp->lstat(metadata_flags::All);
      stat_t beforezerostatc=mkfilec->lstat(metadata_flags::All);
      BOOST_REQUIRE(beforezerostatsp.st_size==buffer.size());
Exemplo n.º 24
0
NewArchiveMember
ObjectFactory::createImportDescriptor(std::vector<uint8_t> &Buffer) {
  static const uint32_t NumberOfSections = 2;
  static const uint32_t NumberOfSymbols = 7;
  static const uint32_t NumberOfRelocations = 3;

  // COFF Header
  coff_file_header Header{
      u16(Config->Machine), u16(NumberOfSections), u32(0),
      u32(sizeof(Header) + (NumberOfSections * sizeof(coff_section)) +
          // .idata$2
          sizeof(coff_import_directory_table_entry) +
          NumberOfRelocations * sizeof(coff_relocation) +
          // .idata$4
          (DLLName.size() + 1)),
      u32(NumberOfSymbols), u16(0),
      u16(is32bit() ? IMAGE_FILE_32BIT_MACHINE : 0),
  };
  append(Buffer, Header);

  // Section Header Table
  static const coff_section SectionTable[NumberOfSections] = {
      {{'.', 'i', 'd', 'a', 't', 'a', '$', '2'},
       u32(0),
       u32(0),
       u32(sizeof(coff_import_directory_table_entry)),
       u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section)),
       u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section) +
           sizeof(coff_import_directory_table_entry)),
       u32(0),
       u16(NumberOfRelocations),
       u16(0),
       u32(IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA |
           IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)},
      {{'.', 'i', 'd', 'a', 't', 'a', '$', '6'},
       u32(0),
       u32(0),
       u32(DLLName.size() + 1),
       u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section) +
           sizeof(coff_import_directory_table_entry) +
           NumberOfRelocations * sizeof(coff_relocation)),
       u32(0),
       u32(0),
       u16(0),
       u16(0),
       u32(IMAGE_SCN_ALIGN_2BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA |
           IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)},
  };
  append(Buffer, SectionTable);

  // .idata$2
  static const coff_import_directory_table_entry ImportDescriptor{
      u32(0), u32(0), u32(0), u32(0), u32(0),
  };
  append(Buffer, ImportDescriptor);

  static const coff_relocation RelocationTable[NumberOfRelocations] = {
      {u32(offsetof(coff_import_directory_table_entry, NameRVA)), u32(2),
       u16(getImgRelRelocation())},
      {u32(offsetof(coff_import_directory_table_entry, ImportLookupTableRVA)),
       u32(3), u16(getImgRelRelocation())},
      {u32(offsetof(coff_import_directory_table_entry, ImportAddressTableRVA)),
       u32(4), u16(getImgRelRelocation())},
  };
  append(Buffer, RelocationTable);

  // .idata$6
  auto S = Buffer.size();
  Buffer.resize(S + DLLName.size() + 1);
  memcpy(&Buffer[S], DLLName.data(), DLLName.size());
  Buffer[S + DLLName.size()] = '\0';

  // Symbol Table
  coff_symbol16 SymbolTable[NumberOfSymbols] = {
      {{{0, 0, 0, 0, 0, 0, 0, 0}},
       u32(0),
       u16(1),
       u16(0),
       IMAGE_SYM_CLASS_EXTERNAL,
       0},
      {{{'.', 'i', 'd', 'a', 't', 'a', '$', '2'}},
       u32(0),
       u16(1),
       u16(0),
       IMAGE_SYM_CLASS_SECTION,
       0},
      {{{'.', 'i', 'd', 'a', 't', 'a', '$', '6'}},
       u32(0),
       u16(2),
       u16(0),
       IMAGE_SYM_CLASS_STATIC,
       0},
      {{{'.', 'i', 'd', 'a', 't', 'a', '$', '4'}},
       u32(0),
       u16(0),
       u16(0),
       IMAGE_SYM_CLASS_SECTION,
       0},
      {{{'.', 'i', 'd', 'a', 't', 'a', '$', '5'}},
       u32(0),
       u16(0),
       u16(0),
       IMAGE_SYM_CLASS_SECTION,
       0},
      {{{0, 0, 0, 0, 0, 0, 0, 0}},
       u32(0),
       u16(0),
       u16(0),
       IMAGE_SYM_CLASS_EXTERNAL,
       0},
      {{{0, 0, 0, 0, 0, 0, 0, 0}},
       u32(0),
       u16(0),
       u16(0),
       IMAGE_SYM_CLASS_EXTERNAL,
       0},
  };
  reinterpret_cast<StringTableOffset &>(SymbolTable[0].Name).Offset =
      sizeof(uint32_t);
  reinterpret_cast<StringTableOffset &>(SymbolTable[5].Name).Offset =
      sizeof(uint32_t) + ImportDescriptorSymbolName.length() + 1;
  reinterpret_cast<StringTableOffset &>(SymbolTable[6].Name).Offset =
      sizeof(uint32_t) + ImportDescriptorSymbolName.length() + 1 +
      NullImportDescriptorSymbolName.length() + 1;
  append(Buffer, SymbolTable);

  // String Table
  writeStringTable(Buffer,
                   {ImportDescriptorSymbolName, NullImportDescriptorSymbolName,
                    NullThunkSymbolName});

  StringRef F{reinterpret_cast<const char *>(Buffer.data()), Buffer.size()};
  return {MemoryBufferRef(F, DLLName)};
}
Exemplo n.º 25
0
void UIShapeCreator::Draw()
{
    if (!UIMainMenu::drawSceneNodes) { return; }

    static auto &assets = AssetsManager::Instance();
    static auto &voxel = *static_cast<VoxelizerRenderer *>
                         (assets->renderers["Voxelizer"].get());
    static auto scene = static_cast<Scene *>(nullptr);
    static auto node = static_cast<Node *>(nullptr);
    static auto material = static_cast<Material *>(nullptr);
    // control variables
    static auto selected = -1;
    static glm::vec3 position;
    static glm::vec3 rotation;
    static glm::vec3 scale;
    static glm::vec3 ambient;
    static glm::vec3 specular;
    static glm::vec3 diffuse;
    static glm::vec3 emissive;
    static float shininess;
    static std::map<Scene *, std::vector<Node *>> addedNodes;
    static std::map<Node *, bool> customMat;
    static auto shapesNames = Shapes::ShapeNameList();
    static int shapeSelected = -1;
    static std::vector<char> name;

    // active scene changed
    if (scene != Scene::Active().get())
    {
        scene = Scene::Active().get();
        selected = -1;
        node = nullptr;
        auto it = addedNodes.find(scene);

        if(it == addedNodes.end())
        {
            addedNodes[scene] = std::vector<Node *>();
        }
    }

    // no active scene
    if (!scene) { return; }

    // begin editor
    Begin("Objects", &UIMainMenu::drawSceneNodes);
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));
    Columns(2);
    Combo("", &shapeSelected, ShapeName, &shapesNames,
          static_cast<int>(shapesNames.size()));
    SameLine();

    if (shapeSelected >= 0 && Button("Create Shape"))
    {
        auto shape = Shapes::GetShape(shapesNames[shapeSelected]);
        scene->rootNode->nodes.push_back(shape);
        scene->rootNode->BuildDrawList();
        addedNodes[scene].push_back(shape.get());
        // add material from shape creator to scene
        auto it = find(scene->materials.begin(), scene->materials.end(),
                       shape->meshes[0]->material);

        if(it == scene->materials.end())
        {
            scene->materials.push_back(shape->meshes[0]->material);
        }

        voxel.RevoxelizeScene();
    }

    for (auto i = 0; i < addedNodes[scene].size(); i++)
    {
        auto &current = addedNodes[scene][i];
        PushID(i);
        BeginGroup();

        // selected becomes the clicked selectable
        if (Selectable(current->name.c_str(), i == selected))
        {
            selected = i;
            node = current;
            position = node->Position();
            rotation = degrees(node->Angles());
            scale = node->Scale();
            // all shapes have only mesh, thus one material
            material = node->meshes[0]->material.get();
            ambient = material->Ambient();
            diffuse = material->Diffuse();
            specular = material->Specular();
            shininess = material->Shininess();
            emissive = material->Emissive();
            // copy name to a standard vector
            name.clear();
            copy(node->name.begin(), node->name.end(), back_inserter(name));
            name.push_back('\0');
        }

        EndGroup();
        PopID();
    }

    NextColumn();

    if (selected >= 0 && node != nullptr)
    {
        if (InputText("Name", name.data(), name.size()))
        {
            node->name = std::string(name.data());
        }

        if (DragFloat3("Position", value_ptr(position), 0.1f))
        {
            node->Position(position);
        }

        if (DragFloat3("Rotation", value_ptr(rotation), 0.1f))
        {
            node->Rotation(radians(rotation));
        }

        if (DragFloat3("Scale", value_ptr(scale), 0.1f))
        {
            node->Scale(scale);
        }

        auto it = customMat.find(node);

        if((it == customMat.end() || !it->second) &&
                Button("Create Custom Material"))
        {
            auto newMesh = std::make_shared<MeshDrawer>(*node->meshes[0]);
            auto newMaterial = std::make_shared<Material>(*node->meshes[0]->material);
            newMaterial->name = node->name + "CustomMat";
            material = newMaterial.get();
            ambient = material->Ambient();
            diffuse = material->Diffuse();
            specular = material->Specular();
            shininess = material->Shininess();
            scene->materials.push_back(newMaterial);
            node->meshes[0] = move(newMesh);
            node->meshes[0]->material = move(newMaterial);
            customMat[node] = true;
        }

        // draw custom material values
        if (ColorEdit3("Ambient", value_ptr(ambient)))
        {
            material->Ambient(ambient);
        }

        if (ColorEdit3("Diffuse", value_ptr(diffuse)))
        {
            material->Diffuse(diffuse);
            voxel.RevoxelizeScene();
        }

        if (ColorEdit3("Specular", value_ptr(specular)))
        {
            material->Specular(specular);
        }

        if (DragFloat("Glossiness", &shininess, 0.001f, 0.0f, 1.0f))
        {
            material->Shininess(shininess);
        }

        if (ColorEdit3("Emissive", value_ptr(emissive)))
        {
            material->Emissive(emissive);
            voxel.RevoxelizeScene();
        }

        if (Button("Delete Shape"))
        {
            static auto &shadowRender = *static_cast<ShadowMapRenderer *>
                                        (assets->renderers["Shadowmapping"].get());
            auto itScene = find_if(scene->rootNode->nodes.begin(),
                                   scene->rootNode->nodes.end(),
                                   [ = ](const std::shared_ptr<Node> &ptr)
            {
                return ptr.get() == node;
            });

            // shape had custom material
            if (it != customMat.end() && it->second)
            {
                auto itMaterial = find(scene->materials.begin(),
                                       scene->materials.end(),
                                       node->meshes[0]->material);

                if (itMaterial != scene->materials.end())
                {
                    scene->materials.erase(itMaterial);
                }
            }

            // remove from scene root node
            if(itScene != scene->rootNode->nodes.end())
            {
                scene->rootNode->nodes.erase(itScene);
                scene->rootNode->BuildDrawList();
            }

            auto itMap = find(addedNodes[scene].begin(),
                              addedNodes[scene].end(), node);

            // remove from scene-node ui map
            if (itMap != addedNodes[scene].end())
            {
                addedNodes[scene].erase(itMap);
            }

            voxel.RevoxelizeScene();
            selected = -1;
            node = nullptr;

            if (shadowRender.Caster()) shadowRender.Caster()->RegisterChange();
        }
    }
    else
    {
        Text("No Node Selected");
    }

    PopStyleVar();
    End();
}
Exemplo n.º 26
0
NewArchiveMember ObjectFactory::createNullThunk(std::vector<uint8_t> &Buffer) {
  static const uint32_t NumberOfSections = 2;
  static const uint32_t NumberOfSymbols = 1;

  // COFF Header
  coff_file_header Header{
      u16(Config->Machine), u16(NumberOfSections), u32(0),
      u32(sizeof(Header) + (NumberOfSections * sizeof(coff_section)) +
          // .idata$5
          sizeof(export_address_table_entry) +
          // .idata$4
          sizeof(export_address_table_entry)),
      u32(NumberOfSymbols), u16(0),
      u16(is32bit() ? IMAGE_FILE_32BIT_MACHINE : 0),
  };
  append(Buffer, Header);

  // Section Header Table
  static const coff_section SectionTable[NumberOfSections] = {
      {{'.', 'i', 'd', 'a', 't', 'a', '$', '5'},
       u32(0),
       u32(0),
       u32(sizeof(export_address_table_entry)),
       u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section)),
       u32(0),
       u32(0),
       u16(0),
       u16(0),
       u32(IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA |
           IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)},
      {{'.', 'i', 'd', 'a', 't', 'a', '$', '4'},
       u32(0),
       u32(0),
       u32(sizeof(export_address_table_entry)),
       u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section) +
           sizeof(export_address_table_entry)),
       u32(0),
       u32(0),
       u16(0),
       u16(0),
       u32(IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA |
           IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)},
  };
  append(Buffer, SectionTable);

  // .idata$5
  static const export_address_table_entry ILT{u32(0)};
  append(Buffer, ILT);

  // .idata$4
  static const export_address_table_entry IAT{u32(0)};
  append(Buffer, IAT);

  // Symbol Table
  coff_symbol16 SymbolTable[NumberOfSymbols] = {
      {{{0, 0, 0, 0, 0, 0, 0, 0}},
       u32(0),
       u16(1),
       u16(0),
       IMAGE_SYM_CLASS_EXTERNAL,
       0},
  };
  reinterpret_cast<StringTableOffset &>(SymbolTable[0].Name).Offset =
      sizeof(uint32_t);
  append(Buffer, SymbolTable);

  // String Table
  writeStringTable(Buffer, {NullThunkSymbolName});

  StringRef F{reinterpret_cast<const char *>(Buffer.data()), Buffer.size()};
  return {MemoryBufferRef{F, DLLName}};
}
Exemplo n.º 27
0
void microfacetNoExpFourierSeries(Float mu_o, Float mu_i, std::complex<Float> eta_,
                                  Float alpha, size_t n, Float phiMax,
                                  std::vector<Float> &result) {

    bool reflect = -mu_i * mu_o > 0;

    Float sinMu2 = math::safe_sqrt((1 - mu_i * mu_i) * (1 - mu_o * mu_o)),
          phiCritical = 0.0f;

    bool conductor = (eta_.imag() != 0.0f);
    std::complex<Float> eta =
        (-mu_i > 0 || conductor) ? eta_ : std::complex<Float>(1) / eta_;

    if (reflect) {
        if (!conductor)
            phiCritical = math::safe_acos((2*eta.real()*eta.real()-mu_i*mu_o-1)/sinMu2);
    } else if (!reflect) {
        if (conductor)
            throw std::runtime_error("lowfreqFourierSeries(): encountered refraction case for a conductor");
        Float etaDenser = (eta.real() > 1 ? eta.real() : 1 / eta.real());
        phiCritical = math::safe_acos((1 - etaDenser * mu_i * mu_o) /
                                      (etaDenser * sinMu2));
    }

    if (!conductor && phiCritical > math::Epsilon &&
        phiCritical < math::Pi - math::Epsilon &&
        phiCritical < phiMax - math::Epsilon) {
        /* Uh oh, some high frequency content leaked in the generally low frequency part.
           Increase the number of coefficients so that we can capture it. Fortunately, this
           happens very rarely. */
        n = std::max(n, (size_t) 100);
    }

    VectorX coeffs(n);
    coeffs.setZero();
    std::function<Float(Float)> integrand = std::bind(
        &microfacetNoExp, mu_o, mu_i, eta_, alpha, std::placeholders::_1);

    const int nEvals = 200;
    if (reflect) {
        if (phiCritical > math::Epsilon && phiCritical < phiMax-math::Epsilon) {
            filonIntegrate(integrand, coeffs.data(), n, nEvals, 0, phiCritical);
            filonIntegrate(integrand, coeffs.data(), n, nEvals, phiCritical, phiMax);
        } else {
            filonIntegrate(integrand, coeffs.data(), n, nEvals, 0, phiMax);
        }
    } else {
        filonIntegrate(integrand, coeffs.data(), n, nEvals, 0,
                       std::min(phiCritical, phiMax));
    }

    if (phiMax < math::Pi - math::Epsilon) {
        /* Precompute some sines and cosines */
        VectorX cosPhi(n), sinPhi(n);
        for (int i=0; i<n; ++i) {
            sinPhi[i] = std::sin(i*phiMax);
            cosPhi[i] = std::cos(i*phiMax);
        }

        /* The fit only occurs on a subset [0, phiMax], where the Fourier
           Fourier basis functions are not orthogonal anymore! The following
           then does a change of basis to proper Fourier coefficients. */
        MatrixX A(n, n);

        for (int i=0; i<n; ++i) {
            for (int j=0; j<=i; ++j) {
                if (i != j) {
                    A(i, j) = A(j, i) = (i * cosPhi[j] * sinPhi[i] -
                                         j * cosPhi[i] * sinPhi[j]) /
                                        (i * i - j * j);
                } else if (i != 0) {
                    A(i, i) = (std::sin(2 * i * phiMax) + 2 * i * phiMax) / (4 * i);
                } else {
                    A(i, i) = phiMax;
                }
            }
        }

        auto svd = A.bdcSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);
        const MatrixX &U = svd.matrixU();
        const MatrixX &V = svd.matrixV();
        const VectorX &sigma = svd.singularValues();

        if (sigma[0] == 0) {
            result.clear();
            result.push_back(0);
            return;
        }

        VectorX temp = VectorX::Zero(n);
        coeffs[0] *= math::Pi;
        coeffs.tail(n-1) *= 0.5 * math::Pi;
        for (int i=0; i<n; ++i) {
            if (sigma[i] < 1e-9f * sigma[0])
                break;
            temp += V.col(i) * U.col(i).dot(coeffs) / sigma[i];
        }
        coeffs = temp;
    }

    result.resize(coeffs.size());
    memcpy(result.data(), coeffs.data(), sizeof(Float) * coeffs.size());
}
Exemplo n.º 28
0
	VectorBuffer(std::vector<CharT> &vec) {
		setg(vec.data(), vec.data(), vec.data() + vec.size());
	}
Exemplo n.º 29
0
void get_tx_tree_hash(const std::vector<Hash>& tx_hashes, Hash& h) {
  tree_hash(tx_hashes.data(), tx_hashes.size(), h);
}
Exemplo n.º 30
0
//==============================================================================
// Vulkan初期化
//==============================================================================
bool initVulkan(HINSTANCE hinst, HWND wnd)
{
	VkResult result;

	//==================================================
	// Vulkanのインスタンス作成
	//==================================================
	VkApplicationInfo applicationInfo = {};
	applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
	applicationInfo.pApplicationName = APPLICATION_NAME;
	applicationInfo.pEngineName = APPLICATION_NAME;
	applicationInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0);

	std::vector<LPCSTR> enabledExtensionsByInstance = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME };

	VkInstanceCreateInfo instanceCreateInfo = {};
	instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	instanceCreateInfo.pNext = nullptr;
	instanceCreateInfo.pApplicationInfo = &applicationInfo;

	if(enabledExtensionsByInstance.empty() == false)
	{
		instanceCreateInfo.enabledExtensionCount = enabledExtensionsByInstance.size();
		instanceCreateInfo.ppEnabledExtensionNames = enabledExtensionsByInstance.data();
	}

	result = vkCreateInstance(&instanceCreateInfo, nullptr, &g_VulkanInstance);
	checkVulkanError(result, TEXT("Vulkanインスタンス作成失敗"));

	//==================================================
	// 物理デバイス(GPUデバイス)
	//==================================================
	// 物理デバイス数を獲得
	uint32_t gpuCount = 0;
	vkEnumeratePhysicalDevices(g_VulkanInstance, &gpuCount, nullptr);
	assert(gpuCount > 0 && TEXT("物理デバイス数の獲得失敗"));

	// 物理デバイス数を列挙
	std::vector<VkPhysicalDevice> physicalDevices(gpuCount);
	result = vkEnumeratePhysicalDevices(g_VulkanInstance, &gpuCount, physicalDevices.data());
	checkVulkanError(result, TEXT("物理デバイスの列挙に失敗しました"));

	// すべてのGPU情報を格納
	g_GPUs.resize(gpuCount);
	for(uint32_t i = 0; i < gpuCount; ++i)
	{
		g_GPUs[i].device = physicalDevices[i];

		// 物理デバイスのプロパティ獲得
		vkGetPhysicalDeviceProperties(g_GPUs[i].device, &g_GPUs[i].deviceProperties);

		// 物理デバイスのメモリプロパティ獲得
		vkGetPhysicalDeviceMemoryProperties(g_GPUs[i].device, &g_GPUs[i].deviceMemoryProperties);
	}

	// ※このサンプルでは最初に列挙されたGPUデバイスを使用する
	g_currentGPU = g_GPUs[0];

	// グラフィックス操作をサポートするキューを検索
	uint32_t queueCount;
	vkGetPhysicalDeviceQueueFamilyProperties(g_currentGPU.device, &queueCount, nullptr);
	assert(queueCount >= 1 && TEXT("物理デバイスキューの検索失敗"));

	std::vector<VkQueueFamilyProperties> queueProps;
	queueProps.resize(queueCount);
	vkGetPhysicalDeviceQueueFamilyProperties(g_currentGPU.device, &queueCount, queueProps.data());

	uint32_t graphicsQueueIndex = 0;
	for(graphicsQueueIndex = 0; graphicsQueueIndex < queueCount; ++graphicsQueueIndex)
	{
		if(queueProps[graphicsQueueIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
		{
			break;
		}
	}
	assert(graphicsQueueIndex < queueCount && TEXT("グラフィックスをサポートするキューを見つけられませんでした"));

	//==================================================
	// Vulkanデバイス作成
	//==================================================
	float queuePrioritie = 0.0f;
	VkDeviceQueueCreateInfo queueCreateInfo = {};
	queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
	queueCreateInfo.queueFamilyIndex = graphicsQueueIndex;
	queueCreateInfo.queueCount = 1;
	queueCreateInfo.pQueuePriorities = &queuePrioritie;

	std::vector<LPCSTR> enabledExtensionsByDevice = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };

	VkDeviceCreateInfo deviceCreateInfo = {};
	deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
	deviceCreateInfo.pNext = nullptr;
	deviceCreateInfo.queueCreateInfoCount = 1;
	deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
	deviceCreateInfo.pEnabledFeatures = nullptr;

	if(enabledExtensionsByDevice.empty() == false)
	{
		deviceCreateInfo.enabledExtensionCount = enabledExtensionsByDevice.size();
		deviceCreateInfo.ppEnabledExtensionNames = enabledExtensionsByDevice.data();
	}

	result = vkCreateDevice(g_currentGPU.device, &deviceCreateInfo, nullptr, &g_VulkanDevice);
	checkVulkanError(result, TEXT("Vulkanデバイス作成失敗"));

	// グラフィックスキュー獲得
	vkGetDeviceQueue(g_VulkanDevice, graphicsQueueIndex, 0, &g_VulkanQueue);

	//==================================================
	// フェンスオブジェクト作成
	//==================================================
	VkFenceCreateInfo fenceCreateInfo = {};
	fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
	fenceCreateInfo.pNext = nullptr;
	fenceCreateInfo.flags = 0;
	result = vkCreateFence(g_VulkanDevice, &fenceCreateInfo, nullptr, &g_VulkanFence);
	checkVulkanError(result, TEXT("フェンスオブジェクト作成失敗"));

	//==================================================
	// 同期(セマフォ)オブジェクト作成
	//==================================================
	VkSemaphoreCreateInfo semaphoreCreateInfo = {};
	semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
	semaphoreCreateInfo.pNext = nullptr;
	semaphoreCreateInfo.flags = 0;

	// コマンドバッファ実行用セマフォ作成
	result = vkCreateSemaphore(g_VulkanDevice, &semaphoreCreateInfo, nullptr, &g_VulkanSemahoreRenderComplete);
	checkVulkanError(result, TEXT("コマンドバッファ実行用セマフォ作成失敗"));

	//==================================================
	// コマンドプール作製
	//==================================================
	VkCommandPoolCreateInfo cmdPoolInfo = {};
	cmdPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
	cmdPoolInfo.queueFamilyIndex = 0;
	cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
	result = vkCreateCommandPool(g_VulkanDevice, &cmdPoolInfo, nullptr, &g_VulkanCommandPool);
	checkVulkanError(result, TEXT("コマンドプール作成失敗"));

	//==================================================
	// コマンドバッファ作成
	//==================================================
	// メモリを確保.
	g_commandBuffers.resize(SWAP_CHAIN_COUNT);

	VkCommandBufferAllocateInfo commandBufferAllocateInfo = {};
	commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
	commandBufferAllocateInfo.pNext = nullptr;
	commandBufferAllocateInfo.commandPool = g_VulkanCommandPool;
	commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
	commandBufferAllocateInfo.commandBufferCount = SWAP_CHAIN_COUNT;

	result = vkAllocateCommandBuffers(g_VulkanDevice, &commandBufferAllocateInfo, g_commandBuffers.data());
	checkVulkanError(result, TEXT("コマンドバッファ作成失敗"));

	//==================================================
	// OS(今回はWin32)用のサーフェスを作成する
	//==================================================
	VkWin32SurfaceCreateInfoKHR surfaceCreateInfo = {};
	surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
	surfaceCreateInfo.hinstance = hinst;
	surfaceCreateInfo.hwnd = wnd;
	result = vkCreateWin32SurfaceKHR(g_VulkanInstance, &surfaceCreateInfo, nullptr, &g_VulkanSurface);
	checkVulkanError(result, TEXT("サーフェス作成失敗"));

	//==================================================
	// スワップチェーンを作成する
	//==================================================
	VkFormat        imageFormat = VK_FORMAT_R8G8B8A8_UNORM;
	VkColorSpaceKHR imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;

	uint32_t surfaceFormatCount = 0;
	result = vkGetPhysicalDeviceSurfaceFormatsKHR(g_currentGPU.device, g_VulkanSurface, &surfaceFormatCount, nullptr);
	checkVulkanError(result, TEXT("サポートしているカラーフォーマット数の獲得失敗"));

	std::vector<VkSurfaceFormatKHR> surfaceFormats;
	surfaceFormats.resize(surfaceFormatCount);
	result = vkGetPhysicalDeviceSurfaceFormatsKHR(g_currentGPU.device, g_VulkanSurface, &surfaceFormatCount, surfaceFormats.data());
	checkVulkanError(result, TEXT("サポートしているカラーフォーマットの獲得失敗"));

	// 一致するカラーフォーマットを検索する
	bool isFind = false;
	for(const auto& surfaceFormat : surfaceFormats)
	{
		if(imageFormat == surfaceFormat.format &&
			imageColorSpace == surfaceFormat.colorSpace)
		{
			isFind = true;
			break;
		}
	}

	if(isFind == false)
	{
		imageFormat = surfaceFormats[0].format;
		imageColorSpace = surfaceFormats[0].colorSpace;
	}

	// サーフェスの機能を獲得する
	VkSurfaceCapabilitiesKHR surfaceCapabilities;
	VkSurfaceTransformFlagBitsKHR surfaceTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
	result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
		g_currentGPU.device,
		g_VulkanSurface,
		&surfaceCapabilities);
	checkVulkanError(result, TEXT("サーフェスの機能の獲得失敗"));

	if((surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) == 0)
	{
		surfaceTransform = surfaceCapabilities.currentTransform;
	}

	// プレゼント機能を獲得する
	VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
	uint32_t presentModeCount;
	result = vkGetPhysicalDeviceSurfacePresentModesKHR(
		g_currentGPU.device,
		g_VulkanSurface,
		&presentModeCount,
		nullptr);
	checkVulkanError(result, TEXT("プレゼント機能数の獲得失敗"));

	std::vector<VkPresentModeKHR> presentModes;
	presentModes.resize(presentModeCount);
	result = vkGetPhysicalDeviceSurfacePresentModesKHR(
		g_currentGPU.device,
		g_VulkanSurface,
		&presentModeCount,
		presentModes.data());
	checkVulkanError(result, TEXT("プレゼント機能の獲得失敗"));

	for(const auto& presentModeInfo : presentModes)
	{
		if(presentModeInfo == VK_PRESENT_MODE_MAILBOX_KHR)
		{
			presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
			break;
		}
		if(presentModeInfo == VK_PRESENT_MODE_IMMEDIATE_KHR)
		{
			presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
		}
	}

	presentModes.clear();

	uint32_t desiredSwapChainImageCount = surfaceCapabilities.minImageCount + 1;
	if(surfaceCapabilities.maxImageCount > 0 && desiredSwapChainImageCount > surfaceCapabilities.maxImageCount)
	{
		desiredSwapChainImageCount = surfaceCapabilities.maxImageCount;
	}

	// スワップチェーン作成
	VkSwapchainCreateInfoKHR swapchainCreateInfo = {};
	swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
	swapchainCreateInfo.pNext = nullptr;
	swapchainCreateInfo.flags = 0;
	swapchainCreateInfo.surface = g_VulkanSurface;
	swapchainCreateInfo.minImageCount = desiredSwapChainImageCount;
	swapchainCreateInfo.imageFormat = imageFormat;
	swapchainCreateInfo.imageColorSpace = imageColorSpace;
	swapchainCreateInfo.imageExtent = { SCREEN_WIDTH, SCREEN_HEIGHT };
	swapchainCreateInfo.imageArrayLayers = 1;
	swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
	swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
	swapchainCreateInfo.queueFamilyIndexCount = 0;
	swapchainCreateInfo.pQueueFamilyIndices = nullptr;
	swapchainCreateInfo.preTransform = surfaceTransform;
	swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
	swapchainCreateInfo.presentMode = presentMode;
	swapchainCreateInfo.clipped = VK_TRUE;
	swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE;

	result = vkCreateSwapchainKHR(g_VulkanDevice, &swapchainCreateInfo, nullptr, &g_VulkanSwapChain);
	checkVulkanError(result, TEXT("サーフェス作成失敗"));

	//==================================================
	// イメージの作成
	//==================================================
	uint32_t swapChainCount = 0;
	result = vkGetSwapchainImagesKHR(g_VulkanDevice, g_VulkanSwapChain, &swapChainCount, nullptr);
	checkVulkanError(result, TEXT("スワップチェーンイメージ数の獲得失敗"));

	g_backBuffersTextures.resize(swapChainCount);

	std::vector<VkImage> images;
	images.resize(swapChainCount);
	result = vkGetSwapchainImagesKHR(g_VulkanDevice, g_VulkanSwapChain, &swapChainCount, images.data());
	checkVulkanError(result, TEXT("スワップチェーンイメージの獲得失敗"));

	for(uint32_t i = 0; i < swapChainCount; ++i)
	{
		g_backBuffersTextures[i].image = images[i];
	}

	images.clear();

	//==================================================
	// イメージビューの生成
	//==================================================
	for(auto& backBuffer : g_backBuffersTextures)
	{
		VkImageViewCreateInfo imageViewCreateInfo = {};
		imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
		imageViewCreateInfo.pNext = nullptr;
		imageViewCreateInfo.flags = 0;
		imageViewCreateInfo.image = backBuffer.image;
		imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
		imageViewCreateInfo.format = imageFormat;
		imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_R;
		imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_G;
		imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_B;
		imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_A;
		imageViewCreateInfo.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };

		result = vkCreateImageView(g_VulkanDevice, &imageViewCreateInfo, nullptr, &backBuffer.view);
		checkVulkanError(result, TEXT("イメージビューの作成失敗"));

		setImageLayout(
			g_VulkanDevice,
			g_commandBuffers[g_currentBufferIndex],
			backBuffer.image,
			VK_IMAGE_ASPECT_COLOR_BIT,
			VK_IMAGE_LAYOUT_UNDEFINED,
			VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
	}

	//==================================================
	// 深度ステンシルバッファの生成
	//==================================================
	VkFormat depthFormat = VK_FORMAT_D24_UNORM_S8_UINT;

	VkImageTiling imageTiling;
	VkFormatProperties formatProperties;
	vkGetPhysicalDeviceFormatProperties(g_currentGPU.device, depthFormat, &formatProperties);

	if(formatProperties.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
	{
		imageTiling = VK_IMAGE_TILING_LINEAR;
	}
	else if(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
	{
		imageTiling = VK_IMAGE_TILING_OPTIMAL;
	}
	else
	{
		checkVulkanError(VK_RESULT_MAX_ENUM, TEXT("サポートされていないフォーマットです"));
		return false;
	}

	VkImageCreateInfo imageCreateInfo = {};
	imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
	imageCreateInfo.pNext = nullptr;
	imageCreateInfo.flags = 0;
	imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
	imageCreateInfo.format = depthFormat;
	imageCreateInfo.extent.width = SCREEN_WIDTH;
	imageCreateInfo.extent.height = SCREEN_HEIGHT;
	imageCreateInfo.extent.depth = 1;
	imageCreateInfo.mipLevels = 1;
	imageCreateInfo.arrayLayers = 1;
	imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
	imageCreateInfo.tiling = imageTiling;
	imageCreateInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
	imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
	imageCreateInfo.queueFamilyIndexCount = 0;
	imageCreateInfo.pQueueFamilyIndices = nullptr;
	imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;

	result = vkCreateImage(g_VulkanDevice, &imageCreateInfo, nullptr, &g_depthBufferTexture.image);
	checkVulkanError(result, TEXT("深度テクスチャ用イメージビュー作成失敗"));

	// メモリ要件を獲得
	VkMemoryRequirements memoryRequirements;
	vkGetImageMemoryRequirements(g_VulkanDevice, g_depthBufferTexture.image, &memoryRequirements);

	VkFlags requirementsMask = 0;
	uint32_t typeBits = memoryRequirements.memoryTypeBits;
	uint32_t typeIndex = 0;

	for(const auto& memoryType : g_currentGPU.deviceMemoryProperties.memoryTypes)
	{
		if((typeBits & 0x1) == 1)
		{
			if((memoryType.propertyFlags & requirementsMask) == requirementsMask)
			{
				break;
			}
		}
		typeBits >>= 1;
		++typeIndex;
	}

	// メモリ確保
	VkMemoryAllocateInfo allocInfo = {};
	allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
	allocInfo.pNext = nullptr;
	allocInfo.allocationSize = memoryRequirements.size;
	allocInfo.memoryTypeIndex = typeIndex;

	result = vkAllocateMemory(g_VulkanDevice, &allocInfo, nullptr, &g_depthBufferTexture.memory);
	checkVulkanError(result, TEXT("深度テクスチャ用メモリ確保失敗"));

	result = vkBindImageMemory(g_VulkanDevice, g_depthBufferTexture.image, g_depthBufferTexture.memory, 0);
	checkVulkanError(result, TEXT("深度テクスチャメモリにバインド失敗"));

	VkImageViewCreateInfo imageViewCreateInfo = {};
	imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
	imageViewCreateInfo.pNext = nullptr;
	imageViewCreateInfo.image = g_depthBufferTexture.image;
	imageViewCreateInfo.format = depthFormat;
	imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_R;
	imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_G;
	imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_B;
	imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_A;
	imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
	imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
	imageViewCreateInfo.subresourceRange.levelCount = 1;
	imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
	imageViewCreateInfo.subresourceRange.layerCount = 1;
	imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
	imageViewCreateInfo.flags = 0;

	result = vkCreateImageView(g_VulkanDevice, &imageViewCreateInfo, nullptr, &g_depthBufferTexture.view);
	checkVulkanError(result, TEXT("深度テクスチャイメージビュー作成失敗"));

	setImageLayout(
		g_VulkanDevice,
		g_commandBuffers[g_currentBufferIndex],
		g_depthBufferTexture.image,
		VK_IMAGE_ASPECT_DEPTH_BIT,
		VK_IMAGE_LAYOUT_UNDEFINED,
		VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);

	//==================================================
	// フレームバッファの生成
	//==================================================
	VkImageView attachments[2];	// 0=カラーバッファ、1=深度バッファ

	VkFramebufferCreateInfo frameBufferCreateInfo = {};
	frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
	frameBufferCreateInfo.pNext = nullptr;
	frameBufferCreateInfo.flags = 0;
	frameBufferCreateInfo.renderPass = VK_NULL_HANDLE;
	frameBufferCreateInfo.attachmentCount = 2;
	frameBufferCreateInfo.pAttachments = attachments;
	frameBufferCreateInfo.width = SCREEN_WIDTH;
	frameBufferCreateInfo.height = SCREEN_HEIGHT;
	frameBufferCreateInfo.layers = 1;

	g_frameBuffers.resize(SWAP_CHAIN_COUNT);
	for(uint32_t i = 0; i < SWAP_CHAIN_COUNT; ++i)
	{
		attachments[0] = g_backBuffersTextures[i].view;
		attachments[1] = g_depthBufferTexture.view;
		auto result = vkCreateFramebuffer(g_VulkanDevice, &frameBufferCreateInfo, nullptr, &g_frameBuffers[i]);
		checkVulkanError(result, TEXT("フレームバッファ作成失敗"));
	}

	return true;
}