<commit_before>#ifndef NEU_CONVOLUTION_LAYER_CONVOLUTION_LAYER_IMPL_HPP
#define NEU_CONVOLUTION_LAYER_CONVOLUTION_LAYER_IMPL_HPP
//20151005
#include <gsl.h>
#include <neu/validation.hpp>
#include <neu/basic_type.hpp>
#include <neu/kernel.hpp>
#include <neu/convolution_layer/indices.hpp>
namespace neu {
	template<typename LearningRateGen>
	class convolution_layer {
	public:
		convolution_layer(
			std::size_t input_width, std::size_t output_width,
			std::size_t filter_width,
			std::size_t input_channel_num, std::size_t output_channel_num,
			std::size_t stride, std::size_t pad, std::size_t batch_size,
			gpu_vector const& filters, gpu_vector const& bias,
			LearningRateGen const& learning_rate_gen,
			convolution_indices const& indices,
			kernel const& convolution_kernel,
			kernel const& convolution_back_kernel,
			kernel const& update_del_filters_kernel)
		: input_width_(input_width), filter_width_(filter_width),
		input_channel_num_(input_channel_num), output_channel_num_(output_channel_num),
		stride_(stride), pad_(pad), batch_size_(batch_size),
		indices_(indices),
		filters_(filters), bias_(bias),
		learning_rate_gen_(learning_rate_gen),
		convolution_kernel_(convolution_kernel),
		convolution_back_kernel_(convolution_back_kernel),
		update_del_filters_kernel_(update_del_filters_kernel),
		output_width_(output_width),
		input_(input_width_*input_width_*input_channel_num_*batch_size_),
		next_input_(output_width_*output_width_*output_channel_num_*batch_size_),
		delta_(next_input_.size()),
		prev_delta_(input_.size()),
		del_filters_(filters.size()),
		del_bias_(bias.size()) {}

		decltype(auto) get_filters() const { return (filters_); }
		decltype(auto) get_bias() const { return (bias_); }

		decltype(auto) forward(gpu_vector const& input) {
			Expects(is_all_of_finite(input));
			input_ = input;
			auto event = neu::enqueue_nd_range_kernel<3>(convolution_kernel_,
				{0, 0, 0}, {output_width_, output_width_, batch_size_},
				static_cast<int>(input_width_), static_cast<int>(output_width_),
				static_cast<int>(filter_width_),
				static_cast<int>(input_channel_num_),
				static_cast<int>(output_channel_num_),
				static_cast<int>(stride_), static_cast<int>(pad_),
				input, next_input_, filters_, bias_);
			event.wait();
			Ensures(is_all_of_finite(next_input_));
		}
		decltype(auto) get_next_input() const {
			return (next_input_);
		}

		decltype(auto) backward(gpu_vector const& delta) {
			Expects(is_all_of_finite(delta));
			delta_ = delta;
			auto event = neu::enqueue_nd_range_kernel<2>(convolution_back_kernel_,
				{0, 0}, {input_width_*input_width_, batch_size_},
				indices_.indices_range_list_for_input,
				indices_.output_indices_list_for_input,
				indices_.filter_indices_list_for_input,
				static_cast<int>(input_width_), static_cast<int>(output_width_),
				static_cast<int>(filter_width_),
				static_cast<int>(input_channel_num_),
				static_cast<int>(output_channel_num_),
				prev_delta_, delta, filters_);
			event.wait();
			Ensures(is_all_of_finite(prev_delta_));
		}
		decltype(auto) get_prev_delta() const { return (prev_delta_); }

		decltype(auto) update() {
			auto event = neu::enqueue_nd_range_kernel<3>(update_del_filters_kernel_,
				{0, 0, 0}, {filter_width_, filter_width_, output_channel_num_},
				static_cast<int>(input_width_), static_cast<int>(output_width_),
				static_cast<int>(filter_width_),
				static_cast<int>(input_channel_num_),
				static_cast<int>(output_channel_num_),
				static_cast<int>(stride_), static_cast<int>(pad_),
				static_cast<int>(batch_size_),
				input_, delta_, del_filters_, del_bias_);
			event.wait();
			Ensures(is_all_of_finite(del_filters_));
			Ensures(is_all_of_finite(del_bias_));
			learning_rate_gen_(filters_, bias_, del_filters_, del_bias_);
			Ensures(is_all_of_finite(filters_));
			Ensures(is_all_of_finite(bias_));
		}

		decltype(auto) get_del_filters() const { return (del_filters_); }
		decltype(auto) get_del_bias() const { return (del_bias_); }

	private:
		std::size_t input_width_;
		std::size_t filter_width_;
		std::size_t input_channel_num_;
		std::size_t output_channel_num_;
		std::size_t stride_;
		std::size_t pad_;
		std::size_t batch_size_;

		convolution_indices indices_;

		gpu_vector filters_;
		gpu_vector bias_;

		LearningRateGen learning_rate_gen_;

		boost::compute::kernel convolution_kernel_;
		boost::compute::kernel convolution_back_kernel_;
		boost::compute::kernel update_del_filters_kernel_;

		std::size_t output_width_;

		gpu_vector input_;
		gpu_vector next_input_;
		gpu_vector delta_;
		gpu_vector prev_delta_;

		gpu_vector del_filters_;
		gpu_vector del_bias_;
	};
}// namespace neu

#endif //NEU_CONVOLUTION_LAYER_CONVOLUTION_LAYER_IMPL_HPP
<commit_msg>add test_forward in convolution_layer<commit_after>#ifndef NEU_CONVOLUTION_LAYER_CONVOLUTION_LAYER_IMPL_HPP
#define NEU_CONVOLUTION_LAYER_CONVOLUTION_LAYER_IMPL_HPP
//20151005
#include <gsl.h>
#include <neu/validation.hpp>
#include <neu/basic_type.hpp>
#include <neu/kernel.hpp>
#include <neu/convolution_layer/indices.hpp>
namespace neu {
	template<typename LearningRateGen>
	class convolution_layer {
	public:
		convolution_layer(
			std::size_t input_width, std::size_t output_width,
			std::size_t filter_width,
			std::size_t input_channel_num, std::size_t output_channel_num,
			std::size_t stride, std::size_t pad, std::size_t batch_size,
			gpu_vector const& filters, gpu_vector const& bias,
			LearningRateGen const& learning_rate_gen,
			convolution_indices const& indices,
			kernel const& convolution_kernel,
			kernel const& convolution_back_kernel,
			kernel const& update_del_filters_kernel)
		: input_width_(input_width), filter_width_(filter_width),
		input_channel_num_(input_channel_num), output_channel_num_(output_channel_num),
		stride_(stride), pad_(pad), batch_size_(batch_size),
		indices_(indices),
		filters_(filters), bias_(bias),
		learning_rate_gen_(learning_rate_gen),
		convolution_kernel_(convolution_kernel),
		convolution_back_kernel_(convolution_back_kernel),
		update_del_filters_kernel_(update_del_filters_kernel),
		output_width_(output_width),
		input_(input_width_*input_width_*input_channel_num_*batch_size_),
		next_input_(output_width_*output_width_*output_channel_num_*batch_size_),
		delta_(next_input_.size()),
		prev_delta_(input_.size()),
		del_filters_(filters.size()),
		del_bias_(bias.size()) {}

		decltype(auto) get_filters() const { return (filters_); }
		decltype(auto) get_bias() const { return (bias_); }

		decltype(auto) test_forward(gpu_vector const& input) {
			const auto input_dim = input_width_*input_width_*input_channel_num_;
			Expects(input.size()%input_dim==0);
			Expects(is_all_of_finite(input));
			auto event = neu::enqueue_nd_range_kernel<3>(convolution_kernel_,
				{0, 0, 0},
				{output_width_, output_width_, input.size()/input_dim},
				static_cast<int>(input_width_), static_cast<int>(output_width_),
				static_cast<int>(filter_width_),
				static_cast<int>(input_channel_num_),
				static_cast<int>(output_channel_num_),
				static_cast<int>(stride_), static_cast<int>(pad_),
				input, next_input_, filters_, bias_);
			event.wait();
			Ensures(is_all_of_finite(next_input_));
		}
		decltype(auto) forward(gpu_vector const& input) {
			Expects(input.size() == input_.size());
			test_forward(input);
			input_ = input;
		}
		decltype(auto) get_next_input() const { return (next_input_); }

		decltype(auto) backward(gpu_vector const& delta) {
			Expects(is_all_of_finite(delta));
			delta_ = delta;
			auto event = neu::enqueue_nd_range_kernel<2>(convolution_back_kernel_,
				{0, 0}, {input_width_*input_width_, batch_size_},
				indices_.indices_range_list_for_input,
				indices_.output_indices_list_for_input,
				indices_.filter_indices_list_for_input,
				static_cast<int>(input_width_), static_cast<int>(output_width_),
				static_cast<int>(filter_width_),
				static_cast<int>(input_channel_num_),
				static_cast<int>(output_channel_num_),
				prev_delta_, delta, filters_);
			event.wait();
			Ensures(is_all_of_finite(prev_delta_));
		}
		decltype(auto) get_prev_delta() const { return (prev_delta_); }

		decltype(auto) update() {
			auto event = neu::enqueue_nd_range_kernel<3>(update_del_filters_kernel_,
				{0, 0, 0}, {filter_width_, filter_width_, output_channel_num_},
				static_cast<int>(input_width_), static_cast<int>(output_width_),
				static_cast<int>(filter_width_),
				static_cast<int>(input_channel_num_),
				static_cast<int>(output_channel_num_),
				static_cast<int>(stride_), static_cast<int>(pad_),
				static_cast<int>(batch_size_),
				input_, delta_, del_filters_, del_bias_);
			event.wait();
			Ensures(is_all_of_finite(del_filters_));
			Ensures(is_all_of_finite(del_bias_));
			learning_rate_gen_(filters_, bias_, del_filters_, del_bias_);
			Ensures(is_all_of_finite(filters_));
			Ensures(is_all_of_finite(bias_));
		}

		decltype(auto) get_del_filters() const { return (del_filters_); }
		decltype(auto) get_del_bias() const { return (del_bias_); }

	private:
		std::size_t input_width_;
		std::size_t filter_width_;
		std::size_t input_channel_num_;
		std::size_t output_channel_num_;
		std::size_t stride_;
		std::size_t pad_;
		std::size_t batch_size_;

		convolution_indices indices_;

		gpu_vector filters_;
		gpu_vector bias_;

		LearningRateGen learning_rate_gen_;

		boost::compute::kernel convolution_kernel_;
		boost::compute::kernel convolution_back_kernel_;
		boost::compute::kernel update_del_filters_kernel_;

		std::size_t output_width_;

		gpu_vector input_;
		gpu_vector next_input_;
		gpu_vector delta_;
		gpu_vector prev_delta_;

		gpu_vector del_filters_;
		gpu_vector del_bias_;
	};
}// namespace neu

#endif //NEU_CONVOLUTION_LAYER_CONVOLUTION_LAYER_IMPL_HPP
<|endoftext|>


<commit_before>#ifndef _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_
#define _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_

/// Wifi not associated to access point: continuous short blinks.
#define WIFI_BLINK_NOTASSOCIATED  0b1010
/// Waiting for IP address: double short blink, pause, double short blink, ...
#define WIFI_BLINK_ASSOC_NOIP  0b101000
/// Connecting to hub: long blinks
#define WIFI_BLINK_CONNECTING  0b1100
/// Connecting to hub: long blinks
#define WIFI_BLINK_FAILED  0b10101100

enum class WlanState : uint8_t
{
    OK = 0,
    NOT_ASSOCIATED = 1,
    NO_IP,
    NO_CONNECTION,
    CONNECTING,
    MDNS_LOOKUP = 5,
    CONNECT_MDNS,
    CONNECT_STATIC,
    CONNECT_FAILED,
    CONNECTION_LOST,
    UPDATE_DISPLAY = 20,
};

extern "C" {
/// Name of wifi accesspoint to connect to.
extern char WIFI_SSID[];
/// Password of wifi connection. If empty, use no encryption.
extern char WIFI_PASS[];
/// Hostname at which the OpenLCB hub is at.
extern char WIFI_HUB_HOSTNAME[];
/// Port number of the OpenLCB hub.
extern int WIFI_HUB_PORT;
}

#endif // _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_
<commit_msg>Add role defines.<commit_after>#ifndef _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_
#define _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_

/// Wifi not associated to access point: continuous short blinks.
#define WIFI_BLINK_NOTASSOCIATED  0b1010
/// Waiting for IP address: double short blink, pause, double short blink, ...
#define WIFI_BLINK_ASSOC_NOIP  0b101000
/// Connecting to hub: long blinks
#define WIFI_BLINK_CONNECTING  0b1100
/// Connecting to hub: long blinks
#define WIFI_BLINK_FAILED  0b10101100

enum class WlanState : uint8_t
{
    OK = 0,
    NOT_ASSOCIATED = 1,
    NO_IP,
    NO_CONNECTION,
    CONNECTING,
    MDNS_LOOKUP = 5,
    CONNECT_MDNS,
    CONNECT_STATIC,
    CONNECT_FAILED,
    CONNECTION_LOST,
    UPDATE_DISPLAY = 20,
};

/** Operating Role.
 */
enum class WlanRole : uint8_t
{
    UNKNOWN = 0, /**< Wi-Fi station mode */
    STA,         /**< Wi-Fi station mode */
    AP           /**< Wi-Fi access point mode */
};

extern "C" {
/// Name of wifi accesspoint to connect to.
extern char WIFI_SSID[];
/// Password of wifi connection. If empty, use no encryption.
extern char WIFI_PASS[];
/// Hostname at which the OpenLCB hub is at.
extern char WIFI_HUB_HOSTNAME[];
/// Port number of the OpenLCB hub.
extern int WIFI_HUB_PORT;
}

#endif // _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: extensionlistbox.hxx,v $
 *
 * $Revision: 1.2 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVTOOLS_EXTENSIONLISTBOX_HXX
#define _SVTOOLS_EXTENSIONLISTBOX_HXX

#include <vcl/ctrl.hxx>
#include <rtl/ustring.hxx>

// ============================================================================

namespace svt
{

#define EXTENSION_LISTBOX_ENTRY_NOTFOUND (sal_Int32) 0xFFFFFFFF

// ============================================================================

/** This abstract class provides methods to implement an extension list box.
    This header is needed for the automatic test tool
*/
class IExtensionListBox: public Control
{
public:
    IExtensionListBox( Window* pParent, WinBits nWinStyle = 0 ): Control( pParent, nWinStyle ){}

    /** @return  The count of the entries in the list box. */
    virtual sal_Int32 getItemCount() const = 0;

    /** @return  The index of the first selected entry in the list box.
        When nothing is selected, which is the case when getItemCount returns '0',
        then this function returns EXTENSION_LISTBOX_ENTRY_NOTFOUND */
    virtual sal_Int32 getSelIndex() const = 0;

    /** @return  The item name of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemName( sal_Int32 index ) const = 0;

    /** @return  The version string of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemVersion( sal_Int32 index ) const = 0;

    /** @return  The description string of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemDescription( sal_Int32 index ) const = 0;

    /** The entry at the given position will be selected
        Index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual void select( sal_Int32 index ) = 0;

    /** The first found entry with the given name will be selected
        When there was no entry found with the name, the selection doesn't change.
        Please note that there might be more than one entry with the same
        name, because:
            1. the name is not unique
            2. one extension can be installed as user and shared extension.
    */
    virtual void select( const ::rtl::OUString & sName ) = 0;
};
// ============================================================================

} // namespace svt

// ============================================================================

#endif // _SVTOOLS_EXTENSIONLISTBOX_HXX

<commit_msg>INTEGRATION: CWS extmgrui04 (1.2.52); FILE MERGED 2008/06/18 08:40:17 dv 1.2.52.1: #i90143# Allowed access to publisher text and link for automatic testing<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: extensionlistbox.hxx,v $
 *
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVTOOLS_EXTENSIONLISTBOX_HXX
#define _SVTOOLS_EXTENSIONLISTBOX_HXX

#include <vcl/ctrl.hxx>
#include <rtl/ustring.hxx>

// ============================================================================

namespace svt
{

#define EXTENSION_LISTBOX_ENTRY_NOTFOUND (sal_Int32) 0xFFFFFFFF

// ============================================================================

/** This abstract class provides methods to implement an extension list box.
    This header is needed for the automatic test tool
*/
class IExtensionListBox: public Control
{
public:
    IExtensionListBox( Window* pParent, WinBits nWinStyle = 0 ): Control( pParent, nWinStyle ){}

    /** @return  The count of the entries in the list box. */
    virtual sal_Int32 getItemCount() const = 0;

    /** @return  The index of the first selected entry in the list box.
        When nothing is selected, which is the case when getItemCount returns '0',
        then this function returns EXTENSION_LISTBOX_ENTRY_NOTFOUND */
    virtual sal_Int32 getSelIndex() const = 0;

    /** @return  The item name of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemName( sal_Int32 index ) const = 0;

    /** @return  The version string of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemVersion( sal_Int32 index ) const = 0;

    /** @return  The description string of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemDescription( sal_Int32 index ) const = 0;

    /** @return  The publisher string of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemPublisher( sal_Int32 index ) const = 0;

    /** @return  The link behind the publisher text of the entry with the given index
        The index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual ::rtl::OUString getItemPublisherLink( sal_Int32 index ) const = 0;

    /** The entry at the given position will be selected
        Index starts with 0.
        Throws an com::sun::star::lang::IllegalArgumentException, when the position is invalid. */
    virtual void select( sal_Int32 index ) = 0;

    /** The first found entry with the given name will be selected
        When there was no entry found with the name, the selection doesn't change.
        Please note that there might be more than one entry with the same
        name, because:
            1. the name is not unique
            2. one extension can be installed as user and shared extension.
    */
    virtual void select( const ::rtl::OUString & sName ) = 0;
};
// ============================================================================

} // namespace svt

// ============================================================================

#endif // _SVTOOLS_EXTENSIONLISTBOX_HXX

<|endoftext|>


<commit_before>#include "swift/extractor/visitors/TypeVisitor.h"

namespace codeql {
void TypeVisitor::visit(swift::TypeBase* type) {
  TypeVisitorBase<TypeVisitor>::visit(type);
  auto label = dispatcher_.fetchLabel(type);
  auto canonical = type->getCanonicalType().getPointer();
  auto canonicalLabel = (canonical == type) ? label : dispatcher_.fetchLabel(canonical);
  dispatcher_.emit(TypesTrap{label, type->getString(), canonicalLabel});
}

codeql::TypeRepr TypeVisitor::translateTypeRepr(const swift::TypeRepr& typeRepr, swift::Type type) {
  auto entry = dispatcher_.createEntry(typeRepr);
  entry.type = dispatcher_.fetchOptionalLabel(type);
  return entry;
}

void TypeVisitor::visitProtocolType(swift::ProtocolType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(ProtocolTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitEnumType(swift::EnumType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(EnumTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitStructType(swift::StructType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(StructTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitClassType(swift::ClassType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(ClassTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitFunctionType(swift::FunctionType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(FunctionTypesTrap{label});
  emitAnyFunctionType(type, label);
}

void TypeVisitor::visitTupleType(swift::TupleType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(TupleTypesTrap{label});
  auto i = 0u;
  for (const auto& e : type->getElements()) {
    auto typeTag = dispatcher_.fetchLabel(e.getType());
    dispatcher_.emit(TupleTypeTypesTrap{label, i, typeTag});
    if (e.hasName()) {
      dispatcher_.emit(TupleTypeNamesTrap{label, i, e.getName().str().str()});
    }
    ++i;
  }
}

void TypeVisitor::visitBoundGenericEnumType(swift::BoundGenericEnumType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BoundGenericEnumTypesTrap{label});
  emitBoundGenericType(type, label);
}

void TypeVisitor::visitMetatypeType(swift::MetatypeType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(MetatypeTypesTrap{label});
}

void TypeVisitor::visitExistentialMetatypeType(swift::ExistentialMetatypeType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(ExistentialMetatypeTypesTrap{label});
}

void TypeVisitor::visitBoundGenericStructType(swift::BoundGenericStructType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BoundGenericStructTypesTrap{label});
  emitBoundGenericType(type, label);
}

void TypeVisitor::visitTypeAliasType(swift::TypeAliasType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getDecl() && "expect TypeAliasType to have Decl");
  dispatcher_.emit(TypeAliasTypesTrap{label, dispatcher_.fetchLabel(type->getDecl())});
}

void TypeVisitor::visitBuiltinIntegerLiteralType(swift::BuiltinIntegerLiteralType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BuiltinIntegerLiteralTypesTrap{label});
}

void TypeVisitor::visitBuiltinFloatType(swift::BuiltinFloatType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BuiltinFloatTypesTrap{label});
}

void TypeVisitor::visitBuiltinIntegerType(swift::BuiltinIntegerType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  auto width = type->getWidth();
  if (width.isFixedWidth()) {
    dispatcher_.emit(BuiltinIntegerTypeWidthsTrap{label, width.getFixedWidth()});
  }
  dispatcher_.emit(BuiltinIntegerTypesTrap{label});
}

void TypeVisitor::visitBoundGenericClassType(swift::BoundGenericClassType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BoundGenericClassTypesTrap{label});
  emitBoundGenericType(type, label);
}

void TypeVisitor::visitDependentMemberType(swift::DependentMemberType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getBase() && "expect TypeAliasType to have Base");
  assert(type->getAssocType() && "expect TypeAliasType to have AssocType");
  auto baseLabel = dispatcher_.fetchLabel(type->getBase());
  auto assocTypeDeclLabel = dispatcher_.fetchLabel(type->getAssocType());
  dispatcher_.emit(DependentMemberTypesTrap{label, baseLabel, assocTypeDeclLabel});
}

void TypeVisitor::visitParenType(swift::ParenType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getUnderlyingType() && "expect ParenType to have UnderlyingType");
  auto typeLabel = dispatcher_.fetchLabel(type->getUnderlyingType());
  dispatcher_.emit(ParenTypesTrap{label, typeLabel});
}

codeql::OptionalType TypeVisitor::translateOptionalType(const swift::OptionalType& type) {
  auto entry = createTypeEntry(type);
  fillUnarySyntaxSugarType(type, entry);
  return entry;
}

codeql::ArraySliceType TypeVisitor::translateArraySliceType(const swift::ArraySliceType& type) {
  auto entry = createTypeEntry(type);
  fillUnarySyntaxSugarType(type, entry);
  return entry;
}

void TypeVisitor::visitDictionaryType(swift::DictionaryType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  auto keyLabel = dispatcher_.fetchLabel(type->getKeyType());
  auto valueLabel = dispatcher_.fetchLabel(type->getValueType());
  dispatcher_.emit(DictionaryTypesTrap{label, keyLabel, valueLabel});
}

void TypeVisitor::visitGenericFunctionType(swift::GenericFunctionType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(GenericFunctionTypesTrap{label});
  emitAnyFunctionType(type, label);
  auto i = 0u;
  for (auto p : type->getGenericParams()) {
    dispatcher_.emit(GenericFunctionTypeGenericParamsTrap{label, i++, dispatcher_.fetchLabel(p)});
  }
}

void TypeVisitor::visitGenericTypeParamType(swift::GenericTypeParamType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(GenericTypeParamTypesTrap{label});
}

void TypeVisitor::visitLValueType(swift::LValueType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getObjectType() && "expect LValueType to have ObjectType");
  dispatcher_.emit(LValueTypesTrap{label, dispatcher_.fetchLabel(type->getObjectType())});
}

codeql::PrimaryArchetypeType TypeVisitor::translatePrimaryArchetypeType(
    const swift::PrimaryArchetypeType& type) {
  auto entry = createTypeEntry(type);
  fillArchetypeType(type, entry);
  return entry;
}

void TypeVisitor::visitUnboundGenericType(swift::UnboundGenericType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(UnboundGenericTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitBoundGenericType(swift::BoundGenericType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  emitBoundGenericType(type, label);
}

void TypeVisitor::fillUnarySyntaxSugarType(const swift::UnarySyntaxSugarType& type,
                                           codeql::UnarySyntaxSugarType& entry) {
  assert(type.getBaseType() && "expect UnarySyntaxSugarType to have BaseType");
  entry.base_type = dispatcher_.fetchLabel(type.getBaseType());
}

void TypeVisitor::emitAnyFunctionType(const swift::AnyFunctionType* type,
                                      TrapLabel<AnyFunctionTypeTag> label) {
  assert(type->getResult() && "expect FunctionType to have Result");
  dispatcher_.emit(AnyFunctionTypesTrap{label, dispatcher_.fetchLabel(type->getResult())});
  auto i = 0u;
  for (const auto& p : type->getParams()) {
    assert(p.getPlainType() && "expect Param to have PlainType");
    dispatcher_.emit(
        AnyFunctionTypeParamTypesTrap{label, i, dispatcher_.fetchLabel(p.getPlainType())});
    if (p.hasLabel()) {
      dispatcher_.emit(AnyFunctionTypeParamLabelsTrap{label, i, p.getLabel().str().str()});
    }
    ++i;
  }

  if (type->isThrowing()) {
    dispatcher_.emit(AnyFunctionTypeIsThrowingTrap{label});
  }

  if (type->isAsync()) {
    dispatcher_.emit(AnyFunctionTypeIsAsyncTrap{label});
  }
}

void TypeVisitor::emitBoundGenericType(swift::BoundGenericType* type,
                                       TrapLabel<BoundGenericTypeTag> label) {
  auto i = 0u;
  for (const auto& t : type->getGenericArgs()) {
    dispatcher_.emit(BoundGenericTypeArgTypesTrap{label, i++, dispatcher_.fetchLabel(t)});
  }
  emitAnyGenericType(type, label);
}

void TypeVisitor::emitAnyGenericType(swift::AnyGenericType* type,
                                     TrapLabel<AnyGenericTypeTag> label) {
  assert(type->getDecl() && "expect AnyGenericType to have Decl");
  dispatcher_.emit(AnyGenericTypesTrap{label, dispatcher_.fetchLabel(type->getDecl())});
  if (auto parent = type->getParent()) {
    dispatcher_.emit(AnyGenericTypeParentsTrap{label, dispatcher_.fetchLabel(parent)});
  }
}

codeql::NestedArchetypeType TypeVisitor::translateNestedArchetypeType(
    const swift::NestedArchetypeType& type) {
  auto entry = createTypeEntry(type);
  entry.parent = dispatcher_.fetchLabel(type.getParent());
  entry.associated_type_declaration = dispatcher_.fetchLabel(type.getAssocType());
  fillArchetypeType(type, entry);
  return entry;
}

void TypeVisitor::fillType(const swift::TypeBase& type, codeql::Type& entry) {
  entry.name = type.getString();
  entry.canonical_type = dispatcher_.fetchLabel(type.getCanonicalType());
}

void TypeVisitor::fillArchetypeType(const swift::ArchetypeType& type, ArchetypeType& entry) {
  entry.interface_type = dispatcher_.fetchLabel(type.getInterfaceType());
  entry.protocols = dispatcher_.fetchRepeatedLabels(type.getConformsTo());
  entry.superclass = dispatcher_.fetchOptionalLabel(type.getSuperclass());
}

codeql::ExistentialType TypeVisitor::translateExistentialType(const swift::ExistentialType& type) {
  auto entry = createTypeEntry(type);
  entry.constraint = dispatcher_.fetchLabel(type.getConstraintType());
  return entry;
}

codeql::DynamicSelfType TypeVisitor::translateDynamicSelfType(const swift::DynamicSelfType& type) {
  auto entry = createTypeEntry(type);
  entry.static_self_type = dispatcher_.fetchLabel(type.getSelfType());
  return entry;
}

codeql::VariadicSequenceType TypeVisitor::translateVariadicSequenceType(
    const swift::VariadicSequenceType& type) {
  auto entry = createTypeEntry(type);
  fillUnarySyntaxSugarType(type, entry);
  return entry;
}

codeql::InOutType TypeVisitor::translateInOutType(const swift::InOutType& type) {
  auto entry = createTypeEntry(type);
  entry.object_type = dispatcher_.fetchLabel(type.getObjectType());
  return entry;
}

codeql::UnmanagedStorageType TypeVisitor::translateUnmanagedStorageType(
    const swift::UnmanagedStorageType& type) {
  codeql::UnmanagedStorageType entry{dispatcher_.assignNewLabel(type)};
  fillReferenceStorageType(type, entry);
  return entry;
}

codeql::UnownedStorageType TypeVisitor::translateUnownedStorageType(
    const swift::UnownedStorageType& type) {
  codeql::UnownedStorageType entry{dispatcher_.assignNewLabel(type)};
  fillReferenceStorageType(type, entry);
  return entry;
}

codeql::WeakStorageType TypeVisitor::translateWeakStorageType(const swift::WeakStorageType& type) {
  codeql::WeakStorageType entry{dispatcher_.assignNewLabel(type)};
  fillReferenceStorageType(type, entry);
  return entry;
}

void TypeVisitor::fillReferenceStorageType(const swift::ReferenceStorageType& type,
                                           codeql::ReferenceStorageType& entry) {
  entry.referent_type = dispatcher_.fetchLabel(type.getReferentType());
  fillType(type, entry);
}

codeql::ProtocolCompositionType TypeVisitor::translateProtocolCompositionType(
    const swift::ProtocolCompositionType& type) {
  auto entry = createTypeEntry(type);
  entry.members = dispatcher_.fetchRepeatedLabels(type.getMembers());
  return entry;
}

codeql::BuiltinIntegerLiteralType TypeVisitor::translateBuiltinIntegerLiteralType(
    const swift::BuiltinIntegerLiteralType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinIntegerType TypeVisitor::translateBuiltinIntegerType(
    const swift::BuiltinIntegerType& type) {
  auto entry = createTypeEntry(type);
  if (type.isFixedWidth()) {
    entry.width = type.getFixedWidth();
  }
  return entry;
}

codeql::BuiltinBridgeObjectType TypeVisitor::translateBuiltinBridgeObjectType(
    const swift::BuiltinBridgeObjectType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinDefaultActorStorageType TypeVisitor::translateBuiltinDefaultActorStorageType(
    const swift::BuiltinDefaultActorStorageType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinExecutorType TypeVisitor::translateBuiltinExecutorType(
    const swift::BuiltinExecutorType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinFloatType TypeVisitor::translateBuiltinFloatType(
    const swift::BuiltinFloatType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinJobType TypeVisitor::translateBuiltinJobType(const swift::BuiltinJobType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinNativeObjectType TypeVisitor::translateBuiltinNativeObjectType(
    const swift::BuiltinNativeObjectType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinRawPointerType TypeVisitor::translateBuiltinRawPointerType(
    const swift::BuiltinRawPointerType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinRawUnsafeContinuationType TypeVisitor::translateBuiltinRawUnsafeContinuationType(
    const swift::BuiltinRawUnsafeContinuationType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinUnsafeValueBufferType TypeVisitor::translateBuiltinUnsafeValueBufferType(
    const swift::BuiltinUnsafeValueBufferType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinVectorType TypeVisitor::translateBuiltinVectorType(
    const swift::BuiltinVectorType& type) {
  return createTypeEntry(type);
}

codeql::OpenedArchetypeType TypeVisitor::translateOpenedArchetypeType(
    const swift::OpenedArchetypeType& type) {
  auto entry = createTypeEntry(type);
  fillArchetypeType(type, entry);
  return entry;
}

codeql::ModuleType TypeVisitor::translateModuleType(const swift::ModuleType& type) {
  auto key = type.getModule()->getRealName().str().str();
  if (type.getModule()->isNonSwiftModule()) {
    key += "|clang";
  }
  auto entry = createTypeEntry(type, key);
  entry.module = dispatcher_.fetchLabel(type.getModule());
  return entry;
}
}  // namespace codeql
<commit_msg>Swift: update extractor for `TypeRepr` changes<commit_after>#include "swift/extractor/visitors/TypeVisitor.h"

namespace codeql {
void TypeVisitor::visit(swift::TypeBase* type) {
  TypeVisitorBase<TypeVisitor>::visit(type);
  auto label = dispatcher_.fetchLabel(type);
  auto canonical = type->getCanonicalType().getPointer();
  auto canonicalLabel = (canonical == type) ? label : dispatcher_.fetchLabel(canonical);
  dispatcher_.emit(TypesTrap{label, type->getString(), canonicalLabel});
}

codeql::TypeRepr TypeVisitor::translateTypeRepr(const swift::TypeRepr& typeRepr, swift::Type type) {
  auto entry = dispatcher_.createEntry(typeRepr);
  entry.type = dispatcher_.fetchLabel(type);
  return entry;
}

void TypeVisitor::visitProtocolType(swift::ProtocolType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(ProtocolTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitEnumType(swift::EnumType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(EnumTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitStructType(swift::StructType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(StructTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitClassType(swift::ClassType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(ClassTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitFunctionType(swift::FunctionType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(FunctionTypesTrap{label});
  emitAnyFunctionType(type, label);
}

void TypeVisitor::visitTupleType(swift::TupleType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(TupleTypesTrap{label});
  auto i = 0u;
  for (const auto& e : type->getElements()) {
    auto typeTag = dispatcher_.fetchLabel(e.getType());
    dispatcher_.emit(TupleTypeTypesTrap{label, i, typeTag});
    if (e.hasName()) {
      dispatcher_.emit(TupleTypeNamesTrap{label, i, e.getName().str().str()});
    }
    ++i;
  }
}

void TypeVisitor::visitBoundGenericEnumType(swift::BoundGenericEnumType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BoundGenericEnumTypesTrap{label});
  emitBoundGenericType(type, label);
}

void TypeVisitor::visitMetatypeType(swift::MetatypeType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(MetatypeTypesTrap{label});
}

void TypeVisitor::visitExistentialMetatypeType(swift::ExistentialMetatypeType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(ExistentialMetatypeTypesTrap{label});
}

void TypeVisitor::visitBoundGenericStructType(swift::BoundGenericStructType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BoundGenericStructTypesTrap{label});
  emitBoundGenericType(type, label);
}

void TypeVisitor::visitTypeAliasType(swift::TypeAliasType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getDecl() && "expect TypeAliasType to have Decl");
  dispatcher_.emit(TypeAliasTypesTrap{label, dispatcher_.fetchLabel(type->getDecl())});
}

void TypeVisitor::visitBuiltinIntegerLiteralType(swift::BuiltinIntegerLiteralType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BuiltinIntegerLiteralTypesTrap{label});
}

void TypeVisitor::visitBuiltinFloatType(swift::BuiltinFloatType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BuiltinFloatTypesTrap{label});
}

void TypeVisitor::visitBuiltinIntegerType(swift::BuiltinIntegerType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  auto width = type->getWidth();
  if (width.isFixedWidth()) {
    dispatcher_.emit(BuiltinIntegerTypeWidthsTrap{label, width.getFixedWidth()});
  }
  dispatcher_.emit(BuiltinIntegerTypesTrap{label});
}

void TypeVisitor::visitBoundGenericClassType(swift::BoundGenericClassType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(BoundGenericClassTypesTrap{label});
  emitBoundGenericType(type, label);
}

void TypeVisitor::visitDependentMemberType(swift::DependentMemberType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getBase() && "expect TypeAliasType to have Base");
  assert(type->getAssocType() && "expect TypeAliasType to have AssocType");
  auto baseLabel = dispatcher_.fetchLabel(type->getBase());
  auto assocTypeDeclLabel = dispatcher_.fetchLabel(type->getAssocType());
  dispatcher_.emit(DependentMemberTypesTrap{label, baseLabel, assocTypeDeclLabel});
}

void TypeVisitor::visitParenType(swift::ParenType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getUnderlyingType() && "expect ParenType to have UnderlyingType");
  auto typeLabel = dispatcher_.fetchLabel(type->getUnderlyingType());
  dispatcher_.emit(ParenTypesTrap{label, typeLabel});
}

codeql::OptionalType TypeVisitor::translateOptionalType(const swift::OptionalType& type) {
  auto entry = createTypeEntry(type);
  fillUnarySyntaxSugarType(type, entry);
  return entry;
}

codeql::ArraySliceType TypeVisitor::translateArraySliceType(const swift::ArraySliceType& type) {
  auto entry = createTypeEntry(type);
  fillUnarySyntaxSugarType(type, entry);
  return entry;
}

void TypeVisitor::visitDictionaryType(swift::DictionaryType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  auto keyLabel = dispatcher_.fetchLabel(type->getKeyType());
  auto valueLabel = dispatcher_.fetchLabel(type->getValueType());
  dispatcher_.emit(DictionaryTypesTrap{label, keyLabel, valueLabel});
}

void TypeVisitor::visitGenericFunctionType(swift::GenericFunctionType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(GenericFunctionTypesTrap{label});
  emitAnyFunctionType(type, label);
  auto i = 0u;
  for (auto p : type->getGenericParams()) {
    dispatcher_.emit(GenericFunctionTypeGenericParamsTrap{label, i++, dispatcher_.fetchLabel(p)});
  }
}

void TypeVisitor::visitGenericTypeParamType(swift::GenericTypeParamType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(GenericTypeParamTypesTrap{label});
}

void TypeVisitor::visitLValueType(swift::LValueType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  assert(type->getObjectType() && "expect LValueType to have ObjectType");
  dispatcher_.emit(LValueTypesTrap{label, dispatcher_.fetchLabel(type->getObjectType())});
}

codeql::PrimaryArchetypeType TypeVisitor::translatePrimaryArchetypeType(
    const swift::PrimaryArchetypeType& type) {
  auto entry = createTypeEntry(type);
  fillArchetypeType(type, entry);
  return entry;
}

void TypeVisitor::visitUnboundGenericType(swift::UnboundGenericType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  dispatcher_.emit(UnboundGenericTypesTrap{label});
  emitAnyGenericType(type, label);
}

void TypeVisitor::visitBoundGenericType(swift::BoundGenericType* type) {
  auto label = dispatcher_.assignNewLabel(type);
  emitBoundGenericType(type, label);
}

void TypeVisitor::fillUnarySyntaxSugarType(const swift::UnarySyntaxSugarType& type,
                                           codeql::UnarySyntaxSugarType& entry) {
  assert(type.getBaseType() && "expect UnarySyntaxSugarType to have BaseType");
  entry.base_type = dispatcher_.fetchLabel(type.getBaseType());
}

void TypeVisitor::emitAnyFunctionType(const swift::AnyFunctionType* type,
                                      TrapLabel<AnyFunctionTypeTag> label) {
  assert(type->getResult() && "expect FunctionType to have Result");
  dispatcher_.emit(AnyFunctionTypesTrap{label, dispatcher_.fetchLabel(type->getResult())});
  auto i = 0u;
  for (const auto& p : type->getParams()) {
    assert(p.getPlainType() && "expect Param to have PlainType");
    dispatcher_.emit(
        AnyFunctionTypeParamTypesTrap{label, i, dispatcher_.fetchLabel(p.getPlainType())});
    if (p.hasLabel()) {
      dispatcher_.emit(AnyFunctionTypeParamLabelsTrap{label, i, p.getLabel().str().str()});
    }
    ++i;
  }

  if (type->isThrowing()) {
    dispatcher_.emit(AnyFunctionTypeIsThrowingTrap{label});
  }

  if (type->isAsync()) {
    dispatcher_.emit(AnyFunctionTypeIsAsyncTrap{label});
  }
}

void TypeVisitor::emitBoundGenericType(swift::BoundGenericType* type,
                                       TrapLabel<BoundGenericTypeTag> label) {
  auto i = 0u;
  for (const auto& t : type->getGenericArgs()) {
    dispatcher_.emit(BoundGenericTypeArgTypesTrap{label, i++, dispatcher_.fetchLabel(t)});
  }
  emitAnyGenericType(type, label);
}

void TypeVisitor::emitAnyGenericType(swift::AnyGenericType* type,
                                     TrapLabel<AnyGenericTypeTag> label) {
  assert(type->getDecl() && "expect AnyGenericType to have Decl");
  dispatcher_.emit(AnyGenericTypesTrap{label, dispatcher_.fetchLabel(type->getDecl())});
  if (auto parent = type->getParent()) {
    dispatcher_.emit(AnyGenericTypeParentsTrap{label, dispatcher_.fetchLabel(parent)});
  }
}

codeql::NestedArchetypeType TypeVisitor::translateNestedArchetypeType(
    const swift::NestedArchetypeType& type) {
  auto entry = createTypeEntry(type);
  entry.parent = dispatcher_.fetchLabel(type.getParent());
  entry.associated_type_declaration = dispatcher_.fetchLabel(type.getAssocType());
  fillArchetypeType(type, entry);
  return entry;
}

void TypeVisitor::fillType(const swift::TypeBase& type, codeql::Type& entry) {
  entry.name = type.getString();
  entry.canonical_type = dispatcher_.fetchLabel(type.getCanonicalType());
}

void TypeVisitor::fillArchetypeType(const swift::ArchetypeType& type, ArchetypeType& entry) {
  entry.interface_type = dispatcher_.fetchLabel(type.getInterfaceType());
  entry.protocols = dispatcher_.fetchRepeatedLabels(type.getConformsTo());
  entry.superclass = dispatcher_.fetchOptionalLabel(type.getSuperclass());
}

codeql::ExistentialType TypeVisitor::translateExistentialType(const swift::ExistentialType& type) {
  auto entry = createTypeEntry(type);
  entry.constraint = dispatcher_.fetchLabel(type.getConstraintType());
  return entry;
}

codeql::DynamicSelfType TypeVisitor::translateDynamicSelfType(const swift::DynamicSelfType& type) {
  auto entry = createTypeEntry(type);
  entry.static_self_type = dispatcher_.fetchLabel(type.getSelfType());
  return entry;
}

codeql::VariadicSequenceType TypeVisitor::translateVariadicSequenceType(
    const swift::VariadicSequenceType& type) {
  auto entry = createTypeEntry(type);
  fillUnarySyntaxSugarType(type, entry);
  return entry;
}

codeql::InOutType TypeVisitor::translateInOutType(const swift::InOutType& type) {
  auto entry = createTypeEntry(type);
  entry.object_type = dispatcher_.fetchLabel(type.getObjectType());
  return entry;
}

codeql::UnmanagedStorageType TypeVisitor::translateUnmanagedStorageType(
    const swift::UnmanagedStorageType& type) {
  codeql::UnmanagedStorageType entry{dispatcher_.assignNewLabel(type)};
  fillReferenceStorageType(type, entry);
  return entry;
}

codeql::UnownedStorageType TypeVisitor::translateUnownedStorageType(
    const swift::UnownedStorageType& type) {
  codeql::UnownedStorageType entry{dispatcher_.assignNewLabel(type)};
  fillReferenceStorageType(type, entry);
  return entry;
}

codeql::WeakStorageType TypeVisitor::translateWeakStorageType(const swift::WeakStorageType& type) {
  codeql::WeakStorageType entry{dispatcher_.assignNewLabel(type)};
  fillReferenceStorageType(type, entry);
  return entry;
}

void TypeVisitor::fillReferenceStorageType(const swift::ReferenceStorageType& type,
                                           codeql::ReferenceStorageType& entry) {
  entry.referent_type = dispatcher_.fetchLabel(type.getReferentType());
  fillType(type, entry);
}

codeql::ProtocolCompositionType TypeVisitor::translateProtocolCompositionType(
    const swift::ProtocolCompositionType& type) {
  auto entry = createTypeEntry(type);
  entry.members = dispatcher_.fetchRepeatedLabels(type.getMembers());
  return entry;
}

codeql::BuiltinIntegerLiteralType TypeVisitor::translateBuiltinIntegerLiteralType(
    const swift::BuiltinIntegerLiteralType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinIntegerType TypeVisitor::translateBuiltinIntegerType(
    const swift::BuiltinIntegerType& type) {
  auto entry = createTypeEntry(type);
  if (type.isFixedWidth()) {
    entry.width = type.getFixedWidth();
  }
  return entry;
}

codeql::BuiltinBridgeObjectType TypeVisitor::translateBuiltinBridgeObjectType(
    const swift::BuiltinBridgeObjectType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinDefaultActorStorageType TypeVisitor::translateBuiltinDefaultActorStorageType(
    const swift::BuiltinDefaultActorStorageType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinExecutorType TypeVisitor::translateBuiltinExecutorType(
    const swift::BuiltinExecutorType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinFloatType TypeVisitor::translateBuiltinFloatType(
    const swift::BuiltinFloatType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinJobType TypeVisitor::translateBuiltinJobType(const swift::BuiltinJobType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinNativeObjectType TypeVisitor::translateBuiltinNativeObjectType(
    const swift::BuiltinNativeObjectType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinRawPointerType TypeVisitor::translateBuiltinRawPointerType(
    const swift::BuiltinRawPointerType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinRawUnsafeContinuationType TypeVisitor::translateBuiltinRawUnsafeContinuationType(
    const swift::BuiltinRawUnsafeContinuationType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinUnsafeValueBufferType TypeVisitor::translateBuiltinUnsafeValueBufferType(
    const swift::BuiltinUnsafeValueBufferType& type) {
  return createTypeEntry(type);
}

codeql::BuiltinVectorType TypeVisitor::translateBuiltinVectorType(
    const swift::BuiltinVectorType& type) {
  return createTypeEntry(type);
}

codeql::OpenedArchetypeType TypeVisitor::translateOpenedArchetypeType(
    const swift::OpenedArchetypeType& type) {
  auto entry = createTypeEntry(type);
  fillArchetypeType(type, entry);
  return entry;
}

codeql::ModuleType TypeVisitor::translateModuleType(const swift::ModuleType& type) {
  auto key = type.getModule()->getRealName().str().str();
  if (type.getModule()->isNonSwiftModule()) {
    key += "|clang";
  }
  auto entry = createTypeEntry(type, key);
  entry.module = dispatcher_.fetchLabel(type.getModule());
  return entry;
}
}  // namespace codeql
<|endoftext|>


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

#include <swri_transform_util/georeference.h>

// C++ standard libraries
#include <fstream>

#include <boost/filesystem.hpp>

// ROS libraries
#include <ros/ros.h>
#include <swri_yaml_util/yaml_util.h>

namespace swri_transform_util
{
  GeoReference::GeoReference(const std::string& path) :
    loaded_(false),
    path_(path),
    image_path_(""),
    width_(0),
    height_(0),
    tile_size_(0),
    extension_("jpg"),
    datum_(""),
    projection_(""),
    transform_(2, 3, CV_64F),
    pixels_(1, 1, CV_32SC2),
    coordinates_(1, 1, CV_64FC2),
    x_offset_(0),
    y_offset_(0)
  {
    // Initialize transform to identity
    transform_.at<double>(0, 0) = 1;
    transform_.at<double>(0, 1) = 0;
    transform_.at<double>(0, 2) = 0;
    transform_.at<double>(1, 0) = 0;
    transform_.at<double>(1, 1) = 1;
    transform_.at<double>(1, 2) = 0;
  }

  GeoReference::GeoReference(const GeoReference& geo) :
    loaded_(geo.loaded_),
    path_(geo.path_),
    image_path_(geo.image_path_),
    width_(geo.width_),
    height_(geo.height_),
    tile_size_(geo.tile_size_),
    extension_(geo.extension_),
    datum_(geo.datum_),
    projection_(geo.projection_),
    transform_(geo.transform_)
  {
  }

  GeoReference::~GeoReference()
  {
  }

  bool GeoReference::Load()
  {
    YAML::Node doc;
    if (!swri_yaml_util::LoadFile(path_, doc))
    {
      ROS_ERROR("Failed to load file: %s", path_.c_str());
      return false;
    }

    try
    {
      doc["image_path"] >> image_path_;

      boost::filesystem::path imagePath(image_path_);

      // If we have an absolute path, we don't need to change it
      // Otherwise, we want to create a relative path from the .geo file
      // location
      if (imagePath.is_complete() == false)
      {
        boost::filesystem::path geoPath(path_);
        image_path_ = (geoPath.parent_path() / imagePath.relative_path()).normalize().string();

        ROS_INFO("georeference: Image path is %s", image_path_.c_str());
      }

      doc["image_width"] >> width_;
      doc["image_height"] >> height_;
      doc["tile_size"] >> tile_size_;
      if(doc["extension"])
      {
          doc["extension"] >> extension_;
      }

      doc["datum"] >> datum_;
      doc["projection"] >> projection_;

      // Parse in the tiepoints
      pixels_ = cv::Mat(1, doc["tiepoints"].size(), CV_32SC2);
      coordinates_ = cv::Mat(1, doc["tiepoints"].size(), CV_64FC2);
      ROS_INFO("georeference: Found %d tiepoints", (int32_t)(doc["tiepoints"].size()));
      for (unsigned int i = 0; i < doc["tiepoints"].size(); i++)
      {
        // Parse pixel column value into the pixel list
        doc["tiepoints"][i]["point"][0] >> pixels_.at<cv::Vec2i>(0, i)[0];

        // Parse pixel row value into the pixel list
        doc["tiepoints"][i]["point"][1] >> pixels_.at<cv::Vec2i>(0, i)[1];

        // Parse the x coordinate into the coordinate list
        doc["tiepoints"][i]["point"][2] >> coordinates_.at<cv::Vec2d>(0, i)[0];

        // Parse the y coordinate into the coordinate list
        doc["tiepoints"][i]["point"][3] >> coordinates_.at<cv::Vec2d>(0, i)[1];
      }

      if (doc["tiepoints"].size() > 1)
      {
        GetTransform();
      }
      else if (doc["tiepoints"].size() == 1)
      {
        // Parse in the X scale
        doc["pixel_scale"][0] >> transform_.at<float>(0, 0);

        // Parse in the Y scale
        doc["pixel_scale"][1] >> transform_.at<float>(1, 1);

        transform_.at<float>(0, 2) = coordinates_.at<cv::Vec2d>(0, 1)[0] -
            pixels_.at<cv::Vec2i>(0, 1)[0] * transform_.at<double>(0, 0);

        transform_.at<float>(1, 2) = coordinates_.at<cv::Vec2d>(0, 1)[1] -
            pixels_.at<cv::Vec2i>(0, 1)[1] * transform_.at<double>(1, 1);
      }
      else
      {
        ROS_ERROR("georeference: No tiepoints.");
        return false;
      }

      Print();
    }
    catch (const YAML::ParserException& e)
    {
      ROS_ERROR("%s", e.what());
      return false;
    }
    catch (const YAML::Exception& e)
    {
      ROS_ERROR("%s", e.what());
      return false;
    }

    loaded_ = true;
    return true;
  }

  void GeoReference::GetTransform()
  {
    // Copy pixels into float 32 matrix
    cv::Mat src(1, pixels_.cols, CV_32FC2);
    for (int i = 0; i < pixels_.cols; i++)
    {
      src.at<cv::Vec2f>(0, i)[0] = static_cast<float>(pixels_.at<cv::Vec2i>(0, i)[0]);
      src.at<cv::Vec2f>(0, i)[1] = static_cast<float>(pixels_.at<cv::Vec2i>(0, i)[1]);
    }

    // Offset coordinates to a new origin to avoid loss of precision
    x_offset_ = coordinates_.at<cv::Vec2d>(0, 0)[0];
    y_offset_ = coordinates_.at<cv::Vec2d>(0, 0)[1];

    // Copy coordinates into float 32 matrix
    cv::Mat dst(1, pixels_.cols, CV_32FC2);
    for (int i = 0; i < pixels_.cols; i++)
    {
      dst.at<cv::Vec2f>(0, i)[0] = coordinates_.at<cv::Vec2d>(0, i)[0] - x_offset_;
      dst.at<cv::Vec2f>(0, i)[1] = coordinates_.at<cv::Vec2d>(0, i)[1] - y_offset_;
    }

    transform_ = cv::estimateRigidTransform(src, dst, true);
    inverse_transform_ = cv::estimateRigidTransform(dst, src, true);
  }

  void GeoReference::GetCoordinate(
    int x_pixel, int y_pixel,
    double& x_coordinate, double& y_coordinate) const
  {
    cv::Mat src(1, 1, CV_32FC2);
    cv::Mat dst(1, 1, CV_32FC2);

    src.at<cv::Vec2f>(0, 0)[0] = x_pixel;
    src.at<cv::Vec2f>(0, 0)[1] = y_pixel;

    cv::transform(src, dst, transform_);

    x_coordinate = dst.at<cv::Vec2f>(0, 0)[0] + x_offset_;
    y_coordinate = dst.at<cv::Vec2f>(0, 0)[1] + y_offset_;
  }

  void GeoReference::GetPixel(
    double x_coordinate, double y_coordinate,
    int& x_pixel, int& y_pixel) const
  {
    cv::Mat src(1, 1, CV_32FC2);
    cv::Mat dst(1, 1, CV_32FC2);

    src.at<cv::Vec2f>(0, 0)[0] = x_coordinate - x_offset_;
    src.at<cv::Vec2f>(0, 0)[1] = y_coordinate - y_offset_;

    cv::transform(src, dst, inverse_transform_);

    x_pixel = static_cast<int>(dst.at<cv::Vec2f>(0, 0)[0]);
    y_pixel = static_cast<int>(dst.at<cv::Vec2f>(0, 0)[1]);
  }

  void GeoReference::Print()
  {
    ROS_INFO("georeference:  path = %s", path_.c_str());
    ROS_INFO("georeference:  image = %s", image_path_.c_str());
    ROS_INFO("georeference:  width = %d", width_);
    ROS_INFO("georeference:  height = %d", height_);
    ROS_INFO("georeference:  tile_size = %d", tile_size_);
    ROS_INFO("georeference:  extension = %s", extension_.c_str());
    ROS_INFO("georeference:  datum = %s", datum_.c_str());
    ROS_INFO("georeference:  projection = %s", projection_.c_str());

    ROS_INFO("georeference:  tiepoints");
    for (int i = 0; i < pixels_.cols; i++)
    {
      ROS_INFO("georeference:     [%d, %d, %lf, %lf]",
          pixels_.at<cv::Vec2i>(0, i)[0],
          pixels_.at<cv::Vec2i>(0, i)[1],
          coordinates_.at<cv::Vec2d>(0, i)[0],
          coordinates_.at<cv::Vec2d>(0, i)[1]);
    }

    ROS_INFO("georeference:  transform: %8lf, %8lf, %8lf",
        transform_.at<double>(0, 0),
        transform_.at<double>(0, 1),
        transform_.at<double>(0, 2) + x_offset_);

    ROS_INFO("georeference:             %8lf, %8lf, %8lf",
        transform_.at<double>(1, 0),
        transform_.at<double>(1, 1),
        transform_.at<double>(1, 2) + y_offset_);

    ROS_INFO("georeference:             %8lf, %8lf, %8lf", 0.0, 0.0, 1.0);
  }
}

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

#include <swri_transform_util/georeference.h>

// C++ standard libraries
#include <fstream>

#include <boost/filesystem.hpp>

// ROS libraries
#include <ros/ros.h>
#include <swri_yaml_util/yaml_util.h>

namespace swri_transform_util
{
  GeoReference::GeoReference(const std::string& path) :
    loaded_(false),
    path_(path),
    image_path_(""),
    width_(0),
    height_(0),
    tile_size_(0),
    extension_("jpg"),
    datum_(""),
    projection_(""),
    transform_(2, 3, CV_64F),
    pixels_(1, 1, CV_32SC2),
    coordinates_(1, 1, CV_64FC2),
    x_offset_(0),
    y_offset_(0)
  {
    // Initialize transform to identity
    transform_.at<double>(0, 0) = 1;
    transform_.at<double>(0, 1) = 0;
    transform_.at<double>(0, 2) = 0;
    transform_.at<double>(1, 0) = 0;
    transform_.at<double>(1, 1) = 1;
    transform_.at<double>(1, 2) = 0;
  }

  GeoReference::GeoReference(const GeoReference& geo) :
    loaded_(geo.loaded_),
    path_(geo.path_),
    image_path_(geo.image_path_),
    width_(geo.width_),
    height_(geo.height_),
    tile_size_(geo.tile_size_),
    extension_(geo.extension_),
    datum_(geo.datum_),
    projection_(geo.projection_),
    transform_(geo.transform_)
  {
  }

  GeoReference::~GeoReference()
  {
  }

  bool GeoReference::Load()
  {
    YAML::Node doc;
    if (!swri_yaml_util::LoadFile(path_, doc))
    {
      ROS_ERROR("Failed to load file: %s", path_.c_str());
      return false;
    }

    try
    {
      doc["image_path"] >> image_path_;

      boost::filesystem::path imagePath(image_path_);

      // If we have an absolute path, we don't need to change it
      // Otherwise, we want to create a relative path from the .geo file
      // location
      if (imagePath.is_complete() == false)
      {
        boost::filesystem::path geoPath(path_);
        image_path_ = (geoPath.parent_path() / imagePath.relative_path()).normalize().string();

        ROS_INFO("georeference: Image path is %s", image_path_.c_str());
      }

      doc["image_width"] >> width_;
      doc["image_height"] >> height_;
      doc["tile_size"] >> tile_size_;
      if(swri_yaml_util::FindValue(doc, "extension"))
      {
          doc["extension"] >> extension_;
      }

      doc["datum"] >> datum_;
      doc["projection"] >> projection_;

      // Parse in the tiepoints
      pixels_ = cv::Mat(1, doc["tiepoints"].size(), CV_32SC2);
      coordinates_ = cv::Mat(1, doc["tiepoints"].size(), CV_64FC2);
      ROS_INFO("georeference: Found %d tiepoints", (int32_t)(doc["tiepoints"].size()));
      for (unsigned int i = 0; i < doc["tiepoints"].size(); i++)
      {
        // Parse pixel column value into the pixel list
        doc["tiepoints"][i]["point"][0] >> pixels_.at<cv::Vec2i>(0, i)[0];

        // Parse pixel row value into the pixel list
        doc["tiepoints"][i]["point"][1] >> pixels_.at<cv::Vec2i>(0, i)[1];

        // Parse the x coordinate into the coordinate list
        doc["tiepoints"][i]["point"][2] >> coordinates_.at<cv::Vec2d>(0, i)[0];

        // Parse the y coordinate into the coordinate list
        doc["tiepoints"][i]["point"][3] >> coordinates_.at<cv::Vec2d>(0, i)[1];
      }

      if (doc["tiepoints"].size() > 1)
      {
        GetTransform();
      }
      else if (doc["tiepoints"].size() == 1)
      {
        // Parse in the X scale
        doc["pixel_scale"][0] >> transform_.at<float>(0, 0);

        // Parse in the Y scale
        doc["pixel_scale"][1] >> transform_.at<float>(1, 1);

        transform_.at<float>(0, 2) = coordinates_.at<cv::Vec2d>(0, 1)[0] -
            pixels_.at<cv::Vec2i>(0, 1)[0] * transform_.at<double>(0, 0);

        transform_.at<float>(1, 2) = coordinates_.at<cv::Vec2d>(0, 1)[1] -
            pixels_.at<cv::Vec2i>(0, 1)[1] * transform_.at<double>(1, 1);
      }
      else
      {
        ROS_ERROR("georeference: No tiepoints.");
        return false;
      }

      Print();
    }
    catch (const YAML::ParserException& e)
    {
      ROS_ERROR("%s", e.what());
      return false;
    }
    catch (const YAML::Exception& e)
    {
      ROS_ERROR("%s", e.what());
      return false;
    }

    loaded_ = true;
    return true;
  }

  void GeoReference::GetTransform()
  {
    // Copy pixels into float 32 matrix
    cv::Mat src(1, pixels_.cols, CV_32FC2);
    for (int i = 0; i < pixels_.cols; i++)
    {
      src.at<cv::Vec2f>(0, i)[0] = static_cast<float>(pixels_.at<cv::Vec2i>(0, i)[0]);
      src.at<cv::Vec2f>(0, i)[1] = static_cast<float>(pixels_.at<cv::Vec2i>(0, i)[1]);
    }

    // Offset coordinates to a new origin to avoid loss of precision
    x_offset_ = coordinates_.at<cv::Vec2d>(0, 0)[0];
    y_offset_ = coordinates_.at<cv::Vec2d>(0, 0)[1];

    // Copy coordinates into float 32 matrix
    cv::Mat dst(1, pixels_.cols, CV_32FC2);
    for (int i = 0; i < pixels_.cols; i++)
    {
      dst.at<cv::Vec2f>(0, i)[0] = coordinates_.at<cv::Vec2d>(0, i)[0] - x_offset_;
      dst.at<cv::Vec2f>(0, i)[1] = coordinates_.at<cv::Vec2d>(0, i)[1] - y_offset_;
    }

    transform_ = cv::estimateRigidTransform(src, dst, true);
    inverse_transform_ = cv::estimateRigidTransform(dst, src, true);
  }

  void GeoReference::GetCoordinate(
    int x_pixel, int y_pixel,
    double& x_coordinate, double& y_coordinate) const
  {
    cv::Mat src(1, 1, CV_32FC2);
    cv::Mat dst(1, 1, CV_32FC2);

    src.at<cv::Vec2f>(0, 0)[0] = x_pixel;
    src.at<cv::Vec2f>(0, 0)[1] = y_pixel;

    cv::transform(src, dst, transform_);

    x_coordinate = dst.at<cv::Vec2f>(0, 0)[0] + x_offset_;
    y_coordinate = dst.at<cv::Vec2f>(0, 0)[1] + y_offset_;
  }

  void GeoReference::GetPixel(
    double x_coordinate, double y_coordinate,
    int& x_pixel, int& y_pixel) const
  {
    cv::Mat src(1, 1, CV_32FC2);
    cv::Mat dst(1, 1, CV_32FC2);

    src.at<cv::Vec2f>(0, 0)[0] = x_coordinate - x_offset_;
    src.at<cv::Vec2f>(0, 0)[1] = y_coordinate - y_offset_;

    cv::transform(src, dst, inverse_transform_);

    x_pixel = static_cast<int>(dst.at<cv::Vec2f>(0, 0)[0]);
    y_pixel = static_cast<int>(dst.at<cv::Vec2f>(0, 0)[1]);
  }

  void GeoReference::Print()
  {
    ROS_INFO("georeference:  path = %s", path_.c_str());
    ROS_INFO("georeference:  image = %s", image_path_.c_str());
    ROS_INFO("georeference:  width = %d", width_);
    ROS_INFO("georeference:  height = %d", height_);
    ROS_INFO("georeference:  tile_size = %d", tile_size_);
    ROS_INFO("georeference:  extension = %s", extension_.c_str());
    ROS_INFO("georeference:  datum = %s", datum_.c_str());
    ROS_INFO("georeference:  projection = %s", projection_.c_str());

    ROS_INFO("georeference:  tiepoints");
    for (int i = 0; i < pixels_.cols; i++)
    {
      ROS_INFO("georeference:     [%d, %d, %lf, %lf]",
          pixels_.at<cv::Vec2i>(0, i)[0],
          pixels_.at<cv::Vec2i>(0, i)[1],
          coordinates_.at<cv::Vec2d>(0, i)[0],
          coordinates_.at<cv::Vec2d>(0, i)[1]);
    }

    ROS_INFO("georeference:  transform: %8lf, %8lf, %8lf",
        transform_.at<double>(0, 0),
        transform_.at<double>(0, 1),
        transform_.at<double>(0, 2) + x_offset_);

    ROS_INFO("georeference:             %8lf, %8lf, %8lf",
        transform_.at<double>(1, 0),
        transform_.at<double>(1, 1),
        transform_.at<double>(1, 2) + y_offset_);

    ROS_INFO("georeference:             %8lf, %8lf, %8lf", 0.0, 0.0, 1.0);
  }
}

<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/graph/graph_proto_serializer.h"

namespace onnxruntime {

void GraphViewerToProto(const GraphViewer& graph_view,
                        ONNX_NAMESPACE::GraphProto& graph_proto,
                        bool include_initializer,
                        bool include_outer_scope_args) {
  graph_proto.set_name(graph_view.Name());
  graph_proto.set_doc_string(graph_view.Description());

  for (const auto* input_arg : graph_view.GetInputsIncludingInitializers()) {
    *(graph_proto.mutable_input()->Add()) = input_arg->ToProto();
  }

  for (const auto* output_arg : graph_view.GetOutputs()) {
    *(graph_proto.mutable_output()->Add()) = output_arg->ToProto();
  }

  for (const auto* value_info : graph_view.GetValueInfo()) {
    *(graph_proto.mutable_value_info()->Add()) = value_info->ToProto();
  }

  if (include_outer_scope_args){
    // add the NodeArg info for outer scope NodeArgs so we capture the type information
    for (const auto& name : graph_view.GetOuterScopeNodeArgNames()) {
      auto* node_arg = graph_view.GetNodeArg(name);
      ORT_ENFORCE(node_arg, "Outer scope node arg name '" + name + "'was added but does not exist. ");
      *(graph_proto.mutable_value_info()->Add()) = node_arg->ToProto();
    }
  }

  // Nodes must be sorted in Topological Order in the GraphProto per ONNX spec.
  for (auto& node_idx : graph_view.GetNodesInTopologicalOrder()) {
    const gsl::not_null<ONNX_NAMESPACE::NodeProto*> node_proto{graph_proto.add_node()};
    const gsl::not_null<const Node*> p_node{graph_view.GetNode(node_idx)};
    // we need to update any GraphProto attributes for subgraphs so that any changes made by things
    // such as the optimizers are captured. otherwise we can end up saving an invalid graph.
    p_node->ToProto(*node_proto, /* update_subgraphs */ true);
  }

  if (include_initializer) {
    auto& initializers = graph_view.GetAllInitializedTensors();
    for (auto& it : initializers) {
      auto* p_initializer = graph_proto.add_initializer();
      *p_initializer = *(it.second);
    }
  }
}

}<commit_msg>Fix graph viewer to proto (#11862)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/graph/graph_proto_serializer.h"

namespace onnxruntime {

void GraphViewerToProto(const GraphViewer& graph_view,
                        ONNX_NAMESPACE::GraphProto& graph_proto,
                        bool include_initializer,
                        bool include_outer_scope_args) {
  graph_proto.set_name(graph_view.Name());
  graph_proto.set_doc_string(graph_view.Description());

  for (const auto* input_arg : graph_view.GetInputsIncludingInitializers()) {
    *(graph_proto.mutable_input()->Add()) = input_arg->ToProto();
  }

  for (const auto* output_arg : graph_view.GetOutputs()) {
    *(graph_proto.mutable_output()->Add()) = output_arg->ToProto();
  }

  for (const auto* value_info : graph_view.GetValueInfo()) {
    *(graph_proto.mutable_value_info()->Add()) = value_info->ToProto();
  }

  if (include_outer_scope_args){
    // add the NodeArg info for outer scope NodeArgs so we capture the type information
    for (const auto& name : graph_view.GetOuterScopeNodeArgNames()) {
      auto* node_arg = graph_view.GetNodeArg(name);
      ORT_ENFORCE(node_arg, "Outer scope node arg name '" + name + "'was added but does not exist. ");
      *(graph_proto.mutable_value_info()->Add()) = node_arg->ToProto();
    }
  }

  // Nodes must be sorted in Topological Order in the GraphProto per ONNX spec.
  for (auto& node_idx : graph_view.GetNodesInTopologicalOrder()) {
    const gsl::not_null<ONNX_NAMESPACE::NodeProto*> node_proto{graph_proto.add_node()};
    const gsl::not_null<const Node*> p_node{graph_view.GetNode(node_idx)};
    // we need to update any GraphProto attributes for subgraphs so that any changes made by things
    // such as the optimizers are captured. otherwise we can end up saving an invalid graph.
    p_node->ToProto(*node_proto, /* update_subgraphs */ true);
  }

  if (include_initializer) {
    std::unordered_set<std::string> current_scope_initializer_set;

    auto& initializers = graph_view.GetAllInitializedTensors();
    for (auto& it : initializers) {
      auto* p_initializer = graph_proto.add_initializer();
      *p_initializer = *(it.second);
      current_scope_initializer_set.insert(it.first);
    }

    // handle outer scope value which is a constant initializer
    if (include_outer_scope_args) {
      for (auto& node_idx : graph_view.GetNodesInTopologicalOrder()) {
        const auto& node = graph_view.GetNode(node_idx);
        for (const auto& input : node->InputDefs()) {
          if (current_scope_initializer_set.find(input->Name()) != current_scope_initializer_set.end()) {
            continue;
          }
          if (graph_view.IsConstantInitializer(input->Name(), true)) {
            auto* p_initializer = graph_proto.add_initializer();
            *p_initializer = *(graph_view.GetConstantInitializer(input->Name(), true));
            current_scope_initializer_set.insert(input->Name());
          }
        }
      }
    }
  }
}

}
<|endoftext|>


<commit_before>#include "{{Name}}Module.h"
#include <cstdio>

{{Name}}Module::{{Name}}Module(ModularSynth& synth)
	:SynthModule(synth, moduleId, 1, 1, 0)
{
}

void {{Name}}Module::cycle()
{
	// Passthru
	setOutput(0, getInput0));
}

const char * {{Name}}Module::getInputName(int input) const
{
	static const char *names[] = {"Input"};
	return names[input];
}

const char * {{Name}}Module::getOutputName(int output) const
{
	static const char *names[] = {"Output"};
	return names[output];
}

const char * {{Name}}Module::getName() const
{
	return "{{Name}}";
}

SynthModule * {{Name}}Module::createModule(ModularSynth& synth)
{
	return new {{Name}}Module(synth);
}
<commit_msg>Fixed typo<commit_after>#include "{{Name}}Module.h"
#include <cstdio>

{{Name}}Module::{{Name}}Module(ModularSynth& synth)
	:SynthModule(synth, moduleId, 1, 1, 0)
{
}

void {{Name}}Module::cycle()
{
	// Passthru
	setOutput(0, getInput(0));
}

const char * {{Name}}Module::getInputName(int input) const
{
	static const char *names[] = {"Input"};
	return names[input];
}

const char * {{Name}}Module::getOutputName(int output) const
{
	static const char *names[] = {"Output"};
	return names[output];
}

const char * {{Name}}Module::getName() const
{
	return "{{Name}}";
}

SynthModule * {{Name}}Module::createModule(ModularSynth& synth)
{
	return new {{Name}}Module(synth);
}
<|endoftext|>


<commit_before>// Copyright 2010 Jens-Michael Hoffmann <jmho@c-xx.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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, see <http://www.gnu.org/licenses/>.

#include "BlendingAlgorithms.h"

#include "TextureTile.h"

#include <cmath>

#include <QtGui/QImage>

namespace Marble
{

void IndependentChannelBlending::blend( QImage * const bottom, QSharedPointer<TextureTile> const & top ) const
{
    QImage const * const topImage = top->image();
    Q_ASSERT( topImage );
    Q_ASSERT( bottom->size() == topImage->size() );
    int const width = bottom->width();
    int const height = bottom->height();
    for ( int y = 0; y < height; ++y ) {
        for ( int x = 0; x < width; ++x ) {
            QRgb const bottomPixel = bottom->pixel( x, y );
            QRgb const topPixel = topImage->pixel( x, y );
            qreal const resultRed = blendChannel( qRed( bottomPixel ) / 255.0,
                                                  qRed( topPixel ) / 255.0 );
            qreal const resultGreen = blendChannel( qGreen( bottomPixel ) / 255.0,
                                                    qGreen( topPixel ) / 255.0 );
            qreal const resultBlue = blendChannel( qBlue( bottomPixel ) / 255.0,
                                                   qBlue( topPixel ) / 255.0 );
            bottom->setPixel( x, y, qRgb( resultRed * 255.0,
                                          resultGreen * 255.0,
                                          resultBlue * 255.0 ));
        }
    }
}

// Neutral blendings

qreal AllanonBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    return ( bottomColorIntensity + topColorIntensity ) / 2.0;
}

qreal ArcusTangentBlending::blendChannel( qreal const bottomColorIntensity,
                                          qreal const topColorIntensity ) const
{
    return 2.0 * atan( topColorIntensity / bottomColorIntensity ) / M_PI;
}

qreal GeometricMeanBlending::blendChannel( qreal const bottomColorIntensity,
                                           qreal const topColorIntensity ) const
{
    return sqrt( bottomColorIntensity * topColorIntensity );
}

qreal LinearLightBlending::blendChannel( qreal const bottomColorIntensity,
                                         qreal const topColorIntensity ) const
{
    return qMin( 1.0, qMax( 0.0, ( bottomColorIntensity + 2.0 * topColorIntensity ) - 1.0 ));
}

qreal OverlayBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    if ( bottomColorIntensity < 0.5 )
        return 2.0 * bottomColorIntensity * topColorIntensity;
    else
        return 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal ParallelBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    // FIXME:    return qMin( qMax( 2.0 / ( 1.0 / bottomColorIntensity + 1.0 / topColorIntensity )), 0.0, 1.0 );
    return 0.0;
}

qreal TextureBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    // FIXME: return qMax( qMin( topColorIntensity + bottomColorIntensity ) - 0.5 ), 1.0 ), 0.0 );
    return 0.0;
}

// Darkening blendings

qreal ColorBurnBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    // FIXME: check if this formula makes sense
    return qMin( 1.0, qMax( 0.0, 1.0 - ( 1.0 - bottomColorIntensity ) / topColorIntensity ));
}

qreal DarkBlending::blendChannel( qreal const bottomColorIntensity,
                                  qreal const topColorIntensity ) const
{
    return ( bottomColorIntensity + 1.0 - topColorIntensity ) * topColorIntensity;
}

qreal DarkenBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    // FIXME: is this really ok? not vice versa?
    return bottomColorIntensity > topColorIntensity ? topColorIntensity : bottomColorIntensity;
}

qreal DivideBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    return log2( 1.0 + bottomColorIntensity / ( 1.0 - topColorIntensity ) / 8.0 );
}

qreal GammaDarkBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    return pow( bottomColorIntensity, 1.0 / topColorIntensity );
}

qreal LinearBurnBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return qMax( 0.0, bottomColorIntensity + topColorIntensity - 1.0 );
}

qreal MultiplyBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    return bottomColorIntensity * topColorIntensity;
}

qreal SubtractiveBlending::blendChannel( qreal const bottomColorIntensity,
                                         qreal const topColorIntensity ) const
{
    return qMax( bottomColorIntensity - topColorIntensity, qreal(0.0) );
}

// Lightening blendings

qreal AdditiveBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    return qMin( topColorIntensity + bottomColorIntensity, qreal(1.0) );
}

qreal ColorDodgeBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return qMin( 1.0, qMax( 0.0, bottomColorIntensity / ( 1.0 - topColorIntensity )));
}

qreal GammaLightBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return pow( bottomColorIntensity, topColorIntensity );
}

qreal HardLightBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    return topColorIntensity < 0.5
        ? 2.0 * bottomColorIntensity * topColorIntensity
        : 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal LightBlending::blendChannel( qreal const bottomColorIntensity,
                                   qreal const topColorIntensity ) const
{
    return bottomColorIntensity * ( 1.0 - topColorIntensity ) + pow( topColorIntensity, 2 );
}

qreal LightenBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    // is this ok?
    return bottomColorIntensity < topColorIntensity ? topColorIntensity : bottomColorIntensity;
}

qreal PinLightBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    return qMax( qreal(0.0), qMax( qreal(2.0 + topColorIntensity - 1.0),
                             qMin( bottomColorIntensity, qreal(2.0 * topColorIntensity ))));
}

qreal ScreenBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal SoftLightBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    return pow( bottomColorIntensity, pow( 2.0, ( 2.0 * ( 0.5 - topColorIntensity ))));
}

qreal VividLightBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return topColorIntensity < 0.5
        ? qMin( 1.0, qMax( 0.0, 1.0 - ( 1.0 - bottomColorIntensity ) / ( 2.0 * topColorIntensity )))
        : qMin( 1.0, qMax( 0.0, bottomColorIntensity / ( 2.0 * ( 1.0 - topColorIntensity ))));
}

// Inverter blendings

qreal AdditiveSubtractiveBlending::blendChannel( qreal const bottomColorIntensity,
                                                 qreal const topColorIntensity ) const
{
    // FIXME:
    //    return qMin( 1.0, qMax( 0.0, abs( bottomColorIntensity * bottomColorIntensity
    //                                      - topColorIntensity * topColorIntensity )));
    return 0.0;
}

qreal BleachBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    // FIXME: "why this is the same formula as Screen Blending? Please correct.)"
    return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal DifferenceBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return qMax( qMin( 1.0, bottomColorIntensity - topColorIntensity + 0.5 ), 0.0 );
}

qreal EquivalenceBlending::blendChannel( qreal const bottomColorIntensity,
                                         qreal const topColorIntensity ) const
{
    return 1.0 - abs( bottomColorIntensity - topColorIntensity );
}

qreal HalfDifferenceBlending::blendChannel( qreal const bottomColorIntensity,
                                            qreal const topColorIntensity ) const
{
    return bottomColorIntensity + topColorIntensity
        - 2.0 * ( bottomColorIntensity * topColorIntensity );
}

// Special purpose blendings

void CloudsBlending::blend( QImage * const bottom, QSharedPointer<TextureTile> const & top ) const
{
    QImage const * const topImage = top->image();
    Q_ASSERT( topImage );
    Q_ASSERT( bottom->size() == topImage->size() );
    int const width = bottom->width();
    int const height = bottom->height();
    for ( int y = 0; y < height; ++y ) {
        for ( int x = 0; x < width; ++x ) {
            qreal const c = qRed( topImage->pixel( x, y )) / 255.0;
            QRgb const bottomPixel = bottom->pixel( x, y );
            int const bottomRed = qRed( bottomPixel );
            int const bottomGreen = qGreen( bottomPixel );
            int const bottomBlue = qBlue( bottomPixel );
            bottom->setPixel( x, y, qRgb(( int )( bottomRed + ( 255 - bottomRed ) * c ),
                                         ( int )( bottomGreen + ( 255 - bottomGreen ) * c ),
                                         ( int )( bottomBlue + ( 255 - bottomBlue ) * c )));
        }
    }
}

}
<commit_msg>Coding style: break too long line.<commit_after>// Copyright 2010 Jens-Michael Hoffmann <jmho@c-xx.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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, see <http://www.gnu.org/licenses/>.

#include "BlendingAlgorithms.h"

#include "TextureTile.h"

#include <cmath>

#include <QtGui/QImage>

namespace Marble
{

void IndependentChannelBlending::blend( QImage * const bottom,
                                        QSharedPointer<TextureTile> const & top ) const
{
    QImage const * const topImage = top->image();
    Q_ASSERT( topImage );
    Q_ASSERT( bottom->size() == topImage->size() );
    int const width = bottom->width();
    int const height = bottom->height();
    for ( int y = 0; y < height; ++y ) {
        for ( int x = 0; x < width; ++x ) {
            QRgb const bottomPixel = bottom->pixel( x, y );
            QRgb const topPixel = topImage->pixel( x, y );
            qreal const resultRed = blendChannel( qRed( bottomPixel ) / 255.0,
                                                  qRed( topPixel ) / 255.0 );
            qreal const resultGreen = blendChannel( qGreen( bottomPixel ) / 255.0,
                                                    qGreen( topPixel ) / 255.0 );
            qreal const resultBlue = blendChannel( qBlue( bottomPixel ) / 255.0,
                                                   qBlue( topPixel ) / 255.0 );
            bottom->setPixel( x, y, qRgb( resultRed * 255.0,
                                          resultGreen * 255.0,
                                          resultBlue * 255.0 ));
        }
    }
}

// Neutral blendings

qreal AllanonBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    return ( bottomColorIntensity + topColorIntensity ) / 2.0;
}

qreal ArcusTangentBlending::blendChannel( qreal const bottomColorIntensity,
                                          qreal const topColorIntensity ) const
{
    return 2.0 * atan( topColorIntensity / bottomColorIntensity ) / M_PI;
}

qreal GeometricMeanBlending::blendChannel( qreal const bottomColorIntensity,
                                           qreal const topColorIntensity ) const
{
    return sqrt( bottomColorIntensity * topColorIntensity );
}

qreal LinearLightBlending::blendChannel( qreal const bottomColorIntensity,
                                         qreal const topColorIntensity ) const
{
    return qMin( 1.0, qMax( 0.0, ( bottomColorIntensity + 2.0 * topColorIntensity ) - 1.0 ));
}

qreal OverlayBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    if ( bottomColorIntensity < 0.5 )
        return 2.0 * bottomColorIntensity * topColorIntensity;
    else
        return 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal ParallelBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    // FIXME:    return qMin( qMax( 2.0 / ( 1.0 / bottomColorIntensity + 1.0 / topColorIntensity )), 0.0, 1.0 );
    return 0.0;
}

qreal TextureBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    // FIXME: return qMax( qMin( topColorIntensity + bottomColorIntensity ) - 0.5 ), 1.0 ), 0.0 );
    return 0.0;
}

// Darkening blendings

qreal ColorBurnBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    // FIXME: check if this formula makes sense
    return qMin( 1.0, qMax( 0.0, 1.0 - ( 1.0 - bottomColorIntensity ) / topColorIntensity ));
}

qreal DarkBlending::blendChannel( qreal const bottomColorIntensity,
                                  qreal const topColorIntensity ) const
{
    return ( bottomColorIntensity + 1.0 - topColorIntensity ) * topColorIntensity;
}

qreal DarkenBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    // FIXME: is this really ok? not vice versa?
    return bottomColorIntensity > topColorIntensity ? topColorIntensity : bottomColorIntensity;
}

qreal DivideBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    return log2( 1.0 + bottomColorIntensity / ( 1.0 - topColorIntensity ) / 8.0 );
}

qreal GammaDarkBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    return pow( bottomColorIntensity, 1.0 / topColorIntensity );
}

qreal LinearBurnBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return qMax( 0.0, bottomColorIntensity + topColorIntensity - 1.0 );
}

qreal MultiplyBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    return bottomColorIntensity * topColorIntensity;
}

qreal SubtractiveBlending::blendChannel( qreal const bottomColorIntensity,
                                         qreal const topColorIntensity ) const
{
    return qMax( bottomColorIntensity - topColorIntensity, qreal(0.0) );
}

// Lightening blendings

qreal AdditiveBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    return qMin( topColorIntensity + bottomColorIntensity, qreal(1.0) );
}

qreal ColorDodgeBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return qMin( 1.0, qMax( 0.0, bottomColorIntensity / ( 1.0 - topColorIntensity )));
}

qreal GammaLightBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return pow( bottomColorIntensity, topColorIntensity );
}

qreal HardLightBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    return topColorIntensity < 0.5
        ? 2.0 * bottomColorIntensity * topColorIntensity
        : 1.0 - 2.0 * ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal LightBlending::blendChannel( qreal const bottomColorIntensity,
                                   qreal const topColorIntensity ) const
{
    return bottomColorIntensity * ( 1.0 - topColorIntensity ) + pow( topColorIntensity, 2 );
}

qreal LightenBlending::blendChannel( qreal const bottomColorIntensity,
                                     qreal const topColorIntensity ) const
{
    // is this ok?
    return bottomColorIntensity < topColorIntensity ? topColorIntensity : bottomColorIntensity;
}

qreal PinLightBlending::blendChannel( qreal const bottomColorIntensity,
                                      qreal const topColorIntensity ) const
{
    return qMax( qreal(0.0), qMax( qreal(2.0 + topColorIntensity - 1.0),
                             qMin( bottomColorIntensity, qreal(2.0 * topColorIntensity ))));
}

qreal ScreenBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal SoftLightBlending::blendChannel( qreal const bottomColorIntensity,
                                       qreal const topColorIntensity ) const
{
    return pow( bottomColorIntensity, pow( 2.0, ( 2.0 * ( 0.5 - topColorIntensity ))));
}

qreal VividLightBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return topColorIntensity < 0.5
        ? qMin( 1.0, qMax( 0.0, 1.0 - ( 1.0 - bottomColorIntensity ) / ( 2.0 * topColorIntensity )))
        : qMin( 1.0, qMax( 0.0, bottomColorIntensity / ( 2.0 * ( 1.0 - topColorIntensity ))));
}

// Inverter blendings

qreal AdditiveSubtractiveBlending::blendChannel( qreal const bottomColorIntensity,
                                                 qreal const topColorIntensity ) const
{
    // FIXME:
    //    return qMin( 1.0, qMax( 0.0, abs( bottomColorIntensity * bottomColorIntensity
    //                                      - topColorIntensity * topColorIntensity )));
    return 0.0;
}

qreal BleachBlending::blendChannel( qreal const bottomColorIntensity,
                                    qreal const topColorIntensity ) const
{
    // FIXME: "why this is the same formula as Screen Blending? Please correct.)"
    return 1.0 - ( 1.0 - bottomColorIntensity ) * ( 1.0 - topColorIntensity );
}

qreal DifferenceBlending::blendChannel( qreal const bottomColorIntensity,
                                        qreal const topColorIntensity ) const
{
    return qMax( qMin( 1.0, bottomColorIntensity - topColorIntensity + 0.5 ), 0.0 );
}

qreal EquivalenceBlending::blendChannel( qreal const bottomColorIntensity,
                                         qreal const topColorIntensity ) const
{
    return 1.0 - abs( bottomColorIntensity - topColorIntensity );
}

qreal HalfDifferenceBlending::blendChannel( qreal const bottomColorIntensity,
                                            qreal const topColorIntensity ) const
{
    return bottomColorIntensity + topColorIntensity
        - 2.0 * ( bottomColorIntensity * topColorIntensity );
}

// Special purpose blendings

void CloudsBlending::blend( QImage * const bottom, QSharedPointer<TextureTile> const & top ) const
{
    QImage const * const topImage = top->image();
    Q_ASSERT( topImage );
    Q_ASSERT( bottom->size() == topImage->size() );
    int const width = bottom->width();
    int const height = bottom->height();
    for ( int y = 0; y < height; ++y ) {
        for ( int x = 0; x < width; ++x ) {
            qreal const c = qRed( topImage->pixel( x, y )) / 255.0;
            QRgb const bottomPixel = bottom->pixel( x, y );
            int const bottomRed = qRed( bottomPixel );
            int const bottomGreen = qGreen( bottomPixel );
            int const bottomBlue = qBlue( bottomPixel );
            bottom->setPixel( x, y, qRgb(( int )( bottomRed + ( 255 - bottomRed ) * c ),
                                         ( int )( bottomGreen + ( 255 - bottomGreen ) * c ),
                                         ( int )( bottomBlue + ( 255 - bottomBlue ) * c )));
        }
    }
}

}
<|endoftext|>